-
Notifications
You must be signed in to change notification settings - Fork 3
/
fleet.go
1485 lines (1266 loc) · 52.8 KB
/
fleet.go
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
package cs
import (
"fmt"
"math"
"github.com/rs/zerolog/log"
)
// warpspeed for using a stargate vs moving with warp drive
const StargateWarpSpeed = 11
// time period to perform a task, like patrol
const Indefinite = 0
// use automatic warp speed for patrols
const PatrolWarpSpeedAutomatic = 0
// target fleets in any range when patrolling
const PatrolRangeInfinite = 0
// no target planet, player, etc
const None = 0
// Fleets are player owned collections of ships. Fleets have a slice of Tokens, one for each unique design
// in the fleet. Fleets also have orders that can be updated by the player, in the form of waypoints and the battle plan.
// Fleets are one of the commandable MapObjects in the game.
type Fleet struct {
MapObject
FleetOrders
PlanetNum int `json:"planetNum"` // for starbase fleets that are owned by a planet
BaseName string `json:"baseName"`
Cargo Cargo `json:"cargo,omitempty"`
Fuel int `json:"fuel"`
Age int `json:"age"`
Tokens []ShipToken `json:"tokens"`
Heading Vector `json:"heading,omitempty"`
WarpSpeed int `json:"warpSpeed,omitempty"`
PreviousPosition *Vector `json:"previousPosition,omitempty"`
OrbitingPlanetNum int `json:"orbitingPlanetNum,omitempty"`
Starbase bool `json:"starbase,omitempty"`
Spec FleetSpec `json:"spec,omitempty"`
battlePlan *BattlePlan
struckMineField bool
remoteMined bool
}
type FleetOrders struct {
Waypoints []Waypoint `json:"waypoints"`
RepeatOrders bool `json:"repeatOrders,omitempty"`
BattlePlanNum int `json:"battlePlanNum,omitempty"`
Purpose FleetPurpose `json:"purpose,omitempty"`
}
type FleetSpec struct {
ShipDesignSpec
BaseCloakedCargo int `json:"baseCloakedCargo"`
BasePacketSpeed int `json:"basePacketSpeed"`
HasMassDriver bool `json:"hasMassDriver,omitempty"`
HasStargate bool `json:"hasStargate,omitempty"`
MassDriver string `json:"massDriver,omitempty"`
MassEmpty int `json:"massEmpty"`
MaxHullMass int `json:"maxHullMass,omitempty"`
MaxRange int `json:"maxRange,omitempty"`
Purposes map[ShipDesignPurpose]bool `json:"purposes"`
SafeHullMass int `json:"safeHullMass,omitempty"`
SafeRange int `json:"safeRange,omitempty"`
Stargate string `json:"stargate,omitempty"`
TotalShips int `json:"totalShips"`
}
type Waypoint struct {
Position Vector `json:"position"`
WarpSpeed int `json:"warpSpeed"`
EstFuelUsage int `json:"estFuelUsage,omitempty"`
Task WaypointTask `json:"task"`
TransportTasks WaypointTransportTasks `json:"transportTasks,omitempty"`
WaitAtWaypoint bool `json:"waitAtWaypoint,omitempty"`
LayMineFieldDuration int `json:"layMineFieldDuration,omitempty"`
PatrolRange int `json:"patrolRange,omitempty"`
PatrolWarpSpeed int `json:"patrolWarpSpeed,omitempty"`
TargetType MapObjectType `json:"targetType,omitempty"`
TargetNum int `json:"targetNum,omitempty"`
TargetPlayerNum int `json:"targetPlayerNum,omitempty"`
TargetName string `json:"targetName,omitempty"`
TransferToPlayer int `json:"transferToPlayer,omitempty"`
PartiallyComplete bool `json:"partiallyComplete,omitempty"`
processed bool `json:"-"`
}
type WaypointTask string
const (
WaypointTaskNone = ""
WaypointTaskTransport = "Transport"
WaypointTaskColonize = "Colonize"
WaypointTaskRemoteMining = "RemoteMining"
WaypointTaskMergeWithFleet = "MergeWithFleet"
WaypointTaskScrapFleet = "ScrapFleet"
WaypointTaskLayMineField = "LayMineField"
WaypointTaskPatrol = "Patrol"
WaypointTaskRoute = "Route"
WaypointTaskTransferFleet = "TransferFleet"
)
type WaypointTransportTasks struct {
Fuel WaypointTransportTask `json:"fuel"`
Ironium WaypointTransportTask `json:"ironium"`
Boranium WaypointTransportTask `json:"boranium"`
Germanium WaypointTransportTask `json:"germanium"`
Colonists WaypointTransportTask `json:"colonists"`
}
type WaypointTransportTask struct {
Amount int `json:"amount,omitempty"`
Action WaypointTaskTransportAction `json:"action,omitempty"`
}
type WaypointTaskTransportAction string
type transportTaskByType map[CargoType]WaypointTransportTask
const (
// No transport task for the specified cargo.
TransportActionNone WaypointTaskTransportAction = ""
// (fuel only) Load or unload fuel until the fleet carries only the exact amount
// needed to reach the next waypoint. You can use this task to send a fleet
// loaded with fuel to rescue a stranded fleet. The rescue fleet will transfer
// only the amount of fuel it can spare without stranding itself.
TransportActionLoadOptimal WaypointTaskTransportAction = "LoadOptimal"
// Load as much of the specified cargo as the fleet can hold.
TransportActionLoadAll WaypointTaskTransportAction = "LoadAll"
// Unload all the specified cargo at the waypoint.
TransportActionUnloadAll WaypointTaskTransportAction = "UnloadAll"
// Load the amount specified only if there is room in the hold.
TransportActionLoadAmount WaypointTaskTransportAction = "LoadAmount"
// Unload the amount specified only if the fleet is carrying that amount.
TransportActionUnloadAmount WaypointTaskTransportAction = "UnloadAmount"
// Loads up to the specified portion of the cargo hold subject to amount available at waypoint and room left in hold.
TransportActionFillPercent WaypointTaskTransportAction = "FillPercent"
// Remain at the waypoint until exactly X % of the hold is filled.
TransportActionWaitForPercent WaypointTaskTransportAction = "WaitForPercent"
// (minerals and colonists only) This command waits until all other loads and unloads are complete,
// then loads as many colonists or amount of a mineral as will fit in the remaining space. For example,
// setting Load All Germanium, Load Dunnage Ironium, will load all the Germanium that is available,
// then as much Ironium as possible. If more than one dunnage cargo is specified, they are loaded in
// the order of Ironium, Boranium, Germanium, and Colonists.
TransportActionLoadDunnage WaypointTaskTransportAction = "LoadDunnage"
// Load or unload the cargo until the amount on board is the amount specified.
// If less than the specified cargo is available, the fleet will not move on.
TransportActionSetAmountTo WaypointTaskTransportAction = "SetAmountTo"
// Load or unload the cargo until the amount at the waypoint is the amount specified.
// This order is always carried out to the best of the fleet’s ability that turn but does not prevent the fleet from moving on.
TransportActionSetWaypointTo WaypointTaskTransportAction = "SetWaypointTo"
)
type FleetPurpose string
const (
FleetPurposeNone FleetPurpose = ""
FleetPurposeScout FleetPurpose = "Scout"
FleetPurposeColonizer FleetPurpose = "Colonizer"
FleetPurposeBomber FleetPurpose = "Bomber"
FleetPurposeFighter FleetPurpose = "Fighter"
FleetPurposeCapitalShip FleetPurpose = "CapitalShip"
FleetPurposeFreighter FleetPurpose = "Freighter"
FleetPurposeColonistFreighter FleetPurpose = "ColonistFreighter"
FleetPurposeArmedFreighter FleetPurpose = "ArmedFreighter"
FleetPurposeMineLayer FleetPurpose = "MineLayer"
FleetPurposeMiner FleetPurpose = "Miner"
FleetPurposeTerraformer FleetPurpose = "Terraformer"
FleetPurposeInvader FleetPurpose = "Invader"
)
func FleetPurposeFromShipDesignPurpose(purpose ShipDesignPurpose) FleetPurpose {
switch purpose {
case ShipDesignPurposeScout:
return FleetPurposeScout
case ShipDesignPurposeColonizer:
return FleetPurposeColonizer
case ShipDesignPurposeBomber:
fallthrough
case ShipDesignPurposeSmartBomber:
fallthrough
case ShipDesignPurposeStructureBomber:
return FleetPurposeBomber
case ShipDesignPurposeFighter:
fallthrough
case ShipDesignPurposeFighterScout:
return FleetPurposeFighter
case ShipDesignPurposeCapitalShip:
return FleetPurposeCapitalShip
case ShipDesignPurposeFreighter:
fallthrough
case ShipDesignPurposeFuelFreighter:
return FleetPurposeFreighter
case ShipDesignPurposeMultiPurposeFreighter:
fallthrough
case ShipDesignPurposeColonistFreighter:
return FleetPurposeColonistFreighter
case ShipDesignPurposeArmedFreighter:
return FleetPurposeArmedFreighter
case ShipDesignPurposeMiner:
return FleetPurposeMiner
case ShipDesignPurposeTerraformer:
return FleetPurposeTerraformer
case ShipDesignPurposeDamageMineLayer:
fallthrough
case ShipDesignPurposeSpeedMineLayer:
return FleetPurposeMineLayer
}
return FleetPurposeNone
}
func newFleet(player *Player, num int, name string, waypoints []Waypoint) Fleet {
return Fleet{
MapObject: MapObject{
Type: MapObjectTypeFleet,
PlayerNum: player.Num,
Dirty: true,
Num: num,
Name: fmt.Sprintf("%s #%d", name, num),
Position: waypoints[0].Position,
},
BaseName: name,
Tokens: []ShipToken{},
FleetOrders: FleetOrders{
Waypoints: waypoints,
},
OrbitingPlanetNum: None,
battlePlan: &player.BattlePlans[0],
}
}
// create a new fleet with a design
func newFleetForDesign(player *Player, design *ShipDesign, quantity, num int, name string, waypoints []Waypoint) Fleet {
return Fleet{
MapObject: MapObject{
Type: MapObjectTypeFleet,
PlayerNum: player.Num,
Dirty: true,
Num: num,
Name: fmt.Sprintf("%s #%d", name, num),
Position: waypoints[0].Position,
},
BaseName: name,
Tokens: []ShipToken{
{design: design, DesignNum: design.Num, Quantity: quantity},
},
FleetOrders: FleetOrders{
Waypoints: waypoints,
},
OrbitingPlanetNum: None,
battlePlan: &player.BattlePlans[0],
}
}
func newFleetForToken(player *Player, num int, token ShipToken, waypoints []Waypoint) Fleet {
return Fleet{
MapObject: MapObject{
Type: MapObjectTypeFleet,
PlayerNum: player.Num,
Dirty: true,
Num: num,
Name: fmt.Sprintf("%s #%d", token.design.Name, num),
Position: waypoints[0].Position,
},
BaseName: token.design.Name,
Tokens: []ShipToken{token},
FleetOrders: FleetOrders{
Waypoints: waypoints,
},
OrbitingPlanetNum: None,
}
}
// create a new fleet that is a starbase
func newStarbase(player *Player, planet *Planet, design *ShipDesign, name string) Fleet {
fleet := newFleetForDesign(player, design, 1, 0, name, []Waypoint{NewPlanetWaypoint(planet.Position, planet.Num, planet.Name, 1)})
fleet.PlanetNum = planet.Num
fleet.Starbase = true
return fleet
}
func (f *Fleet) String() string {
return fmt.Sprintf("Fleet %s #%d", f.BaseName, f.Num)
}
func (f *Fleet) withPlayerNum(playerNum int) *Fleet {
f.PlayerNum = playerNum
return f
}
func (f *Fleet) withNum(num int) *Fleet {
f.Num = num
return f
}
func (f *Fleet) withCargo(cargo Cargo) *Fleet {
f.Cargo = cargo
return f
}
func (f *Fleet) withFuel(fuel int) *Fleet {
f.Fuel = fuel
return f
}
func (f *Fleet) withPosition(position Vector) *Fleet {
f.Position = position
// todo: should we set waypoints in a builder?
f.Waypoints = []Waypoint{{Position: position}}
return f
}
func (f *Fleet) withWaypoints(waypoints ...Waypoint) *Fleet {
f.Waypoints = waypoints
return f
}
func (f *Fleet) withOrbitingPlanetNum(num int) *Fleet {
f.OrbitingPlanetNum = num
return f
}
// get a pointer to a ShipToken a design, or nil if it's not present
func (f *Fleet) getTokenByDesign(designNum int) *ShipToken {
for i, token := range f.Tokens {
if token.DesignNum == designNum {
return &f.Tokens[i]
}
}
return nil
}
func (f *Fleet) Orbiting() bool {
return f.OrbitingPlanetNum != None
}
func (f *Fleet) Idle() bool {
return len(f.Waypoints) == 1 && f.Waypoints[0].Task == WaypointTaskNone
}
func (f *Fleet) Rename(name string) {
f.BaseName = name
f.Name = fmt.Sprintf("%s #%d", f.BaseName, f.Num)
}
func NewPlanetWaypoint(position Vector, num int, name string, warpSpeed int) Waypoint {
return Waypoint{
Position: position,
TargetType: MapObjectTypePlanet,
TargetNum: num,
TargetName: name,
TargetPlayerNum: None,
WarpSpeed: warpSpeed,
}
}
func NewFleetWaypoint(position Vector, num int, playerNum int, name string, warpSpeed int) Waypoint {
return Waypoint{
Position: position,
TargetType: MapObjectTypeFleet,
TargetNum: num,
TargetPlayerNum: playerNum,
TargetName: name,
WarpSpeed: warpSpeed,
}
}
func NewPositionWaypoint(position Vector, warpSpeed int) Waypoint {
return Waypoint{
Position: position,
WarpSpeed: warpSpeed,
TargetNum: None,
TargetPlayerNum: None,
}
}
func (wp *Waypoint) clearTarget() {
wp.TargetName = ""
wp.TargetNum = None
wp.TargetPlayerNum = None
wp.TargetType = MapObjectTypeNone
}
func (wp *Waypoint) targetPlanet(planet *Planet) {
wp.TargetType = MapObjectTypePlanet
wp.TargetName = planet.Name
wp.TargetNum = planet.Num
}
func (wp Waypoint) WithTask(task WaypointTask) Waypoint {
wp.Task = task
return wp
}
func (wp Waypoint) WithTransportTasks(transportTasks WaypointTransportTasks) Waypoint {
wp.TransportTasks = transportTasks
return wp
}
// get a list of transport tasks keyed by cargotype
func (wp Waypoint) getTransportTasks() transportTaskByType {
tasks := transportTaskByType{}
if wp.TransportTasks.Fuel.Action != TransportActionNone {
tasks[Fuel] = wp.TransportTasks.Fuel
}
if wp.TransportTasks.Ironium.Action != TransportActionNone {
tasks[Ironium] = wp.TransportTasks.Ironium
}
if wp.TransportTasks.Boranium.Action != TransportActionNone {
tasks[Boranium] = wp.TransportTasks.Boranium
}
if wp.TransportTasks.Germanium.Action != TransportActionNone {
tasks[Germanium] = wp.TransportTasks.Germanium
}
if wp.TransportTasks.Colonists.Action != TransportActionNone {
tasks[Colonists] = wp.TransportTasks.Colonists
}
return tasks
}
// inject designs into tokens so all the various Compute* functions work
func (f *Fleet) InjectDesigns(designs []*ShipDesign) error {
designsByNum := make(map[int]*ShipDesign, len(designs))
for i := range designs {
design := designs[i]
designsByNum[design.Num] = design
}
// inject the design into this
for i := range f.Tokens {
token := &f.Tokens[i]
token.design = designsByNum[token.DesignNum]
if token.design == nil {
return fmt.Errorf("unable to find design %d for fleet %s", token.DesignNum, f.Name)
}
}
return nil
}
// compute all the computable values of this fleet (cargo capacity, armor, mass)
func ComputeFleetSpec(rules *Rules, player *Player, fleet *Fleet) FleetSpec {
spec := FleetSpec{
ShipDesignSpec: ShipDesignSpec{
ScanRange: NoScanner,
ScanRangePen: NoScanner,
SpaceDock: UnlimitedSpaceDock,
},
Purposes: map[ShipDesignPurpose]bool{},
}
spec.Mass = fleet.Cargo.Total()
for _, token := range fleet.Tokens {
// update our total ship count
spec.TotalShips += token.Quantity
if token.design.Purpose != ShipDesignPurposeNone {
spec.Purposes[token.design.Purpose] = true
}
if token.design.Spec.Starbase {
spec.Starbase = true
}
spec.MaxPopulation = MaxInt(spec.MaxPopulation, token.design.Spec.MaxPopulation)
spec.InnateScanRangePenFactor = math.Max(spec.InnateScanRangePenFactor, token.design.Spec.InnateScanRangePenFactor) // Ultra Station and Death Stars have pen scanning
// use the lowest ideal speed for this fleet
// if we have multiple engines
if (token.design.Spec.Engine != Engine{}) {
if spec.Engine.IdealSpeed == 0 {
spec.Engine.IdealSpeed = token.design.Spec.Engine.IdealSpeed
spec.Engine.FreeSpeed = token.design.Spec.Engine.FreeSpeed
spec.Engine.MaxSafeSpeed = token.design.Spec.Engine.MaxSafeSpeed
} else {
spec.Engine.IdealSpeed = MinInt(spec.Engine.IdealSpeed, token.design.Spec.Engine.IdealSpeed)
spec.Engine.FreeSpeed = token.design.Spec.Engine.FreeSpeed
spec.Engine.MaxSafeSpeed = MinInt(spec.Engine.MaxSafeSpeed, token.design.Spec.Engine.MaxSafeSpeed)
}
}
// cost
spec.Cost = token.design.Spec.Cost.MultiplyInt(token.Quantity)
// mass
spec.Mass += token.design.Spec.Mass * token.Quantity
spec.MassEmpty += token.design.Spec.Mass * token.Quantity
// armor
spec.Armor += token.design.Spec.Armor * token.Quantity
// shield
spec.Shields += token.design.Spec.Shields * token.Quantity
// cargo
spec.CargoCapacity += token.design.Spec.CargoCapacity * token.Quantity
// fuel
spec.FuelCapacity += token.design.Spec.FuelCapacity * token.Quantity
spec.FuelGeneration += token.design.Spec.FuelGeneration * token.Quantity
// minesweep
spec.MineSweep += token.design.Spec.MineSweep * token.Quantity
// remote mining
spec.MiningRate += token.design.Spec.MiningRate * token.Quantity
// remote terraforming
spec.TerraformRate += token.design.Spec.TerraformRate * token.Quantity
// colonization
spec.Colonizer = spec.Colonizer || token.design.Spec.Colonizer
spec.OrbitalConstructionModule = spec.OrbitalConstructionModule || token.design.Spec.OrbitalConstructionModule
// radiating parts
spec.Radiating = spec.Radiating || token.design.Spec.Radiating
// spec all mine layers in the fleet
if token.design.Spec.CanLayMines {
spec.CanLayMines = true
if spec.MineLayingRateByMineType == nil {
spec.MineLayingRateByMineType = make(map[MineFieldType]int)
}
for key := range token.design.Spec.MineLayingRateByMineType {
if _, ok := spec.MineLayingRateByMineType[key]; ok {
spec.MineLayingRateByMineType[key] = 0
}
spec.MineLayingRateByMineType[key] += token.design.Spec.MineLayingRateByMineType[key] * token.Quantity
}
}
// We should only have one ship stack with spacdock capabilities, but for this logic just go with the max
spec.SpaceDock = MaxInt(spec.SpaceDock, token.design.Spec.SpaceDock)
// sadly, the fleet only gets the best repair bonus from one design
spec.RepairBonus = math.Max(spec.RepairBonus, token.design.Spec.RepairBonus)
spec.ScanRange = MaxInt(spec.ScanRange, token.design.Spec.ScanRange)
spec.ScanRangePen = MaxInt(spec.ScanRangePen, token.design.Spec.ScanRangePen)
if token.design.Spec.Scanner {
spec.Scanner = true
}
// add bombs
if token.design.Spec.Bomber {
spec.Bomber = true
for _, bomb := range token.design.Spec.Bombs {
bomb.Quantity *= token.Quantity
spec.Bombs = append(spec.Bombs, bomb)
}
for _, bomb := range token.design.Spec.SmartBombs {
bomb.Quantity *= token.Quantity
spec.SmartBombs = append(spec.SmartBombs, bomb)
}
for _, bomb := range token.design.Spec.RetroBombs {
bomb.Quantity *= token.Quantity
spec.RetroBombs = append(spec.RetroBombs, bomb)
}
}
// check if any tokens have weapons
// we process weapon slots per stack, so we don't need to spec all
// weapons in a fleet
if token.design.Spec.HasWeapons {
spec.HasWeapons = true
}
if token.design.Spec.CloakUnits > 0 {
// calculate the cloak units for this token based on the design's cloak units (i.e. 70 cloak units / kT for a stealh cloak)
spec.CloakUnits += token.design.Spec.CloakUnits
} else {
// if this ship doesn't have cloaking, it counts as cargo (except for races with free cargo cloaking)
if !player.Race.Spec.FreeCargoCloaking {
spec.BaseCloakedCargo += token.design.Spec.Mass * token.Quantity
}
}
// choose the best tachyon detector ship
spec.ReduceCloaking = math.Max(spec.ReduceCloaking, token.design.Spec.ReduceCloaking)
spec.CanStealFleetCargo = spec.CanStealFleetCargo || token.design.Spec.CanStealFleetCargo
spec.CanStealPlanetCargo = spec.CanStealPlanetCargo || token.design.Spec.CanStealPlanetCargo
// stargate fields
if token.design.Spec.SafeHullMass != 0 {
spec.Stargate = token.design.Spec.Stargate
spec.HasStargate = true
spec.SafeHullMass = token.design.Spec.SafeHullMass
}
if token.design.Spec.MaxHullMass != 0 {
spec.MaxHullMass = token.design.Spec.MaxHullMass
}
if token.design.Spec.SafeRange != 0 {
spec.SafeRange = token.design.Spec.SafeRange
}
if token.design.Spec.MaxRange != 0 {
spec.MaxRange = token.design.Spec.MaxRange
}
if token.design.Spec.SafePacketSpeed != 0 {
spec.HasMassDriver = true
spec.MassDriver = token.design.Spec.MassDriver
spec.SafePacketSpeed = token.design.Spec.SafePacketSpeed
spec.BasePacketSpeed = token.design.Spec.BasePacketSpeed
spec.AdditionalMassDrivers = token.design.Spec.AdditionalMassDrivers
}
}
// compute the cloaking based on the cloak units and cargo
spec.CloakPercent = computeFleetCloakPercent(&spec, fleet.Cargo.Total(), player.Race.Spec.FreeCargoCloaking)
if !spec.Starbase {
spec.EstimatedRange = fleet.getEstimatedRange(player, spec.Engine.IdealSpeed, spec.CargoCapacity)
}
return spec
}
// compute fuel usage for each waypoint
func (f *Fleet) computeFuelUsage(player *Player) {
for i := range f.Waypoints {
wp := &f.Waypoints[i]
if i > 0 && wp.WarpSpeed < StargateWarpSpeed {
wpPrevious := f.Waypoints[i-1]
fuelUsage := f.GetFuelCost(player, wp.WarpSpeed, wp.Position.DistanceTo(wpPrevious.Position))
wp.EstFuelUsage = fuelUsage
} else {
wp.EstFuelUsage = 0
}
}
}
// compute a fleet's cloak percent based on its current cargo/mass/cloak units
func computeFleetCloakPercent(spec *FleetSpec, cargoTotal int, freeCargoCloaking bool) int {
cloakUnits := spec.CloakUnits
// starbases have no mass or cargo, but fleet cloaking is adjusted for it
if spec.Mass > 0 {
// figure out how much cargo we are cloaking
cloakedCargo := 0
if !freeCargoCloaking {
cloakedCargo = cargoTotal
}
cloakUnits = int(math.Round(float64(cloakUnits) * float64(spec.MassEmpty) / float64(spec.MassEmpty+cloakedCargo)))
}
return getCloakPercentForCloakUnits(cloakUnits)
}
// make sure we don't overflow our fuel. After a battle, we might have more fuel than our fleet can hold
func (fleet *Fleet) reduceFuelToMax() {
fleet.Fuel = MinInt(fleet.Spec.FuelCapacity, fleet.Fuel)
}
// make sure we don't overflow our cargo. After a battle, we might have more cargo than our fleet can hold
// return any dropped cargo
func (fleet *Fleet) reduceCargoToMax() Cargo {
capacity := fleet.Spec.CargoCapacity
cargo := fleet.Cargo
// no capacity, no cargo
if capacity == 0 {
fleet.Cargo = Cargo{}
return cargo
}
// check if we have more cargo than we can hold
total := fleet.Cargo.Total()
if total > capacity {
// save the people first!
if fleet.Cargo.Colonists > 0 {
fleet.Cargo.Colonists = MinInt(fleet.Cargo.Colonists, capacity)
}
// if we have 110kT of space and 10kT is taken up by colonists, we have 100kT remaining capacity
// if we have 200kT of minerals left, we keep half of each
minerals := fleet.Cargo.ToMineral()
remainingCapacity := MaxInt(0, capacity-fleet.Cargo.Colonists)
// if we have no capacity left, drop all minerals and
if remainingCapacity == 0 {
fleet.Cargo = Cargo{Colonists: fleet.Cargo.Colonists}
return cargo.Subtract(fleet.Cargo)
}
totalMinerals := minerals.Total()
// reduce each mineral by a percent
percentToKeep := 1 / (float64(totalMinerals) / float64(remainingCapacity))
minerals = minerals.MultiplyFloat64(percentToKeep)
fleet.Cargo = Cargo{
minerals.Ironium,
minerals.Boranium,
minerals.Germanium,
fleet.Cargo.Colonists,
}
}
return cargo.Subtract(fleet.Cargo)
}
// return true if this fleet would attack another player's fleet, planet, minefield, etc.
func (fleet *Fleet) willAttack(fleetPlayer *Player, otherPlayerNum int) bool {
switch fleet.battlePlan.AttackWho {
case BattleAttackWhoEnemies:
return fleetPlayer.IsEnemy(otherPlayerNum)
case BattleAttackWhoEnemiesAndNeutrals:
return fleetPlayer.IsEnemy(otherPlayerNum) || fleetPlayer.IsNeutral(otherPlayerNum)
case BattleAttackWhoEveryone:
return true
default:
return false
}
}
func (f *Fleet) availableCargoSpace() int {
return Clamp(f.Spec.CargoCapacity-f.Cargo.Total(), 0, f.Spec.CargoCapacity)
}
func (f *Fleet) availableFuelSpace() int {
return Clamp(f.Spec.FuelCapacity-f.Fuel, 0, f.Spec.FuelCapacity)
}
// transfer cargo from a fleet to a cargo holder
func (f *Fleet) transferToDest(dest cargoHolder, cargoType CargoType, transferAmount int) error {
destCargo := dest.getCargo()
if transferAmount > 0 && !f.Cargo.CanTransferAmount(cargoType, transferAmount) {
return fmt.Errorf("fleet %s cannot transfer %d to %s, there is not enough in the fleet to transfer", f.Name, transferAmount, dest.getMapObject().Name)
}
if transferAmount < 0 && f.availableCargoSpace() < -transferAmount {
return fmt.Errorf("fleet %s has %d cargo space available, cannot transfer %dkT from %s", f.Name, f.availableCargoSpace(), transferAmount, dest.getMapObject().Name)
}
if transferAmount < 0 && !destCargo.CanTransferAmount(cargoType, -transferAmount) {
return fmt.Errorf("fleet %s cannot transfer %d from %s, there is not enough to transfer", f.Name, transferAmount, dest.getMapObject().Name)
}
if transferAmount > 0 && dest.getCargoCapacity() != Unlimited && (dest.getCargoCapacity()-destCargo.Total()) < transferAmount {
return fmt.Errorf("fleet %s cannot transfer %d to %s, there is not enough to space to hold the cargo", f.Name, transferAmount, dest.getMapObject().Name)
}
// transfer the cargo
f.Cargo.SubtractAmount(cargoType, transferAmount)
destCargo.AddAmount(cargoType, transferAmount)
return nil
}
// remove any empty tokens that were destroyed (by minefields, overgating, battle... it's a dangerous universe)
func (fleet *Fleet) removeEmptyTokens() {
updatedTokens := make([]ShipToken, 0, len(fleet.Tokens))
for _, token := range fleet.Tokens {
// keep this token
if token.Quantity > 0 {
updatedTokens = append(updatedTokens, token)
}
}
fleet.Tokens = updatedTokens
}
// move a fleet through space, check for minefields, use fuel, etc
func (fleet *Fleet) moveFleet(rules *Rules, mapObjectGetter mapObjectGetter, playerGetter playerGetter) {
player := playerGetter.getPlayer(fleet.PlayerNum)
wp0 := fleet.Waypoints[0]
wp1 := fleet.Waypoints[1]
totalDist := fleet.Position.DistanceTo(wp1.Position)
fleet.PreviousPosition = &Vector{fleet.Position.X, fleet.Position.Y}
dist := float64(wp1.WarpSpeed * wp1.WarpSpeed)
// round up, if we are <1 away, i.e. the target is 81.9 ly away, warp 9 (81 ly travel) should be able to make it there
if dist < totalDist && totalDist-dist < 1 {
dist = math.Ceil(totalDist)
}
// make sure we end up at a whole number
vectorTravelled := wp1.Position.Subtract(fleet.Position).Normalized().Scale(dist)
dist = vectorTravelled.Length()
// don't overshoot
dist = math.Min(totalDist, dist)
// check for CE engine failure
if player.Race.Spec.EngineFailureRate > 0 && wp1.WarpSpeed > player.Race.Spec.EngineReliableSpeed && player.Race.Spec.EngineFailureRate >= rules.random.Float64() {
messager.fleetEngineFailure(player, fleet)
return
}
// get the cost for the fleet
fuelCost := fleet.GetFuelCost(player, wp1.WarpSpeed, dist)
var fuelGenerated int = 0
if fuelCost > fleet.Fuel {
// we will run out of fuel
// if this distance would have cost us 10 fuel but we have 6 left, only travel 60% of the distance.
distanceFactor := float64(fleet.Fuel) / float64(fuelCost)
dist = dist * distanceFactor
// collide with minefields on route, but don't hit a minefield if we run out of fuel beforehand
dist = checkForMineFieldCollision(rules, playerGetter, mapObjectGetter, fleet, wp1, dist)
// remove any tokens destroyed by minefields and return if the fleet is gone
fleet.removeEmptyTokens()
if len(fleet.Tokens) == 0 {
return
}
fleet.Fuel = 0
wp1.WarpSpeed = fleet.Spec.Engine.FreeSpeed
fleet.Waypoints[1] = wp1
messager.fleetOutOfFuel(player, fleet, wp1.WarpSpeed)
// if we ran out of fuel 60% of the way to our normal distance, the remaining 40% of our time
// was spent travelling at fuel generation speeds:
remainingDistanceTravelled := (1 - distanceFactor) * float64(wp1.WarpSpeed*wp1.WarpSpeed)
dist += remainingDistanceTravelled
fuelGenerated = fleet.getFuelGeneration(wp1.WarpSpeed, remainingDistanceTravelled)
} else {
// collide with minefields on route, but don't hit a minefield if we run out of fuel beforehand
actualDist := checkForMineFieldCollision(rules, playerGetter, mapObjectGetter, fleet, wp1, dist)
// remove any tokens destroyed by minefields and return if the fleet is gone
fleet.removeEmptyTokens()
if len(fleet.Tokens) == 0 {
return
}
if actualDist != dist {
dist = actualDist
fuelCost = fleet.GetFuelCost(player, wp1.WarpSpeed, dist)
// we hit a minefield, update fuel usage
}
fleet.Fuel -= fuelCost
fuelGenerated = fleet.getFuelGeneration(wp1.WarpSpeed, dist)
}
// message the player about fuel generation
fuelGenerated = MinInt(fuelGenerated, fleet.Spec.FuelCapacity-fleet.Fuel)
if fuelGenerated > 0 {
fleet.Fuel += fuelGenerated
messager.fleetGeneratedFuel(player, fleet, fuelGenerated)
}
// assuming we move at all, make sure we are no longer orbiting any planets
if dist > 0 && fleet.Orbiting() {
fleet.OrbitingPlanetNum = None
}
if totalDist == dist {
fleet.completeMove(mapObjectGetter, player, wp0, wp1)
} else {
// update what other people see for this fleet's speed and direction
if fleet.struckMineField {
fleet.WarpSpeed = 0
fleet.Heading = Vector{}
} else {
fleet.WarpSpeed = wp1.WarpSpeed
fleet.Heading = (wp1.Position.Subtract(fleet.Position)).Normalized()
}
// move this fleet closer to the next waypoint
wp0.TargetType = MapObjectTypeNone
wp0.TargetNum = None
wp0.TargetPlayerNum = None
wp0.TargetName = ""
wp0.PartiallyComplete = true
fleet.Position = fleet.Position.Add(fleet.Heading.Scale(dist))
fleet.Position = fleet.Position.Round()
wp0.Position = fleet.Position
// don't do any transport in mid space, reset this
if wp0.Task == WaypointTaskTransport {
wp0.Task = WaypointTaskNone
wp0.TransportTasks = WaypointTransportTasks{}
}
fleet.Waypoints[0] = wp0
}
// if we ended up at a planet, make sure we are orbiting it
if fleet.OrbitingPlanetNum == None {
for _, mo := range mapObjectGetter.getMapObjectsAtPosition(fleet.Position) {
if planet, ok := mo.(*Planet); ok {
fleet.OrbitingPlanetNum = planet.Num
}
}
}
}
// GateFleet moves the fleet the cool way, with stargates!
func (fleet *Fleet) gateFleet(rules *Rules, mapObjectGetter mapObjectGetter, playerGetter playerGetter) {
player := playerGetter.getPlayer(fleet.PlayerNum)
wp0 := fleet.Waypoints[0]
wp1 := fleet.Waypoints[1]
totalDist := fleet.Position.DistanceTo(wp1.Position)
fleet.PreviousPosition = &Vector{fleet.Position.X, fleet.Position.Y}
// if we got here, both source and dest have stargates
sourcePlanet := mapObjectGetter.getPlanet(fleet.OrbitingPlanetNum)
destPlanet := mapObjectGetter.getPlanet(wp1.TargetNum)
if sourcePlanet == nil || !sourcePlanet.Spec.HasStargate {
messager.fleetStargateInvalidSource(player, fleet, wp0)
return
}
if destPlanet == nil || !destPlanet.Spec.HasStargate {
messager.fleetStargateInvalidDest(player, fleet, wp0, wp1)
return
}
sourcePlanetPlayer := playerGetter.getPlayer(sourcePlanet.PlayerNum)
destPlanetPlayer := playerGetter.getPlayer(destPlanet.PlayerNum)
if !sourcePlanetPlayer.IsFriend(player.Num) {
messager.fleetStargateInvalidSourceOwner(player, fleet, wp0, wp1)
return
}
if !destPlanetPlayer.IsFriend(player.Num) {
messager.fleetStargateInvalidDestOwner(player, fleet, wp0, wp1)
return
}
if fleet.Cargo.Colonists > 0 && !sourcePlanet.OwnedBy(player.Num) && !player.Race.Spec.CanGateCargo {
messager.fleetStargateInvalidColonists(player, fleet, wp0, wp1)
return
}
sourceStargate := sourcePlanet.Spec
destStargate := destPlanet.Spec
// only the source gate matters for range
minSafeRange := sourceStargate.SafeRange
minSafeHullMass := MinInt(sourceStargate.SafeHullMass, destStargate.SafeHullMass)
// check if we are exceeding the max distance
if totalDist > float64(minSafeRange*rules.StargateMaxRangeFactor) {
messager.fleetStargateInvalidRange(player, fleet, wp0, wp1, totalDist)
return
}
// check if any ships exceed the max mass allowed
for _, token := range fleet.Tokens {
if token.design.Spec.Mass > minSafeHullMass*rules.StargateMaxHullMassFactor {
messager.fleetStargateInvalidMass(player, fleet, wp0, wp1)
return
}
}
// dump cargo if we aren't IT
if fleet.Cargo.Total() > 0 && !player.Race.Spec.CanGateCargo {
messager.fleetStargateDumpedCargo(player, fleet, wp0, wp1, fleet.Cargo)
sourcePlanet.Cargo = sourcePlanet.Cargo.Add(fleet.Cargo)
fleet.Cargo = Cargo{}
}
// apply overgate damage and delete tokens (and possibly the fleet)
// also vanish tokens for non IT races
fleet.applyOvergatePenalty(player, rules, totalDist, wp0, wp1, sourceStargate, destStargate)
// if the fleet is gone, we're done
if len(fleet.Tokens) == 0 {
return
}
// we survived, warp it!
fleet.completeMove(mapObjectGetter, player, wp0, wp1)
}
// applyOvergatePenalty applies damage (if any) to each token that overgated
func (fleet *Fleet) applyOvergatePenalty(player *Player, rules *Rules, distance float64, wp0, wp1 Waypoint, sourceStargate, destStargate PlanetSpec) {
var totalDamage, shipsLostToDamage, shipsLostToTheVoid, startingShips int
for i := range fleet.Tokens {
token := &fleet.Tokens[i]
startingShips += token.Quantity
// Inner stellar travellers never lose ships to the void, but everyone else does
if player.Race.Spec.ShipsVanishInVoid {
rangeVanishChance := token.getStargateRangeVanishingChance(distance, sourceStargate.SafeRange)
massVanishingChance := token.getStargateMassVanishingChance(sourceStargate.SafeHullMass, rules.StargateMaxHullMassFactor)