/
World.cs
590 lines (467 loc) · 15.3 KB
/
World.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
#region Copyright & License Information
/*
* Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Effects;
using OpenRA.FileFormats;
using OpenRA.Graphics;
using OpenRA.Network;
using OpenRA.Orders;
using OpenRA.Primitives;
using OpenRA.Support;
using OpenRA.Traits;
namespace OpenRA
{
public enum WorldType { Regular, Shellmap, Editor }
public sealed class World : IDisposable
{
internal readonly TraitDictionary TraitDict = new TraitDictionary();
readonly SortedDictionary<uint, Actor> actors = new SortedDictionary<uint, Actor>();
readonly List<IEffect> effects = new List<IEffect>();
readonly List<IEffect> unpartitionedEffects = new List<IEffect>();
readonly List<ISync> syncedEffects = new List<ISync>();
readonly Queue<Action<World>> frameEndActions = new Queue<Action<World>>();
public int Timestep;
internal readonly OrderManager OrderManager;
public Session LobbyInfo { get { return OrderManager.LobbyInfo; } }
public readonly MersenneTwister SharedRandom;
public readonly MersenneTwister LocalRandom;
public readonly IModelCache ModelCache;
public Player[] Players = new Player[0];
public void SetPlayers(IEnumerable<Player> players, Player localPlayer)
{
if (Players.Length > 0)
throw new InvalidOperationException("Players are fixed once they have been set.");
Players = players.ToArray();
SetLocalPlayer(localPlayer);
}
public Player LocalPlayer { get; private set; }
public event Action GameOver = () => { };
public bool IsGameOver { get; private set; }
public void EndGame()
{
if (!IsGameOver)
{
IsGameOver = true;
foreach (var t in WorldActor.TraitsImplementing<IGameOver>())
t.GameOver(this);
gameInfo.FinalGameTick = WorldTick;
GameOver();
}
}
Player renderPlayer;
public Player RenderPlayer
{
get
{
return renderPlayer;
}
set
{
if (LocalPlayer == null || LocalPlayer.UnlockedRenderPlayer)
renderPlayer = value;
}
}
public bool FogObscures(Actor a) { return RenderPlayer != null && !a.CanBeViewedByPlayer(RenderPlayer); }
public bool FogObscures(CPos p) { return RenderPlayer != null && !RenderPlayer.Shroud.IsVisible(p); }
public bool FogObscures(WPos pos) { return RenderPlayer != null && !RenderPlayer.Shroud.IsVisible(pos); }
public bool ShroudObscures(CPos p) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(p); }
public bool ShroudObscures(WPos pos) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(pos); }
public bool ShroudObscures(PPos uv) { return RenderPlayer != null && !RenderPlayer.Shroud.IsExplored(uv); }
public bool IsReplay
{
get { return OrderManager.Connection is ReplayConnection; }
}
public bool IsLoadingGameSave
{
get { return OrderManager.NetFrameNumber <= OrderManager.GameSaveLastFrame; }
}
public int GameSaveLoadingPercentage
{
get { return OrderManager.NetFrameNumber * 100 / OrderManager.GameSaveLastFrame; }
}
void SetLocalPlayer(Player localPlayer)
{
if (localPlayer == null)
return;
if (!Players.Contains(localPlayer))
throw new ArgumentException("The local player must be one of the players in the world.", "localPlayer");
if (IsReplay)
return;
LocalPlayer = localPlayer;
// Set the property backing field directly
renderPlayer = LocalPlayer;
}
public readonly Actor WorldActor;
public readonly Map Map;
public readonly IActorMap ActorMap;
public readonly ScreenMap ScreenMap;
public readonly WorldType Type;
readonly GameInformation gameInfo;
public void IssueOrder(Order o) { OrderManager.IssueOrder(o); } /* avoid exposing the OM to mod code */
IOrderGenerator orderGenerator;
public IOrderGenerator OrderGenerator
{
get
{
return orderGenerator;
}
set
{
Sync.AssertUnsynced("The current order generator may not be changed from synced code");
if (orderGenerator != null)
orderGenerator.Deactivate();
orderGenerator = value;
}
}
public readonly ISelection Selection;
public void CancelInputMode() { OrderGenerator = new UnitOrderGenerator(); }
public bool ToggleInputMode<T>() where T : IOrderGenerator, new()
{
if (OrderGenerator is T)
{
CancelInputMode();
return false;
}
else
{
OrderGenerator = new T();
return true;
}
}
public bool RulesContainTemporaryBlocker { get; private set; }
bool wasLoadingGameSave;
internal World(ModData modData, Map map, OrderManager orderManager, WorldType type)
{
Type = type;
OrderManager = orderManager;
orderGenerator = new UnitOrderGenerator();
Map = map;
Timestep = orderManager.LobbyInfo.GlobalSettings.Timestep;
SharedRandom = new MersenneTwister(orderManager.LobbyInfo.GlobalSettings.RandomSeed);
LocalRandom = new MersenneTwister();
ModelCache = modData.ModelSequenceLoader.CacheModels(map, modData, map.Rules.ModelSequences);
var worldActorType = type == WorldType.Editor ? "EditorWorld" : "World";
WorldActor = CreateActor(worldActorType, new TypeDictionary());
ActorMap = WorldActor.Trait<IActorMap>();
ScreenMap = WorldActor.Trait<ScreenMap>();
Selection = WorldActor.Trait<ISelection>();
Selection.SetNotifySelection(WorldActor.TraitsImplementing<INotifySelection>());
// Add players
foreach (var cmp in WorldActor.TraitsImplementing<ICreatePlayers>())
cmp.CreatePlayers(this);
// Set defaults for any unset stances
foreach (var p in Players)
foreach (var q in Players)
if (!p.Stances.ContainsKey(q))
p.Stances[q] = Stance.Neutral;
Game.Sound.SoundVolumeModifier = 1.0f;
gameInfo = new GameInformation
{
Mod = Game.ModData.Manifest.Id,
Version = Game.ModData.Manifest.Metadata.Version,
MapUid = Map.Uid,
MapTitle = Map.Title
};
RulesContainTemporaryBlocker = map.Rules.Actors.Any(a => a.Value.HasTraitInfo<ITemporaryBlockerInfo>());
}
public void AddToMaps(Actor self, IOccupySpace ios)
{
ActorMap.AddInfluence(self, ios);
ActorMap.AddPosition(self, ios);
ScreenMap.AddOrUpdate(self);
}
public void UpdateMaps(Actor self, IOccupySpace ios)
{
if (!self.IsInWorld)
return;
ScreenMap.AddOrUpdate(self);
ActorMap.UpdatePosition(self, ios);
}
public void RemoveFromMaps(Actor self, IOccupySpace ios)
{
ActorMap.RemoveInfluence(self, ios);
ActorMap.RemovePosition(self, ios);
ScreenMap.Remove(self);
}
public void LoadComplete(WorldRenderer wr)
{
if (IsLoadingGameSave)
{
wasLoadingGameSave = true;
Game.Sound.DisableAllSounds = true;
foreach (var nsr in WorldActor.TraitsImplementing<INotifyGameLoading>())
nsr.GameLoading(this);
}
// ScreenMap must be initialized before anything else
using (new PerfTimer("ScreenMap.WorldLoaded"))
ScreenMap.WorldLoaded(this, wr);
foreach (var iwl in WorldActor.TraitsImplementing<IWorldLoaded>())
{
// These have already been initialized
if (iwl == ScreenMap)
continue;
using (new PerfTimer(iwl.GetType().Name + ".WorldLoaded"))
iwl.WorldLoaded(this, wr);
}
foreach (var p in Players)
foreach (var iwl in p.PlayerActor.TraitsImplementing<IWorldLoaded>())
using (new PerfTimer(iwl.GetType().Name + ".WorldLoaded"))
iwl.WorldLoaded(this, wr);
gameInfo.StartTimeUtc = DateTime.UtcNow;
foreach (var player in Players)
gameInfo.AddPlayer(player, OrderManager.LobbyInfo);
var echo = OrderManager.Connection as EchoConnection;
var rc = echo != null ? echo.Recorder : null;
if (rc != null)
rc.Metadata = new ReplayMetadata(gameInfo);
}
public void SetWorldOwner(Player p)
{
WorldActor.Owner = p;
}
public Actor CreateActor(string name, TypeDictionary initDict)
{
return CreateActor(true, name, initDict);
}
public Actor CreateActor(bool addToWorld, string name, TypeDictionary initDict)
{
var a = new Actor(this, name, initDict);
foreach (var t in a.TraitsImplementing<INotifyCreated>())
t.Created(a);
if (addToWorld)
Add(a);
return a;
}
public void Add(Actor a)
{
a.IsInWorld = true;
actors.Add(a.ActorID, a);
ActorAdded(a);
foreach (var t in a.TraitsImplementing<INotifyAddedToWorld>())
t.AddedToWorld(a);
}
public void Remove(Actor a)
{
a.IsInWorld = false;
actors.Remove(a.ActorID);
ActorRemoved(a);
foreach (var t in a.TraitsImplementing<INotifyRemovedFromWorld>())
t.RemovedFromWorld(a);
}
public void Add(IEffect e)
{
effects.Add(e);
var sp = e as ISpatiallyPartitionable;
if (sp == null)
unpartitionedEffects.Add(e);
var se = e as ISync;
if (se != null)
syncedEffects.Add(se);
}
public void Remove(IEffect e)
{
effects.Remove(e);
var sp = e as ISpatiallyPartitionable;
if (sp == null)
unpartitionedEffects.Remove(e);
var se = e as ISync;
if (se != null)
syncedEffects.Remove(se);
}
public void RemoveAll(Predicate<IEffect> predicate)
{
effects.RemoveAll(predicate);
unpartitionedEffects.RemoveAll(e => predicate((IEffect)e));
syncedEffects.RemoveAll(e => predicate((IEffect)e));
}
public void AddFrameEndTask(Action<World> a) { frameEndActions.Enqueue(a); }
public event Action<Actor> ActorAdded = _ => { };
public event Action<Actor> ActorRemoved = _ => { };
public bool Paused { get; internal set; }
public bool PredictedPaused { get; internal set; }
public bool PauseStateLocked { get; set; }
public int WorldTick { get; private set; }
Dictionary<int, MiniYaml> gameSaveTraitData = new Dictionary<int, MiniYaml>();
internal void AddGameSaveTraitData(int traitIndex, MiniYaml yaml)
{
gameSaveTraitData[traitIndex] = yaml;
}
public void SetPauseState(bool paused)
{
if (PauseStateLocked)
return;
IssueOrder(Order.PauseGame(paused));
PredictedPaused = paused;
}
public void SetLocalPauseState(bool paused)
{
Paused = PredictedPaused = paused;
}
public void Tick()
{
if (wasLoadingGameSave && !IsLoadingGameSave)
{
foreach (var kv in gameSaveTraitData)
{
var tp = TraitDict.ActorsWithTrait<IGameSaveTraitData>()
.Skip(kv.Key)
.FirstOrDefault();
if (tp.Actor == null)
break;
tp.Trait.ResolveTraitData(tp.Actor, kv.Value.Nodes);
}
gameSaveTraitData.Clear();
Game.Sound.DisableAllSounds = false;
foreach (var nsr in WorldActor.TraitsImplementing<INotifyGameLoaded>())
nsr.GameLoaded(this);
wasLoadingGameSave = false;
}
if (!Paused)
{
WorldTick++;
using (new PerfSample("tick_actors"))
foreach (var a in actors.Values)
a.Tick();
ActorsWithTrait<ITick>().DoTimed(x => x.Trait.Tick(x.Actor), "Trait");
effects.DoTimed(e => e.Tick(this), "Effect");
}
while (frameEndActions.Count != 0)
frameEndActions.Dequeue()(this);
}
// For things that want to update their render state once per tick, ignoring pause state
public void TickRender(WorldRenderer wr)
{
ActorsWithTrait<ITickRender>().DoTimed(x => x.Trait.TickRender(wr, x.Actor), "Render");
ScreenMap.TickRender();
}
public IEnumerable<Actor> Actors { get { return actors.Values; } }
public IEnumerable<IEffect> Effects { get { return effects; } }
public IEnumerable<IEffect> UnpartitionedEffects { get { return unpartitionedEffects; } }
public IEnumerable<ISync> SyncedEffects { get { return syncedEffects; } }
public Actor GetActorById(uint actorId)
{
Actor a;
if (actors.TryGetValue(actorId, out a))
return a;
return null;
}
uint nextAID = 0;
internal uint NextAID()
{
return nextAID++;
}
public int SyncHash()
{
// using (new PerfSample("synchash"))
{
var n = 0;
var ret = 0;
// Hash all the actors.
foreach (var a in Actors)
ret += n++ * (int)(1 + a.ActorID) * Sync.HashActor(a);
// Hash fields marked with the ISync interface.
foreach (var actor in ActorsHavingTrait<ISync>())
foreach (var syncHash in actor.SyncHashes)
ret += n++ * (int)(1 + actor.ActorID) * syncHash.Hash();
// Hash game state relevant effects such as projectiles.
foreach (var sync in SyncedEffects)
ret += n++ * Sync.Hash(sync);
// Hash the shared random number generator.
ret += SharedRandom.Last;
// Hash player RenderPlayer status
foreach (var p in Players)
if (p.UnlockedRenderPlayer)
ret += Sync.HashPlayer(p);
return ret;
}
}
public IEnumerable<TraitPair<T>> ActorsWithTrait<T>()
{
return TraitDict.ActorsWithTrait<T>();
}
public IEnumerable<Actor> ActorsHavingTrait<T>()
{
return TraitDict.ActorsHavingTrait<T>();
}
public IEnumerable<Actor> ActorsHavingTrait<T>(Func<T, bool> predicate)
{
return TraitDict.ActorsHavingTrait(predicate);
}
public void OnPlayerWinStateChanged(Player player)
{
var pi = gameInfo.GetPlayer(player);
if (pi != null)
{
pi.Outcome = player.WinState;
pi.OutcomeTimestampUtc = DateTime.UtcNow;
}
}
public void RequestGameSave(string filename)
{
// Allow traits to save arbitrary data that will be passed back via IGameSaveTraitData.ResolveTraitData
// at the end of the save restoration
// TODO: This will need to be generalized to a request / response pair for multiplayer game saves
var i = 0;
foreach (var tp in TraitDict.ActorsWithTrait<IGameSaveTraitData>())
{
var data = tp.Trait.IssueTraitData(tp.Actor);
if (data != null)
{
var yaml = new List<MiniYamlNode>() { new MiniYamlNode(i.ToString(), new MiniYaml("", data)) };
IssueOrder(new Order("GameSaveTraitData", null, false)
{
IsImmediate = true,
TargetString = yaml.WriteToString()
});
}
i++;
}
IssueOrder(new Order("CreateGameSave", null, false)
{
IsImmediate = true,
TargetString = filename
});
}
public bool Disposing;
public void Dispose()
{
Disposing = true;
if (OrderGenerator != null)
OrderGenerator.Deactivate();
frameEndActions.Clear();
Game.Sound.StopAudio();
Game.Sound.StopVideo();
if (IsLoadingGameSave)
Game.Sound.DisableAllSounds = false;
ModelCache.Dispose();
// Dispose newer actors first, and the world actor last
foreach (var a in actors.Values.Reverse())
a.Dispose();
// Actor disposals are done in a FrameEndTask
while (frameEndActions.Count != 0)
frameEndActions.Dequeue()(this);
}
}
public struct TraitPair<T> : IEquatable<TraitPair<T>>
{
public readonly Actor Actor;
public readonly T Trait;
public TraitPair(Actor actor, T trait) { Actor = actor; Trait = trait; }
public static bool operator ==(TraitPair<T> me, TraitPair<T> other) { return me.Actor == other.Actor && Equals(me.Trait, other.Trait); }
public static bool operator !=(TraitPair<T> me, TraitPair<T> other) { return !(me == other); }
public override int GetHashCode() { return Actor.GetHashCode() ^ Trait.GetHashCode(); }
public bool Equals(TraitPair<T> other) { return this == other; }
public override bool Equals(object obj) { return obj is TraitPair<T> && Equals((TraitPair<T>)obj); }
public override string ToString() { return Actor.Info.Name + "->" + Trait.GetType().Name; }
}
}