-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathunit_terraform.lua
More file actions
3855 lines (3306 loc) · 126 KB
/
Copy pathunit_terraform.lua
File metadata and controls
3855 lines (3306 loc) · 126 KB
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
-- $Id: unit_terraform.lua 4610 2009-05-12 13:03:32Z google frog $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Terraformers",
desc = "Terraforming script for lasso based area/line terraform, also ramp",
author = "Google Frog",
date = "Nov, 2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if gadgetHandler:IsSyncedCode() then
--------------------------------------------------------------------------------
-- SYNCED
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local USE_TERRAIN_TEXTURE_CHANGE = true -- (Spring.GetModOptions() or {}).terratex == "1"
local ECHO_COST = false
local ECHO_DETAILED_COST_ESTIMATE = false
-- Speedups
local cos = math.cos
local floor = math.floor
local abs = math.abs
local pi = math.pi
local ceil = math.ceil
local sqrt = math.sqrt
local pow = math.pow
local random = math.random
local max = math.max
local min = math.min
local spGetGroundHeight = Spring.GetGroundHeight
local spGetGroundOrigHeight = Spring.GetGroundOrigHeight
local spGetGroundNormal = Spring.GetGroundNormal
local spLevelHeightMap = Spring.LevelHeightMap
local spGetUnitBuildFacing = Spring.GetUnitBuildFacing
local spGetUnitCommands = Spring.GetUnitCommands
local spValidUnitID = Spring.ValidUnitID
local spGetGameFrame = Spring.GetGameFrame
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local spSetHeightMap = Spring.SetHeightMap
local spSetHeightMapFunc = Spring.SetHeightMapFunc
local spCreateUnit = Spring.CreateUnit
local spDestroyUnit = Spring.DestroyUnit
local spGetAllyTeamList = Spring.GetAllyTeamList
local spSetUnitLosMask = Spring.SetUnitLosMask
local spSetUnitLosState = Spring.SetUnitLosState
local spGetTeamInfo = Spring.GetTeamInfo
local spGetUnitHealth = Spring.GetUnitHealth
local spSetUnitHealth = Spring.SetUnitHealth
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitAllyTeam = Spring.GetUnitAllyTeam
local spAddHeightMap = Spring.AddHeightMap
local spGetUnitPosition = Spring.GetUnitPosition
local spSetUnitPosition = Spring.SetUnitPosition
local spSetUnitSensorRadius = Spring.SetUnitSensorRadius
local spGetUnitIsDead = Spring.GetUnitIsDead
local spSetUnitRulesParam = Spring.SetUnitRulesParam
local mapWidth = Game.mapSizeX
local mapHeight = Game.mapSizeZ
local CMD_OPT_RIGHT = CMD.OPT_RIGHT
local CMD_OPT_ALT = CMD.OPT_ALT
local CMD_REPAIR = CMD.REPAIR
local CMD_INSERT = CMD.INSERT
local SQRT_2 = sqrt(2)
local ALLIED_TABLE = {allied = true}
--------------------------------------------------------------------------------
-- Configuration
--------------------------------------------------------------------------------
local bumpyMap = {}
for i = 0, 64, 8 do
bumpyMap[i] = {}
for j = 0, 64, 8 do
bumpyMap[i][j] = 32 - max(abs(i-32), abs(j-32))
end
end
local maxCommandPoints = 2500
local maxCommandUnits = 1000
local maxAreaSize = 2000 -- max X or Z bound of area terraform
local areaSegMaxSize = 200 -- max width and height of terraform squares
local maxWallPoints = 700 -- max points that can makeup a wall
local wallSegmentLength = 14 -- how many points are part of a wall segment (points are seperated 8 elmos orthagonally)
local maxRampWidth = 200 -- maximun width of ramp segment
local maxRampLegth = 200 -- maximun length of ramp segment
local maxHeightDifference = 28 -- max difference of height around terraforming, Makes Shraka Pyramids
local maxHeightDiffDownInner = 8
local maxEdgeHeightDiff = 4 -- max difference of terraform around the edge of the pyramid
local maxRampGradient = 5
local volumeCost = 0.0128
local pointExtraAreaCost = 0 -- 0.027
local pointExtraAreaCostDepth = 14
local pointExtraPerimeterCost = 0.15
local pointExtraPerimeterCostDepth = 10
local baseTerraunitCost = 6
local inbuiltCostMult = 0.5
local noBuildBaseCost = 3
local baseSpendProp = 0.94
local perimeterEdgeCost = {
[0] = 0,
[1] = 1,
[2] = 1.4,
[3] = 1,
[4] = 1,
}
-- cost of a point = volumeCost*diffHeight + extraCost*(extraCostDepth < diffHeight and diffHeight or extraCostDepth)
-- cost of shraka pyramid point = volumeCost*diffHeight
--ramp dimensions
local maxTotalRampLength = 3000
local maxTotalRampWidth = 800
local minTotalRampLength = 64
local minTotalRampWidth = 48
local checkLoopFrames = 1200 -- how many frames it takes to check through all cons
local terraformDecayFrames = 2*60*30 -- how many frames a terrablock can survive for without a repair command
local decayCheckFrequency = 90 -- frequency of terraform decay checks
local structureCheckLoopFrames = 300 -- frequency of slow update for building deformation check
local terraUnitLeash = 100 -- how many elmos a terraunit is allowed to roam
local enemyDistConst = 36 -- Constant added to enemy distinct check
local nearbyEnemyPenalty = 20 -- Cost multiplier for terraform on enemy units
local pyramidLimitExtra = 8 -- Extra limit on pyramid height before terraform is cancelled.
local costMult = 1
local modOptions = Spring.GetModOptions()
if modOptions.terracostmult then
costMult = modOptions.terracostmult
end
local ENEMY_BLOCK_TERRA = not (tonumber(modOptions.enemyterra) == 1)
volumeCost = volumeCost * costMult * inbuiltCostMult
pointExtraPerimeterCost = pointExtraPerimeterCost * costMult * inbuiltCostMult
pointExtraAreaCost = pointExtraAreaCost * costMult * inbuiltCostMult
--------------------------------------------------------------------------------
-- Arrays
--------------------------------------------------------------------------------
local steepnessMarkers = {inner = {count = 0, data = {}, frame = 0}}
local structure = {}
local structureTable = {}
local structureCount = 0
local structureAreaMap = {}
local structureCheckFrame = {}
local currentCheckFrame = 0
local terraformUnit = {}
local terraformUnitTable = {}
local terraformUnitCount = 0
local terraformOrder = {}
local terraformOrders = 0
local constructor = {}
local constructorTable = {}
local constructors = 0
local currentCon = 0
local checkInterval = 0
-- Performance
local MIN_UPDATE_PERIOD = 6
local MAX_UPDATE_PERIOD = 40
local updatePeriod = 20 -- how many frames to update
local terraformOperations = 0 -- tracks how many operations. Used to prevent slowdown.
local nextUpdateCheck = 0 -- Time at which to check performance
-- Map terraform commands given by teamID and tag.
local fallbackCommands = {}
local terraunitDefID = UnitDefNames["terraunit"].id
local terraUnitHP = UnitDefs[terraunitDefID].health - 1000 -- Stop terraunit having full health to make it always able to be built.
local terraUnitCost = UnitDefs[terraunitDefID].metalCost
local terraBuildMult = terraUnitHP/UnitDefs[terraunitDefID].health
local terraformUnitDefIDs = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
if ud and ud.isBuilder and not ud.isFactory and (ud.terraformSpeed > 0) then
terraformUnitDefIDs[i] = true
end
end
local REPAIR_ORDER_PARAMS = {0, CMD_REPAIR, CMD_OPT_RIGHT, 0} -- static because only the 4th parameter changes
local wantForceCompleteFrameZero = false
local freeTerraform = false
local debugMode = false
local debugModeUnitID
--------------------------------------------------------------------------------
-- Custom Commands
--------------------------------------------------------------------------------
include("LuaRules/Configs/customcmds.h.lua")
local rampCmdDesc = {
id = CMD_RAMP,
type = CMDTYPE.ICON_MAP,
name = 'Ramp',
cursor = 'Ramp',
action = 'rampground',
tooltip = 'Build a Ramp - Click and drag between two positions.',
}
local levelCmdDesc = {
id = CMD_LEVEL,
type = CMDTYPE.ICON_AREA,
name = 'Level',
cursor = 'Level',
action = 'levelground',
tooltip = 'Level the terrain - Click and drag a line or closed shape.',
}
local raiseCmdDesc = {
id = CMD_RAISE,
type = CMDTYPE.ICON_AREA,
name = 'Raise',
cursor = 'Raise',
action = 'raiseground',
tooltip = 'Raises/Lower terrain - Click and drag a line or closed shape.',
}
local smoothCmdDesc = {
id = CMD_SMOOTH,
type = CMDTYPE.ICON_AREA,
name = 'Smooth',
cursor = 'Smooth',
action = 'smoothground',
tooltip = 'Smooth the terrain - Click and drag a line or closed shape.',
}
local restoreCmdDesc = {
id = CMD_RESTORE,
type = CMDTYPE.ICON_AREA,
name = 'Restore2',
cursor = 'Restore2',
action = 'restoreground',
tooltip = 'Restore the terrain to its original shape - Click and drag a line or closed shape.',
}
local bumpyCmdDesc = {
id = CMD_BUMPY,
type = CMDTYPE.ICON_AREA,
name = 'Bumpify',
cursor = 'Repair',
action = 'bumpifyground',
tooltip = 'Makes the ground bumpy',
}
local fallbackableCommands = {
[CMD_RAMP] = true,
[CMD_LEVEL] = true,
[CMD_RAISE] = true,
[CMD_SMOOTH] = true,
[CMD_RESTORE] = true,
}
local wantedCommands = {
[CMD_RAMP] = true,
[CMD_LEVEL] = true,
[CMD_RAISE] = true,
[CMD_SMOOTH] = true,
[CMD_RESTORE] = true,
[CMD_TERRAFORM_INTERNAL] = true,
}
local cmdDescsArray = {
rampCmdDesc,
levelCmdDesc,
raiseCmdDesc,
smoothCmdDesc,
restoreCmdDesc,
--bumpyCmdDesc,
}
if (not Game.mapDamage) then -- map has "notDeformable = true", or "disablemapdamage = 1" modoption was set in the startscript
include("LuaRules/colors.h.lua")
local disabledText = '\n' .. RedStr .. "DISABLED" .. PinkStr .. " (map not deformable)"
for _, cmdDesc in ipairs(cmdDescsArray) do
cmdDesc.disabled = true
cmdDesc.tooltip = cmdDesc.tooltip .. disabledText
end
elseif modOptions.terrarestoreonly == "1" then
include("LuaRules/colors.h.lua")
local disabledText = '\n' .. RedStr .. "DISABLED" .. PinkStr .. " (only restore allowed)"
for _, cmdDesc in ipairs(cmdDescsArray) do
if cmdDesc ~= restoreCmdDesc then
cmdDesc.disabled = true
cmdDesc.tooltip = cmdDesc.tooltip .. disabledText
end
end
end
--------------------------------------------------------------------------------
-- Structure Utilities
--------------------------------------------------------------------------------
local function AddStructure(unitID, i, j)
local k = 1
while structureAreaMap[k] and structureAreaMap[k][i] and structureAreaMap[k][i][j] do
k = k + 1
end
if not structureAreaMap[k] then
structureAreaMap[k] = {}
end
if not structureAreaMap[k][i] then
structureAreaMap[k][i] = {}
end
structureAreaMap[k][i][j] = unitID
end
local function RemoveStructure(unitID, i, j)
local k = 1
local index
while structureAreaMap[k] and structureAreaMap[k][i] and structureAreaMap[k][i][j] do
if structureAreaMap[k][i][j] == unitID then
index = k
end
k = k + 1
end
if not index then
Spring.Echo("LUA_ERRRUN", "Structure removal failure:", unitID, k, "i, j:", i, j)
return
end
local structCount = k - 1
if index == 1 and structCount == 1 then
structureAreaMap[structCount][i][j] = nil
return
end
structureAreaMap[index][i][j] = structureAreaMap[structCount][i][j]
structureAreaMap[structCount][i][j] = nil
end
local function HasStructure(i, j)
return structureAreaMap[1] and structureAreaMap[1][i] and structureAreaMap[1][i][j]
end
--------------------------------------------------------------------------------
-- New Functions
--------------------------------------------------------------------------------
local unitAlreadyEchoed = {}
local function EchoUnit(unitID)
if debugMode and not unitAlreadyEchoed[unitID] and ((not debugModeUnitID) or debugModeUnitID[unitID]) then
Spring.Utilities.UnitEcho(unitID, unitID)
unitAlreadyEchoed[unitID] = true
end
end
local function IsDebug(unitID)
return debugMode and ((not debugModeUnitID) or debugModeUnitID[unitID])
end
local function EchoDebug(unitID, ...)
if IsDebug(unitID) then
Spring.Echo(unitID, ...)
end
end
local function IsBadNumber(value, thingToSay)
local isBad = (string.find(tostring(value), "n") and true) or false
if isBad then
Spring.Echo("Terraform bad number detected", thingToSay, value)
end
return isBad
end
local function SetTooltip(unitID, spent, estimatedCost)
Spring.SetUnitRulesParam(unitID, "terraform_spent", spent, ALLIED_TABLE)
if IsBadNumber(estimatedCost, "SetTooltip") then
estimatedCost = 100 -- the estimate is for widgets only so better to have wrong data than to crash
end
Spring.SetUnitRulesParam(unitID, "terraform_estimate", estimatedCost, ALLIED_TABLE)
end
local function IsPositionTerraformable(x, z, ignoreStructure)
if (not ignoreStructure) and HasStructure(x, z) then
return false
end
if GG.map_AllowPositionTerraform then
return GG.map_AllowPositionTerraform(x, z)
end
return true
end
local function SetupPointStructure(point, structArea, segArea)
local currHeight = point.orHeight
local x, z = point.x, point.z
if (structArea[x] and structArea[x][z]) or (GG.map_AllowPositionTerraform and not GG.map_AllowPositionTerraform(x, z)) then
point.diffHeight = 0.0001
point.structure = structArea[x][z] or 1000
else
point.diffHeight = point.aimHeight - currHeight
segArea[x][z] = {orHeight = point.orHeight, diffHeight = point.diffHeight, building = false}
end
end
local function GetGroundOrigHeightOverride(x, z, xOff, zOff)
if GG.mapgen_origHeight and GG.mapgen_origHeight[x] and GG.mapgen_origHeight[x][z] then
return GG.mapgen_origHeight[x][z] - (Spring.GetGameRulesParam("waterlevel") or 0)
end
return spGetGroundOrigHeight(x + (xOff or 0), z + (zOff or 0))
end
--------------------------------------------------------------------------------
-- Enemy Terraform Blocking
--------------------------------------------------------------------------------
local function CheckNearbyEnemy(unitID)
if not ENEMY_BLOCK_TERRA then
return
end
local nearbyEnemyID = Spring.GetUnitNearestEnemy(unitID, terraformUnit[unitID].enemyCheckDist, true)
local nearbyEnemy = (nearbyEnemyID and true) or false
if IsDebug(unitID) then
Spring.Echo("nearbyEnemy", nearbyEnemy, math.random())
if nearbyEnemyID then
Spring.Utilities.UnitEcho(nearbyEnemyID, "")
end
end
if nearbyEnemy ~= terraformUnit[unitID].nearbyEnemy then
spSetUnitRulesParam(unitID, "terraform_enemy", (nearbyEnemy and nearbyEnemyID) or -1, ALLIED_TABLE)
terraformUnit[unitID].nearbyEnemy = nearbyEnemy
Spring.SetUnitCosts(unitID, {buildTime = terraUnitCost*((nearbyEnemy and nearbyEnemyPenalty) or 1)})
EchoDebug(unitID, "SetUnitCosts mult", ((nearbyEnemy and nearbyEnemyPenalty) or 1))
end
end
local function InitialiseNearbyEnemy(unitID)
local data = terraformUnit[unitID]
local size = math.sqrt((data.border.bottom - data.border.top)^2 + (data.border.right - data.border.left)^2)
data.enemyCheckDist = size*0.5 + terraUnitLeash + enemyDistConst
EchoDebug(unitID, "enemyCheckDist", data.enemyCheckDist)
CheckNearbyEnemy(unitID)
end
--------------------------------------------------------------------------------
-- Terraform Calculation Functions
--------------------------------------------------------------------------------
local function linearEquation(x,m,x1,y1)
return m*(x-x1)+y1
end
local function distance(x1,y1,x2,y2)
return ((x1-x2)^2+(y1-y2)^2)^0.5
end
local function pointHeight(xs, ys, zs, x, z, m, h, xdis)
local xInt = (z-zs+m*xs+x/m)/(m+1/m)
local ratio = abs(xInt-xs)/xdis
return ratio*h+ys
end
local function bumpyFunc(x,z,bumpyType)
local sign = pow(-1,((x - x%64)/64 + (z - z%64)/64))
--return pow(-1,((x - x%8)/8 + (z - z%8)/8))*3*(bumpyType + 1)
return bumpyMap[x%64][z%64]*sign*(bumpyType + 1)
end
local function checkPointCreation(terraform_type, volumeSelection, orHeight, newHeight, startHeight, x, z)
if terraform_type == 6 then
local _, ny, _ = spGetGroundNormal(x,z)
if ny > select(2,spGetGroundNormal(x+8,z)) then
ny = select(2,spGetGroundNormal(x+8,z))
end
if ny > select(2,spGetGroundNormal(x-8,z)) then
ny = select(2,spGetGroundNormal(x-8,z))
end
if ny > select(2,spGetGroundNormal(x,z+8)) then
ny = select(2,spGetGroundNormal(x,z+8))
end
if ny > select(2,spGetGroundNormal(x,z-8)) then
ny = select(2,spGetGroundNormal(x,z-8))
end
--if (volumeSelection == 1 and ny > 0.595) or ny > 0.894 then
-- Spring.MarkerAddLine(x,0,z,x+8,0,z+8)
-- Spring.MarkerAddLine(x+8,0,z,x,0,z+8)
--end
return (volumeSelection == 1 and ny > 0.595) or ny > 0.894
end
if volumeSelection == 0 or terraform_type == 2 then
return true
end
if abs(orHeight-newHeight) == 0 then
return false
end
if terraform_type == 5 then
return (volumeSelection == 1 and orHeight < startHeight) or (volumeSelection == 2 and orHeight > startHeight)
else
return (volumeSelection == 1 and orHeight < newHeight) or (volumeSelection == 2 and orHeight > newHeight)
end
end
local function updateBorderWithPoint(border, x, z)
if x < border.left then
border.left = x
end
if x > border.right then
border.right = x
end
if z < border.top then
border.top = z
end
if z > border.bottom then
border.bottom = z
end
end
local function getPointInsideMap(x,z)
if x < 1 then
x = 1
end
if x > mapWidth-1 then
x = mapWidth-1
end
if z < 1 then
z = 1
end
if z > mapHeight-1 then
z = mapHeight-1
end
return x, z
end
local function SetInivisbleToEnemy(unitID, team)
local allyTeamList = spGetAllyTeamList()
local _,_,_,_,_,unitAllyTeam = spGetTeamInfo(team, false)
for i=1, #allyTeamList do
local allyID = allyTeamList[i]
if allyID ~= unitAllyTeam then
spSetUnitLosState(unitID, allyID, 0)
spSetUnitLosMask(unitID, allyID, 15)
end
end
end
local function setupTerraunit(unitID, team, x, y, z)
y = y or CallAsTeam(team, function () return spGetGroundHeight(x,z) end)
Spring.MoveCtrl.Enable(unitID)
Spring.MoveCtrl.SetPosition(unitID, x, y or 0, z)
Spring.MoveCtrl.Disable(unitID)
spSetUnitSensorRadius(unitID,"los",0) -- REMOVE IN 0.83
spSetUnitSensorRadius(unitID,"airLos",0) -- REMOVE IN 0.83
SetInivisbleToEnemy(unitID, team)
spSetUnitHealth(unitID, {
health = 0.01,
build = 0
})
end
local function GetTerraunitLeashedSpot(teamID, anchorX, anchorZ, biasX, biasZ)
local x, z
local vx = biasX - anchorX
local vz = biasZ - anchorZ
local leashLength = sqrt(vx*vx + vz*vz)
if leashLength > terraUnitLeash then
-- cruel leash!
local leashScale = terraUnitLeash / leashLength
x = anchorX + leashScale * vx
z = anchorZ + leashScale * vz
else
x = biasX
z = biasZ
end
x, z = getPointInsideMap(x, z)
local y = CallAsTeam(teamID, spGetGroundHeight, x, z)
return x, y, z
end
local function AddFallbackCommand(teamID, commandTag, terraunits, terraunitList, commandX, commandZ)
fallbackCommands[teamID] = fallbackCommands[teamID] or {}
fallbackCommands[teamID][commandTag] = {
terraunits = terraunits,
terraunitList = terraunitList,
commandX = commandX,
commandZ = commandZ,
}
end
local function GetUnitAveragePosition(unit, units)
if not unit then
return
end
local unitsX = 0
local unitsZ = 0
local i = 1
while i <= units do
if (spValidUnitID(unit[i])) then
local x,_,z = spGetUnitPosition(unit[i])
unitsX = unitsX + x
unitsZ = unitsZ + z
i = i + 1
else
unit[i] = unit[units]
unit[units] = nil
units = units - 1
end
end
if units == 0 then
return
end
return unitsX/units, unitsZ/units
end
local function TerraformRamp(x1, y1, z1, x2, y2, z2, terraform_width, unit, units, team, volumeSelection, shift, commandX, commandZ, commandTag, disableForceCompletion, noDecay)
--** Initial constructor processing **
local unitsX, unitsZ = GetUnitAveragePosition(unit, units)
if not unitsX then
unitsX, unitsZ = commandX, commandZ
end
--calculate equations of the 3 lines, left, right and mid
local border = {}
if abs(x1 - x2) < 0.1 then
x2 = x1 + 0.1
end
if abs(z1 - z2) < 0.1 then
z2 = z1 + 0.1
end
local dis = distance(x1,z1,x2,z2)
if dis < minTotalRampLength-0.05 or dis > maxTotalRampLength+0.05 then
return
end
if terraform_width < minTotalRampWidth or terraform_width > maxTotalRampWidth*2 then
return
end
local xdis = abs(x1-x2)
local heightDiff = y2-y1
if heightDiff/dis > maxRampGradient then
heightDiff = maxRampGradient*dis
elseif heightDiff/dis < -maxRampGradient then
heightDiff = -maxRampGradient*dis
end
-- Due to previous checks, m is not 0 or infinity.
local m = (z1-z2)/(x1-x2)
local segmentsAlong = ceil(dis/maxRampLegth)
local segmentsAcross = ceil(terraform_width/maxRampWidth)
local segLength = dis/segmentsAlong
local segWidth = terraform_width/segmentsAcross
local widthScale = terraform_width/dis
local lengthScale = segLength/dis
local add = {x = (x2-x1)*lengthScale, z = (z2-z1)*lengthScale}
local addPerp = {x = (z1-z2)*segWidth/dis, z = -(x1-x2)*segWidth/dis}
local mid = {x = (x1-x2)*widthScale/2, z = (z1-z2)*widthScale/2}
local leftRot = {x = mid.z+x1, z = -mid.x+z1}
local rightRot = {x = -mid.z+x1, z = mid.x+z1}
--Spring.MarkerAddPoint(leftRot.x,0,leftRot.z,"L")
--Spring.MarkerAddPoint(rightRot.x,0,rightRot.z,"R")
--Spring.MarkerAddPoint(rightRot.x+add.x,0,rightRot.z+add.z,"R + A")
--Spring.MarkerAddPoint(rightRot.x+addPerp.x,0,rightRot.z+addPerp.z,"R + AP")
local topleftGrad
local botleftGrad
local toppoint
local botpoint
local leftpoint
local rightpoint
--** Store the 4 points of each segment diamond, changes with quadrant **
if x1 < x2 then
if z1 < z2 then
-- bottom right
topleftGrad = -1/m
botleftGrad = m
toppoint = rightRot
leftpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
rightpoint = {x = toppoint.x+add.x, z = toppoint.z+add.z}
botpoint = {x = leftpoint.x+add.x, z = leftpoint.z+add.z}
border = {left = leftRot.x, right = rightRot.x-x1+x2, top = rightRot.z, bottom = leftRot.z-z1+z2}
else
-- top right
topleftGrad = m
botleftGrad = -1/m
leftpoint = rightRot
botpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
rightpoint = {x = botpoint.x+add.x, z = botpoint.z+add.z}
toppoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
border = {left = rightRot.x, right = leftRot.x-x1+x2, top = rightRot.z-z1+z2, bottom = leftRot.z}
end
else
if z1 < z2 then
-- bottom left
topleftGrad = m
botleftGrad = -1/m
rightpoint = rightRot
toppoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
botpoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
leftpoint = {x = toppoint.x+add.x, z = toppoint.z+add.z}
border = {left = leftRot.x-x1+x2, right = rightRot.x, top = rightRot.z-z1+z2, bottom = leftRot.z}
else
-- top left
topleftGrad = -1/m
botleftGrad = m
botpoint = rightRot
rightpoint = {x = rightRot.x+addPerp.x, z = rightRot.z+addPerp.z}
toppoint = {x = rightpoint.x+add.x, z = rightpoint.z+add.z}
leftpoint = {x = rightRot.x+add.x, z = rightRot.z+add.z}
border = {left = rightRot.x-x1+x2, right = leftRot.x, top = leftRot.z-z1+z2, bottom = rightRot.z}
end
end
-- check it's all working
--[[
Spring.MarkerAddPoint( border.left,0,border.top,"topleft")
Spring.MarkerAddPoint( border.right,0,border.bottom,"botright")
Spring.MarkerAddPoint( x1,y1,z1, "start")
Spring.MarkerAddPoint( x2,y2,z2, "end")
Spring.MarkerAddPoint( leftpoint.x,y1,leftpoint.z, "leftP")
Spring.MarkerAddPoint( toppoint.x,y1,toppoint.z, "topP")
Spring.MarkerAddPoint( botpoint.x,y1,botpoint.z, "botP")
Spring.MarkerAddPoint( leftpoint.x,y1,toppoint.z, "topleft")
Spring.MarkerAddPoint( rightpoint.x,y1,botpoint.z, "botright")
Spring.MarkerAddLine(toppoint.x,y1,toppoint.z,leftpoint.x,y1,leftpoint.z)
Spring.MarkerAddLine(botpoint.x,y1,botpoint.z,leftpoint.x,y1,leftpoint.z)
Spring.MarkerAddLine(toppoint.x,y1,toppoint.z,rightpoint.x,y1,rightpoint.z)
Spring.MarkerAddLine(botpoint.x,y1,botpoint.z,rightpoint.x,y1,rightpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,toppoint.z,rightpoint.x,y1,toppoint.z)
Spring.MarkerAddLine(rightpoint.x,y1,toppoint.z,rightpoint.x,y1,botpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,toppoint.z,leftpoint.x,y1,botpoint.z)
Spring.MarkerAddLine(leftpoint.x,y1,botpoint.z,rightpoint.x,y1,botpoint.z)
--]]
--** Split the ramp into segments and calculate the points within each one**
local segment = {}
local n = 1
do local i = 0
while i < segmentsAlong do
local j = 0
while j < segmentsAcross do
local middleSegment = (i > 0) and (j > 0) and (i < segmentsAlong - 1) and (j < segmentsAcross - 1)
local offset = (middleSegment and 8) or 0
segment[n] = {}
segment[n].along = i
segment[n].point = {}
segment[n].area = {}
segment[n].border = {
left = floor((leftpoint.x+add.x*i+addPerp.x*j)/8)*8 - offset,
right = ceil((rightpoint.x+add.x*i+addPerp.x*j)/8)*8 + offset,
top = floor((toppoint.z+add.z*i+addPerp.z*j)/8)*8 - offset,
bottom = ceil((botpoint.z+add.z*i+addPerp.z*j)/8)*8 + offset
}
-- end of segment
--segment[n].position = {x = (rightRot.x-4+add.x*i+addPerp.x*(j+0.5)-16*(x2-x1)/dis), z = (rightRot.z-4+add.z*i+addPerp.z*(j+0.5)-16*(z2-z1)/dis)}
-- middle of segment
segment[n].position = {x = rightRot.x+add.x*(i+0.5)+addPerp.x*(j+0.5), z = rightRot.z+add.z*(i+0.5)+addPerp.z*(j+0.5)}
local pc = 1
local topline1 = {x = leftpoint.x+add.x*i+addPerp.x*j - offset, z = leftpoint.z+add.z*i+addPerp.z*j - offset, m = topleftGrad}
local topline2 = {x = toppoint.x+add.x*i+addPerp.x*j + offset, z = toppoint.z+add.z*i+addPerp.z*j - offset, m = botleftGrad}
local botline1 = {x = leftpoint.x+add.x*i+addPerp.x*j - offset, z = leftpoint.z+add.z*i+addPerp.z*j + offset, m = botleftGrad}
local botline2 = {x = botpoint.x+add.x*i+addPerp.x*j + offset, z = botpoint.z+add.z*i+addPerp.z*j + offset, m = topleftGrad}
local topline = topline1
local botline = botline1
local lx = segment[n].border.left - offset
while lx <= segment[n].border.right + offset do
segment[n].area[lx] = {}
local zmin = linearEquation(lx,topline.m,topline.x,topline.z)
local zmax = linearEquation(lx,botline.m,botline.x,botline.z)
local lz = segment[n].border.top
while lz <= zmax do
if zmin <= lz then
local h = pointHeight(x1, y1, z1, lx, lz, m, heightDiff, xdis)
local orHeight = spGetGroundHeight(lx,lz)
if checkPointCreation(4, volumeSelection, orHeight, h, 0, lx, lz) then
segment[n].point[pc] = {x = lx, y = h ,z = lz, orHeight = orHeight, prevHeight = spGetGroundHeight(lx,lz)}
pc = pc + 1
end
end
lz = lz+8
end
lx = lx+8
if topline == topline1 and topline2.x < lx then
topline = topline2
end
if botline == botline1 and botline2.x < lx then
botline = botline2
end
end
if pc ~= 1 then
segment[n].points = pc - 1
n = n + 1
end
j = j+1
end
i = i+1
end end
--** Detect potentially overlapping buildings**
local localStructure = {}
local localStructureCount = 0
for i = 1, structureCount do
local s = structure[structureTable[i] ]
if (border.left < s.maxx and
border.right > s.minx and
border.top < s.maxz and
border.bottom > s.minz) then
localStructureCount = localStructureCount + 1
localStructure[localStructureCount] = i
end
end
--** Creates terraform building and assigns each one segment data **
local block = {}
local blocks = 0
terraformOrders = terraformOrders + 1
terraformOrder[terraformOrders] = {border = border, index = {}, indexes = 0}
local rampLevels = {count = 0, data = {[0] = {along = false}}}
local frame = spGetGameFrame()
for i = 1,n-1 do
-- detect overlapping buildings
segment[i].structure = {}
segment[i].structureCount = 0
segment[i].structureArea = {}
for j = 1, localStructureCount do
local s = structure[structureTable[localStructure[j]]]
if (segment[i].border.left < s.maxx and
segment[i].border.right > s.minx and
segment[i].border.top < s.maxz and
segment[i].border.bottom > s.minz) then
segment[i].structureCount = segment[i].structureCount + 1
segment[i].structure[segment[i].structureCount] = {id = s}
s.checkAtDeath = true
for lx = s.minx, s.maxx, 8 do
if not segment[i].structureArea[lx] then
segment[i].structureArea[lx] = {}
end
for lz = s.minz,s.maxz, 8 do
segment[i].structureArea[lx][lz] = (segment[i].structureArea[lx][lz] or 0) + 1
end
end
end
end
-- calculate cost
local totalCost = 0
local areaCost = 0
local perimeterCost = 0
for j = 1, segment[i].points do
if not segment[i].area[segment[i].point[j].x] then
segment[i].area[segment[i].point[j].x] = {}
end
segment[i].point[j].aimHeight = segment[i].point[j].y
SetupPointStructure(segment[i].point[j], segment[i].structureArea, segment[i].area)
totalCost = totalCost + abs(segment[i].point[j].diffHeight)
areaCost = areaCost + (pointExtraAreaCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraAreaCostDepth)
end
-- Perimeter Cost
local pyramidCostEstimate = 0
for j = 1, segment[i].points do
local x = segment[i].point[j].x
local z = segment[i].point[j].z
if segment[i].area[x] and segment[i].area[x][z] then
local edgeCount = 0
if (not segment[i].area[x+8]) or (not segment[i].area[x+8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x-8]) or (not segment[i].area[x-8][z]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z+8]) then
edgeCount = edgeCount + 1
end
if (not segment[i].area[x][z-8]) then
edgeCount = edgeCount + 1
end
if perimeterEdgeCost[edgeCount] > 0 then
perimeterCost = perimeterCost + perimeterEdgeCost[edgeCount]*(pointExtraPerimeterCostDepth > abs(segment[i].point[j].diffHeight) and abs(segment[i].point[j].diffHeight) or pointExtraPerimeterCostDepth)
end
if edgeCount > 0 then
local height = abs(segment[i].point[j].diffHeight)
if height > 30 then
pyramidCostEstimate = pyramidCostEstimate + ((height - height%maxHeightDifference)*(floor(height/maxHeightDifference)-1)*0.5 + floor(height/maxHeightDifference)*(height%maxHeightDifference))*volumeCost
end
end
end
end
if totalCost ~= 0 then
local baseCost = areaCost*pointExtraAreaCost + perimeterCost*pointExtraPerimeterCost + baseTerraunitCost
totalCost = totalCost*volumeCost + baseCost
if ECHO_DETAILED_COST_ESTIMATE then
Spring.Echo("Total Cost", totalCost, "Area Cost", areaCost*pointExtraAreaCost, "Perimeter Cost", perimeterCost*pointExtraPerimeterCost)
end
local pos = segment[i].position
local terraunitX, teamY, terraunitZ = GetTerraunitLeashedSpot(team, pos.x, pos.z, unitsX, unitsZ)
local id = spCreateUnit(terraunitDefID, terraunitX, teamY or 0, terraunitZ, 0, team, true)
if id then
spSetUnitHealth(id, 0.01)
if segment[i].along ~= rampLevels.data[rampLevels.count].along then