Merge branch 'main' into 343-add-ability-to-select-unit-nation-and-livery

This commit is contained in:
Pax1601
2023-09-03 15:18:35 +02:00
243 changed files with 105641 additions and 174 deletions

View File

@@ -19,7 +19,7 @@ interface CustomEventMap {
"mapStateChanged": CustomEvent<string>,
"mapContextMenu": CustomEvent<>,
"mapVisibilityOptionsChanged": CustomEvent<>,
"commandModeOptionsChanged": CustomEvent<>,
"commandModeOptionsChanged": CustomEvent<>,
"contactsUpdated": CustomEvent<Unit>,
}

View File

@@ -135,21 +135,19 @@ export const layers = {
/* Map constants */
export const IDLE = "Idle";
export const MOVE_UNIT = "Move unit";
export const BOMBING = "Bombing";
export const CARPET_BOMBING = "Carpet bombing";
export const FIRE_AT_AREA = "Fire at area";
export const COALITIONAREA_DRAW_POLYGON = "Draw Coalition Area";
export const visibilityControls: string[] = ["human", "dcs", "aircraft", "groundunit-sam", "groundunit-other", "navyunit", "airbase"];
export const visibilityControlsTypes: string[][] = [["human"], ["dcs"], ["aircraft"], ["groundunit-sam", "groundunit-sam-radar", "groundunit-sam-launcher"], ["groundunit-other", "groundunit-ewr"], ["navyunit"], ["airbase"]];
export const visibilityControlsTootlips: string[] = ["Toggle human players visibility", "Toggle DCS controlled units visibility", "Toggle aircrafts visibility", "Toggle SAM units visibility", "Toggle ground units (not SAM) visibility", "Toggle navy units visibility", "Toggle airbases visibility"];
export const visibilityControlsTooltips: string[] = ["Toggle human players visibility", "Toggle DCS controlled units visibility", "Toggle aircrafts visibility", "Toggle SAM units visibility", "Toggle ground units (not SAM) visibility", "Toggle navy units visibility", "Toggle airbases visibility"];
export const IADSTypes = ["AAA", "MANPADS", "SAM Site", "Radar"];
export const IADSDensities: {[key: string]: number}= {"AAA": 0.8, "MANPADS": 0.3, "SAM Site": 0.1, "Radar": 0.05};
export const SHOW_CONTACT_LINES = "Show unit contact lines";
export const HIDE_GROUP_MEMBERS = "Hide group members when zoomed out";
export const SHOW_UNIT_PATHS = "Show unit paths";
export const SHOW_UNIT_TARGETS = "Show unit targets";
export const SHOW_UNIT_LABELS = "Show unit labels";
export const SHOW_UNIT_PATHS = "Show unit paths";
export const SHOW_UNIT_TARGETS = "Show unit targets";
export enum DataIndexes {
startOfData = 0,

View File

@@ -19,9 +19,7 @@ export class Dropdown {
this.#defaultValue = this.#value.innerText;
this.#callback = callback;
if (options != null) {
this.setOptions(options);
}
if (options != null) this.setOptions(options);
this.#value.addEventListener("click", (ev) => { this.#toggle(); });

View File

@@ -0,0 +1,594 @@
import { LatLng } from "leaflet";
import { getActiveCoalition, getMap, getMissionHandler, getUnitsManager, setActiveCoalition } from "..";
import { spawnExplosion, spawnSmoke } from "../server/server";
import { aircraftDatabase } from "../unit/aircraftdatabase";
import { groundUnitDatabase } from "../unit/groundunitdatabase";
import { helicopterDatabase } from "../unit/helicopterdatabase";
import { ContextMenu } from "./contextmenu";
import { Dropdown } from "./dropdown";
import { Switch } from "./switch";
import { Slider } from "./slider";
import { ftToM } from "../other/utils";
import { GAME_MASTER } from "../constants/constants";
import { navyUnitDatabase } from "../unit/navyunitdatabase";
import { CoalitionArea } from "../map/coalitionarea";
import { SmokeMarker } from "../map/smokemarker";
export class MapContextMenu extends ContextMenu {
#coalitionSwitch: Switch;
#aircraftRoleDropdown: Dropdown;
#aircraftLabelDropdown: Dropdown;
#aircraftCountDropdown: Dropdown;
#aircraftLoadoutDropdown: Dropdown;
#aircraftSpawnAltitudeSlider: Slider;
#helicopterRoleDropdown: Dropdown;
#helicopterLabelDropdown: Dropdown;
#helicopterCountDropdown: Dropdown;
#helicopterLoadoutDropdown: Dropdown;
#helicopterSpawnAltitudeSlider: Slider;
#groundUnitTypeDropdown: Dropdown;
#groundUnitLabelDropdown: Dropdown;
#groundUnitCountDropdown: Dropdown;
#navyUnitTypeDropdown: Dropdown;
#navyUnitLabelDropdown: Dropdown;
#navyUnitCountDropdown: Dropdown;
#spawnOptions = { role: "", name: "", latlng: new LatLng(0, 0), coalition: "blue", loadout: "", airbaseName: "", altitude: 0, count: 1 };
#coalitionArea: CoalitionArea | null = null;
constructor(id: string) {
super(id);
this.#coalitionSwitch = new Switch("coalition-switch", (value: boolean) => this.#onSwitchClick(value));
this.#coalitionSwitch.setValue(false);
this.#coalitionSwitch.getContainer()?.addEventListener("contextmenu", (e) => this.#onSwitchRightClick(e));
/* Aircraft menu */
this.#aircraftRoleDropdown = new Dropdown("aircraft-role-options", (role: string) => this.#setAircraftRole(role));
this.#aircraftLabelDropdown = new Dropdown("aircraft-label-options", (type: string) => this.#setAircraftLabel(type));
this.#aircraftCountDropdown = new Dropdown("aircraft-count-options", (type: string) => this.#setAircraftCount(type));
this.#aircraftCountDropdown.setOptions(["1", "2", "3", "4"]);
this.#aircraftCountDropdown.setValue("1");
this.#aircraftLoadoutDropdown = new Dropdown("aircraft-loadout-options", (loadout: string) => this.#setAircraftLoadout(loadout));
this.#aircraftSpawnAltitudeSlider = new Slider("aircraft-spawn-altitude-slider", 0, 50000, "ft", (value: number) => {this.#spawnOptions.altitude = ftToM(value);});
this.#aircraftSpawnAltitudeSlider.setIncrement(500);
this.#aircraftSpawnAltitudeSlider.setValue(20000);
this.#aircraftSpawnAltitudeSlider.setActive(true);
/* Helicopter menu */
this.#helicopterRoleDropdown = new Dropdown("helicopter-role-options", (role: string) => this.#setHelicopterRole(role));
this.#helicopterLabelDropdown = new Dropdown("helicopter-label-options", (type: string) => this.#setHelicopterLabel(type));
this.#helicopterCountDropdown = new Dropdown("helicopter-count-options", (type: string) => this.#setHelicopterCount(type));
this.#helicopterCountDropdown.setOptions(["1", "2", "3", "4"]);
this.#helicopterCountDropdown.setValue("1");
this.#helicopterLoadoutDropdown = new Dropdown("helicopter-loadout-options", (loadout: string) => this.#setHelicopterLoadout(loadout));
this.#helicopterSpawnAltitudeSlider = new Slider("helicopter-spawn-altitude-slider", 0, 10000, "ft", (value: number) => {this.#spawnOptions.altitude = ftToM(value);});
this.#helicopterSpawnAltitudeSlider.setIncrement(50);
this.#helicopterSpawnAltitudeSlider.setValue(5000);
this.#helicopterSpawnAltitudeSlider.setActive(true);
var count = [];
for (let i = 1; i < 10; i++) count.push(String(i));
/* Ground unit menu */
this.#groundUnitTypeDropdown = new Dropdown("groundunit-type-options", (type: string) => this.#setGroundUnitType(type));
this.#groundUnitLabelDropdown = new Dropdown("groundunit-label-options", (name: string) => this.#setGroundUnitLabel(name));
this.#groundUnitCountDropdown = new Dropdown("groundunit-count-options", (count: string) => this.#setGroundUnitCount(count));
this.#groundUnitCountDropdown.setOptions(count);
this.#groundUnitCountDropdown.setValue("1");
/* Navy unit menu */
this.#navyUnitTypeDropdown = new Dropdown("navyunit-type-options", (type: string) => this.#setNavyUnitType(type));
this.#navyUnitLabelDropdown = new Dropdown("navyunit-label-options", (name: string) => this.#setNavyUnitLabel(name));
this.#navyUnitCountDropdown = new Dropdown("navyunit-count-options", (count: string) => this.#setNavyUnitCount(count));
this.#navyUnitCountDropdown.setOptions(count);
this.#navyUnitCountDropdown.setValue("1");
document.addEventListener("mapContextMenuShow", (e: any) => {
if (this.getVisibleSubMenu() !== e.detail.type)
this.showSubMenu(e.detail.type);
else
this.hideSubMenus(e.detail.type);
});
document.addEventListener("contextMenuDeployAircrafts", () => {
this.#spawnOptions.coalition = getActiveCoalition();
if (this.#spawnOptions) {
const liveryID = aircraftDatabase.getByName(this.#spawnOptions.name)?.liveryID;
var unitTable = {unitType: this.#spawnOptions.name, location: this.#spawnOptions.latlng, altitude: this.#spawnOptions.altitude, loadout: this.#spawnOptions.loadout, liveryID: liveryID? liveryID: ""};
var units = [];
for (let i = 1; i < parseInt(this.#aircraftCountDropdown.getValue()) + 1; i++) {
units.push(unitTable);
}
if (getUnitsManager().spawnUnits("Aircraft", units, getActiveCoalition(), false, this.#spawnOptions.airbaseName)) {
getMap().addTemporaryMarker(this.#spawnOptions.latlng, this.#spawnOptions.name, getActiveCoalition());
this.hide();
}
}
});
document.addEventListener("contextMenuDeployHelicopters", () => {
this.#spawnOptions.coalition = getActiveCoalition();
if (this.#spawnOptions) {
const liveryID = aircraftDatabase.getByName(this.#spawnOptions.name)?.liveryID;
var unitTable = {unitType: this.#spawnOptions.name, location: this.#spawnOptions.latlng, altitude: this.#spawnOptions.altitude, loadout: this.#spawnOptions.loadout, liveryID: liveryID? liveryID: ""};
var units = [];
for (let i = 1; i < parseInt(this.#helicopterCountDropdown.getValue()) + 1; i++) {
units.push(unitTable);
}
if (getUnitsManager().spawnUnits("Helicopter", units, getActiveCoalition(), false, this.#spawnOptions.airbaseName)) {
getMap().addTemporaryMarker(this.#spawnOptions.latlng, this.#spawnOptions.name, getActiveCoalition());
this.hide();
}
}
});
document.addEventListener("contextMenuDeployGroundUnits", () => {
this.#spawnOptions.coalition = getActiveCoalition();
if (this.#spawnOptions) {
const liveryID = aircraftDatabase.getByName(this.#spawnOptions.name)?.liveryID;
var unitTable = {unitType: this.#spawnOptions.name, location: this.#spawnOptions.latlng, liveryID: liveryID? liveryID: ""};
var units = [];
for (let i = 1; i < parseInt(this.#groundUnitCountDropdown.getValue()) + 1; i++) {
units.push(JSON.parse(JSON.stringify(unitTable)));
unitTable.location.lat += 0.0001;
}
if (getUnitsManager().spawnUnits("GroundUnit", units, getActiveCoalition(), false)) {
getMap().addTemporaryMarker(this.#spawnOptions.latlng, this.#spawnOptions.name, getActiveCoalition());
this.hide();
}
}
});
document.addEventListener("contextMenuDeployNavyUnits", () => {
this.#spawnOptions.coalition = getActiveCoalition();
if (this.#spawnOptions) {
const liveryID = aircraftDatabase.getByName(this.#spawnOptions.name)?.liveryID;
var unitTable = {unitType: this.#spawnOptions.name, location: this.#spawnOptions.latlng, liveryID: liveryID? liveryID: ""};
var units = [];
for (let i = 1; i < parseInt(this.#navyUnitCountDropdown.getValue()) + 1; i++) {
units.push(JSON.parse(JSON.stringify(unitTable)));
unitTable.location.lat += 0.0001;
}
if (getUnitsManager().spawnUnits("NavyUnit", units, getActiveCoalition(), false)) {
getMap().addTemporaryMarker(this.#spawnOptions.latlng, this.#spawnOptions.name, getActiveCoalition());
this.hide();
}
}
});
document.addEventListener("contextMenuDeploySmoke", (e: any) => {
this.hide();
spawnSmoke(e.detail.color, this.getLatLng());
var marker = new SmokeMarker(this.getLatLng(), e.detail.color);
marker.addTo(getMap());
});
document.addEventListener("contextMenuExplosion", (e: any) => {
this.hide();
spawnExplosion(e.detail.strength, this.getLatLng());
});
document.addEventListener("editCoalitionArea", (e: any) => {
this.hide();
if (this.#coalitionArea) {
getMap().deselectAllCoalitionAreas();
this.#coalitionArea.setSelected(true);
}
});
document.addEventListener("commandModeOptionsChanged", (e: any) => {
this.#refreshOptions();
});
this.hide();
}
show(x: number, y: number, latlng: LatLng) {
super.show(x, y, latlng);
this.showUpperBar();
this.showAltitudeSlider();
this.#spawnOptions.airbaseName = "";
this.#spawnOptions.latlng = latlng;
this.getContainer()?.querySelectorAll('[data-coalition]').forEach((element: any) => { element.setAttribute("data-coalition", getActiveCoalition()) });
if (getActiveCoalition() == "blue")
this.#coalitionSwitch.setValue(false);
else if (getActiveCoalition() == "red")
this.#coalitionSwitch.setValue(true);
else
this.#coalitionSwitch.setValue(undefined);
if (getMissionHandler().getCommandModeOptions().commandMode !== GAME_MASTER)
this.#coalitionSwitch.hide()
this.getContainer()?.querySelector("#coalition-area-button")?.classList.toggle("hide", true);
}
showSubMenu(type: string) {
if (type === "more")
this.getContainer()?.querySelector("#more-options-button-bar")?.classList.toggle("hide");
else if (["aircraft", "groundunit"].includes(type))
this.getContainer()?.querySelector("#more-options-button-bar")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#aircraft-spawn-menu")?.classList.toggle("hide", type !== "aircraft");
this.getContainer()?.querySelector("#aircraft-spawn-button")?.classList.toggle("is-open", type === "aircraft");
this.getContainer()?.querySelector("#helicopter-spawn-menu")?.classList.toggle("hide", type !== "helicopter");
this.getContainer()?.querySelector("#helicopter-spawn-button")?.classList.toggle("is-open", type === "helicopter");
this.getContainer()?.querySelector("#groundunit-spawn-menu")?.classList.toggle("hide", type !== "groundunit");
this.getContainer()?.querySelector("#groundunit-spawn-button")?.classList.toggle("is-open", type === "groundunit");
this.getContainer()?.querySelector("#navyunit-spawn-menu")?.classList.toggle("hide", type !== "navyunit");
this.getContainer()?.querySelector("#navyunit-spawn-button")?.classList.toggle("is-open", type === "navyunit");
this.getContainer()?.querySelector("#smoke-spawn-menu")?.classList.toggle("hide", type !== "smoke");
this.getContainer()?.querySelector("#smoke-spawn-button")?.classList.toggle("is-open", type === "smoke");
this.getContainer()?.querySelector("#explosion-menu")?.classList.toggle("hide", type !== "explosion");
this.getContainer()?.querySelector("#explosion-spawn-button")?.classList.toggle("is-open", type === "explosion");
(this.getContainer()?.querySelectorAll(".deploy-unit-button"))?.forEach((element: Node) => {(element as HTMLButtonElement).disabled = true;})
this.#resetAircraftRole();
this.#resetAircraftLabel();
this.#resetHelicopterRole();
this.#resetHelicopterLabel();
this.#resetGroundUnitType();
this.#resetGroundUnitLabel();
this.#resetNavyUnitType();
this.#resetNavyUnitLabel();
this.#aircraftCountDropdown.setValue("1");
this.#helicopterCountDropdown.setValue("1");
this.#groundUnitCountDropdown.setValue("1");
this.clip();
if (type === "aircraft") {
this.#spawnOptions.altitude = ftToM(this.#aircraftSpawnAltitudeSlider.getValue());
}
else if (type === "helicopter") {
this.#spawnOptions.altitude = ftToM(this.#helicopterSpawnAltitudeSlider.getValue());
}
this.setVisibleSubMenu(type);
}
hideSubMenus(type: string) {
this.getContainer()?.querySelector("#more-options-button-bar")?.classList.toggle("hide", ["aircraft", "groundunit"].includes(type));
this.getContainer()?.querySelector("#aircraft-spawn-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#aircraft-spawn-button")?.classList.toggle("is-open", false);
this.getContainer()?.querySelector("#helicopter-spawn-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#helicopter-spawn-button")?.classList.toggle("is-open", false);
this.getContainer()?.querySelector("#groundunit-spawn-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#groundunit-spawn-button")?.classList.toggle("is-open", false);
this.getContainer()?.querySelector("#navyunit-spawn-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#navyunit-spawn-button")?.classList.toggle("is-open", false);
this.getContainer()?.querySelector("#smoke-spawn-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#smoke-spawn-button")?.classList.toggle("is-open", false);
this.getContainer()?.querySelector("#explosion-menu")?.classList.toggle("hide", true);
this.getContainer()?.querySelector("#explosion-spawn-button")?.classList.toggle("is-open", false);
this.#resetAircraftRole();
this.#resetAircraftLabel();
this.#resetHelicopterRole();
this.#resetHelicopterLabel();
this.#resetHelicopterRole();
this.#resetHelicopterLabel();
this.#resetGroundUnitType();
this.#resetGroundUnitLabel();
this.#resetNavyUnitType();
this.#resetNavyUnitLabel();
this.clip();
this.setVisibleSubMenu(null);
}
showUpperBar() {
this.getContainer()?.querySelector(".upper-bar")?.classList.toggle("hide", false);
}
hideUpperBar() {
this.getContainer()?.querySelector(".upper-bar")?.classList.toggle("hide", true);
}
showLowerBar() {
this.getContainer()?.querySelector("#more-options-button-bar")?.classList.toggle("hide", false);
}
hideLowerBar() {
this.getContainer()?.querySelector("#more-optionsbutton-bar")?.classList.toggle("hide", true);
}
showAltitudeSlider() {
this.getContainer()?.querySelector("#aircraft-spawn-altitude-slider")?.classList.toggle("hide", false);
}
hideAltitudeSlider() {
this.getContainer()?.querySelector("#aircraft-spawn-altitude-slider")?.classList.toggle("hide", true);
}
setAirbaseName(airbaseName: string) {
this.#spawnOptions.airbaseName = airbaseName;
}
setLatLng(latlng: LatLng) {
this.#spawnOptions.latlng = latlng;
}
setCoalitionArea(coalitionArea: CoalitionArea) {
this.#coalitionArea = coalitionArea;
this.getContainer()?.querySelector("#coalition-area-button")?.classList.toggle("hide", false);
}
#onSwitchClick(value: boolean) {
value? setActiveCoalition("red"): setActiveCoalition("blue");
this.getContainer()?.querySelectorAll('[data-coalition]').forEach((element: any) => { element.setAttribute("data-coalition", getActiveCoalition()) });
}
#onSwitchRightClick(e: any) {
this.#coalitionSwitch.setValue(undefined);
setActiveCoalition("neutral");
this.getContainer()?.querySelectorAll('[data-coalition]').forEach((element: any) => { element.setAttribute("data-coalition", getActiveCoalition()) });
}
#refreshOptions() {
if (!aircraftDatabase.getRoles().includes(this.#aircraftRoleDropdown.getValue()))
this.#resetAircraftRole();
if (!aircraftDatabase.getByRole(this.#aircraftRoleDropdown.getValue()).map((blueprint) => { return blueprint.label }).includes(this.#aircraftLabelDropdown.getValue()))
this.#resetAircraftLabel();
if (!helicopterDatabase.getRoles().includes(this.#helicopterRoleDropdown.getValue()))
this.#resetHelicopterRole();
if (!helicopterDatabase.getByRole(this.#helicopterRoleDropdown.getValue()).map((blueprint) => { return blueprint.label }).includes(this.#helicopterLabelDropdown.getValue()))
this.#resetHelicopterLabel();
if (!groundUnitDatabase.getRoles().includes(this.#groundUnitTypeDropdown.getValue()))
this.#resetGroundUnitType();
if (!groundUnitDatabase.getByType(this.#groundUnitTypeDropdown.getValue()).map((blueprint) => { return blueprint.label }).includes(this.#groundUnitLabelDropdown.getValue()))
this.#resetGroundUnitLabel();
if (!navyUnitDatabase.getRoles().includes(this.#navyUnitTypeDropdown.getValue()))
this.#resetNavyUnitType();
if (!navyUnitDatabase.getByType(this.#navyUnitTypeDropdown.getValue()).map((blueprint) => { return blueprint.label }).includes(this.#aircraftLabelDropdown.getValue()))
this.#resetNavyUnitLabel();
}
/********* Aircraft spawn menu *********/
#setAircraftRole(role: string) {
this.#spawnOptions.role = role;
this.#resetAircraftLabel();
this.#aircraftLabelDropdown.setOptions(aircraftDatabase.getByRole(role).map((blueprint) => { return blueprint.label }));
this.#aircraftLabelDropdown.selectValue(0);
this.clip();
this.#computeSpawnPoints();
}
#resetAircraftRole() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-loadout-list")).replaceChildren();
this.#aircraftRoleDropdown.reset();
this.#aircraftLabelDropdown.reset();
this.#aircraftRoleDropdown.setOptions(aircraftDatabase.getRoles());
this.clip();
}
#setAircraftLabel(label: string) {
this.#resetAircraftLabel();
var name = aircraftDatabase.getByLabel(label)?.name || null;
if (name != null) {
this.#spawnOptions.name = name;
this.#aircraftLoadoutDropdown.setOptions(aircraftDatabase.getLoadoutNamesByRole(name, this.#spawnOptions.role));
this.#aircraftLoadoutDropdown.selectValue(0);
var image = (<HTMLImageElement>this.getContainer()?.querySelector("#aircraft-unit-image"));
image.src = `images/units/${aircraftDatabase.getByLabel(label)?.filename}`;
image.classList.toggle("hide", false);
}
this.clip();
this.#computeSpawnPoints();
}
#resetAircraftLabel() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-loadout-list")).replaceChildren();
this.#aircraftLoadoutDropdown.reset();
(<HTMLImageElement>this.getContainer()?.querySelector("#aircraft-unit-image")).classList.toggle("hide", true);
this.clip();
}
#setAircraftCount(count: string) {
this.#spawnOptions.count = parseInt(count);
this.clip();
this.#computeSpawnPoints();
}
#setAircraftLoadout(loadoutName: string) {
var loadout = aircraftDatabase.getLoadoutByName(this.#spawnOptions.name, loadoutName);
if (loadout) {
this.#spawnOptions.loadout = loadout.code;
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = false;
var items = loadout.items.map((item: any) => { return `${item.quantity}x ${item.name}`; });
items.length == 0 ? items.push("Empty loadout") : "";
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-loadout-list")).replaceChildren(
...items.map((item: any) => {
var div = document.createElement('div');
div.innerText = item;
return div;
})
)
}
this.clip();
}
/********* Helicopter spawn menu *********/
#setHelicopterRole(role: string) {
this.#spawnOptions.role = role;
this.#resetHelicopterLabel();
this.#helicopterLabelDropdown.setOptions(helicopterDatabase.getByRole(role).map((blueprint) => { return blueprint.label }));
this.#helicopterLabelDropdown.selectValue(0);
this.clip();
this.#computeSpawnPoints();
}
#resetHelicopterRole() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-loadout-list")).replaceChildren();
this.#helicopterRoleDropdown.reset();
this.#helicopterLabelDropdown.reset();
this.#helicopterRoleDropdown.setOptions(helicopterDatabase.getRoles());
this.clip();
}
#setHelicopterLabel(label: string) {
this.#resetHelicopterLabel();
var name = helicopterDatabase.getByLabel(label)?.name || null;
if (name != null) {
this.#spawnOptions.name = name;
this.#helicopterLoadoutDropdown.setOptions(helicopterDatabase.getLoadoutNamesByRole(name, this.#spawnOptions.role));
this.#helicopterLoadoutDropdown.selectValue(0);
var image = (<HTMLImageElement>this.getContainer()?.querySelector("#helicopter-unit-image"));
image.src = `images/units/${helicopterDatabase.getByLabel(label)?.filename}`;
image.classList.toggle("hide", false);
}
this.clip();
this.#computeSpawnPoints();
}
#resetHelicopterLabel() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-loadout-list")).replaceChildren();
this.#helicopterLoadoutDropdown.reset();
(<HTMLImageElement>this.getContainer()?.querySelector("#helicopter-unit-image")).classList.toggle("hide", true);
this.clip();
}
#setHelicopterCount(count: string) {
this.#spawnOptions.count = parseInt(count);
this.clip();
this.#computeSpawnPoints();
}
#setHelicopterLoadout(loadoutName: string) {
var loadout = helicopterDatabase.getLoadoutByName(this.#spawnOptions.name, loadoutName);
if (loadout) {
this.#spawnOptions.loadout = loadout.code;
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = false;
var items = loadout.items.map((item: any) => { return `${item.quantity}x ${item.name}`; });
items.length == 0 ? items.push("Empty loadout") : "";
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-loadout-list")).replaceChildren(
...items.map((item: any) => {
var div = document.createElement('div');
div.innerText = item;
return div;
})
)
}
this.clip();
}
/********* Groundunit spawn menu *********/
#setGroundUnitType(role: string) {
this.#resetGroundUnitLabel();
const types = groundUnitDatabase.getByType(role).map((blueprint) => { return blueprint.label });
this.#groundUnitLabelDropdown.setOptions(types);
this.#groundUnitLabelDropdown.selectValue(0);
this.clip();
this.#computeSpawnPoints();
}
#resetGroundUnitType() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#groundunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
this.#groundUnitTypeDropdown.reset();
this.#groundUnitLabelDropdown.reset();
const types = groundUnitDatabase.getTypes();
this.#groundUnitTypeDropdown.setOptions(types);
this.clip();
}
#setGroundUnitLabel(label: string) {
this.#resetGroundUnitLabel();
var type = groundUnitDatabase.getByLabel(label)?.name || null;
if (type != null) {
this.#spawnOptions.name = type;
(<HTMLButtonElement>this.getContainer()?.querySelector("#groundunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = false;
}
this.clip();
this.#computeSpawnPoints();
}
#resetGroundUnitLabel() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#groundunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
this.clip();
}
#setGroundUnitCount(count: string) {
this.#spawnOptions.count = parseInt(count);
this.clip();
this.#computeSpawnPoints();
}
/********* Navyunit spawn menu *********/
#setNavyUnitType(role: string) {
this.#resetNavyUnitLabel();
const types = navyUnitDatabase.getByType(role).map((blueprint) => { return blueprint.label });
this.#navyUnitLabelDropdown.setOptions(types);
this.#navyUnitLabelDropdown.selectValue(0);
this.clip();
this.#computeSpawnPoints();
}
#resetNavyUnitType() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#navyunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
this.#navyUnitTypeDropdown.reset();
this.#navyUnitLabelDropdown.reset();
const types = navyUnitDatabase.getTypes();
this.#navyUnitTypeDropdown.setOptions(types);
this.clip();
}
#setNavyUnitLabel(label: string) {
this.#resetNavyUnitLabel();
var type = navyUnitDatabase.getByLabel(label)?.name || null;
if (type != null) {
this.#spawnOptions.name = type;
(<HTMLButtonElement>this.getContainer()?.querySelector("#navyunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = false;
}
this.clip();
this.#computeSpawnPoints();
}
#resetNavyUnitLabel() {
(<HTMLButtonElement>this.getContainer()?.querySelector("#navyunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = true;
this.clip();
}
#setNavyUnitCount(count: string) {
this.#spawnOptions.count = parseInt(count);
this.clip();
this.#computeSpawnPoints();
}
#computeSpawnPoints() {
if (getMissionHandler() && getMissionHandler().getCommandModeOptions().commandMode !== GAME_MASTER){
var aircraftCount = parseInt(this.#aircraftCountDropdown.getValue());
var aircraftSpawnPoints = aircraftCount * aircraftDatabase.getSpawnPointsByLabel(this.#aircraftLabelDropdown.getValue());
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-spawn-menu")?.querySelector(".deploy-unit-button")).dataset.points = `${aircraftSpawnPoints}`;
(<HTMLButtonElement>this.getContainer()?.querySelector("#aircraft-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = aircraftSpawnPoints >= getMissionHandler().getAvailableSpawnPoints();
var helicopterCount = parseInt(this.#helicopterCountDropdown.getValue());
var helicopterSpawnPoints = helicopterCount * helicopterDatabase.getSpawnPointsByLabel(this.#helicopterLabelDropdown.getValue());
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-spawn-menu")?.querySelector(".deploy-unit-button")).dataset.points = `${helicopterSpawnPoints}`;
(<HTMLButtonElement>this.getContainer()?.querySelector("#helicopter-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = helicopterSpawnPoints >= getMissionHandler().getAvailableSpawnPoints();
var groundUnitCount = parseInt(this.#groundUnitCountDropdown.getValue());
var groundUnitSpawnPoints = groundUnitCount * groundUnitDatabase.getSpawnPointsByLabel(this.#groundUnitLabelDropdown.getValue());
(<HTMLButtonElement>this.getContainer()?.querySelector("#groundunit-spawn-menu")?.querySelector(".deploy-unit-button")).dataset.points = `${groundUnitSpawnPoints}`;
(<HTMLButtonElement>this.getContainer()?.querySelector("#groundunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = groundUnitSpawnPoints >= getMissionHandler().getAvailableSpawnPoints();
var navyUnitCount = parseInt(this.#navyUnitCountDropdown.getValue());
var navyUnitSpawnPoints = navyUnitCount * navyUnitDatabase.getSpawnPointsByLabel(this.#navyUnitLabelDropdown.getValue());
(<HTMLButtonElement>this.getContainer()?.querySelector("#navyunit-spawn-menu")?.querySelector(".deploy-unit-button")).dataset.points = `${navyUnitSpawnPoints}`;
(<HTMLButtonElement>this.getContainer()?.querySelector("#navyunit-spawn-menu")?.querySelector(".deploy-unit-button")).disabled = navyUnitSpawnPoints >= getMissionHandler().getAvailableSpawnPoints();
}
}
}

View File

@@ -137,9 +137,6 @@ function setupEvents() {
return;
}
switch (ev.code) {
case "KeyL":
document.body.toggleAttribute("data-hide-labels");
break;
case "KeyT":
toggleDemoEnabled();
break;

View File

@@ -1,5 +1,5 @@
import * as L from "leaflet"
import { getMissionHandler, getUnitsManager } from "..";
import { getInfoPopup, getMissionHandler, getUnitsManager } from "..";
import { BoxSelect } from "./boxselect";
import { MapContextMenu } from "../contextmenus/mapcontextmenu";
import { UnitContextMenu } from "../contextmenus/unitcontextmenu";
@@ -12,7 +12,7 @@ import { DestinationPreviewMarker } from "./destinationpreviewmarker";
import { TemporaryUnitMarker } from "./temporaryunitmarker";
import { ClickableMiniMap } from "./clickableminimap";
import { SVGInjector } from '@tanem/svg-injector'
import { layers as mapLayers, mapBounds, minimapBoundaries, IDLE, COALITIONAREA_DRAW_POLYGON, visibilityControls, visibilityControlsTootlips, FIRE_AT_AREA, MOVE_UNIT, CARPET_BOMBING, BOMBING, SHOW_CONTACT_LINES, HIDE_GROUP_MEMBERS, SHOW_UNIT_PATHS, SHOW_UNIT_TARGETS, visibilityControlsTypes } from "../constants/constants";
import { layers as mapLayers, mapBounds, minimapBoundaries, IDLE, COALITIONAREA_DRAW_POLYGON, visibilityControls, visibilityControlsTootlips, MOVE_UNIT, SHOW_CONTACT_LINES, HIDE_GROUP_MEMBERS, SHOW_UNIT_PATHS, SHOW_UNIT_TARGETS, visibilityControlsTypes, SHOW_UNIT_LABELS } from "../constants/constants";
import { TargetMarker } from "./targetmarker";
import { CoalitionArea } from "./coalitionarea";
import { CoalitionAreaContextMenu } from "../contextmenus/coalitionareacontextmenu";
@@ -46,7 +46,7 @@ export class Map extends L.Map {
#temporaryMarkers: TemporaryUnitMarker[] = [];
#selecting: boolean = false;
#isZooming: boolean = false;
#destinationGroupRotation: number = 0;
#computeDestinationRotation: boolean = false;
#destinationRotationCenter: L.LatLng | null = null;
@@ -55,6 +55,8 @@ export class Map extends L.Map {
#targetCursor: TargetMarker = new TargetMarker(new L.LatLng(0, 0), { interactive: false });
#destinationPreviewCursors: DestinationPreviewMarker[] = [];
#drawingCursor: DrawingCursor = new DrawingCursor();
#longPressHandled: boolean = false;
#longPressTimer: number = 0;
#mapContextMenu: MapContextMenu = new MapContextMenu("map-contextmenu");
#unitContextMenu: UnitContextMenu = new UnitContextMenu("unit-contextmenu");
@@ -65,7 +67,7 @@ export class Map extends L.Map {
#mapSourceDropdown: Dropdown;
#mapVisibilityOptionsDropdown: Dropdown;
#optionButtons: { [key: string]: HTMLButtonElement[] } = {}
#visibiityOptions: { [key: string]: boolean } = {}
#visibilityOptions: { [key: string]: boolean } = {}
/**
*
@@ -95,7 +97,7 @@ export class Map extends L.Map {
this.#mapSourceDropdown = new Dropdown("map-type", (layerName: string) => this.setLayer(layerName), this.getLayers());
/* Visibility options dropdown */
this.#mapVisibilityOptionsDropdown = new Dropdown("map-visibility-options", () => {});
this.#mapVisibilityOptionsDropdown = new Dropdown("map-visibility-options", (value: string) => { });
/* Init the state machine */
this.#state = IDLE;
@@ -138,7 +140,6 @@ export class Map extends L.Map {
})
}
});
document.addEventListener("toggleCoalitionAreaDraw", (ev: CustomEventInit) => {
this.getMapContextMenu().hide();
@@ -156,6 +157,10 @@ export class Map extends L.Map {
this.#panToUnit(this.#centerUnit);
});
document.addEventListener("mapVisibilityOptionsChanged", () => {
this.getContainer().toggleAttribute("data-hide-labels", !this.getVisibilityOptions()[SHOW_UNIT_LABELS]);
});
/* Pan interval */
this.#panInterval = window.setInterval(() => {
if (this.#panLeft || this.#panDown || this.#panRight || this.#panLeft)
@@ -166,19 +171,19 @@ export class Map extends L.Map {
/* Option buttons */
this.#optionButtons["visibility"] = visibilityControls.map((option: string, index: number) => {
var typesArrayString = `"${visibilityControlsTypes[index][0]}"`;
visibilityControlsTypes[index].forEach((type: string, idx: number) => {if (idx > 0) typesArrayString = `${typesArrayString}, "${type}"`});
return this.#createOptionButton(option, `visibility/${option.toLowerCase()}.svg`, visibilityControlsTootlips[index], "toggleMarkerVisibility", `{"types": [${typesArrayString}]}`);
visibilityControlsTypes[index].forEach((type: string, idx: number) => { if (idx > 0) typesArrayString = `${typesArrayString}, "${type}"` });
return this.#createOptionButton(option, `visibility/${option.toLowerCase()}.svg`, visibilityControlsTooltips[index], "toggleMarkerVisibility", `{"types": [${typesArrayString}]}`);
});
document.querySelector("#unit-visibility-control")?.append(...this.#optionButtons["visibility"]);
/* Create the checkboxes to select the advanced visibility options */
this.#visibiityOptions[SHOW_CONTACT_LINES] = false;
this.#visibiityOptions[HIDE_GROUP_MEMBERS] = true;
this.#visibiityOptions[SHOW_UNIT_PATHS] = true;
this.#visibiityOptions[SHOW_UNIT_TARGETS] = true;
this.#mapVisibilityOptionsDropdown.setOptionsElements(Object.keys(this.#visibiityOptions).map((option: string) => {
return createCheckboxOption(option, option, this.#visibiityOptions[option], (ev: any) => {
this.#visibilityOptions[SHOW_CONTACT_LINES] = false;
this.#visibilityOptions[HIDE_GROUP_MEMBERS] = true;
this.#visibilityOptions[SHOW_UNIT_PATHS] = true;
this.#visibilityOptions[SHOW_UNIT_TARGETS] = true;
this.#visibilityOptions[SHOW_UNIT_LABELS] = true;
this.#mapVisibilityOptionsDropdown.setOptionsElements(Object.keys(this.#visibilityOptions).map((option: string) => {
return createCheckboxOption(option, option, this.#visibilityOptions[option], (ev: any) => {
this.#setVisibilityOption(option, ev);
});
}));
@@ -456,7 +461,7 @@ export class Map extends L.Map {
}
getVisibilityOptions() {
return this.#visibiityOptions;
return this.#visibilityOptions;
}
/* Event handlers */
@@ -486,15 +491,23 @@ export class Map extends L.Map {
}
#onContextMenu(e: any) {
/* A long press will show the point action context menu */
window.clearInterval(this.#longPressTimer);
if (this.#longPressHandled) {
this.#longPressHandled = false;
return;
}
this.hideMapContextMenu();
if (this.#state === IDLE) {
if (this.#state == IDLE) {
this.showMapContextMenu(e.originalEvent.x, e.originalEvent.y, e.latlng);
var clickedCoalitionArea = null;
/* Coalition areas are ordered in the #coalitionAreas array according to their zindex. Select the upper one */
for (let coalitionArea of this.#coalitionAreas) {
if (coalitionArea.getBounds().contains(e.latlng)) {
if (coalitionArea.getSelected())
if (coalitionArea.getSelected())
clickedCoalitionArea = coalitionArea;
else
this.getMapContextMenu().setCoalitionArea(coalitionArea);
@@ -509,22 +522,11 @@ export class Map extends L.Map {
getUnitsManager().selectedUnitsClearDestinations();
}
getUnitsManager().selectedUnitsAddDestination(this.#computeDestinationRotation && this.#destinationRotationCenter != null ? this.#destinationRotationCenter : e.latlng, this.#shiftKey, this.#destinationGroupRotation)
this.#destinationGroupRotation = 0;
this.#destinationRotationCenter = null;
this.#computeDestinationRotation = false;
}
else if (this.#state === BOMBING) {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsBombPoint(this.getMouseCoordinates());
}
else if (this.#state === CARPET_BOMBING) {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsCarpetBomb(this.getMouseCoordinates());
}
else if (this.#state === FIRE_AT_AREA) {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsFireAtArea(this.getMouseCoordinates());
}
else {
this.setState(IDLE);
}
@@ -558,6 +560,56 @@ export class Map extends L.Map {
this.#destinationRotationCenter = this.getMouseCoordinates();
}
}
this.#longPressTimer = window.setTimeout(() => {
if (e.originalEvent.button != 2)
return;
this.hideMapContextMenu();
this.#longPressHandled = true;
var options: { [key: string]: { text: string, tooltip: string } } = {};
const selectedUnits = getUnitsManager().getSelectedUnits();
const selectedUnitTypes = getUnitsManager().getSelectedUnitsTypes();
if (selectedUnitTypes.length === 1 && ["Aircraft", "Helicopter"].includes(selectedUnitTypes[0])) {
if (selectedUnits.every((unit: Unit) => { return unit.canFulfillRole(["CAS", "Strike"]) })) {
options["bomb"] = { text: "Precision bombing", tooltip: "Precision bombing of a specific point" };
options["carpet-bomb"] = { text: "Carpet bombing", tooltip: "Carpet bombing close to a point" };
} else {
getInfoPopup().setText(`Selected units can not perform point actions.`);
}
}
else if (selectedUnitTypes.length === 1 && ["GroundUnit", "NavyUnit"].includes(selectedUnitTypes[0])) {
if (selectedUnits.every((unit: Unit) => { return ["Gun Artillery", "Rocket Artillery", "Infantry", "IFV", "Tank", "Cruiser", "Destroyer", "Frigate"].includes(unit.getType()) }))
options["fire-at-area"] = { text: "Fire at area", tooltip: "Fire at a large area" };
else
getInfoPopup().setText(`Selected units can not perform point actions.`);
}
else {
getInfoPopup().setText(`Multiple unit types selected, no common actions available.`);
}
if (Object.keys(options).length > 0) {
this.showUnitContextMenu(e.originalEvent.x, e.originalEvent.y, e.latlng);
this.getUnitContextMenu().setOptions(options, (option: string) => {
this.hideUnitContextMenu();
if (option === "bomb") {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsBombPoint(this.getMouseCoordinates());
}
else if (option === "carpet-bomb") {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsCarpetBomb(this.getMouseCoordinates());
}
else if (option === "fire-at-area") {
getUnitsManager().getSelectedUnits().length > 0 ? this.setState(MOVE_UNIT) : this.setState(IDLE);
getUnitsManager().selectedUnitsFireAtArea(this.getMouseCoordinates());
}
});
}
}, 150);
this.#longPressHandled = false;
}
#onMouseUp(e: any) {
@@ -575,9 +627,6 @@ export class Map extends L.Map {
this.#destinationGroupRotation = -bearing(this.#destinationRotationCenter.lat, this.#destinationRotationCenter.lng, this.getMouseCoordinates().lat, this.getMouseCoordinates().lng);
this.#updateDestinationCursors();
}
else if ([BOMBING, CARPET_BOMBING, FIRE_AT_AREA].includes(this.#state)) {
this.#targetCursor.setLatLng(this.getMouseCoordinates());
}
else if (this.#state === COALITIONAREA_DRAW_POLYGON) {
this.#drawingCursor.setLatLng(e.latlng);
/* Update the polygon being drawn with the current position of the mouse cursor */
@@ -680,7 +729,7 @@ export class Map extends L.Map {
else {
Object.values(getUnitsManager().selectedUnitsComputeGroupDestination(groupLatLng, this.#destinationGroupRotation)).forEach((latlng: L.LatLng, idx: number) => {
if (idx < this.#destinationPreviewCursors.length)
this.#destinationPreviewCursors[idx].setLatLng(this.#shiftKey? latlng : this.getMouseCoordinates());
this.#destinationPreviewCursors[idx].setLatLng(this.#shiftKey ? latlng : this.getMouseCoordinates());
})
};
}
@@ -733,19 +782,19 @@ export class Map extends L.Map {
/* Hide all the unnecessary cursors depending on the active state */
if (this.#state !== IDLE) this.#hideDefaultCursor();
if (this.#state !== MOVE_UNIT) this.#hideDestinationCursors();
if (![BOMBING, CARPET_BOMBING, FIRE_AT_AREA].includes(this.#state)) this.#hideTargetCursor();
//if (![BOMBING, CARPET_BOMBING, FIRE_AT_AREA].includes(this.#state)) this.#hideTargetCursor();
if (this.#state !== COALITIONAREA_DRAW_POLYGON) this.#hideDrawingCursor();
/* Show the active cursor depending on the active state */
if (this.#state === IDLE) this.#showDefaultCursor();
else if (this.#state === MOVE_UNIT) this.#showDestinationCursors();
else if ([BOMBING, CARPET_BOMBING, FIRE_AT_AREA].includes(this.#state)) this.#showTargetCursor();
//else if ([BOMBING, CARPET_BOMBING, FIRE_AT_AREA].includes(this.#state)) this.#showTargetCursor();
else if (this.#state === COALITIONAREA_DRAW_POLYGON) this.#showDrawingCursor();
}
}
#setVisibilityOption(option: string, ev: any) {
this.#visibiityOptions[option] = ev.currentTarget.checked;
this.#visibilityOptions[option] = ev.currentTarget.checked;
document.dispatchEvent(new CustomEvent("mapVisibilityOptionsChanged"));
}
}

View File

@@ -0,0 +1,31 @@
import { DivIcon, LatLngExpression, MarkerOptions } from "leaflet";
import { CustomMarker } from "./custommarker";
import { SVGInjector } from "@tanem/svg-injector";
import { getMap } from "..";
export class SmokeMarker extends CustomMarker {
#color: string;
constructor(latlng: LatLngExpression, color: string, options?: MarkerOptions) {
super(latlng, options);
this.setZIndexOffset(9999);
this.#color = color;
window.setTimeout(() => { this.removeFrom(getMap()); }, 300000) /* Remove the smoke after 5 minutes */
}
createIcon() {
this.setIcon(new DivIcon({
iconSize: [52, 52],
iconAnchor: [26, 52],
className: "leaflet-smoke-marker",
}));
var el = document.createElement("div");
el.classList.add("ol-smoke-icon");
el.setAttribute("data-color", this.#color);
var img = document.createElement("img");
img.src = "/resources/theme/images/markers/smoke.svg";
img.onload = () => SVGInjector(img);
el.appendChild(img);
this.getElement()?.appendChild(el);
}
}

View File

@@ -6,7 +6,7 @@ import { CustomMarker } from '../map/custommarker';
import { SVGInjector } from '@tanem/svg-injector';
import { UnitDatabase } from './unitdatabase';
import { TargetMarker } from '../map/targetmarker';
import { BOMBING, CARPET_BOMBING, DLINK, DataIndexes, FIRE_AT_AREA, GAME_MASTER, HIDE_GROUP_MEMBERS, IDLE, IRST, MOVE_UNIT, OPTIC, RADAR, ROEs, RWR, SHOW_CONTACT_LINES, SHOW_UNIT_PATHS, SHOW_UNIT_TARGETS, VISUAL, emissionsCountermeasures, reactionsToThreat, states } from '../constants/constants';
import { DLINK, DataIndexes, GAME_MASTER, HIDE_GROUP_MEMBERS, IDLE, IRST, MOVE_UNIT, OPTIC, RADAR, ROEs, RWR, SHOW_CONTACT_LINES, SHOW_UNIT_PATHS, SHOW_UNIT_TARGETS, VISUAL, emissionsCountermeasures, reactionsToThreat, states } from '../constants/constants';
import { Ammo, Contact, GeneralSettings, Offset, Radio, TACAN, ObjectIconOptions } from '../@types/unit';
import { DataExtractor } from '../server/dataextractor';
import { groundUnitDatabase } from './groundunitdatabase';
@@ -77,7 +77,7 @@ export class Unit extends CustomMarker {
};
#ammo: Ammo[] = [];
#contacts: Contact[] = [];
#activePath: LatLng[] = [];
#activePath: LatLng[] = [];
#isLeader: boolean = false;
#selectable: boolean;
@@ -95,43 +95,43 @@ export class Unit extends CustomMarker {
#hotgroup: number | null = null;
#detectionMethods: number[] = [];
getAlive() {return this.#alive};
getHuman() {return this.#human};
getControlled() {return this.#controlled};
getCoalition() {return this.#coalition};
getCountry() {return this.#country};
getName() {return this.#name};
getUnitName() {return this.#unitName};
getGroupName() {return this.#groupName};
getState() {return this.#state};
getTask() {return this.#task};
getHasTask() {return this.#hasTask};
getPosition() {return this.#position};
getSpeed() {return this.#speed};
getHeading() {return this.#heading};
getIsTanker() {return this.#isTanker};
getIsAWACS() {return this.#isAWACS};
getOnOff() {return this.#onOff};
getFollowRoads() {return this.#followRoads};
getFuel() {return this.#fuel};
getDesiredSpeed() {return this.#desiredSpeed};
getDesiredSpeedType() {return this.#desiredSpeedType};
getDesiredAltitude() {return this.#desiredAltitude};
getDesiredAltitudeType() {return this.#desiredAltitudeType};
getLeaderID() {return this.#leaderID};
getFormationOffset() {return this.#formationOffset};
getTargetID() {return this.#targetID};
getTargetPosition() {return this.#targetPosition};
getROE() {return this.#ROE};
getReactionToThreat() {return this.#reactionToThreat};
getEmissionsCountermeasures() {return this.#emissionsCountermeasures};
getTACAN() {return this.#TACAN};
getRadio() {return this.#radio};
getGeneralSettings() {return this.#generalSettings};
getAmmo() {return this.#ammo};
getContacts() {return this.#contacts};
getActivePath() {return this.#activePath};
getIsLeader() {return this.#isLeader};
getAlive() { return this.#alive };
getHuman() { return this.#human };
getControlled() { return this.#controlled };
getCoalition() { return this.#coalition };
getCountry() { return this.#country };
getName() { return this.#name };
getUnitName() { return this.#unitName };
getGroupName() { return this.#groupName };
getState() { return this.#state };
getTask() { return this.#task };
getHasTask() { return this.#hasTask };
getPosition() { return this.#position };
getSpeed() { return this.#speed };
getHeading() { return this.#heading };
getIsTanker() { return this.#isTanker };
getIsAWACS() { return this.#isAWACS };
getOnOff() { return this.#onOff };
getFollowRoads() { return this.#followRoads };
getFuel() { return this.#fuel };
getDesiredSpeed() { return this.#desiredSpeed };
getDesiredSpeedType() { return this.#desiredSpeedType };
getDesiredAltitude() { return this.#desiredAltitude };
getDesiredAltitudeType() { return this.#desiredAltitudeType };
getLeaderID() { return this.#leaderID };
getFormationOffset() { return this.#formationOffset };
getTargetID() { return this.#targetID };
getTargetPosition() { return this.#targetPosition };
getROE() { return this.#ROE };
getReactionToThreat() { return this.#reactionToThreat };
getEmissionsCountermeasures() { return this.#emissionsCountermeasures };
getTACAN() { return this.#TACAN };
getRadio() { return this.#radio };
getGeneralSettings() { return this.#generalSettings };
getAmmo() { return this.#ammo };
getContacts() { return this.#contacts };
getActivePath() { return this.#activePath };
getIsLeader() { return this.#isLeader };
static getConstructor(type: string) {
if (type === "GroundUnit") return GroundUnit;
@@ -157,7 +157,7 @@ export class Unit extends CustomMarker {
this.on('contextmenu', (e) => this.#onContextMenu(e));
this.on('mouseover', () => { if (this.belongsToCommandedCoalition()) this.setHighlighted(true); })
this.on('mouseout', () => { this.setHighlighted(false); })
getMap().on("zoomend", () => {this.#onZoom();})
getMap().on("zoomend", () => { this.#onZoom(); })
/* Deselect units if they are hidden */
document.addEventListener("toggleCoalitionVisibility", (ev: CustomEventInit) => {
@@ -166,13 +166,13 @@ export class Unit extends CustomMarker {
document.addEventListener("toggleUnitVisibility", (ev: CustomEventInit) => {
window.setTimeout(() => { this.setSelected(this.getSelected() && !this.getHidden()) }, 300);
});
});
document.addEventListener("mapVisibilityOptionsChanged", (ev: CustomEventInit) => {
this.#updateMarker();
if (this.getSelected())
this.drawLines();
});
});
}
getCategory() {
@@ -223,12 +223,12 @@ export class Unit extends CustomMarker {
case DataIndexes.radio: this.#radio = dataExtractor.extractRadio(); break;
case DataIndexes.generalSettings: this.#generalSettings = dataExtractor.extractGeneralSettings(); break;
case DataIndexes.ammo: this.#ammo = dataExtractor.extractAmmo(); break;
case DataIndexes.contacts: this.#contacts = dataExtractor.extractContacts(); document.dispatchEvent(new CustomEvent("contactsUpdated", {detail: this})); break;
case DataIndexes.contacts: this.#contacts = dataExtractor.extractContacts(); document.dispatchEvent(new CustomEvent("contactsUpdated", { detail: this })); break;
case DataIndexes.activePath: this.#activePath = dataExtractor.extractActivePath(); break;
case DataIndexes.isLeader: this.#isLeader = dataExtractor.extractBool(); break;
}
}
/* Dead units can't be selected */
this.setSelected(this.getSelected() && this.#alive && !this.getHidden())
@@ -323,7 +323,7 @@ export class Unit extends CustomMarker {
/* Only alive units can be selected. Some units are not selectable (weapons) */
if ((this.#alive || !selected) && this.getSelectable() && this.getSelected() != selected && this.belongsToCommandedCoalition()) {
this.#selected = selected;
if (selected) {
document.dispatchEvent(new CustomEvent("unitSelection", { detail: this }));
this.#updateMarker();
@@ -342,7 +342,7 @@ export class Unit extends CustomMarker {
else
this.#updateMarker();
}
}
}
@@ -386,7 +386,7 @@ export class Unit extends CustomMarker {
belongsToCommandedCoalition() {
if (getMissionHandler().getCommandModeOptions().commandMode !== GAME_MASTER && getMissionHandler().getCommandedCoalition() !== this.#coalition)
return false;
return true;
return true;
}
getType() {
@@ -434,7 +434,15 @@ export class Unit extends CustomMarker {
var unitIcon = document.createElement("div");
unitIcon.classList.add("unit-icon");
var img = document.createElement("img");
img.src = `/resources/theme/images/units/${this.getMarkerCategory()}.svg`;
var imgSrc;
/* If a unit does not belong to the commanded coalition or it is not visually detected, show it with the generic aircraft square */
if (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC].includes(value)))
imgSrc = this.getMarkerCategory();
else
imgSrc = "aircraft";
img.src = `/resources/theme/images/units/${imgSrc}.svg`;
img.onload = () => SVGInjector(img);
unitIcon.appendChild(img);
unitIcon.toggleAttribute("data-rotate-to-heading", iconOptions.rotateToHeading);
@@ -499,12 +507,12 @@ export class Unit extends CustomMarker {
updateVisibility() {
const hiddenUnits = getUnitsManager().getHiddenTypes();
var hidden = ((this.#human && hiddenUnits.includes("human")) ||
(this.#controlled == false && hiddenUnits.includes("dcs")) ||
(hiddenUnits.includes(this.getMarkerCategory())) ||
(hiddenUnits.includes(this.#coalition)) ||
(!this.belongsToCommandedCoalition() && (this.#detectionMethods.length == 0 || (this.#detectionMethods.length == 1 && this.#detectionMethods[0] === RWR))) ||
(getMap().getVisibilityOptions()[HIDE_GROUP_MEMBERS] && !this.#isLeader && this.getCategory() == "GroundUnit" && getMap().getZoom() < 13 && (this.belongsToCommandedCoalition() || (!this.belongsToCommandedCoalition() && this.#detectionMethods.length == 0)))) &&
!(this.getSelected());
(this.#controlled == false && hiddenUnits.includes("dcs")) ||
(hiddenUnits.includes(this.getMarkerCategory())) ||
(hiddenUnits.includes(this.#coalition)) ||
(!this.belongsToCommandedCoalition() && (this.#detectionMethods.length == 0 || (this.#detectionMethods.length == 1 && this.#detectionMethods[0] === RWR))) ||
(getMap().getVisibilityOptions()[HIDE_GROUP_MEMBERS] && !this.#isLeader && this.getCategory() == "GroundUnit" && getMap().getZoom() < 13 && (this.belongsToCommandedCoalition() || (!this.belongsToCommandedCoalition() && this.#detectionMethods.length == 0)))) &&
!(this.getSelected());
this.setHidden(hidden || !this.#alive);
}
@@ -514,9 +522,9 @@ export class Unit extends CustomMarker {
/* Add the marker if not present */
if (!getMap().hasLayer(this) && !this.getHidden()) {
if (getMap().isZooming())
this.once("zoomend", () => {this.addTo(getMap())})
else
if (getMap().isZooming())
this.once("zoomend", () => { this.addTo(getMap()) })
else
this.addTo(getMap());
}
@@ -559,10 +567,22 @@ export class Unit extends CustomMarker {
return loadouts.some((loadout: LoadoutBlueprint) => {
return (roles as string[]).some((role: string) => { return loadout.roles.includes(role) });
});
} else
} else
return false;
}
isInViewport() {
const mapBounds = getMap().getBounds();
const unitPos = this.getPosition();
return (unitPos.lng > mapBounds.getWest()
&& unitPos.lng < mapBounds.getEast()
&& unitPos.lat > mapBounds.getSouth()
&& unitPos.lat < mapBounds.getNorth());
}
/********************** Unit commands *************************/
addDestination(latlng: L.LatLng) {
if (!this.#human) {
@@ -704,24 +724,28 @@ export class Unit extends CustomMarker {
#onClick(e: any) {
if (!this.#preventClick) {
if (getMap().getState() === IDLE || getMap().getState() === MOVE_UNIT || e.originalEvent.ctrlKey) {
if (!e.originalEvent.ctrlKey)
if (!e.originalEvent.ctrlKey)
getUnitsManager().deselectAllUnits();
this.setSelected( !this.getSelected() );
if ( this.getSelected() ) {
document.dispatchEvent( new CustomEvent( "unitSelection", { "detail": this }));
} else {
document.dispatchEvent( new CustomEvent( "unitDeselection", { "detail": this }));
}
this.setSelected(!this.getSelected());
const detail = { "detail": { "unit": this } };
if (this.getSelected())
document.dispatchEvent(new CustomEvent("unitSelected", detail));
else
document.dispatchEvent(new CustomEvent("unitDeselection", { "detail": this }));
}
}
this.#timer = window.setTimeout(() => {
this.#preventClick = false;
}, 200);
this.#timer = window.setTimeout(() => { this.#preventClick = false; }, 200);
}
#onDoubleClick(e: any) {
const unitsManager = getUnitsManager();
Object.values(unitsManager.getUnits()).forEach((unit: Unit) => {
if (unit.getAlive() === true && unit.getName() === this.getName() && unit.isInViewport())
unitsManager.selectUnit(unit.ID, false);
});
clearTimeout(this.#timer);
this.#preventClick = true;
}
@@ -744,23 +768,6 @@ export class Unit extends CustomMarker {
}
}
if ((selectedUnits.length === 0 && this.getCategory() == "Aircraft") || (selectedUnitTypes.length === 1 && ["Aircraft"].includes(selectedUnitTypes[0]))) {
if (selectedUnits.concat([this]).every((unit: Unit) => { return unit.canFulfillRole(["CAS", "Strike"]) })) {
options["bomb"] = { text: "Precision bombing", tooltip: "Precision bombing of a specific point" };
options["carpet-bomb"] = { text: "Carpet bombing", tooltip: "Carpet bombing close to a point" };
}
}
if ((selectedUnits.length === 0 && this.getCategory() == "GroundUnit") || selectedUnitTypes.length === 1 && ["GroundUnit"].includes(selectedUnitTypes[0])) {
if (selectedUnits.concat([this]).every((unit: Unit) => { return ["Gun Artillery", "Rocket Artillery", "Infantry", "IFV", "Tank"].includes(this.getType()) }))
options["fire-at-area"] = { text: "Fire at area", tooltip: "Fire at a large area" };
}
if ((selectedUnits.length === 0 && this.getCategory() == "NavyUnit") || selectedUnitTypes.length === 1 && ["NavyUnit"].includes(selectedUnitTypes[0])) {
if (selectedUnits.concat([this]).every((unit: Unit) => { return ["Cruiser", "Destroyer", "Frigate"].includes(this.getType()) }))
options["fire-at-area"] = { text: "Fire at area", tooltip: "Fire at a large area" };
}
if (selectedUnitTypes.length === 1 && ["NavyUnit", "GroundUnit"].includes(selectedUnitTypes[0]) && getUnitsManager().getSelectedUnitsVariable((unit: Unit) => {return unit.getCoalition()}) !== undefined)
options["group"] = { text: "Create group", tooltip: "Create a group from the selected units." };
@@ -783,14 +790,7 @@ export class Unit extends CustomMarker {
else if (action === "group")
getUnitsManager().selectedUnitsCreateGroup();
else if (action === "follow")
this.#showFollowOptions(e);
else if (action === "bomb")
getMap().setState(BOMBING);
else if (action === "carpet-bomb")
getMap().setState(CARPET_BOMBING);
else if (action === "fire-at-area")
getMap().setState(FIRE_AT_AREA);
this.#showFollowOptions(e);
}
#showFollowOptions(e: any) {
@@ -811,7 +811,7 @@ export class Unit extends CustomMarker {
getMap().hideUnitContextMenu();
this.#applyFollowOptions(option);
});
getMap().showUnitContextMenu(e.originalEvent.x, e.originalEvent.y, e.latlng);
}
@@ -1092,16 +1092,17 @@ export class Unit extends CustomMarker {
export class AirUnit extends Unit {
getIconOptions() {
var belongsToCommandedCoalition = this.belongsToCommandedCoalition();
return {
showState: this.belongsToCommandedCoalition(),
showVvi: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showHotgroup: this.belongsToCommandedCoalition(),
showUnitIcon: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showShortLabel: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC].includes(value))),
showFuel: this.belongsToCommandedCoalition(),
showAmmo: this.belongsToCommandedCoalition(),
showSummary: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showCallsign: this.belongsToCommandedCoalition(),
showState: belongsToCommandedCoalition,
showVvi: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showHotgroup: belongsToCommandedCoalition,
showUnitIcon: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showShortLabel: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC].includes(value))),
showFuel: belongsToCommandedCoalition,
showAmmo: belongsToCommandedCoalition,
showSummary: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showCallsign: belongsToCommandedCoalition,
rotateToHeading: false
};
}
@@ -1133,16 +1134,17 @@ export class GroundUnit extends Unit {
}
getIconOptions() {
var belongsToCommandedCoalition = this.belongsToCommandedCoalition();
return {
showState: this.belongsToCommandedCoalition(),
showState: belongsToCommandedCoalition,
showVvi: false,
showHotgroup: this.belongsToCommandedCoalition(),
showUnitIcon: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showHotgroup: belongsToCommandedCoalition,
showUnitIcon: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showShortLabel: false,
showFuel: false,
showAmmo: false,
showSummary: false,
showCallsign: this.belongsToCommandedCoalition(),
showCallsign: belongsToCommandedCoalition,
rotateToHeading: false
};
}
@@ -1153,7 +1155,7 @@ export class GroundUnit extends Unit {
getType() {
var blueprint = groundUnitDatabase.getByName(this.getName());
return blueprint?.type? blueprint.type: "";
return blueprint?.type ? blueprint.type : "";
}
}
@@ -1163,16 +1165,17 @@ export class NavyUnit extends Unit {
}
getIconOptions() {
var belongsToCommandedCoalition = this.belongsToCommandedCoalition();
return {
showState: this.belongsToCommandedCoalition(),
showState: belongsToCommandedCoalition,
showVvi: false,
showHotgroup: true,
showUnitIcon: (this.belongsToCommandedCoalition() || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showUnitIcon: (belongsToCommandedCoalition || this.getDetectionMethods().some(value => [VISUAL, OPTIC, RADAR, IRST, DLINK].includes(value))),
showShortLabel: false,
showFuel: false,
showAmmo: false,
showSummary: false,
showCallsign: this.belongsToCommandedCoalition(),
showCallsign: belongsToCommandedCoalition,
rotateToHeading: false
};
}
@@ -1187,6 +1190,6 @@ export class NavyUnit extends Unit {
getType() {
var blueprint = navyUnitDatabase.getByName(this.getName());
return blueprint?.type? blueprint.type: "";
return blueprint?.type ? blueprint.type : "";
}
}