-
Notifications
You must be signed in to change notification settings - Fork 324
/
StreamingWorld.cs
1838 lines (1578 loc) · 76.4 KB
/
StreamingWorld.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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Project: Daggerfall Tools For Unity
// Copyright: Copyright (C) 2009-2020 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors: LypyL, Hazelnut
//
// Notes:
//
#define SHOW_LAYOUT_TIMES
//#define SHOW_LAYOUT_TIMES_NATURE
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using DaggerfallConnect;
using DaggerfallConnect.Arena2;
using DaggerfallConnect.Utility;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.Utility;
using DaggerfallWorkshop.Game.Serialization;
using Unity.Jobs;
namespace DaggerfallWorkshop
{
/// <summary>
/// Manages terrains for streaming world at runtime.
/// At runtime only coordinates from LocalPlayerGPS will be used. Be sure to apply desired preview to PlayerGPS.
/// Terrain tiles are spread outwards from a centre tile up to TerrainDistance around player.
/// Terrains will be marked inactive once they pass beyond TerrainDistance.
/// Inactive terrains greater than TerrainDistance+1 from player will be recycled.
/// Locations and other loose objects greater than TerrainDistance+1 from player will be destroyed.
/// </summary>
public class StreamingWorld : MonoBehaviour
{
#region Fields
const HideFlags defaultHideFlags = HideFlags.None;
const int maxTerrainArray = 256; // Maximum terrains in memory at any time
// Local player GPS for tracking player virtual position
public PlayerGPS LocalPlayerGPS;
// Number of terrains tiles to load around central terrain tile
// Each terrain is equivalent to one full city area of 8x8 RMB blocks
// 1 : ( 2 * 1 + 1 ) * ( 2 * 1 + 1 ) = 9 tiles
// 2 : ( 2 * 2 + 1 ) * ( 2 * 2 + 1 ) = 25 tiles
// 3 : ( 2 * 3 + 1 ) * ( 2 * 3 + 1 ) = 49 tiles
// 4 : ( 2 * 4 + 1 ) * ( 2 * 4 + 1 ) = 81 tiles
[Range(1, 4)]
public int TerrainDistance = 3;
// This controls central map pixel for streaming world
// Synced to PlayerGPS at runtime
[Range(TerrainHelper.minMapPixelX, TerrainHelper.maxMapPixelX)]
public int MapPixelX = TerrainHelper.defaultMapPixelX;
[Range(TerrainHelper.minMapPixelY, TerrainHelper.maxMapPixelY)]
public int MapPixelY = TerrainHelper.defaultMapPixelY;
// Increasing scale will amplify height of small details
// This scale is replicated to every managed terrain
// Not recommended to use greater than default value
[Range(TerrainHelper.minTerrainScale, TerrainHelper.maxTerrainScale)]
public float TerrainScale = TerrainHelper.defaultTerrainScale;
[HideInInspector]
public string EditorFindLocationString = "Daggerfall/Privateer's Hold";
//public bool AddLocationBeacon = false;
public GameObject streamingTarget = null;
public bool suppressWorld = false;
public bool ShowDebugString = false;
// List of terrain objects
// Terrains all have the same format and will be endlessly recycled
TerrainDesc[] terrainArray = new TerrainDesc[maxTerrainArray];
Dictionary<int, int> terrainIndexDict = new Dictionary<int, int>();
// List of loose objects, such as locations or loot containers
// These objects are not recycled and will created/destroyed as needed
List<LooseObjectDesc> looseObjectsList = new List<LooseObjectDesc>();
// Compensation for floating origin
Vector3 worldCompensation = Vector3.zero;
Vector3 playerStartPos;
Vector3 lastPlayerPos;
DaggerfallUnity dfUnity;
DFPosition mapOrigin;
double worldX, worldZ;
readonly TerrainTexturing terrainTexturing = new TerrainTexturing();
bool isReady = false;
Vector3 autoRepositionOffset = Vector3.zero;
RepositionMethods autoRepositionMethod = RepositionMethods.RandomStartMarker;
bool init;
bool terrainUpdateRunning;
bool updateLocatations;
DaggerfallLocation currentPlayerLocationObject;
int playerTilemapIndex = -1;
DFPosition prevMapPixel;
private int? travelStartX = null;
private int? travelStartZ = null;
#endregion
#region Properties
/// <summary>
/// True if component is ready.
/// </summary>
public bool IsReady { get { return ReadyCheck(); } }
/// <summary>
/// True if world is currently initialising.
/// </summary>
public bool IsInit { get { return init; } }
/// <summary>
/// Gets the scene name for the current map pixel.
/// </summary>
public string SceneName { get { return GetSceneName(MapPixelX, MapPixelY); } }
/// <summary>Gets the scene name for the given map pixel.</summary>
public static string GetSceneName(int MapPixelX, int MapPixelY)
{
return string.Format("DaggerfallWorld [mapX={0}, mapY={1}]", MapPixelX, MapPixelY);
}
/// <summary>
/// Gets Transform of central terrain player is standing on.
/// </summary>
public Transform PlayerTerrainTransform { get { return GetPlayerTerrainTransform(); } }
/// <summary>
/// Offset position of world for floating origin logic.
/// </summary>
public Vector3 WorldCompensation { get { return worldCompensation; } }
/// <summary>
/// This value is the amount of scene player movement equivalent to 1 native world map unit.
/// </summary>
public static float SceneMapRatio { get { return 1f / MeshReader.GlobalScale; } }
// Streaming world objects are ultimately parented to this object
// If left null, world objects will be parented to this transform
// This allows for decoupling of GPS logic and streaming functions
public Transform StreamingTarget
{
get { return (streamingTarget != null) ? streamingTarget.transform : this.transform; }
}
public TerrainTexturing TerrainTexturing
{
get { return terrainTexturing; }
}
/// <summary>
/// Gets current DaggerfallLocation (if any) for player's current map pixel.
/// Will return null for any map pixel in wilderness or if world still being built on init.
/// </summary>
public DaggerfallLocation CurrentPlayerLocationObject
{
get { return currentPlayerLocationObject; }
}
/// <summary>
/// Gets index of tile under player at their current world position.
/// There are many different tiles a player can stand on, including corner tiles for roads, etc.
/// The main tile types in nature are:
/// -1 = Nothing/Error
/// 0 = Water
/// 1 = Dirt (snow in winter set)
/// 2 = Grass (snow in winter set)
/// 3 = Stone (snow in winter set)
/// </summary>
public int PlayerTileMapIndex
{
get { return playerTilemapIndex; }
}
public bool IsRepositioningPlayer { get; private set; }
#endregion
#region Structs/Enums
public struct TerrainDesc
{
public bool active;
public bool updateData;
public bool updateNature;
public bool updateLocation;
public bool hasLocation;
public GameObject terrainObject;
public GameObject billboardBatchObject;
public int mapPixelX;
public int mapPixelY;
}
struct LooseObjectDesc
{
public GameObject gameObject;
public int mapPixelX;
public int mapPixelY;
public bool statefulObj;
}
/// <summary>
/// Methods for auto-reposition logic.
/// </summary>
public enum RepositionMethods
{
None,
Origin,
Offset,
DungeonEntrance,
RandomStartMarker,
DirectionFromStartMarker,
}
#endregion
#region Unity
private void Awake()
{
SaveLoadManager.OnStartLoad += SaveLoadManager_OnStartLoad;
StartGameBehaviour.OnNewGame += StartGameBehaviour_OnNewGame;
}
void Update()
{
// Cannot proceed until ready and player is set
if (!ReadyCheck())
return;
// Handle moving to new map pixel or first-time init
DFPosition curMapPixel = LocalPlayerGPS.CurrentMapPixel;
if (curMapPixel.X != MapPixelX ||
curMapPixel.Y != MapPixelY ||
init)
{
Debug.Log(string.Format("Entering new map pixel X={0}, Y={1}", curMapPixel.X, curMapPixel.Y));
prevMapPixel = new DFPosition(MapPixelX, MapPixelY);
MapPixelX = curMapPixel.X;
MapPixelY = curMapPixel.Y;
UpdateWorld();
InitPlayerTerrain();
StartCoroutine(UpdateTerrains());
updateLocatations = true;
init = false;
}
// Exit if terrain data still updating
// Raise location update flag any time terrain updates
if (terrainUpdateRunning)
{
updateLocatations = true;
return;
}
// Update locations when terrain data finished
// This flag is raised during terrain update
if (updateLocatations)
{
UpdateLocations();
updateLocatations = false;
}
// Reposition player
if (autoRepositionMethod != RepositionMethods.None)
{
switch (autoRepositionMethod)
{
case RepositionMethods.DirectionFromStartMarker:
case RepositionMethods.RandomStartMarker:
PositionPlayerToLocation();
break;
case RepositionMethods.Offset:
RepositionPlayer(MapPixelX, MapPixelY, autoRepositionOffset);
break;
case RepositionMethods.DungeonEntrance:
PositionPlayerToDungeonExit();
break;
default:
case RepositionMethods.Origin:
RepositionPlayer(MapPixelX, MapPixelY, Vector3.zero);
break;
}
autoRepositionMethod = RepositionMethods.None;
}
// Do not update world position if player is inside dungeon
// This can cause player to become desynced from world as dungeon can
// actually extend beyond the current map pixel area
if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideDungeon)
return;
// Get distance player has moved in world map units and apply to world position
Vector3 playerPos = LocalPlayerGPS.transform.position;
worldX += (playerPos.x - lastPlayerPos.x) * SceneMapRatio;
worldZ += (playerPos.z - lastPlayerPos.z) * SceneMapRatio;
// Sync PlayerGPS to new world position
LocalPlayerGPS.WorldX = (int)worldX;
LocalPlayerGPS.WorldZ = (int)worldZ;
// Update last player position
lastPlayerPos = playerPos;
// Update index of terrain tile beneath player in world
UpdatePlayerTerrainTileIndex();
}
void UpdatePlayerTerrainTileIndex()
{
playerTilemapIndex = -1;
// Player must be above a known terrain object
DaggerfallTerrain playerTerrain = GetPlayerTerrain();
if (!playerTerrain)
return;
// The terrain must have a valid tilemap array
if (playerTerrain.TileMap == null || playerTerrain.TileMap.Length == 0)
return;
// Get player relative position from terrain origin
Vector3 relativePos = lastPlayerPos - playerTerrain.transform.position;
// Convert X, Z position into 0-1 domain
float dim = MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale;
float u = relativePos.x / dim;
float v = relativePos.z / dim;
// Get clamped offset into tilemap array
int x = Mathf.Clamp((int)(MapsFile.WorldMapTileDim * u), 0, MapsFile.WorldMapTileDim - 1);
int y = Mathf.Clamp((int)(MapsFile.WorldMapTileDim * v), 0, MapsFile.WorldMapTileDim - 1);
// Update index - divide by 4 to find actual tile base as each tile has 4x variants (flip, rotate, etc.)
playerTilemapIndex = playerTerrain.TileMap[y * MapsFile.WorldMapTileDim + x].r / 4;
//Debug.LogFormat("X={0}, Z={1}, Index={2}", x, y, playerTilemapIndex);
}
void OnGUI()
{
if (Event.current.type.Equals(EventType.Repaint) && ShowDebugString)
{
GUIStyle style = new GUIStyle();
style.normal.textColor = Color.black;
string text = GetDebugString();
GUI.Label(new Rect(10, 30, 800, 24), text, style);
GUI.Label(new Rect(8, 28, 800, 24), text);
}
}
#endregion
#region Public Methods
/// <summary>
/// Teleport to specific map pixel with an optional automatic reposition.
/// </summary>
public void TeleportToCoordinates(int mapPixelX, int mapPixelY, RepositionMethods autoReposition = RepositionMethods.Origin)
{
TeleportToMapPixel(mapPixelX, mapPixelY, Vector3.zero, autoReposition);
}
/// <summary>
/// Teleport to specific map pixel and apply a specific reposition.
/// </summary>
public void TeleportToCoordinates(int mapPixelX, int mapPixelY, Vector3 repositionOffset)
{
TeleportToMapPixel(mapPixelX, mapPixelY, repositionOffset, RepositionMethods.None);
}
/// <summary>
/// Teleport to specific world coordinates.
/// </summary>
public void TeleportToWorldCoordinates(int worldPosX, int worldPosZ)
{
// Convert world coordinates to map pixel and find origin world position of tile
DFPosition mapPixel = MapsFile.WorldCoordToMapPixel(worldPosX, worldPosZ);
DFPosition originWorldPos = MapsFile.MapPixelToWorldCoord(mapPixel.X, mapPixel.Y);
// Find reposition offset based on difference between tile origin and desired absolute position
Vector3 offset = new Vector3(
(worldPosX - originWorldPos.X) / SceneMapRatio,
0,
(worldPosZ - originWorldPos.Y) / SceneMapRatio);
// Teleport to coordinates with reposition
TeleportToMapPixel(mapPixel.X, mapPixel.Y, offset, RepositionMethods.Offset);
}
// Offset world compensation for floating origin world
/// <summary>
/// Offset world compensation for floating origin.
/// </summary>
/// <param name="change">Amount to offset world compensation.</param>
/// <param name="offsetLastPlayerPos">Optionally update last known player position so GPS does not change.</param>
public void OffsetWorldCompensation(Vector3 offset, bool offsetLastPlayerPos = true)
{
worldCompensation += offset;
if (offsetLastPlayerPos)
lastPlayerPos += offset;
RaiseOnFloatingOriginChangeEvent();
}
/// <summary>
/// Returns terrain GameObject from mapPixel, or null if
/// no terrain objects are mapped to that pixel
/// </summary>
public GameObject GetTerrainFromPixel(DFPosition mapPixel)
{
return GetTerrainFromPixel(mapPixel.X, mapPixel.Y);
}
/// <summary>
/// Returns terrain GameObject from mapPixel, or null if
/// no terrain objects are mapped to that pixel
/// </summary>
public GameObject GetTerrainFromPixel(int mapPixelX, int mapPixelY)//##Lypyl
{
//Get Key for terrain lookup
int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY);
if (terrainIndexDict.ContainsKey(key))
return terrainArray[terrainIndexDict[key]].terrainObject;
else
return null;
}
public void SetAutoReposition(RepositionMethods method, Vector3 offset)
{
autoRepositionOffset = offset;
autoRepositionMethod = method;
}
/// <summary>
/// Track an exterior object in streaming world.
/// Tracked object will be automatically destroyed when outside of range.
/// </summary>
/// <param name="gameObject">Game object to track.</param>
/// <param name="statefulObj">True to mark as a stateful game object which is managed by SerializedStateManager.</param>
/// <param name="mapPixelX">Map pixel X to store gameobject. -1 for player location.</param>
/// <param name="mapPixelY">Map pixel Y to store gameobject. -1 for player location.</param>
/// <param name="setParent">True to set parent as StreamingTarget.</param>
public void TrackLooseObject(GameObject gameObject, bool statefulObj = false, int mapPixelX = -1, int mapPixelY = -1, bool setParent = false)
{
// Create loose object description
LooseObjectDesc desc = new LooseObjectDesc();
desc.gameObject = gameObject;
if (mapPixelX == -1)
desc.mapPixelX = MapPixelX;
if (mapPixelY == -1)
desc.mapPixelY = MapPixelY;
desc.statefulObj = statefulObj;
looseObjectsList.Add(desc);
// Change object parent
if (setParent)
gameObject.transform.parent = StreamingTarget.transform;
}
public void ClearStatefulLooseObjects()
{
looseObjectsList.RemoveAll(x => {
if (x.statefulObj)
Destroy(x.gameObject);
return x.statefulObj;
});
}
/// <summary>
/// Gets the building directory for current player position.
/// </summary>
/// <returns>BuildingDirectory or null if player not inside a location map pixel.</returns>
public BuildingDirectory GetCurrentBuildingDirectory()
{
if (!currentPlayerLocationObject)
return null;
return currentPlayerLocationObject.GetComponent<BuildingDirectory>();
}
/// <summary>
/// Gets the city navigation component for current player position.
/// </summary>
/// <returns>CityNavigation or null if player not inside a location map pixel.</returns>
public CityNavigation GetCurrentCityNavigation()
{
if (!currentPlayerLocationObject)
return null;
return currentPlayerLocationObject.GetComponent<CityNavigation>();
}
/// <summary>
/// Gets terrain transform at mapPixelX, mapPixelY.
/// </summary>
/// <returns>DaggerfallTerrain Transform if found, or null if not currently in world.</returns>
public Transform GetTerrainTransform(int mapPixelX, int mapPixelY)
{
int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY);
if (!terrainIndexDict.ContainsKey(key))
return null;
return terrainArray[terrainIndexDict[key]].terrainObject.transform;
}
/// <summary>
/// Gets the DaggerfallLocation component for current player position.
/// </summary>
/// <returns>DaggerfallLocation component if player inside location map pixel, otherwise null.</returns>
private DaggerfallLocation GetPlayerLocationObject()
{
// Look for location at current map pixel coords inside loose object list
for (int i = 0; i < looseObjectsList.Count; i++)
{
LooseObjectDesc desc = looseObjectsList[i];
if (!desc.statefulObj && desc.gameObject && desc.mapPixelX == MapPixelX && desc.mapPixelY == MapPixelY)
{
DaggerfallLocation location = desc.gameObject.GetComponent<DaggerfallLocation>();
if (location)
return location;
}
}
return null;
}
#endregion
#region World Setup Methods
// Init world at startup or when player teleports
private void InitWorld()
{
// Cannot init world without a player, as world positions around player
// Also do nothing if world is on hold at start
if (LocalPlayerGPS == null || suppressWorld)
return;
// Player must be at origin on init for proper world sync
// Starting position will be assigned when terrain ready based on respositionMethod
LocalPlayerGPS.transform.position = Vector3.zero;
// Raise OnPreInitWorld event
RaiseOnPreInitWorldEvent();
// Init streaming world
ClearStreamingWorld();
worldCompensation = Vector3.zero;
mapOrigin = LocalPlayerGPS.CurrentMapPixel;
MapPixelX = mapOrigin.X;
MapPixelY = mapOrigin.Y;
playerStartPos = new Vector3(LocalPlayerGPS.transform.position.x, 0, LocalPlayerGPS.transform.position.z);
lastPlayerPos = playerStartPos;
// Set player world position to match PlayerGPS
// StreamingWorld will then sync player to world
worldX = LocalPlayerGPS.WorldX;
worldZ = LocalPlayerGPS.WorldZ;
init = true;
RaiseOnInitWorldEvent();
}
// Place terrain tiles when player changes map pixels
private void UpdateWorld()
{
int dim = TerrainDistance * 2 + 1;
int xs = MapPixelX - TerrainDistance;
int ys = MapPixelY - TerrainDistance;
for (int y = ys; y < ys + dim; y++)
{
for (int x = xs; x < xs + dim; x++)
{
PlaceTerrain(x, y);
}
}
}
// Fully init central terrain so player can be dropped into world as soon as possible
private void InitPlayerTerrain()
{
if (!init)
return;
#if SHOW_LAYOUT_TIMES
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
CollectLooseObjects();
int playerTerrainIndex = terrainIndexDict[TerrainHelper.MakeTerrainKey(MapPixelX, MapPixelY)];
UpdateTerrainData(terrainArray[playerTerrainIndex]);
terrainArray[playerTerrainIndex].updateData = false;
UpdateTerrainNature(terrainArray[playerTerrainIndex]);
terrainArray[playerTerrainIndex].updateNature = false;
#if SHOW_LAYOUT_TIMES
stopwatch.Stop();
DaggerfallUnity.LogMessage(string.Format("Time to init player terrain: {0}ms", stopwatch.ElapsedMilliseconds), true);
#endif
StartCoroutine(UpdateLocation(playerTerrainIndex, false));
terrainArray[playerTerrainIndex].updateLocation = false;
}
private IEnumerator UpdateTerrains()
{
RaiseOnUpdateTerrainsStartEvent();
terrainUpdateRunning = true;
#if SHOW_LAYOUT_TIMES
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
// Update terrain heights and nature billboards
CollectTerrains();
for (int i = 0; i < terrainArray.Length; i++)
{
if (terrainArray[i].active)
{
if (terrainArray[i].updateData)
{
if (init)
UpdateTerrainData(terrainArray[i]);
else
yield return StartCoroutine(UpdateTerrainDataCoroutine(terrainArray[i]));
terrainArray[i].updateData = false;
}
if (terrainArray[i].updateNature)
{
UpdateTerrainNature(terrainArray[i]);
terrainArray[i].updateNature = false;
if (!init)
yield return new WaitForEndOfFrame();
}
}
}
// If this is an init we can use the load time to unload unused assets
// Keeps memory usage much lower over time
if (init)
{
DaggerfallUnity.Instance.MaterialReader.PruneCache();
DaggerfallGC.ThrottledUnloadUnusedAssets();
}
// Set terrain neighbours
UpdateNeighbours();
#if SHOW_LAYOUT_TIMES
stopwatch.Stop();
DaggerfallUnity.LogMessage(string.Format("Time to update terrains: {0}ms", stopwatch.ElapsedMilliseconds), true);
#endif
terrainUpdateRunning = false;
RaiseOnUpdateTerrainsEndEvent();
}
private void UpdateLocations()
{
CollectLooseObjects();
for (int i = 0; i < terrainArray.Length; i++)
{
if (terrainArray[i].active && terrainArray[i].hasLocation)
StartCoroutine(UpdateLocation(i, true));
}
// Update current player location object once location update complete
currentPlayerLocationObject = GetPlayerLocationObject();
// Raise event
RaiseOnAvailableLocationGameObjectEvent();
}
private IEnumerator UpdateLocation(int index, bool allowYield)
{
if (terrainArray[index].active && terrainArray[index].hasLocation && terrainArray[index].updateLocation)
{
#if SHOW_LAYOUT_TIMES
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
// Disable update flag
terrainArray[index].updateLocation = false;
// Create location object
DFLocation location;
GameObject locationObject = CreateLocationGameObject(index, out location);
if (locationObject)
{
// Add building directory to location game object
BuildingDirectory buildingDirectory = locationObject.AddComponent<BuildingDirectory>();
buildingDirectory.SetLocation(location);
// Add location to loose object list
LooseObjectDesc looseObject = new LooseObjectDesc();
looseObject.gameObject = locationObject;
looseObject.mapPixelX = terrainArray[index].mapPixelX;
looseObject.mapPixelY = terrainArray[index].mapPixelY;
looseObject.statefulObj = false;
looseObjectsList.Add(looseObject);
// Create billboard batch game objects for this location
// Streaming world always batches for performance, regardless of options
int natureArchive = ClimateSwaps.GetNatureArchive(LocalPlayerGPS.ClimateSettings.NatureSet, dfUnity.WorldTime.Now.SeasonValue);
//TextureAtlasBuilder miscBillboardAtlas = dfUnity.MaterialReader.MiscBillboardAtlas;
DaggerfallBillboardBatch natureBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(natureArchive, locationObject.transform);
DaggerfallBillboardBatch lightsBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.LightsTextureArchive, locationObject.transform);
DaggerfallBillboardBatch animalsBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.AnimalsTextureArchive, locationObject.transform);
//DaggerfallBillboardBatch miscBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(miscBillboardAtlas.AtlasMaterial, locationObject.transform);
// Set hide flags
natureBillboardBatch.hideFlags = defaultHideFlags;
lightsBillboardBatch.hideFlags = defaultHideFlags;
animalsBillboardBatch.hideFlags = defaultHideFlags;
//miscBillboardBatch.hideFlags = defaultHideFlags;
// Position RMB blocks inside terrain area
int width = location.Exterior.ExteriorData.Width;
int height = location.Exterior.ExteriorData.Height;
DFPosition tilePos = TerrainHelper.GetLocationTerrainTileOrigin(location);
Vector3 origin = new Vector3(tilePos.X * RMBLayout.RMBTileSide, 2.0f * MeshReader.GlobalScale, tilePos.Y * RMBLayout.RMBTileSide);
// Get location component
DaggerfallLocation dfLocation = locationObject.GetComponent<DaggerfallLocation>();
// Create CityNavigation component
CityNavigation cityNavigation = dfLocation.gameObject.AddComponent<CityNavigation>();
cityNavigation.FormatNavigation(location.RegionName, location.Name, width, height);
// Create PopulationManager component for locations with wandering NPCs
if (location.MapTableData.LocationType == DFRegion.LocationTypes.TownCity ||
location.MapTableData.LocationType == DFRegion.LocationTypes.TownHamlet ||
location.MapTableData.LocationType == DFRegion.LocationTypes.TownVillage ||
location.MapTableData.LocationType == DFRegion.LocationTypes.HomeFarms ||
location.MapTableData.LocationType == DFRegion.LocationTypes.HomeWealthy ||
location.MapTableData.LocationType == DFRegion.LocationTypes.ReligionTemple ||
location.MapTableData.LocationType == DFRegion.LocationTypes.Tavern)
{
dfLocation.gameObject.AddComponent<PopulationManager>();
}
// Perform layout and yield after each block is placed
ContentReader contentReader = DaggerfallUnity.Instance.ContentReader;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Set block origin for billboard batches
// This causes next additions to be offset by this position
Vector3 blockOrigin = origin + new Vector3((x * RMBLayout.RMBSide), 0, (y * RMBLayout.RMBSide));
natureBillboardBatch.BlockOrigin = blockOrigin;
lightsBillboardBatch.BlockOrigin = blockOrigin;
animalsBillboardBatch.BlockOrigin = blockOrigin;
//miscBillboardBatch.BlockOrigin = blockOrigin;
// Get block name and data
DFBlock blockData;
string blockName = contentReader.BlockFileReader.CheckName(contentReader.MapFileReader.GetRmbBlockName(ref location, x, y));
RMBLayout.GetBlockData(blockName, out blockData);
// Add block
GameObject go = GameObjectHelper.CreateRMBBlockGameObject(
blockData,
x,
y,
false,
dfUnity.Option_CityBlockPrefab,
natureBillboardBatch,
lightsBillboardBatch,
animalsBillboardBatch,
null,
null,
dfLocation.Summary.Nature,
dfUnity.WorldTime.Now.SeasonValue == DaggerfallDateTime.Seasons.Winter ? ClimateSeason.Winter : ClimateSeason.Summer);
// Set game object properties
go.hideFlags = defaultHideFlags;
go.transform.parent = locationObject.transform;
go.transform.localPosition = blockOrigin;
if (allowYield)
dfLocation.ApplyClimateSettings();
// Set navigation info for this block
cityNavigation.SetRMBData(ref blockData, x, y);
// Optionally yield after placing block
if (allowYield)
yield return new WaitForEndOfFrame();
}
}
// Only apply climate settings after entire location updated if not spanning multiple frames.
if (!allowYield)
dfLocation.ApplyClimateSettings();
// Apply billboard batches
natureBillboardBatch.Apply();
lightsBillboardBatch.Apply();
animalsBillboardBatch.Apply();
//miscBillboardBatch.Apply();
RaiseOnUpdateLocationGameObjectEvent(locationObject, allowYield);
//// TEST: Store a RAW image of navgrid
//string filename = string.Format("{0} [{1}x{2}].raw", location.Name, cityNavigation.CityWidth * 64, cityNavigation.CityHeight * 64);
//cityNavigation.SaveTestRawImage(Path.Combine(@"d:\test\navgrids\", filename));
}
#if SHOW_LAYOUT_TIMES
stopwatch.Stop();
DaggerfallUnity.LogMessage(string.Format("Time to update location {1}: {0}ms", stopwatch.ElapsedMilliseconds, index), true);
#endif
}
}
// Place a single terrain and mark it for update
private void PlaceTerrain(int mapPixelX, int mapPixelY)
{
// Do nothing if out of range
if (mapPixelX < MapsFile.MinMapPixelX || mapPixelX >= MapsFile.MaxMapPixelX ||
mapPixelY < MapsFile.MinMapPixelY || mapPixelY >= MapsFile.MaxMapPixelY)
{
return;
}
// Get terrain key
int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY);
// If terrain is available
if (terrainIndexDict.ContainsKey(key))
{
// Terrain exists, check if active
int index = terrainIndexDict[key];
if (terrainArray[index].active)
{
// Terrain already active in scene, nothing to do
}
else
{
// Terrain inactive but available, re-activate terrain
terrainArray[index].active = true;
terrainArray[index].terrainObject.SetActive(true);
terrainArray[index].billboardBatchObject.SetActive(true);
}
// If any nature model replacements are used then do extra nature updates for any terrains moving into or out of distance 1 or less.
if (TerrainHelper.NatureMeshUsed)
{
int prevDist = GetTerrainDist(prevMapPixel, terrainArray[index].mapPixelX, terrainArray[index].mapPixelY);
int currDist = GetTerrainDist(LocalPlayerGPS.CurrentMapPixel, terrainArray[index].mapPixelX, terrainArray[index].mapPixelY);
if ((prevDist == 1 && currDist > 1) || (currDist == 1 && prevDist > 1))
terrainArray[index].updateNature = true;
}
return;
}
// Need to place a new terrain, find next available terrain
// This will either find a fresh terrain or recycle an old one
int nextTerrain = FindNextAvailableTerrain();
if (nextTerrain == -1)
return;
// Setup new terrain
terrainArray[nextTerrain].active = true;
terrainArray[nextTerrain].updateData = true;
terrainArray[nextTerrain].updateNature = true;
terrainArray[nextTerrain].mapPixelX = mapPixelX;
terrainArray[nextTerrain].mapPixelY = mapPixelY;
if (!terrainArray[nextTerrain].terrainObject)
{
// Create game objects for new terrain
// This is only done once then recycled
CreateTerrainGameObjects(
mapPixelX,
mapPixelY,
out terrainArray[nextTerrain].terrainObject,
out terrainArray[nextTerrain].billboardBatchObject);
}
// Apply local transform
float scale = MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale;
int xdif = mapPixelX - mapOrigin.X;
int ydif = mapPixelY - mapOrigin.Y;
Vector3 localPosition = new Vector3(xdif * scale, 0, -ydif * scale) + WorldCompensation;
terrainArray[nextTerrain].terrainObject.transform.localPosition = localPosition;
// Add new terrain index to dictionary
terrainIndexDict.Add(key, nextTerrain);
// Check if terrain has a location, if so it will be added on next update
ContentReader.MapSummary mapSummary;
terrainArray[nextTerrain].hasLocation = dfUnity.ContentReader.HasLocation(mapPixelX, mapPixelY, out mapSummary);
terrainArray[nextTerrain].updateLocation = terrainArray[nextTerrain].hasLocation;
}
// Finds next available terrain in array
private int FindNextAvailableTerrain()
{
// Evaluate terrain array
int found = -1;
for (int i = 0; i < terrainArray.Length; i++)
{
// A null terrain has never been instantiated and is free
if (terrainArray[i].terrainObject == null)
{
found = i;
break;
}
// Inactive terrain object can be evaluated for recycling based
// on distance from current map pixel
if (!terrainArray[i].active)
{
// If terrain out of range then recycle
if (!IsInRange(terrainArray[i].mapPixelX, terrainArray[i].mapPixelY))
{
found = i;
break;
}
}
}
// Was a terrain found?
if (found != -1)
{
// If we are recycling an inactive terrain, remove it from dictionary first
int key = TerrainHelper.MakeTerrainKey(terrainArray[found].mapPixelX, terrainArray[found].mapPixelY);
if (terrainIndexDict.ContainsKey(key))
{
terrainIndexDict.Remove(key);
}
return found;
}
else
{
// Unable to find an available terrain
// This should never happen unless TerrainDistance too high or maxTerrainArray too low
DaggerfallUnity.LogMessage("StreamingWorld: Unable to find free terrain. Check maxTerrainArray is sized appropriately and you are collecting terrains. This can also happen when player movement speed too high.", true);
if (Application.isEditor)
Debug.Break();
else
Application.Quit();
return -1;
}
}
#endregion
#region World Cleanup Methods
// Remove managed child objects
private void ClearStreamingWorld()
{
// Collect everything
CollectTerrains(true);
CollectLooseObjects(true);
// Clear lists
terrainIndexDict.Clear();
// Raise event
RaiseOnClearStreamingWorldEvent();
}
// Mark inactive any terrains outside of range
private void CollectTerrains(bool collectAll = false)
{
for (int i = 0; i < terrainArray.Length; i++)
{
// Ignore uninitialised and inactive terrains
if (terrainArray[i].terrainObject == null ||
!terrainArray[i].active)
{
continue;
}
// If terrain out of range then mark inactive for recycling
if (!IsInRange(terrainArray[i].mapPixelX, terrainArray[i].mapPixelY) || collectAll)
{
// Mark terrain inactive
terrainArray[i].terrainObject.name = "Pooled";