From 10de9f62dd42873f1e53216aa8731b611640271d Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 11:09:21 +0000 Subject: [PATCH 01/19] Render runtime decals on modular objects A runtime EveSpaceObjectDecal (no static index buffers) builds its index buffer by testing the parent mesh's triangles against the decal volume. A modular object (EveStation2 from CreateModularObject + AddHull) has no mesh of its own, so PushChildrenAndDecalRenderables skipped its decals and nothing rendered. When the parent has no mesh, gather the part geometries with CollectOwnedGeometry and project each decal onto every part whose bounds its volume touches. Each part gets its own index buffer, built on the CPU with the decal volume moved into part space, and its own per-object data (part world transform and part-space decal matrices). The buffers are owned by the decal rather than cached on the shared mesh data, since a hull geometry is shared between parts and runtime decals come and go. They are rebuilt when the decal or a part moves. A part's LOD follows its share of the object's screen size, as the instanced mesh manager does. Unlike the single mesh path this is not gated on buildDecalBuffers: modular objects have no precomputed decal buffers, so building them is the only way to show the decal. The triangle gather moves out of CreateDecalIndexBuffers into BuildDecalGeometry and the batch setup into CommitBatch, shared by both paths. GetDecalPrimitiveCounts dereferenced m_baseGeometryResource when the decal had no geometry, which access-violated for a decal on a meshless model or with no parent. It now returns an empty list there, and for a modular parent returns per-LOD counts summed over the parts. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 379 ++++++++++++------ .../Attachments/EveSpaceObjectDecal.h | 39 ++ trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 18 + 3 files changed, 317 insertions(+), 119 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 52e288c8d..f23c2f418 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -14,6 +14,7 @@ #include "TriFrustum.h" #include "Tr2InstancedMesh.h" #include "TriSettingsRegistrar.h" +#include "Eve/SpaceObject/Children/EveSpaceObjectChild.h" CCP_STATS_DECLARED_ELSEWHERE( primitiveCount ); @@ -49,7 +50,8 @@ EveSpaceObjectDecal::EveSpaceObjectDecal( IRoot* lockobj ) : m_instanceData( nullptr ), m_minBounds( 0, 0, 0 ), m_maxBounds( 0, 0, 0 ), - m_isGeometryFrozen( false ) + m_isGeometryFrozen( false ), + m_usePartTargets( false ) { // init PrepareResources(); @@ -94,6 +96,8 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) { m_decalGeometry = nullptr; } + // the part targets cache the decal volume in part space + m_partTargets.clear(); } return true; } @@ -111,6 +115,13 @@ bool EveSpaceObjectDecal::OnPrepareResources() { m_decalGeometry = nullptr; } + for( auto& target : m_partTargets ) + { + if( target.decalGeometry && !target.decalGeometry->m_indexBuffer.IsValid() ) + { + target.decalGeometry = nullptr; + } + } return true; } @@ -181,6 +192,12 @@ void EveSpaceObjectDecal::UpdateVisibility( const EveUpdateContext& updateContex // ------------------------------------------------------------------------------------------------------ void EveSpaceObjectDecal::GetRenderables( std::vector& renderables, DecalMeshCache& meshCache, TriGeometryRes* geomRes, float screensize ) { + if( m_usePartTargets ) + { + m_usePartTargets = false; + m_partTargets.clear(); + } + if( m_isVisible <= 0 || !geomRes ) { return; @@ -224,6 +241,111 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab renderables.push_back( this ); } +void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, DecalMeshCacheMap& meshCaches, const std::vector& parts, float objectScreenSize, float objectRadius ) +{ + if( !m_usePartTargets ) + { + // switching from a single mesh parent: drop anything tied to that mesh + m_usePartTargets = true; + m_decalGeometry = nullptr; + m_baseGeometryResource = nullptr; + m_instanceData = nullptr; + m_vertexDeclarationOverride = Tr2EffectStateManager::UNINITIALIZED_DECLARATION; + } + + if( m_isVisible <= 0 ) + { + return; + } + + for( auto& target : m_partTargets ) + { + target.seen = false; + } + + for( const auto& part : parts ) + { + TriGeometryRes* geometry = part.geometry; + if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) + { + continue; + } + TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); + if( !meshData ) + { + continue; + } + + auto found = std::find_if( m_partTargets.begin(), m_partTargets.end(), [&]( const PartTarget& target ) { + return !target.seen && target.geometry == geometry && target.childToObject == part.childToObject; + } ); + if( found == m_partTargets.end() ) + { + PartTarget target; + target.geometry = geometry; + target.childToObject = part.childToObject; + // part vertices are in part space; the decal volume lives in object space + target.decalMatrix = m_decalMatrix * Inverse( part.childToObject ); + target.inverseDecalMatrix = Inverse( target.decalMatrix ); + + // cheap reject: does the decal volume touch the part's bounds at all? + Vector3 decalMin( -1.f, -1.f, -1.f ); + Vector3 decalMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( decalMin, decalMax, target.decalMatrix ); + target.overlaps = decalMin.x <= meshData->m_maxBounds.x && decalMax.x >= meshData->m_minBounds.x && + decalMin.y <= meshData->m_maxBounds.y && decalMax.y >= meshData->m_minBounds.y && + decalMin.z <= meshData->m_maxBounds.z && decalMax.z >= meshData->m_minBounds.z; + + // the instanced mesh manager picks a part's LOD from the part's own bounding sphere + if( objectRadius > 0.f ) + { + const Matrix& m = part.childToObject; + float scale = std::max( { Length( Vector3( m._11, m._12, m._13 ) ), + Length( Vector3( m._21, m._22, m._23 ) ), + Length( Vector3( m._31, m._32, m._33 ) ) } ); + target.screenSizeScale = meshData->m_boundingSphere.w * scale / objectRadius; + } + m_partTargets.push_back( std::move( target ) ); + found = m_partTargets.end() - 1; + } + found->seen = true; + + if( !found->overlaps ) + { + continue; + } + + if( !found->decalGeometry || found->decalGeometry->m_lodMask != meshData->m_lodMask ) + { + found->decalGeometry = BuildDecalGeometry( meshData, meshCaches[geometry], found->decalMatrix, found->inverseDecalMatrix ); + } + } + + m_partTargets.erase( std::remove_if( m_partTargets.begin(), m_partTargets.end(), []( const PartTarget& target ) { return !target.seen; } ), m_partTargets.end() ); + + bool anyVisible = false; + for( auto& target : m_partTargets ) + { + target.lodIndex = -1; + if( !target.decalGeometry || !target.decalGeometry->m_indexBuffer.IsValid() ) + { + continue; + } + int lodIndex = m_isGeometryFrozen ? 0 : target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize * target.screenSizeScale ); + if( lodIndex < 0 || lodIndex >= int( target.decalGeometry->m_lods.size() ) || !target.decalGeometry->m_lods[lodIndex].m_primitiveCount ) + { + continue; + } + target.lodIndex = lodIndex; + anyVisible = true; + } + + if( anyVisible ) + { + renderables.push_back( this ); + } +} + void EveSpaceObjectDecal::GetInstancedRenderables( std::vector& renderables, DecalMeshCache& meshCache, const Tr2InstancedMesh* instancedMesh, float instanceScreenSize ) { GetRenderables( renderables, meshCache, instancedMesh->GetGeometryResource(), instanceScreenSize ); @@ -257,12 +379,37 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, return; } - if( !m_baseGeometryResource || !m_decalEffect ) + if( !m_decalEffect || !m_display ) { return; } - if( !m_display ) + if( m_usePartTargets ) + { + for( const auto& target : m_partTargets ) + { + if( target.lodIndex < 0 || !target.decalGeometry || !target.decalGeometry->m_indexBuffer.IsValid() || !target.geometry->IsGood() ) + { + continue; + } + const TriGeometryResLodData* lod = target.geometry->GetMeshLod( 0, target.lodIndex ); + if( !lod || !lod->m_allocationsValid ) + { + continue; + } + auto partData = batches->Allocate(); + if( !partData ) + { + return; + } + // draw the part's vertices with the part's world transform and the decal volume in part space + FillPerObjectData( *partData, target.childToObject * m_parentData.transform, target.decalMatrix, target.inverseDecalMatrix, IdentityMatrix() ); + CommitBatch( batches, lod, *target.decalGeometry, target.lodIndex, partData ); + } + return; + } + + if( !m_baseGeometryResource ) { return; } @@ -292,11 +439,16 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, return; } + CommitBatch( batches, lod, *m_decalGeometry, m_geometryLodIndex, perObjectData ); +} + +void EveSpaceObjectDecal::CommitBatch( ITriRenderBatchAccumulator* batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ) +{ Tr2RenderBatch batch; batch.SetPriority( m_priority ); batch.SetMaterial( m_decalEffect ); auto declaration = m_vertexDeclarationOverride != Tr2EffectStateManager::UNINITIALIZED_DECLARATION ? m_vertexDeclarationOverride : lod->m_mesh->m_vertexDeclarationHandle; - batch.SetGeometry( declaration, lod->m_vertexAllocation, m_decalGeometry->m_indexBuffer ); + batch.SetGeometry( declaration, lod->m_vertexAllocation, decalGeometry.m_indexBuffer ); batch.SetPerObjectData( perObjectData ); @@ -304,9 +456,9 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, { ITr2InstanceData::InstanceData data = m_instanceData->GetInstanceData( 0, std::numeric_limits::max() ); batch.SetDrawIndexedInstanced( - m_decalGeometry->m_lods[m_geometryLodIndex].m_primitiveCount * 3, + decalGeometry.m_lods[lodIndex].m_primitiveCount * 3, data.count, - m_decalGeometry->m_indexBuffer.GetStartIndex() + m_decalGeometry->m_lods[m_geometryLodIndex].m_startIndex, + decalGeometry.m_indexBuffer.GetStartIndex() + decalGeometry.m_lods[lodIndex].m_startIndex, lod->m_vertexAllocation.GetOffset() / lod->m_vertexAllocation.GetStride(), data.offset / data.stride ); batch.m_vertexStreams[1] = &data.buffer; @@ -315,9 +467,9 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, else { batch.SetDrawIndexedInstanced( - m_decalGeometry->m_lods[m_geometryLodIndex].m_primitiveCount * 3, + decalGeometry.m_lods[lodIndex].m_primitiveCount * 3, 1, - m_decalGeometry->m_indexBuffer.GetStartIndex() + m_decalGeometry->m_lods[m_geometryLodIndex].m_startIndex, + decalGeometry.m_indexBuffer.GetStartIndex() + decalGeometry.m_lods[lodIndex].m_startIndex, lod->m_vertexAllocation.GetOffset() / lod->m_vertexAllocation.GetStride(), 0 ); } @@ -352,37 +504,41 @@ Tr2PerObjectData* EveSpaceObjectDecal::GetPerObjectData( ITriRenderBatchAccumula return NULL; } + FillPerObjectData( *perObjectData, m_parentData.transform, m_decalMatrix, m_inverseDecalMatrix, m_parentBoneMatrix ); + return perObjectData; +} + +void EveSpaceObjectDecal::FillPerObjectData( EveDecalPerObjectData& data, const Matrix& worldMatrix, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix, const Matrix& parentBoneMatrix ) const +{ // world matrix - perObjectData->m_vsData.m_worldMatrix = Transpose( m_parentData.transform ); + data.m_vsData.m_worldMatrix = Transpose( worldMatrix ); // inv world matrix - perObjectData->m_vsData.m_invWorldMatrix = Inverse( perObjectData->m_vsData.m_worldMatrix ); + data.m_vsData.m_invWorldMatrix = Inverse( data.m_vsData.m_worldMatrix ); // decal matrix (both nrm and inv) - perObjectData->m_vsData.m_decalMatrix = Transpose( m_decalMatrix ); - perObjectData->m_vsData.m_inverseDecalMatrix = Transpose( m_inverseDecalMatrix ); + data.m_vsData.m_decalMatrix = Transpose( decalMatrix ); + data.m_vsData.m_inverseDecalMatrix = Transpose( inverseDecalMatrix ); // matrix from possible bone animation of parent - perObjectData->m_vsData.m_parentBoneMatrix = Transpose( m_parentBoneMatrix ); - perObjectData->m_vsData.m_invParentBoneMatrix = Inverse( Transpose( m_parentBoneMatrix ) ); + data.m_vsData.m_parentBoneMatrix = Transpose( parentBoneMatrix ); + data.m_vsData.m_invParentBoneMatrix = Inverse( Transpose( parentBoneMatrix ) ); // clip sphere data from parent - perObjectData->m_psData.m_shipData = m_parentData.shipData; - perObjectData->m_psData.m_clipData = Vector4( m_parentData.clipSphereCenter, m_parentData.clipRadiusSq ); - perObjectData->m_psData.m_clipRadius2Sq = m_parentData.clipRadius2Sq; + data.m_psData.m_shipData = m_parentData.shipData; + data.m_psData.m_clipData = Vector4( m_parentData.clipSphereCenter, m_parentData.clipRadiusSq ); + data.m_psData.m_clipRadius2Sq = m_parentData.clipRadius2Sq; // display data - perObjectData->m_psData.m_displayData = Vector4( (float)m_parentData.killCount, m_isVisible, 0.f, 0.f ); + data.m_psData.m_displayData = Vector4( (float)m_parentData.killCount, m_isVisible, 0.f, 0.f ); if( m_parentData.shLighting ) { - memcpy( perObjectData->m_psData.m_shLightingCoefficients, m_parentData.shLighting, sizeof( perObjectData->m_psData.m_shLightingCoefficients ) ); + memcpy( data.m_psData.m_shLightingCoefficients, m_parentData.shLighting, sizeof( data.m_psData.m_shLightingCoefficients ) ); } else { - memset( perObjectData->m_psData.m_shLightingCoefficients, 0, sizeof( perObjectData->m_psData.m_shLightingCoefficients ) ); + memset( data.m_psData.m_shLightingCoefficients, 0, sizeof( data.m_psData.m_shLightingCoefficients ) ); } - - return perObjectData; } void EveSpaceObjectDecal::CopyFrom( EveSpaceObjectDecal* object ) @@ -593,8 +749,6 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { TRINITY_STATS_ZONE( __FUNCTION__ ); - USE_MAIN_THREAD_RENDER_CONTEXT(); - // is loaded and good? if( !geomRes ) { @@ -613,8 +767,6 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De m_decalGeometry = nullptr; - std::vector allIndices; - TriGeometryResMeshData* meshData = geomRes->GetMeshData( 0 ); if( !meshData ) @@ -631,17 +783,51 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De } } + auto newDecal = BuildDecalGeometry( meshData, meshCache, m_decalMatrix, m_inverseDecalMatrix ); + if( !newDecal ) + { + return; + } + + meshData->m_decals.push_back( newDecal ); + m_decalGeometry = newDecal; +} + +// ------------------------------------------------------------------------------------------------------ +std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometry( TriGeometryResMeshData* meshData, DecalMeshCache& meshCache, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ) +{ + TRINITY_STATS_ZONE( __FUNCTION__ ); + + USE_MAIN_THREAD_RENDER_CONTEXT(); + + std::vector allIndices; + std::shared_ptr newDecal = std::make_shared(); - newDecal->m_inverseDecalMatrix = m_inverseDecalMatrix; + newDecal->m_inverseDecalMatrix = inverseDecalMatrix; newDecal->m_lodMask = meshData->m_lodMask; + // is vertex compressed to 16bit floats? + bool vertexPositionCompressed = false; + Tr2VertexDefinition vd; + if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) + { + if( auto pos = vd.Find( vd.POSITION ) ) + { + vertexPositionCompressed = pos->m_dataType == vd.FLOAT16_4; + } + } + + Vector3 aabbMin( -1.f, -1.f, -1.f ); + Vector3 aabbMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); + for( int i = 0; i < static_cast( meshData->m_lods.size() ); i++ ) { TriGeometryResLodData* lod = meshData->m_lods[i].get(); if( !lod->m_allocationsValid ) { - return; + return nullptr; } // lock existing buffers, we do this only once and it is managed, so this call is ok @@ -660,7 +846,7 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( FAILED( lod->m_vertexAllocation.MapForReading( originalVertices, renderContext ) ) ) { - return; + return nullptr; } } ON_BLOCK_EXIT( [&] { if( readingBuffers ) lod->m_vertexAllocation.UnmapForReading( renderContext ); } ); @@ -669,7 +855,7 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( FAILED( lod->m_indexAllocation.MapForReading( originalIndices, renderContext ) ) ) { - return; + return nullptr; } } ON_BLOCK_EXIT( [&] { if( readingBuffers ) lod->m_indexAllocation.UnmapForReading( renderContext ); } ); @@ -687,34 +873,10 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De // correct source pointers const unsigned int* indices32 = reinterpret_cast( originalIndices ); const unsigned short* indices16 = reinterpret_cast( originalIndices ); - // collect indices for decal geometry - std::vector decalIndices32; - std::vector decalIndices16; bool is16bit = lod->m_indexAllocation.GetStride() == 2; - if( is16bit ) - { - decalIndices16.reserve( lod->m_primitiveCount * 3 ); - } - else - { - decalIndices32.reserve( lod->m_primitiveCount * 3 ); - } - - // is vertex compressed to 16bit floats? - bool vertexPositionCompressed = false; - Tr2VertexDefinition vd; - if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) - { - if( auto pos = vd.Find( vd.POSITION ) ) - { - vertexPositionCompressed = pos->m_dataType == vd.FLOAT16_4; - } - } - - Vector3 aabbMin( -1.f, -1.f, -1.f ); - Vector3 aabbMax( 1.f, 1.f, 1.f ); - BoundingBoxTransform( aabbMin, aabbMax, m_decalMatrix ); + MeshDecalLodData buffer; + buffer.m_startIndex = uint32_t( allIndices.size() ); for( unsigned int t = 0; t < lod->m_primitiveCount; ++t ) { @@ -722,76 +884,35 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De unsigned int index0 = is16bit ? indices16[0] : indices32[0]; unsigned int index1 = is16bit ? indices16[1] : indices32[1]; unsigned int index2 = is16bit ? indices16[2] : indices32[2]; + // next! + indices16 += 3; + indices32 += 3; + // do real collision detection here + Vector3 pos[3]; if( vertexPositionCompressed ) { - Vector3 pos[3]; pos[0] = *reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); pos[1] = *reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); pos[2] = *reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); - if( IntersectTriangleAABB( pos, pos + 1, pos + 2, aabbMin, aabbMax ) ) - { - if( IntersectTriangleOrientedBox( pos, pos + 1, pos + 2, m_inverseDecalMatrix ) ) - { - if( is16bit ) - { - decalIndices16.push_back( index0 ); - decalIndices16.push_back( index1 ); - decalIndices16.push_back( index2 ); - } - else - { - decalIndices32.push_back( index0 ); - decalIndices32.push_back( index1 ); - decalIndices32.push_back( index2 ); - } - } - } } else { - const Vector3* v0 = reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); - const Vector3* v1 = reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); - const Vector3* v2 = reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); - - if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) ) - { - if( IntersectTriangleOrientedBox( v0, v1, v2, m_inverseDecalMatrix ) ) - { - if( is16bit ) - { - decalIndices16.push_back( index0 ); - decalIndices16.push_back( index1 ); - decalIndices16.push_back( index2 ); - } - else - { - decalIndices32.push_back( index0 ); - decalIndices32.push_back( index1 ); - decalIndices32.push_back( index2 ); - } - } - } + pos[0] = *reinterpret_cast( originalVertices + index0 * meshData->m_bytesPerVertex ); + pos[1] = *reinterpret_cast( originalVertices + index1 * meshData->m_bytesPerVertex ); + pos[2] = *reinterpret_cast( originalVertices + index2 * meshData->m_bytesPerVertex ); + } + if( IntersectTriangleAABB( pos, pos + 1, pos + 2, aabbMin, aabbMax ) && + IntersectTriangleOrientedBox( pos, pos + 1, pos + 2, inverseDecalMatrix ) ) + { + allIndices.push_back( index0 ); + allIndices.push_back( index1 ); + allIndices.push_back( index2 ); } - // next! - indices16 += 3; - indices32 += 3; - } - - // primitive count and index size - MeshDecalLodData buffer; - buffer.m_startIndex = uint32_t( allIndices.size() ); - if( is16bit ) - { - buffer.m_primitiveCount = unsigned( decalIndices16.size() / 3 ); - allIndices.insert( end( allIndices ), begin( decalIndices16 ), end( decalIndices16 ) ); - } - else - { - buffer.m_primitiveCount = unsigned( decalIndices32.size() / 3 ); - allIndices.insert( end( allIndices ), begin( decalIndices32 ), end( decalIndices32 ) ); } + // primitive count; the decal index buffer is always 32 bit + buffer.m_primitiveCount = ( uint32_t( allIndices.size() ) - buffer.m_startIndex ) / 3; newDecal->m_lods.push_back( buffer ); } @@ -800,12 +921,11 @@ void EveSpaceObjectDecal::CreateDecalIndexBuffers( TriGeometryResPtr geomRes, De { if( !SUCCEEDED( g_sharedBuffer.Allocate( 4, uint32_t( allIndices.size() ), allIndices.data(), renderContext, newDecal->m_indexBuffer ) ) ) { - return; + return nullptr; } } - meshData->m_decals.push_back( newDecal ); - m_decalGeometry = newDecal; + return newDecal; } void EveSpaceObjectDecal::SetIndices( const std::vector>& indices ) @@ -928,15 +1048,36 @@ void EveSpaceObjectDecal::GetPickingBatches( ITriRenderBatchAccumulator* batches std::vector EveSpaceObjectDecal::GetDecalPrimitiveCounts() const { std::vector counts; - if( m_decalGeometry ) + if( m_usePartTargets ) + { + // per LOD, summed over all the parts the decal projects onto + for( const auto& target : m_partTargets ) + { + if( !target.decalGeometry ) + { + continue; + } + const auto& lods = target.decalGeometry->m_lods; + if( counts.size() < lods.size() ) + { + counts.resize( lods.size(), 0 ); + } + for( size_t i = 0; i < lods.size(); ++i ) + { + counts[i] += lods[i].m_primitiveCount; + } + } + } + else if( m_decalGeometry ) { for( auto& buffer : m_decalGeometry->m_lods ) { counts.push_back( buffer.m_primitiveCount ); } } - else + else if( m_baseGeometryResource ) { + // no geometry yet: report what the static index buffers hold TriGeometryResMeshData* meshData = m_baseGeometryResource->GetMeshData( 0 ); if( meshData ) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 6de349978..ec844fea1 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -14,6 +14,7 @@ #include "Eve/IEveSpaceObject2.h" #include "Eve/EveUpdateContext.h" #include "../../../Resources/TriGeometryRes.h" +#include BLUE_DECLARE_INTERFACE( ITr2InstanceData ); BLUE_DECLARE( Tr2Buffer ); @@ -72,6 +73,11 @@ struct DecalMeshCache std::vector buffers; }; +// CPU copies of the vertex/index buffers of each hull geometry, shared by all decals of an object within a frame +using DecalMeshCacheMap = std::unordered_map; + +struct EveChildGeometry; + // -------------------------------------------------------------------------------- // Description: // ToDo @@ -130,6 +136,15 @@ BLUE_CLASS( EveSpaceObjectDecal ) : void UpdateVisibility( const EveUpdateContext& updateContext, const IEveSpaceObject2::ParentData* parentData ); void GetRenderables( std::vector & renderables, DecalMeshCache & meshCache, TriGeometryRes * geomRes, float screensize ); void GetInstancedRenderables( std::vector & renderables, DecalMeshCache & meshCache, const Tr2InstancedMesh* instancedMesh, float instanceScreenSize = std::numeric_limits::max() ); + /** + * @brief Gathers the decal for a parent without a mesh of its own (a modular object), projecting it onto + * every part geometry the decal volume overlaps. Index buffers are built on the CPU from the parts' + * vertices and owned by this decal; they are rebuilt when the decal or a part moves. + * @param parts Part geometries of the parent, in the parent's object space (EveSpaceObjectChild::CollectOwnedGeometry). + * @param objectScreenSize Screen size of the whole parent, used to pick a LOD per part. + * @param objectRadius Bounding sphere radius of the whole parent in object space. + */ + void GetModularRenderables( std::vector & renderables, DecalMeshCacheMap & meshCaches, const std::vector& parts, float objectScreenSize, float objectRadius ); // access position etc. const Vector3& GetPosition() const; @@ -161,6 +176,11 @@ BLUE_CLASS( EveSpaceObjectDecal ) : private: // create void CreateDecalIndexBuffers( TriGeometryResPtr geomRes, DecalMeshCache & meshCache ); + // Collects the triangles of every LOD of meshData that intersect the decal volume. Returns null if the + // mesh buffers are not ready yet. inverseDecalMatrix maps the mesh's vertex space into decal space. + static std::shared_ptr BuildDecalGeometry( TriGeometryResMeshData * meshData, DecalMeshCache & meshCache, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ); + void FillPerObjectData( EveDecalPerObjectData & data, const Matrix& worldMatrix, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix, const Matrix& parentBoneMatrix ) const; + void CommitBatch( ITriRenderBatchAccumulator * batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ); // update void UpdateDecalMatrix(); void CreateStaticIndexBuffers( TriGeometryResPtr geomRes ); @@ -216,6 +236,25 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // the geometry can be frozen bool m_isGeometryFrozen; + + // A part of a modular parent that the decal may project onto + struct PartTarget + { + TriGeometryResPtr geometry; + Matrix childToObject; + // the decal volume expressed in the part's vertex space + Matrix decalMatrix; + Matrix inverseDecalMatrix; + // owned here rather than cached on the (shared) mesh data: runtime decals come and go + std::shared_ptr decalGeometry; + float screenSizeScale = 1.f; + int lodIndex = -1; + bool overlaps = false; + bool seen = false; + }; + std::vector m_partTargets; + // true when the parent has no mesh and the decal renders through m_partTargets + bool m_usePartTargets; }; TYPEDEF_BLUECLASS( EveSpaceObjectDecal ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index f046b8701..ff3e5567c 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -1592,6 +1592,24 @@ void EveSpaceObject2::PushChildrenAndDecalRenderables( std::vector parts; + std::vector areas; + for( auto& child : m_effectChildren ) + { + child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); + } + if( !parts.empty() ) + { + DecalMeshCacheMap meshCaches; + for( auto it = m_decals.begin(); it != m_decals.end(); ++it ) + { + ( *it )->GetModularRenderables( renderables, meshCaches, parts, m_meshScreenSize, m_boundingSphereRadius ); + } + } + } } void EveSpaceObject2::UpdateVisibility( const EveUpdateContext& updateContext, const Matrix& parentTransform ) From a7a5d17c532d2a34ff6d0b9f07227681e4437cc2 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 11:37:26 +0000 Subject: [PATCH 02/19] Let runtime decals build their geometry in the client A decal without static index buffers only builds its geometry when the buildDecalBuffers setting is on, and the client enables it only in content mode. Runtime decals on ordinary meshes (collision scratches on level geometry) therefore never showed in the game. Add a persisted dynamicIndexBuffers attribute. A decal with it set builds its geometry whatever buildDecalBuffers says, and owns the buffer instead of adding it to the mesh's shared decal cache, which only grows and would collect one entry per scratch. Decals without the attribute, including SOF decals that miss their baked buffers, behave as before. BuildDecalGeometry now skips the buffer readback when the decal volume is outside the mesh bounds. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 23 +++++++++++++++---- .../Attachments/EveSpaceObjectDecal.h | 4 ++++ .../Attachments/EveSpaceObjectDecal_Blue.cpp | 6 +++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index f23c2f418..98c208ca2 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -51,6 +51,7 @@ EveSpaceObjectDecal::EveSpaceObjectDecal( IRoot* lockobj ) : m_minBounds( 0, 0, 0 ), m_maxBounds( 0, 0, 0 ), m_isGeometryFrozen( false ), + m_dynamicIndexBuffers( false ), m_usePartTargets( false ) { // init @@ -218,6 +219,11 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab { CreateStaticIndexBuffers( geomRes ); } + else if( m_dynamicIndexBuffers ) + { + // runtime decal: owned here, never added to the mesh's shared decal cache (that cache only grows) + m_decalGeometry = mesh && geomRes->IsGood() ? BuildDecalGeometry( mesh, meshCache, m_decalMatrix, m_inverseDecalMatrix ) : nullptr; + } else if( g_buildDecalBuffers ) { CreateDecalIndexBuffers( geomRes, meshCache ); @@ -806,6 +812,19 @@ std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometry( TriGeome newDecal->m_inverseDecalMatrix = inverseDecalMatrix; newDecal->m_lodMask = meshData->m_lodMask; + Vector3 aabbMin( -1.f, -1.f, -1.f ); + Vector3 aabbMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); + + // a decal volume outside the mesh bounds hits nothing: skip reading the buffers back + if( aabbMin.x > meshData->m_maxBounds.x || aabbMax.x < meshData->m_minBounds.x || + aabbMin.y > meshData->m_maxBounds.y || aabbMax.y < meshData->m_minBounds.y || + aabbMin.z > meshData->m_maxBounds.z || aabbMax.z < meshData->m_minBounds.z ) + { + newDecal->m_lods.resize( meshData->m_lods.size() ); + return newDecal; + } + // is vertex compressed to 16bit floats? bool vertexPositionCompressed = false; Tr2VertexDefinition vd; @@ -817,10 +836,6 @@ std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometry( TriGeome } } - Vector3 aabbMin( -1.f, -1.f, -1.f ); - Vector3 aabbMax( 1.f, 1.f, 1.f ); - BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); - for( int i = 0; i < static_cast( meshData->m_lods.size() ); i++ ) { TriGeometryResLodData* lod = meshData->m_lods[i].get(); diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index ec844fea1..43c5f55a7 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -237,6 +237,10 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // the geometry can be frozen bool m_isGeometryFrozen; + // build the index buffer at runtime even when g_buildDecalBuffers is off; the buffer is then owned by + // this decal instead of being cached on the mesh + bool m_dynamicIndexBuffers; + // A part of a modular parent that the decal may project onto struct PartTarget { diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp index 945c4c9b6..5c36c014e 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp @@ -26,6 +26,12 @@ const Be::ClassInfo* EveSpaceObjectDecal::ExposeToBlue() MAP_ATTRIBUTE( "minScreenSize", m_minScreenSize, "min size on screen in pixels before the decal is LODed out", Be::READWRITE | Be::PERSIST ) MAP_ATTRIBUTE( "decalEffect", m_decalEffect, "The effect used to draw the decal", Be::READWRITE | Be::PERSIST ) + MAP_ATTRIBUTE( + "dynamicIndexBuffers", + m_dynamicIndexBuffers, + "Build the decal geometry from the parent mesh at runtime, whatever the buildDecalBuffers setting says. " + "For runtime decals (impacts, scratches) that have no baked index buffers; ignored when static index buffers are set.", + Be::READWRITE | Be::PERSIST ) MAP_ATTRIBUTE( "batchType", m_batchType, "Batch type (render pass) used to render the decal", Be::READ ) From 5a59f6a67a1e7a5932339759335c6bd513a10672 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 12:07:27 +0000 Subject: [PATCH 03/19] Cache mesh triangles for runtime decal builds A runtime decal read every LOD of its mesh back from the GPU and tested every triangle, about 120 ms per decal on a 3.66 M triangle level mesh. The first runtime build against a mesh now copies its buffers back once (main thread) and hands them to a worker thread that converts them and buckets the triangles of each LOD into a hierarchical loose grid: each triangle is stored once, in the cell of its centre on the finest level whose cells fit it, with the index list reordered by cell. Later builds only test the triangles in the cells around the decal box. Until the worker finishes, the build returns nothing and the decal tries again on a later frame. The cache (DecalTriangleCache) hangs off TriGeometryResMeshData, so it is freed with the mesh data on release, re-initialization and reload, and is rebuilt if the mesh's LOD set changes. The worker owns its copies, so releasing the mesh mid-build is safe. Both runtime paths use it: decals with dynamicIndexBuffers and decals on modular objects (which no longer need the per-frame DecalMeshCacheMap). Decals built through buildDecalBuffers keep the old full scan and the shared mesh cache. Co-Authored-By: Claude Opus 5.5 --- trinity/CMakeLists.txt | 2 + .../Attachments/EveDecalTriangleCache.cpp | 298 ++++++++++++++++++ .../Attachments/EveDecalTriangleCache.h | 62 ++++ .../Attachments/EveSpaceObjectDecal.cpp | 56 +++- .../Attachments/EveSpaceObjectDecal.h | 13 +- trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 3 +- trinity/Resources/TriGeometryRes.h | 3 + 7 files changed, 425 insertions(+), 12 deletions(-) create mode 100644 trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp create mode 100644 trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h diff --git a/trinity/CMakeLists.txt b/trinity/CMakeLists.txt index 749f5c35c..9c238506b 100644 --- a/trinity/CMakeLists.txt +++ b/trinity/CMakeLists.txt @@ -315,6 +315,8 @@ set(_SOURCES Eve/SpaceObject/Attachments/EveMeshOverlayEffect.cpp Eve/SpaceObject/Attachments/EveMeshOverlayEffect.h Eve/SpaceObject/Attachments/EveMeshOverlayEffect_Blue.cpp + Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp + Eve/SpaceObject/Attachments/EveDecalTriangleCache.h Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp new file mode 100644 index 000000000..2408d311a --- /dev/null +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -0,0 +1,298 @@ +// Copyright © 2026 CCP ehf. + +#include "StdAfx.h" +#include "EveDecalTriangleCache.h" +#include "Utilities/BoundingBox.h" +#include "Shader/Tr2EffectStateManager.h" +#include + +namespace +{ +// average number of triangles per cell the finest grid level aims for +constexpr float TRIANGLES_PER_CELL = 4.f; +constexpr uint32_t MAX_CELLS_PER_AXIS = 256; +constexpr float MAX_CELLS = float( 1u << 21 ); + +// Raw copy of one LOD's buffers, taken on the main thread and converted on the worker +struct RawLod +{ + std::vector vertices; + std::vector indices; + uint32_t vertexCount = 0; + uint32_t indexStride = 4; + uint32_t primitiveCount = 0; +}; + +// Reads one LOD back from the GPU. Returns false if the buffers can't be read. +bool CopyLod( const TriGeometryResMeshData& meshData, TriGeometryResLodData& lod, RawLod& out ) +{ + USE_MAIN_THREAD_RENDER_CONTEXT(); + + const unsigned char* vertices = nullptr; + const unsigned char* indices = nullptr; + if( FAILED( lod.m_vertexAllocation.MapForReading( vertices, renderContext ) ) ) + { + return false; + } + ON_BLOCK_EXIT( [&] { lod.m_vertexAllocation.UnmapForReading( renderContext ); } ); + if( FAILED( lod.m_indexAllocation.MapForReading( indices, renderContext ) ) ) + { + return false; + } + ON_BLOCK_EXIT( [&] { lod.m_indexAllocation.UnmapForReading( renderContext ); } ); + + out.vertexCount = meshData.m_bytesPerVertex ? std::min( lod.m_vertexCount, lod.m_vertexAllocation.GetSize() / meshData.m_bytesPerVertex ) : 0; + out.indexStride = lod.m_indexAllocation.GetStride() == 2 ? 2 : 4; + out.primitiveCount = std::min( lod.m_primitiveCount, lod.m_indexAllocation.GetSize() / ( out.indexStride * 3 ) ); + out.vertices.assign( vertices, vertices + size_t( out.vertexCount ) * meshData.m_bytesPerVertex ); + out.indices.assign( indices, indices + size_t( out.primitiveCount ) * 3 * out.indexStride ); + return true; +} + +void ConvertLod( const RawLod& raw, uint32_t bytesPerVertex, bool positionsCompressed, DecalTriangleCache::Lod& out ) +{ + out.positions.resize( raw.vertexCount ); + for( uint32_t v = 0; v < raw.vertexCount; ++v ) + { + const uint8_t* vertex = raw.vertices.data() + size_t( v ) * bytesPerVertex; + if( positionsCompressed ) + { + out.positions[v] = *reinterpret_cast( vertex ); + } + else + { + out.positions[v] = *reinterpret_cast( vertex ); + } + } + + const size_t indexCount = size_t( raw.primitiveCount ) * 3; + out.indices.resize( indexCount ); + for( size_t i = 0; i < indexCount; ++i ) + { + uint32_t index = raw.indexStride == 2 ? reinterpret_cast( raw.indices.data() )[i] : reinterpret_cast( raw.indices.data() )[i]; + out.indices[i] = index < raw.vertexCount ? index : 0; + } +} + +uint32_t CellCoordinate( float value, float origin, float invCellSize, uint32_t dim ) +{ + return uint32_t( std::clamp( ( value - origin ) * invCellSize, 0.f, float( dim - 1 ) ) ); +} + +void BuildGrid( DecalTriangleCache::Lod& lod ) +{ + const size_t triangleCount = lod.indices.size() / 3; + if( triangleCount == 0 || lod.positions.empty() ) + { + lod.levels.assign( 1, {} ); + lod.cellStart.assign( 2, 0 ); + return; + } + + Vector3 minBounds( FLT_MAX, FLT_MAX, FLT_MAX ); + Vector3 maxBounds( -FLT_MAX, -FLT_MAX, -FLT_MAX ); + for( const auto& p : lod.positions ) + { + minBounds = Minimize( minBounds, p ); + maxBounds = Maximize( maxBounds, p ); + } + + // finest level: cells proportional to the extents, aiming for TRIANGLES_PER_CELL triangles per cell; + // every coarser level halves the cell count per axis until one cell covers everything + Vector3 extents = maxBounds - minBounds; + float largest = std::max( { extents.x, extents.y, extents.z, 1e-6f } ); + const float e[3] = { std::max( extents.x, largest * 1e-3f ), std::max( extents.y, largest * 1e-3f ), std::max( extents.z, largest * 1e-3f ) }; + float targetCells = std::clamp( float( triangleCount ) / TRIANGLES_PER_CELL, 1.f, MAX_CELLS ); + float cellEdge = std::cbrt( e[0] * e[1] * e[2] / targetCells ); + uint32_t dims[3]; + for( int a = 0; a < 3; ++a ) + { + dims[a] = std::clamp( uint32_t( std::ceil( e[a] / cellEdge ) ), 1u, MAX_CELLS_PER_AXIS ); + } + lod.levels.clear(); + uint32_t totalCells = 0; + for( ;; ) + { + DecalTriangleCache::Level level; + level.origin = minBounds; + level.cellSize = Vector3( e[0] / dims[0], e[1] / dims[1], e[2] / dims[2] ); + level.invCellSize = Vector3( dims[0] / e[0], dims[1] / e[1], dims[2] / e[2] ); + std::copy( dims, dims + 3, level.dims ); + level.firstCell = totalCells; + totalCells += dims[0] * dims[1] * dims[2]; + lod.levels.push_back( level ); + if( dims[0] == 1 && dims[1] == 1 && dims[2] == 1 ) + { + break; + } + for( auto& d : dims ) + { + d = std::max( 1u, ( d + 1 ) / 2 ); + } + } + // the coarsest level is one cell: make sure it takes any triangle, including degenerate bounds + lod.levels.back().cellSize = Vector3( FLT_MAX, FLT_MAX, FLT_MAX ); + + // each triangle goes to the cell of its centre on the finest level whose cells it fits in + std::vector triangleCell( triangleCount ); + lod.cellStart.assign( size_t( totalCells ) + 1, 0 ); + for( size_t t = 0; t < triangleCount; ++t ) + { + const Vector3& a = lod.positions[lod.indices[t * 3 + 0]]; + const Vector3& b = lod.positions[lod.indices[t * 3 + 1]]; + const Vector3& c = lod.positions[lod.indices[t * 3 + 2]]; + Vector3 lo = Minimize( Minimize( a, b ), c ); + Vector3 hi = Maximize( Maximize( a, b ), c ); + Vector3 size = hi - lo; + Vector3 centre = ( lo + hi ) * 0.5f; + size_t l = 0; + while( size.x > lod.levels[l].cellSize.x || size.y > lod.levels[l].cellSize.y || size.z > lod.levels[l].cellSize.z ) + { + ++l; + } + const auto& level = lod.levels[l]; + uint32_t x = CellCoordinate( centre.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y = CellCoordinate( centre.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z = CellCoordinate( centre.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + uint32_t cell = level.firstCell + ( z * level.dims[1] + y ) * level.dims[0] + x; + triangleCell[t] = cell; + ++lod.cellStart[cell + 1]; + } + for( uint32_t c = 0; c < totalCells; ++c ) + { + lod.cellStart[c + 1] += lod.cellStart[c]; + } + + // counting sort the triangles by cell + std::vector sorted( lod.indices.size() ); + std::vector cursor( lod.cellStart.begin(), lod.cellStart.end() - 1 ); + for( size_t t = 0; t < triangleCount; ++t ) + { + uint32_t to = cursor[triangleCell[t]]++; + std::copy( &lod.indices[t * 3], &lod.indices[t * 3] + 3, &sorted[size_t( to ) * 3] ); + } + lod.indices.swap( sorted ); +} +} + +const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshData ) +{ + if( !meshData ) + { + return nullptr; + } + + auto& cache = meshData->m_decalTriangleCache; + if( cache && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) + { + return cache->ready.load( std::memory_order_acquire ) ? cache.get() : nullptr; + } + + TRINITY_STATS_ZONE( __FUNCTION__ ); + + for( auto& lod : meshData->m_lods ) + { + if( !lod->m_allocationsValid ) + { + return nullptr; + } + } + + bool positionsCompressed = false; + Tr2VertexDefinition vd; + if( Tr2EffectStateManager::GetVertexDeclarationElements( meshData->m_vertexDeclarationHandle, vd ) ) + { + if( auto pos = vd.Find( vd.POSITION ) ) + { + positionsCompressed = pos->m_dataType == vd.FLOAT16_4; + } + } + + std::vector raw( meshData->m_lods.size() ); + for( size_t i = 0; i < meshData->m_lods.size(); ++i ) + { + if( !CopyLod( *meshData, *meshData->m_lods[i], raw[i] ) ) + { + return nullptr; + } + } + + auto newCache = std::make_shared(); + newCache->lodMask = meshData->m_lodMask; + newCache->lods.resize( meshData->m_lods.size() ); + cache = newCache; + + // the worker only touches its own copies, so the mesh may be released while it runs + std::thread( [newCache, raw = std::move( raw ), bytesPerVertex = meshData->m_bytesPerVertex, positionsCompressed]() { + for( size_t i = 0; i < raw.size(); ++i ) + { + ConvertLod( raw[i], bytesPerVertex, positionsCompressed, newCache->lods[i] ); + BuildGrid( newCache->lods[i] ); + } + newCache->ready.store( true, std::memory_order_release ); + } ).detach(); + return nullptr; +} + +void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const +{ + if( lodIndex >= lods.size() ) + { + return; + } + const Lod& lod = lods[lodIndex]; + + for( const auto& level : lod.levels ) + { + // a triangle stored here is no larger than a cell, so its centre is within half a cell of the box + Vector3 margin = Minimize( level.cellSize * 0.5f, Vector3( 1e30f, 1e30f, 1e30f ) ); + Vector3 lo = aabbMin - margin; + Vector3 hi = aabbMax + margin; + uint32_t x0 = CellCoordinate( lo.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y0 = CellCoordinate( lo.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z0 = CellCoordinate( lo.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + uint32_t x1 = CellCoordinate( hi.x, level.origin.x, level.invCellSize.x, level.dims[0] ); + uint32_t y1 = CellCoordinate( hi.y, level.origin.y, level.invCellSize.y, level.dims[1] ); + uint32_t z1 = CellCoordinate( hi.z, level.origin.z, level.invCellSize.z, level.dims[2] ); + for( uint32_t z = z0; z <= z1; ++z ) + { + for( uint32_t y = y0; y <= y1; ++y ) + { + // cells x0..x1 of a row are contiguous, and so are their triangles + uint32_t row = level.firstCell + ( z * level.dims[1] + y ) * level.dims[0]; + for( uint32_t t = lod.cellStart[row + x0]; t < lod.cellStart[row + x1 + 1]; ++t ) + { + const uint32_t* tri = &lod.indices[size_t( t ) * 3]; + const Vector3* v0 = &lod.positions[tri[0]]; + const Vector3* v1 = &lod.positions[tri[1]]; + const Vector3* v2 = &lod.positions[tri[2]]; + // cheap bounds reject before the exact tests + if( std::max( { v0->x, v1->x, v2->x } ) < aabbMin.x || std::min( { v0->x, v1->x, v2->x } ) > aabbMax.x || + std::max( { v0->y, v1->y, v2->y } ) < aabbMin.y || std::min( { v0->y, v1->y, v2->y } ) > aabbMax.y || + std::max( { v0->z, v1->z, v2->z } ) < aabbMin.z || std::min( { v0->z, v1->z, v2->z } ) > aabbMax.z ) + { + continue; + } + if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) && IntersectTriangleOrientedBox( v0, v1, v2, inverseDecalMatrix ) ) + { + out.insert( out.end(), tri, tri + 3 ); + } + } + } + } + } +} + +size_t DecalTriangleCache::GetMemoryUsage() const +{ + size_t bytes = sizeof( *this ); + for( const auto& lod : lods ) + { + bytes += sizeof( lod ); + bytes += lod.positions.capacity() * sizeof( Vector3 ); + bytes += lod.indices.capacity() * sizeof( uint32_t ); + bytes += lod.levels.capacity() * sizeof( Level ); + bytes += lod.cellStart.capacity() * sizeof( uint32_t ); + } + return bytes; +} diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h new file mode 100644 index 000000000..03076b4bb --- /dev/null +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -0,0 +1,62 @@ +// Copyright © 2026 CCP ehf. + +#pragma once + +#include "../../../Resources/TriGeometryRes.h" +#include + +/** + * @brief CPU copy of a mesh's triangles, bucketed in a hierarchical loose grid per LOD, so that a runtime + * decal only tests the triangles near its volume instead of reading back and scanning the whole mesh. + * + * Each triangle is stored once, in the cell of its centre on the finest grid level whose cells are at + * least as large as the triangle; a query looks at every level with its box grown by half a cell there. + * + * The first runtime decal build against a mesh reads the mesh back from the GPU on the main thread and + * builds the grid on a worker thread; until that finishes, Get returns null and the decal tries again on a + * later frame. The cache is owned by the mesh's TriGeometryResMeshData, + * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on + * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. + */ +struct DecalTriangleCache +{ + struct Level + { + Vector3 origin = Vector3( 0.f, 0.f, 0.f ); + Vector3 cellSize = Vector3( 0.f, 0.f, 0.f ); + Vector3 invCellSize = Vector3( 0.f, 0.f, 0.f ); + uint32_t dims[3] = { 1, 1, 1 }; + // index of this level's first cell in Lod::cellStart + uint32_t firstCell = 0; + }; + + struct Lod + { + std::vector positions; + // 3 per triangle, the LOD's index buffer values, reordered so each cell's triangles are contiguous + std::vector indices; + std::vector levels; + // triangles cellStart[c] .. cellStart[c + 1] (in units of triangles) belong to cell c + std::vector cellStart; + }; + + uint32_t lodMask = 0; + std::vector lods; + // set by the worker thread once lods can be read + std::atomic ready = false; + + /** + * @brief Returns the cache for meshData, starting to build it if needed. + * @return null while the mesh's buffers or the cache are not ready yet. + */ + static const DecalTriangleCache* Get( TriGeometryResMeshData* meshData ); + + /** + * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. + * @param aabbMin, aabbMax Bounds of the decal volume in the mesh's vertex space. + * @param inverseDecalMatrix Maps the mesh's vertex space into decal space (the volume is [-1, 1]^3). + */ + void Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const; + + size_t GetMemoryUsage() const; +}; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 98c208ca2..84ca00965 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -15,6 +15,7 @@ #include "Tr2InstancedMesh.h" #include "TriSettingsRegistrar.h" #include "Eve/SpaceObject/Children/EveSpaceObjectChild.h" +#include "EveDecalTriangleCache.h" CCP_STATS_DECLARED_ELSEWHERE( primitiveCount ); @@ -222,7 +223,7 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab else if( m_dynamicIndexBuffers ) { // runtime decal: owned here, never added to the mesh's shared decal cache (that cache only grows) - m_decalGeometry = mesh && geomRes->IsGood() ? BuildDecalGeometry( mesh, meshCache, m_decalMatrix, m_inverseDecalMatrix ) : nullptr; + m_decalGeometry = mesh && geomRes->IsGood() ? BuildDecalGeometryCached( mesh, m_decalMatrix, m_inverseDecalMatrix ) : nullptr; } else if( g_buildDecalBuffers ) { @@ -247,7 +248,7 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab renderables.push_back( this ); } -void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, DecalMeshCacheMap& meshCaches, const std::vector& parts, float objectScreenSize, float objectRadius ) +void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, const std::vector& parts, float objectScreenSize, float objectRadius ) { if( !m_usePartTargets ) { @@ -323,7 +324,7 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r if( !found->decalGeometry || found->decalGeometry->m_lodMask != meshData->m_lodMask ) { - found->decalGeometry = BuildDecalGeometry( meshData, meshCaches[geometry], found->decalMatrix, found->inverseDecalMatrix ); + found->decalGeometry = BuildDecalGeometryCached( meshData, found->decalMatrix, found->inverseDecalMatrix ); } } @@ -943,6 +944,55 @@ std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometry( TriGeome return newDecal; } +// ------------------------------------------------------------------------------------------------------ +std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometryCached( TriGeometryResMeshData* meshData, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ) +{ + TRINITY_STATS_ZONE( __FUNCTION__ ); + + std::shared_ptr newDecal = std::make_shared(); + newDecal->m_inverseDecalMatrix = inverseDecalMatrix; + newDecal->m_lodMask = meshData->m_lodMask; + + Vector3 aabbMin( -1.f, -1.f, -1.f ); + Vector3 aabbMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( aabbMin, aabbMax, decalMatrix ); + + // a decal volume outside the mesh bounds hits nothing: don't build the cache for it + if( aabbMin.x > meshData->m_maxBounds.x || aabbMax.x < meshData->m_minBounds.x || + aabbMin.y > meshData->m_maxBounds.y || aabbMax.y < meshData->m_minBounds.y || + aabbMin.z > meshData->m_maxBounds.z || aabbMax.z < meshData->m_minBounds.z ) + { + newDecal->m_lods.resize( meshData->m_lods.size() ); + return newDecal; + } + + const DecalTriangleCache* cache = DecalTriangleCache::Get( meshData ); + if( !cache ) + { + return nullptr; + } + + std::vector allIndices; + for( size_t i = 0; i < meshData->m_lods.size(); ++i ) + { + MeshDecalLodData lod; + lod.m_startIndex = uint32_t( allIndices.size() ); + cache->Query( i, aabbMin, aabbMax, inverseDecalMatrix, allIndices ); + lod.m_primitiveCount = ( uint32_t( allIndices.size() ) - lod.m_startIndex ) / 3; + newDecal->m_lods.push_back( lod ); + } + + if( !allIndices.empty() ) + { + USE_MAIN_THREAD_RENDER_CONTEXT(); + if( !SUCCEEDED( g_sharedBuffer.Allocate( 4, uint32_t( allIndices.size() ), allIndices.data(), renderContext, newDecal->m_indexBuffer ) ) ) + { + return nullptr; + } + } + return newDecal; +} + void EveSpaceObjectDecal::SetIndices( const std::vector>& indices ) { m_decalGeometry = nullptr; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 43c5f55a7..f5b9029b1 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -14,7 +14,6 @@ #include "Eve/IEveSpaceObject2.h" #include "Eve/EveUpdateContext.h" #include "../../../Resources/TriGeometryRes.h" -#include BLUE_DECLARE_INTERFACE( ITr2InstanceData ); BLUE_DECLARE( Tr2Buffer ); @@ -73,9 +72,6 @@ struct DecalMeshCache std::vector buffers; }; -// CPU copies of the vertex/index buffers of each hull geometry, shared by all decals of an object within a frame -using DecalMeshCacheMap = std::unordered_map; - struct EveChildGeometry; // -------------------------------------------------------------------------------- @@ -138,13 +134,13 @@ BLUE_CLASS( EveSpaceObjectDecal ) : void GetInstancedRenderables( std::vector & renderables, DecalMeshCache & meshCache, const Tr2InstancedMesh* instancedMesh, float instanceScreenSize = std::numeric_limits::max() ); /** * @brief Gathers the decal for a parent without a mesh of its own (a modular object), projecting it onto - * every part geometry the decal volume overlaps. Index buffers are built on the CPU from the parts' - * vertices and owned by this decal; they are rebuilt when the decal or a part moves. + * every part geometry the decal volume overlaps. Index buffers are built on the CPU from each part + * geometry's DecalTriangleCache and owned by this decal; they are rebuilt when the decal or a part moves. * @param parts Part geometries of the parent, in the parent's object space (EveSpaceObjectChild::CollectOwnedGeometry). * @param objectScreenSize Screen size of the whole parent, used to pick a LOD per part. * @param objectRadius Bounding sphere radius of the whole parent in object space. */ - void GetModularRenderables( std::vector & renderables, DecalMeshCacheMap & meshCaches, const std::vector& parts, float objectScreenSize, float objectRadius ); + void GetModularRenderables( std::vector & renderables, const std::vector& parts, float objectScreenSize, float objectRadius ); // access position etc. const Vector3& GetPosition() const; @@ -179,6 +175,9 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // Collects the triangles of every LOD of meshData that intersect the decal volume. Returns null if the // mesh buffers are not ready yet. inverseDecalMatrix maps the mesh's vertex space into decal space. static std::shared_ptr BuildDecalGeometry( TriGeometryResMeshData * meshData, DecalMeshCache & meshCache, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ); + // Same result as BuildDecalGeometry, but reads the triangles from the mesh's DecalTriangleCache + // (built once per mesh), so only the triangles near the decal volume are tested. + static std::shared_ptr BuildDecalGeometryCached( TriGeometryResMeshData * meshData, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix ); void FillPerObjectData( EveDecalPerObjectData & data, const Matrix& worldMatrix, const Matrix& decalMatrix, const Matrix& inverseDecalMatrix, const Matrix& parentBoneMatrix ) const; void CommitBatch( ITriRenderBatchAccumulator * batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ); // update diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index ff3e5567c..d982ba808 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -1603,10 +1603,9 @@ void EveSpaceObject2::PushChildrenAndDecalRenderables( std::vectorGetModularRenderables( renderables, meshCaches, parts, m_meshScreenSize, m_boundingSphereRadius ); + ( *it )->GetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius ); } } } diff --git a/trinity/Resources/TriGeometryRes.h b/trinity/Resources/TriGeometryRes.h index 99a465cd9..c88cfb808 100644 --- a/trinity/Resources/TriGeometryRes.h +++ b/trinity/Resources/TriGeometryRes.h @@ -139,6 +139,7 @@ struct MeshDecalData }; struct TriGeometryResMeshData; +struct DecalTriangleCache; extern bool g_eveIsAudioOcclusionGeometryEnabled; @@ -216,6 +217,8 @@ struct TriGeometryResMeshData std::unique_ptr m_audioGeometry; std::vector> m_decals; + // CPU triangles + grid for runtime decals, built on demand (see DecalTriangleCache) + std::shared_ptr m_decalTriangleCache; uint32_t m_lodMask; //A bit mask of which LODs have been loaded. TrackableStdVector> m_lods; From cf4f76f330d1207c7891199f65800e09b79d5eee Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 16:08:25 +0000 Subject: [PATCH 04/19] Find the nearest hull edge for runtime decals EveSpaceObject2.GetNearestHullEdge(position, radius) returns the point on an edge of the object's geometry (its mesh, or a modular object's parts) nearest to an object-space point, with the normal a decal there should project along to wrap over the edge. An edge is a fold sharper than 30 degrees between two triangles, matched by vertex position so split vertices join up, or an open edge. The search runs on the per-mesh DecalTriangleCache, whose cell walk is now shared with the decal query. Not found while a mesh's cache is building. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 193 ++++++++++++++++-- .../Attachments/EveDecalTriangleCache.h | 12 ++ trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 77 +++++++ trinity/Eve/SpaceObject/EveSpaceObject2.h | 10 + .../Eve/SpaceObject/EveSpaceObject2_Blue.cpp | 9 + 5 files changed, 283 insertions(+), 18 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index 2408d311a..e77eddb7a 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -5,6 +5,7 @@ #include "Utilities/BoundingBox.h" #include "Shader/Tr2EffectStateManager.h" #include +#include namespace { @@ -234,14 +235,12 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD return nullptr; } -void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const +namespace +{ +// Calls fn( triangle ) for each triangle of lod whose bounds touch [aabbMin, aabbMax]. +template +void ForEachTriangleNear( const DecalTriangleCache::Lod& lod, const Vector3& aabbMin, const Vector3& aabbMax, Fn&& fn ) { - if( lodIndex >= lods.size() ) - { - return; - } - const Lod& lod = lods[lodIndex]; - for( const auto& level : lod.levels ) { // a triangle stored here is no larger than a cell, so its centre is within half a cell of the box @@ -263,26 +262,184 @@ void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const V for( uint32_t t = lod.cellStart[row + x0]; t < lod.cellStart[row + x1 + 1]; ++t ) { const uint32_t* tri = &lod.indices[size_t( t ) * 3]; - const Vector3* v0 = &lod.positions[tri[0]]; - const Vector3* v1 = &lod.positions[tri[1]]; - const Vector3* v2 = &lod.positions[tri[2]]; - // cheap bounds reject before the exact tests - if( std::max( { v0->x, v1->x, v2->x } ) < aabbMin.x || std::min( { v0->x, v1->x, v2->x } ) > aabbMax.x || - std::max( { v0->y, v1->y, v2->y } ) < aabbMin.y || std::min( { v0->y, v1->y, v2->y } ) > aabbMax.y || - std::max( { v0->z, v1->z, v2->z } ) < aabbMin.z || std::min( { v0->z, v1->z, v2->z } ) > aabbMax.z ) + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + // cheap bounds reject before any exact test + if( std::max( { v0.x, v1.x, v2.x } ) < aabbMin.x || std::min( { v0.x, v1.x, v2.x } ) > aabbMax.x || + std::max( { v0.y, v1.y, v2.y } ) < aabbMin.y || std::min( { v0.y, v1.y, v2.y } ) > aabbMax.y || + std::max( { v0.z, v1.z, v2.z } ) < aabbMin.z || std::min( { v0.z, v1.z, v2.z } ) > aabbMax.z ) { continue; } - if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) && IntersectTriangleOrientedBox( v0, v1, v2, inverseDecalMatrix ) ) - { - out.insert( out.end(), tri, tri + 3 ); - } + fn( tri ); } } } } } +// A vertex position rounded to a tenth of a millimetre, so split vertices compare equal +struct VertexKey +{ + int64_t x, y, z; + bool operator==( const VertexKey& other ) const + { + return x == other.x && y == other.y && z == other.z; + } + bool operator<( const VertexKey& other ) const + { + return x != other.x ? x < other.x : y != other.y ? y < other.y : z < other.z; + } +}; + +VertexKey MakeKey( const Vector3& p ) +{ + return { int64_t( std::llround( p.x * 1e4f ) ), int64_t( std::llround( p.y * 1e4f ) ), int64_t( std::llround( p.z * 1e4f ) ) }; +} + +struct EdgeKey +{ + VertexKey a, b; + bool operator==( const EdgeKey& other ) const + { + return a == other.a && b == other.b; + } +}; + +struct EdgeKeyHash +{ + size_t operator()( const EdgeKey& key ) const + { + size_t h = 1469598103934665603ull; + for( int64_t v : { key.a.x, key.a.y, key.a.z, key.b.x, key.b.y, key.b.z } ) + { + h = ( h ^ size_t( v ) ) * 1099511628211ull; + } + return h; + } +}; + +struct EdgeFaces +{ + Vector3 p0, p1; + Vector3 normals[2]; + uint32_t count = 0; +}; + +Vector3 ClosestPointOnSegment( const Vector3& p, const Vector3& a, const Vector3& b ) +{ + Vector3 ab = b - a; + float lengthSq = Dot( ab, ab ); + float t = lengthSq > 0.f ? std::clamp( Dot( p - a, ab ) / lengthSq, 0.f, 1.f ) : 0.f; + return a + ab * t; +} +} + +void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const +{ + if( lodIndex >= lods.size() ) + { + return; + } + const Lod& lod = lods[lodIndex]; + ForEachTriangleNear( lod, aabbMin, aabbMax, [&]( const uint32_t* tri ) { + const Vector3* v0 = &lod.positions[tri[0]]; + const Vector3* v1 = &lod.positions[tri[1]]; + const Vector3* v2 = &lod.positions[tri[2]]; + if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) && IntersectTriangleOrientedBox( v0, v1, v2, inverseDecalMatrix ) ) + { + out.insert( out.end(), tri, tri + 3 ); + } + } ); +} + +bool DecalTriangleCache::FindNearestEdge( size_t lodIndex, const Vector3& point, float radius, float sharpCos, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const +{ + if( lodIndex >= lods.size() || radius <= 0.f ) + { + return false; + } + const Lod& lod = lods[lodIndex]; + const Vector3 extent( radius, radius, radius ); + + // Every edge that comes within radius of point lies in this box, and so does every + // triangle on either side of it: an edge's faces are all gathered, so a fold is never + // mistaken for an open edge because its other face was out of the query. + std::unordered_map edges; + ForEachTriangleNear( lod, point - extent, point + extent, [&]( const uint32_t* tri ) { + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + Vector3 faceNormal = Cross( v1 - v0, v2 - v0 ); + float area = Length( faceNormal ); + if( area < 1e-8f ) + { + return; + } + faceNormal = faceNormal / area; + const Vector3* corners[3] = { &v0, &v1, &v2 }; + for( int i = 0; i < 3; ++i ) + { + const Vector3& a = *corners[i]; + const Vector3& b = *corners[( i + 1 ) % 3]; + VertexKey ka = MakeKey( a ); + VertexKey kb = MakeKey( b ); + if( ka == kb ) + { + continue; + } + EdgeKey key = kb < ka ? EdgeKey{ kb, ka } : EdgeKey{ ka, kb }; + EdgeFaces& faces = edges[key]; + if( faces.count == 0 ) + { + faces.p0 = a; + faces.p1 = b; + } + if( faces.count < 2 ) + { + faces.normals[faces.count] = faceNormal; + } + ++faces.count; + } + } ); + + bool found = false; + float bestDistance = radius; + for( const auto& entry : edges ) + { + const EdgeFaces& faces = entry.second; + Vector3 normal; + if( faces.count == 1 ) + { + normal = faces.normals[0]; + } + else if( faces.count == 2 && Dot( faces.normals[0], faces.normals[1] ) < sharpCos ) + { + normal = faces.normals[0] + faces.normals[1]; + float length = Length( normal ); + // two faces folded flat onto each other (a thin fin): either face will do + normal = length > 1e-4f ? normal / length : faces.normals[0]; + } + else + { + // a smooth fold, or a non-manifold edge shared by more than two triangles + continue; + } + Vector3 closest = ClosestPointOnSegment( point, faces.p0, faces.p1 ); + float distance = Length( closest - point ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + outPosition = closest; + outNormal = normal; + } + } + outDistance = bestDistance; + return found; +} + size_t DecalTriangleCache::GetMemoryUsage() const { size_t bytes = sizeof( *this ); diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 03076b4bb..f36adec7f 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -58,5 +58,17 @@ struct DecalTriangleCache */ void Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const; + /** + * @brief Finds the point on a hull edge of LOD lodIndex nearest to point, within radius. + * + * An edge is where two triangles meet at a fold sharper than sharpCos (the cosine of the + * angle between their face normals), or an open edge with a triangle on one side only. + * Vertices are matched by position, so the split vertices of a hard edge still join up. + * @param outNormal The two faces' normals averaged (a face's own on an open edge): a + * decal projected along it wraps over the edge onto both faces. + * @return false if no edge lies within radius. + */ + bool FindNearestEdge( size_t lodIndex, const Vector3& point, float radius, float sharpCos, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const; + size_t GetMemoryUsage() const; }; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index d982ba808..61888a3e0 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -35,6 +35,7 @@ #include "Controllers/ITr2Controller.h" #include "Eve/SpaceObject/Children/EveChildInheritProperties.h" #include "Eve/SpaceObject/Children/EveChildMesh.h" +#include "Eve/SpaceObject/Attachments/EveDecalTriangleCache.h" #include "Shader/Tr2Shader.h" #include "../../Tr2RingBuffer.h" @@ -2826,6 +2827,82 @@ bool EveSpaceObject2::GetDamageLocatorBindPosition( int index, Vector3& out ) co return true; } +std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +{ + // cosine of the fold, between two faces' normals, that counts as an edge + constexpr float SHARP_EDGE_COS = 0.866f; + + std::vector parts; + std::vector areas; + if( m_mesh && m_mesh->GetGeometryResource() ) + { + EveChildGeometry own; + own.geometry = m_mesh->GetGeometryResource(); + own.childToObject = IdentityMatrix(); + parts.push_back( own ); + } + for( auto& child : m_effectChildren ) + { + child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); + } + + bool found = false; + float bestDistance = radius; + Vector3 bestPosition = position; + Vector3 bestNormal( 0.f, 0.f, 0.f ); + for( const auto& part : parts ) + { + TriGeometryRes* geometry = part.geometry; + if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) + { + continue; + } + TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); + if( !meshData ) + { + continue; + } + const Matrix& m = part.childToObject; + float scale = std::max( { Length( Vector3( m._11, m._12, m._13 ) ), Length( Vector3( m._21, m._22, m._23 ) ), Length( Vector3( m._31, m._32, m._33 ) ) } ); + if( scale <= 0.f ) + { + continue; + } + Matrix objectToPart = Inverse( m ); + Vector3 local = XMVector3TransformCoord( position, objectToPart ); + float localRadius = bestDistance / scale; + // cheap reject: the part's bounds are further away than the best edge so far + if( local.x + localRadius < meshData->m_minBounds.x || local.x - localRadius > meshData->m_maxBounds.x || + local.y + localRadius < meshData->m_minBounds.y || local.y - localRadius > meshData->m_maxBounds.y || + local.z + localRadius < meshData->m_minBounds.z || local.z - localRadius > meshData->m_maxBounds.z ) + { + continue; + } + const DecalTriangleCache* cache = DecalTriangleCache::Get( meshData ); + if( !cache ) + { + continue; + } + Vector3 edgePosition, edgeNormal; + float localDistance; + if( !cache->FindNearestEdge( 0, local, localRadius, SHARP_EDGE_COS, edgePosition, edgeNormal, localDistance ) ) + { + continue; + } + Vector3 objectPosition = XMVector3TransformCoord( edgePosition, m ); + float distance = Length( objectPosition - position ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + bestPosition = objectPosition; + // normals take the inverse transpose of the part transform + bestNormal = Normalize( Vector3( XMVector3TransformNormal( edgeNormal, Transpose( objectToPart ) ) ) ); + } + } + return std::make_pair( found, std::make_pair( bestPosition, bestNormal ) ); +} + Vector3 EveSpaceObject2::GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ) { Vector3 out; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.h b/trinity/Eve/SpaceObject/EveSpaceObject2.h index b603c40fc..26333d068 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.h +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.h @@ -511,6 +511,16 @@ BLUE_CLASS( EveSpaceObject2 ) : int GetClosestLocatorIndex( const Vector3* position, BlueSharedString locatorSetName ); unsigned int GetLocatorCount( BlueSharedString locatorSetName ) const; Vector3 GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); + + /** + * @brief The point on an edge of the object's own geometry (its mesh, or a modular object's + * parts) nearest to position, and the normal to project a decal along so it wraps the edge. + * @see DecalTriangleCache::FindNearestEdge + * @param position, radius Object space; only edges within radius are considered. + * @return (found, (position, normal)) in object space. Not found while a mesh's triangle + * cache is still being built, which the first call on that mesh starts. + */ + std::pair> GetNearestHullEdge( const Vector3& position, float radius ); Vector3 GetLocatorRotationFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorPosition( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorDirection( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp index 350ac1d5c..e14fc69a4 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp @@ -548,6 +548,15 @@ const Be::ClassInfo* EveSpaceObject2::ExposeToBlue() "Get the closest locator in set to target, does not mind about direction of locator.\n" ":param position: position of target\n" ":param locatorSetName: name of locator set \n" ) + MAP_METHOD_AND_WRAP( + "GetNearestHullEdge", + GetNearestHullEdge, + "( position, radius ) -> ( found, ( position, normal ) )\n" + "Nearest point on an edge of the object's geometry (a fold sharper than 30 degrees, or an open edge), " + "in object space, with the normal a decal there should project along to wrap over the edge. " + "Not found while the geometry's triangle cache is still being built.\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) MAP_METHOD_AND_WRAP( "GetLocatorPositionFromSet", GetLocatorPositionFromSet, From b4c4c398d12885f9ef3657aa1ffc219c0c72f0d9 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 16:40:03 +0000 Subject: [PATCH 05/19] Keep runtime decals off faces they would smear across A runtime decal now leaves out triangles more than ~66 degrees off its projection axis (either winding): its texture stretched into long streaks along faces nearly parallel to the axis. A decal on an edge sits 45 degrees to each face, so it still wraps the edge. Baked decals are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../SpaceObject/Attachments/EveDecalTriangleCache.cpp | 11 ++++++++++- .../SpaceObject/Attachments/EveDecalTriangleCache.h | 6 +++++- .../SpaceObject/Attachments/EveSpaceObjectDecal.cpp | 9 ++++++++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index e77eddb7a..eb5299f41 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -336,7 +336,7 @@ Vector3 ClosestPointOnSegment( const Vector3& p, const Vector3& a, const Vector3 } } -void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const +void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, const Vector3& projectionAxis, float minFacing, std::vector& out ) const { if( lodIndex >= lods.size() ) { @@ -347,6 +347,15 @@ void DecalTriangleCache::Query( size_t lodIndex, const Vector3& aabbMin, const V const Vector3* v0 = &lod.positions[tri[0]]; const Vector3* v1 = &lod.positions[tri[1]]; const Vector3* v2 = &lod.positions[tri[2]]; + if( minFacing > 0.f ) + { + Vector3 faceNormal = Cross( *v1 - *v0, *v2 - *v0 ); + float length = Length( faceNormal ); + if( length < 1e-12f || std::abs( Dot( faceNormal, projectionAxis ) ) < minFacing * length ) + { + return; + } + } if( IntersectTriangleAABB( v0, v1, v2, aabbMin, aabbMax ) && IntersectTriangleOrientedBox( v0, v1, v2, inverseDecalMatrix ) ) { out.insert( out.end(), tri, tri + 3 ); diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index f36adec7f..cdb0a0678 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -55,8 +55,12 @@ struct DecalTriangleCache * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. * @param aabbMin, aabbMax Bounds of the decal volume in the mesh's vertex space. * @param inverseDecalMatrix Maps the mesh's vertex space into decal space (the volume is [-1, 1]^3). + * @param projectionAxis Unit direction the decal projects along, in the mesh's vertex space. + * @param minFacing Triangles whose face normal is closer to perpendicular to projectionAxis than + * this (|cos| of the angle between them) are left out: the decal's texture would smear along + * them. Either winding counts. Pass a value <= 0 to keep every triangle. */ - void Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, std::vector& out ) const; + void Query( size_t lodIndex, const Vector3& aabbMin, const Vector3& aabbMax, const Matrix& inverseDecalMatrix, const Vector3& projectionAxis, float minFacing, std::vector& out ) const; /** * @brief Finds the point on a hull edge of LOD lodIndex nearest to point, within radius. diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 84ca00965..7f5deef51 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -972,12 +972,19 @@ std::shared_ptr EveSpaceObjectDecal::BuildDecalGeometryCached( Tr return nullptr; } + // faces more than ~66 degrees off the projection axis would smear the decal's texture across + // them; leaving them out still lets a decal on an edge (45 degrees to each face) wrap it + constexpr float MIN_FACING = 0.4f; + Vector3 projectionAxis( decalMatrix._11, decalMatrix._12, decalMatrix._13 ); + float axisLength = Length( projectionAxis ); + projectionAxis = axisLength > 0.f ? projectionAxis / axisLength : Vector3( 1.f, 0.f, 0.f ); + std::vector allIndices; for( size_t i = 0; i < meshData->m_lods.size(); ++i ) { MeshDecalLodData lod; lod.m_startIndex = uint32_t( allIndices.size() ); - cache->Query( i, aabbMin, aabbMax, inverseDecalMatrix, allIndices ); + cache->Query( i, aabbMin, aabbMax, inverseDecalMatrix, projectionAxis, MIN_FACING, allIndices ); lod.m_primitiveCount = ( uint32_t( allIndices.size() ) - lod.m_startIndex ) / 3; newDecal->m_lods.push_back( lod ); } From 986605e6557ececadaaf096f7e988b38dc11260c Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Wed, 11 Nov 2026 16:56:44 +0000 Subject: [PATCH 06/19] Put runtime decals on everything an object draws Level geometry has a placeholder mesh of its own and draws through an EveChildInstancedMeshes child, so its runtime decals were projected onto the placeholder and found nothing. A runtime decal (dynamicIndexBuffers) on an object with both now goes onto its mesh and its children's parts. Baked decals, and those built by buildDecalBuffers, stay on the object's own mesh. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.h | 6 +++ trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 52 +++++++++++-------- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index f5b9029b1..b0d74c429 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -142,6 +142,12 @@ BLUE_CLASS( EveSpaceObjectDecal ) : */ void GetModularRenderables( std::vector & renderables, const std::vector& parts, float objectScreenSize, float objectRadius ); + // true if this decal builds its own geometry at runtime (dynamicIndexBuffers) + bool HasDynamicIndexBuffers() const + { + return m_dynamicIndexBuffers; + } + // access position etc. const Vector3& GetPosition() const; void SetPosition( const Vector3& pos ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index 61888a3e0..76a56933d 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -1579,35 +1579,43 @@ void EveSpaceObject2::PushChildrenAndDecalRenderables( std::vectorGetGeometryResource(); - if( geometryRes ) + return; + } + + TriGeometryResPtr geometryRes = m_mesh ? m_mesh->GetGeometryResource() : nullptr; + // geometry the object draws through its children (a modular object's parts, or the + // instanced meshes of level geometry that has only a placeholder mesh of its own) + std::vector parts; + std::vector areas; + for( auto& child : m_effectChildren ) + { + child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); + } + if( !parts.empty() && geometryRes ) + { + // a runtime decal goes onto everything the object draws, its own mesh included + EveChildGeometry own; + own.geometry = geometryRes; + own.childToObject = IdentityMatrix(); + parts.insert( parts.begin(), own ); + } + + DecalMeshCache meshCache; + for( auto it = m_decals.begin(); it != m_decals.end(); ++it ) + { + // a baked decal, or one built by the buildDecalBuffers setting, belongs to the object's own mesh + if( parts.empty() || ( geometryRes && !( *it )->HasDynamicIndexBuffers() ) ) { - DecalMeshCache meshCache; - // runn over every decal and update it - for( EveSpaceObjectDecalVector::const_iterator it = m_decals.begin(); it != m_decals.end(); ++it ) + if( geometryRes ) { - // now prep to get the renderables ( *it )->GetRenderables( renderables, meshCache, geometryRes, m_meshScreenSize ); } } - } - else if( !m_mesh && m_isMeshVisible && !m_decals.empty() ) - { - // modular objects have no mesh of their own: project the decals onto the parts' geometry - std::vector parts; - std::vector areas; - for( auto& child : m_effectChildren ) - { - child->CollectOwnedGeometry( TRIBATCHTYPE_OPAQUE, IdentityMatrix(), parts, areas ); - } - if( !parts.empty() ) + else { - for( auto it = m_decals.begin(); it != m_decals.end(); ++it ) - { - ( *it )->GetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius ); - } + ( *it )->GetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius ); } } } From 006525a700b6c9d1222eeb32e240c6acd85f2e82 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 10:47:52 +0000 Subject: [PATCH 07/19] Draw part decals at their part's LOD, pulled towards the eye Part decals picked their LOD from the object's screen size scaled by the part's size, so near a threshold a decal could sit on another LOD's triangles than the part it marks, and flicker as the camera moved. They now pick it as the part is drawn: the object's own mesh at the object's screen size, instanced parts from the instance's sphere as EveChildInstancedMeshes sizes it and EveInstancedMeshManager::GetMeshLod picks it. A part decal's world matrix is composed on the CPU while the part is drawn through the instanced path, so their depths differ by rounding and, with no depth write or bias in the decal pass, can z-fight. Part decals are now scaled by 1 - 4e-4 about the eye: no pixel moves, and the depth comes that fraction of the distance closer. Decals on a single mesh are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 69 +++++++++++++++++-- .../Attachments/EveSpaceObjectDecal.h | 8 ++- trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 2 +- 3 files changed, 73 insertions(+), 6 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 7f5deef51..032632f92 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -130,6 +130,9 @@ bool EveSpaceObjectDecal::OnPrepareResources() void EveSpaceObjectDecal::UpdateVisibility( const EveUpdateContext& updateContext, const IEveSpaceObject2::ParentData* parentData ) { m_isVisible = 0; + m_lastFrustum = updateContext.GetFrustum(); + m_lastInvLodFactor = updateContext.GetInvLodFactor(); + m_hasLastFrustum = true; if( !m_display || !m_decalEffect ) { @@ -248,7 +251,36 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab renderables.push_back( this ); } -void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, const std::vector& parts, float objectScreenSize, float objectRadius ) +namespace +{ +// A part decal's world matrix is composed on the CPU, while the part itself is drawn through the +// instanced path (instance matrix, then the child's world matrix, on the GPU): the two positions +// differ by rounding, and with no depth write or bias the decal z-fights its own surface. Scaling +// the decal about the eye by this much leaves every pixel where it is and moves it this fraction of +// its distance towards the eye, which is well above that rounding and well below anything visible. +constexpr float PART_DEPTH_PULL = 4e-4f; + +// The LOD the instanced mesh manager draws a part with (EveInstancedMeshManager::GetMeshLod) +int InstancedMeshLod( const TriGeometryResMeshData& meshData, float screenSize ) +{ + const size_t lodCount = meshData.m_lods.size(); + for( size_t lod = 0; lod + 1 < lodCount; ++lod ) + { + if( screenSize > meshData.m_lods[lod + 1]->m_maxScreenSize ) + { + return int( lod ); + } + } + return int( lodCount ) - 1; +} + +float MaxAxisScale( const Matrix& m ) +{ + return std::sqrt( std::max( { LengthSq( Vector3( m._11, m._12, m._13 ) ), LengthSq( Vector3( m._21, m._22, m._23 ) ), LengthSq( Vector3( m._31, m._32, m._33 ) ) } ) ); +} +} + +void EveSpaceObjectDecal::GetModularRenderables( std::vector& renderables, const std::vector& parts, float objectScreenSize, float objectRadius, const TriGeometryRes* ownGeometry ) { if( !m_usePartTargets ) { @@ -303,7 +335,9 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r decalMin.y <= meshData->m_maxBounds.y && decalMax.y >= meshData->m_minBounds.y && decalMin.z <= meshData->m_maxBounds.z && decalMax.z >= meshData->m_minBounds.z; - // the instanced mesh manager picks a part's LOD from the part's own bounding sphere + Vector3 boundsCenter = ( meshData->m_minBounds + meshData->m_maxBounds ) * 0.5f; + target.lodRadius = Length( meshData->m_maxBounds - meshData->m_minBounds ) * 0.5f + Length( boundsCenter ); + // fallback before the first visibility update: scale the object's screen size by the part's size if( objectRadius > 0.f ) { const Matrix& m = part.childToObject; @@ -338,7 +372,28 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r { continue; } - int lodIndex = m_isGeometryFrozen ? 0 : target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize * target.screenSizeScale ); + int lodIndex = 0; + if( m_isGeometryFrozen ) + { + lodIndex = 0; + } + else if( target.geometry == ownGeometry ) + { + // the object's own mesh draws at the object's screen size + lodIndex = target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize ); + } + else if( m_hasLastFrustum ) + { + // as EveChildInstancedMeshes sizes the instance's sphere and EveInstancedMeshManager picks its LOD + Matrix world = target.childToObject * m_parentData.transform; + float screenSize = m_lastFrustum.GetPixelSizeAccrossEst( world.GetTranslation(), target.lodRadius * MaxAxisScale( world ) ) * m_lastInvLodFactor; + const TriGeometryResMeshData* meshData = target.geometry->GetMeshData( 0 ); + lodIndex = meshData ? InstancedMeshLod( *meshData, screenSize ) : -1; + } + else + { + lodIndex = target.geometry->GetLodIndexForScreenSize( 0, objectScreenSize * target.screenSizeScale ); + } if( lodIndex < 0 || lodIndex >= int( target.decalGeometry->m_lods.size() ) || !target.decalGeometry->m_lods[lodIndex].m_primitiveCount ) { continue; @@ -410,7 +465,13 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, return; } // draw the part's vertices with the part's world transform and the decal volume in part space - FillPerObjectData( *partData, target.childToObject * m_parentData.transform, target.decalMatrix, target.inverseDecalMatrix, IdentityMatrix() ); + Matrix world = target.childToObject * m_parentData.transform; + if( m_hasLastFrustum ) + { + const Vector3& eye = m_lastFrustum.m_viewPos; + world = world * TranslationMatrix( -eye ) * ScalingMatrix( 1.f - PART_DEPTH_PULL, 1.f - PART_DEPTH_PULL, 1.f - PART_DEPTH_PULL ) * TranslationMatrix( eye ); + } + FillPerObjectData( *partData, world, target.decalMatrix, target.inverseDecalMatrix, IdentityMatrix() ); CommitBatch( batches, lod, *target.decalGeometry, target.lodIndex, partData ); } return; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index b0d74c429..8fb7cd245 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -140,7 +140,7 @@ BLUE_CLASS( EveSpaceObjectDecal ) : * @param objectScreenSize Screen size of the whole parent, used to pick a LOD per part. * @param objectRadius Bounding sphere radius of the whole parent in object space. */ - void GetModularRenderables( std::vector & renderables, const std::vector& parts, float objectScreenSize, float objectRadius ); + void GetModularRenderables( std::vector & renderables, const std::vector& parts, float objectScreenSize, float objectRadius, const TriGeometryRes* ownGeometry ); // true if this decal builds its own geometry at runtime (dynamicIndexBuffers) bool HasDynamicIndexBuffers() const @@ -257,11 +257,17 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // owned here rather than cached on the (shared) mesh data: runtime decals come and go std::shared_ptr decalGeometry; float screenSizeScale = 1.f; + // radius of the part's bounds about its own origin, as the instanced mesh manager sizes it for LOD + float lodRadius = 0.f; int lodIndex = -1; bool overlaps = false; bool seen = false; }; std::vector m_partTargets; + // the camera of the last visibility update: part LODs and the depth pull are taken from it + TriFrustum m_lastFrustum; + float m_lastInvLodFactor = 1.f; + bool m_hasLastFrustum = false; // true when the parent has no mesh and the decal renders through m_partTargets bool m_usePartTargets; }; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index 76a56933d..0b8effab3 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -1615,7 +1615,7 @@ void EveSpaceObject2::PushChildrenAndDecalRenderables( std::vectorGetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius ); + ( *it )->GetModularRenderables( renderables, parts, m_meshScreenSize, m_boundingSphereRadius, geometryRes ); } } } From c808d5d162d00aa8622aa998188ae63c2ad60d18 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 10:55:10 +0000 Subject: [PATCH 08/19] Size the part decal depth pull to the part's rounding Level geometry instances sit tens of km from their object's origin, so the hull's two-step instanced transform and the decal's composed matrix round apart by millimetres whatever the camera distance: a fixed 0.04% pull left the decal behind its surface up close. The pull now covers two float steps at the largest coordinate in the part's transform chain, from the part's nearest point to the eye (no nearer than 2 m), between 0.04% and 0.5%. Still a scale about the eye, so no pixel moves. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 032632f92..84732ca8b 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -255,10 +255,15 @@ namespace { // A part decal's world matrix is composed on the CPU, while the part itself is drawn through the // instanced path (instance matrix, then the child's world matrix, on the GPU): the two positions -// differ by rounding, and with no depth write or bias the decal z-fights its own surface. Scaling -// the decal about the eye by this much leaves every pixel where it is and moves it this fraction of -// its distance towards the eye, which is well above that rounding and well below anything visible. -constexpr float PART_DEPTH_PULL = 4e-4f; +// differ by rounding, and with no depth write or bias the decal z-fights its own surface. The decal +// is scaled about the eye, which leaves every pixel where it is and moves its depth a fraction of +// its distance towards the eye. That rounding is a few float steps at the largest coordinate in +// the chain (a level instance sits tens of km from its object's origin), so the fraction covers +// PART_DEPTH_ULPS of them at the part's nearest point (no nearer than 2 m), within these bounds. +constexpr float PART_DEPTH_PULL_MIN = 4e-4f; +constexpr float PART_DEPTH_PULL_MAX = 0.005f; +constexpr float PART_DEPTH_ULPS = 2.f; +constexpr float FLOAT_STEP = 1.f / 8388608.f; // 2^-23, a float's relative resolution // The LOD the instanced mesh manager draws a part with (EveInstancedMeshManager::GetMeshLod) int InstancedMeshLod( const TriGeometryResMeshData& meshData, float screenSize ) @@ -469,7 +474,12 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, if( m_hasLastFrustum ) { const Vector3& eye = m_lastFrustum.m_viewPos; - world = world * TranslationMatrix( -eye ) * ScalingMatrix( 1.f - PART_DEPTH_PULL, 1.f - PART_DEPTH_PULL, 1.f - PART_DEPTH_PULL ) * TranslationMatrix( eye ); + float objectScale = MaxAxisScale( m_parentData.transform ); + // the largest magnitudes the part's vertices pass through on the way to world space + float magnitude = std::max( { Length( target.childToObject.GetTranslation() ) * objectScale, Length( m_parentData.transform.GetTranslation() ), Length( world.GetTranslation() ) } ); + float nearest = std::max( Length( world.GetTranslation() - eye ) - target.lodRadius * MaxAxisScale( world ), 2.f ); + float pull = std::clamp( PART_DEPTH_ULPS * magnitude * FLOAT_STEP / nearest, PART_DEPTH_PULL_MIN, PART_DEPTH_PULL_MAX ); + world = world * TranslationMatrix( -eye ) * ScalingMatrix( 1.f - pull, 1.f - pull, 1.f - pull ) * TranslationMatrix( eye ); } FillPerObjectData( *partData, world, target.decalMatrix, target.inverseDecalMatrix, IdentityMatrix() ); CommitBatch( batches, lod, *target.decalGeometry, target.lodIndex, partData ); From d1876b36210984c00178f829f39e7129c3bcab8a Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 12:05:07 +0000 Subject: [PATCH 09/19] Find the nearest surface point for runtime decals EveSpaceObject2.GetNearestSurfacePoint(position, radius) returns the point on the object's own geometry nearest to an object-space point and that triangle's normal, turned towards the point: where to put a decal, and the true surface normal to project it along. It searches the same per-mesh DecalTriangleCache as GetNearestHullEdge, which now shares the part walk. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 76 +++++++++++++++++++ .../Attachments/EveDecalTriangleCache.h | 7 ++ trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 32 +++++--- trinity/Eve/SpaceObject/EveSpaceObject2.h | 17 +++++ .../Eve/SpaceObject/EveSpaceObject2_Blue.cpp | 8 ++ 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index eb5299f41..c3d33061e 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -327,6 +327,46 @@ struct EdgeFaces uint32_t count = 0; }; +// Closest point to p on triangle abc (Ericson, Real-Time Collision Detection 5.1.5) +Vector3 ClosestPointOnTriangle( const Vector3& p, const Vector3& a, const Vector3& b, const Vector3& c ) +{ + Vector3 ab = b - a, ac = c - a, ap = p - a; + float d1 = Dot( ab, ap ), d2 = Dot( ac, ap ); + if( d1 <= 0.f && d2 <= 0.f ) + { + return a; + } + Vector3 bp = p - b; + float d3 = Dot( ab, bp ), d4 = Dot( ac, bp ); + if( d3 >= 0.f && d4 <= d3 ) + { + return b; + } + float vc = d1 * d4 - d3 * d2; + if( vc <= 0.f && d1 >= 0.f && d3 <= 0.f ) + { + return a + ab * ( d1 / ( d1 - d3 ) ); + } + Vector3 cp = p - c; + float d5 = Dot( ab, cp ), d6 = Dot( ac, cp ); + if( d6 >= 0.f && d5 <= d6 ) + { + return c; + } + float vb = d5 * d2 - d1 * d6; + if( vb <= 0.f && d2 >= 0.f && d6 <= 0.f ) + { + return a + ac * ( d2 / ( d2 - d6 ) ); + } + float va = d3 * d6 - d5 * d4; + if( va <= 0.f && ( d4 - d3 ) >= 0.f && ( d5 - d6 ) >= 0.f ) + { + return b + ( c - b ) * ( ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ) ); + } + float denom = 1.f / ( va + vb + vc ); + return a + ab * ( vb * denom ) + ac * ( vc * denom ); +} + Vector3 ClosestPointOnSegment( const Vector3& p, const Vector3& a, const Vector3& b ) { Vector3 ab = b - a; @@ -449,6 +489,42 @@ bool DecalTriangleCache::FindNearestEdge( size_t lodIndex, const Vector3& point, return found; } +bool DecalTriangleCache::FindNearestSurface( size_t lodIndex, const Vector3& point, float radius, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const +{ + if( lodIndex >= lods.size() || radius <= 0.f ) + { + return false; + } + const Lod& lod = lods[lodIndex]; + const Vector3 extent( radius, radius, radius ); + bool found = false; + float bestDistance = radius; + ForEachTriangleNear( lod, point - extent, point + extent, [&]( const uint32_t* tri ) { + const Vector3& v0 = lod.positions[tri[0]]; + const Vector3& v1 = lod.positions[tri[1]]; + const Vector3& v2 = lod.positions[tri[2]]; + Vector3 faceNormal = Cross( v1 - v0, v2 - v0 ); + float area = Length( faceNormal ); + if( area < 1e-8f ) + { + return; + } + Vector3 closest = ClosestPointOnTriangle( point, v0, v1, v2 ); + float distance = Length( closest - point ); + if( distance <= bestDistance ) + { + found = true; + bestDistance = distance; + outPosition = closest; + faceNormal = faceNormal / area; + // either winding: face the side the query point is on + outNormal = Dot( faceNormal, point - closest ) < 0.f ? -faceNormal : faceNormal; + } + } ); + outDistance = bestDistance; + return found; +} + size_t DecalTriangleCache::GetMemoryUsage() const { size_t bytes = sizeof( *this ); diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index cdb0a0678..07a8ff7bf 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -74,5 +74,12 @@ struct DecalTriangleCache */ bool FindNearestEdge( size_t lodIndex, const Vector3& point, float radius, float sharpCos, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const; + /** + * @brief Finds the point on a triangle of LOD lodIndex nearest to point, within radius. + * @param outNormal The triangle's face normal, turned to the side point is on. + * @return false if no triangle lies within radius. + */ + bool FindNearestSurface( size_t lodIndex, const Vector3& point, float radius, Vector3& outPosition, Vector3& outNormal, float& outDistance ) const; + size_t GetMemoryUsage() const; }; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index 0b8effab3..6ef3f0ad6 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -2835,11 +2835,9 @@ bool EveSpaceObject2::GetDamageLocatorBindPosition( int index, Vector3& out ) co return true; } -std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +template +std::pair> EveSpaceObject2::FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ) { - // cosine of the fold, between two faces' normals, that counts as an edge - constexpr float SHARP_EDGE_COS = 0.866f; - std::vector parts; std::vector areas; if( m_mesh && m_mesh->GetGeometryResource() ) @@ -2879,7 +2877,7 @@ std::pair> EveSpaceObject2::GetNearestHullEdge Matrix objectToPart = Inverse( m ); Vector3 local = XMVector3TransformCoord( position, objectToPart ); float localRadius = bestDistance / scale; - // cheap reject: the part's bounds are further away than the best edge so far + // cheap reject: the part's bounds are further away than the best result so far if( local.x + localRadius < meshData->m_minBounds.x || local.x - localRadius > meshData->m_maxBounds.x || local.y + localRadius < meshData->m_minBounds.y || local.y - localRadius > meshData->m_maxBounds.y || local.z + localRadius < meshData->m_minBounds.z || local.z - localRadius > meshData->m_maxBounds.z ) @@ -2891,13 +2889,13 @@ std::pair> EveSpaceObject2::GetNearestHullEdge { continue; } - Vector3 edgePosition, edgeNormal; + Vector3 partPosition, partNormal; float localDistance; - if( !cache->FindNearestEdge( 0, local, localRadius, SHARP_EDGE_COS, edgePosition, edgeNormal, localDistance ) ) + if( !query( *cache, local, localRadius, partPosition, partNormal, localDistance ) ) { continue; } - Vector3 objectPosition = XMVector3TransformCoord( edgePosition, m ); + Vector3 objectPosition = XMVector3TransformCoord( partPosition, m ); float distance = Length( objectPosition - position ); if( distance <= bestDistance ) { @@ -2905,12 +2903,28 @@ std::pair> EveSpaceObject2::GetNearestHullEdge bestDistance = distance; bestPosition = objectPosition; // normals take the inverse transpose of the part transform - bestNormal = Normalize( Vector3( XMVector3TransformNormal( edgeNormal, Transpose( objectToPart ) ) ) ); + bestNormal = Normalize( Vector3( XMVector3TransformNormal( partNormal, Transpose( objectToPart ) ) ) ); } } return std::make_pair( found, std::make_pair( bestPosition, bestNormal ) ); } +std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +{ + // cosine of the fold, between two faces' normals, that counts as an edge + constexpr float SHARP_EDGE_COS = 0.866f; + return FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + return cache.FindNearestEdge( 0, point, r, SHARP_EDGE_COS, outPosition, outNormal, outDistance ); + } ); +} + +std::pair> EveSpaceObject2::GetNearestSurfacePoint( const Vector3& position, float radius ) +{ + return FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + return cache.FindNearestSurface( 0, point, r, outPosition, outNormal, outDistance ); + } ); +} + Vector3 EveSpaceObject2::GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ) { Vector3 out; diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.h b/trinity/Eve/SpaceObject/EveSpaceObject2.h index 26333d068..9f39618f4 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.h +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.h @@ -521,6 +521,23 @@ BLUE_CLASS( EveSpaceObject2 ) : * cache is still being built, which the first call on that mesh starts. */ std::pair> GetNearestHullEdge( const Vector3& position, float radius ); + + /** + * @brief The point on the object's own geometry (its mesh, or a modular object's parts) nearest + * to position, and that surface's normal, turned towards position. + * @see DecalTriangleCache::FindNearestSurface + * @param position, radius Object space; only surfaces within radius are considered. + * @return (found, (position, normal)) in object space. Not found while a mesh's triangle + * cache is still being built, which the first call on that mesh starts. + */ + std::pair> GetNearestSurfacePoint( const Vector3& position, float radius ); + +private: + // The nearest of query( cache, part-space point, part-space radius ) over the object's own geometry + template + std::pair> FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ); + +public: Vector3 GetLocatorRotationFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorPosition( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); bool GetLocatorDirection( Vector3 * out, int index, bool inWorldSpace, BlueSharedString locatorSetName ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp index e14fc69a4..bce922ab3 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp @@ -557,6 +557,14 @@ const Be::ClassInfo* EveSpaceObject2::ExposeToBlue() "Not found while the geometry's triangle cache is still being built.\n" ":param position: object-space point\n" ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "GetNearestSurfacePoint", + GetNearestSurfacePoint, + "( position, radius ) -> ( found, ( position, normal ) )\n" + "Nearest point on the object's geometry, in object space, with that surface's normal turned " + "towards position. Not found while the geometry's triangle cache is still being built.\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) MAP_METHOD_AND_WRAP( "GetLocatorPositionFromSet", GetLocatorPositionFromSet, From ba8a63b06d84237a268625bcedae7bb4cc50d407 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:18:06 +0000 Subject: [PATCH 10/19] Run decal cache builds as capped tasks, drained at shutdown Each cache build ran on its own detached std::thread: unbounded when many meshes are first hit at once, and nothing joined them at exit. Builds now run in one shared task group, at most two at a time (a mesh asked for beyond that retries on a later frame, before any readback). Tr2Renderer::Shutdown calls DecalTriangleCache::Shutdown, which stops new builds, cancels queued ones and waits for the running ones; a cancelled build never marks its cache ready. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 47 ++++++++++++++++--- .../Attachments/EveDecalTriangleCache.h | 10 +++- trinity/Tr2Renderer.cpp | 2 + 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index c3d33061e..23f3fb79d 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -4,7 +4,7 @@ #include "EveDecalTriangleCache.h" #include "Utilities/BoundingBox.h" #include "Shader/Tr2EffectStateManager.h" -#include +#include "TbbStub.h" #include namespace @@ -13,6 +13,22 @@ namespace constexpr float TRIANGLES_PER_CELL = 4.f; constexpr uint32_t MAX_CELLS_PER_AXIS = 256; constexpr float MAX_CELLS = float( 1u << 21 ); +// grid builds in flight at once; a mesh asked for beyond that retries on a later frame +constexpr int MAX_CONCURRENT_BUILDS = 2; + +struct BuildQueue +{ + Tr2ParallelTaskGroup group; + std::atomic inFlight = 0; + std::atomic shutDown = false; +}; + +// never destroyed: Shutdown drains it, and tearing a task group down during static destruction is unsafe +BuildQueue& GetBuildQueue() +{ + static BuildQueue* queue = new BuildQueue(); + return *queue; +} // Raw copy of one LOD's buffers, taken on the main thread and converted on the worker struct RawLod @@ -191,6 +207,12 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD TRINITY_STATS_ZONE( __FUNCTION__ ); + BuildQueue& queue = GetBuildQueue(); + if( queue.shutDown.load() || queue.inFlight.load() >= MAX_CONCURRENT_BUILDS ) + { + return nullptr; + } + for( auto& lod : meshData->m_lods ) { if( !lod->m_allocationsValid ) @@ -223,18 +245,31 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD newCache->lods.resize( meshData->m_lods.size() ); cache = newCache; - // the worker only touches its own copies, so the mesh may be released while it runs - std::thread( [newCache, raw = std::move( raw ), bytesPerVertex = meshData->m_bytesPerVertex, positionsCompressed]() { - for( size_t i = 0; i < raw.size(); ++i ) + // the task only touches its own copies, so the mesh may be released while it runs + ++queue.inFlight; + queue.group.run( [newCache, raw = std::move( raw ), bytesPerVertex = meshData->m_bytesPerVertex, positionsCompressed, &queue]() { + for( size_t i = 0; i < raw.size() && !queue.shutDown.load(); ++i ) { ConvertLod( raw[i], bytesPerVertex, positionsCompressed, newCache->lods[i] ); BuildGrid( newCache->lods[i] ); } - newCache->ready.store( true, std::memory_order_release ); - } ).detach(); + if( !queue.shutDown.load() ) + { + newCache->ready.store( true, std::memory_order_release ); + } + --queue.inFlight; + } ); return nullptr; } +void DecalTriangleCache::Shutdown() +{ + BuildQueue& queue = GetBuildQueue(); + queue.shutDown.store( true ); + queue.group.cancel(); + queue.group.wait(); +} + namespace { // Calls fn( triangle ) for each triangle of lod whose bounds touch [aabbMin, aabbMax]. diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 07a8ff7bf..6e5127bf7 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -13,8 +13,8 @@ * least as large as the triangle; a query looks at every level with its box grown by half a cell there. * * The first runtime decal build against a mesh reads the mesh back from the GPU on the main thread and - * builds the grid on a worker thread; until that finishes, Get returns null and the decal tries again on a - * later frame. The cache is owned by the mesh's TriGeometryResMeshData, + * builds the grid as a task in a shared task group, at most MAX_CONCURRENT_BUILDS at a time; until that + * finishes, Get returns null and the decal tries again on a later frame. The cache is owned by the mesh's TriGeometryResMeshData, * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. */ @@ -51,6 +51,12 @@ struct DecalTriangleCache */ static const DecalTriangleCache* Get( TriGeometryResMeshData* meshData ); + /** + * @brief Cancels the builds that have not started and waits for the running ones. Get starts no + * build afterwards. + */ + static void Shutdown(); + /** * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. * @param aabbMin, aabbMax Bounds of the decal volume in the mesh's vertex space. diff --git a/trinity/Tr2Renderer.cpp b/trinity/Tr2Renderer.cpp index d1fbc170a..ce62db5a4 100644 --- a/trinity/Tr2Renderer.cpp +++ b/trinity/Tr2Renderer.cpp @@ -10,6 +10,7 @@ #include "TriSettingsRegistrar.h" #include "TriPoolAllocator.h" #include "Resources/TriGeometryRes.h" +#include "Eve/SpaceObject/Attachments/EveDecalTriangleCache.h" using namespace Tr2RenderContextEnum; @@ -357,6 +358,7 @@ bool Tr2Renderer::Initialize() void Tr2Renderer::Shutdown() { + DecalTriangleCache::Shutdown(); GlobalStore().UnregisterVariable( "Time" ); USE_MAIN_THREAD_RENDER_CONTEXT(); //TODO! renderContext.m_esm.Shutdown(); From b37386d2f3e8dbd7c890f75747927dd75469c6e1 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:18:45 +0000 Subject: [PATCH 11/19] Back off after a failed decal cache readback When reading a LOD back from the GPU failed, Get remembered nothing, so every later call (every frame, for every decal on the mesh) paid the readback again, tens of ms on a large mesh. The failure is now stored on the mesh as a failed cache with a retry time: 2 s after the first failure, doubling up to 60 s. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 18 +++++++++++++++++- .../Attachments/EveDecalTriangleCache.h | 5 +++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index 23f3fb79d..ef3425524 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -15,6 +15,9 @@ constexpr uint32_t MAX_CELLS_PER_AXIS = 256; constexpr float MAX_CELLS = float( 1u << 21 ); // grid builds in flight at once; a mesh asked for beyond that retries on a later frame constexpr int MAX_CONCURRENT_BUILDS = 2; +// after a failed readback, wait this long before the next, doubling up to the cap +constexpr std::chrono::seconds RETRY_BACKOFF_FIRST( 2 ); +constexpr std::chrono::seconds RETRY_BACKOFF_MAX( 60 ); struct BuildQueue { @@ -200,7 +203,12 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD } auto& cache = meshData->m_decalTriangleCache; - if( cache && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) + const auto now = std::chrono::steady_clock::now(); + if( cache && cache->failed && now < cache->retryAt ) + { + return nullptr; + } + if( cache && !cache->failed && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) { return cache->ready.load( std::memory_order_acquire ) ? cache.get() : nullptr; } @@ -236,6 +244,14 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD { if( !CopyLod( *meshData, *meshData->m_lods[i], raw[i] ) ) { + // a readback costs tens of ms on a large mesh: don't repeat it every frame + uint32_t failures = cache && cache->failed ? cache->failures + 1 : 1; + auto backoff = std::min( RETRY_BACKOFF_FIRST * ( 1 << std::min( failures - 1, 5u ) ), RETRY_BACKOFF_MAX ); + auto failedCache = std::make_shared(); + failedCache->failed = true; + failedCache->failures = failures; + failedCache->retryAt = now + backoff; + cache = failedCache; return nullptr; } } diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 6e5127bf7..6af7cb912 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -4,6 +4,7 @@ #include "../../../Resources/TriGeometryRes.h" #include +#include /** * @brief CPU copy of a mesh's triangles, bucketed in a hierarchical loose grid per LOD, so that a runtime @@ -44,6 +45,10 @@ struct DecalTriangleCache std::vector lods; // set by the worker thread once lods can be read std::atomic ready = false; + // the mesh could not be read back: Get does not try again before retryAt + bool failed = false; + uint32_t failures = 0; + std::chrono::steady_clock::time_point retryAt; /** * @brief Returns the cache for meshData, starting to build it if needed. From f251cb1e07bb22bf23e598bac6d36874ffb90ae6 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:19:58 +0000 Subject: [PATCH 12/19] Broad-phase decal part targets once per parts change Every frame, GetModularRenderables matched each part against every part target with find_if (quadratic on the 55-mesh instanced level object) and kept a target, with its part-space matrices, for every part, overlapping or not. The parts list is now hashed each frame; only when the hash or the decal volume changes does a broad phase run: the decal box against each part's bounds in object space, keeping just the parts it touches and the geometry already built for those that are unchanged. Unchanged frames only look after the targets that exist. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 110 +++++++++++------- .../Attachments/EveSpaceObjectDecal.h | 5 +- 2 files changed, 69 insertions(+), 46 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 84732ca8b..3c683feec 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -100,6 +100,7 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) } // the part targets cache the decal volume in part space m_partTargets.clear(); + m_partsSignature = 0; } return true; } @@ -201,6 +202,7 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab { m_usePartTargets = false; m_partTargets.clear(); + m_partsSignature = 0; } if( m_isVisible <= 0 || !geomRes ) @@ -279,6 +281,25 @@ int InstancedMeshLod( const TriGeometryResMeshData& meshData, float screenSize ) return int( lodCount ) - 1; } +// FNV-1a over each part's geometry and transform: equal for the same parts list +uint64_t PartsSignature( const std::vector& parts ) +{ + uint64_t hash = 1469598103934665603ull; + auto mix = [&hash]( const void* data, size_t size ) { + const auto* bytes = static_cast( data ); + for( size_t i = 0; i < size; ++i ) + { + hash = ( hash ^ bytes[i] ) * 1099511628211ull; + } + }; + for( const auto& part : parts ) + { + mix( &part.geometry, sizeof( part.geometry ) ); + mix( &part.childToObject, sizeof( part.childToObject ) ); + } + return hash ? hash : 1; +} + float MaxAxisScale( const Matrix& m ) { return std::sqrt( std::max( { LengthSq( Vector3( m._11, m._12, m._13 ) ), LengthSq( Vector3( m._21, m._22, m._23 ) ), LengthSq( Vector3( m._31, m._32, m._33 ) ) } ) ); @@ -302,73 +323,74 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r return; } - for( auto& target : m_partTargets ) + const uint64_t signature = PartsSignature( parts ); + if( signature != m_partsSignature ) { - target.seen = false; - } + // broad phase: the parts whose bounds the decal volume touches, in object space + Vector3 decalMin( -1.f, -1.f, -1.f ); + Vector3 decalMax( 1.f, 1.f, 1.f ); + BoundingBoxTransform( decalMin, decalMax, m_decalMatrix ); - for( const auto& part : parts ) - { - TriGeometryRes* geometry = part.geometry; - if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) - { - continue; - } - TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); - if( !meshData ) + std::vector previous = std::move( m_partTargets ); + m_partTargets.clear(); + for( const auto& part : parts ) { - continue; - } + TriGeometryRes* geometry = part.geometry; + if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) + { + continue; + } + TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); + if( !meshData ) + { + continue; + } + Vector3 partMin = meshData->m_minBounds; + Vector3 partMax = meshData->m_maxBounds; + BoundingBoxTransform( partMin, partMax, part.childToObject ); + if( decalMin.x > partMax.x || decalMax.x < partMin.x || decalMin.y > partMax.y || decalMax.y < partMin.y || decalMin.z > partMax.z || decalMax.z < partMin.z ) + { + continue; + } + + // a part already targeted keeps its built geometry + auto kept = std::find_if( previous.begin(), previous.end(), [&]( const PartTarget& target ) { + return target.geometry == geometry && target.childToObject == part.childToObject; + } ); + if( kept != previous.end() ) + { + m_partTargets.push_back( std::move( *kept ) ); + previous.erase( kept ); + continue; + } - auto found = std::find_if( m_partTargets.begin(), m_partTargets.end(), [&]( const PartTarget& target ) { - return !target.seen && target.geometry == geometry && target.childToObject == part.childToObject; - } ); - if( found == m_partTargets.end() ) - { PartTarget target; target.geometry = geometry; target.childToObject = part.childToObject; // part vertices are in part space; the decal volume lives in object space target.decalMatrix = m_decalMatrix * Inverse( part.childToObject ); target.inverseDecalMatrix = Inverse( target.decalMatrix ); - - // cheap reject: does the decal volume touch the part's bounds at all? - Vector3 decalMin( -1.f, -1.f, -1.f ); - Vector3 decalMax( 1.f, 1.f, 1.f ); - BoundingBoxTransform( decalMin, decalMax, target.decalMatrix ); - target.overlaps = decalMin.x <= meshData->m_maxBounds.x && decalMax.x >= meshData->m_minBounds.x && - decalMin.y <= meshData->m_maxBounds.y && decalMax.y >= meshData->m_minBounds.y && - decalMin.z <= meshData->m_maxBounds.z && decalMax.z >= meshData->m_minBounds.z; - Vector3 boundsCenter = ( meshData->m_minBounds + meshData->m_maxBounds ) * 0.5f; target.lodRadius = Length( meshData->m_maxBounds - meshData->m_minBounds ) * 0.5f + Length( boundsCenter ); // fallback before the first visibility update: scale the object's screen size by the part's size if( objectRadius > 0.f ) { - const Matrix& m = part.childToObject; - float scale = std::max( { Length( Vector3( m._11, m._12, m._13 ) ), - Length( Vector3( m._21, m._22, m._23 ) ), - Length( Vector3( m._31, m._32, m._33 ) ) } ); - target.screenSizeScale = meshData->m_boundingSphere.w * scale / objectRadius; + target.screenSizeScale = meshData->m_boundingSphere.w * MaxAxisScale( part.childToObject ) / objectRadius; } m_partTargets.push_back( std::move( target ) ); - found = m_partTargets.end() - 1; - } - found->seen = true; - - if( !found->overlaps ) - { - continue; } + m_partsSignature = signature; + } - if( !found->decalGeometry || found->decalGeometry->m_lodMask != meshData->m_lodMask ) + for( auto& target : m_partTargets ) + { + TriGeometryResMeshData* meshData = target.geometry->IsGood() ? target.geometry->GetMeshData( 0 ) : nullptr; + if( meshData && ( !target.decalGeometry || target.decalGeometry->m_lodMask != meshData->m_lodMask ) ) { - found->decalGeometry = BuildDecalGeometryCached( meshData, found->decalMatrix, found->inverseDecalMatrix ); + target.decalGeometry = BuildDecalGeometryCached( meshData, target.decalMatrix, target.inverseDecalMatrix ); } } - m_partTargets.erase( std::remove_if( m_partTargets.begin(), m_partTargets.end(), []( const PartTarget& target ) { return !target.seen; } ), m_partTargets.end() ); - bool anyVisible = false; for( auto& target : m_partTargets ) { diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 8fb7cd245..44184f986 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -260,10 +260,11 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // radius of the part's bounds about its own origin, as the instanced mesh manager sizes it for LOD float lodRadius = 0.f; int lodIndex = -1; - bool overlaps = false; - bool seen = false; }; + // the parts the decal volume overlaps, from the broad phase of the parts list m_partsSignature names std::vector m_partTargets; + // hash of the parts list m_partTargets was built from; 0 when they must be rebuilt + uint64_t m_partsSignature = 0; // the camera of the last visibility update: part LODs and the depth pull are taken from it TriFrustum m_lastFrustum; float m_lastInvLodFactor = 1.f; From 30db885334ea17c33926cd5c0a794ff65b7fb3a3 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:20:45 +0000 Subject: [PATCH 13/19] Report decal triangle cache memory in the statistics The CPU triangle caches (about 30 bytes per triangle, so ~100 MB for a 3.7M-triangle mesh) were invisible to memory statistics. Each cache now adds its size to the new Trinity/decalTriangleCacheBytes statistic (CST_MEMORY) when Get first hands it out ready, and takes it off again when it is destroyed with its geometry. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 22 ++++++++++++++++++- .../Attachments/EveDecalTriangleCache.h | 5 +++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index ef3425524..cd99fc8b0 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -7,6 +7,8 @@ #include "TbbStub.h" #include +CCP_STATS_DECLARE( decalTriangleCacheBytes, "Trinity/decalTriangleCacheBytes", false, CST_MEMORY, "Memory of the CPU triangle caches runtime decals build their geometry from." ); + namespace { // average number of triangles per cell the finest grid level aims for @@ -210,7 +212,17 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD } if( cache && !cache->failed && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) { - return cache->ready.load( std::memory_order_acquire ) ? cache.get() : nullptr; + if( !cache->ready.load( std::memory_order_acquire ) ) + { + return nullptr; + } + if( cache->reportedBytes.load() == 0 ) + { + int64_t bytes = int64_t( cache->GetMemoryUsage() ); + cache->reportedBytes.store( bytes ); + CCP_STATS_ADD( decalTriangleCacheBytes, bytes ); + } + return cache.get(); } TRINITY_STATS_ZONE( __FUNCTION__ ); @@ -576,6 +588,14 @@ bool DecalTriangleCache::FindNearestSurface( size_t lodIndex, const Vector3& poi return found; } +DecalTriangleCache::~DecalTriangleCache() +{ + if( int64_t bytes = reportedBytes.load() ) + { + CCP_STATS_ADD( decalTriangleCacheBytes, -bytes ); + } +} + size_t DecalTriangleCache::GetMemoryUsage() const { size_t bytes = sizeof( *this ); diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 6af7cb912..2ddaea81f 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -18,6 +18,7 @@ * finishes, Get returns null and the decal tries again on a later frame. The cache is owned by the mesh's TriGeometryResMeshData, * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. + * Its memory is reported as Trinity/decalTriangleCacheBytes. */ struct DecalTriangleCache { @@ -49,6 +50,10 @@ struct DecalTriangleCache bool failed = false; uint32_t failures = 0; std::chrono::steady_clock::time_point retryAt; + // bytes added to the Trinity/decalTriangleCacheBytes statistic, taken off again on destruction + std::atomic reportedBytes = 0; + + ~DecalTriangleCache(); /** * @brief Returns the cache for meshData, starting to build it if needed. From da60928dec76de0eef60c8e9c2ed8a50fd5e7ac9 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:22:23 +0000 Subject: [PATCH 14/19] Add decal growScale: animate the drawn volume without rebuilds A change to position, rotation or scaling rebuilds a runtime decal's geometry (and its part targets), so a curve animating scaling, such as a scratch growing over its first 0.2 s, rebuilt it every frame. The new growScale attribute (per axis, 0..1, default 1) shrinks only the volume the decal is drawn in: its geometry stays built for the full scaling, the shader gets the drawn matrices, and the decal texture's bordered sampler shows nothing outside them. Changing growScale only recomputes those matrices; each axis is held at 1e-4 or more so a grow from 0 stays invertible. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 22 ++++++++++++++++--- .../Attachments/EveSpaceObjectDecal.h | 7 ++++++ .../Attachments/EveSpaceObjectDecal_Blue.cpp | 7 ++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 3c683feec..ad640ad98 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -74,6 +74,16 @@ void EveSpaceObjectDecal::UpdateDecalMatrix() m_decalMatrix = TransformationMatrix( m_scaling, m_rotation, m_position ); // and calc the inverse right away, is needed for intersection m_inverseDecalMatrix = Inverse( m_decalMatrix ); + UpdateDrawDecalMatrix(); +} + +void EveSpaceObjectDecal::UpdateDrawDecalMatrix() +{ + // a grow from 0 must not make the drawn volume singular + constexpr float MIN_GROW = 1e-4f; + Vector3 grow( std::max( m_growScale.x, MIN_GROW ), std::max( m_growScale.y, MIN_GROW ), std::max( m_growScale.z, MIN_GROW ) ); + m_drawDecalMatrix = ScalingMatrix( grow ) * m_decalMatrix; + m_drawInverseDecalMatrix = Inverse( m_drawDecalMatrix ); } // ------------------------------------------------------------------------------------------------------ @@ -102,6 +112,11 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) m_partTargets.clear(); m_partsSignature = 0; } + else if( IsMatch( value, m_growScale ) ) + { + // the geometry stays built for the full volume; only what is drawn of it changes + UpdateDrawDecalMatrix(); + } return true; } @@ -368,7 +383,8 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r target.geometry = geometry; target.childToObject = part.childToObject; // part vertices are in part space; the decal volume lives in object space - target.decalMatrix = m_decalMatrix * Inverse( part.childToObject ); + target.objectToPart = Inverse( part.childToObject ); + target.decalMatrix = m_decalMatrix * target.objectToPart; target.inverseDecalMatrix = Inverse( target.decalMatrix ); Vector3 boundsCenter = ( meshData->m_minBounds + meshData->m_maxBounds ) * 0.5f; target.lodRadius = Length( meshData->m_maxBounds - meshData->m_minBounds ) * 0.5f + Length( boundsCenter ); @@ -503,7 +519,7 @@ void EveSpaceObjectDecal::GetBatches( ITriRenderBatchAccumulator* batches, float pull = std::clamp( PART_DEPTH_ULPS * magnitude * FLOAT_STEP / nearest, PART_DEPTH_PULL_MIN, PART_DEPTH_PULL_MAX ); world = world * TranslationMatrix( -eye ) * ScalingMatrix( 1.f - pull, 1.f - pull, 1.f - pull ) * TranslationMatrix( eye ); } - FillPerObjectData( *partData, world, target.decalMatrix, target.inverseDecalMatrix, IdentityMatrix() ); + FillPerObjectData( *partData, world, m_drawDecalMatrix * target.objectToPart, target.childToObject * m_drawInverseDecalMatrix, IdentityMatrix() ); CommitBatch( batches, lod, *target.decalGeometry, target.lodIndex, partData ); } return; @@ -604,7 +620,7 @@ Tr2PerObjectData* EveSpaceObjectDecal::GetPerObjectData( ITriRenderBatchAccumula return NULL; } - FillPerObjectData( *perObjectData, m_parentData.transform, m_decalMatrix, m_inverseDecalMatrix, m_parentBoneMatrix ); + FillPerObjectData( *perObjectData, m_parentData.transform, m_drawDecalMatrix, m_drawInverseDecalMatrix, m_parentBoneMatrix ); return perObjectData; } diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 44184f986..6a4aab7b9 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -188,6 +188,7 @@ BLUE_CLASS( EveSpaceObjectDecal ) : void CommitBatch( ITriRenderBatchAccumulator * batches, const TriGeometryResLodData* lod, const MeshDecalData& decalGeometry, int lodIndex, const Tr2PerObjectData* perObjectData ); // update void UpdateDecalMatrix(); + void UpdateDrawDecalMatrix(); void CreateStaticIndexBuffers( TriGeometryResPtr geomRes ); bool HasStaticIndexBuffers() const; @@ -218,6 +219,11 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // matrices representing the "volume" of the decal projection Matrix m_decalMatrix; Matrix m_inverseDecalMatrix; + // per-axis share (0..1) of that volume the decal draws in: animating it rebuilds no geometry + Vector3 m_growScale = Vector3( 1.f, 1.f, 1.f ); + // the drawn volume: m_decalMatrix with m_growScale applied in decal space + Matrix m_drawDecalMatrix; + Matrix m_drawInverseDecalMatrix; // base mesh geometry TriGeometryResPtr m_baseGeometryResource; @@ -254,6 +260,7 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // the decal volume expressed in the part's vertex space Matrix decalMatrix; Matrix inverseDecalMatrix; + Matrix objectToPart; // owned here rather than cached on the (shared) mesh data: runtime decals come and go std::shared_ptr decalGeometry; float screenSizeScale = 1.f; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp index 5c36c014e..ea8a2c93c 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal_Blue.cpp @@ -21,6 +21,13 @@ const Be::ClassInfo* EveSpaceObjectDecal::ExposeToBlue() MAP_ATTRIBUTE( "position", m_position, "center of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ) MAP_ATTRIBUTE( "rotation", m_rotation, "orientation of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ); MAP_ATTRIBUTE( "scaling", m_scaling, "size of decal", Be::READWRITE | Be::NOTIFY | Be::PERSIST ); + MAP_ATTRIBUTE( + "growScale", + m_growScale, + "Per-axis share (0..1) of the volume scaling sets that the decal draws in. Animating it costs no geometry " + "rebuild, unlike scaling: the decal's geometry stays built for the full volume and the shader shows nothing " + "outside the drawn one.", + Be::READWRITE | Be::NOTIFY | Be::PERSIST ); MAP_ATTRIBUTE( "parentBoneIndex", m_parentBoneIndex, "the bone index this decal is tight to (-1 to disable)", Be::READWRITE | Be::PERSIST ); MAP_ATTRIBUTE( "minScreenSize", m_minScreenSize, "min size on screen in pixels before the decal is LODed out", Be::READWRITE | Be::PERSIST ) From bfc34dba4ef8b6ded88c9952ddc07827b4da23a9 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 13:23:42 +0000 Subject: [PATCH 15/19] Tell a building geometry cache from nothing in reach GetNearestHullEdge and GetNearestSurfacePoint answered "not found" both when nothing lies within the radius and when a part in reach was still building its triangle cache (or held back by the build cap or a readback backoff), so callers could not tell "give up" from "ask again". QueryNearestHullEdge and QueryNearestSurfacePoint return (status, (position, normal)) with status 0 found, 1 none in reach (every part in reach searched), 2 pending. The Get variants keep their (found, (position, normal)) results on top of them. Co-Authored-By: Claude Opus 5.5 --- trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 30 +++++++++++++++---- trinity/Eve/SpaceObject/EveSpaceObject2.h | 24 ++++++++++++++- .../Eve/SpaceObject/EveSpaceObject2_Blue.cpp | 16 ++++++++++ 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index 6ef3f0ad6..c74072f97 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -2836,7 +2836,7 @@ bool EveSpaceObject2::GetDamageLocatorBindPosition( int index, Vector3& out ) co } template -std::pair> EveSpaceObject2::FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ) +std::pair> EveSpaceObject2::FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ) { std::vector parts; std::vector areas; @@ -2853,6 +2853,7 @@ std::pair> EveSpaceObject2::FindNearestOnGeome } bool found = false; + bool pending = false; float bestDistance = radius; Vector3 bestPosition = position; Vector3 bestNormal( 0.f, 0.f, 0.f ); @@ -2861,6 +2862,7 @@ std::pair> EveSpaceObject2::FindNearestOnGeome TriGeometryRes* geometry = part.geometry; if( !geometry || !geometry->IsGood() || !geometry->GetMeshCount() ) { + pending = pending || ( geometry && !geometry->IsGood() ); continue; } TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); @@ -2887,6 +2889,7 @@ std::pair> EveSpaceObject2::FindNearestOnGeome const DecalTriangleCache* cache = DecalTriangleCache::Get( meshData ); if( !cache ) { + pending = true; continue; } Vector3 partPosition, partNormal; @@ -2906,23 +2909,38 @@ std::pair> EveSpaceObject2::FindNearestOnGeome bestNormal = Normalize( Vector3( XMVector3TransformNormal( partNormal, Transpose( objectToPart ) ) ) ); } } - return std::make_pair( found, std::make_pair( bestPosition, bestNormal ) ); + GeometryQueryStatus status = found ? GeometryQueryStatus::FOUND : pending ? GeometryQueryStatus::PENDING : GeometryQueryStatus::NONE; + return std::make_pair( status, std::make_pair( bestPosition, bestNormal ) ); } -std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +std::pair> EveSpaceObject2::QueryNearestHullEdge( const Vector3& position, float radius ) { // cosine of the fold, between two faces' normals, that counts as an edge constexpr float SHARP_EDGE_COS = 0.866f; - return FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + auto result = FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { return cache.FindNearestEdge( 0, point, r, SHARP_EDGE_COS, outPosition, outNormal, outDistance ); } ); + return std::make_pair( int( result.first ), result.second ); } -std::pair> EveSpaceObject2::GetNearestSurfacePoint( const Vector3& position, float radius ) +std::pair> EveSpaceObject2::QueryNearestSurfacePoint( const Vector3& position, float radius ) { - return FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { + auto result = FindNearestOnGeometry( position, radius, [&]( const DecalTriangleCache& cache, const Vector3& point, float r, Vector3& outPosition, Vector3& outNormal, float& outDistance ) { return cache.FindNearestSurface( 0, point, r, outPosition, outNormal, outDistance ); } ); + return std::make_pair( int( result.first ), result.second ); +} + +std::pair> EveSpaceObject2::GetNearestHullEdge( const Vector3& position, float radius ) +{ + auto result = QueryNearestHullEdge( position, radius ); + return std::make_pair( result.first == int( GeometryQueryStatus::FOUND ), result.second ); +} + +std::pair> EveSpaceObject2::GetNearestSurfacePoint( const Vector3& position, float radius ) +{ + auto result = QueryNearestSurfacePoint( position, radius ); + return std::make_pair( result.first == int( GeometryQueryStatus::FOUND ), result.second ); } Vector3 EveSpaceObject2::GetLocatorPositionFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ) diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.h b/trinity/Eve/SpaceObject/EveSpaceObject2.h index 9f39618f4..3df4f1522 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.h +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.h @@ -532,10 +532,32 @@ BLUE_CLASS( EveSpaceObject2 ) : */ std::pair> GetNearestSurfacePoint( const Vector3& position, float radius ); + // Status of QueryNearestHullEdge and QueryNearestSurfacePoint + enum class GeometryQueryStatus : int + { + FOUND = 0, + // nothing within the radius, and every part in reach was searched + NONE = 1, + // nothing found yet: a part in reach is still building its triangle cache, ask again later + PENDING = 2, + }; + + /** + * @brief GetNearestHullEdge, telling a part still building its triangle cache from nothing in reach. + * @return (status, (position, normal)), status a GeometryQueryStatus. + */ + std::pair> QueryNearestHullEdge( const Vector3& position, float radius ); + + /** + * @brief GetNearestSurfacePoint, telling a part still building its triangle cache from nothing in reach. + * @return (status, (position, normal)), status a GeometryQueryStatus. + */ + std::pair> QueryNearestSurfacePoint( const Vector3& position, float radius ); + private: // The nearest of query( cache, part-space point, part-space radius ) over the object's own geometry template - std::pair> FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ); + std::pair> FindNearestOnGeometry( const Vector3& position, float radius, Query&& query ); public: Vector3 GetLocatorRotationFromSet( int index, bool inWorldSpace, BlueSharedString locatorSetName ); diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp index bce922ab3..d24ff77c6 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2_Blue.cpp @@ -557,6 +557,22 @@ const Be::ClassInfo* EveSpaceObject2::ExposeToBlue() "Not found while the geometry's triangle cache is still being built.\n" ":param position: object-space point\n" ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "QueryNearestHullEdge", + QueryNearestHullEdge, + "( position, radius ) -> ( status, ( position, normal ) )\n" + "GetNearestHullEdge with a status: 0 found, 1 nothing within radius (every part in reach searched), " + "2 pending (a part in reach is still building its triangle cache; ask again on a later frame).\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) + MAP_METHOD_AND_WRAP( + "QueryNearestSurfacePoint", + QueryNearestSurfacePoint, + "( position, radius ) -> ( status, ( position, normal ) )\n" + "GetNearestSurfacePoint with a status: 0 found, 1 nothing within radius (every part in reach searched), " + "2 pending (a part in reach is still building its triangle cache; ask again on a later frame).\n" + ":param position: object-space point\n" + ":param radius: search radius in metres\n" ) MAP_METHOD_AND_WRAP( "GetNearestSurfacePoint", GetNearestSurfacePoint, From 7c7560ac65901f4f3d5c4e9c5f49f9b6cb6e848e Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 14:24:26 +0000 Subject: [PATCH 16/19] Free decal triangle caches nothing has used for a minute A mesh's triangle cache lived as long as the mesh: ~30 bytes per triangle, ~109 MB for a 3.66 M-triangle level piece, kept after the ship had left it. Get (behind every decal build and every GetNearest*/QueryNearest* call) now stamps the cache's last use. Once a second, from Tr2Renderer::EndFrame, ReleaseIdle frees the triangles of every ready cache unused for 60 s, takes its bytes off Trinity/decalTriangleCacheBytes and marks it released, so the next Get rebuilds it. A minute covers the gaps of a collision burst (a grind calls Get every metre, a ship bumping around a piece returns within seconds), so those don't pay a rebuild (a readback of tens of ms plus about a second of build). The caches built are tracked in a small main-thread list of weak pointers, so a cache released with its mesh just drops out and no mesh is reached through it. A cache still building is never touched (its task owns it until ready), and a failed readback, which holds no triangles, keeps its backoff. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 53 ++++++++++++++++++- .../Attachments/EveDecalTriangleCache.h | 13 ++++- trinity/Tr2Renderer.cpp | 2 + 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index cd99fc8b0..f56835305 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -20,6 +20,20 @@ constexpr int MAX_CONCURRENT_BUILDS = 2; // after a failed readback, wait this long before the next, doubling up to the cap constexpr std::chrono::seconds RETRY_BACKOFF_FIRST( 2 ); constexpr std::chrono::seconds RETRY_BACKOFF_MAX( 60 ); +// A cache unused this long has its triangles freed. Collisions come in bursts: a grind calls Get every +// metre, and a ship bumping around one level piece comes back to it within seconds, so a minute keeps +// those from paying a rebuild (a readback of tens of ms plus about a second of build) while a ship +// that has moved on gives the memory (~30 bytes per triangle) back. +constexpr std::chrono::seconds IDLE_RELEASE( 60 ); +constexpr std::chrono::seconds IDLE_SWEEP_INTERVAL( 1 ); + +// caches built so far, for ReleaseIdle; main thread only. Weak, so a mesh released with its cache +// leaves no dangling entry, and no mesh is ever reached through it. +std::vector>& GetCacheRegistry() +{ + static std::vector>* registry = new std::vector>(); + return *registry; +} struct BuildQueue { @@ -210,12 +224,13 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD { return nullptr; } - if( cache && !cache->failed && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) + if( cache && !cache->failed && !cache->released && cache->lodMask == meshData->m_lodMask && cache->lods.size() == meshData->m_lods.size() ) { if( !cache->ready.load( std::memory_order_acquire ) ) { return nullptr; } + cache->lastUsed = now; if( cache->reportedBytes.load() == 0 ) { int64_t bytes = int64_t( cache->GetMemoryUsage() ); @@ -271,7 +286,9 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD auto newCache = std::make_shared(); newCache->lodMask = meshData->m_lodMask; newCache->lods.resize( meshData->m_lods.size() ); + newCache->lastUsed = now; cache = newCache; + GetCacheRegistry().push_back( newCache ); // the task only touches its own copies, so the mesh may be released while it runs ++queue.inFlight; @@ -588,6 +605,40 @@ bool DecalTriangleCache::FindNearestSurface( size_t lodIndex, const Vector3& poi return found; } +void DecalTriangleCache::ReleaseIdle() +{ + static std::chrono::steady_clock::time_point nextSweep; + const auto now = std::chrono::steady_clock::now(); + if( now < nextSweep ) + { + return; + } + nextSweep = now + IDLE_SWEEP_INTERVAL; + + auto& registry = GetCacheRegistry(); + registry.erase( std::remove_if( registry.begin(), registry.end(), [&]( const std::weak_ptr& entry ) { + auto cache = entry.lock(); + if( !cache ) + { + return true; + } + // a cache still building belongs to its task until it is ready: leave it alone + if( !cache->ready.load( std::memory_order_acquire ) || now - cache->lastUsed < IDLE_RELEASE ) + { + return false; + } + std::vector().swap( cache->lods ); + cache->released = true; + cache->ready.store( false, std::memory_order_release ); + if( int64_t bytes = cache->reportedBytes.exchange( 0 ) ) + { + CCP_STATS_ADD( decalTriangleCacheBytes, -bytes ); + } + return true; + } ), + registry.end() ); +} + DecalTriangleCache::~DecalTriangleCache() { if( int64_t bytes = reportedBytes.load() ) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 2ddaea81f..4ecd26149 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -18,7 +18,8 @@ * finishes, Get returns null and the decal tries again on a later frame. The cache is owned by the mesh's TriGeometryResMeshData, * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. - * Its memory is reported as Trinity/decalTriangleCacheBytes. + * Its memory is reported as Trinity/decalTriangleCacheBytes. A ready cache that Get has not handed out + * for IDLE_RELEASE has its triangles freed by ReleaseIdle; the next Get against the mesh rebuilds it. */ struct DecalTriangleCache { @@ -52,6 +53,10 @@ struct DecalTriangleCache std::chrono::steady_clock::time_point retryAt; // bytes added to the Trinity/decalTriangleCacheBytes statistic, taken off again on destruction std::atomic reportedBytes = 0; + // when Get last handed this cache out; ReleaseIdle frees the triangles of a cache idle too long + std::chrono::steady_clock::time_point lastUsed; + // ReleaseIdle freed the triangles: Get rebuilds the cache + bool released = false; ~DecalTriangleCache(); @@ -67,6 +72,12 @@ struct DecalTriangleCache */ static void Shutdown(); + /** + * @brief Frees the triangles of every ready cache Get has not handed out for IDLE_RELEASE. Called once + * a frame on the main thread (Tr2Renderer::EndFrame); does its work at most once a second. + */ + static void ReleaseIdle(); + /** * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. * @param aabbMin, aabbMax Bounds of the decal volume in the mesh's vertex space. diff --git a/trinity/Tr2Renderer.cpp b/trinity/Tr2Renderer.cpp index ce62db5a4..4abf37d2e 100644 --- a/trinity/Tr2Renderer.cpp +++ b/trinity/Tr2Renderer.cpp @@ -1057,6 +1057,8 @@ void Tr2Renderer::BeginFrame() void Tr2Renderer::EndFrame() { + DecalTriangleCache::ReleaseIdle(); + if( s_debugTextRenderer ) { s_debugTextRenderer->Clear(); From 5ded55e4283b422c31a02405b6075168daa54b22 Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 14:33:54 +0000 Subject: [PATCH 17/19] Keep a runtime decal's geometry while its volume stays inside Any change to a runtime decal's position, rotation or scaling threw its geometry and part targets away and rebuilt them. Now, when the new volume lies inside the one the geometry was built for (all eight corners within it), the geometry and targets are kept and only the drawn matrices change: every triangle the new volume touches is already in the built geometry, and the decal texture's bordered sampler shows nothing outside the drawn volume. A volume that leaves the built one rebuilds as before, and every rebuild records the volume it was built from. Baked decals are unchanged; growScale remains the way to animate growth without rebuilds. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveSpaceObjectDecal.cpp | 45 +++++++++++++++++++ .../Attachments/EveSpaceObjectDecal.h | 4 ++ 2 files changed, 49 insertions(+) diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index ad640ad98..1ec4da8c6 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -86,10 +86,31 @@ void EveSpaceObjectDecal::UpdateDrawDecalMatrix() m_drawInverseDecalMatrix = Inverse( m_drawDecalMatrix ); } +namespace +{ +// Whether the volume decalMatrix maps [-1, 1]^3 to lies inside the one builtInverse maps back to it +bool IsVolumeInside( const Matrix& decalMatrix, const Matrix& builtInverse ) +{ + constexpr float SLACK = 1e-3f; + Matrix toBuilt = decalMatrix * builtInverse; + for( int corner = 0; corner < 8; ++corner ) + { + Vector3 p( corner & 1 ? 1.f : -1.f, corner & 2 ? 1.f : -1.f, corner & 4 ? 1.f : -1.f ); + Vector3 q = XMVector3TransformCoord( p, toBuilt ); + if( std::abs( q.x ) > 1.f + SLACK || std::abs( q.y ) > 1.f + SLACK || std::abs( q.z ) > 1.f + SLACK ) + { + return false; + } + } + return true; +} +} + // ------------------------------------------------------------------------------------------------------ bool EveSpaceObjectDecal::Initialize() { UpdateDecalMatrix(); + m_builtInverseDecalMatrix = m_inverseDecalMatrix; PrepareResources(); @@ -103,6 +124,13 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) { // update the decal matrix UpdateDecalMatrix(); + if( !HasStaticIndexBuffers() && HasBuiltRuntimeGeometry() && IsVolumeInside( m_decalMatrix, m_builtInverseDecalMatrix ) ) + { + // every triangle the new volume touches is in the built geometry already, and the shader + // shows nothing outside the drawn volume: only the drawn matrices change + return true; + } + m_builtInverseDecalMatrix = m_inverseDecalMatrix; // and rebuild the index buffer, cause decal volume has changed size and might hit new triangles if( !HasStaticIndexBuffers() ) { @@ -120,6 +148,19 @@ bool EveSpaceObjectDecal::OnModified( Be::Var* value ) return true; } +bool EveSpaceObjectDecal::HasBuiltRuntimeGeometry() const +{ + if( !m_usePartTargets ) + { + return m_decalGeometry != nullptr; + } + if( m_partTargets.empty() || !m_partsSignature ) + { + return false; + } + return std::all_of( m_partTargets.begin(), m_partTargets.end(), []( const PartTarget& target ) { return target.decalGeometry != nullptr; } ); +} + // ------------------------------------------------------------------------------------------------------ void EveSpaceObjectDecal::ReleaseResources( TriStorage ) { @@ -244,10 +285,12 @@ void EveSpaceObjectDecal::GetRenderables( std::vector& renderab { // runtime decal: owned here, never added to the mesh's shared decal cache (that cache only grows) m_decalGeometry = mesh && geomRes->IsGood() ? BuildDecalGeometryCached( mesh, m_decalMatrix, m_inverseDecalMatrix ) : nullptr; + m_builtInverseDecalMatrix = m_inverseDecalMatrix; } else if( g_buildDecalBuffers ) { CreateDecalIndexBuffers( geomRes, meshCache ); + m_builtInverseDecalMatrix = m_inverseDecalMatrix; } } @@ -379,6 +422,8 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r continue; } + // built from the current volume: a later volume must fit inside this one to keep the geometry + m_builtInverseDecalMatrix = m_inverseDecalMatrix; PartTarget target; target.geometry = geometry; target.childToObject = part.childToObject; diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h index 6a4aab7b9..f832d6d48 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.h @@ -224,6 +224,10 @@ BLUE_CLASS( EveSpaceObjectDecal ) : // the drawn volume: m_decalMatrix with m_growScale applied in decal space Matrix m_drawDecalMatrix; Matrix m_drawInverseDecalMatrix; + // inverse of the volume the runtime geometry was built for: a later volume inside it keeps the geometry + Matrix m_builtInverseDecalMatrix; + // m_decalGeometry or every part target holds geometry built from the decal volume + bool HasBuiltRuntimeGeometry() const; // base mesh geometry TriGeometryResPtr m_baseGeometryResource; From 9e13a6d5751062700fa4c641b0ed47eba9e498cd Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 14:35:20 +0000 Subject: [PATCH 18/19] Limit decal cache readbacks to one per frame, scale builds to cores The real cost of a first decal on a mesh is the main-thread GPU readback (tens of ms on a large mesh), not the background build, yet nothing bounded how many readbacks one frame could start; the build cap of two only indirectly limited them. Get now starts at most one readback per frame (the counter resets in DecalTriangleCache::EndFrame, which Tr2Renderer::EndFrame calls and which also runs the idle release), so first hits on several new meshes spread over frames. With that bound, the background build cap scales with the machine: a quarter of the hardware threads, at least two (eight on a 32-thread machine). Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 21 ++++++++++++++----- .../Attachments/EveDecalTriangleCache.h | 16 +++++++------- trinity/Tr2Renderer.cpp | 2 +- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index f56835305..051b95832 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -5,6 +5,7 @@ #include "Utilities/BoundingBox.h" #include "Shader/Tr2EffectStateManager.h" #include "TbbStub.h" +#include #include CCP_STATS_DECLARE( decalTriangleCacheBytes, "Trinity/decalTriangleCacheBytes", false, CST_MEMORY, "Memory of the CPU triangle caches runtime decals build their geometry from." ); @@ -15,8 +16,12 @@ namespace constexpr float TRIANGLES_PER_CELL = 4.f; constexpr uint32_t MAX_CELLS_PER_AXIS = 256; constexpr float MAX_CELLS = float( 1u << 21 ); -// grid builds in flight at once; a mesh asked for beyond that retries on a later frame -constexpr int MAX_CONCURRENT_BUILDS = 2; +// GPU readbacks a frame may start: each holds the main thread for tens of ms on a large mesh, so a +// burst of first hits on new meshes spreads over frames instead of stalling one +constexpr int MAX_READBACKS_PER_FRAME = 1; +// grid builds in flight at once, out of the hardware threads; a mesh asked for beyond that retries later +constexpr unsigned BUILD_THREADS_SHARE = 4; +constexpr int MIN_CONCURRENT_BUILDS = 2; // after a failed readback, wait this long before the next, doubling up to the cap constexpr std::chrono::seconds RETRY_BACKOFF_FIRST( 2 ); constexpr std::chrono::seconds RETRY_BACKOFF_MAX( 60 ); @@ -27,7 +32,7 @@ constexpr std::chrono::seconds RETRY_BACKOFF_MAX( 60 ); constexpr std::chrono::seconds IDLE_RELEASE( 60 ); constexpr std::chrono::seconds IDLE_SWEEP_INTERVAL( 1 ); -// caches built so far, for ReleaseIdle; main thread only. Weak, so a mesh released with its cache +// caches built so far, for EndFrame's idle release; main thread only. Weak, so a mesh released with its cache // leaves no dangling entry, and no mesh is ever reached through it. std::vector>& GetCacheRegistry() { @@ -40,6 +45,9 @@ struct BuildQueue Tr2ParallelTaskGroup group; std::atomic inFlight = 0; std::atomic shutDown = false; + const int maxInFlight = std::max( MIN_CONCURRENT_BUILDS, int( std::thread::hardware_concurrency() / BUILD_THREADS_SHARE ) ); + // main thread only + int readbacksThisFrame = 0; }; // never destroyed: Shutdown drains it, and tearing a task group down during static destruction is unsafe @@ -243,7 +251,7 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD TRINITY_STATS_ZONE( __FUNCTION__ ); BuildQueue& queue = GetBuildQueue(); - if( queue.shutDown.load() || queue.inFlight.load() >= MAX_CONCURRENT_BUILDS ) + if( queue.shutDown.load() || queue.inFlight.load() >= queue.maxInFlight || queue.readbacksThisFrame >= MAX_READBACKS_PER_FRAME ) { return nullptr; } @@ -266,6 +274,7 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD } } + ++queue.readbacksThisFrame; std::vector raw( meshData->m_lods.size() ); for( size_t i = 0; i < meshData->m_lods.size(); ++i ) { @@ -605,8 +614,10 @@ bool DecalTriangleCache::FindNearestSurface( size_t lodIndex, const Vector3& poi return found; } -void DecalTriangleCache::ReleaseIdle() +void DecalTriangleCache::EndFrame() { + GetBuildQueue().readbacksThisFrame = 0; + static std::chrono::steady_clock::time_point nextSweep; const auto now = std::chrono::steady_clock::now(); if( now < nextSweep ) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index 4ecd26149..b29f33945 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -14,12 +14,13 @@ * least as large as the triangle; a query looks at every level with its box grown by half a cell there. * * The first runtime decal build against a mesh reads the mesh back from the GPU on the main thread and - * builds the grid as a task in a shared task group, at most MAX_CONCURRENT_BUILDS at a time; until that + * builds the grid as a task in a shared task group. A frame does at most one readback (tens of ms on a + * large mesh) and a quarter of the hardware threads (at least two) build at once; until its build * finishes, Get returns null and the decal tries again on a later frame. The cache is owned by the mesh's TriGeometryResMeshData, * so it is released together with the geometry (TriGeometryRes::ReleaseResources clears the mesh data on * release, re-initialization and reload). It is also rebuilt if the mesh's LOD set no longer matches. * Its memory is reported as Trinity/decalTriangleCacheBytes. A ready cache that Get has not handed out - * for IDLE_RELEASE has its triangles freed by ReleaseIdle; the next Get against the mesh rebuilds it. + * for IDLE_RELEASE has its triangles freed by EndFrame; the next Get against the mesh rebuilds it. */ struct DecalTriangleCache { @@ -53,9 +54,9 @@ struct DecalTriangleCache std::chrono::steady_clock::time_point retryAt; // bytes added to the Trinity/decalTriangleCacheBytes statistic, taken off again on destruction std::atomic reportedBytes = 0; - // when Get last handed this cache out; ReleaseIdle frees the triangles of a cache idle too long + // when Get last handed this cache out; EndFrame frees the triangles of a cache idle too long std::chrono::steady_clock::time_point lastUsed; - // ReleaseIdle freed the triangles: Get rebuilds the cache + // EndFrame freed the triangles: Get rebuilds the cache bool released = false; ~DecalTriangleCache(); @@ -73,10 +74,11 @@ struct DecalTriangleCache static void Shutdown(); /** - * @brief Frees the triangles of every ready cache Get has not handed out for IDLE_RELEASE. Called once - * a frame on the main thread (Tr2Renderer::EndFrame); does its work at most once a second. + * @brief Called once a frame on the main thread (Tr2Renderer::EndFrame): opens the next frame's + * readback, and at most once a second frees the triangles of every ready cache Get has not handed + * out for IDLE_RELEASE. */ - static void ReleaseIdle(); + static void EndFrame(); /** * @brief Appends the indices of the triangles of LOD lodIndex that intersect the decal volume. diff --git a/trinity/Tr2Renderer.cpp b/trinity/Tr2Renderer.cpp index 4abf37d2e..46f823287 100644 --- a/trinity/Tr2Renderer.cpp +++ b/trinity/Tr2Renderer.cpp @@ -1057,7 +1057,7 @@ void Tr2Renderer::BeginFrame() void Tr2Renderer::EndFrame() { - DecalTriangleCache::ReleaseIdle(); + DecalTriangleCache::EndFrame(); if( s_debugTextRenderer ) { From a9142e0e926eb8df4d6f04edc9d1eca2977e308d Mon Sep 17 00:00:00 2001 From: Jonathan Dunn Date: Thu, 12 Nov 2026 14:39:03 +0000 Subject: [PATCH 19/19] Keep runtime decals and placement queries off animated parts Part decals are built from a part's rest-pose triangles and drawn with an identity parent bone, and the nearest-edge and nearest-surface queries read the same rest-pose positions. On a skinned or morphed part (an EveChildMesh can be either) the decal would stay behind as the part moved, and a query would answer with where the part is not. Such parts are now left out of the decal broad phase and of the queries (DecalTriangleCache::IsDeformed: any area of the mesh skinned or morphed). Creation hull parts and instanced level geometry are static and unaffected. Co-Authored-By: Claude Opus 5.5 --- .../Attachments/EveDecalTriangleCache.cpp | 15 +++++++++++++++ .../Attachments/EveDecalTriangleCache.h | 6 ++++++ .../Attachments/EveSpaceObjectDecal.cpp | 4 +++- trinity/Eve/SpaceObject/EveSpaceObject2.cpp | 3 ++- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp index 051b95832..1e4c5f07d 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.cpp @@ -316,6 +316,21 @@ const DecalTriangleCache* DecalTriangleCache::Get( TriGeometryResMeshData* meshD return nullptr; } +bool DecalTriangleCache::IsDeformed( const TriGeometryResMeshData& meshData ) +{ + for( const auto& lod : meshData.m_lods ) + { + for( const auto& area : lod->m_areas ) + { + if( area.m_isSkinned || area.m_isMorphed ) + { + return true; + } + } + } + return false; +} + void DecalTriangleCache::Shutdown() { BuildQueue& queue = GetBuildQueue(); diff --git a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h index b29f33945..1014e2454 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h +++ b/trinity/Eve/SpaceObject/Attachments/EveDecalTriangleCache.h @@ -67,6 +67,12 @@ struct DecalTriangleCache */ static const DecalTriangleCache* Get( TriGeometryResMeshData* meshData ); + /** + * @brief Whether any area of the mesh is skinned or morphed. Its vertices move away from the + * positions the cache holds, so a decal or a nearest query built on them would land wrong. + */ + static bool IsDeformed( const TriGeometryResMeshData& meshData ); + /** * @brief Cancels the builds that have not started and waits for the running ones. Get starts no * build afterwards. diff --git a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp index 1ec4da8c6..7f4362a0a 100644 --- a/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp +++ b/trinity/Eve/SpaceObject/Attachments/EveSpaceObjectDecal.cpp @@ -399,7 +399,9 @@ void EveSpaceObjectDecal::GetModularRenderables( std::vector& r continue; } TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); - if( !meshData ) + // a part's decal is drawn with an identity parent bone on its rest-pose triangles: an + // animated part would leave it behind + if( !meshData || DecalTriangleCache::IsDeformed( *meshData ) ) { continue; } diff --git a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp index c74072f97..8ee6ef433 100644 --- a/trinity/Eve/SpaceObject/EveSpaceObject2.cpp +++ b/trinity/Eve/SpaceObject/EveSpaceObject2.cpp @@ -2866,7 +2866,8 @@ std::pair> Eve continue; } TriGeometryResMeshData* meshData = geometry->GetMeshData( 0 ); - if( !meshData ) + // the cache holds rest-pose positions, which an animated part moves away from + if( !meshData || DecalTriangleCache::IsDeformed( *meshData ) ) { continue; }