Line data Source code
1 : // Setting this to true will display some warnings when commands
2 : // are likely to fail, which may be useful for debugging AIs
3 1 : var g_DebugCommands = false;
4 :
5 1 : var g_Commands = {
6 :
7 : "aichat": function(player, cmd, data)
8 : {
9 0 : var cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
10 0 : var notification = { "players": [player] };
11 0 : for (var key in cmd)
12 0 : notification[key] = cmd[key];
13 0 : cmpGuiInterface.PushNotification(notification);
14 : },
15 :
16 : "cheat": function(player, cmd, data)
17 : {
18 0 : Cheat(cmd);
19 : },
20 :
21 : "collect-treasure": function(player, cmd, data)
22 : {
23 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
24 : {
25 0 : cmpUnitAI.CollectTreasure(cmd.target, cmd.queued);
26 : });
27 : },
28 :
29 : "collect-treasure-near-position": function(player, cmd, data)
30 : {
31 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
32 : {
33 0 : cmpUnitAI.CollectTreasureNearPosition(cmd.x, cmd.z, cmd.queued);
34 : });
35 : },
36 :
37 : "diplomacy": function(player, cmd, data)
38 : {
39 0 : if (Engine.QueryInterface(SYSTEM_ENTITY, IID_CeasefireManager).IsCeasefireActive())
40 0 : return;
41 :
42 0 : const cmpDiplomacy = QueryPlayerIDInterface(player, IID_Diplomacy);
43 0 : if (!cmpDiplomacy || cmpDiplomacy.IsTeamLocked())
44 0 : return;
45 :
46 0 : switch (cmd.to)
47 : {
48 : case "ally":
49 0 : cmpDiplomacy.Ally(cmd.player);
50 0 : break;
51 : case "neutral":
52 0 : cmpDiplomacy.SetNeutral(cmd.player);
53 0 : break;
54 : case "enemy":
55 0 : cmpDiplomacy.SetEnemy(cmd.player);
56 0 : break;
57 : default:
58 0 : warn("Invalid command: Could not set "+player+" diplomacy status of player "+cmd.player+" to "+cmd.to);
59 : }
60 :
61 0 : Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface).PushNotification({
62 : "type": "diplomacy",
63 : "players": [player],
64 : "targetPlayer": cmd.player,
65 : "status": cmd.to
66 : });
67 : },
68 :
69 : "tribute": function(player, cmd, data)
70 : {
71 0 : data.cmpPlayer.TributeResource(cmd.player, cmd.amounts);
72 : },
73 :
74 : "control-all": function(player, cmd, data)
75 : {
76 0 : if (!InitAttributes.settings.CheatsEnabled)
77 0 : return;
78 :
79 0 : var cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
80 0 : cmpGuiInterface.PushNotification({
81 : "type": "aichat",
82 : "players": [player],
83 : "message": markForTranslation("(Cheat - control all units)")
84 : });
85 :
86 0 : data.cmpPlayer.SetControlAllUnits(cmd.flag);
87 : },
88 :
89 : "reveal-map": function(player, cmd, data)
90 : {
91 0 : if (!InitAttributes.settings.CheatsEnabled)
92 0 : return;
93 :
94 0 : var cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
95 0 : cmpGuiInterface.PushNotification({
96 : "type": "aichat",
97 : "players": [player],
98 : "message": markForTranslation("(Cheat - reveal map)")
99 : });
100 :
101 : // Reveal the map for all players, not just the current player,
102 : // primarily to make it obvious to everyone that the player is cheating
103 0 : var cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
104 0 : cmpRangeManager.SetLosRevealWholeMapForAll(cmd.enable);
105 : },
106 :
107 : "walk": function(player, cmd, data)
108 : {
109 0 : const ents = data.entities.length;
110 0 : const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation);
111 0 : if (uais.length === 1 || uais.length !== ents)
112 0 : uais.forEach(cmpUnitAI =>
113 : {
114 0 : cmpUnitAI.Walk(cmd.x, cmd.z, cmd.queued, cmd.pushFront);
115 : });
116 : else
117 : {
118 0 : const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z);
119 0 : uais.forEach((cmpUnitAI, index) =>
120 : {
121 0 : cmpUnitAI.Walk(positions[index].x, positions[index].y, cmd.queued, cmd.pushFront);
122 : });
123 : }
124 : },
125 :
126 : "walk-custom": function(player, cmd, data)
127 : {
128 0 : for (const ent in data.entities)
129 0 : GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI =>
130 : {
131 0 : cmpUnitAI.Walk(cmd.targetPositions[ent].x, cmd.targetPositions[ent].y, cmd.queued, cmd.pushFront);
132 : });
133 : },
134 :
135 : "walk-to-range": function(player, cmd, data)
136 : {
137 : // Only used by the AI
138 0 : for (const ent of data.entities)
139 : {
140 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
141 0 : if (cmpUnitAI)
142 0 : cmpUnitAI.WalkToPointRange(cmd.x, cmd.z, cmd.min, cmd.max, cmd.queued, cmd.pushFront);
143 : }
144 : },
145 :
146 : "attack-walk": function(player, cmd, data)
147 : {
148 0 : const ents = data.entities.length;
149 0 : const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation);
150 0 : if (uais.length === 1 || uais.length !== ents)
151 0 : uais.forEach(cmpUnitAI =>
152 : {
153 0 : cmpUnitAI.WalkAndFight(cmd.x, cmd.z, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront);
154 : });
155 : else
156 : {
157 0 : const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z);
158 0 : uais.forEach((cmpUnitAI, index) =>
159 : {
160 0 : cmpUnitAI.WalkAndFight(positions[index].x, positions[index].y, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront);
161 : });
162 : }
163 : },
164 :
165 : "attack-walk-custom": function(player, cmd, data)
166 : {
167 0 : for (const ent in data.entities)
168 0 : GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI =>
169 : {
170 0 : cmpUnitAI.WalkAndFight(cmd.targetPositions[ent].x, cmd.targetPositions[ent].y, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront);
171 : });
172 : },
173 :
174 : "attack": function(player, cmd, data)
175 : {
176 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
177 : {
178 0 : cmpUnitAI.Attack(cmd.target, cmd.allowCapture, cmd.queued, cmd.pushFront);
179 : });
180 : },
181 :
182 : "attack-group": function(player, cmd, data)
183 : {
184 0 : const unitAIs = data.entities.flatMap(ent =>
185 : {
186 0 : const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
187 0 : const cmpAttack = Engine.QueryInterface(ent, IID_Attack);
188 :
189 : // Check if unit can move and has attack capability
190 0 : const canAttack = cmpAttack && cmpAttack.GetAttackTypes().length > 0;
191 0 : return (cmpUnitAI && cmpUnitAI.AbleToMove() && canAttack) ? [cmpUnitAI] : [];
192 : });
193 :
194 0 : if (!unitAIs.length || !cmd.targets?.length)
195 0 : return;
196 :
197 : // Pass the entire target array and unit count to each UnitAI
198 0 : unitAIs.forEach((cmpUnitAI, index) =>
199 : {
200 0 : cmpUnitAI.AttackGroup(cmd.targets, index, unitAIs.length, cmd.allowCapture, cmd.queued, cmd.pushFront);
201 : });
202 : },
203 :
204 : "patrol": function(player, cmd, data)
205 : {
206 0 : const ents = data.entities.length;
207 0 : const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation);
208 0 : if (uais.length === 1 || uais.length !== ents)
209 0 : uais.forEach(cmpUnitAI =>
210 : {
211 0 : cmpUnitAI.Patrol(cmd.x, cmd.z, cmd.targetClasses, cmd.allowCapture, cmd.queued);
212 : });
213 : else
214 : {
215 0 : const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z);
216 0 : uais.forEach((cmpUnitAI, index) =>
217 : {
218 0 : cmpUnitAI.Patrol(positions[index].x, positions[index].y, cmd.targetClasses, cmd.allowCapture, cmd.queued);
219 : });
220 : }
221 : },
222 :
223 : "heal": function(player, cmd, data)
224 : {
225 0 : if (g_DebugCommands && !(IsOwnedByPlayer(player, cmd.target) || IsOwnedByAllyOfPlayer(player, cmd.target)))
226 0 : warn("Invalid command: heal target is not owned by player "+player+" or their ally: "+uneval(cmd));
227 :
228 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
229 : {
230 0 : cmpUnitAI.Heal(cmd.target, cmd.queued, cmd.pushFront);
231 : });
232 : },
233 :
234 : "repair": function(player, cmd, data)
235 : {
236 : // This covers both repairing damaged buildings, and constructing unfinished foundations
237 0 : if (g_DebugCommands && !IsOwnedByAllyOfPlayer(player, cmd.target))
238 0 : warn("Invalid command: repair target is not owned by ally of player "+player+": "+uneval(cmd));
239 :
240 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
241 : {
242 0 : cmpUnitAI.Repair(cmd.target, cmd.autocontinue, cmd.queued, cmd.pushFront);
243 : });
244 : },
245 :
246 : "gather": function(player, cmd, data)
247 : {
248 0 : if (g_DebugCommands && !(IsOwnedByPlayer(player, cmd.target) || IsOwnedByGaia(cmd.target)))
249 0 : warn("Invalid command: resource is not owned by gaia or player "+player+": "+uneval(cmd));
250 :
251 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
252 : {
253 0 : cmpUnitAI.Gather(cmd.target, cmd.queued, cmd.pushFront);
254 : });
255 : },
256 :
257 : "gather-near-position": function(player, cmd, data)
258 : {
259 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
260 : {
261 0 : cmpUnitAI.GatherNearPosition(cmd.x, cmd.z, cmd.resourceType, cmd.resourceTemplate, cmd.queued, cmd.pushFront);
262 : });
263 : },
264 :
265 : "returnresource": function(player, cmd, data)
266 : {
267 0 : if (g_DebugCommands && !IsOwnedByPlayer(player, cmd.target))
268 0 : warn("Invalid command: dropsite is not owned by player "+player+": "+uneval(cmd));
269 :
270 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
271 : {
272 0 : cmpUnitAI.ReturnResource(cmd.target, cmd.queued, cmd.pushFront);
273 : });
274 : },
275 :
276 : "back-to-work": function(player, cmd, data)
277 : {
278 0 : for (const ent of data.entities)
279 : {
280 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
281 0 : if (!cmpUnitAI || !cmpUnitAI.BackToWork())
282 0 : notifyBackToWorkFailure(player);
283 : }
284 : },
285 :
286 : "call-to-arms": function(player, cmd, data)
287 : {
288 0 : const unitsToMove = data.entities.filter(ent =>
289 0 : MatchesClassList(Engine.QueryInterface(ent, IID_Identity).GetClassesList(),
290 : ["Soldier", "Warship", "Siege", "Healer"])
291 : );
292 0 : GetFormationUnitAIs(unitsToMove, player, cmd, data.formation).forEach(cmpUnitAI =>
293 : {
294 0 : if (cmd.pushFront)
295 : {
296 0 : cmpUnitAI.WalkAndFight(cmd.position.x, cmd.position.z, cmd.targetClasses, cmd.allowCapture, false, cmd.pushFront);
297 0 : cmpUnitAI.DropAtNearestDropSite(false, cmd.pushFront);
298 : }
299 : else
300 : {
301 0 : cmpUnitAI.DropAtNearestDropSite(cmd.queued, false);
302 0 : cmpUnitAI.WalkAndFight(cmd.position.x, cmd.position.z, cmd.targetClasses, cmd.allowCapture, true, false);
303 : }
304 : });
305 : },
306 :
307 : "remove-guard": function(player, cmd, data)
308 : {
309 0 : for (const ent of data.entities)
310 : {
311 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
312 0 : if (cmpUnitAI)
313 0 : cmpUnitAI.RemoveGuard();
314 : }
315 : },
316 :
317 : "train": function(player, cmd, data)
318 : {
319 0 : if (!Number.isInteger(cmd.count) || cmd.count <= 0)
320 : {
321 0 : warn("Invalid command: can't train " + uneval(cmd.count) + " units");
322 0 : return;
323 : }
324 :
325 : // Check entity limits
326 0 : var template = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager).GetTemplate(cmd.template);
327 0 : var unitCategory = null;
328 0 : if (template.TrainingRestrictions)
329 0 : unitCategory = template.TrainingRestrictions.Category;
330 :
331 : // Verify that the building(s) can be controlled by the player
332 0 : if (data.entities.length <= 0)
333 : {
334 0 : if (g_DebugCommands)
335 0 : warn("Invalid command: training building(s) cannot be controlled by player "+player+": "+uneval(cmd));
336 0 : return;
337 : }
338 :
339 0 : for (const ent of data.entities)
340 : {
341 0 : if (unitCategory)
342 : {
343 0 : var cmpPlayerEntityLimits = QueryOwnerInterface(ent, IID_EntityLimits);
344 0 : if (cmpPlayerEntityLimits && !cmpPlayerEntityLimits.AllowedToTrain(unitCategory, cmd.count, cmd.template, template.TrainingRestrictions.MatchLimit))
345 : {
346 0 : if (g_DebugCommands)
347 0 : warn(unitCategory + " train limit is reached: " + uneval(cmd));
348 0 : continue;
349 : }
350 : }
351 :
352 0 : var cmpTechnologyManager = QueryOwnerInterface(ent, IID_TechnologyManager);
353 0 : if (cmpTechnologyManager && !cmpTechnologyManager.CanProduce(cmd.template))
354 : {
355 0 : if (g_DebugCommands)
356 0 : warn("Invalid command: training requires unresearched technology: " + uneval(cmd));
357 0 : continue;
358 : }
359 :
360 0 : const cmpTrainer = Engine.QueryInterface(ent, IID_Trainer);
361 0 : if (!cmpTrainer)
362 0 : continue;
363 :
364 0 : let templateName = cmd.template;
365 : // Check if the building can train the unit
366 : // TODO: the AI API does not take promotion technologies into account for the list
367 : // of trainable units (taken directly from the unit template). Here is a temporary fix.
368 0 : if (data.cmpPlayer.IsAI())
369 0 : templateName = GetUpgradedTemplate(player, cmd.template);
370 :
371 0 : if (cmpTrainer.CanTrain(templateName))
372 0 : Engine.QueryInterface(ent, IID_ProductionQueue)?.AddItem(templateName, "unit", +cmd.count, cmd.metadata, cmd.pushFront);
373 : }
374 : },
375 :
376 : "research": function(player, cmd, data)
377 : {
378 0 : var cmpTechnologyManager = QueryOwnerInterface(cmd.entity, IID_TechnologyManager);
379 0 : if (cmpTechnologyManager && !cmpTechnologyManager.CanResearch(cmd.template))
380 : {
381 0 : if (g_DebugCommands)
382 0 : warn("Invalid command: Requirements to research technology are not met: " + uneval(cmd));
383 0 : return;
384 : }
385 :
386 0 : var queue = Engine.QueryInterface(cmd.entity, IID_ProductionQueue);
387 0 : if (queue)
388 0 : queue.AddItem(cmd.template, "technology", undefined, cmd.metadata, cmd.pushFront);
389 : },
390 :
391 : "stop-production": function(player, cmd, data)
392 : {
393 0 : const cmpProductionQueue = Engine.QueryInterface(cmd.entity, IID_ProductionQueue);
394 0 : if (cmpProductionQueue)
395 0 : cmpProductionQueue.RemoveItem(cmd.id);
396 : },
397 :
398 : "construct": function(player, cmd, data)
399 : {
400 0 : TryConstructBuilding(player, data.cmpPlayer, data.controlAllUnits, cmd);
401 : },
402 :
403 : "construct-wall": function(player, cmd, data)
404 : {
405 0 : TryConstructWall(player, data.cmpPlayer, data.controlAllUnits, cmd);
406 : },
407 :
408 : "delete-entities": function(player, cmd, data)
409 : {
410 0 : for (const ent of data.entities)
411 : {
412 0 : if (!data.controlAllUnits)
413 : {
414 0 : const cmpIdentity = Engine.QueryInterface(ent, IID_Identity);
415 0 : if (cmpIdentity && cmpIdentity.IsUndeletable())
416 0 : continue;
417 :
418 0 : const cmpCapturable = QueryMiragedInterface(ent, IID_Capturable);
419 0 : if (cmpCapturable &&
420 : cmpCapturable.GetCapturePoints()[player] < cmpCapturable.GetMaxCapturePoints() / 2)
421 0 : continue;
422 :
423 0 : const cmpResourceSupply = QueryMiragedInterface(ent, IID_ResourceSupply);
424 0 : if (cmpResourceSupply && cmpResourceSupply.GetKillBeforeGather())
425 0 : continue;
426 : }
427 :
428 0 : const cmpMirage = Engine.QueryInterface(ent, IID_Mirage);
429 0 : if (cmpMirage)
430 : {
431 0 : const cmpMiragedHealth = Engine.QueryInterface(cmpMirage.parent, IID_Health);
432 0 : if (cmpMiragedHealth)
433 0 : cmpMiragedHealth.Kill();
434 : else
435 0 : Engine.DestroyEntity(cmpMirage.parent);
436 :
437 0 : Engine.DestroyEntity(ent);
438 0 : continue;
439 : }
440 :
441 0 : const cmpHealth = Engine.QueryInterface(ent, IID_Health);
442 0 : if (cmpHealth)
443 0 : cmpHealth.Kill();
444 : else
445 0 : Engine.DestroyEntity(ent);
446 : }
447 : },
448 :
449 : "focus-fire": function(player, cmd, data)
450 : {
451 0 : for (const ent of data.entities)
452 : {
453 0 : Engine.QueryInterface(ent, IID_BuildingAI)?.AddFocusTarget(cmd.target, cmd.queued, cmd.pushFront);
454 : }
455 : },
456 :
457 : "set-rallypoint": function(player, cmd, data)
458 : {
459 0 : const structures = FilterEntityListWithAllies(cmd.structures || [], player, data.controlAllUnits);
460 0 : for (const structure of structures)
461 : {
462 0 : const cmpRallyPoint = Engine.QueryInterface(structure, IID_RallyPoint);
463 0 : if (!cmpRallyPoint)
464 0 : continue;
465 :
466 0 : if (!cmd.queued)
467 0 : cmpRallyPoint.Unset(player);
468 :
469 0 : cmpRallyPoint.AddPosition(cmd.x, cmd.z, player);
470 0 : cmpRallyPoint.AddData(clone(cmd.data), player);
471 : }
472 : },
473 :
474 : "unset-rallypoint": function(player, cmd, data)
475 : {
476 0 : const structures = FilterEntityListWithAllies(cmd.structures || [], player, data.controlAllUnits);
477 0 : for (const structure of structures)
478 : {
479 0 : const cmpRallyPoint = Engine.QueryInterface(structure, IID_RallyPoint);
480 0 : if (!cmpRallyPoint)
481 0 : continue;
482 :
483 0 : cmpRallyPoint.Unset(player);
484 : }
485 : },
486 :
487 : "resign": function(player, cmd, data)
488 : {
489 0 : data.cmpPlayer.Defeat(markForTranslation("%(player)s has resigned."));
490 : },
491 :
492 : "occupy-turret": function(player, cmd, data)
493 : {
494 0 : GetFormationUnitAIs(data.entities, player).forEach(cmpUnitAI =>
495 : {
496 0 : cmpUnitAI.OccupyTurret(cmd.target, cmd.queued);
497 : });
498 : },
499 :
500 : "garrison": function(player, cmd, data)
501 : {
502 0 : if (!CanPlayerOrAllyControlUnit(cmd.target, player, data.controlAllUnits))
503 : {
504 0 : if (g_DebugCommands)
505 0 : warn("Invalid command: garrison target cannot be controlled by player "+player+" (or ally): "+uneval(cmd));
506 0 : return;
507 : }
508 :
509 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
510 : {
511 0 : cmpUnitAI.Garrison(cmd.target, cmd.queued, cmd.pushFront);
512 : });
513 : },
514 :
515 : "guard": function(player, cmd, data)
516 : {
517 0 : if (!IsOwnedByPlayerOrMutualAlly(cmd.target, player, data.controlAllUnits))
518 : {
519 0 : if (g_DebugCommands)
520 0 : warn("Invalid command: Guard/escort target is not owned by player " + player + " or ally thereof: " + uneval(cmd));
521 0 : return;
522 : }
523 :
524 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
525 : {
526 0 : cmpUnitAI.Guard(cmd.target, cmd.queued, cmd.pushFront);
527 : });
528 : },
529 :
530 : "stop": function(player, cmd, data)
531 : {
532 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
533 : {
534 0 : cmpUnitAI.Stop(cmd.queued);
535 : });
536 : },
537 :
538 : "leave-turret": function(player, cmd, data)
539 : {
540 0 : let notUnloaded = 0;
541 0 : for (const ent of data.entities)
542 : {
543 0 : const cmpTurretable = Engine.QueryInterface(ent, IID_Turretable);
544 0 : if (!cmpTurretable || !cmpTurretable.LeaveTurret())
545 0 : ++notUnloaded;
546 : }
547 :
548 0 : if (notUnloaded)
549 0 : notifyUnloadFailure(player);
550 : },
551 :
552 : "unload-turrets": function(player, cmd, data)
553 : {
554 0 : let notUnloaded = 0;
555 0 : for (const ent of data.entities)
556 : {
557 0 : const cmpTurretHolder = Engine.QueryInterface(ent, IID_TurretHolder);
558 0 : for (const turret of cmpTurretHolder.GetEntities())
559 : {
560 0 : const cmpTurretable = Engine.QueryInterface(turret, IID_Turretable);
561 0 : if (!cmpTurretable || !cmpTurretable.LeaveTurret())
562 0 : ++notUnloaded;
563 : }
564 : }
565 :
566 0 : if (notUnloaded)
567 0 : notifyUnloadFailure(player);
568 : },
569 :
570 : "unload": function(player, cmd, data)
571 : {
572 0 : if (!CanPlayerOrAllyControlUnit(cmd.garrisonHolder, player, data.controlAllUnits))
573 : {
574 0 : if (g_DebugCommands)
575 0 : warn("Invalid command: unload target cannot be controlled by player "+player+" (or ally): "+uneval(cmd));
576 0 : return;
577 : }
578 :
579 0 : var cmpGarrisonHolder = Engine.QueryInterface(cmd.garrisonHolder, IID_GarrisonHolder);
580 0 : var notUngarrisoned = 0;
581 :
582 : // The owner can ungarrison every garrisoned unit
583 0 : if (IsOwnedByPlayer(player, cmd.garrisonHolder))
584 0 : data.entities = cmd.entities;
585 :
586 0 : for (const ent of data.entities)
587 0 : if (!cmpGarrisonHolder || !cmpGarrisonHolder.Unload(ent))
588 0 : ++notUngarrisoned;
589 :
590 0 : if (notUngarrisoned != 0)
591 0 : notifyUnloadFailure(player, cmd.garrisonHolder);
592 : },
593 :
594 : "unload-template": function(player, cmd, data)
595 : {
596 0 : var entities = FilterEntityListWithAllies(cmd.garrisonHolders, player, data.controlAllUnits);
597 0 : for (const garrisonHolder of entities)
598 : {
599 0 : var cmpGarrisonHolder = Engine.QueryInterface(garrisonHolder, IID_GarrisonHolder);
600 0 : if (cmpGarrisonHolder)
601 : {
602 : // Only the owner of the garrisonHolder may unload entities from any owners
603 0 : if (!IsOwnedByPlayer(player, garrisonHolder) && !data.controlAllUnits &&
604 : player != +cmd.owner)
605 0 : continue;
606 :
607 0 : if (!cmpGarrisonHolder.UnloadTemplate(cmd.template, cmd.owner, cmd.all))
608 0 : notifyUnloadFailure(player, garrisonHolder);
609 : }
610 : }
611 : },
612 :
613 : "unload-all-by-owner": function(player, cmd, data)
614 : {
615 0 : var entities = FilterEntityListWithAllies(cmd.garrisonHolders, player, data.controlAllUnits);
616 0 : for (const garrisonHolder of entities)
617 : {
618 0 : var cmpGarrisonHolder = Engine.QueryInterface(garrisonHolder, IID_GarrisonHolder);
619 0 : if (!cmpGarrisonHolder || !cmpGarrisonHolder.UnloadAllByOwner(player))
620 0 : notifyUnloadFailure(player, garrisonHolder);
621 : }
622 : },
623 :
624 : "unload-all": function(player, cmd, data)
625 : {
626 0 : var entities = FilterEntityList(cmd.garrisonHolders, player, data.controlAllUnits);
627 0 : for (const garrisonHolder of entities)
628 : {
629 0 : var cmpGarrisonHolder = Engine.QueryInterface(garrisonHolder, IID_GarrisonHolder);
630 0 : if (!cmpGarrisonHolder || !cmpGarrisonHolder.UnloadAll())
631 0 : notifyUnloadFailure(player, garrisonHolder);
632 : }
633 : },
634 :
635 : "alert-raise": function(player, cmd, data)
636 : {
637 0 : for (const ent of data.entities)
638 : {
639 0 : var cmpAlertRaiser = Engine.QueryInterface(ent, IID_AlertRaiser);
640 0 : if (cmpAlertRaiser)
641 0 : cmpAlertRaiser.RaiseAlert();
642 : }
643 : },
644 :
645 : "alert-end": function(player, cmd, data)
646 : {
647 0 : for (const ent of data.entities)
648 : {
649 0 : var cmpAlertRaiser = Engine.QueryInterface(ent, IID_AlertRaiser);
650 0 : if (cmpAlertRaiser)
651 0 : cmpAlertRaiser.EndOfAlert();
652 : }
653 : },
654 :
655 : "formation": function(player, cmd, data)
656 : {
657 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation, true).forEach(cmpUnitAI =>
658 : {
659 0 : cmpUnitAI.MoveIntoFormation(cmd);
660 : });
661 : },
662 :
663 : "promote": function(player, cmd, data)
664 : {
665 0 : if (!InitAttributes.settings.CheatsEnabled)
666 0 : return;
667 :
668 0 : var cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
669 0 : cmpGuiInterface.PushNotification({
670 : "type": "aichat",
671 : "players": [player],
672 : "message": markForTranslation("(Cheat - promoted units)"),
673 : "translateMessage": true
674 : });
675 :
676 0 : for (const ent of cmd.entities)
677 : {
678 0 : var cmpPromotion = Engine.QueryInterface(ent, IID_Promotion);
679 0 : if (cmpPromotion)
680 0 : cmpPromotion.IncreaseXp(cmpPromotion.GetRequiredXp() - cmpPromotion.GetCurrentXp());
681 : }
682 : },
683 :
684 : "stance": function(player, cmd, data)
685 : {
686 0 : for (const ent of data.entities)
687 : {
688 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
689 0 : if (cmpUnitAI && !cmpUnitAI.IsTurret())
690 0 : cmpUnitAI.SwitchToStance(cmd.name);
691 : }
692 : },
693 :
694 : "lock-gate": function(player, cmd, data)
695 : {
696 0 : for (const ent of data.entities)
697 : {
698 0 : var cmpGate = Engine.QueryInterface(ent, IID_Gate);
699 0 : if (!cmpGate)
700 0 : continue;
701 :
702 0 : if (cmd.lock)
703 0 : cmpGate.LockGate();
704 : else
705 0 : cmpGate.UnlockGate();
706 : }
707 : },
708 :
709 : "setup-trade-route": function(player, cmd, data)
710 : {
711 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
712 : {
713 0 : cmpUnitAI.SetupTradeRoute(cmd.target, cmd.source, cmd.route, cmd.queued);
714 : });
715 : },
716 :
717 : "cancel-setup-trade-route": function(player, cmd, data)
718 : {
719 0 : GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI =>
720 : {
721 0 : cmpUnitAI.CancelSetupTradeRoute(cmd.target);
722 : });
723 : },
724 :
725 : "set-trading-goods": function(player, cmd, data)
726 : {
727 0 : data.cmpPlayer.SetTradingGoods(cmd.tradingGoods);
728 : },
729 :
730 : "barter": function(player, cmd, data)
731 : {
732 0 : var cmpBarter = Engine.QueryInterface(SYSTEM_ENTITY, IID_Barter);
733 0 : cmpBarter.ExchangeResources(player, cmd.sell, cmd.buy, cmd.amount);
734 : },
735 :
736 : "set-shading-color": function(player, cmd, data)
737 : {
738 : // Prevent multiplayer abuse
739 0 : if (!data.cmpPlayer.IsAI())
740 0 : return;
741 :
742 : // Debug command to make an entity brightly colored
743 0 : for (const ent of cmd.entities)
744 : {
745 0 : var cmpVisual = Engine.QueryInterface(ent, IID_Visual);
746 0 : if (cmpVisual)
747 0 : cmpVisual.SetShadingColor(cmd.rgb[0], cmd.rgb[1], cmd.rgb[2], 0); // alpha isn't used so just send 0
748 : }
749 : },
750 :
751 : "pack": function(player, cmd, data)
752 : {
753 0 : for (const ent of data.entities)
754 : {
755 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
756 0 : if (!cmpUnitAI)
757 0 : continue;
758 :
759 0 : if (cmd.pack)
760 0 : cmpUnitAI.Pack(cmd.queued, cmd.pushFront);
761 : else
762 0 : cmpUnitAI.Unpack(cmd.queued, cmd.pushFront);
763 : }
764 : },
765 :
766 : "cancel-pack": function(player, cmd, data)
767 : {
768 0 : for (const ent of data.entities)
769 : {
770 0 : var cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
771 0 : if (!cmpUnitAI)
772 0 : continue;
773 :
774 0 : if (cmd.pack)
775 0 : cmpUnitAI.CancelPack(cmd.queued, cmd.pushFront);
776 : else
777 0 : cmpUnitAI.CancelUnpack(cmd.queued, cmd.pushFront);
778 : }
779 : },
780 :
781 : "upgrade": function(player, cmd, data)
782 : {
783 0 : for (const ent of data.entities)
784 : {
785 0 : var cmpUpgrade = Engine.QueryInterface(ent, IID_Upgrade);
786 :
787 0 : if (!cmpUpgrade || !cmpUpgrade.CanUpgradeTo(cmd.template))
788 0 : continue;
789 :
790 0 : if (cmpUpgrade.WillCheckPlacementRestrictions(cmd.template) && ObstructionsBlockingTemplateChange(ent, cmd.template))
791 : {
792 0 : var cmpGUIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
793 0 : cmpGUIInterface.PushNotification({
794 : "players": [player],
795 : "message": markForTranslation("Cannot upgrade as distance requirements are not verified or terrain is obstructed.")
796 : });
797 0 : continue;
798 : }
799 :
800 : // Check entity limits
801 0 : var cmpEntityLimits = QueryPlayerIDInterface(player, IID_EntityLimits);
802 0 : if (cmpEntityLimits && !cmpEntityLimits.AllowedToReplace(ent, cmd.template))
803 : {
804 0 : if (g_DebugCommands)
805 0 : warn("Invalid command: build limits check failed for player " + player + ": " + uneval(cmd));
806 0 : continue;
807 : }
808 :
809 0 : if (!RequirementsHelper.AreRequirementsMet(cmpUpgrade.GetRequirements(cmd.template), player))
810 : {
811 0 : if (g_DebugCommands)
812 0 : warn("Invalid command: upgrading is not possible for this player or requires unresearched technology: " + uneval(cmd));
813 0 : continue;
814 : }
815 :
816 0 : cmpUpgrade.Upgrade(cmd.template, data.cmpPlayer);
817 : }
818 : },
819 :
820 : "cancel-upgrade": function(player, cmd, data)
821 : {
822 0 : for (const ent of data.entities)
823 : {
824 0 : const cmpUpgrade = Engine.QueryInterface(ent, IID_Upgrade);
825 0 : if (cmpUpgrade)
826 0 : cmpUpgrade.CancelUpgrade(player);
827 : }
828 : },
829 :
830 : "attack-request": function(player, cmd, data)
831 : {
832 : // Send a chat message to human players
833 0 : var cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
834 0 : cmpGuiInterface.PushNotification({
835 : "type": "aichat",
836 : "players": [player],
837 : "message": "/allies " + markForTranslation("Attack against %(_player_)s requested."),
838 : "translateParameters": ["_player_"],
839 : "parameters": { "_player_": cmd.player }
840 : });
841 :
842 : // And send an attackRequest event to the AIs
843 0 : const cmpAIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_AIInterface);
844 0 : if (cmpAIInterface)
845 0 : cmpAIInterface.PushEvent("AttackRequest", cmd);
846 : },
847 :
848 : "spy-request": function(player, cmd, data)
849 : {
850 0 : const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
851 0 : const ent = pickRandom(cmpRangeManager.GetEntitiesByPlayer(cmd.player).filter(entity =>
852 : {
853 0 : const cmpVisionSharing = Engine.QueryInterface(entity, IID_VisionSharing);
854 0 : return cmpVisionSharing && cmpVisionSharing.IsBribable() && !cmpVisionSharing.ShareVisionWith(player);
855 : }));
856 :
857 0 : const cmpGUIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
858 0 : cmpGUIInterface.PushNotification({
859 : "type": "spy-response",
860 : "players": [player],
861 : "target": cmd.player,
862 : "entity": ent
863 : });
864 0 : if (ent)
865 0 : Engine.QueryInterface(ent, IID_VisionSharing).AddSpy(player);
866 : else
867 : {
868 0 : const template = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager).GetTemplate("special/spy");
869 0 : IncurBribeCost(template, player, cmd.player, true);
870 : // update statistics for failed bribes
871 0 : const cmpBribesStatisticsTracker = QueryPlayerIDInterface(player, IID_StatisticsTracker);
872 0 : if (cmpBribesStatisticsTracker)
873 0 : cmpBribesStatisticsTracker.IncreaseFailedBribesCounter();
874 0 : cmpGUIInterface.PushNotification({
875 : "type": "text",
876 : "players": [player],
877 : "message": markForTranslation("There are no bribable units"),
878 : "translateMessage": true
879 : });
880 : }
881 : },
882 :
883 : "diplomacy-request": function(player, cmd, data)
884 : {
885 0 : const cmpAIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_AIInterface);
886 0 : if (cmpAIInterface)
887 0 : cmpAIInterface.PushEvent("DiplomacyRequest", cmd);
888 : },
889 :
890 : "tribute-request": function(player, cmd, data)
891 : {
892 0 : const cmpAIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_AIInterface);
893 0 : if (cmpAIInterface)
894 0 : cmpAIInterface.PushEvent("TributeRequest", cmd);
895 : },
896 :
897 : "dialog-answer": function(player, cmd, data)
898 : {
899 : // Currently nothing. Triggers can read it anyway, and send this
900 : // message to any component you like.
901 : },
902 :
903 : "set-dropsite-sharing": function(player, cmd, data)
904 : {
905 0 : for (const ent of data.entities)
906 : {
907 0 : const cmpResourceDropsite = Engine.QueryInterface(ent, IID_ResourceDropsite);
908 0 : if (cmpResourceDropsite && cmpResourceDropsite.IsSharable())
909 0 : cmpResourceDropsite.SetSharing(cmd.shared);
910 : }
911 : },
912 :
913 : "autoqueue-on": function(player, cmd, data)
914 : {
915 0 : for (const ent of data.entities)
916 : {
917 0 : const cmpProductionQueue = Engine.QueryInterface(ent, IID_ProductionQueue);
918 0 : if (cmpProductionQueue)
919 0 : cmpProductionQueue.EnableAutoQueue();
920 : }
921 : },
922 :
923 : "autoqueue-off": function(player, cmd, data)
924 : {
925 0 : for (const ent of data.entities)
926 : {
927 0 : const cmpProductionQueue = Engine.QueryInterface(ent, IID_ProductionQueue);
928 0 : if (cmpProductionQueue)
929 0 : cmpProductionQueue.DisableAutoQueue();
930 : }
931 : },
932 :
933 : };
934 :
935 : function ProcessCommand(player, cmd)
936 : {
937 0 : const cmpPlayer = QueryPlayerIDInterface(player);
938 0 : if (!cmpPlayer)
939 0 : return;
940 :
941 0 : const data = {
942 : "cmpPlayer": cmpPlayer,
943 : "controlAllUnits": cmpPlayer.CanControlAllUnits()
944 : };
945 :
946 0 : if (cmd.entities)
947 0 : data.entities = FilterEntityList(cmd.entities, player, data.controlAllUnits);
948 :
949 : // TODO: queuing order and forcing formations doesn't really work.
950 : // To play nice, we'll still no-formation queued order if units are in formation
951 : // but the opposite perhaps ought to be implemented.
952 0 : if (!cmd.queued || cmd.formation == NULL_FORMATION)
953 0 : data.formation = cmd.formation || undefined;
954 :
955 : // Allow focusing the camera on recent commands
956 0 : const commandData = {
957 : "type": "playercommand",
958 : "players": [player],
959 : "cmd": cmd
960 : };
961 :
962 : // Save the position, since the GUI event is received after the unit died
963 0 : if (cmd.type == "delete-entities")
964 : {
965 0 : const cmpPosition = cmd.entities[0] && Engine.QueryInterface(cmd.entities[0], IID_Position);
966 0 : commandData.position = cmpPosition && cmpPosition.IsInWorld() && cmpPosition.GetPosition2D();
967 : }
968 :
969 0 : const cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
970 0 : cmpGuiInterface.PushNotification(commandData);
971 :
972 : // Note: checks of UnitAI targets are not robust enough here, as ownership
973 : // can change after the order is issued, they should be checked by UnitAI
974 : // when the specific behavior (e.g. attack, garrison) is performed.
975 : // (Also it's not ideal if a command silently fails, it's nicer if UnitAI
976 : // moves the entities closer to the target before giving up.)
977 :
978 : // Now handle various commands
979 0 : if (g_Commands[cmd.type])
980 : {
981 0 : var cmpTrigger = Engine.QueryInterface(SYSTEM_ENTITY, IID_Trigger);
982 0 : cmpTrigger.CallEvent("OnPlayerCommand", { "player": player, "cmd": cmd });
983 0 : g_Commands[cmd.type](player, cmd, data);
984 : }
985 : else
986 0 : error("Invalid command: unknown command type: "+uneval(cmd));
987 : }
988 :
989 : /**
990 : * Sends a GUI notification about unit(s) that failed to ungarrison.
991 : */
992 : function notifyUnloadFailure(player)
993 : {
994 0 : const cmpGUIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
995 0 : cmpGUIInterface.PushNotification({
996 : "type": "text",
997 : "players": [player],
998 : "message": markForTranslation("Unable to unload unit(s)."),
999 : "translateMessage": true
1000 : });
1001 : }
1002 :
1003 : /**
1004 : * Sends a GUI notification about worker(s) that failed to go back to work.
1005 : */
1006 : function notifyBackToWorkFailure(player)
1007 : {
1008 0 : var cmpGUIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
1009 0 : cmpGUIInterface.PushNotification({
1010 : "type": "text",
1011 : "players": [player],
1012 : "message": markForTranslation("Some unit(s) can't go back to work"),
1013 : "translateMessage": true
1014 : });
1015 : }
1016 :
1017 : /**
1018 : * Sends a GUI notification about entities that can't be controlled.
1019 : * @param {number} player - The player-ID of the player that needs to receive this message.
1020 : */
1021 : function notifyOrderFailure(entity, player)
1022 : {
1023 0 : const cmpIdentity = Engine.QueryInterface(entity, IID_Identity);
1024 0 : if (!cmpIdentity)
1025 0 : return;
1026 :
1027 0 : const cmpGUIInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
1028 0 : cmpGUIInterface.PushNotification({
1029 : "type": "text",
1030 : "players": [player],
1031 : "message": markForTranslation("%(unit)s can't be controlled."),
1032 : "parameters": { "unit": cmpIdentity.GetGenericName() },
1033 : "translateParameters": ["unit"],
1034 : "translateMessage": true
1035 : });
1036 : }
1037 :
1038 : /**
1039 : * Get some information about the formations used by entities.
1040 : */
1041 : function ExtractFormations(ents)
1042 : {
1043 0 : const entities = []; // Entities with UnitAI.
1044 0 : const members = {}; // { formationentity: [ent, ent, ...], ... }
1045 0 : const templates = {}; // { formationentity: template }
1046 0 : for (const ent of ents)
1047 : {
1048 0 : const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
1049 0 : if (!cmpUnitAI)
1050 0 : continue;
1051 :
1052 0 : entities.push(ent);
1053 :
1054 0 : const fid = cmpUnitAI.GetFormationController();
1055 0 : if (fid == INVALID_ENTITY)
1056 0 : continue;
1057 :
1058 0 : if (!members[fid])
1059 : {
1060 0 : members[fid] = [];
1061 0 : templates[fid] = cmpUnitAI.GetFormationTemplate();
1062 : }
1063 0 : members[fid].push(ent);
1064 : }
1065 :
1066 0 : return {
1067 : "entities": entities,
1068 : "members": members,
1069 : "templates": templates
1070 : };
1071 : }
1072 :
1073 : /**
1074 : * Tries to find the best angle to put a dock at a given position
1075 : * Taken from GuiInterface.js
1076 : */
1077 : function GetDockAngle(template, x, z)
1078 : {
1079 0 : var cmpTerrain = Engine.QueryInterface(SYSTEM_ENTITY, IID_Terrain);
1080 0 : var cmpWaterManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_WaterManager);
1081 0 : if (!cmpTerrain || !cmpWaterManager)
1082 0 : return undefined;
1083 :
1084 : // Get footprint size
1085 0 : var halfSize = 0;
1086 0 : if (template.Footprint.Square)
1087 0 : halfSize = Math.max(template.Footprint.Square["@depth"], template.Footprint.Square["@width"])/2;
1088 0 : else if (template.Footprint.Circle)
1089 0 : halfSize = template.Footprint.Circle["@radius"];
1090 :
1091 : /* Find direction of most open water, algorithm:
1092 : * 1. Pick points in a circle around dock
1093 : * 2. If point is in water, add to array
1094 : * 3. Scan array looking for consecutive points
1095 : * 4. Find longest sequence of consecutive points
1096 : * 5. If sequence equals all points, no direction can be determined,
1097 : * expand search outward and try (1) again
1098 : * 6. Calculate angle using average of sequence
1099 : */
1100 0 : const numPoints = 16;
1101 0 : for (let dist = 0; dist < 4; ++dist)
1102 : {
1103 0 : var waterPoints = [];
1104 0 : for (let i = 0; i < numPoints; ++i)
1105 : {
1106 0 : var angle = (i/numPoints)*2*Math.PI;
1107 0 : var d = halfSize*(dist+1);
1108 0 : var nx = x - d*Math.sin(angle);
1109 0 : var nz = z + d*Math.cos(angle);
1110 :
1111 0 : if (cmpTerrain.GetGroundLevel(nx, nz) < cmpWaterManager.GetWaterLevel(nx, nz))
1112 0 : waterPoints.push(i);
1113 : }
1114 0 : var consec = [];
1115 0 : var length = waterPoints.length;
1116 0 : if (!length)
1117 0 : continue;
1118 0 : for (let i = 0; i < length; ++i)
1119 : {
1120 0 : let count = 0;
1121 0 : for (let j = 0; j < length - 1; ++j)
1122 : {
1123 0 : if ((waterPoints[(i + j) % length] + 1) % numPoints == waterPoints[(i + j + 1) % length])
1124 0 : ++count;
1125 : else
1126 0 : break;
1127 : }
1128 0 : consec[i] = count;
1129 : }
1130 0 : let start = 0;
1131 0 : let count = 0;
1132 0 : for (const c in consec)
1133 : {
1134 0 : if (consec[c] > count)
1135 : {
1136 0 : start = c;
1137 0 : count = consec[c];
1138 : }
1139 : }
1140 :
1141 : // If we've found a shoreline, stop searching
1142 0 : if (count != numPoints-1)
1143 0 : return -((waterPoints[start] + consec[start]/2) % numPoints) / numPoints * 2 * Math.PI;
1144 : }
1145 0 : return undefined;
1146 : }
1147 :
1148 : /**
1149 : * Attempts to construct a building using the specified parameters.
1150 : * Returns true on success, false on failure.
1151 : */
1152 : function TryConstructBuilding(player, cmpPlayer, controlAllUnits, cmd)
1153 : {
1154 : // Message structure:
1155 : // {
1156 : // "type": "construct",
1157 : // "entities": [...], // entities that will be ordered to construct the building (if applicable)
1158 : // "template": "...", // template name of the entity being constructed
1159 : // "x": ...,
1160 : // "z": ...,
1161 : // "angle": ...,
1162 : // "metadata": "...", // AI metadata of the building
1163 : // "actorSeed": ...,
1164 : // "autorepair": true, // whether to automatically start constructing/repairing the new foundation
1165 : // "autocontinue": true, // whether to automatically gather/build/etc after finishing this
1166 : // "queued": true, // whether to add the construction/repairing of this foundation to entities' queue (if applicable)
1167 : // "obstructionControlGroup": ..., // Optional; the obstruction control group ID that should be set for this building prior to obstruction
1168 : // // testing to determine placement validity. If specified, must be a valid control group ID (> 0).
1169 : // "obstructionControlGroup2": ..., // Optional; secondary obstruction control group ID that should be set for this building prior to obstruction
1170 : // // testing to determine placement validity. May be INVALID_ENTITY.
1171 : // }
1172 :
1173 : /*
1174 : * Construction process:
1175 : * . Take resources away immediately.
1176 : * . Create a foundation entity with 1hp, 0% build progress.
1177 : * . Increase hp and build progress up to 100% when people work on it.
1178 : * . If it's destroyed, an appropriate fraction of the resource cost is refunded.
1179 : * . If it's completed, it gets replaced with the real building.
1180 : */
1181 :
1182 : // Check whether we can control these units
1183 0 : var entities = FilterEntityList(cmd.entities, player, controlAllUnits);
1184 0 : if (!entities.length)
1185 0 : return false;
1186 :
1187 0 : var foundationTemplate = "foundation|" + cmd.template;
1188 :
1189 : // Tentatively create the foundation (we might find later that it's a invalid build command)
1190 0 : var ent = Engine.AddEntity(foundationTemplate);
1191 0 : if (ent == INVALID_ENTITY)
1192 : {
1193 : // Error (e.g. invalid template names)
1194 0 : error("Error creating foundation entity for '" + cmd.template + "'");
1195 0 : return false;
1196 : }
1197 :
1198 : // If it's a dock, get the right angle.
1199 0 : var template = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager).GetTemplate(cmd.template);
1200 0 : var angle = cmd.angle;
1201 0 : if (template.BuildRestrictions.PlacementType === "shore")
1202 : {
1203 0 : const angleDock = GetDockAngle(template, cmd.x, cmd.z);
1204 0 : if (angleDock !== undefined)
1205 0 : angle = angleDock;
1206 : }
1207 :
1208 : // Move the foundation to the right place
1209 0 : var cmpPosition = Engine.QueryInterface(ent, IID_Position);
1210 0 : cmpPosition.JumpTo(cmd.x, cmd.z);
1211 0 : cmpPosition.SetYRotation(angle);
1212 :
1213 : // Set the obstruction control group if needed
1214 0 : if (cmd.obstructionControlGroup || cmd.obstructionControlGroup2)
1215 : {
1216 0 : var cmpObstruction = Engine.QueryInterface(ent, IID_Obstruction);
1217 :
1218 : // primary control group must always be valid
1219 0 : if (cmd.obstructionControlGroup)
1220 : {
1221 0 : if (cmd.obstructionControlGroup <= 0)
1222 0 : warn("[TryConstructBuilding] Invalid primary obstruction control group " + cmd.obstructionControlGroup + " received; must be > 0");
1223 :
1224 0 : cmpObstruction.SetControlGroup(cmd.obstructionControlGroup);
1225 : }
1226 :
1227 0 : if (cmd.obstructionControlGroup2)
1228 0 : cmpObstruction.SetControlGroup2(cmd.obstructionControlGroup2);
1229 : }
1230 :
1231 : // Make it owned by the current player
1232 0 : var cmpOwnership = Engine.QueryInterface(ent, IID_Ownership);
1233 0 : cmpOwnership.SetOwner(player);
1234 :
1235 : // Check whether building placement is valid
1236 0 : var cmpBuildRestrictions = Engine.QueryInterface(ent, IID_BuildRestrictions);
1237 0 : if (cmpBuildRestrictions)
1238 : {
1239 0 : var ret = cmpBuildRestrictions.CheckPlacement();
1240 0 : if (!ret.success)
1241 : {
1242 0 : if (g_DebugCommands)
1243 0 : warn("Invalid command: build restrictions check failed with '"+ret.message+"' for player "+player+": "+uneval(cmd));
1244 :
1245 0 : const cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
1246 0 : ret.players = [player];
1247 0 : cmpGuiInterface.PushNotification(ret);
1248 :
1249 : // Remove the foundation because the construction was aborted
1250 : // move it out of world because it's not destroyed immediately.
1251 0 : cmpPosition.MoveOutOfWorld();
1252 0 : Engine.DestroyEntity(ent);
1253 0 : return false;
1254 : }
1255 : }
1256 : else
1257 0 : error("cmpBuildRestrictions not defined");
1258 :
1259 : // Check entity limits
1260 0 : var cmpEntityLimits = QueryPlayerIDInterface(player, IID_EntityLimits);
1261 0 : if (cmpEntityLimits && !cmpEntityLimits.AllowedToBuild(cmpBuildRestrictions.GetCategory()))
1262 : {
1263 0 : if (g_DebugCommands)
1264 0 : warn("Invalid command: build limits check failed for player "+player+": "+uneval(cmd));
1265 :
1266 : // Remove the foundation because the construction was aborted
1267 0 : cmpPosition.MoveOutOfWorld();
1268 0 : Engine.DestroyEntity(ent);
1269 0 : return false;
1270 : }
1271 :
1272 0 : var cmpTechnologyManager = QueryPlayerIDInterface(player, IID_TechnologyManager);
1273 0 : if (cmpTechnologyManager && !cmpTechnologyManager.CanProduce(cmd.template))
1274 : {
1275 0 : if (g_DebugCommands)
1276 0 : warn("Invalid command: required technology check failed for player "+player+": "+uneval(cmd));
1277 :
1278 0 : const cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
1279 0 : cmpGuiInterface.PushNotification({
1280 : "type": "text",
1281 : "players": [player],
1282 : "message": markForTranslation("The building's technology requirements are not met."),
1283 : "translateMessage": true
1284 : });
1285 :
1286 : // Remove the foundation because the construction was aborted
1287 0 : cmpPosition.MoveOutOfWorld();
1288 0 : Engine.DestroyEntity(ent);
1289 : }
1290 :
1291 : // We need the cost after tech and aura modifications.
1292 0 : const cmpCost = Engine.QueryInterface(ent, IID_Cost);
1293 0 : const costs = cmpCost.GetResourceCosts();
1294 :
1295 0 : if (!cmpPlayer.TrySubtractResources(costs))
1296 : {
1297 0 : if (g_DebugCommands)
1298 0 : warn("Invalid command: building cost check failed for player "+player+": "+uneval(cmd));
1299 :
1300 0 : Engine.DestroyEntity(ent);
1301 0 : cmpPosition.MoveOutOfWorld();
1302 0 : return false;
1303 : }
1304 :
1305 0 : var cmpVisual = Engine.QueryInterface(ent, IID_Visual);
1306 0 : if (cmpVisual && cmd.actorSeed !== undefined)
1307 0 : cmpVisual.SetActorSeed(cmd.actorSeed);
1308 :
1309 : // Initialise the foundation
1310 0 : var cmpFoundation = Engine.QueryInterface(ent, IID_Foundation);
1311 0 : cmpFoundation.InitialiseConstruction(cmd.template);
1312 :
1313 : // send Metadata info if any
1314 0 : if (cmd.metadata)
1315 0 : Engine.PostMessage(ent, MT_AIMetadata, { "id": ent, "metadata": cmd.metadata, "owner": player });
1316 :
1317 : // Tell the units to start building this new entity
1318 0 : if (cmd.autorepair)
1319 : {
1320 0 : ProcessCommand(player, {
1321 : "type": "repair",
1322 : "entities": entities,
1323 : "target": ent,
1324 : "autocontinue": cmd.autocontinue,
1325 : "queued": cmd.queued,
1326 : "pushFront": cmd.pushFront,
1327 : "formation": cmd.formation || undefined
1328 : });
1329 : }
1330 :
1331 0 : return ent;
1332 : }
1333 :
1334 : function TryConstructWall(player, cmpPlayer, controlAllUnits, cmd)
1335 : {
1336 : // 'cmd' message structure:
1337 : // {
1338 : // "type": "construct-wall",
1339 : // "entities": [...], // entities that will be ordered to construct the wall (if applicable)
1340 : // "pieces": [ // ordered list of information about the pieces making up the wall (towers, wall segments, ...)
1341 : // {
1342 : // "template": "...", // one of the templates from the wallset
1343 : // "x": ...,
1344 : // "z": ...,
1345 : // "angle": ...,
1346 : // },
1347 : // ...
1348 : // ],
1349 : // "wallSet": {
1350 : // "templates": {
1351 : // "tower": // tower template name
1352 : // "long": // long wall segment template name
1353 : // ... // etc.
1354 : // },
1355 : // "maxTowerOverlap": ...,
1356 : // "minTowerOverlap": ...,
1357 : // },
1358 : // "startSnappedEntity": // optional; entity ID of tower being snapped to at the starting side of the wall
1359 : // "endSnappedEntity": // optional; entity ID of tower being snapped to at the ending side of the wall
1360 : // "autorepair": true, // whether to automatically start constructing/repairing the new foundation
1361 : // "autocontinue": true, // whether to automatically gather/build/etc after finishing this
1362 : // "queued": true, // whether to add the construction/repairing of this wall's pieces to entities' queue (if applicable)
1363 : // }
1364 :
1365 0 : if (cmd.pieces.length <= 0)
1366 0 : return;
1367 :
1368 0 : if (cmd.startSnappedEntity && cmd.pieces[0].template == cmd.wallSet.templates.tower)
1369 : {
1370 0 : error("[TryConstructWall] Starting wall piece cannot be a tower (" + cmd.wallSet.templates.tower + ") when snapping at the starting side");
1371 0 : return;
1372 : }
1373 :
1374 0 : if (cmd.endSnappedEntity && cmd.pieces[cmd.pieces.length - 1].template == cmd.wallSet.templates.tower)
1375 : {
1376 0 : error("[TryConstructWall] Ending wall piece cannot be a tower (" + cmd.wallSet.templates.tower + ") when snapping at the ending side");
1377 0 : return;
1378 : }
1379 :
1380 : // Assign obstruction control groups to allow the wall pieces to mutually overlap during foundation placement
1381 : // and during construction. The scheme here is that whatever wall pieces are inbetween two towers inherit the control
1382 : // groups of both of the towers they are connected to (either newly constructed ones as part of the wall, or existing
1383 : // towers in the case of snapping). The towers themselves all keep their default unique control groups.
1384 :
1385 : // To support this, every non-tower piece registers the entity ID of the towers (or foundations thereof) that neighbour
1386 : // it on either side. Specifically, each non-tower wall piece has its primary control group set equal to that of the
1387 : // first tower encountered towards the starting side of the wall, and its secondary control group set equal to that of
1388 : // the first tower encountered towards the ending side of the wall (if any).
1389 :
1390 : // We can't build the whole wall at once by linearly stepping through the wall pieces and build them, because the
1391 : // wall segments may/will need the entity IDs of towers that come afterwards. So, build it in two passes:
1392 : //
1393 : // FIRST PASS:
1394 : // - Go from start to end and construct wall piece foundations as far as we can without running into a piece that
1395 : // cannot be built (e.g. because it is obstructed). At each non-tower, set the most recently built tower's ID
1396 : // as the primary control group, thus allowing it to be built overlapping the previous piece.
1397 : // - If we encounter a new tower along the way (which will gain its own control group), do the following:
1398 : // o First build it using temporarily the same control group of the previous (non-tower) piece
1399 : // o Set the previous piece's secondary control group to the tower's entity ID
1400 : // o Restore the primary control group of the constructed tower back its original (unique) value.
1401 : // The temporary control group is necessary to allow the newer tower with its unique control group ID to be able
1402 : // to be placed while overlapping the previous piece.
1403 : //
1404 : // SECOND PASS:
1405 : // - Go end to start from the last successfully placed wall piece (which might be a tower we backtracked to), this
1406 : // time registering the right neighbouring tower in each non-tower piece.
1407 :
1408 : // first pass; L -> R
1409 :
1410 0 : var lastTowerIndex = -1; // index of the last tower we've encountered in cmd.pieces
1411 0 : var lastTowerControlGroup = null; // control group of the last tower we've encountered, to assign to non-tower pieces
1412 :
1413 : // If we're snapping to an existing entity at the starting end, set lastTowerControlGroup to its control group ID so that
1414 : // the first wall piece can be built while overlapping it.
1415 0 : if (cmd.startSnappedEntity)
1416 : {
1417 0 : var cmpSnappedStartObstruction = Engine.QueryInterface(cmd.startSnappedEntity, IID_Obstruction);
1418 0 : if (!cmpSnappedStartObstruction)
1419 : {
1420 0 : error("[TryConstructWall] Snapped entity on starting side does not have an obstruction component");
1421 0 : return;
1422 : }
1423 :
1424 0 : lastTowerControlGroup = cmpSnappedStartObstruction.GetControlGroup();
1425 : // warn("setting lastTowerControlGroup to control group of start snapped entity " + cmd.startSnappedEntity + ": " + lastTowerControlGroup);
1426 : }
1427 :
1428 0 : var i = 0;
1429 0 : var queued = cmd.queued;
1430 0 : var pieces = clone(cmd.pieces);
1431 0 : for (; i < pieces.length; ++i)
1432 : {
1433 0 : const piece = pieces[i];
1434 :
1435 : // All wall pieces after the first must be queued.
1436 0 : if (i > 0 && !queued)
1437 0 : queued = true;
1438 :
1439 : // 'lastTowerControlGroup' must always be defined and valid here, except if we're at the first piece and we didn't do
1440 : // start position snapping (implying that the first entity we build must be a tower)
1441 0 : if (lastTowerControlGroup === null || lastTowerControlGroup == INVALID_ENTITY)
1442 : {
1443 0 : if (!(i == 0 && piece.template == cmd.wallSet.templates.tower && !cmd.startSnappedEntity))
1444 : {
1445 0 : error("[TryConstructWall] Expected last tower control group to be available, none found (1st pass, iteration " + i + ")");
1446 0 : break;
1447 : }
1448 : }
1449 :
1450 0 : var constructPieceCmd = {
1451 : "type": "construct",
1452 : "entities": cmd.entities,
1453 : "template": piece.template,
1454 : "x": piece.x,
1455 : "z": piece.z,
1456 : "angle": piece.angle,
1457 : "autorepair": cmd.autorepair,
1458 : "autocontinue": cmd.autocontinue,
1459 : "queued": queued,
1460 : // Regardless of whether we're building a tower or an intermediate wall piece, it is always (first) constructed
1461 : // using the control group of the last tower (see comments above).
1462 : "obstructionControlGroup": lastTowerControlGroup,
1463 : };
1464 :
1465 : // If we're building the last piece and we're attaching to a snapped entity, we need to add in the snapped entity's
1466 : // control group directly at construction time (instead of setting it in the second pass) to allow it to be built
1467 : // while overlapping the snapped entity.
1468 0 : if (i == pieces.length - 1 && cmd.endSnappedEntity)
1469 : {
1470 0 : var cmpEndSnappedObstruction = Engine.QueryInterface(cmd.endSnappedEntity, IID_Obstruction);
1471 0 : if (cmpEndSnappedObstruction)
1472 0 : constructPieceCmd.obstructionControlGroup2 = cmpEndSnappedObstruction.GetControlGroup();
1473 : }
1474 :
1475 0 : var pieceEntityId = TryConstructBuilding(player, cmpPlayer, controlAllUnits, constructPieceCmd);
1476 0 : if (pieceEntityId)
1477 : {
1478 : // wall piece foundation successfully built, save the entity ID in the piece info object so we can reference it later
1479 0 : piece.ent = pieceEntityId;
1480 :
1481 : // if we built a tower, do the control group dance (see outline above) and update lastTowerControlGroup and lastTowerIndex
1482 0 : if (piece.template == cmd.wallSet.templates.tower)
1483 : {
1484 0 : var cmpTowerObstruction = Engine.QueryInterface(pieceEntityId, IID_Obstruction);
1485 0 : var newTowerControlGroup = pieceEntityId;
1486 :
1487 0 : if (i > 0)
1488 : {
1489 : // warn(" updating previous wall piece's secondary control group to " + newTowerControlGroup);
1490 0 : var cmpPreviousObstruction = Engine.QueryInterface(pieces[i-1].ent, IID_Obstruction);
1491 : // TODO: ensure that cmpPreviousObstruction exists
1492 : // TODO: ensure that the previous obstruction does not yet have a secondary control group set
1493 0 : cmpPreviousObstruction.SetControlGroup2(newTowerControlGroup);
1494 : }
1495 :
1496 : // TODO: ensure that cmpTowerObstruction exists
1497 0 : cmpTowerObstruction.SetControlGroup(newTowerControlGroup); // give the tower its own unique control group
1498 :
1499 0 : lastTowerIndex = i;
1500 0 : lastTowerControlGroup = newTowerControlGroup;
1501 : }
1502 : }
1503 : else // failed to build wall piece, abort
1504 0 : break;
1505 : }
1506 :
1507 0 : var lastBuiltPieceIndex = i - 1;
1508 0 : var wallComplete = (lastBuiltPieceIndex == pieces.length - 1);
1509 :
1510 : // At this point, 'i' is the index of the last wall piece that was successfully constructed (which may or may not be a tower).
1511 : // Now do the second pass going right-to-left, registering the control groups of the towers to the right of each piece (if any)
1512 : // as their secondary control groups.
1513 :
1514 0 : lastTowerControlGroup = null; // control group of the last tower we've encountered, to assign to non-tower pieces
1515 :
1516 : // only start off with the ending side's snapped tower's control group if we were able to build the entire wall
1517 0 : if (cmd.endSnappedEntity && wallComplete)
1518 : {
1519 0 : var cmpSnappedEndObstruction = Engine.QueryInterface(cmd.endSnappedEntity, IID_Obstruction);
1520 0 : if (!cmpSnappedEndObstruction)
1521 : {
1522 0 : error("[TryConstructWall] Snapped entity on ending side does not have an obstruction component");
1523 0 : return;
1524 : }
1525 :
1526 0 : lastTowerControlGroup = cmpSnappedEndObstruction.GetControlGroup();
1527 : }
1528 :
1529 0 : for (let j = lastBuiltPieceIndex; j >= 0; --j)
1530 : {
1531 0 : const piece = pieces[j];
1532 :
1533 0 : if (!piece.ent)
1534 : {
1535 0 : error("[TryConstructWall] No entity ID set for constructed entity of template '" + piece.template + "'");
1536 0 : continue;
1537 : }
1538 :
1539 0 : var cmpPieceObstruction = Engine.QueryInterface(piece.ent, IID_Obstruction);
1540 0 : if (!cmpPieceObstruction)
1541 : {
1542 0 : error("[TryConstructWall] Wall piece of template '" + piece.template + "' has no Obstruction component");
1543 0 : continue;
1544 : }
1545 :
1546 0 : if (piece.template == cmd.wallSet.templates.tower)
1547 : {
1548 : // encountered a tower entity, update the last tower control group
1549 0 : lastTowerControlGroup = cmpPieceObstruction.GetControlGroup();
1550 : }
1551 : else
1552 : {
1553 : // Encountered a non-tower entity, update its secondary control group to 'lastTowerControlGroup'.
1554 : // Note that the wall piece may already have its secondary control group set to the tower's entity ID from a control group
1555 : // dance during the first pass, in which case we should validate it against 'lastTowerControlGroup'.
1556 :
1557 0 : var existingSecondaryControlGroup = cmpPieceObstruction.GetControlGroup2();
1558 0 : if (existingSecondaryControlGroup == INVALID_ENTITY)
1559 : {
1560 0 : if (lastTowerControlGroup != null && lastTowerControlGroup != INVALID_ENTITY)
1561 : {
1562 0 : cmpPieceObstruction.SetControlGroup2(lastTowerControlGroup);
1563 : }
1564 : }
1565 0 : else if (existingSecondaryControlGroup != lastTowerControlGroup)
1566 : {
1567 0 : error("[TryConstructWall] Existing secondary control group of non-tower entity does not match expected value (2nd pass, iteration " + j + ")");
1568 0 : break;
1569 : }
1570 : }
1571 : }
1572 : }
1573 :
1574 : /**
1575 : * Remove the given list of entities from their current formations.
1576 : */
1577 : function RemoveFromFormation(ents)
1578 : {
1579 0 : const formation = ExtractFormations(ents);
1580 0 : for (const fid in formation.members)
1581 : {
1582 0 : const cmpFormation = Engine.QueryInterface(+fid, IID_Formation);
1583 0 : if (cmpFormation)
1584 0 : cmpFormation.RemoveMembers(formation.members[fid]);
1585 : }
1586 : }
1587 :
1588 : /**
1589 : * Returns a list of UnitAI components, each belonging either to a
1590 : * selected unit or to a formation entity for groups of the selected units.
1591 : */
1592 : function GetFormationUnitAIs(ents, player, cmd, formationTemplate, forceTemplate)
1593 : {
1594 : // If an individual was selected, remove it from any formation
1595 : // and command it individually.
1596 0 : if (ents.length == 1)
1597 : {
1598 0 : const cmpUnitAI = Engine.QueryInterface(ents[0], IID_UnitAI);
1599 0 : if (!cmpUnitAI)
1600 0 : return [];
1601 :
1602 0 : RemoveFromFormation(ents);
1603 :
1604 0 : return [ cmpUnitAI ];
1605 : }
1606 :
1607 0 : let formationUnitAIs = [];
1608 : // Find what formations the selected entities are currently in,
1609 : // and default to that unless the formation is forced or it's the null formation
1610 : // (we want that to reset whatever formations units are in).
1611 0 : if (formationTemplate != NULL_FORMATION)
1612 : {
1613 0 : const formation = ExtractFormations(ents);
1614 0 : const formationIds = Object.keys(formation.members);
1615 0 : if (formationIds.length == 1)
1616 : {
1617 : // Selected units either belong to this formation or have no formation.
1618 0 : const fid = formationIds[0];
1619 0 : const cmpFormation = Engine.QueryInterface(+fid, IID_Formation);
1620 0 : if (cmpFormation && cmpFormation.GetMemberCount() == formation.members[fid].length &&
1621 : cmpFormation.GetMemberCount() == formation.entities.length)
1622 : {
1623 0 : cmpFormation.DeleteTwinFormations();
1624 :
1625 : // The whole formation was selected, so reuse its controller for this command.
1626 0 : if (!forceTemplate || formationTemplate == formation.templates[fid])
1627 : {
1628 0 : formationTemplate = formation.templates[fid];
1629 0 : formationUnitAIs = [Engine.QueryInterface(+fid, IID_UnitAI)];
1630 : }
1631 0 : else if (formationTemplate && CanMoveEntsIntoFormation(formation.entities, formationTemplate))
1632 0 : formationUnitAIs = [cmpFormation.LoadFormation(formationTemplate)];
1633 : }
1634 0 : else if (cmpFormation && !forceTemplate)
1635 : {
1636 : // Just reuse the template.
1637 0 : formationTemplate = formation.templates[fid];
1638 : }
1639 : }
1640 0 : else if (formationIds.length)
1641 : {
1642 : // Check if all entities share a common formation, if so reuse this template.
1643 0 : let template = formation.templates[formationIds[0]];
1644 0 : for (let i = 1; i < formationIds.length; ++i)
1645 0 : if (formation.templates[formationIds[i]] != template)
1646 : {
1647 0 : template = null;
1648 0 : break;
1649 : }
1650 0 : if (template && !forceTemplate)
1651 0 : formationTemplate = template;
1652 : }
1653 : }
1654 :
1655 : // Separate out the units that don't support the chosen formation.
1656 0 : const formedUnits = [];
1657 0 : const nonformedUnitAIs = [];
1658 0 : for (const ent of ents)
1659 : {
1660 0 : const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
1661 0 : const cmpPosition = Engine.QueryInterface(ent, IID_Position);
1662 0 : if (!cmpUnitAI || !cmpPosition || !cmpPosition.IsInWorld())
1663 0 : continue;
1664 :
1665 : // TODO: We only check if the formation is usable by some units
1666 : // if we move them to it. We should check if we can use formations
1667 : // for the other cases.
1668 0 : const nullFormation = (formationTemplate || cmpUnitAI.GetFormationTemplate()) == NULL_FORMATION;
1669 0 : if (nullFormation || !cmpUnitAI.CanUseFormation(formationTemplate || NULL_FORMATION))
1670 : {
1671 0 : if (nullFormation && cmpUnitAI.GetFormationController())
1672 0 : cmpUnitAI.LeaveFormation(cmd.queued || false);
1673 0 : nonformedUnitAIs.push(cmpUnitAI);
1674 : }
1675 : else
1676 0 : formedUnits.push(ent);
1677 : }
1678 0 : if (nonformedUnitAIs.length == ents.length)
1679 : {
1680 : // No units support the formation.
1681 0 : return nonformedUnitAIs;
1682 : }
1683 :
1684 0 : if (!formationUnitAIs.length)
1685 : {
1686 : // We need to give the selected units a new formation controller.
1687 :
1688 : // TODO replace the fixed 60 with something sensible, based on vision range f.e.
1689 0 : const formationSeparation = 60;
1690 0 : const clusters = ClusterEntities(formedUnits, formationSeparation);
1691 0 : const formationEnts = [];
1692 0 : for (const cluster of clusters)
1693 : {
1694 0 : RemoveFromFormation(cluster);
1695 :
1696 0 : if (!formationTemplate || !CanMoveEntsIntoFormation(cluster, formationTemplate))
1697 : {
1698 0 : for (const ent of cluster)
1699 0 : nonformedUnitAIs.push(Engine.QueryInterface(ent, IID_UnitAI));
1700 :
1701 0 : continue;
1702 : }
1703 :
1704 : // Create the new controller.
1705 0 : const formationEnt = Engine.AddEntity(formationTemplate);
1706 0 : const cmpFormation = Engine.QueryInterface(formationEnt, IID_Formation);
1707 0 : formationUnitAIs.push(Engine.QueryInterface(formationEnt, IID_UnitAI));
1708 0 : cmpFormation.SetFormationSeparation(formationSeparation);
1709 0 : cmpFormation.SetMembers(cluster);
1710 :
1711 0 : for (const ent of formationEnts)
1712 0 : cmpFormation.RegisterTwinFormation(ent);
1713 :
1714 0 : formationEnts.push(formationEnt);
1715 0 : const cmpOwnership = Engine.QueryInterface(formationEnt, IID_Ownership);
1716 0 : cmpOwnership.SetOwner(player);
1717 : }
1718 : }
1719 :
1720 0 : return nonformedUnitAIs.concat(formationUnitAIs);
1721 : }
1722 :
1723 : /**
1724 : * Group a list of entities in clusters via single-links
1725 : */
1726 : function ClusterEntities(ents, separationDistance)
1727 : {
1728 0 : const clusters = [];
1729 0 : if (!ents.length)
1730 0 : return clusters;
1731 :
1732 0 : const distSq = separationDistance * separationDistance;
1733 0 : const positions = [];
1734 : // triangular matrix with the (squared) distances between the different clusters
1735 : // the other half is not initialised
1736 0 : const matrix = [];
1737 0 : for (let i = 0; i < ents.length; ++i)
1738 : {
1739 0 : matrix[i] = [];
1740 0 : clusters.push([ents[i]]);
1741 0 : const cmpPosition = Engine.QueryInterface(ents[i], IID_Position);
1742 0 : positions.push(cmpPosition.GetPosition2D());
1743 0 : for (let j = 0; j < i; ++j)
1744 0 : matrix[i][j] = positions[i].distanceToSquared(positions[j]);
1745 : }
1746 0 : while (clusters.length > 1)
1747 : {
1748 : // search two clusters that are closer than the required distance
1749 : let closeClusters;
1750 :
1751 0 : for (let i = matrix.length - 1; i >= 0 && !closeClusters; --i)
1752 0 : for (let j = i - 1; j >= 0 && !closeClusters; --j)
1753 0 : if (matrix[i][j] < distSq)
1754 0 : closeClusters = [i, j];
1755 :
1756 : // if no more close clusters found, just return all found clusters so far
1757 0 : if (!closeClusters)
1758 0 : return clusters;
1759 :
1760 : // make a new cluster with the entities from the two found clusters
1761 0 : const newCluster = clusters[closeClusters[0]].concat(clusters[closeClusters[1]]);
1762 :
1763 : // calculate the minimum distance between the new cluster and all other remaining
1764 : // clusters by taking the minimum of the two distances.
1765 0 : const distances = [];
1766 0 : for (let i = 0; i < clusters.length; ++i)
1767 : {
1768 0 : const a = closeClusters[1];
1769 0 : const b = closeClusters[0];
1770 0 : if (i == a || i == b)
1771 0 : continue;
1772 0 : const dist1 = matrix[a][i] !== undefined ? matrix[a][i] : matrix[i][a];
1773 0 : const dist2 = matrix[b][i] !== undefined ? matrix[b][i] : matrix[i][b];
1774 0 : distances.push(Math.min(dist1, dist2));
1775 : }
1776 : // remove the rows and columns in the matrix for the merged clusters,
1777 : // and the clusters themselves from the cluster list
1778 0 : clusters.splice(closeClusters[0], 1);
1779 0 : clusters.splice(closeClusters[1], 1);
1780 0 : matrix.splice(closeClusters[0], 1);
1781 0 : matrix.splice(closeClusters[1], 1);
1782 0 : for (let i = 0; i < matrix.length; ++i)
1783 : {
1784 0 : if (matrix[i].length > closeClusters[0])
1785 0 : matrix[i].splice(closeClusters[0], 1);
1786 0 : if (matrix[i].length > closeClusters[1])
1787 0 : matrix[i].splice(closeClusters[1], 1);
1788 : }
1789 : // add a new row of distances to the matrix and the new cluster
1790 0 : clusters.push(newCluster);
1791 0 : matrix.push(distances);
1792 : }
1793 0 : return clusters;
1794 : }
1795 :
1796 : function GetFormationRequirements(formationTemplate)
1797 : {
1798 0 : var template = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager).GetTemplate(formationTemplate);
1799 0 : if (!template.Formation)
1800 0 : return false;
1801 :
1802 0 : return { "minCount": +template.Formation.RequiredMemberCount };
1803 : }
1804 :
1805 :
1806 : function CanMoveEntsIntoFormation(ents, formationTemplate)
1807 : {
1808 : // TODO: should check the player's civ is allowed to use this formation
1809 : // See simulation/components/Player.js GetFormations() for a list of all allowed formations
1810 :
1811 0 : const requirements = GetFormationRequirements(formationTemplate);
1812 0 : if (!requirements)
1813 0 : return false;
1814 :
1815 0 : let count = 0;
1816 0 : for (const ent of ents)
1817 0 : if (Engine.QueryInterface(ent, IID_UnitAI)?.CanUseFormation(formationTemplate))
1818 0 : ++count;
1819 :
1820 0 : return count >= requirements.minCount;
1821 : }
1822 :
1823 : /**
1824 : * Check if player can control this entity
1825 : * returns: true if the entity is owned by the player and controllable
1826 : * or control all units is activated, else false
1827 : */
1828 : function CanControlUnit(entity, player, controlAll)
1829 : {
1830 0 : const cmpIdentity = Engine.QueryInterface(entity, IID_Identity);
1831 0 : const canBeControlled = IsOwnedByPlayer(player, entity) &&
1832 : (!cmpIdentity || cmpIdentity.IsControllable()) ||
1833 : controlAll;
1834 :
1835 0 : if (!canBeControlled)
1836 0 : notifyOrderFailure(entity, player);
1837 :
1838 0 : return canBeControlled;
1839 : }
1840 :
1841 : /**
1842 : * @param {number} entity - The entityID to verify.
1843 : * @param {number} player - The playerID to check against.
1844 : * @return {boolean}.
1845 : */
1846 : function IsOwnedByPlayerOrMutualAlly(entity, player)
1847 : {
1848 0 : return IsOwnedByPlayer(player, entity) || IsOwnedByMutualAllyOfPlayer(player, entity);
1849 : }
1850 :
1851 : /**
1852 : * Check if player can control this entity
1853 : * @return {boolean} - True if the entity is valid and controlled by the player
1854 : * or the entity is owned by an mutualAlly and can be controlled
1855 : * or control all units is activated, else false.
1856 : */
1857 : function CanPlayerOrAllyControlUnit(entity, player, controlAll)
1858 : {
1859 0 : return CanControlUnit(player, entity, controlAll) ||
1860 : IsOwnedByMutualAllyOfPlayer(player, entity) && CanOwnerControlEntity(entity);
1861 : }
1862 :
1863 : /**
1864 : * @return {boolean} - Whether the owner of this entity can control the entity.
1865 : */
1866 : function CanOwnerControlEntity(entity)
1867 : {
1868 0 : const cmpOwner = QueryOwnerInterface(entity);
1869 0 : return cmpOwner && CanControlUnit(entity, cmpOwner.GetPlayerID());
1870 : }
1871 :
1872 : /**
1873 : * Filter entities which the player can control.
1874 : */
1875 : function FilterEntityList(entities, player, controlAll)
1876 : {
1877 0 : return entities.filter(ent => CanControlUnit(ent, player, controlAll));
1878 : }
1879 :
1880 : /**
1881 : * Filter entities which the player can control or are mutualAlly
1882 : */
1883 : function FilterEntityListWithAllies(entities, player, controlAll)
1884 : {
1885 0 : return entities.filter(ent => CanPlayerOrAllyControlUnit(ent, player, controlAll));
1886 : }
1887 :
1888 : /**
1889 : * Incur the player with the cost of a bribe, optionally multiply the cost with
1890 : * the additionalMultiplier
1891 : */
1892 : function IncurBribeCost(template, player, playerBribed, failedBribe)
1893 : {
1894 3 : const cmpPlayerBribed = QueryPlayerIDInterface(playerBribed);
1895 3 : if (!cmpPlayerBribed)
1896 0 : return false;
1897 :
1898 3 : const costs = {};
1899 : // Additional cost for this owner
1900 3 : let multiplier = cmpPlayerBribed.GetSpyCostMultiplier();
1901 3 : if (failedBribe)
1902 0 : multiplier *= template.VisionSharing.FailureCostRatio;
1903 :
1904 3 : for (const res in template.Cost.Resources)
1905 3 : costs[res] = Math.floor(multiplier * ApplyValueModificationsToTemplate("Cost/Resources/" + res, +template.Cost.Resources[res], player, template));
1906 :
1907 3 : const cmpPlayer = QueryPlayerIDInterface(player);
1908 3 : return cmpPlayer && cmpPlayer.TrySubtractResources(costs);
1909 : }
1910 :
1911 1 : Engine.RegisterGlobal("GetFormationRequirements", GetFormationRequirements);
1912 1 : Engine.RegisterGlobal("CanMoveEntsIntoFormation", CanMoveEntsIntoFormation);
1913 1 : Engine.RegisterGlobal("GetDockAngle", GetDockAngle);
1914 1 : Engine.RegisterGlobal("ProcessCommand", ProcessCommand);
1915 1 : Engine.RegisterGlobal("g_Commands", g_Commands);
1916 1 : Engine.RegisterGlobal("IncurBribeCost", IncurBribeCost);
|