From baa26edb301f6ade91e5467777494f5dcafb131c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:58:21 +0300 Subject: [PATCH 01/19] Fix VirtualMeshList vertex and index storage --- Source.Common/Physics/VirtualMesh.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Source.Common/Physics/VirtualMesh.cs b/Source.Common/Physics/VirtualMesh.cs index 5e51941d3..f39c10494 100644 --- a/Source.Common/Physics/VirtualMesh.cs +++ b/Source.Common/Physics/VirtualMesh.cs @@ -8,12 +8,12 @@ public static class VirtualMeshConstants public const int MAX_VIRTUAL_TRIANGLES = 1024; } -[InlineArray(VirtualMeshConstants.MAX_VIRTUAL_TRIANGLES)] +[InlineArray(VirtualMeshConstants.MAX_VIRTUAL_TRIANGLES * 3)] public struct InlineArrayMaxVirtualTriangles { T first; } public struct VirtualMeshList { - public Vector3 Verts; + public List? Verts; public int IndexCount; public int TriangleCount; public int VertexCount; @@ -30,9 +30,9 @@ public struct VirtualMeshTriangleList public interface IVirtualMeshEvent { - void GetVirtualMesh(object userData, Span list); + void GetVirtualMesh(object userData, ref VirtualMeshList list); void GetWorldspaceBounds(object userData, out Vector3 mins, out Vector3 maxs); - void GetTrianglesInSphere(object userData, in Vector3 center, float radius, Span list); + void GetTrianglesInSphere(object userData, in Vector3 center, float radius, ref VirtualMeshTriangleList list); } public struct VirtualMeshParams From bf046355e18c5749971194115798511fd95d840f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:06:47 +0300 Subject: [PATCH 02/19] Add DispCollTree.GetVirtualMeshList --- Source.Common/DispCollCommon.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Source.Common/DispCollCommon.cs b/Source.Common/DispCollCommon.cs index eeca26e8d..294da3faa 100644 --- a/Source.Common/DispCollCommon.cs +++ b/Source.Common/DispCollCommon.cs @@ -1,5 +1,6 @@ using Source.Common.Formats.BSP; using Source.Common.Mathematics; +using Source.Common.Physics; using System; using System.Collections.Generic; @@ -811,6 +812,23 @@ ushort Cache_EdgeCrossAxisZ(in Vector3 vecEdge, in Vector3 vecOnEdge, in Vector3 return (ushort)AddPlane(vecNormal); } + public void GetVirtualMeshList(ref VirtualMeshList list) { + int i; + int triangleCount = GetTriSize(); + list.IndexCount = triangleCount * 3; + list.TriangleCount = triangleCount; + list.VertexCount = Verts.Count; + list.Verts = Verts; + list.SurfacePropsIndex = GetSurfaceProps(0); + int index = 0; + for (i = 0; i < triangleCount; i++) { + list.Indices[index + 0] = (ushort)Tris[i].GetVert(0); + list.Indices[index + 1] = (ushort)Tris[i].GetVert(1); + list.Indices[index + 2] = (ushort)Tris[i].GetVert(2); + index += 3; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetPower(int power) => Power = power; [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetPower() => Power; From 1e857f971e2713d8a6c9fad367a9f36f6430afcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:14:09 +0300 Subject: [PATCH 03/19] Implement CreateVirtualMesh for Box3D physics --- Source.Common/Physics/PhysicsInterface.cs | 2 +- Source.Physics/PhysicsCollide.cs | 34 +++++++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/Source.Common/Physics/PhysicsInterface.cs b/Source.Common/Physics/PhysicsInterface.cs index 42b45a639..5406b144c 100644 --- a/Source.Common/Physics/PhysicsInterface.cs +++ b/Source.Common/Physics/PhysicsInterface.cs @@ -190,7 +190,7 @@ public interface IPhysicsCollision IPhysicsCollision ThreadContextCreate(); void ThreadContextDestroy(IPhysicsCollision threadContext); - PhysCollide CreateVirtualMesh(in VirtualMeshParams meshParams); + PhysCollide? CreateVirtualMesh(in VirtualMeshParams meshParams); bool SupportsVirtualMesh(); bool GetBBoxCacheSize(out uint cachedSize, out nint cachedCount); diff --git a/Source.Physics/PhysicsCollide.cs b/Source.Physics/PhysicsCollide.cs index f72d6f69d..72f0f44a6 100644 --- a/Source.Physics/PhysicsCollide.cs +++ b/Source.Physics/PhysicsCollide.cs @@ -1112,9 +1112,39 @@ public void DestroyQueryModel(ICollisionQuery query) { } public void ThreadContextDestroy(IPhysicsCollision threadContext) { } - public PhysCollide CreateVirtualMesh(in VirtualMeshParams meshParams) => throw new NotImplementedException(); + public PhysCollide? CreateVirtualMesh(in VirtualMeshParams meshParams) { + if (meshParams.MeshEventHandler == null) + return null; + + VirtualMeshList list = default; + meshParams.MeshEventHandler.GetVirtualMesh(meshParams.UserData!, ref list); + if (list.TriangleCount <= 0 || list.VertexCount <= 0) + return null; + + Vector3[] verts = new Vector3[list.VertexCount]; + for (int i = 0; i < list.VertexCount; i++) + verts[i] = SourceToBox.Distance(list.Verts![i]); + + int[] indices = new int[list.TriangleCount * 3]; + for (int i = 0; i < list.TriangleCount; i++) { + indices[i * 3 + 0] = list.Indices[i * 3 + 0]; + indices[i * 3 + 1] = list.Indices[i * 3 + 2]; + indices[i * 3 + 2] = list.Indices[i * 3 + 1]; + } + + MeshDef def = default; + def.vertices = verts; + def.indices = indices; + def.useMedianSplit = true; + def.identifyEdges = true; + MeshData mesh = MeshData.Create(def, default); + if (mesh.IsNull) + return null; + + return new BoxPhysCollide { Mesh = mesh }; + } - public bool SupportsVirtualMesh() => false; + public bool SupportsVirtualMesh() => true; public bool GetBBoxCacheSize(out uint cachedSize, out nint cachedCount) { cachedSize = 0; From 25861b508ab1fa1f6621a10255dd59a793bd91b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:22:38 +0300 Subject: [PATCH 04/19] Create displacement physics collides at map load --- Source.Engine/CModel_Private.cs | 54 ++++++++++++++++++++++++ Source.Engine/CollisionModelSubsystem.cs | 4 +- Source.Engine/ModelInfo.cs | 2 +- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/Source.Engine/CModel_Private.cs b/Source.Engine/CModel_Private.cs index 988ad343a..1d6576f63 100644 --- a/Source.Engine/CModel_Private.cs +++ b/Source.Engine/CModel_Private.cs @@ -6,6 +6,7 @@ using Source.Common.Commands; using Source.Common.Formats.BSP; using Source.Common.Mathematics; +using Source.Common.Physics; using System.Numerics; using System.Runtime.CompilerServices; @@ -121,6 +122,23 @@ public void Init(in Vector3 minsIn, in Vector3 maxsIn, int counterIn, Contents c } } +class VirtualTerrain : IVirtualMeshEvent +{ + public void GetVirtualMesh(object userData, ref VirtualMeshList list) { + int index = (int)userData; + Assert(index >= 0 && index < CM.g_DispCollTreeCount); + g_DispCollTrees![index].GetVirtualMeshList(ref list); + } + public void GetWorldspaceBounds(object userData, out Vector3 mins, out Vector3 maxs) { + int index = (int)userData; + mins = g_DispBounds![index].Mins; + maxs = g_DispBounds[index].Maxs; + } + public void GetTrianglesInSphere(object userData, in Vector3 center, float radius, ref VirtualMeshTriangleList list) { + throw new NotImplementedException(); + } +} + public static partial class CM { static readonly ObjectPool g_TraceInfoPool = new(); @@ -311,6 +329,42 @@ public static Span Vis(Span dest, int destlen, int cluster, int visT public static nint g_DispCollTreeCount = 0; + static readonly VirtualTerrain g_VirtualTerrain = new(); + static PhysCollide?[] g_TerrainList = []; + + public static PhysCollide? PhysCollideForDisp(int index) { + if (index < 0 || index >= g_DispCollTreeCount) + return null; + + return g_TerrainList[index]; + } + + public static void CreateDispPhysCollide(int dispLumpSize) { + g_TerrainList = new PhysCollide?[g_DispCollTreeCount]; + for (int i = 0; i < g_DispCollTreeCount; i++) { + DispCollTree dispTree = g_DispCollTrees![i]; + if (dispTree != null && dispTree.CheckFlags(CoreDispInfo.SURF_NOPHYSICS_COLL)) { + g_TerrainList[i] = null; + continue; + } + VirtualMeshParams meshParams = default; + meshParams.MeshEventHandler = g_VirtualTerrain; + meshParams.UserData = i; + meshParams.BuildOuterHull = dispLumpSize > 0 ? false : true; + + g_TerrainList[i] = physcollision.CreateVirtualMesh(meshParams); + } + } + + public static void DestroyDispPhysCollide() { + for (int i = g_TerrainList.Length - 1; i >= 0; --i) { + PhysCollide? collide = g_TerrainList[i]; + if (collide != null) + physcollision.DestroyCollide(collide); + } + g_TerrainList = []; + } + internal static TraceInfo BeginTrace() { TraceInfo traceInfo = g_TraceInfoPool.Alloc(); diff --git a/Source.Engine/CollisionModelSubsystem.cs b/Source.Engine/CollisionModelSubsystem.cs index e66fb78d6..a7f1c01f4 100644 --- a/Source.Engine/CollisionModelSubsystem.cs +++ b/Source.Engine/CollisionModelSubsystem.cs @@ -94,7 +94,7 @@ internal void Destroy() { physcollision.VCollideUnload(MapCollisionModels[i].VCollisionData); // DispCollTrees_FreeLeafList(this); - // CM.DestroyDispPhysCollide(); + CM.DestroyDispPhysCollide(); // DispCollTrees_Free(CM.g_DispCollTrees); // CM.g_DispCollTrees = null; // CM.g_DispBounds = null; @@ -649,6 +649,8 @@ internal void LoadDispInfo() { // Link each displacement into the BSP leaves it touches. CM_DispTreeLeafnum(); + + CM.CreateDispPhysCollide((int)MapLoadHelper.GetLumpSize(LumpIndex.PhysDisp)); } // Port of CM_DispTreeLeafnum + CDispLeafBuilder: build the per-leaf displacement lists. diff --git a/Source.Engine/ModelInfo.cs b/Source.Engine/ModelInfo.cs index 39ea85545..75f6a5553 100644 --- a/Source.Engine/ModelInfo.cs +++ b/Source.Engine/ModelInfo.cs @@ -337,7 +337,7 @@ public void SetViewScreenFadeRange(float flMinSize, float flMaxSize) { public byte ComputeViewScreenFade(in Vector3 absOrigin, float radius, float fadeScale) => 255;// TODO!! public PhysCollide? GetCollideForVirtualTerrain(int index) { - throw new NotImplementedException(); + return CM.PhysCollideForDisp(index); } public bool IsUsingFBTexture(Model? model, int nSkin, int nBody, object? pClientRenderable) { From 035e77a824e25cb53f7fbb7f39044d4e86e3f2ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:29:52 +0300 Subject: [PATCH 05/19] Create virtual terrain physics for the world --- Game.Shared/PhysicsShared.cs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/Game.Shared/PhysicsShared.cs b/Game.Shared/PhysicsShared.cs index 25b799818..359c1496c 100644 --- a/Game.Shared/PhysicsShared.cs +++ b/Game.Shared/PhysicsShared.cs @@ -441,6 +441,25 @@ public static bool PhysModelParseSolidByIndex(ref Solid solid, BaseEntity entity return obj; } + public static void PhysCreateVirtualTerrain(BaseEntity world, in ObjectParams defaultParams) { + if (physenv == null) + return; + + for (int i = 0; i < BSPFileCommon.MAX_MAP_DISPINFO; i++) { + PhysCollide? collide = modelinfo.GetCollideForVirtualTerrain(i); + if (collide != null) { + Solid solid = default; + solid.Params = defaultParams; + solid.Params.EnableCollisions = true; + solid.Params.GameData = world; + solid.Params.Name = $"vdisp_{i:D4}"; + int surfaceData = (int)physprops.GetSurfaceIndex("default"); + IPhysicsObject? obj = physenv.CreatePolyObjectStatic(collide, surfaceData, vec3_origin, vec3_angle, ref solid.Params); + obj!.SetCallbackFlags(obj.GetCallbackFlags() | CallbackFlags.NeverDeleted); + } + } + } + public static IPhysicsObject? PhysCreateWorld_Shared(BaseEntity world, VCollide? worldCollide, in ObjectParams defaultParams) { Solid solid = default; Fluid fluid = default; @@ -457,6 +476,8 @@ public static bool PhysModelParseSolidByIndex(ref Solid solid, BaseEntity entity IPhysicsObject? worldPhysics = physenv.CreatePolyObjectStatic(worldCollide.Solids[0]!, surfaceData, vec3_origin, vec3_angle, ref oparams); IVPhysicsKeyParser parse = physcollision.VPhysicsKeyParserCreate(worldCollide.KeyValues!); + + bool createVirtualTerrain = false; while (!parse.Finished()) { ReadOnlySpan block = parse.GetCurrentBlockName(); @@ -472,8 +493,13 @@ public static bool PhysModelParseSolidByIndex(ref Solid solid, BaseEntity entity if (solid.Index == 0) continue; - if (solid.Index >= worldCollide.SolidCount || worldCollide.Solids[solid.Index] == null) + if (solid.Index >= worldCollide.SolidCount) + continue; + + if (worldCollide.Solids[solid.Index] == null) { + createVirtualTerrain = true; continue; + } IPhysicsObject? obj = physenv.CreatePolyObjectStatic(worldCollide.Solids[solid.Index]!, surfaceData, vec3_origin, vec3_angle, ref solid.Params); if (obj == null) @@ -487,11 +513,18 @@ public static bool PhysModelParseSolidByIndex(ref Solid solid, BaseEntity entity else if (strcmpi(block, "fluid") == 0) { parse.ParseFluid(ref fluid, null); } + else if (strcmpi(block, "virtualterrain") == 0) { + createVirtualTerrain = true; + parse.SkipBlock(); + } else parse.SkipBlock(); } physcollision.VPhysicsKeyParserDestroy(parse); + if (createVirtualTerrain && physcollision.SupportsVirtualMesh()) + PhysCreateVirtualTerrain(world, defaultParams); + return worldPhysics; } #endif From 2eb6d08af5f913628bbf4bb500358bd6bb49d34a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:52:16 +0300 Subject: [PATCH 06/19] Set brush surface props from the material $surfaceprop --- Source.Engine/CollisionModelSubsystem.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/CollisionModelSubsystem.cs b/Source.Engine/CollisionModelSubsystem.cs index a7f1c01f4..88de00c69 100644 --- a/Source.Engine/CollisionModelSubsystem.cs +++ b/Source.Engine/CollisionModelSubsystem.cs @@ -171,7 +171,7 @@ internal void LoadTextures() { var = material.FindVar("$surfaceprop", out varFound, false); if (varFound) { ReadOnlySpan props = var.GetStringValue(); - // TODO: set surface properties. + MapSurfaces.AsSpan()[i].SurfaceProps = (ushort)physprop.GetSurfaceIndex(props); } } } From dbd7ddcbc8860884110e74617a8698c7e43373ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:58:43 +0300 Subject: [PATCH 07/19] Set displacement surface props from their material --- Source.Engine/CollisionModelSubsystem.cs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Source.Engine/CollisionModelSubsystem.cs b/Source.Engine/CollisionModelSubsystem.cs index 88de00c69..39f24b33f 100644 --- a/Source.Engine/CollisionModelSubsystem.cs +++ b/Source.Engine/CollisionModelSubsystem.cs @@ -564,6 +564,7 @@ internal void LoadDispInfo() { BSPDDispInfo[] dispInfos = new MapLoadHelper(LumpIndex.DispInfo).LoadLumpData(); DispVert[] dispVerts = new MapLoadHelper(LumpIndex.DispVerts).LoadLumpData(); DispTri[] dispTris = new MapLoadHelper(LumpIndex.DispTris).LoadLumpData(); + BSPTexInfo[] texinfos = new MapLoadHelper(LumpIndex.TexInfo).LoadLumpData(); if (faces.Length == 0) return; @@ -643,8 +644,24 @@ internal void LoadDispInfo() { tree.GetBounds(out Vector3 treeMins, out Vector3 treeMaxs); g_DispBounds[i].Init(treeMins, treeMaxs, tree.Counter, tree.GetContents()); - // NOTE: surface props are left at their defaults; physprops material lookup - // is not yet wired in the collision subsystem (see LoadTextures TODO). + ref BSPTexInfo tex = ref texinfos[face.TexInfo]; + if (tex.TexData >= 0) { + IMaterial material = materials!.FindMaterial(MapSurfaces[tex.TexData].Name, MaterialDefines.TEXTURE_GROUP_WORLD, true); + if (!material.IsErrorMaterial()) { + IMaterialVar var = material.FindVar("$surfaceprop", out bool varFound, false); + if (varFound) { + ReadOnlySpan props = var.GetStringValue(); + tree.SetSurfaceProps(0, (short)physprop.GetSurfaceIndex(props)); + tree.SetSurfaceProps(1, (short)physprop.GetSurfaceIndex(props)); + } + + var = material.FindVar("$surfaceprop2", out varFound, false); + if (varFound) { + ReadOnlySpan props = var.GetStringValue(); + tree.SetSurfaceProps(1, (short)physprop.GetSurfaceIndex(props)); + } + } + } } // Link each displacement into the BSP leaves it touches. From 723aa763a2f6d890bdd64b5aca21dc15f8ba01b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:04:27 +0300 Subject: [PATCH 08/19] Implement SetWorldMaterialIndexTable --- Source.Physics/PhysicsMaterial.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Source.Physics/PhysicsMaterial.cs b/Source.Physics/PhysicsMaterial.cs index 054e6471d..518c5d929 100644 --- a/Source.Physics/PhysicsMaterial.cs +++ b/Source.Physics/PhysicsMaterial.cs @@ -269,10 +269,15 @@ private ReadOnlySpan ParseKeyvalue(ReadOnlySpan buffer, scoped Span< return buffer; } + readonly nint[] WorldMaterialMap = new nint[128]; + public void SetWorldMaterialIndexTable(Span mapArray) { - throw new NotImplementedException(); + int size = Math.Min(mapArray.Length, WorldMaterialMap.Length); + mapArray[..size].CopyTo(WorldMaterialMap); } + internal nint RemapWorldMaterial(int index) => WorldMaterialMap[index]; + public nint SurfacePropCount() { return Props.Count; } From 793854937bbf66f90a22a68eaafc39282752b918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:09:55 +0300 Subject: [PATCH 09/19] Load the world material table before creating the world --- Game.Shared/PhysicsShared.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Game.Shared/PhysicsShared.cs b/Game.Shared/PhysicsShared.cs index 359c1496c..a9c316652 100644 --- a/Game.Shared/PhysicsShared.cs +++ b/Game.Shared/PhysicsShared.cs @@ -473,6 +473,18 @@ public static void PhysCreateVirtualTerrain(BaseEntity world, in ObjectParams de oparams.GameData = world; oparams.Name = "world"; + Span surfaceTable = stackalloc nint[128]; + IVPhysicsKeyParser tableParse = physcollision.VPhysicsKeyParserCreate(worldCollide.KeyValues!); + while (!tableParse.Finished()) { + if (strcmpi(tableParse.GetCurrentBlockName(), "materialtable") == 0) { + tableParse.ParseSurfaceTable(surfaceTable, null); + physprops.SetWorldMaterialIndexTable(surfaceTable); + } + else + tableParse.SkipBlock(); + } + physcollision.VPhysicsKeyParserDestroy(tableParse); + IPhysicsObject? worldPhysics = physenv.CreatePolyObjectStatic(worldCollide.Solids[0]!, surfaceData, vec3_origin, vec3_angle, ref oparams); IVPhysicsKeyParser parse = physcollision.VPhysicsKeyParserCreate(worldCollide.KeyValues!); From b0efd3ca3131f36533ca60b6466648d33a1f2685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:18:31 +0300 Subject: [PATCH 10/19] Apply world materials per convex hull --- Source.Physics/PhysicsEnvironment.cs | 2 +- Source.Physics/PhysicsObject.cs | 36 +++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 2255d38d6..31e1613d2 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -246,7 +246,7 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve foreach (BoxPhysConvex convex in collide.Convexes) { if (convex.Hull.IsNull) continue; - Shape.CreateHull(bodyId, shapeDef, isStatic ? convex.Hull : convex.GetSimHull()); + Shape.CreateHull(bodyId, PhysicsObject.MakeConvexShapeDef(convex, materialIndex, false), isStatic ? convex.Hull : convex.GetSimHull()); } if (!collide.Mesh.IsNull) diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index ca608d490..ae1d4fccd 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -683,6 +683,38 @@ public float ComputeShadowControlEx(in HLShadowControlParams parms, float second public PhysCollide GetCollide() => Collide!; public ReadOnlySpan GetName() => Name; + internal static int ConvexMaterialIndex(BoxPhysConvex convex, int materialIndex) { + byte[]? materials = convex.QueryMaterials; + Vector3[]? verts = convex.QueryVerts; + if (materials == null || verts == null) + return materialIndex; + + Span areas = stackalloc float[128]; + int best = 0; + for (int i = 0; i < materials.Length; i++) { + int material = materials[i]; + if (material == 0) + continue; + + Vector3 a = verts[i * 3 + 0]; + areas[material] += Vector3.Cross(verts[i * 3 + 1] - a, verts[i * 3 + 2] - a).Length(); + if (best == 0 || areas[material] > areas[best]) + best = material; + } + + return best == 0 ? materialIndex : (int)((PhysicsSurfaceProps)physprops).RemapWorldMaterial(best); + } + + internal static ShapeDef MakeConvexShapeDef(BoxPhysConvex convex, int materialIndex, bool sensor) + => MakeShapeDef(sensor ? materialIndex : ConvexMaterialIndex(convex, materialIndex), materialIndex, sensor); + + static ShapeDef MakeShapeDef(int shapeMaterial, int materialIndex, bool sensor) { + ShapeDef shapeDef = MakeShapeDef(shapeMaterial, sensor); + if (shapeMaterial != materialIndex) + shapeDef.baseMaterial.userMaterialId = (ulong)shapeMaterial + 1; + return shapeDef; + } + internal static ShapeDef MakeShapeDef(int materialIndex, bool sensor) { ShapeDef shapeDef = ShapeDef.Default; shapeDef.enableSensorEvents = true; @@ -719,7 +751,9 @@ void RebuildShapes(bool asSensor) { foreach (BoxPhysConvex convex in Collide.Convexes) { if (convex.Hull.IsNull) continue; - Shape.CreateHull(BodyId, shapeDef, Static ? convex.Hull : convex.GetSimHull()); + ShapeDef convexShapeDef = MakeConvexShapeDef(convex, MaterialIndex, asSensor); + convexShapeDef.updateBodyMass = false; + Shape.CreateHull(BodyId, convexShapeDef, Static ? convex.Hull : convex.GetSimHull()); } if (!Collide.Mesh.IsNull) Shape.CreateMesh(BodyId, shapeDef, Collide.Mesh, Vector3.One); From e16cabc00a55eb46be41a9f8422b0ee9e83562f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:26:08 +0300 Subject: [PATCH 11/19] Use the displacement surface prop for its physics mesh --- Source.Physics/PhysicsCollide.cs | 3 ++- Source.Physics/PhysicsEnvironment.cs | 3 +-- Source.Physics/PhysicsObject.cs | 10 ++++++++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Source.Physics/PhysicsCollide.cs b/Source.Physics/PhysicsCollide.cs index 72f0f44a6..35030278c 100644 --- a/Source.Physics/PhysicsCollide.cs +++ b/Source.Physics/PhysicsCollide.cs @@ -112,6 +112,7 @@ internal sealed unsafe class BoxPhysCollide : PhysCollide { public readonly List Convexes = []; public MeshData Mesh; + public int MeshMaterialIndex = -1; public Vector3 MassCenter; public Vector3 UnitInertia; @@ -1141,7 +1142,7 @@ public void ThreadContextDestroy(IPhysicsCollision threadContext) { } if (mesh.IsNull) return null; - return new BoxPhysCollide { Mesh = mesh }; + return new BoxPhysCollide { Mesh = mesh, MeshMaterialIndex = list.SurfacePropsIndex }; } public bool SupportsVirtualMesh() => true; diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 31e1613d2..8f538c4d4 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -242,7 +242,6 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve BoxPhysCollide? collide = collisionModel as BoxPhysCollide; if (collide != null) { - ShapeDef shapeDef = PhysicsObject.MakeShapeDef(materialIndex, false); foreach (BoxPhysConvex convex in collide.Convexes) { if (convex.Hull.IsNull) continue; @@ -250,7 +249,7 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve } if (!collide.Mesh.IsNull) - Shape.CreateMesh(bodyId, shapeDef, collide.Mesh, Vector3.One); + Shape.CreateMesh(bodyId, PhysicsObject.MakeMeshShapeDef(collide, materialIndex, false), collide.Mesh, Vector3.One); } Vector3 massCenter = collide?.MassCenter ?? default; diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index ae1d4fccd..18750f051 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -708,6 +708,9 @@ internal static int ConvexMaterialIndex(BoxPhysConvex convex, int materialIndex) internal static ShapeDef MakeConvexShapeDef(BoxPhysConvex convex, int materialIndex, bool sensor) => MakeShapeDef(sensor ? materialIndex : ConvexMaterialIndex(convex, materialIndex), materialIndex, sensor); + internal static ShapeDef MakeMeshShapeDef(BoxPhysCollide collide, int materialIndex, bool sensor) + => MakeShapeDef(sensor || collide.MeshMaterialIndex < 0 ? materialIndex : collide.MeshMaterialIndex, materialIndex, sensor); + static ShapeDef MakeShapeDef(int shapeMaterial, int materialIndex, bool sensor) { ShapeDef shapeDef = MakeShapeDef(shapeMaterial, sensor); if (shapeMaterial != materialIndex) @@ -755,8 +758,11 @@ void RebuildShapes(bool asSensor) { convexShapeDef.updateBodyMass = false; Shape.CreateHull(BodyId, convexShapeDef, Static ? convex.Hull : convex.GetSimHull()); } - if (!Collide.Mesh.IsNull) - Shape.CreateMesh(BodyId, shapeDef, Collide.Mesh, Vector3.One); + if (!Collide.Mesh.IsNull) { + ShapeDef meshShapeDef = MakeMeshShapeDef(Collide, MaterialIndex, asSensor); + meshShapeDef.updateBodyMass = false; + Shape.CreateMesh(BodyId, meshShapeDef, Collide.Mesh, Vector3.One); + } } else if (SphereRadius > 0.0f) { Sphere sphere = new() { center = default, radius = SourceToBox.Distance(SphereRadius) }; From ad3ef48ea917133d0dc34d1a373fd775add06160 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:33:47 +0300 Subject: [PATCH 12/19] Report per-shape surface props in collisions and friction --- Source.Physics/PhysicsEnvironment.cs | 4 ++-- Source.Physics/PhysicsFriction.cs | 16 +++++++++++++--- Source.Physics/PhysicsObject.cs | 5 +++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 8f538c4d4..6019cfa5d 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -567,8 +567,8 @@ void DrainContactEvents() { VCollisionEvent ev = default; ev.Objects[0] = p1; ev.Objects[1] = p2; - ev.SurfaceProps[0] = p1.GetMaterialIndex(); - ev.SurfaceProps[1] = p2.GetMaterialIndex(); + ev.SurfaceProps[0] = p1.GetShapeMaterialIndex(hit.shapeIdA); + ev.SurfaceProps[1] = p2.GetShapeMaterialIndex(hit.shapeIdB); ev.IsCollision = isCollision; ev.IsShadowCollision = isShadowCollision; ev.DeltaCollisionTime = deltaCollisionTime; diff --git a/Source.Physics/PhysicsFriction.cs b/Source.Physics/PhysicsFriction.cs index c18c11bc6..1ae0028ef 100644 --- a/Source.Physics/PhysicsFriction.cs +++ b/Source.Physics/PhysicsFriction.cs @@ -13,6 +13,8 @@ struct Entry { public PhysicsObject Self; public PhysicsObject Other; + public int SelfMaterial; + public int OtherMaterial; public Vector3 Normal; public Vector3 Point; public float NormalForce; @@ -42,6 +44,8 @@ public PhysicsFrictionSnapshot(PhysicsObject self, float stepTime) { if (other == null) continue; + int selfMaterial = self.GetShapeMaterialIndex(selfIsA ? contact.shapeIdA : contact.shapeIdB); + int otherMaterial = other.GetShapeMaterialIndex(selfIsA ? contact.shapeIdB : contact.shapeIdA); Vector3 comA = BoxToSource.Unitless(bodyA.WorldCenter); { @@ -58,6 +62,8 @@ public PhysicsFrictionSnapshot(PhysicsObject self, float stepTime) { Entries.Add(new Entry { Self = self, Other = other, + SelfMaterial = selfMaterial, + OtherMaterial = otherMaterial, Normal = normal, Point = BoxToSource.Distance(SourceToBox.Unitless(comA + BoxToSource.Unitless(point.anchorA))), NormalForce = BoxToSource.Distance(point.totalNormalImpulse * invStep), @@ -77,7 +83,11 @@ public PhysicsFrictionSnapshot(PhysicsObject self, float stepTime) { return index == 1 ? Entries[Index].Other : Entries[Index].Self; } - public int GetMaterial(int index) => GetObject(index) is PhysicsObject obj ? obj.GetMaterialIndex() : 0; + public int GetMaterial(int index) { + if (!IsValid()) + return 0; + return index == 1 ? Entries[Index].OtherMaterial : Entries[Index].SelfMaterial; + } public void GetContactPoint(out Vector3 vec) => vec = IsValid() ? Entries[Index].Point : default; public void GetSurfaceNormal(out Vector3 vec) => vec = IsValid() ? Entries[Index].Normal : default; @@ -94,8 +104,8 @@ public void DeleteAllMarkedContacts(bool wakeObjects) { } public float GetFrictionCoefficient() { if (!IsValid()) return 0.0f; - SurfaceData_ptr? selfSurface = physprops.GetSurfaceData(Entries[Index].Self.GetMaterialIndex()); - SurfaceData_ptr? otherSurface = physprops.GetSurfaceData(Entries[Index].Other.GetMaterialIndex()); + SurfaceData_ptr? selfSurface = physprops.GetSurfaceData(Entries[Index].SelfMaterial); + SurfaceData_ptr? otherSurface = physprops.GetSurfaceData(Entries[Index].OtherMaterial); float self = selfSurface != null ? selfSurface.Physics.Friction : 0.0f; float other = otherSurface != null ? otherSurface.Physics.Friction : self; return self * other; diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index 18750f051..7dbe36da1 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -718,6 +718,11 @@ static ShapeDef MakeShapeDef(int shapeMaterial, int materialIndex, bool sensor) return shapeDef; } + internal int GetShapeMaterialIndex(Shape shape) { + ulong id = shape.SurfaceMaterial.userMaterialId; + return id != 0 ? (int)(id - 1) : MaterialIndex; + } + internal static ShapeDef MakeShapeDef(int materialIndex, bool sensor) { ShapeDef shapeDef = ShapeDef.Default; shapeDef.enableSensorEvents = true; From a57166f53f394cbb0b61ae6a61eee62b0e86d742 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:58:22 +0300 Subject: [PATCH 13/19] Update Box3D.Sharp to 0.1.2 --- Source.Physics/Source.Physics.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Physics/Source.Physics.csproj b/Source.Physics/Source.Physics.csproj index 9b71ccf27..fbce2515d 100644 --- a/Source.Physics/Source.Physics.csproj +++ b/Source.Physics/Source.Physics.csproj @@ -11,7 +11,7 @@ - + From cebfa967cb808cbea0dda6ee72f02b3b3bb6ed3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:04:39 +0300 Subject: [PATCH 14/19] Mix restitution with MultiplyClamp like IVP --- Source.Physics/PhysicsEnvironment.cs | 2 +- Source.Physics/PhysicsObject.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 6019cfa5d..2d9a18149 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -93,7 +93,7 @@ public PhysicsEnvironment() { def.contactSpeed = SourceToBox.Distance(100.0f); def.workerCount = (uint)Math.Clamp(Environment.ProcessorCount / 2, 1, MaxWorkers); def.frictionMixingRule = MixingRule.Multiply; - def.restitutionMixingRule = MixingRule.GeometricMean; + def.restitutionMixingRule = MixingRule.MultiplyClamp; WorldId = World.Create(def); WorldId.SetCustomFilterHandler(this); diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index 7dbe36da1..25c43b0ec 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -376,7 +376,7 @@ public void SetMaterialIndex(int materialIndex) { return; float friction = MathF.Max(surface.Physics.Friction, 0.0f); - float restitution = Math.Clamp(surface.Physics.Elasticity, 0.0f, 1.0f); + float restitution = MathF.Max(surface.Physics.Elasticity, 0.0f); ForEachShape(shape => { shape.Friction = friction; shape.Restitution = restitution; @@ -739,7 +739,7 @@ internal static ShapeDef MakeShapeDef(int materialIndex, bool sensor) { SurfaceData_ptr? surface = physprops.GetSurfaceData(materialIndex); if (surface != null) { shapeDef.baseMaterial.friction = MathF.Max(surface.Physics.Friction, 0.0f); - shapeDef.baseMaterial.restitution = Math.Clamp(surface.Physics.Elasticity, 0.0f, 1.0f); + shapeDef.baseMaterial.restitution = MathF.Max(surface.Physics.Elasticity, 0.0f); if (surface.Physics.Density > 0.0f) shapeDef.density = surface.Physics.Density; } From 568adc648ac9f6cc67acf68493ef86bde7d04797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:12:51 +0300 Subject: [PATCH 15/19] Apply world materials per hull face --- Source.Physics/PhysicsEnvironment.cs | 8 +-- Source.Physics/PhysicsObject.cs | 75 +++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 9 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 2d9a18149..2cbe6f569 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -242,10 +242,12 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve BoxPhysCollide? collide = collisionModel as BoxPhysCollide; if (collide != null) { + Span faceMaterials = stackalloc SurfaceMaterial[Box3D.Constants.MaxHullFaces]; foreach (BoxPhysConvex convex in collide.Convexes) { if (convex.Hull.IsNull) continue; - Shape.CreateHull(bodyId, PhysicsObject.MakeConvexShapeDef(convex, materialIndex, false), isStatic ? convex.Hull : convex.GetSimHull()); + HullData hull = isStatic ? convex.Hull : convex.GetSimHull(); + Shape.CreateHull(bodyId, PhysicsObject.MakeConvexShapeDef(convex, hull, materialIndex, false, faceMaterials), hull); } if (!collide.Mesh.IsNull) @@ -567,8 +569,8 @@ void DrainContactEvents() { VCollisionEvent ev = default; ev.Objects[0] = p1; ev.Objects[1] = p2; - ev.SurfaceProps[0] = p1.GetShapeMaterialIndex(hit.shapeIdA); - ev.SurfaceProps[1] = p2.GetShapeMaterialIndex(hit.shapeIdB); + ev.SurfaceProps[0] = hit.userMaterialIdA != 0 ? (int)(hit.userMaterialIdA - 1) : p1.GetMaterialIndex(); + ev.SurfaceProps[1] = hit.userMaterialIdB != 0 ? (int)(hit.userMaterialIdB - 1) : p2.GetMaterialIndex(); ev.IsCollision = isCollision; ev.IsShadowCollision = isShadowCollision; ev.DeltaCollisionTime = deltaCollisionTime; diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index 25c43b0ec..dc3d77c31 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -705,8 +705,70 @@ internal static int ConvexMaterialIndex(BoxPhysConvex convex, int materialIndex) return best == 0 ? materialIndex : (int)((PhysicsSurfaceProps)physprops).RemapWorldMaterial(best); } - internal static ShapeDef MakeConvexShapeDef(BoxPhysConvex convex, int materialIndex, bool sensor) - => MakeShapeDef(sensor ? materialIndex : ConvexMaterialIndex(convex, materialIndex), materialIndex, sensor); + static int FillFaceMaterials(BoxPhysConvex convex, HullData hull, int materialIndex, Span faceMaterials) { + byte[]? materials = convex.QueryMaterials; + Vector3[]? verts = convex.QueryVerts; + if (materials == null || verts == null || hull.IsNull || !materials.AsSpan().ContainsAnyExcept((byte)0)) + return 0; + + Vector3 center = default; + foreach (Vector3 vert in verts) + center += vert; + center /= verts.Length; + + ReadOnlySpan planes = hull.Planes; + int faceCount = Math.Min(planes.Length, faceMaterials.Length); + for (int f = 0; f < faceCount; f++) { + float bestDot = float.MinValue; + int best = 0; + for (int t = 0; t < materials.Length; t++) { + Vector3 a = verts[t * 3 + 0], b = verts[t * 3 + 1], c = verts[t * 3 + 2]; + Vector3 normal = Vector3.Cross(b - a, c - a); + float length = normal.Length(); + if (length <= 0.0f) + continue; + + normal /= length; + if (Vector3.Dot(normal, (a + b + c) / 3.0f - center) < 0.0f) + normal = -normal; + + float dot = Vector3.Dot(normal, planes[f].normal); + if (dot > bestDot) { + bestDot = dot; + best = materials[t]; + } + } + + int faceMaterial = best == 0 ? materialIndex : (int)((PhysicsSurfaceProps)physprops).RemapWorldMaterial(best); + faceMaterials[f] = MakeSurfaceMaterial(faceMaterial, materialIndex); + } + return faceCount; + } + + internal static ShapeDef MakeConvexShapeDef(BoxPhysConvex convex, HullData hull, int materialIndex, bool sensor, Span faceMaterials) { + ShapeDef shapeDef = MakeShapeDef(sensor ? materialIndex : ConvexMaterialIndex(convex, materialIndex), materialIndex, sensor); + if (!sensor) { + int faceCount = FillFaceMaterials(convex, hull, materialIndex, faceMaterials); + if (faceCount > 0) + shapeDef.materials = faceMaterials[..faceCount]; + } + return shapeDef; + } + + static SurfaceMaterial MakeSurfaceMaterial(int shapeMaterial, int materialIndex) { + SurfaceMaterial material = ShapeDef.Default.baseMaterial; + SurfaceData_ptr? surface = physprops.GetSurfaceData(shapeMaterial); + if (surface != null) + ApplySurfaceMaterial(ref material, surface); + if (shapeMaterial != materialIndex) + material.userMaterialId = (ulong)shapeMaterial + 1; + return material; + } + + static void ApplySurfaceMaterial(ref SurfaceMaterial material, SurfaceData_ptr surface) { + material.friction = MathF.Max(surface.Physics.Friction, 0.0f); + material.restitution = MathF.Max(surface.Physics.Elasticity, 0.0f); + } internal static ShapeDef MakeMeshShapeDef(BoxPhysCollide collide, int materialIndex, bool sensor) => MakeShapeDef(sensor || collide.MeshMaterialIndex < 0 ? materialIndex : collide.MeshMaterialIndex, materialIndex, sensor); @@ -738,8 +800,7 @@ internal static ShapeDef MakeShapeDef(int materialIndex, bool sensor) { SurfaceData_ptr? surface = physprops.GetSurfaceData(materialIndex); if (surface != null) { - shapeDef.baseMaterial.friction = MathF.Max(surface.Physics.Friction, 0.0f); - shapeDef.baseMaterial.restitution = MathF.Max(surface.Physics.Elasticity, 0.0f); + ApplySurfaceMaterial(ref shapeDef.baseMaterial, surface); if (surface.Physics.Density > 0.0f) shapeDef.density = surface.Physics.Density; } @@ -756,12 +817,14 @@ void RebuildShapes(bool asSensor) { shapeDef.updateBodyMass = false; if (Collide != null) { + Span faceMaterials = stackalloc SurfaceMaterial[Box3D.Constants.MaxHullFaces]; foreach (BoxPhysConvex convex in Collide.Convexes) { if (convex.Hull.IsNull) continue; - ShapeDef convexShapeDef = MakeConvexShapeDef(convex, MaterialIndex, asSensor); + HullData hull = Static ? convex.Hull : convex.GetSimHull(); + ShapeDef convexShapeDef = MakeConvexShapeDef(convex, hull, MaterialIndex, asSensor, faceMaterials); convexShapeDef.updateBodyMass = false; - Shape.CreateHull(BodyId, convexShapeDef, Static ? convex.Hull : convex.GetSimHull()); + Shape.CreateHull(BodyId, convexShapeDef, hull); } if (!Collide.Mesh.IsNull) { ShapeDef meshShapeDef = MakeMeshShapeDef(Collide, MaterialIndex, asSensor); From 1f44d3c1342a3fc5de4a39930dafbc618e441749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:39:18 +0300 Subject: [PATCH 16/19] Fix sim hull inflation blowing out on shallow corners --- Source.Physics/PhysicsCollide.cs | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/Source.Physics/PhysicsCollide.cs b/Source.Physics/PhysicsCollide.cs index 35030278c..0d3572c4f 100644 --- a/Source.Physics/PhysicsCollide.cs +++ b/Source.Physics/PhysicsCollide.cs @@ -37,8 +37,9 @@ public HullData GetSimHull() { ReadOnlySpan planes = Hull.Planes; float inflate = SourceToBox.Distance(0.25f); + float tolerance = 0.01f * inflate; - Vector3[] verts = new Vector3[vertexCount]; + List verts = new(vertexCount); Span faces = stackalloc int[32]; for (int v = 0; v < vertexCount; v++) { Vector3 p = BoxToSource.Unitless(points[v]); @@ -84,17 +85,28 @@ public HullData GetSimHull() { float d2 = planes[faces[i2]].offset + inflate; x = (d0 * Vector3.Cross(n1, n2) + d1 * Vector3.Cross(n2, n0) + d2 * Vector3.Cross(n0, n1)) * (1.0f / det); } - if (i2 < 0 || (x - p).Length() > 20.0f * inflate) { - Vector3 sum = n0; - for (int i = 1; i < faceCount; i++) - sum += BoxToSource.Unitless(planes[faces[i]].normal); - float len = sum.Length(); - x = p + inflate * (len > 1e-6f ? sum * (1.0f / len) : n0); + bool valid = i2 >= 0 && (x - p).Length() <= 2.0f * inflate; + for (int j = 0; valid && j < planes.Length; j++) { + if (Vector3.Dot(BoxToSource.Unitless(planes[j].normal), x) > planes[j].offset + inflate + tolerance) + valid = false; + } + + if (valid) { + verts.Add(SourceToBox.Unitless(x)); + continue; + } + + for (int i = 0; i < faceCount; i++) { + Vector3 normal = BoxToSource.Unitless(planes[faces[i]].normal); + bool duplicate = false; + for (int k = 0; k < i && !duplicate; k++) + duplicate = Vector3.Dot(normal, BoxToSource.Unitless(planes[faces[k]].normal)) > 0.999f; + if (!duplicate) + verts.Add(SourceToBox.Unitless(p + inflate * normal)); } - verts[v] = SourceToBox.Unitless(x); } - SimHull = BoxHullCooking.CreateHullSafe(verts, BoxHullCooking.MaxHullVertices); + SimHull = BoxHullCooking.CreateHullSafe(CollectionsMarshal.AsSpan(verts), BoxHullCooking.MaxHullVertices); return !SimHull.IsNull ? SimHull : Hull; } From a5cca53bc47e6a45bdcda5bb7aecd4cd177d270b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:44:52 +0300 Subject: [PATCH 17/19] Fix props using IVP diagonal inertia instead of shape inertia --- Source.Physics/PhysicsEnvironment.cs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 2cbe6f569..53e3880c2 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -212,27 +212,23 @@ static BodyDef MakeBodyDef(bool isStatic, in Vector3 position, in QAngle angles) return bodyDef; } - static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Vector3 unitInertia, float inertiaFactor) { + static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, float inertiaFactor) { if (inertiaFactor <= 0) inertiaFactor = 1.0f; if (inertiaFactor > 1e14f) inertiaFactor = 1e14f; - const float minInertia = BoxUnits.InchesToMetres * BoxUnits.InchesToMetres; - Vector3 inertia = unitInertia * (mass * inertiaFactor); - inertia.X = inertia.X > 0.0f ? inertia.X : minInertia; - inertia.Y = inertia.Y > 0.0f ? inertia.Y : minInertia; - inertia.Z = inertia.Z > 0.0f ? inertia.Z : minInertia; - body.ApplyMassFromShapes(); - MassData massData = default; + MassData massData = body.MassData; + float scale = (massData.mass > 0.0f ? mass / massData.mass : 1.0f) * inertiaFactor; massData.mass = mass; - massData.center = SourceToBox.Distance(massCenter); - massData.inertia.cx.X = inertia.X; - massData.inertia.cy.Y = inertia.Y; - massData.inertia.cz.Z = inertia.Z; + massData.inertia.cx *= scale; + massData.inertia.cy *= scale; + massData.inertia.cz *= scale; + if (massCenter != Vector3.Zero) + massData.center = SourceToBox.Distance(massCenter); body.MassData = massData; } @@ -260,7 +256,7 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve if (!isStatic) { float mass = Math.Clamp(objParams.Mass, PhysicsConstants.VPHYSICS_MIN_MASS, PhysicsConstants.VPHYSICS_MAX_MASS); - ApplyMassProperties(bodyId, mass, massCenter, collide?.UnitInertia ?? default, objParams.Inertia); + ApplyMassProperties(bodyId, mass, massCenter, objParams.Inertia); } PhysicsObject obj = new(bodyId, this, isStatic, materialIndex, collisionModel, objParams, hasParams); @@ -284,9 +280,8 @@ static void ApplyMassProperties(Body body, float mass, in Vector3 massCenter, Ve Shape.CreateSphere(bodyId, shapeDef, sphere); if (!isStatic) { - float r = sphere.radius; float mass = Math.Clamp(objParams.Mass, PhysicsConstants.VPHYSICS_MIN_MASS, PhysicsConstants.VPHYSICS_MAX_MASS); - ApplyMassProperties(bodyId, mass, default, new Vector3(0.4f * r * r), objParams.Inertia); + ApplyMassProperties(bodyId, mass, default, objParams.Inertia); } PhysicsObject obj = new(bodyId, this, isStatic, materialIndex, null, objParams, true); From de5900612fa85c79f02f3d4b7a4bac85801f51be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:46:05 +0300 Subject: [PATCH 18/19] Fix collision events dropping impacts IVP reports --- Source.Physics/PhysicsEnvironment.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 53e3880c2..2ddc4c745 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -28,7 +28,6 @@ internal unsafe partial class PhysicsEnvironment : IPhysicsEnvironment, ICustomF static readonly ConVar vbox_contact_damping = new("vbox_contact_damping", "10", 0, "Contact damping ratio. Higher settles overlap with less bounce.", 0.0, 100.0); static readonly ConVar vbox_contact_speed = new("vbox_contact_speed", "400", 0, "Overlap push-out speed cap in in/s.", 0.0, 1000.0); - const float CollisionEventInterval = 0.2f; const float PenetrationDepth = 2.0f; const int MaxWorkers = 64; @@ -87,7 +86,7 @@ public PhysicsEnvironment() { PerformanceParams.Defaults(); WorldDef def = WorldDef.Default; - def.hitEventThreshold = SourceToBox.Distance(70.0f); + def.hitEventThreshold = SourceToBox.Distance(2.0f); def.maximumLinearSpeed = SourceToBox.Distance(3500.0f); def.enableContinuous = true; def.contactSpeed = SourceToBox.Distance(100.0f); @@ -551,8 +550,8 @@ void DrainContactEvents() { float delta1 = p1.LastCollisionPartnerId == p2.UniqueId ? (float)SimulationClock - p1.LastCollisionTime : 1000.0f; float delta2 = p2.LastCollisionPartnerId == p1.UniqueId ? (float)SimulationClock - p2.LastCollisionTime : 1000.0f; float deltaCollisionTime = MathF.Min(delta1, delta2); - if (deltaCollisionTime < CollisionEventInterval) - continue; + if (deltaCollisionTime > 999.0f) + deltaCollisionTime = 1.0f; p1.LastCollisionTime = (float)SimulationClock; p1.LastCollisionPartnerId = p2.UniqueId; From de87cc94259724a5f51263366c4994364753e2ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:47:21 +0300 Subject: [PATCH 19/19] Add vbox_dumpcollide command --- Source.Physics/Main.cs | 14 ++++++++ Source.Physics/PhysicsEnvironment.cs | 7 ++++ Source.Physics/PhysicsObject.cs | 48 ++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) diff --git a/Source.Physics/Main.cs b/Source.Physics/Main.cs index a65361ae3..ffe1de57d 100644 --- a/Source.Physics/Main.cs +++ b/Source.Physics/Main.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection; +using Source.Common.Commands; using Source.Common.Physics; using System.Runtime.CompilerServices; @@ -77,6 +78,19 @@ public void DestroyEnvironment(IPhysicsEnvironment? env) { (env as PhysicsEnvironment)?.Destroy(); } + [ConCommand("vbox_dumpcollide", "Dumps collision and mass data of physics objects whose name contains the argument.", FCvar.Cheat)] + void vbox_dumpcollide(in TokenizedCommand args) { + if (args.ArgC() < 2) { + Msg("Usage: vbox_dumpcollide \n"); + return; + } + + for (int i = 0; i < Environments.Count; i++) { + if (Environments[i] is PhysicsEnvironment environment) + environment.DumpCollide(i, args[1]); + } + } + public IPhysicsEnvironment? GetActiveEnvironmentByIndex(int index) { if (index < 0 || index >= Environments.Count) return null; diff --git a/Source.Physics/PhysicsEnvironment.cs b/Source.Physics/PhysicsEnvironment.cs index 2ddc4c745..7d33c1ada 100644 --- a/Source.Physics/PhysicsEnvironment.cs +++ b/Source.Physics/PhysicsEnvironment.cs @@ -642,6 +642,13 @@ void SolvePenetrations(float dt) { } } + internal void DumpCollide(int environmentIndex, ReadOnlySpan filter) { + foreach (PhysicsObject obj in Objects) { + if (obj.GetName().Contains(filter, StringComparison.OrdinalIgnoreCase)) + obj.DumpCollide(environmentIndex); + } + } + public bool IsInSimulation() => InSimulation; public TimeUnit_t GetSimulationTimestep() => SimulationTimestep; diff --git a/Source.Physics/PhysicsObject.cs b/Source.Physics/PhysicsObject.cs index dc3d77c31..8e35935cb 100644 --- a/Source.Physics/PhysicsObject.cs +++ b/Source.Physics/PhysicsObject.cs @@ -683,6 +683,54 @@ public float ComputeShadowControlEx(in HLShadowControlParams parms, float second public PhysCollide GetCollide() => Collide!; public ReadOnlySpan GetName() => Name; + static string HullInfo(HullData hull) { + if (hull.IsNull) + return "none"; + + ReadOnlySpan points = hull.Points; + Vector3 mins = new(float.MaxValue), maxs = new(float.MinValue); + foreach (Vector3 point in points) { + mins = Vector3.Min(mins, point); + maxs = Vector3.Max(maxs, point); + } + mins = BoxToSource.Distance(mins); + maxs = BoxToSource.Distance(maxs); + Vector3 size = maxs - mins; + return $"{hull.VertexCount} verts, {hull.FaceCount} faces, mins ({mins.X:F2} {mins.Y:F2} {mins.Z:F2}) maxs ({maxs.X:F2} {maxs.Y:F2} {maxs.Z:F2}) size ({size.X:F2} {size.Y:F2} {size.Z:F2})"; + } + + internal void DumpCollide(int environmentIndex) { + GetPosition(out Vector3 position, out QAngle angles); + Vector3 velocity = BoxToSource.Distance(BodyId.LinearVelocity); + Vector3 angularVelocity = BoxToSource.AngularImpulse(BodyId.AngularVelocity); + Msg($"[env {environmentIndex}] \"{Name}\" static {Static}, asleep {IsAsleep()}, material {physprops.GetPropName(MaterialIndex)} ({MaterialIndex})\n"); + Msg($" pos ({position.X:F2} {position.Y:F2} {position.Z:F2}) ang ({angles.X:F2} {angles.Y:F2} {angles.Z:F2})\n"); + Msg($" vel ({velocity.X:F2} {velocity.Y:F2} {velocity.Z:F2}) angvel ({angularVelocity.X:F2} {angularVelocity.Y:F2} {angularVelocity.Z:F2})\n"); + + if (!Static) { + MassData massData = BodyId.MassData; + Vector3 center = BoxToSource.Distance(massData.center); + Matrix3 inertia = massData.inertia; + Msg($" mass {massData.mass:F3} (game {CachedMass:F3}), local mass center ({center.X:F3} {center.Y:F3} {center.Z:F3})\n"); + Msg($" inertia ({inertia.cx.X:G4} {inertia.cx.Y:G4} {inertia.cx.Z:G4}) ({inertia.cy.X:G4} {inertia.cy.Y:G4} {inertia.cy.Z:G4}) ({inertia.cz.X:G4} {inertia.cz.Y:G4} {inertia.cz.Z:G4})\n"); + } + + if (Collide == null) { + Msg(SphereRadius > 0.0f ? $" sphere radius {SphereRadius:F2}\n" : " no collide\n"); + return; + } + + Vector3 collideCenter = Collide.MassCenter; + Msg($" collide: {Collide.Convexes.Count} convexes, mesh {(Collide.Mesh.IsNull ? "none" : $"{Collide.Mesh.Triangles.Length} tris")}, authored mass center ({collideCenter.X:F3} {collideCenter.Y:F3} {collideCenter.Z:F3})\n"); + for (int i = 0; i < Collide.Convexes.Count; i++) { + BoxPhysConvex convex = Collide.Convexes[i]; + Msg($" convex {i}: gamedata {convex.GameData}, ivp triangles {convex.QueryMaterials?.Length ?? 0}\n"); + Msg($" hull {HullInfo(convex.Hull)}\n"); + if (!Static) + Msg($" sim hull {HullInfo(convex.GetSimHull())}\n"); + } + } + internal static int ConvexMaterialIndex(BoxPhysConvex convex, int materialIndex) { byte[]? materials = convex.QueryMaterials; Vector3[]? verts = convex.QueryVerts;