forked from zxbc/BAR_widgets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_customformations2.lua
1539 lines (1269 loc) · 49.2 KB
/
cmd_customformations2.lua
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
function widget:GetInfo()
return {
name = "CustomFormations2",
desc = "Allows you to draw your own formation line. Modified for speed and quality on high unit count.",
author = "Errrrrrr, Niobium", -- based on 'Custom Formations' by jK and gunblob
version = "v4.3",
date = "June 2, 2023",
license = "GNU GPL, v2 or later",
layer = 10000,
enabled = true,
handler = true,
}
end
-----------------------------------------------------------------------------------------
-- Modifications by Errrrrrr:
-- Distance matrices calc and sorting for matching algo moved to Update, values cached
-- Clash resolution changed to hierarchical, if time allows will process more tiers
-- Overall optimality should improve with very large unit count
-- Added some console messages for the new processing, set debugMode to true to see them
-----------------------------------------------------------------------------------------
local debugMode = false
-- 06/04/13 -- Cleaned up commands in Custom Formations:
-- To give a line command: select command, then right click & drag
-- To give a command within an area: select command, then left click and drag
-- To give a command at a point: select command, left click and don't drag
-- To area attack (bombers etc only): select command, hold alt, left click and drag
-- To deselect non-default command and return to default command: right click and don't drag
-- To deselect default command: left click
-- 29/05/13 -- Dots are of consistent size depending on zoom and terrain height
-- 25/05/13 -- Fixed crash bug that was triggered by pressing the left mouse button during line drawing with right mouse button. Also improved visuals.
-- 13/04/13 -- Visuals remade by PixelOfDeath
-- 23/03/13 -- Attack order y-coord placement remade by Bluestone for spring 94+
local getMiniMapFlipped = VFS.Include("luaui/Widgets/Include/minimap_utils.lua").getMiniMapFlipped
local dotImage = "LuaUI/Images/formationDot.dds"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- User Configurable Constants
--------------------------------------------------------------------------------
-- Minimum spacing between commands (Squared) when drawing a path for a single unit, must be >16*16 (Or orders overlap and cancel)
local minPathSpacingSq = 50 * 50
-- Minimum line length to cause formation move instead of single-click-style order
local minFormationLength = 20
-- How long should algorithms take. (~0.1 gives visible stutter, default: 0.05)
local maxHngTime = 0.01 -- Desired maximum time for hungarian algorithm
local maxNoXTime = 0.01 -- Strict maximum time for backup algorithm
local defaultHungarianUnits = 40 -- Need a baseline to start from when no config data saved
local minHungarianUnits = 10 -- If we kept reducing maxUnits it can get to a point where it can never increase, so we enforce minimums on the algorithms.
local unitIncreaseThresh = 0.85 -- We only increase maxUnits if the units are great enough for time to be meaningful
-- Alpha loss per second after releasing mouse
local lineFadeRate = 2.0
-- What commands are eligible for custom formations
local CMD_SETTARGET = 34923
local formationCmds = {
[CMD.MOVE] = true,
[CMD.FIGHT] = true,
[CMD.ATTACK] = true,
[CMD.PATROL] = true,
[CMD.UNLOAD_UNIT] = true,
[CMD_SETTARGET] = true -- set target
}
-- What commands require alt to be held
local requiresAlt = {
--nothing!
}
-- Context-based default commands that can be overridden (meaning that cf2 doesn't touch the command i.e. guard/attack when mouseover unit)
-- If the mouse remains on the same target for both Press/Release then the formation is ignored and original command is issued.
-- Normal logic will follow after override, i.e. must be a formationCmd to get formation, alt must be held if requiresAlt, etc.
local overrideCmds = {
[CMD.GUARD] = CMD.MOVE,
[CMD.ATTACK] = CMD.MOVE,
[CMD_SETTARGET] = CMD.MOVE
}
-- What commands can be issued at a position or unit/feature ID (Only used by GetUnitPosition)
local positionCmds = {
[CMD.MOVE]=true, [CMD.ATTACK]=true, [CMD.RECLAIM]=true, [CMD.RESTORE]=true, [CMD.RESURRECT]=true,
[CMD.PATROL]=true, [CMD.CAPTURE]=true, [CMD.FIGHT]=true, [CMD.MANUALFIRE]=true,
[CMD.UNLOAD_UNIT]=true, [CMD.UNLOAD_UNITS]=true,[CMD.LOAD_UNITS]=true, [CMD.GUARD]=true, [CMD.AREA_ATTACK] = true,
[CMD_SETTARGET] = true -- set target
}
local chobbyInterface
local lineLength = 0
--------------------------------------------------------------------------------
-- Globals
--------------------------------------------------------------------------------
local maxHungarianUnits = defaultHungarianUnits -- Also set when loading config
local fNodes = {} -- Formation nodes, filled as we draw
local fDists = {} -- fDists[i] = distance from node 1 to node i
local totaldxy = 0 -- Measure of distance mouse has moved, used to unjag lines drawn in minimap
local dimmCmd = nil -- The dimming command (Used for color)
local dimmNodes = {} -- The current nodes of dimming line
local dimmAlpha = 0 -- The current alpha of dimming line
local pathCandidate = false -- True if we should start a path on mouse move
local draggingPath = false -- True if we are dragging a path for unit(s) to follow
local lastPathPos = nil -- The last point added to the path, used for min-distance check
local overriddenCmd = nil -- The command we ignored in favor of move
local overriddenTarget = nil -- The target (for params) we ignored
local usingCmd = nil -- The command to execute across the line
local usingRMB = false -- All commands use right mouse + drag to do a formation command
local inMinimap = false -- Is the line being drawn in the minimap
local endShift = false -- True to reset command when shift is released
local MiniMapFullProxy = (Spring.GetConfigInt("MiniMapFullProxy", 0) == 1)
-- cache tables for preprocessing
local unitSetCache = {}
local nodesCache = {}
local unitsCache = {}
-- cache tables for delayed processing
local delayedProcessing = 0
local unitSetCacheDelayed = {}
local nodesCacheDelayed = {}
local unitsCacheDelayed = {}
--------------------------------------------------------------------------------
-- Speedups
--------------------------------------------------------------------------------
local GL_LINE_STRIP = GL.LINE_STRIP
local glVertex = gl.Vertex
local glLineStipple = gl.LineStipple
local glLineWidth = gl.LineWidth
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glScale = gl.Scale
local glTranslate = gl.Translate
local glLoadIdentity = gl.LoadIdentity
local spGetActiveCommand = Spring.GetActiveCommand
local spSetActiveCommand = Spring.SetActiveCommand
local spGetDefaultCommand = Spring.GetDefaultCommand
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spGetModKeyState = Spring.GetModKeyState
local spGetInvertQueueKey = Spring.GetInvertQueueKey
local spIsAboveMiniMap = Spring.IsAboveMiniMap
local spGetUnitDefID = Spring.GetUnitDefID
local spGiveOrder = Spring.GiveOrder
local spGetUnitIsTransporting = Spring.GetUnitIsTransporting
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitPosition = Spring.GetUnitPosition
local spTraceScreenRay = Spring.TraceScreenRay
local spGetGroundHeight = Spring.GetGroundHeight
local spGetFeaturePosition = Spring.GetFeaturePosition
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetUnitHeight = Spring.GetUnitHeight
local spGetCameraPosition = Spring.GetCameraPosition
local spGetViewGeometry = Spring.GetViewGeometry
local spTraceScreenRay = Spring.TraceScreenRay
local mapSizeX, mapSizeZ = Game.mapSizeX, Game.mapSizeZ
local maxUnits = Game.maxUnits
local osclock = os.clock
local tsort = table.sort
local floor = math.floor
local ceil = math.ceil
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local max = math.max
local huge = math.huge
local pi2 = 2*math.pi
local CMD_INSERT = CMD.INSERT
local CMD_MOVE = CMD.MOVE
local CMD_ATTACK = CMD.ATTACK
local CMD_UNLOADUNIT = CMD.UNLOAD_UNIT
local CMD_UNLOADUNITS = CMD.UNLOAD_UNITS
local CMD_OPT_ALT = CMD.OPT_ALT
local CMD_OPT_CTRL = CMD.OPT_CTRL
local CMD_OPT_META = CMD.OPT_META
local CMD_OPT_SHIFT = CMD.OPT_SHIFT
local CMD_OPT_RIGHT = CMD.OPT_RIGHT
local keyShift = 304
local selectedUnits = Spring.GetSelectedUnits()
local selectedUnitsCount = Spring.GetSelectedUnitsCount()
--------------------------------------------------------------------------------
-- Helper Functions
--------------------------------------------------------------------------------
-- deepcopy a table
local function deepCopy(original)
if type(original) ~= 'table' then
return original
end
local copy = {}
for key, value in next, original, nil do
copy[deepCopy(key)] = deepCopy(value)
end
return setmetatable(copy, getmetatable(original))
end
local function GetModKeys()
local alt, ctrl, meta, shift = spGetModKeyState()
if spGetInvertQueueKey() then -- Shift inversion
shift = not shift
end
return alt, ctrl, meta, shift
end
local function GetUnitFinalPosition(uID)
local ux, uy, uz = spGetUnitPosition(uID)
local cmds = spGetCommandQueue(uID,5000)
if cmds then
for i = #cmds, 1, -1 do
local cmd = cmds[i]
if (cmd.id < 0) or positionCmds[cmd.id] then
local params = cmd.params
if #params >= 3 then
return params[1], params[2], params[3]
else
if #params == 1 then
local pID = params[1]
local px, py, pz
if pID > maxUnits then
px, py, pz = spGetFeaturePosition(pID - maxUnits)
else
px, py, pz = spGetUnitPosition(pID)
end
if px then
return px, py, pz
end
end
end
end
end
end
return ux, uy, uz
end
local function SetColor(cmdID, alpha)
if cmdID == CMD_MOVE then glColor(0.5, 1.0, 0.5, alpha) -- Green
elseif cmdID == CMD_ATTACK then glColor(1.0, 0.2, 0.2, alpha) -- Red
elseif cmdID == CMD_UNLOADUNIT then glColor(1.0, 1.0, 0.0, alpha) -- Yellow
elseif cmdID == CMD_SETTARGET then glColor(1.0, 0.7, 0.0, alpha) -- Orange
else glColor(0.5, 0.5, 1.0, alpha) -- Blue
end
end
local function CanUnitExecute(uID, cmdID)
if cmdID == CMD_UNLOADUNIT then
local transporting = spGetUnitIsTransporting(uID)
return (transporting and #transporting > 0)
end
return (spFindUnitCmdDesc(uID, cmdID) ~= nil)
end
local function GetExecutingUnits(cmdID)
local units = {}
for i = 1, selectedUnitsCount do
local uID = selectedUnits[i]
if CanUnitExecute(uID, cmdID) then
units[#units + 1] = uID
end
end
return units
end
local function AddFNode(pos)
local px, pz = pos[1], pos[3]
if px < 0 or pz < 0 or px > mapSizeX or pz > mapSizeZ then
return false
end
local n = #fNodes
if n == 0 then
fNodes[1] = pos
fDists[1] = 0
else
local prevNode = fNodes[n]
local dx, dz = px - prevNode[1], pz - prevNode[3]
local distSq = dx*dx + dz*dz
if distSq == 0.0 then -- Don't add if duplicate
return false
end
fNodes[n + 1] = pos
fDists[n + 1] = fDists[n] + sqrt(distSq)
lineLength = lineLength+distSq^0.5
WG.customformations_linelength = lineLength
end
totaldxy = 0
return true
end
local function GetInterpNodes(mUnits)
local number = #mUnits
local spacing = fDists[#fNodes] / (#mUnits - 1)
local interpNodes = {}
local sPos = fNodes[1]
local sX = sPos[1]
local sZ = sPos[3]
local sY=spGetGroundHeight(sX, sZ)
local sDist = 0
local eIdx = 2
local ePos = fNodes[2]
local eX = ePos[1]
local eZ = ePos[3]
local eDist = fDists[2]
local eY
interpNodes[1] = {sX, sY, sZ}
for n = 1, number - 2 do
local reqDist = n * spacing
while (reqDist > eDist) do
sX = eX
sZ = eZ
sDist = eDist
eIdx = eIdx + 1
ePos = fNodes[eIdx]
eX = ePos[1]
eZ = ePos[3]
eDist = fDists[eIdx]
end
local nFrac = (reqDist - sDist) / (eDist - sDist)
local nX = sX * (1 - nFrac) + eX * nFrac
local nZ = sZ * (1 - nFrac) + eZ * nFrac
local nY = spGetGroundHeight(nX, nZ)
interpNodes[n + 1] = {nX, nY, nZ}
end
ePos = fNodes[#fNodes]
eX = ePos[1]
eZ = ePos[3]
eY = spGetGroundHeight(eX, eZ)
interpNodes[number] = {eX, eY, eZ}
--DEBUG for i=1,number do Spring.Echo(interpNodes[i]) end
return interpNodes
end
local function GetCmdOpts(alt, ctrl, meta, shift, right)
local opts = { alt=alt, ctrl=ctrl, meta=meta, shift=shift, right=right }
local coded = 0
if alt then coded = coded + CMD_OPT_ALT end
if ctrl then coded = coded + CMD_OPT_CTRL end
if meta then coded = coded + CMD_OPT_META end
if shift then coded = coded + CMD_OPT_SHIFT end
if right then coded = coded + CMD_OPT_RIGHT end
opts.coded = coded
return opts
end
local function GiveNotifyingOrder(cmdID, cmdParams, cmdOpts)
if widgetHandler:CommandNotify(cmdID, cmdParams, cmdOpts) then
return
end
spGiveOrder(cmdID, cmdParams, cmdOpts.coded)
end
local function GiveNotifyingOrderToUnit(uArr, oArr, uID, cmdID, cmdParams, cmdOpts)
for _, w in ipairs(widgetHandler.widgets) do
if w.UnitCommandNotify and w:UnitCommandNotify(uID, cmdID, cmdParams, cmdOpts) then
return
end
end
uArr[#uArr + 1] = uID
oArr[#oArr + 1] = {cmdID, cmdParams, cmdOpts.coded}
return
end
function widget:SelectionChanged(sel)
selectedUnits = sel
selectedUnitsCount = Spring.GetSelectedUnitsCount()
end
--------------------------------------------------------------------------------
-- Mouse/keyboard Callins
--------------------------------------------------------------------------------
function widget:MousePress(mx, my, mButton)
lineLength=0 --for linestipple
-- Where did we click
inMinimap = spIsAboveMiniMap(mx, my)
if inMinimap and not MiniMapFullProxy then return false end
if mButton ~= 3 and usingRMB then
fNodes = {}
fDists = {}
usingRMB = false
end
--Spring.Echo("mouse:", mButton)
if mButton ~= 3 then return false end --all formation commands are done using right click & drag
-- Get command that would've been issued
local _, activeCmdID = spGetActiveCommand()
if activeCmdID then
usingCmd = activeCmdID
usingRMB = true
else
local _, defaultCmdID = spGetDefaultCommand() --spGetActiveCommand() returns nil if the default command (typically move) is in use
if not defaultCmdID then return false end
local overrideCmdID = overrideCmds[defaultCmdID]
if overrideCmdID then
local targType, targID = spTraceScreenRay(mx, my, false, inMinimap)
if targType == 'unit' then
overriddenCmd = defaultCmdID
overriddenTarget = targID
elseif targType == 'feature' then
overriddenCmd = defaultCmdID
overriddenTarget = targID + maxUnits
else
-- We can't reversibly override a command if we can't get the original target, so we give up overriding it.
return false
end
usingCmd = overrideCmdID
else
overriddenCmd = nil
overriddenTarget = nil
usingCmd = defaultCmdID
end
usingRMB = true
end
-- Without this, the unloads issued will use the area of the last area unload
if usingCmd == CMD_UNLOADUNITS then
usingCmd = CMD_UNLOADUNIT
end
-- Is this command eligible for a custom formation ?
local alt, ctrl, meta, shift = GetModKeys()
if not (formationCmds[usingCmd] and (alt or not requiresAlt[usingCmd])) then
return false
end
-- Get clicked position
local _, pos = spTraceScreenRay(mx, my, true, inMinimap)
if not pos then return false end
-- Setup formation node array
if not AddFNode(pos) then return false end
-- Is this line a path candidate (We don't do a path off an overriden command)
pathCandidate = (not overriddenCmd) and (selectedUnitsCount==1 or (alt and not requiresAlt[usingCmd]))
-- We handled the mouse press
WG.customformations_linelength = lineLength
return true
end
function widget:MouseMove(mx, my, dx, dy, mButton)
-- It is possible for MouseMove to fire after MouseRelease
if #fNodes == 0 then
return false
end
-- Minimap-specific checks
if inMinimap then
totaldxy = totaldxy + dx*dx + dy*dy
if (totaldxy < 5) or not spIsAboveMiniMap(mx, my) then
return false
end
end
-- Get clicked position
local _, pos = spTraceScreenRay(mx, my, true, inMinimap)
if not pos then return false end
-- Add the new formation node
if not AddFNode(pos) then return false end
-- Have we started drawing a line?
if #fNodes == 2 then
-- We have enough nodes to start drawing now
widgetHandler:UpdateWidgetCallIn("DrawInMiniMap", self)
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
-- If the line is a path, start the units moving to this node
if pathCandidate then
local alt, ctrl, meta, shift = GetModKeys()
local cmdOpts = GetCmdOpts(false, ctrl, meta, shift, usingRMB) -- using alt uses springs box formation, so we set it off always
GiveNotifyingOrder(usingCmd, pos, cmdOpts)
lastPathPos = pos
draggingPath = true
end
else
-- Are we dragging a path?
if draggingPath then
local dx, dz = pos[1] - lastPathPos[1], pos[3] - lastPathPos[3]
if (dx*dx + dz*dz) > minPathSpacingSq then
local alt, ctrl, meta, shift = GetModKeys()
local cmdOpts = GetCmdOpts(false, ctrl, meta, true, usingRMB) -- using alt uses springs box formation, so we set it off always
GiveNotifyingOrder(usingCmd, pos, cmdOpts)
lastPathPos = pos
end
end
end
WG.customformations_linelength = lineLength
return false
end
function widget:MouseRelease(mx, my, mButton)
lineLength = 0
WG.customformations_linelength = lineLength
-- It is possible for MouseRelease to fire after MouseRelease
if #fNodes == 0 then
return false
end
-- Modkeys / command reset
local alt, ctrl, meta, shift = GetModKeys()
if not usingRMB then
if shift then
endShift = true -- Reset on release of shift
else
spSetActiveCommand(0) -- Deselect command
end
end
-- Are we going to use the drawn formation?
local usingFormation = true
-- Override checking
if overriddenCmd then
local targetID
local targType, targID = spTraceScreenRay(mx, my, false, inMinimap)
if targType == 'unit' then
targetID = targID
elseif targType == 'feature' then
targetID = targID + maxUnits
end
if targetID and targetID == overriddenTarget then
-- Signal that we are no longer using the drawn formation
usingFormation = false
-- Process the original command instead
local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB)
GiveNotifyingOrder(overriddenCmd, {overriddenTarget}, cmdOpts)
end
end
-- Using path? If so then we do nothing
if draggingPath then
draggingPath = false
-- Using formation? If so then it's time to calculate and issue orders.
elseif usingFormation then
-- Add final position (Sometimes we don't get the last MouseMove before this MouseRelease)
if (not inMinimap) or spIsAboveMiniMap(mx, my) then
local _, pos = spTraceScreenRay(mx, my, true, inMinimap)
if pos then
AddFNode(pos)
end
end
-- Get command options
local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB)
-- Single click ? (no line drawn)
--if (#fNodes == 1) then
-- we add the drag threshold code here
-- tracing to a point with a drag threshold pixel delta added to mouse coord, to get world distance
local selectionThreshold = Spring.GetConfigInt("MouseDragFrontCommandThreshold")*2
local _, dragDeltaPos = spTraceScreenRay(mx,my+selectionThreshold, true, false, false, true)
local _, pos = spTraceScreenRay(mx, my, true, false, false, true)
local dragDelta = 0
if dragDeltaPos and pos then
dragDelta = pos[3] - dragDeltaPos[3]
end
local adjustedMinFormationLength = max(dragDelta, minFormationLength)
if fDists[#fNodes] < adjustedMinFormationLength or (usingCmd == CMD.UNLOAD_UNIT and fDists[#fNodes] < 64*(selectedUnitsCount - 1)) then
-- We should check if any units are able to execute it,
-- but the order is small enough network-wise that the tiny bug potential isn't worth it.
-- Check if this order was meant to target a unit
local targetID
if overrideCmds[usingCmd] then
local targType, targID = spTraceScreenRay(mx, my, false, inMinimap)
if targType == 'unit' then
targetID = targID
elseif targType == 'feature' then
targetID = targID + maxUnits
end
end
if targetID then
-- Give order (i.e. pass the command to the engine to use as normal)
GiveNotifyingOrder(usingCmd, {targetID}, cmdOpts)
elseif usingCmd == CMD_MOVE then
GiveNotifyingOrder(usingCmd, {fNodes[1][1],fNodes[1][2],fNodes[1][3]}, cmdOpts)
else
-- Deselect command, select default command instead
spSetActiveCommand(0)
end
else
-- Order is a formation; line was drawn
-- Are any units able to execute it?
local mUnits = unitsCache -- GetExecutingUnits(usingCmd)
if mUnits and #mUnits > 0 then
local interpNodes = nodesCache --GetInterpNodes(mUnits)
if not interpNodes or #interpNodes == 0 then
nodesCache = GetInterpNodes(mUnits)
end
local orders
if (#mUnits <= maxHungarianUnits) then
orders = GetOrdersHungarian(interpNodes, mUnits, #mUnits, shift and not meta)
--Spring.Echo("Used Hungarian!")
else
orders = GetOrdersNoX(interpNodes, mUnits, #mUnits, shift and not meta)
end
local unitArr = {}
local orderArr = {}
if meta then
local altOpts = GetCmdOpts(true, false, false, false, false)
for i = 1, #orders do
local orderPair = orders[i]
local orderPos = orderPair[2]
GiveNotifyingOrderToUnit(unitArr, orderArr, orderPair[1], CMD_INSERT, {0, usingCmd, cmdOpts.coded, orderPos[1], orderPos[2], orderPos[3]}, altOpts)
if (i == #orders and #unitArr > 0) or #unitArr >= 583 then
Spring.GiveOrderArrayToUnitArray(unitArr, orderArr, true)
unitArr = {}
orderArr = {}
end
end
else
for i = 1, #orders do
local orderPair = orders[i]
GiveNotifyingOrderToUnit(unitArr, orderArr, orderPair[1], usingCmd, orderPair[2], cmdOpts)
if (i == #orders and #unitArr > 0) or #unitArr >= 583 then
Spring.GiveOrderArrayToUnitArray(unitArr, orderArr, true)
unitArr = {}
orderArr = {}
end
end
end
spSetActiveCommand(0) -- Deselect command
--[[ -- move caches over to delayed, initiate delayed processing
delayedProcessing = 5 -- we set this to 5 ticks of 0.1s for a total of 0.5s, counting down
unitSetCacheDelayed = deepCopy(unitSetCache)
nodesCacheDelayed = deepCopy(nodesCache)
unitsCacheDelayed = deepCopy(unitsCache) ]]
-- clear preprocessing caches
unitSetCache = {}
nodesCache = {}
unitsCache = {}
end
end
end
if #fNodes > 1 then
dimmCmd = usingCmd
dimmNodes = fNodes
dimmAlpha = 1.0
widgetHandler:UpdateWidgetCallIn("Update", self)
end
fNodes = {}
fDists = {}
return true
end
function widget:KeyRelease(key)
if (key == keyShift) and endShift then
spSetActiveCommand(0)
endShift = false
end
end
--------------------------------------------------------------------------------
-- Drawing
--------------------------------------------------------------------------------
local function tVerts(verts)
for i = 1, #verts do
local v = verts[i]
glVertex(v[1], v[2], v[3])
end
end
local function tVertsMinimap(verts)
for i = 1, #verts do
local v = verts[i]
glVertex(v[1], v[3], 1)
end
end
local function DrawGroundquad(x,y,z,size)
gl.TexCoord(0,0)
gl.Vertex(x-size,y,z-size)
gl.TexCoord(0,1)
gl.Vertex(x-size,y,z+size)
gl.TexCoord(1,1)
gl.Vertex(x+size,y,z+size)
gl.TexCoord(1,0)
gl.Vertex(x+size,y,z-size)
end
local function DrawFilledCircleOutFading(pos, size, cornerCount)
SetColor(usingCmd, 1)
local lengthPerUnit = lineLength / (selectedUnitsCount-1)
local lengthUnitNext = lengthPerUnit
if (lengthPerUnit < 64) and (usingCmd == CMD.UNLOAD_UNIT) then
glColor(1.0,0.3,0.0,1.0)
end
gl.Texture(dotImage)
gl.BeginEnd(GL.QUADS,DrawGroundquad, pos[1], pos[2], pos[3], size)
gl.Texture(false)
end
local function DrawFormationDots(vertFunction, zoomY)
gl.PushAttrib(GL.ALL_ATTRIB_BITS)
local currentLength = 0
local lengthPerUnit = lineLength / (selectedUnitsCount-1)
local lengthUnitNext = lengthPerUnit
local dotSize = sqrt(zoomY*0.24)
if (#fNodes > 1) and (selectedUnitsCount > 1) then
SetColor(usingCmd, 0.6)
if (lengthPerUnit < 64) and (usingCmd == CMD.UNLOAD_UNIT) then
glColor(1.0,0.3,0.0,0.6)
end
DrawFilledCircleOutFading(fNodes[1], dotSize)
if (#fNodes > 2) then
for i=1, #fNodes-1 do
local x = fNodes[i][1]
local y = fNodes[i][3]
local x2 = fNodes[i+1][1]
local y2 = fNodes[i+1][3]
local dx = x - x2
local dy = y - y2
local length = sqrt((dx*dx)+(dy*dy))
while (currentLength + length >= lengthUnitNext) do
local factor = (lengthUnitNext - currentLength) / length
local factorPos =
{fNodes[i][1] + ((fNodes[i+1][1] - fNodes[i][1]) * factor),
fNodes[i][2] + ((fNodes[i+1][2] - fNodes[i][2]) * factor),
fNodes[i][3] + ((fNodes[i+1][3] - fNodes[i][3]) * factor)}
DrawFilledCircleOutFading(factorPos, dotSize)
lengthUnitNext = lengthUnitNext + lengthPerUnit
end
currentLength = currentLength + length
end
end
DrawFilledCircleOutFading(fNodes[#fNodes], dotSize)
end
gl.PopAttrib(GL.ALL_ATTRIB_BITS)
end
local function DrawFormationLines(vertFunction, lineStipple)
glLineStipple(lineStipple, 4369)
glLineWidth(2.0)
if #fNodes > 1 then
SetColor(usingCmd, 1.0)
glBeginEnd(GL_LINE_STRIP, vertFunction, fNodes)
end
if #dimmNodes > 1 then
SetColor(dimmCmd, dimmAlpha)
glBeginEnd(GL_LINE_STRIP, vertFunction, dimmNodes)
end
glLineWidth(1.0)
glLineStipple(false)
end
local Xs, Ys = spGetViewGeometry()
Xs, Ys = Xs*0.5, Ys*0.5
function widget:ViewResize(viewSizeX, viewSizeY)
Xs, Ys = spGetViewGeometry()
Xs, Ys = Xs*0.5, Ys*0.5
end
function widget:RecvLuaMsg(msg, playerID)
if msg:sub(1,18) == 'LobbyOverlayActive' then
chobbyInterface = (msg:sub(1,19) == 'LobbyOverlayActive1')
end
end
function widget:DrawWorld()
if chobbyInterface then return end
if #fNodes > 1 or #dimmNodes > 1 then
local camX, camY, camZ = spGetCameraPosition()
local at, p = spTraceScreenRay(Xs,Ys,true,false,false)
local zoomY
if at == "ground" then
local dx, dy, dz = camX-p[1], camY-p[2], camZ-p[3]
--zoomY = ((dx*dx + dy*dy + dz*dz)*0.01)^0.25 --tests show that sqrt(sqrt(x)) is faster than x^0.25
zoomY = sqrt(dx*dx + dy*dy + dz*dz)
else
--zoomY = sqrt((camY - max(spGetGroundHeight(camX, camZ), 0))*0.1)
zoomY = camY - max(spGetGroundHeight(camX, camZ), 0)
end
if zoomY < 6 then zoomY = 6 end
if lineLength > 0 then --don't try and draw if the command was cancelled by having two mouse buttons pressed at once
DrawFormationDots(tVerts, zoomY)
end
glColor(1,1,1,1)
end
end
--TODO maybe include minimap drawing again
function widget:DrawInMiniMap()
glPushMatrix()
glLoadIdentity()
if getMiniMapFlipped() then
glTranslate(1, 0, 0)
glScale(-1 / mapSizeX, 1 / mapSizeZ, 1)
else
glTranslate(0, 1, 0)
glScale(1 / mapSizeX, -1 / mapSizeZ, 1)
end
DrawFormationLines(tVertsMinimap, 1)
glPopMatrix()
end
local function updatePreprocessingCache(delayed)
local units, nodes, unitSet
unitsCache = GetExecutingUnits(usingCmd)
units = unitsCache
if #units > 0 then
nodesCache = GetInterpNodes(unitsCache)
nodes = nodesCache
unitSet = unitSetCache
--Spring.Echo("Processing unitSetCache on ".. tostring(#unitsCache).." units...")
local fdist = -1
local fm
local _, _, _, shifted = GetModKeys()
local unitCount = #units
if unitCount == 0 then return end
for u = 1, unitCount do
-- Get unit position
local ux, uz
if shifted then
ux, _, uz = GetUnitFinalPosition(units[u])
else
ux, _, uz = spGetUnitPosition(units[u])
end
if ux then
unitSet[u] = {ux, units[u], uz, -1} -- Such that x/z are in same place as in nodes (So we can use same sort function)
-- Work on finding furthest points (As we have ux/uz already)
for i = u - 1, 1, -1 do
local up = unitSet[i]
local vx, vz = up[1], up[3]
local dx, dz = vx - ux, vz - uz
local dist = dx*dx + dz*dz
if (dist > fdist) then
fdist = dist
fm = (vz - uz) / (vx - ux)
end
end
end
end
if #nodes == 0 then return end
-- Maybe nodes are further apart than the units
for i = 1, unitCount - 1 do
local np = nodes[i]
local nx, nz = np[1], np[3]
for j = i + 1, unitCount do
local mp = nodes[j]
local mx, mz = mp[1], mp[3]
local dx, dz = mx - nx, mz - nz
local dist = dx*dx + dz*dz
if (dist > fdist) then
fdist = dist
fm = (mz - nz) / (mx - nx)
end
end
end
local function sortFunc(a, b)
-- y = mx + c
-- c = y - mx
-- c = y + x / m (For perp line)
return (a[3] + a[1] / fm) < (b[3] + b[1] / fm)
end
if fm then
tsort(unitSet, sortFunc)
tsort(nodes, sortFunc)
end
for u = 1, unitCount do
unitSet[u][4] = nodes[u]
end
else
return
end
end
local frames = 0
function widget:Update(deltaTime)
frames = frames + 1
-- cache unit and note positions every 2 frames when drawing formation
-- worst case scenario is cache is 2 frames old
if frames % 2 == 1 and usingCmd and #fNodes > 1 then
updatePreprocessingCache(false)
end
--[[ if frames % 3 == 2 and delayedProcessing > 0 then
--Spring.Echo("delayed processing left: ".. tostring(delayedProcessing))
-- do delayed processing here
delayedProcessing = delayedProcessing - 1
end ]]
dimmAlpha = dimmAlpha - lineFadeRate * deltaTime
if dimmAlpha <= 0 then
dimmNodes = {}
--widgetHandler:RemoveWidgetCallIn("Update", self)
if #fNodes == 0 then
widgetHandler:RemoveWidgetCallIn("DrawWorld", self)
widgetHandler:RemoveWidgetCallIn("DrawInMiniMap", self)
end