Skip to content

Commit ff7999b

Browse files
authored
Merge pull request #257 from Earu/materialsystem/vtf-resources-and-render-gaps
VTF resource data, spritecard flag, user clip transform and texcoord fixes
2 parents 6be510d + 879ae31 commit ff7999b

10 files changed

Lines changed: 142 additions & 45 deletions

File tree

‎Source.Common/MaterialSystem/IMaterial.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,7 @@ public interface IMaterial
484484
bool NeedsPowerOfTwoFrameBufferTexture(bool checkSpecificToThisFrame);
485485
bool NeedsFullFrameBufferTexture(bool checkSpecificToThisFrame);
486486
bool NeedsLightmapBlendAlpha();
487+
bool IsSpriteCard();
487488
}
488489

489490
// Intended to only be used by the material system and not other components

‎Source.Common/MaterialSystem/IMesh.cs‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,25 @@ internal void TexCoord3f(int stage, float s, float t, float u) {
420420
*pDst = u;
421421
}
422422

423+
internal void TexCoord4f(int stage, float s, float t, float u, float w) {
424+
float* pDst = stage switch {
425+
0 => CurrTexCoord0,
426+
1 => CurrTexCoord1,
427+
2 => CurrTexCoord2,
428+
3 => CurrTexCoord3,
429+
4 => CurrTexCoord4,
430+
5 => CurrTexCoord5,
431+
6 => CurrTexCoord6,
432+
7 => CurrTexCoord7,
433+
_ => null
434+
};
435+
if (pDst == null) return;
436+
*pDst++ = s;
437+
*pDst++ = t;
438+
*pDst++ = u;
439+
*pDst = w;
440+
}
441+
423442
public void AdvanceVertex() {
424443
if (++CurrentVertex > VertexCount)
425444
VertexCount = CurrentVertex;
@@ -988,8 +1007,8 @@ public unsafe void Color4ubv(in Color rgba) {
9881007
public void TexCoord2fv(int stage, in Vector2 vec) => VertexBuilder.TexCoord2f(stage, vec.X, vec.Y);
9891008
public void TexCoord3f(int stage, float s, float t, float u) => VertexBuilder.TexCoord3f(stage, s, t, u);
9901009
public void TexCoord3fv(int stage, ReadOnlySpan<float> stu) => VertexBuilder.TexCoord3f(stage, stu[0], stu[1], stu[2]);
991-
public void TexCoord4f(int stage, float s, float t, float u, float w) => throw new NotImplementedException();
992-
public void TexCoord4fv(int stage, ReadOnlySpan<float> stuv) => throw new NotImplementedException();
1010+
public void TexCoord4f(int stage, float s, float t, float u, float w) => VertexBuilder.TexCoord4f(stage, s, t, u, w);
1011+
public void TexCoord4fv(int stage, ReadOnlySpan<float> stuv) => VertexBuilder.TexCoord4f(stage, stuv[0], stuv[1], stuv[2], stuv[3]);
9931012

9941013
public void TexCoordSubRect2f(int stage, float s, float t, float offsetS, float offsetT, float scaleS, float scaleT) => throw new NotImplementedException();
9951014
public void TexCoordSubRect2fv(int stage, ReadOnlySpan<float> st, ReadOnlySpan<float> offset, ReadOnlySpan<float> scale) => throw new NotImplementedException();

‎Source.MaterialSystem/MatRenderContext.cs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -673,9 +673,7 @@ public void EnableNonInteractiveMode(MaterialNonInteractiveMode mode) {
673673
throw new NotImplementedException("Incomplete port of IMatRenderContext");
674674
}
675675

676-
public void EnableUserClipTransformOverride(bool enable) {
677-
throw new NotImplementedException("Incomplete port of IMatRenderContext");
678-
}
676+
public void EnableUserClipTransformOverride(bool enable) => shaderAPI.EnableUserClipTransformOverride(enable);
679677

680678
public void EndMorphAccumulation() {
681679
throw new NotImplementedException("Incomplete port of IMatRenderContext");
@@ -902,9 +900,7 @@ public void UnlockLookup(ColorCorrectionHandle_t handle) {
902900
throw new NotImplementedException("Incomplete port of IMatRenderContext");
903901
}
904902

905-
public void UserClipTransform(in Matrix4x4 worldToView) {
906-
throw new NotImplementedException("Incomplete port of IMatRenderContext");
907-
}
903+
public void UserClipTransform(in Matrix4x4 worldToView) => shaderAPI.UserClipTransform(worldToView);
908904

909905
public void DrawClearBufferQuad(byte r, byte g, byte b, byte a, bool clearColor, bool clearAlpha, bool clearDepth) {
910906
throw new NotImplementedException("Incomplete port of IMatRenderContextInternal");

‎Source.MaterialSystem/MatRenderContextBase.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,11 +404,15 @@ public float ComputePixelWidthOfSphere(in Vector3 origin, float radius) {
404404
}
405405

406406
public virtual void GetWorldSpaceCameraPosition(out Vector3 vecCameraPos) {
407+
RecomputeViewState();
407408
vecCameraPos = VecViewOrigin;
408409
}
409410

410411
public virtual void GetWorldSpaceCameraVectors(out Vector3 forward, out Vector3 right, out Vector3 up) {
411-
throw new NotImplementedException("Incomplete port of IMatRenderContext");
412+
RecomputeViewState();
413+
forward = VecViewForward;
414+
right = VecViewRight;
415+
up = VecViewUp;
412416
}
413417

414418
public virtual Vector3 GetToneMappingScaleLinear() {

‎Source.MaterialSystem/MatStub.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ public void SetUseFixedFunctionBakedLighting(bool enable) { }
327327
public bool NeedsPowerOfTwoFrameBufferTexture(bool checkSpecificToThisFrame) => false;
328328
public bool NeedsFullFrameBufferTexture(bool checkSpecificToThisFrame) => false;
329329
public bool NeedsLightmapBlendAlpha() => false;
330+
public bool IsSpriteCard() => false;
330331
}
331332

332333
public class DummyMorph : IMorph

‎Source.MaterialSystem/Material.cs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1425,6 +1425,13 @@ public bool IsTwoSided() {
14251425
return GetMaterialVarFlag(MaterialVarFlags.NoCull);
14261426
}
14271427

1428+
public bool IsSpriteCard() {
1429+
Precache();
1430+
if (IsValidRenderState())
1431+
return (GetMaterialVarFlags2() & MaterialVarFlags2.IsSpritecard) != 0;
1432+
return false;
1433+
}
1434+
14281435
public bool IsAlphaTested() {
14291436
Precache();
14301437
if (Shader != null && IsValidRenderState())

‎Source.MaterialSystem/MaterialSystem.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1053,6 +1053,9 @@ public ReadOnlySpan<char> GetForcedTextureLoadPathID() {
10531053
char c = materialName[i];
10541054
tempNameBuffer[i] = c == '\\' ? '/' : c;
10551055
}
1056+
int extension = tempNameBuffer.LastIndexOfAny('.', '/');
1057+
if (extension > 0 && tempNameBuffer[extension] == '.')
1058+
tempNameBuffer = tempNameBuffer[..extension];
10561059
IMaterialInternal? existingMaterial = MaterialDict.FindMaterial(tempNameBuffer, false);
10571060

10581061
if (existingMaterial != null)

‎Source.MaterialSystem/Texture.cs‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,26 @@ public int GetNumAnimationFrames() {
9393
return FrameCount;
9494
}
9595

96-
public Span<byte> GetResourceData(uint type) {
97-
throw new NotImplementedException();
96+
readonly Dictionary<ResourceEntryType, byte[]> ResourceData = [];
97+
98+
public Span<byte> GetResourceData(uint type)
99+
=> ResourceData.TryGetValue(ResourceEntryInfo.ParseTag((byte)type, (byte)(type >> 8), (byte)(type >> 16)), out byte[]? data) ? data : default;
100+
101+
void StoreResourceData(IVTFTexture vtfTexture) {
102+
uint count = vtfTexture.GetResourceTypes([]);
103+
if (count == 0)
104+
return;
105+
106+
Span<ResourceEntryType> types = stackalloc ResourceEntryType[(int)count];
107+
vtfTexture.GetResourceTypes(types);
108+
foreach (ResourceEntryType type in types) {
109+
if (type == ResourceEntryType.LowResThumbnail || type == ResourceEntryType.HighResImageData)
110+
continue;
111+
112+
Span<byte> data = vtfTexture.GetResourceData(type);
113+
if (!data.IsEmpty)
114+
ResourceData.TryAdd(type, data.ToArray());
115+
}
98116
}
99117

100118
public void IncrementReferenceCount() => ++RefCount;
@@ -699,6 +717,8 @@ private void MigrateShaderAPITextures() {
699717

700718
Reflectivity = vtfTexture.Reflectivity();
701719

720+
StoreResourceData(vtfTexture);
721+
702722
// TODO: How does Source stream textures?
703723
if (ConvertToActualFormat(vtfTexture)) {
704724

@@ -713,9 +733,9 @@ private bool SLoadTextureBitsFromFile(ref IVTFTexture vtfTexture, IFileHandle fi
713733
out TexDimensions dimsMapping, out TexDimensions dimsActual, out TexDimensions dimsAllocated,
714734
out uint stripFlags) {
715735
// TODO; finish the complexities of texture loading
716-
if (!vtfTexture!.Unserialize(fileHandle.Stream, false)) {
736+
bool loaded = vtfTexture!.Unserialize(fileHandle.Stream, false);
737+
if (!loaded)
717738
Warning($"VTF texture '{fileHandle.GetPath()}' failed to load!\n");
718-
}
719739

720740
dimsMapping = new() {
721741
Width = (ushort)vtfTexture.Width(),
@@ -729,7 +749,7 @@ private bool SLoadTextureBitsFromFile(ref IVTFTexture vtfTexture, IFileHandle fi
729749
int nMipSkipCount = ComputeMipSkipCount(name, dimsMapping, false, vtfTexture, fullFlags, DesiredDimensionLimit, ref StreamingMips, out settings, out dimsActual, out dimsAllocated, out stripFlags);
730750

731751

732-
return true;
752+
return loaded;
733753
}
734754

735755
unsafe byte* ImageData;
@@ -1198,6 +1218,8 @@ public void OnRestore() {
11981218
}
11991219

12001220
private void Shutdown() {
1221+
ResourceData.Clear();
1222+
12011223
// Frees the texture regen class
12021224
TextureRegenerator = null;
12031225

‎Source.ShaderAPI.Gl46/ShaderAPIGl46.cs‎

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,8 @@ private unsafe void CreateMatrixStacks() {
268268
int UserClipPlaneChanged;
269269
readonly Vector4[] UserClipPlaneWorld = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES];
270270
readonly Vector4[] UserClipPlaneProj = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES];
271+
bool UserClipTransformOverride;
272+
Matrix4x4 UserClipTransform_ = Matrix4x4.Identity;
271273
float FogZ;
272274

273275
private void MarkAllUserClipPlanesDirty() {
@@ -278,7 +280,8 @@ private unsafe void CommitUserClipPlanes() {
278280
if ((UserClipPlaneChanged & UserClipPlaneEnabled & ((1 << Gl46.HardwareConfig.MAXUSERCLIPPLANES) - 1)) == 0)
279281
return;
280282

281-
Matrix4x4 worldToProjectionInvTrans = Matrices[(int)MaterialMatrixMode.View] * Matrices[(int)MaterialMatrixMode.Projection];
283+
Matrix4x4 worldToView = UserClipTransformOverride ? UserClipTransform_ : Matrices[(int)MaterialMatrixMode.View];
284+
Matrix4x4 worldToProjectionInvTrans = worldToView * Matrices[(int)MaterialMatrixMode.Projection];
282285
Matrix4x4.Invert(worldToProjectionInvTrans, out worldToProjectionInvTrans);
283286
worldToProjectionInvTrans = Matrix4x4.Transpose(worldToProjectionInvTrans);
284287

@@ -1214,15 +1217,19 @@ void ConfigureAttribute(Span<uint> bindings, OpenGL_ShaderInputAttribute attr, V
12141217
else
12151218
glDisableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.Specular);
12161219

1220+
Assert(format.GetTexCoordDimensionSize(6) == 0 || (format & VertexFormat.Wrinkle) == 0);
1221+
Assert(format.GetTexCoordDimensionSize(7) == 0 || ((format & VertexFormat.Specular) == 0 && !staticLit));
1222+
12171223
Span<VertexElement> texCoordElements = [VertexElement.TexCoord1D_0, VertexElement.TexCoord2D_0, VertexElement.TexCoord3D_0, VertexElement.TexCoord4D_0];
12181224
for (int i = 0; i < IMesh.VERTEX_MAX_TEXTURE_COORDINATES; i++) {
1225+
OpenGL_ShaderInputAttribute location = TexCoordLocation(i);
12191226
int texCoordSize = format.GetTexCoordDimensionSize(i);
12201227
if (texCoordSize > 0) {
12211228
VertexElement element = (VertexElement)((int)texCoordElements[texCoordSize - 1] + i);
1222-
ConfigureAttribute(bindings, (OpenGL_ShaderInputAttribute)((int)OpenGL_ShaderInputAttribute.TexCoord0 + i), element, texCoordSize);
1229+
ConfigureAttribute(bindings, location, element, texCoordSize);
12231230
}
1224-
else
1225-
glDisableVertexArrayAttrib(vao, (uint)((int)OpenGL_ShaderInputAttribute.TexCoord0 + i));
1231+
else if (location >= OpenGL_ShaderInputAttribute.TexCoord0)
1232+
glDisableVertexArrayAttrib(vao, (uint)location);
12261233
}
12271234

12281235
if ((format & VertexFormat.TangentS) != 0)
@@ -1249,15 +1256,25 @@ void ConfigureAttribute(Span<uint> bindings, OpenGL_ShaderInputAttribute attr, V
12491256

12501257
int normalOffset = (int)(VertexElement.Position.GetSize() + VertexElement.Wrinkle.GetSize());
12511258

1252-
glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition);
1253-
glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 4, GL_FLOAT, false, 0);
1254-
glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 2);
1259+
if (format.GetTexCoordDimensionSize(OpenGL_ShaderInputAttribute.FlexPosition - OpenGL_ShaderInputAttribute.TexCoord0) == 0) {
1260+
glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition);
1261+
glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 4, GL_FLOAT, false, 0);
1262+
glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 2);
1263+
}
12551264

1256-
glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal);
1257-
glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 3, GL_FLOAT, false, (uint)normalOffset);
1258-
glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 2);
1265+
if (format.GetTexCoordDimensionSize(OpenGL_ShaderInputAttribute.FlexNormal - OpenGL_ShaderInputAttribute.TexCoord0) == 0) {
1266+
glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal);
1267+
glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 3, GL_FLOAT, false, (uint)normalOffset);
1268+
glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 2);
1269+
}
12591270
}
12601271

1272+
static OpenGL_ShaderInputAttribute TexCoordLocation(int index) => index switch {
1273+
6 => OpenGL_ShaderInputAttribute.Wrinkle,
1274+
7 => OpenGL_ShaderInputAttribute.Specular,
1275+
_ => OpenGL_ShaderInputAttribute.TexCoord0 + index
1276+
};
1277+
12611278
public IMesh GetDynamicMesh(IMaterial material, int hwSkinBoneCount, bool buffered, IMesh? vertexOverride, IMesh? indexOverride) {
12621279
Assert(material == null || material.IsRealTimeVersion());
12631280
return MeshMgr.GetDynamicMesh(material, 0, hwSkinBoneCount, buffered, vertexOverride, indexOverride);
@@ -3471,7 +3488,12 @@ public void EnableHWMorphing(bool enable) {
34713488
public void EnableShaderShaderMutex(bool enable) { }
34723489

34733490
public void EnableUserClipTransformOverride(bool enable) {
3474-
throw new NotImplementedException("Incomplete port of IShaderAPI");
3491+
if (UserClipTransformOverride == enable)
3492+
return;
3493+
3494+
FlushBufferedPrimitives();
3495+
UserClipTransformOverride = enable;
3496+
MarkAllUserClipPlanesDirty();
34753497
}
34763498

34773499
public void EndOcclusionQueryDrawing(ShaderAPIOcclusionQuery_t query) {
@@ -3847,7 +3869,14 @@ public void TexSetPriority(int priority) {
38473869
}
38483870

38493871
public void UserClipTransform(in Matrix4x4 worldToView) {
3850-
throw new NotImplementedException("Incomplete port of IShaderAPI");
3872+
Matrix4x4 transform = Matrix4x4.Transpose(worldToView);
3873+
if (UserClipTransform_ == transform)
3874+
return;
3875+
UserClipTransform_ = transform;
3876+
if (UserClipTransformOverride) {
3877+
FlushBufferedPrimitives();
3878+
MarkAllUserClipPlanesDirty();
3879+
}
38513880
}
38523881

38533882
public void BindStandardVertexTexture(VertexTextureSampler sampler, StandardTextureId id) {

‎Source.VTF/VTFTexture.cs‎

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ public sealed class VTFTexture : IVTFTexture
4444
int CoarsestMipmapLevel;
4545

4646
List<ResourceEntryInfo> ResourcesInfo = [];
47+
readonly Dictionary<ResourceEntryType, byte[]> ResourcesData = [];
4748
float IVTFTexture.BumpScale() => BumpScale;
4849

4950
public void ComputeAlphaFlags() {
@@ -224,15 +225,10 @@ public void GenerateMipmaps() {
224225
throw new NotImplementedException();
225226
}
226227

227-
public unsafe Span<byte> GetResourceData(ResourceEntryType type) {
228-
ref ResourceEntryInfo info = ref FindResourceEntryInfo(type);
228+
public Span<byte> GetResourceData(ResourceEntryType type)
229+
=> ResourcesData.TryGetValue(type & ~ResourceEntryType.Flag_Mask, out byte[]? data) ? data : default;
229230

230-
return null;
231-
}
232-
233-
public bool HasResourceEntry(ResourceEntryType type) {
234-
throw new NotImplementedException();
235-
}
231+
public bool HasResourceEntry(ResourceEntryType type) => !Unsafe.IsNullRef(ref FindResourceEntryInfo(type));
236232

237233
int IVTFTexture.Height() => Height;
238234

@@ -479,6 +475,9 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk
479475
if (!ReadHeader(stream, out header))
480476
return false;
481477

478+
ResourcesInfo.Clear();
479+
ResourcesData.Clear();
480+
482481
header.Flags |= (uint)forceFlags;
483482
var flags = (TextureFlags)header.Flags;
484483

@@ -573,7 +572,8 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk
573572
return false;
574573
}
575574

576-
// TODO: LoadNewResources
575+
if (!LoadNewResources(stream))
576+
return false;
577577

578578
ref ResourceEntryInfo imageDataInfo = ref FindResourceEntryInfo(ResourceEntryType.HighResImageData);
579579
if (!Unsafe.IsNullRef(ref imageDataInfo)) {
@@ -587,6 +587,31 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk
587587
return true;
588588
}
589589

590+
private bool LoadNewResources(Stream stream) {
591+
using BinaryReader reader = new(stream, Encoding.ASCII, true);
592+
foreach (ResourceEntryInfo resource in ResourcesInfo) {
593+
ResourceEntryType type = resource.Tag & ~ResourceEntryType.Flag_Mask;
594+
if (type == ResourceEntryType.LowResThumbnail || type == ResourceEntryType.HighResImageData)
595+
continue;
596+
597+
if ((resource.Flags & ((uint)ResourceEntryType.Flag_HasNoDataChunk >> 24)) != 0) {
598+
ResourcesData[type] = BitConverter.GetBytes(resource.Offset);
599+
continue;
600+
}
601+
602+
if (resource.Offset > stream.Length - sizeof(int))
603+
return false;
604+
605+
stream.Seek(resource.Offset, SeekOrigin.Begin);
606+
int numBytes = reader.ReadInt32();
607+
if (numBytes < 0 || numBytes > stream.Length - stream.Position)
608+
return false;
609+
610+
ResourcesData[type] = reader.ReadBytes(numBytes);
611+
}
612+
return true;
613+
}
614+
590615
private bool LoadImageData(Stream stream, VTFFileHeader header, int skipMipLevels) {
591616
if (skipMipLevels > 0) {
592617
if (header.NumMipLevels < skipMipLevels) {
@@ -616,16 +641,6 @@ private bool LoadImageData(Stream stream, VTFFileHeader header, int skipMipLevel
616641
int firstAvailableMip = 0;
617642
int lastAvailableMip = MipCount - 1;
618643

619-
Span<byte> data = GetResourceData(ResourceEntryType.TextureLOD);
620-
if (!data.IsEmpty) {
621-
ref TextureStreamSettings_t streamSettings = ref MemoryMarshal.Cast<byte, TextureStreamSettings_t>(data)[0];
622-
firstAvailableMip = Math.Max(0, streamSettings.FirstAvailableMip - skipMipLevels);
623-
lastAvailableMip = Math.Max(0, streamSettings.LastAvailableMip - skipMipLevels);
624-
mipDataPresent = false;
625-
}
626-
627-
// Not doing streamable textures right now
628-
629644
Assert(firstAvailableMip >= 0 && firstAvailableMip <= lastAvailableMip && lastAvailableMip < MipCount);
630645

631646
FinestMipmapLevel = firstAvailableMip;

0 commit comments

Comments
 (0)