using System.IO.Compression; using ViaFerrea.Core.Common; namespace ViaFerrea.Protocol.Messages; /// Codici di . public enum RejectCode : ushort { ProtocolVersion = 1, BadToken = 2, DataMismatch = 3, ServerFull = 4, NoGame = 5 } public sealed class Welcome : IMessage { public MessageId Id => MessageId.Welcome; public ulong SessionId { get; init; } public required WorldSummary Summary { get; init; } public ulong DataHash { get; init; } public string Difficulty { get; init; } = ""; public void Write(ref SpanWriter w) { w.U64(SessionId); Summary.Write(ref w); w.U64(DataHash); w.String(Difficulty); w.Flags(0); } public static Welcome Read(ref SpanReader r) { var m = new Welcome { SessionId = r.U64(), Summary = WorldSummary.Read(ref r), DataHash = r.U64(), Difficulty = r.String() }; r.Flags(); return m; } } public sealed class Reject : IMessage { public MessageId Id => MessageId.Reject; public RejectCode Code { get; init; } public string Reason { get; init; } = ""; public void Write(ref SpanWriter w) { w.U16((ushort)Code); w.String(Reason); w.Flags(0); } public static Reject Read(ref SpanReader r) { var m = new Reject { Code = (RejectCode)r.U16(), Reason = r.String() }; r.Flags(); return m; } } public sealed class Pong : IMessage { public MessageId Id => MessageId.Pong; public ulong Nonce { get; init; } public ulong ServerTick { get; init; } public void Write(ref SpanWriter w) { w.U64(Nonce); w.U64(ServerTick); w.Flags(0); } public static Pong Read(ref SpanReader r) { var m = new Pong { Nonce = r.U64(), ServerTick = r.U64() }; r.Flags(); return m; } } /// /// Un chunk del terreno: altezze (dm), tipi di cella e larghezza dei fiumi, compressi con Brotli. /// I chunk di bordo possono essere più piccoli di ChunkCells. /// public sealed class MapChunk : IMessage { public MessageId Id => MessageId.MapChunk; public int Cx { get; init; } public int Cy { get; init; } public int Width { get; init; } public int Height { get; init; } public ushort[] Heights { get; init; } = []; public byte[] Types { get; init; } = []; public byte[] RiverWidth { get; init; } = []; public void Write(ref SpanWriter w) { w.I32(Cx); w.I32(Cy); w.I32(Width); w.I32(Height); int n = Width * Height; if (Heights.Length != n || Types.Length != n || RiverWidth.Length != n) throw new ProtocolException("chunk incoerente"); var raw = new byte[n * 4]; for (int i = 0; i < n; i++) { raw[2 * i] = (byte)Heights[i]; raw[2 * i + 1] = (byte)(Heights[i] >> 8); } Types.CopyTo(raw, 2 * n); RiverWidth.CopyTo(raw, 3 * n); var packed = new byte[BrotliEncoder.GetMaxCompressedLength(raw.Length)]; if (!BrotliEncoder.TryCompress(raw, packed, out int written, quality: 4, window: 22)) throw new ProtocolException("compressione del chunk fallita"); w.U8(1); // compressione: 1 = Brotli w.Bytes(packed.AsSpan(0, written)); w.Flags(0); } public static MapChunk Read(ref SpanReader r) { int cx = r.I32(), cy = r.I32(), width = r.I32(), height = r.I32(); if (width <= 0 || height <= 0 || width > 1024 || height > 1024) throw new ProtocolException("dimensioni del chunk non valide"); int n = width * height; byte compression = r.U8(); byte[] packed = r.Bytes(); var raw = new byte[n * 4]; if (compression == 1) { if (!BrotliDecoder.TryDecompress(packed, raw, out int written) || written != raw.Length) throw new ProtocolException("chunk corrotto"); } else if (compression == 0 && packed.Length == raw.Length) packed.CopyTo(raw, 0); else throw new ProtocolException($"compressione sconosciuta: {compression}"); var heights = new ushort[n]; for (int i = 0; i < n; i++) heights[i] = (ushort)(raw[2 * i] | raw[2 * i + 1] << 8); r.Flags(); return new MapChunk { Cx = cx, Cy = cy, Width = width, Height = height, Heights = heights, Types = raw.AsSpan(2 * n, n).ToArray(), RiverWidth = raw.AsSpan(3 * n, n).ToArray(), }; } } /// Liste di entità comuni a snapshot e delta. public sealed class EntityLists { public List Companies { get; init; } = []; public List Towns { get; init; } = []; public List Industries { get; init; } = []; public List Hubs { get; init; } = []; public List Nodes { get; init; } = []; public List Stations { get; init; } = []; public List Depots { get; init; } = []; public List Lines { get; init; } = []; public List Vehicles { get; init; } = []; public List Trains { get; init; } = []; public int TotalCount => Companies.Count + Towns.Count + Industries.Count + Hubs.Count + Nodes.Count + Stations.Count + Depots.Count + Lines.Count + Vehicles.Count + Trains.Count; public void Write(ref SpanWriter w) { w.Count(Companies.Count); foreach (var x in Companies) x.Write(ref w); w.Count(Towns.Count); foreach (var x in Towns) x.Write(ref w); w.Count(Industries.Count); foreach (var x in Industries) x.Write(ref w); w.Count(Hubs.Count); foreach (var x in Hubs) x.Write(ref w); w.Count(Nodes.Count); foreach (var x in Nodes) x.Write(ref w); w.Count(Stations.Count); foreach (var x in Stations) x.Write(ref w); w.Count(Depots.Count); foreach (var x in Depots) x.Write(ref w); w.Count(Lines.Count); foreach (var x in Lines) x.Write(ref w); w.Count(Vehicles.Count); foreach (var x in Vehicles) x.Write(ref w); w.Count(Trains.Count); foreach (var x in Trains) x.Write(ref w); } public static EntityLists Read(ref SpanReader r) { var m = new EntityLists(); for (int n = r.Count(), i = 0; i < n; i++) m.Companies.Add(CompanyInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Towns.Add(TownInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Industries.Add(IndustryInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Hubs.Add(HubInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Nodes.Add(NodeInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Stations.Add(StationInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Depots.Add(DepotInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Lines.Add(LineInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Vehicles.Add(VehicleInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Trains.Add(TrainInfo.Read(ref r)); return m; } } /// Stato completo delle entità (all'ingresso e dopo un caricamento). public sealed class EntitySnapshot : IMessage { public MessageId Id => MessageId.EntitySnapshot; public long Tick { get; init; } public required EntityLists Entities { get; init; } public void Write(ref SpanWriter w) { w.I64(Tick); Entities.Write(ref w); w.Flags(0); } public static EntitySnapshot Read(ref SpanReader r) { var m = new EntitySnapshot { Tick = r.I64(), Entities = EntityLists.Read(ref r) }; r.Flags(); return m; } } /// Entità nuove o cambiate dall'ultimo invio e quelle rimosse. public sealed class EntityDelta : IMessage { public MessageId Id => MessageId.EntityDelta; public long Tick { get; init; } public required EntityLists Changed { get; init; } public List<(EntityType Type, int Id)> Removed { get; init; } = []; public void Write(ref SpanWriter w) { w.I64(Tick); Changed.Write(ref w); w.Count(Removed.Count); foreach (var (type, id) in Removed) { w.U8((byte)type); w.I32(id); } w.Flags(0); } public static EntityDelta Read(ref SpanReader r) { long tick = r.I64(); var changed = EntityLists.Read(ref r); int n = r.Count(); var removed = new List<(EntityType, int)>(n); for (int i = 0; i < n; i++) removed.Add(((EntityType)r.U8(), r.I32())); r.Flags(); return new EntityDelta { Tick = tick, Changed = changed, Removed = removed }; } } /// Archi di binario nuovi o cambiati (opere, cantiere, condizione, segnali) e archi demoliti. public sealed class TrackWorks : IMessage { public MessageId Id => MessageId.TrackWorks; public List Edges { get; init; } = []; public List Removed { get; init; } = []; public void Write(ref SpanWriter w) { w.Count(Edges.Count); foreach (var e in Edges) e.Write(ref w); w.Count(Removed.Count); foreach (int id in Removed) w.I32(id); w.Flags(0); } public static TrackWorks Read(ref SpanReader r) { var m = new TrackWorks(); for (int n = r.Count(), i = 0; i < n; i++) m.Edges.Add(EdgeInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Removed.Add(r.I32()); r.Flags(); return m; } } /// /// Moto di un treno: tratti dalla coda alla testa e oltre (percorso prenotato), la distanza della /// testa lungo i tratti e la velocità; il client interpola avanzando la testa a velocità costante. /// public sealed class TrainMotion : IMessage { public MessageId Id => MessageId.TrainMotion; public int TrainId { get; init; } public long Tick { get; init; } public byte State { get; init; } public float Condition { get; init; } /// Velocità in m/s di orologio dei treni. public float Speed { get; init; } public float LengthM { get; init; } public double HeadDistance { get; init; } public List Segments { get; init; } = []; public void Write(ref SpanWriter w) { w.I32(TrainId); w.I64(Tick); w.U8(State); w.F32(Condition); w.F32(Speed); w.F32(LengthM); w.F64(HeadDistance); w.Count(Segments.Count); foreach (var s in Segments) { w.I32(s.Edge); w.Bool(s.Forward); w.F64(s.FromS); w.F64(s.ToS); } w.Flags(0); } public static TrainMotion Read(ref SpanReader r) { int id = r.I32(); long tick = r.I64(); byte state = r.U8(); float cond = r.F32(), speed = r.F32(), length = r.F32(); double head = r.F64(); int n = r.Count(); var segs = new List(n); for (int i = 0; i < n; i++) segs.Add(new MotionSegment(r.I32(), r.Bool(), r.F64(), r.F64())); r.Flags(); return new TrainMotion { TrainId = id, Tick = tick, State = state, Condition = cond, Speed = speed, LengthM = length, HeadDistance = head, Segments = segs }; } } /// Resoconto giornaliero: data, conti della compagnia, prezzi, eventi del giorno, hash di stato. public sealed class DailyDigest : IMessage { public MessageId Id => MessageId.DailyDigest; public long Day { get; init; } public long Tick { get; init; } public string Date { get; init; } = ""; public Money Cash { get; init; } public Money NetWorth { get; init; } public string Rating { get; init; } = ""; public List Prices { get; init; } = []; public List Events { get; init; } = []; public ulong StateHash { get; init; } public bool Slow { get; init; } public byte Speed { get; init; } public float TickMs { get; init; } public void Write(ref SpanWriter w) { w.I64(Day); w.I64(Tick); w.String(Date); w.Money(Cash); w.Money(NetWorth); w.String(Rating); w.Count(Prices.Count); foreach (var p in Prices) w.Money(p); w.Count(Events.Count); foreach (var e in Events) e.Write(ref w); w.U64(StateHash); w.Bool(Slow); w.U8(Speed); w.F32(TickMs); w.Flags(0); } public static DailyDigest Read(ref SpanReader r) { long day = r.I64(), tick = r.I64(); string date = r.String(); var cash = r.Money(); var worth = r.Money(); string rating = r.String(); var prices = new List(); for (int n = r.Count(), i = 0; i < n; i++) prices.Add(r.Money()); var events = new List(); for (int n = r.Count(), i = 0; i < n; i++) events.Add(EventInfo.Read(ref r)); var m = new DailyDigest { Day = day, Tick = tick, Date = date, Cash = cash, NetWorth = worth, Rating = rating, Prices = prices, Events = events, StateHash = r.U64(), Slow = r.Bool(), Speed = r.U8(), TickMs = r.F32(), }; r.Flags(); return m; } } /// Avviso di manutenzione di un treno o di un deposito (F4). public sealed class MaintenanceAlert : IMessage { public MessageId Id => MessageId.MaintenanceAlert; public int Train { get; init; } = -1; public int Depot { get; init; } = -1; public string Component { get; init; } = ""; public float Condition { get; init; } public int DueDays { get; init; } public string Text { get; init; } = ""; public void Write(ref SpanWriter w) { w.I32(Train); w.I32(Depot); w.String(Component); w.F32(Condition); w.I32(DueDays); w.String(Text); w.Flags(0); } public static MaintenanceAlert Read(ref SpanReader r) { var m = new MaintenanceAlert { Train = r.I32(), Depot = r.I32(), Component = r.String(), Condition = r.F32(), DueDays = r.I32(), Text = r.String() }; r.Flags(); return m; } } /// Provenienza dei lavoratori di un posto di lavoro (Registro degli impieghi). public sealed class EmploymentSource { public int Town { get; init; } public int HomeStation { get; init; } = -1; /// Prima linea del percorso (−1 = a piedi). public int Line { get; init; } = -1; public byte Category { get; init; } public int Headcount { get; init; } public float Coverage { get; init; } public void Write(ref SpanWriter w) { w.I32(Town); w.I32(HomeStation); w.I32(Line); w.U8(Category); w.I32(Headcount); w.F32(Coverage); w.Flags(0); } public static EmploymentSource Read(ref SpanReader r) { var m = new EmploymentSource { Town = r.I32(), HomeStation = r.I32(), Line = r.I32(), Category = r.U8(), Headcount = r.I32(), Coverage = r.F32() }; r.Flags(); return m; } } /// Riga del Registro degli impieghi: un posto di lavoro (industria o deposito). public sealed class EmploymentRow { /// Indice del posto di lavoro (industria o deposito secondo ). public int Industry { get; init; } public int JobsWorkers { get; init; } public int JobsStaff { get; init; } public float WorkersPresent { get; init; } public float StaffPresent { get; init; } /// Motivo dei posti scoperti, in italiano (per i lettori senza il blocco F4). public string Reason { get; init; } = ""; public List Sources { get; init; } = []; // blocco 1 (F4): tipo di posto e codici dei motivi (UncoveredReason di Core) /// 0 = industria, 1 = deposito. public byte Kind { get; set; } public byte WorkersReason { get; set; } public byte StaffReason { get; set; } public int WorkersReasonLine { get; set; } = -1; public int StaffReasonLine { get; set; } = -1; public void Write(ref SpanWriter w) { w.I32(Industry); w.I32(JobsWorkers); w.I32(JobsStaff); w.F32(WorkersPresent); w.F32(StaffPresent); w.String(Reason); w.Count(Sources.Count); foreach (var s in Sources) s.Write(ref w); w.Flags(1); w.U8(Kind); w.U8(WorkersReason); w.U8(StaffReason); w.I32(WorkersReasonLine); w.I32(StaffReasonLine); } public static EmploymentRow Read(ref SpanReader r) { int ind = r.I32(), jw = r.I32(), js = r.I32(); float wp = r.F32(), sp = r.F32(); string reason = r.String(); var sources = new List(); for (int n = r.Count(), i = 0; i < n; i++) sources.Add(EmploymentSource.Read(ref r)); var m = new EmploymentRow { Industry = ind, JobsWorkers = jw, JobsStaff = js, WorkersPresent = wp, StaffPresent = sp, Reason = reason, Sources = sources }; byte flags = r.Flags(); if ((flags & 1) != 0) { m.Kind = r.U8(); m.WorkersReason = r.U8(); m.StaffReason = r.U8(); m.WorkersReasonLine = r.I32(); m.StaffReasonLine = r.I32(); } return m; } } /// Convenzione di pendolarismo (sezione 9) nel Registro degli impieghi. public sealed class AgreementInfo { public int Id { get; init; } public int Industry { get; init; } public int Carrier { get; init; } public int SeatsPerDay { get; init; } public Money MonthlyFee { get; init; } /// AgreementState di Core: 0 proposta, 1 attiva, 2 rifiutata, 3 scaduta, 4 saltata, 5 conclusa. public byte State { get; init; } public long ProposedDay { get; init; } public long StartDay { get; init; } = -1; public long EndDay { get; init; } = -1; public float Coverage { get; init; } public int ShortDays { get; init; } public void Write(ref SpanWriter w) { w.I32(Id); w.I32(Industry); w.I32(Carrier); w.I32(SeatsPerDay); w.Money(MonthlyFee); w.U8(State); w.I64(ProposedDay); w.I64(StartDay); w.I64(EndDay); w.F32(Coverage); w.I32(ShortDays); w.Flags(0); } public static AgreementInfo Read(ref SpanReader r) { var m = new AgreementInfo { Id = r.I32(), Industry = r.I32(), Carrier = r.I32(), SeatsPerDay = r.I32(), MonthlyFee = r.Money(), State = r.U8(), ProposedDay = r.I64(), StartDay = r.I64(), EndDay = r.I64(), Coverage = r.F32(), ShortDays = r.I32(), }; r.Flags(); return m; } } /// Registro degli impieghi della compagnia: ogni mese, dopo le convenzioni e su richiesta. public sealed class EmploymentReport : IMessage { public MessageId Id => MessageId.EmploymentReport; public long Day { get; init; } public List Rows { get; init; } = []; // blocco 1 (F4): convenzioni proposte e attive public List Agreements { get; init; } = []; public void Write(ref SpanWriter w) { w.I64(Day); w.Count(Rows.Count); foreach (var row in Rows) row.Write(ref w); w.Flags(1); w.Count(Agreements.Count); foreach (var a in Agreements) a.Write(ref w); } public static EmploymentReport Read(ref SpanReader r) { var m = new EmploymentReport { Day = r.I64() }; for (int n = r.Count(), i = 0; i < n; i++) m.Rows.Add(EmploymentRow.Read(ref r)); byte flags = r.Flags(); if ((flags & 1) != 0) { for (int n = r.Count(), i = 0; i < n; i++) m.Agreements.Add(AgreementInfo.Read(ref r)); } return m; } } /// Componente di un veicolo nella cartella di manutenzione. public sealed class ComponentCard { public string Component { get; init; } = ""; public float Condition { get; init; } /// Usura media giornaliera degli ultimi giorni (punti/giorno). public float WearPerDay { get; init; } public void Write(ref SpanWriter w) { w.String(Component); w.F32(Condition); w.F32(WearPerDay); w.Flags(0); } public static ComponentCard Read(ref SpanReader r) { var m = new ComponentCard { Component = r.String(), Condition = r.F32(), WearPerDay = r.F32() }; r.Flags(); return m; } } public sealed class VehicleCard { public int Vehicle { get; init; } public string Type { get; init; } = ""; public float OdometerKm { get; init; } public float AgeYears { get; init; } public float AgeFactor { get; init; } public List Components { get; init; } = []; public void Write(ref SpanWriter w) { w.I32(Vehicle); w.String(Type); w.F32(OdometerKm); w.F32(AgeYears); w.F32(AgeFactor); w.Count(Components.Count); foreach (var c in Components) c.Write(ref w); w.Flags(0); } public static VehicleCard Read(ref SpanReader r) { var m = new VehicleCard { Vehicle = r.I32(), Type = r.String(), OdometerKm = r.F32(), AgeYears = r.F32(), AgeFactor = r.F32() }; for (int n = r.Count(), i = 0; i < n; i++) m.Components.Add(ComponentCard.Read(ref r)); r.Flags(); return m; } } /// Voce dello storico della cartella di manutenzione. public sealed class MaintenanceRecordInfo { public long Day { get; init; } public string Intervention { get; init; } = ""; public Money Cost { get; init; } public int Depot { get; init; } = -1; public int Parts { get; init; } public void Write(ref SpanWriter w) { w.I64(Day); w.String(Intervention); w.Money(Cost); w.I32(Depot); w.I32(Parts); w.Flags(0); } public static MaintenanceRecordInfo Read(ref SpanReader r) { var m = new MaintenanceRecordInfo { Day = r.I64(), Intervention = r.String(), Cost = r.Money(), Depot = r.I32(), Parts = r.I32() }; r.Flags(); return m; } } /// /// Cartella di manutenzione di un treno (10.3): componenti per veicolo, guasto in corso, politica, /// prossimo intervento, costi dell'anno e storico. Si invia su richiesta (RequestDetail). /// public sealed class MaintenanceCard : IMessage { public MessageId Id => MessageId.MaintenanceCard; public int Train { get; init; } public long Day { get; init; } public float Condition { get; init; } public TrainMaintenanceStatus Status { get; init; } /// Politica effettiva e quella propria del treno (255 = ereditata). public byte Policy { get; init; } public byte PolicyOverride { get; init; } = byte.MaxValue; public bool Reserve { get; init; } /// FailureKind di Core e componente guasto. public byte Failure { get; init; } public int FailedVehicle { get; init; } = -1; public string FailedComponent { get; init; } = ""; /// Ore (orologio dei treni) all'arrivo del soccorso, −1 se non serve. public float RescueHours { get; init; } = -1; public string NextIntervention { get; init; } = ""; public float NextDueDays { get; init; } public string PlannedIntervention { get; init; } = ""; public int MaintenanceDepot { get; init; } = -1; public float ServiceKmPerDay { get; init; } public Money CostThisYear { get; init; } public Money CostLastYear { get; init; } public int FailuresThisYear { get; init; } public int FailuresTotal { get; init; } public int CoveredBy { get; init; } = -1; public int Covering { get; init; } = -1; public List Vehicles { get; init; } = []; public List History { get; init; } = []; public void Write(ref SpanWriter w) { w.I32(Train); w.I64(Day); w.F32(Condition); w.U8((byte)Status); w.U8(Policy); w.U8(PolicyOverride); w.Bool(Reserve); w.U8(Failure); w.I32(FailedVehicle); w.String(FailedComponent); w.F32(RescueHours); w.String(NextIntervention); w.F32(NextDueDays); w.String(PlannedIntervention); w.I32(MaintenanceDepot); w.F32(ServiceKmPerDay); w.Money(CostThisYear); w.Money(CostLastYear); w.I32(FailuresThisYear); w.I32(FailuresTotal); w.I32(CoveredBy); w.I32(Covering); w.Count(Vehicles.Count); foreach (var v in Vehicles) v.Write(ref w); w.Count(History.Count); foreach (var h in History) h.Write(ref w); w.Flags(0); } public static MaintenanceCard Read(ref SpanReader r) { var m = new MaintenanceCard { Train = r.I32(), Day = r.I64(), Condition = r.F32(), Status = (TrainMaintenanceStatus)r.U8(), Policy = r.U8(), PolicyOverride = r.U8(), Reserve = r.Bool(), Failure = r.U8(), FailedVehicle = r.I32(), FailedComponent = r.String(), RescueHours = r.F32(), NextIntervention = r.String(), NextDueDays = r.F32(), PlannedIntervention = r.String(), MaintenanceDepot = r.I32(), ServiceKmPerDay = r.F32(), CostThisYear = r.Money(), CostLastYear = r.Money(), FailuresThisYear = r.I32(), FailuresTotal = r.I32(), CoveredBy = r.I32(), Covering = r.I32(), }; for (int n = r.Count(), i = 0; i < n; i++) m.Vehicles.Add(VehicleCard.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.History.Add(MaintenanceRecordInfo.Read(ref r)); r.Flags(); return m; } } /// Lavoro nel Registro officina. public sealed class WorkshopJobInfo { public int Train { get; init; } public string Intervention { get; init; } = ""; public bool InStall { get; init; } public bool Started { get; init; } public float Progress { get; init; } public float Days { get; init; } public int Parts { get; init; } public long QueuedDay { get; init; } public void Write(ref SpanWriter w) { w.I32(Train); w.String(Intervention); w.Bool(InStall); w.Bool(Started); w.F32(Progress); w.F32(Days); w.I32(Parts); w.I64(QueuedDay); w.Flags(0); } public static WorkshopJobInfo Read(ref SpanReader r) { var m = new WorkshopJobInfo { Train = r.I32(), Intervention = r.String(), InStall = r.Bool(), Started = r.Bool(), Progress = r.F32(), Days = r.F32(), Parts = r.I32(), QueuedDay = r.I64(), }; r.Flags(); return m; } } /// /// Registro officina di un deposito (10.3): stalli, personale, ricambi, coda dei lavori e treni /// prenotati. Si invia su richiesta (RequestDetail). /// public sealed class WorkshopRegister : IMessage { public MessageId Id => MessageId.WorkshopRegister; public int Depot { get; init; } public long Day { get; init; } public int Stalls { get; init; } public int JobsStaff { get; init; } public float StaffPresent { get; init; } /// Velocità del lavoro (1 a personale completo). public float WorkRate { get; init; } public int SpareParts { get; init; } public int PartsTarget { get; init; } /// Ricambi già destinati a lavori in coda e treni prenotati. public int PartsReserved { get; init; } public List Jobs { get; init; } = []; /// Treni prenotati in arrivo e relativo intervento. public List Booked { get; init; } = []; public void Write(ref SpanWriter w) { w.I32(Depot); w.I64(Day); w.I32(Stalls); w.I32(JobsStaff); w.F32(StaffPresent); w.F32(WorkRate); w.I32(SpareParts); w.I32(PartsTarget); w.I32(PartsReserved); w.Count(Jobs.Count); foreach (var j in Jobs) j.Write(ref w); w.Count(Booked.Count); foreach (var j in Booked) j.Write(ref w); w.Flags(0); } public static WorkshopRegister Read(ref SpanReader r) { var m = new WorkshopRegister { Depot = r.I32(), Day = r.I64(), Stalls = r.I32(), JobsStaff = r.I32(), StaffPresent = r.F32(), WorkRate = r.F32(), SpareParts = r.I32(), PartsTarget = r.I32(), PartsReserved = r.I32(), }; for (int n = r.Count(), i = 0; i < n; i++) m.Jobs.Add(WorkshopJobInfo.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Booked.Add(WorkshopJobInfo.Read(ref r)); r.Flags(); return m; } } public sealed class SharePrice { public int Company { get; init; } public Money Price { get; init; } public float Change { get; init; } public bool Listed { get; init; } // blocco 1 (F5): prezzo esatto, capitalizzazione, flottante libero, quota del fondatore public double PriceCents { get; set; } public long Outstanding { get; set; } public long FreeFloat { get; set; } public float FounderShare { get; set; } public int ControlledBy { get; set; } = -1; public void Write(ref SpanWriter w) { w.I32(Company); w.Money(Price); w.F32(Change); w.Bool(Listed); w.Flags(1); w.F64(PriceCents); w.I64(Outstanding); w.I64(FreeFloat); w.F32(FounderShare); w.I32(ControlledBy); } public static SharePrice Read(ref SpanReader r) { var m = new SharePrice { Company = r.I32(), Price = r.Money(), Change = r.F32(), Listed = r.Bool() }; if ((r.Flags() & 1) != 0) { m.PriceCents = r.F64(); m.Outstanding = r.I64(); m.FreeFloat = r.I64(); m.FounderShare = r.F32(); m.ControlledBy = r.I32(); } return m; } } public sealed class BidInfo { public int Bid { get; init; } public int Bidder { get; init; } public int Target { get; init; } public Money PricePerShare { get; init; } public double TargetShare { get; init; } public long ExpiresDay { get; init; } // blocco 1 (F5): stato, quota già impegnata (azioni dell'offerente + adesioni), difese, cavaliere bianco public byte State { get; set; } public double CommittedShare { get; set; } public byte Defenses { get; set; } public int Knight { get; set; } = -1; /// Vero se la compagnia della sessione ha già aderito. public bool Accepted { get; set; } public void Write(ref SpanWriter w) { w.I32(Bid); w.I32(Bidder); w.I32(Target); w.Money(PricePerShare); w.F64(TargetShare); w.I64(ExpiresDay); w.Flags(1); w.U8(State); w.F64(CommittedShare); w.U8(Defenses); w.I32(Knight); w.Bool(Accepted); } public static BidInfo Read(ref SpanReader r) { var m = new BidInfo { Bid = r.I32(), Bidder = r.I32(), Target = r.I32(), PricePerShare = r.Money(), TargetShare = r.F64(), ExpiresDay = r.I64() }; if ((r.Flags() & 1) != 0) { m.State = r.U8(); m.CommittedShare = r.F64(); m.Defenses = r.U8(); m.Knight = r.I32(); m.Accepted = r.Bool(); } return m; } } /// Listino giornaliero della borsa e offerte pubbliche in corso (F5). public sealed class MarketTape : IMessage { public MessageId Id => MessageId.MarketTape; public long Day { get; init; } public List Shares { get; init; } = []; public List Bids { get; init; } = []; public void Write(ref SpanWriter w) { w.I64(Day); w.Count(Shares.Count); foreach (var s in Shares) s.Write(ref w); w.Count(Bids.Count); foreach (var b in Bids) b.Write(ref w); w.Flags(0); } public static MarketTape Read(ref SpanReader r) { var m = new MarketTape { Day = r.I64() }; for (int n = r.Count(), i = 0; i < n; i++) m.Shares.Add(SharePrice.Read(ref r)); for (int n = r.Count(), i = 0; i < n; i++) m.Bids.Add(BidInfo.Read(ref r)); r.Flags(); return m; } } /// Esito di un comando, con il numero di sequenza del client e gli id creati. public sealed class CommandResultMessage : IMessage { public MessageId Id => MessageId.CommandResult; public uint Seq { get; init; } public ushort Type { get; init; } public ushort Error { get; init; } public string Message { get; init; } = ""; public int[] Created { get; init; } = []; public long Tick { get; init; } public bool Ok => Error == 0; public void Write(ref SpanWriter w) { w.U32(Seq); w.U16(Type); w.U16(Error); w.String(Message); w.Count(Created.Length); foreach (int c in Created) w.I32(c); w.I64(Tick); w.Flags(0); } public static CommandResultMessage Read(ref SpanReader r) { uint seq = r.U32(); ushort type = r.U16(), error = r.U16(); string message = r.String(); var created = new int[r.Count()]; for (int i = 0; i < created.Length; i++) created[i] = r.I32(); var m = new CommandResultMessage { Seq = seq, Type = type, Error = error, Message = message, Created = created, Tick = r.I64() }; r.Flags(); return m; } } /// Notifica immediata (evento rilevante per la compagnia della sessione). public sealed class Notification : IMessage { public MessageId Id => MessageId.Notification; public required EventInfo Event { get; init; } public void Write(ref SpanWriter w) { Event.Write(ref w); w.Flags(0); } public static Notification Read(ref SpanReader r) { var m = new Notification { Event = EventInfo.Read(ref r) }; r.Flags(); return m; } } /// La «Cronaca» mensile. public sealed class Newspaper : IMessage { public MessageId Id => MessageId.Newspaper; public long Day { get; init; } public string Title { get; init; } = ""; public List<(string Headline, string Body)> Articles { get; init; } = []; public void Write(ref SpanWriter w) { w.I64(Day); w.String(Title); w.Count(Articles.Count); foreach (var (h, b) in Articles) { w.String(h); w.String(b); } w.Flags(0); } public static Newspaper Read(ref SpanReader r) { var m = new Newspaper { Day = r.I64(), Title = r.String() }; for (int n = r.Count(), i = 0; i < n; i++) m.Articles.Add((r.String(), r.String())); r.Flags(); return m; } } public sealed class SaveInfo { public string SaveId { get; init; } = ""; public string Name { get; init; } = ""; public string GameDate { get; init; } = ""; public long SizeBytes { get; init; } public long SavedUnixMs { get; init; } public bool Autosave { get; init; } public void Write(ref SpanWriter w) { w.String(SaveId); w.String(Name); w.String(GameDate); w.I64(SizeBytes); w.I64(SavedUnixMs); w.Bool(Autosave); w.Flags(0); } public static SaveInfo Read(ref SpanReader r) { var m = new SaveInfo { SaveId = r.String(), Name = r.String(), GameDate = r.String(), SizeBytes = r.I64(), SavedUnixMs = r.I64(), Autosave = r.Bool() }; r.Flags(); return m; } } /// Risposta a ListSaves e a Save (salvataggi disponibili sul server). public sealed class SaveList : IMessage { public MessageId Id => MessageId.SaveList; public List Saves { get; init; } = []; public void Write(ref SpanWriter w) { w.Count(Saves.Count); foreach (var s in Saves) s.Write(ref w); w.Flags(0); } public static SaveList Read(ref SpanReader r) { var m = new SaveList(); for (int n = r.Count(), i = 0; i < n; i++) m.Saves.Add(SaveInfo.Read(ref r)); r.Flags(); return m; } }