Continued

This commit is contained in:
2026-06-04 00:06:18 -07:00
parent 8e9b4412ce
commit 5c11ff4fad
42 changed files with 1287 additions and 29 deletions
Binary file not shown.
+117
View File
@@ -0,0 +1,117 @@
fileFormatVersion: 2
guid: dd4de11cfd2910947b35819172869126
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
customData:
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
+148
View File
@@ -0,0 +1,148 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &3885353946372160549
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3572766465862231365}
- component: {fileID: 3909651526955663392}
- component: {fileID: 3320445911748035220}
- component: {fileID: 9053853372340598254}
- component: {fileID: 6834786618115927220}
- component: {fileID: 1794795016809289889}
m_Layer: 0
m_Name: Turret
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &3572766465862231365
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 2.5, y: 2.5, z: 2.5}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &3909651526955663392
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
m_Mesh: {fileID: 4300000, guid: abc00000000010690097314383055197, type: 3}
--- !u!23 &3320445911748035220
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
m_Enabled: 1
m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RayTracingAccelStructBuildFlagsOverride: 0
m_RayTracingAccelStructBuildFlags: 1
m_SmallMeshCulling: 1
m_ForceMeshLod: -1
m_MeshLodSelectionBias: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 175e5bfb2ad02704caa3d1753aad499d, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_GlobalIlluminationMeshLod: 0
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_MaskInteraction: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!114 &9053853372340598254
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: c16549610bfe4458aa9389201d072bb6, type: 3}
m_Name:
m_EditorClassIdentifier: Unity.Entities.Hybrid::Unity.Entities.Hybrid.Baking.LinkedEntityGroupAuthoring
--- !u!114 &6834786618115927220
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7c79d771cedb4794bf100ce60df5f764, type: 3}
m_Name:
m_EditorClassIdentifier: Unity.NetCode.Authoring.Hybrid::Unity.NetCode.GhostAuthoringComponent
HasOwner: 0
SupportAutoCommandTarget: 1
TrackInterpolationDelay: 0
GhostGroup: 0
UsePreSerialization: 0
UseSingleBaseline: 0
RollbackPredictedSpawnedGhostState: 0
RollbackPredictionOnStructuralChanges: 1
DefaultGhostMode: 0
SupportedGhostModes: 3
OptimizationMode: 0
Importance: 1
MaxSendRate: 0
prefabId:
--- !u!114 &1794795016809289889
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 3885353946372160549}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: dfb1e0820cbf41b4bbbe99066dfadd40, type: 3}
m_Name:
m_EditorClassIdentifier: ProjectM.Authoring::ProjectM.Authoring.TurretAuthoring
Range: 10
CooldownTicks: 30
Damage: 12
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5459c9edea89bd94fa6f5043ae00eb40
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 97bd1bd2a09697f449a5580826a0355d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,44 @@
using ProjectM.Simulation;
using Unity.Entities;
using UnityEngine;
namespace ProjectM.Authoring
{
/// <summary>
/// Authoring for the baked <see cref="StructureCatalog"/> singleton (the build cost/prefab table). For the
/// M6 foundation there is one buildable type (Turret), so the entry is flat fields — only the prefab
/// object-ref + cost amount need inspector wiring; the type + cost-resource are byte consts in the baker
/// (enum-via-MCP is unreliable, and bytes dodge the cross-assembly enum-in-Burst hazard). M7 generalizes to
/// an array; the runtime <see cref="StructureCatalogEntry"/> buffer is already the data-driven shape. Place
/// once in the gameplay subscene.
/// </summary>
public class StructureCatalogAuthoring : MonoBehaviour
{
[Tooltip("Turret structure ghost prefab (TurretAuthoring + GhostAuthoring).")]
public GameObject TurretPrefab;
[Tooltip("Ore cost to build a turret.")]
[Min(0)] public int TurretCostOre = 10;
private class StructureCatalogBaker : Baker<StructureCatalogAuthoring>
{
public override void Bake(StructureCatalogAuthoring authoring)
{
var entity = GetEntity(authoring, TransformUsageFlags.None);
AddComponent<StructureCatalog>(entity);
var buf = AddBuffer<StructureCatalogEntry>(entity);
if (authoring.TurretPrefab != null)
{
buf.Add(new StructureCatalogEntry
{
Type = StructureType.Turret,
Prefab = GetEntity(authoring.TurretPrefab, TransformUsageFlags.Dynamic),
CostResourceId = ResourceId.Ore,
CostAmount = authoring.TurretCostOre,
});
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 40093ed42072f5a4889f5f62f510aa27
@@ -0,0 +1,39 @@
using ProjectM.Simulation;
using Unity.Entities;
using UnityEngine;
namespace ProjectM.Authoring
{
/// <summary>
/// Authoring for the turret structure ghost prefab (duplicate UpgradePickup.prefab so the ownerless
/// interpolated GhostAuthoringComponent comes free). Bakes <see cref="PlacedStructure"/>{Type=Turret} +
/// <see cref="Turret"/> stats. BuildPlaceSystem stamps Cell + LastProcessedTick at placement.
/// </summary>
public class TurretAuthoring : MonoBehaviour
{
[Min(1f)] public float Range = 10f;
[Min(1)] public int CooldownTicks = 30;
[Min(1f)] public float Damage = 12f;
private class TurretBaker : Baker<TurretAuthoring>
{
public override void Bake(TurretAuthoring authoring)
{
var entity = GetEntity(authoring, TransformUsageFlags.Dynamic);
AddComponent(entity, new PlacedStructure
{
Type = StructureType.Turret,
Cell = default,
NextTick = 0u,
LastProcessedTick = 0u,
});
AddComponent(entity, new Turret
{
Range = authoring.Range,
CooldownTicks = authoring.CooldownTicks,
Damage = authoring.Damage,
});
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dfb1e0820cbf41b4bbbe99066dfadd40
@@ -28,6 +28,7 @@ namespace ProjectM.Authoring
});
AddComponent<ResourceLedger>(entity);
AddBuffer<StorageEntry>(entity);
AddComponent(entity, new GoalProgress { Charge = 0, Target = 10 });
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ef7d7956e34fb0d43a145bc4cfd425d0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,97 @@
using ProjectM.Simulation;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
namespace ProjectM.Client
{
/// <summary>
/// Client-only sender for build + upgrade RPCs. Keyboard: B builds a Turret at the local player's current
/// grid cell; U upgrades ability damage. Editor-only statics (PlaceStructure / PlaceTurret / UpgradeAbility)
/// drive the same path from execute_code for headless validation (a one-shot key can't be injected on an
/// unfocused editor — the StorageOpSendSystem idiom). Managed SystemBase (reads the Input System);
/// UnityEngine.InputSystem is fully qualified to avoid the ProjectM.Simulation.PlayerInput name collision.
/// The server re-validates legality + cost authoritatively; this only sends a hint.
/// </summary>
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)]
public partial class BuildSendSystem : SystemBase
{
#if UNITY_EDITOR
struct PendingBuild { public byte Type; public int CellX; public int CellZ; }
static readonly System.Collections.Generic.Queue<PendingBuild> s_PendingBuild =
new System.Collections.Generic.Queue<PendingBuild>();
static int s_PendingUpgrades = 0;
/// <summary>EDITOR / execute_code hook: queue a structure placement at a specific cell.</summary>
public static void PlaceStructure(byte type, int cellX, int cellZ) =>
s_PendingBuild.Enqueue(new PendingBuild { Type = type, CellX = cellX, CellZ = cellZ });
/// <summary>EDITOR / execute_code hook: queue a turret placement at a specific cell.</summary>
public static void PlaceTurret(int cellX, int cellZ) => PlaceStructure(StructureType.Turret, cellX, cellZ);
/// <summary>EDITOR / execute_code hook: queue an ability-damage upgrade.</summary>
public static void UpgradeAbility() => s_PendingUpgrades++;
#endif
protected override void OnCreate()
{
RequireForUpdate<NetworkId>();
}
protected override void OnUpdate()
{
if (!SystemAPI.TryGetSingletonEntity<NetworkId>(out var connection))
return;
var keyboard = UnityEngine.InputSystem.Keyboard.current;
if (keyboard != null)
{
if (keyboard.bKey.wasPressedThisFrame && TryGetLocalPlayerCell(out int2 cell))
SendBuild(connection, StructureType.Turret, cell.x, cell.y);
if (keyboard.uKey.wasPressedThisFrame)
SendUpgrade(connection);
}
#if UNITY_EDITOR
while (s_PendingBuild.Count > 0)
{
var b = s_PendingBuild.Dequeue();
SendBuild(connection, b.Type, b.CellX, b.CellZ);
}
while (s_PendingUpgrades > 0)
{
s_PendingUpgrades--;
SendUpgrade(connection);
}
#endif
}
bool TryGetLocalPlayerCell(out int2 cell)
{
cell = default;
if (!SystemAPI.TryGetSingleton<BaseAnchor>(out var anchor))
return false;
foreach (var xform in SystemAPI.Query<RefRO<LocalTransform>>().WithAll<GhostOwnerIsLocal, PlayerTag>())
{
cell = BaseGridMath.WorldToCell(anchor, xform.ValueRO.Position);
return true;
}
return false;
}
void SendBuild(Entity connection, byte type, int cellX, int cellZ)
{
var e = EntityManager.CreateEntity();
EntityManager.AddComponentData(e, new BuildPlaceRequest { StructureType = type, CellX = cellX, CellZ = cellZ });
EntityManager.AddComponentData(e, new SendRpcCommandRequest { TargetConnection = connection });
}
void SendUpgrade(Entity connection)
{
var e = EntityManager.CreateEntity();
EntityManager.AddComponentData(e, new AbilityUpgradeRequest());
EntityManager.AddComponentData(e, new SendRpcCommandRequest { TargetConnection = connection });
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 765356fd6c5e64c4e9ab588f99d3388f
@@ -27,6 +27,8 @@ namespace ProjectM.Client
Text _phaseText;
Text _resourceText;
Text _locationText;
RectTransform _goalFill;
Text _goalText;
GameObject _respawnOverlay;
EntityQuery _huskQuery;
@@ -81,6 +83,13 @@ namespace ProjectM.Client
_locationText.color = onExpedition ? new Color(1f, 0.8f, 0.4f) : new Color(0.6f, 0.85f, 1f);
}
if (_goalFill != null && SystemAPI.TryGetSingleton<GoalProgress>(out var goal))
{
float gfrac = goal.Target > 0 ? Mathf.Clamp01(goal.Charge / (float)goal.Target) : 0f;
SetFill(_goalFill, gfrac);
if (_goalText != null) _goalText.text = "GOAL " + goal.Charge + " / " + goal.Target;
}
if (_resourceText != null)
{
string res = "";
@@ -211,6 +220,12 @@ namespace ProjectM.Client
var lrt = _locationText.rectTransform;
lrt.anchorMin = new Vector2(0.5f, 1f); lrt.anchorMax = new Vector2(0.5f, 1f); lrt.pivot = new Vector2(0.5f, 1f);
lrt.anchoredPosition = new Vector2(0, -96); lrt.sizeDelta = new Vector2(760, 36);
// Goal progress bar (top-center, below the location line).
var goalBg = MakeBar("GoalBg", _canvas.transform, new Color(0f, 0f, 0f, 0.55f), Vector2.zero, new Vector2(360, 16));
goalBg.anchorMin = new Vector2(0.5f, 1f); goalBg.anchorMax = new Vector2(0.5f, 1f); goalBg.pivot = new Vector2(0.5f, 1f);
goalBg.anchoredPosition = new Vector2(0, -126); goalBg.sizeDelta = new Vector2(360, 16);
_goalFill = MakeFill("GoalFill", goalBg, new Color(0.8f, 0.6f, 1f));
_goalText = MakeText("GoalText", goalBg, "GOAL 0 / 10", 15, TextAnchor.MiddleCenter, Color.white, font);
// Downed / respawning overlay (full screen, toggled by Dead).
_respawnOverlay = new GameObject("RespawnOverlay", typeof(RectTransform));
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 73829e22632af284d880736d6b0a371f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,92 @@
using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.NetCode;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative ability-damage upgrade (handles <see cref="AbilityUpgradeRequest"/> RPCs). Resolves
/// the sender's player (SourceConnection -&gt; NetworkId -&gt; GhostOwner) and, if the global ledger affords the
/// Aether cost, withdraws it IN-PLACE and grows a single damage <see cref="StatModifier"/> on the player
/// (replace-by-SourceId so the [InternalBufferCapacity(8)] buffer stays bounded — repeated upgrades grow one
/// row's percent rather than appending). StatRecomputeSystem folds it into EffectiveAbilityStats.Damage on
/// both worlds. Plain server SimulationSystemGroup (not predicted → applied once).
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct AbilityUpgradeSystem : ISystem
{
const uint UpgradeSourceId = 0x00A0E711u; // distinct sentinel so the upgrade modifier is found + grown
const float TierStep = 0.25f; // +25% damage per tier
const int CostAmount = 20; // Aether per tier
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<ResourceLedger>();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<AbilityUpgradeRequest, ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var ledger = SystemAPI.GetBuffer<StorageEntry>(SystemAPI.GetSingletonEntity<ResourceLedger>());
var playerByConn = new NativeHashMap<int, Entity>(8, Allocator.Temp);
foreach (var (owner, entity) in
SystemAPI.Query<RefRO<GhostOwner>>().WithAll<PlayerTag, StatModifier>().WithEntityAccess())
playerByConn[owner.ValueRO.NetworkId] = entity;
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (receive, requestEntity) in
SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>>().WithAll<AbilityUpgradeRequest>().WithEntityAccess())
{
var conn = receive.ValueRO.SourceConnection;
if (SystemAPI.HasComponent<NetworkId>(conn)
&& playerByConn.TryGetValue(SystemAPI.GetComponent<NetworkId>(conn).Value, out var player))
{
int have = 0;
for (int i = 0; i < ledger.Length; i++)
if (ledger[i].ItemId == ResourceId.Aether) { have = ledger[i].Count; break; }
if (have >= CostAmount)
{
StorageMath.Withdraw(ledger, ResourceId.Aether, CostAmount);
var mods = SystemAPI.GetBuffer<StatModifier>(player);
bool grown = false;
for (int i = 0; i < mods.Length; i++)
{
if (mods[i].SourceId == UpgradeSourceId && mods[i].Target == (byte)StatTarget.Damage)
{
var m = mods[i];
m.Value += TierStep;
mods[i] = m;
grown = true;
break;
}
}
if (!grown)
mods.Add(new StatModifier
{
Target = (byte)StatTarget.Damage,
Op = (byte)ModOp.PercentAdd,
Value = TierStep,
SourceId = UpgradeSourceId,
});
}
}
ecb.DestroyEntity(requestEntity);
}
ecb.Playback(state.EntityManager);
playerByConn.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ff2ed6b5fa37a174aa7413f4d2f5d6b3
@@ -0,0 +1,104 @@
using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative structure placement (handles <see cref="BuildPlaceRequest"/> RPCs). Derives
/// occupancy by scanning live <see cref="PlacedStructure"/> ghosts into a Temp NativeHashSet (structures
/// are the source of truth — no cached buffer on the immutable BaseAnchor). For each request it validates
/// catalog/legality/occupancy/cost, and on success commits IN-PLACE (StorageMath.Withdraw on the global
/// ledger + reserve the cell in the set) so two same-tick requests for one cell can't both pass — the
/// StorageOpReceiveSystem in-place idiom — then instantiates the catalog prefab at the cell center
/// (RegionTag{Base}, world-owned, NextTick=0, LastProcessedTick stamped). Plain server SimulationSystemGroup
/// (not predicted → applied once). Rejects invalid requests silently.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct BuildPlaceSystem : ISystem
{
ComponentLookup<LocalTransform> m_TransformLookup;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
m_TransformLookup = state.GetComponentLookup<LocalTransform>(isReadOnly: true);
state.RequireForUpdate<StructureCatalog>();
state.RequireForUpdate<BaseAnchor>();
state.RequireForUpdate<ResourceLedger>();
state.RequireForUpdate<NetworkTime>();
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<BuildPlaceRequest, ReceiveRpcCommandRequest>();
state.RequireForUpdate(state.GetEntityQuery(builder));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
m_TransformLookup.Update(ref state);
uint now = SystemAPI.GetSingleton<NetworkTime>().ServerTick.TickIndexForValidTick;
var anchor = SystemAPI.GetSingleton<BaseAnchor>();
var catalog = SystemAPI.GetBuffer<StructureCatalogEntry>(SystemAPI.GetSingletonEntity<StructureCatalog>());
var ledger = SystemAPI.GetBuffer<StorageEntry>(SystemAPI.GetSingletonEntity<ResourceLedger>());
// Derive occupancy from the live structure set (authoritative source of truth).
var occupied = new NativeHashSet<int2>(64, Allocator.Temp);
foreach (var ps in SystemAPI.Query<RefRO<PlacedStructure>>())
occupied.Add(ps.ValueRO.Cell);
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (request, receive, requestEntity) in
SystemAPI.Query<RefRO<BuildPlaceRequest>, RefRO<ReceiveRpcCommandRequest>>().WithEntityAccess())
{
var req = request.ValueRO;
int2 cell = new int2(req.CellX, req.CellZ);
int entryIdx = -1;
for (int i = 0; i < catalog.Length; i++)
if (catalog[i].Type == req.StructureType) { entryIdx = i; break; }
if (entryIdx >= 0 && catalog[entryIdx].Prefab != Entity.Null
&& BuildPlacementMath.CanPlace(anchor, occupied, cell))
{
var entry = catalog[entryIdx];
int have = 0;
for (int i = 0; i < ledger.Length; i++)
if (ledger[i].ItemId == entry.CostResourceId) { have = ledger[i].Count; break; }
if (have >= entry.CostAmount)
{
// Commit IN-PLACE so a second same-tick request sees the spend + reservation.
StorageMath.Withdraw(ledger, entry.CostResourceId, entry.CostAmount);
occupied.Add(cell);
var structure = ecb.Instantiate(entry.Prefab);
var xform = m_TransformLookup[entry.Prefab];
xform.Position = BaseGridMath.CellToWorld(anchor, cell); // preserve baked Scale
ecb.SetComponent(structure, xform);
ecb.SetComponent(structure, new PlacedStructure
{
Type = req.StructureType,
Cell = cell,
NextTick = 0u,
LastProcessedTick = TickUtil.NonZero(now),
});
ecb.AddComponent(structure, new RegionTag { Region = RegionId.Base });
}
}
ecb.DestroyEntity(requestEntity);
}
ecb.Playback(state.EntityManager);
occupied.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1886c7056b315e42b7754f50c43c59e
@@ -0,0 +1,110 @@
using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
namespace ProjectM.Server
{
/// <summary>
/// Server-only turret fire (hitscan) — EnemyAISystem reversed. Snapshots living Husks once (entity, planar
/// pos, region); each turret picks the nearest Husk in ITS region within Range and, on a NetworkTick
/// cooldown stored in <see cref="PlacedStructure.NextTick"/>, appends a direct <c>DamageEvent</c>
/// (SourceNetworkId=-1) to it. Reuses HealthApplyDamageSystem (already destroys EnemyTag at HP&lt;=0) — no
/// projectile, no tunnelling, no friendly-fire. Plain server SimulationSystemGroup
/// <c>[UpdateAfter(PredictedSimulationSystemGroup)]</c> (the predicted group is OrderFirst → UpdateBefore is
/// ignored); the appended DamageEvent drains next tick (~16ms), consistent with EnemyAISystem. Self-gates:
/// Husks only exist during the Defend wave.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(PredictedSimulationSystemGroup))]
public partial struct TurretFireSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<NetworkTime>();
state.RequireForUpdate(state.GetEntityQuery(ComponentType.ReadOnly<Turret>()));
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
var serverTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
if (!serverTick.IsValid)
return;
uint now = serverTick.TickIndexForValidTick;
var huskEntities = new NativeList<Entity>(Allocator.Temp);
var huskPos = new NativeList<float2>(Allocator.Temp);
var huskRegion = new NativeList<byte>(Allocator.Temp);
foreach (var (xform, health, region, e) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Health>, RefRO<RegionTag>>()
.WithAll<EnemyTag>().WithEntityAccess())
{
if (health.ValueRO.Current <= 0f)
continue;
huskEntities.Add(e);
huskPos.Add(xform.ValueRO.Position.xz);
huskRegion.Add(region.ValueRO.Region);
}
if (huskEntities.Length == 0)
{
huskEntities.Dispose(); huskPos.Dispose(); huskRegion.Dispose();
return;
}
var ecb = new EntityCommandBuffer(Allocator.Temp);
foreach (var (ps, turret, xform, region) in
SystemAPI.Query<RefRW<PlacedStructure>, RefRO<Turret>, RefRO<LocalTransform>, RefRO<RegionTag>>())
{
uint nextRaw = ps.ValueRO.NextTick;
if (nextRaw != 0)
{
var nextTick = new NetworkTick(nextRaw);
if (nextTick.IsValid && nextTick.IsNewerThan(serverTick))
continue; // still cooling down
}
float2 tp = xform.ValueRO.Position.xz;
byte treg = region.ValueRO.Region;
float rangeSq = turret.ValueRO.Range * turret.ValueRO.Range;
int best = -1;
float bestSq = float.MaxValue;
for (int i = 0; i < huskEntities.Length; i++)
{
if (huskRegion[i] != treg)
continue;
float sq = math.distancesq(huskPos[i], tp);
if (sq <= rangeSq && sq < bestSq)
{
bestSq = sq;
best = i;
}
}
if (best >= 0)
{
ecb.AppendToBuffer(huskEntities[best], new DamageEvent
{
Amount = turret.ValueRO.Damage,
SourceNetworkId = -1,
});
uint cd = (uint)math.max(1, turret.ValueRO.CooldownTicks);
ps.ValueRW.NextTick = TickUtil.NonZero(now + cd);
}
}
ecb.Playback(state.EntityManager);
ecb.Dispose();
huskEntities.Dispose(); huskPos.Dispose(); huskRegion.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 53cc7669bd6cc5d4e8307b18732897bc
@@ -71,6 +71,13 @@ namespace ProjectM.Server
cycle.Phase = CyclePhase.Expedition;
cycle.CycleNumber += 1;
cycle.PhaseEndTick = TickUtil.NonZero(now + CyclePhase.ExpeditionTicks);
// Long-arc goal: one charge per completed cycle (single writer).
if (SystemAPI.HasComponent<GoalProgress>(cycleEntity))
{
var goal = SystemAPI.GetComponent<GoalProgress>(cycleEntity);
goal.Charge += 1;
SystemAPI.SetComponent(cycleEntity, goal);
}
}
break;
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 53b186388519ddb458c72bb717085721
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
using Unity.NetCode;
namespace ProjectM.Simulation
{
/// <summary>
/// Client -&gt; server request to upgrade the sender's ability damage one tier, spending Aether from the
/// shared ledger. A one-off RPC. The server grows a single damage <see cref="StatModifier"/> on the
/// player (replace-by-SourceId so the buffer stays bounded), which StatRecomputeSystem folds into
/// EffectiveAbilityStats.Damage on both worlds — no new replicated component.
/// </summary>
public struct AbilityUpgradeRequest : IRpcCommand { }
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1236d3751a5740741a4a10e0a653565f
@@ -0,0 +1,18 @@
using Unity.NetCode;
namespace ProjectM.Simulation
{
/// <summary>
/// Client -&gt; server request to build a structure of <see cref="StructureType"/> at grid cell
/// (<see cref="CellX"/>, <see cref="CellZ"/>). A one-off action, so an RPC (mirrors StorageOpRequest /
/// RegionTransitRequest). StructureType is a byte; the cell is two int scalars (NOT an int2) to stay
/// within the project's scalar-only RPC payload precedent (avoids first-of-its-kind composite-math-in-RPC
/// codegen risk on Netcode 1.13.2). The server re-validates legality + cost authoritatively.
/// </summary>
public struct BuildPlaceRequest : IRpcCommand
{
public byte StructureType;
public int CellX;
public int CellZ;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dbcc491dc3dd853459cd8cfad2458b17
@@ -0,0 +1,24 @@
using Unity.Collections;
using Unity.Mathematics;
namespace ProjectM.Simulation
{
/// <summary>
/// Pure, deterministic build-placement helpers (unit-tested like <see cref="BaseGridMath"/> /
/// <c>StorageMath</c>). Occupancy is DERIVED from the live structure set each placement (the structure
/// ghosts are the source of truth — restart- and replay-order-safe), never cached on the immutable
/// baked <see cref="BaseAnchor"/>. The server passes a Temp <see cref="NativeHashSet{T}"/> of occupied
/// cells built by scanning live <see cref="PlacedStructure"/> ghosts.
/// </summary>
public static class BuildPlacementMath
{
/// <summary>True if <paramref name="cell"/> is occupied in the derived set.</summary>
public static bool IsOccupied(in NativeHashSet<int2> occupied, int2 cell) => occupied.Contains(cell);
/// <summary>Full server placement legality: the cell is in-plot (half-open, negative-safe) AND not occupied.</summary>
public static bool CanPlace(in BaseAnchor anchor, in NativeHashSet<int2> occupied, int2 cell)
{
return BaseGridMath.IsCellInPlot(anchor, cell) && !occupied.Contains(cell);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 203dcbd4f9cc089408633b0bb6ccb2c1
@@ -0,0 +1,75 @@
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
namespace ProjectM.Simulation
{
/// <summary>
/// Structure type ids (a byte, not an enum, per the cross-assembly enum-in-Burst hazard). Turret is the
/// first concrete structure; Harvester/Fabricator/Conveyor are RESERVED now (free) for the M7 automation
/// pillar (production chains) so adding them later is purely additive.
/// </summary>
public static class StructureType
{
public const byte None = 0;
public const byte Turret = 1;
// Reserved for M7 automation — do not reuse these codes:
public const byte Harvester = 2;
public const byte Fabricator = 3;
public const byte Conveyor = 4;
}
/// <summary>
/// A built base structure occupying one grid cell. An ownerless INTERPOLATED ghost (RegionTag{Base},
/// world-owned, runtime-spawned by BuildPlaceSystem). <see cref="Type"/> is the only replicated field
/// (a cheap byte for client visual branching); <see cref="Cell"/> is server-only (clients derive it from
/// the replicated LocalTransform via <see cref="BaseGridMath.WorldToCell"/>, so it stays off the wire).
/// <see cref="NextTick"/> / <see cref="LastProcessedTick"/> are server-only raw NetworkTick values
/// (<see cref="TickUtil.NonZero"/>-guarded; 0 = inactive): the Turret reuses <see cref="NextTick"/> as its
/// fire cooldown NOW (not dead weight), and M7 production reuses both as the next-production-tick +
/// deterministic offline catch-up linchpin (produced = floor((now - LastProcessedTick)/period)). These two
/// tick fields are the IDENTITY/TIMING that cannot be reconstructed retroactively, so they are baked now.
/// </summary>
public struct PlacedStructure : IComponentData
{
/// <summary>Structure type (see <see cref="StructureType"/>); the only replicated field.</summary>
[GhostField] public byte Type;
/// <summary>Occupied grid cell (server-only; clients derive it from LocalTransform).</summary>
public int2 Cell;
/// <summary>Next action tick (server-only; turret cooldown now / next production tick in M7). 0 = inactive.</summary>
public uint NextTick;
/// <summary>Last tick this structure was processed (server-only; M7 offline-catch-up baseline). Stamped at spawn.</summary>
public uint LastProcessedTick;
}
/// <summary>
/// A buildable defense turret (the first structure). Hitscan: <c>TurretFireSystem</c> applies a direct
/// <c>DamageEvent</c> to the nearest in-range living Husk on cooldown (reusing
/// <see cref="PlacedStructure.NextTick"/>) — reuses HealthApplyDamageSystem, no projectile/friendly-fire.
/// </summary>
public struct Turret : IComponentData
{
public float Range;
public int CooldownTicks;
public float Damage;
}
/// <summary>
/// One row of the build catalog: cost + prefab per structure type. Modeled on AbilityPrefabElement
/// (prefab baked via GetEntity, NEVER inside a blob — blobs don't remap entity refs). M7 adds a recipe
/// column to this element additively (the catalog is baked, not replicated → no format break).
/// </summary>
public struct StructureCatalogEntry : IBufferElementData
{
public byte Type;
public Entity Prefab;
public byte CostResourceId;
public int CostAmount;
}
/// <summary>Tag on the baked singleton carrying the <see cref="StructureCatalogEntry"/> buffer (the build cost/prefab table).</summary>
public struct StructureCatalog : IComponentData { }
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 00d3379caf4807d4ebd97432848dd5d5
@@ -0,0 +1,20 @@
using Unity.Entities;
using Unity.NetCode;
namespace ProjectM.Simulation
{
/// <summary>
/// Long-arc progress toward the goal ("reach THEM"). Lives on the GLOBAL CycleDirector ghost (relevant in
/// every region, alongside CycleState + the resource ledger), so it is visible to all players regardless
/// of region. SINGLE writer: <c>CyclePhaseSystem</c> increments <see cref="Charge"/> on each completed
/// cycle (Build -&gt; Expedition). The HUD observes it for a progress bar.
/// </summary>
public struct GoalProgress : IComponentData
{
/// <summary>Accumulated progress.</summary>
[GhostField] public int Charge;
/// <summary>Charge required to reach the goal.</summary>
[GhostField] public int Target;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e1f60b3396850074ca0e44b831b5980c
+47
View File
@@ -273,6 +273,52 @@ Transform:
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &380046993
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 380046995}
- component: {fileID: 380046994}
m_Layer: 0
m_Name: StructureCatalog
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &380046994
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 380046993}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 40093ed42072f5a4889f5f62f510aa27, type: 3}
m_Name:
m_EditorClassIdentifier: ProjectM.Authoring::ProjectM.Authoring.StructureCatalogAuthoring
TurretPrefab: {fileID: 3885353946372160549, guid: 5459c9edea89bd94fa6f5043ae00eb40, type: 3}
TurretCostOre: 10
--- !u!4 &380046995
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 380046993}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &409538537
GameObject:
m_ObjectHideFlags: 0
@@ -1217,3 +1263,4 @@ SceneRoots:
- {fileID: 17637047}
- {fileID: 1192434518}
- {fileID: 236770154}
- {fileID: 380046995}