diff --git a/.gitignore b/.gitignore index 6c3d373..c6ca7b9 100644 --- a/.gitignore +++ b/.gitignore @@ -15,5 +15,14 @@ Generator/utils/extract units/units.txt generator.log templates/Scenarios/user templates/Scenarios/downloaded +templates/Imports/user +templates/Imports/downloaded +templates/Forces/user +templates/Forces/downloaded config/user-data.yaml *.exe +config/user-data.yaml +server/user-files/modules/mapscript-sql.py +distribution/ +MissionOutput/ + diff --git a/Generator/MissionGenerator.py b/Generator/MissionGenerator.py index 1633467..89ab13e 100644 --- a/Generator/MissionGenerator.py +++ b/Generator/MissionGenerator.py @@ -2,6 +2,7 @@ import json import yaml import sys import os +import operator import RotorOpsMission as ROps import RotorOpsUnits @@ -28,10 +29,18 @@ import qtmodern.windows # UPDATE BUILD VERSION maj_version = 1 -minor_version = 1 -patch_version = 2 +minor_version = 2 +patch_version = 0 + +modules_version = 2 +modules_url = 'https://dcs-helicopters.com/user-files/modules/' +version_url = 'https://dcs-helicopters.com/app-updates/versions.yaml' +modules_map_url = 'https://dcs-helicopters.com/user-files/modules/module-map-v2.yaml' +ratings_url = 'https://dcs-helicopters.com/user-files/ratings.php' +allowed_paths = ['templates\\Scenarios\\downloaded', 'templates\\Forces\\downloaded', 'templates\\Imports\\downloaded'] user_files_url = 'https://dcs-helicopters.com/user-files/' +version_url = 'https://dcs-helicopters.com/app-updates/versioncheck.yaml' #Setup logfile and exception handler logger = logging.getLogger(__name__) @@ -50,27 +59,39 @@ class directories: os.chdir("..") cls.home_dir = os.getcwd() cls.scenarios = cls.home_dir + "\\templates\\Scenarios" - cls.forces = cls.home_dir + "\\templates\\Forces" + cls.forces_downloaded = cls.home_dir + "\\templates\\Forces\\downloaded" + cls.forces_user = cls.home_dir + "\\templates\\Forces\\user" cls.scripts = cls.home_dir + "\\scripts" cls.sound = cls.home_dir + "\\sound\\embedded" cls.output = cls.home_dir + "\\MissionOutput" cls.assets = cls.home_dir + "\\assets" - cls.imports = cls.home_dir + "\\templates\\Imports" + cls.imports_downloaded = cls.home_dir + "\\templates\\Imports\\downloaded" + cls.imports_user = cls.home_dir + "\\templates\\Imports\\user" cls.user_datafile_path = cls.home_dir + "\\config\\user-data.yaml" cls.scenarios_downloaded = cls.scenarios + "\\downloaded" cls.scenarios_user = cls.scenarios + "\\user" cls.default_config = cls.home_dir + '\\config\\default-config.yaml' os.chdir(current_dir) -directories.find() + @classmethod + def createDirectories(cls): + required_dirs = [cls.scenarios_user, cls.scenarios_downloaded, cls.imports_user, cls.imports_downloaded, cls.forces_user, cls.forces_downloaded, cls.output] + for path in required_dirs: + if not os.path.exists(path): + os.makedirs(path) -import MissionGeneratorScenario + +directories.find() +directories.createDirectories() + +import MissionGeneratorTemplates def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): #example of handling error subclasses sys.__excepthook__(exc_type, exc_value, exc_traceback) return + QApplication.restoreOverrideCursor() logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) msg = QMessageBox() msg.setWindowTitle("Uncaught exception") @@ -82,9 +103,6 @@ sys.excepthook = handle_exception version_string = str(maj_version) + "." + str(minor_version) + "." + str(patch_version) -# scenarios = [] -red_forces_files = [] -blue_forces_files = [] defenders_text = "Defending Forces:" attackers_text = "Attacking Forces:" ratings_json = None @@ -120,16 +138,17 @@ class Window(QMainWindow, Ui_MainWindow): self.player_slots = [] self.user_output_dir = None self.user_data = None + self.forces_list = [] + self.imports_list = [] self.user_data = self.loadUserData() - self.m = ROps.RotorOpsMission() self.setupUi(self) self.connectSignalsSlots() self.populateScenarios() - self.populateForces("red", self.redforces_comboBox, red_forces_files) - self.populateForces("blue", self.blueforces_comboBox, blue_forces_files) + self.populateForces() self.populateSlotSelection() + self.getImports() # self.blue_forces_label.setText(attackers_text) # self.red_forces_label.setText(defenders_text) @@ -139,11 +158,15 @@ class Window(QMainWindow, Ui_MainWindow): "QStatusBar{padding-left:5px;}") self.version_label.setText("Version " + version_string) + self.scenarioChanged() - - - - + self.time_comboBox.addItem("Default Time") + self.time_comboBox.addItem("Day") + self.time_comboBox.addItem("Night") + self.time_comboBox.addItem("Dusk") + self.time_comboBox.addItem("Dawn") + self.time_comboBox.addItem("Noon") + self.time_comboBox.addItem("Random") def connectSignalsSlots(self): @@ -212,7 +235,7 @@ class Window(QMainWindow, Ui_MainWindow): basename = filename.removesuffix('.miz') mizpath = os.path.join(path, folder, filename) # create scenario object - s = MissionGeneratorScenario.Scenario(mizpath, basename) + s = MissionGeneratorTemplates.Scenario(mizpath, basename) #apply some properties if found in the downloads directory if path == directories.scenarios_downloaded: @@ -221,7 +244,6 @@ class Window(QMainWindow, Ui_MainWindow): s.packageID = folder if ratings_json: - print(ratings_json) for module in ratings_json: if module['package'] == folder: s.rating = module["avg_rating"] @@ -256,8 +278,8 @@ class Window(QMainWindow, Ui_MainWindow): t_scenarios.append(s) scenarios = t_scenarios.copy() - #self.scenario_comboBox.addItem(s.name) - self.scenarios_list = scenarios.copy() + self.scenarios_list = sorted(scenarios, key=lambda x: x.name, reverse=False) + for s in self.scenarios_list: self.scenario_comboBox.addItem(s.name) @@ -268,18 +290,67 @@ class Window(QMainWindow, Ui_MainWindow): self.populateScenarios() # self.scenarioChanged() haven't tried yet - def populateForces(self, side, combobox, files_list): - os.chdir(directories.home_dir) - # os.chdir(directories.forces + "/" + side) - os.chdir(directories.forces) - path = os.getcwd() - dir_list = os.listdir(path) - logger.info("Looking for " + side + " Forces files in '" + path) + def populateForces(self): + self.forces_list = [] - for filename in dir_list: - if filename.endswith(".miz"): - files_list.append(filename) - combobox.addItem(filename.removesuffix('.miz')) + for path in [directories.forces_downloaded, directories.forces_user]: + logger.info("Looking for forces files in " + path) + os.chdir(path) + module_folders = next(os.walk('.'))[1] + + for folder in module_folders: + for filename in os.listdir(folder): + if filename.endswith(".miz"): + basename = filename.removesuffix('.miz') + mizpath = os.path.join(path, folder, filename) + config_file_path = os.path.join(path, folder, basename + '.yaml') + if os.path.exists(config_file_path): + # create forces object with config + try: + config = yaml.safe_load(open(config_file_path)) + f = MissionGeneratorTemplates.Forces(mizpath, filename, config) + self.forces_list.append(f) + except: + logger.error("Error in " + config_file_path) + + else: + # create forces object without config + f = MissionGeneratorTemplates.Forces(mizpath, basename) + self.forces_list.append(f) + + self.forces_list = sorted(self.forces_list, key=lambda x: x.name, reverse=False) + + for forces in self.forces_list: + self.redforces_comboBox.addItem(forces.name) + self.blueforces_comboBox.addItem(forces.name) + + def getImports(self): + self.imports_list = [] + + for path in [directories.imports_downloaded, directories.imports_user]: + logger.info("Looking for imports files in " + path) + os.chdir(path) + module_folders = next(os.walk('.'))[1] + + for folder in module_folders: + for filename in os.listdir(folder): + if filename.endswith(".miz"): + basename = filename.removesuffix('.miz') + mizpath = os.path.join(path, folder, filename) + config_file_path = os.path.join(path, folder, basename + '.yaml') + if os.path.exists(config_file_path): + # create imports object with config + try: + config = yaml.safe_load(config_file_path) + f = MissionGeneratorTemplates.Import(mizpath, filename, config) + self.imports_list.append(f) + except: + logger.error("Error in " + config_file_path) + + else: + # create imports object without config + f = MissionGeneratorTemplates.Import(mizpath, filename) + self.imports_list.append(f) def populateSlotSelection(self): self.slot_template_comboBox.addItem("Multiple Slots") @@ -321,8 +392,7 @@ class Window(QMainWindow, Ui_MainWindow): # reset some UI elements self.defense_checkBox.setEnabled(True) - if self.lockedSlot(): - self.slot_template_comboBox.removeItem(self.lockedSlot()) + self.slot_template_comboBox.removeItem(self.lockedSlot()) self.slot_template_comboBox.setEnabled(True) self.slot_template_comboBox.setCurrentIndex(0) @@ -362,11 +432,14 @@ class Window(QMainWindow, Ui_MainWindow): button.setEnabled(True) if 'blue_forces' in config: - self.blueforces_comboBox.setCurrentIndex(self.blueforces_comboBox.findText(config['blue_forces'])) + for template in self.forces_list: + if template.basename == config['blue_forces']: + self.blueforces_comboBox.setCurrentIndex(self.blueforces_comboBox.findText(template.name)) if 'red_forces' in config: - if self.redforces_comboBox.findText(config['red_forces']) >= 0: - self.redforces_comboBox.setCurrentIndex(self.redforces_comboBox.findText(config['red_forces'])) + for template in self.forces_list: + if template.basename == config['red_forces']: + self.redforces_comboBox.setCurrentIndex(self.redforces_comboBox.findText(template.name)) except Exception as e: logger.error("Error loading config file: " + str(e)) @@ -416,16 +489,16 @@ class Window(QMainWindow, Ui_MainWindow): return QApplication.setOverrideCursor(Qt.WaitCursor) + self.slot_template_comboBox.setCurrentIndex(0) self.scenario = self.scenarios_list[self.scenario_comboBox.currentIndex()] + # reset generator options to default + default_config = self.loadScenarioConfig(directories.default_config) + self.applyScenarioConfig(default_config) + if self.scenario.config: self.applyScenarioConfig(self.scenario.config) - self.m.setConfig(self.scenario.config) - else: - default_config = self.loadScenarioConfig(directories.default_config) - self.applyScenarioConfig(default_config) - self.m.setConfig(default_config) path = self.scenario.path.removesuffix(".miz") + ".jpg" if os.path.isfile(path): @@ -462,17 +535,27 @@ class Window(QMainWindow, Ui_MainWindow): def generateMissionAction(self): QApplication.setOverrideCursor(Qt.WaitCursor) - red_forces_filename = red_forces_files[self.redforces_comboBox.currentIndex()] - blue_forces_filename = blue_forces_files[self.blueforces_comboBox.currentIndex()] + red_forces = self.forces_list[self.redforces_comboBox.currentIndex()] + blue_forces = self.forces_list[self.blueforces_comboBox.currentIndex()] scenario_name = self.scenario.name scenario_path = self.scenario.path - source = "offline" + + credits = ("'" + scenario_name + "' mission template by " + self.scenario.author + "\n" + + "'" + red_forces.name + "' by " + red_forces.author + "\n" + + "'" + blue_forces.name + "' by " + blue_forces.author + "\n" + ) + + objects = { + "imports": self.imports_list, + } + data = { - "source": source, + "objects": objects, + "credits": credits, "scenario_file": scenario_path, "scenario_name": scenario_name, - "red_forces_filename": red_forces_filename, - "blue_forces_filename": blue_forces_filename, + "red_forces_path": red_forces.path, + "blue_forces_path": blue_forces.path, "red_quantity": self.redqty_spinBox.value(), "blue_quantity": self.blueqty_spinBox.value(), "inf_spawn_qty": self.inf_spawn_spinBox.value(), @@ -483,7 +566,7 @@ class Window(QMainWindow, Ui_MainWindow): "f_awacs": self.awacs_checkBox.isChecked(), "f_tankers": self.tankers_checkBox.isChecked(), "voiceovers": self.voiceovers_checkBox.isChecked(), - "force_offroad": self.force_offroad_checkBox.isChecked(), + "force_offroad": self.scenario.getConfigValue("force_offroad", default=False), "game_display": self.game_status_checkBox.isChecked(), "defending": self.defense_checkBox.isChecked(), "slots": self.slot_template_comboBox.currentText(), @@ -494,6 +577,17 @@ class Window(QMainWindow, Ui_MainWindow): "smoke_pickup_zones": self.smoke_pickup_zone_checkBox.isChecked(), "player_slots": self.player_slots, "player_hotstart": self.hotstart_checkBox.isChecked(), + "random_weather": self.random_weather_checkBox.isChecked(), + "time": self.time_comboBox.currentText(), + "start_trigger": self.scenario.getConfigValue("start_trigger", default=True), + "end_trigger": self.scenario.getConfigValue("end_trigger", default=True), + "farp_spawns": self.farp_spawn_checkBox.isChecked(), + "staging_logistics_file": self.scenario.getConfigValue("staging_logistics_file", default=None), + "zone_farp_file": self.scenario.getConfigValue("zone_farp_file", default=None), + "defensive_farp_file": self.scenario.getConfigValue("defensive_farp_file", default=None), + "logistics_farp_file": self.scenario.getConfigValue("logistics_farp_file", default=None), + "zone_protect_file": self.scenario.getConfigValue("zone_protect_file", default=None), + "script": self.scenario.getConfigValue("script", default=None), } logger.info("Generating mission with options:") @@ -674,7 +768,7 @@ class Window(QMainWindow, Ui_MainWindow): def checkVersion(splashscreen): - version_url = 'https://dcs-helicopters.com/app-updates/versioncheck.yaml' + try: r = requests.get(version_url, allow_redirects=False, timeout=7) v = yaml.safe_load(r.content) @@ -693,31 +787,33 @@ def checkVersion(splashscreen): -modules_url = 'https://dcs-helicopters.com/user-files/modules/' -version_url = 'https://dcs-helicopters.com/app-updates/versions.yaml' -modules_map_url = 'https://dcs-helicopters.com/user-files/modules/module-map.yaml' -ratings_url = 'https://dcs-helicopters.com/user-files/ratings.php' - def loadModules(splashscreen): + msg = QMessageBox() + msg.setWindowTitle("Unable to connect to server") + msg.setText( + "We were unable to connect to the RotorOps server to download content. This is a temporary problem, so please try again later. If the problem persists, please get in touch via Discord.") try: r = requests.get(modules_map_url, allow_redirects=False, timeout=7) if not r.status_code == 200: logger.error("Could not retrieve the modules map.") + x = msg.exec_() return except: logger.error("Failed to retrieve module map.") + x = msg.exec_() return module_list = yaml.safe_load(r.content) files_success = [] files_failed = [] - new_scenarios = [] - updated_scenarios = [] + new_modules = [] + updated_modules = [] + outversioned_modules = [] # Download scenarios files - #os.chdir(directories.scenarios) + if module_list: for module in module_list: @@ -725,15 +821,31 @@ def loadModules(splashscreen): should_download = False new_module = False + # only allow predefined paths + dp = module_list[module]["path"] + if dp not in allowed_paths: + logger.warning("Invalid path for module: " + module) + continue + # check if local version already exists - package_file_path = os.path.join(directories.scenarios_downloaded, module, "package.yaml") + package_file_path = os.path.join(directories.home_dir, module_list[module]["path"], module, "package.yaml") if os.path.exists(package_file_path): pkg_file = yaml.safe_load(open(package_file_path)) else: pkg_file = None - #compare local and remote versions + # compare required generator version and actual version + if 'requires' in module_list[module]: + if module_list[module]['requires'] > modules_version: + name = 'unknown module' + if 'name' in module_list[module]: + name = module_list[module]['name'] + outversioned_modules.append(name) + continue + + + # compare local and remote versions if pkg_file and 'version' in pkg_file: local_version = pkg_file['version'] @@ -744,6 +856,20 @@ def loadModules(splashscreen): should_download = True new_module = True + # delete modules with 'remove' dist property + if 'dist' in module_list[module] and module_list[module]['dist'] == 'remove': + for filename in module_list[module]["files"]: + module_dir = os.path.join(directories.home_dir, module_list[module]["path"], module) + file_path = os.path.join(module_dir, filename) + if os.path.exists(file_path): + try: + os.remove(file_path) + print("Removed module file: " + filename) + except: + logger.error("Error while trying to remove " + filename) + continue + + # download files if should_download: logger.info("Updating module: " + module) module_dir = os.path.join(directories.home_dir, module_list[module]["path"], module) @@ -751,10 +877,11 @@ def loadModules(splashscreen): # download files in remote package for filename in module_list[module]["files"]: broken_file = False + type_path = module_list[module]["type"] splash.showMessage("Downloading " + filename + " ...", Qt.AlignHCenter | Qt.AlignTop, Qt.white) app.processEvents() - url = modules_url + module + "/" + filename + url = modules_url + type_path + "/" + module + "/" + filename try: r = requests.get(url, allow_redirects=False, timeout=10) except: @@ -771,9 +898,9 @@ def loadModules(splashscreen): # do some stuff for the dialog popup if filename.endswith('.miz') and "name" in module_list[module]: if new_module: - new_scenarios.append(module_list[module]["name"]) + new_modules.append(module_list[module]["name"]) else: - updated_scenarios.append(module_list[module]["name"]) + updated_modules.append(module_list[module]["name"]) else: broken_file = True files_failed.append(filename) @@ -791,7 +918,7 @@ def loadModules(splashscreen): logger.error("Problem encountered with modules map.") # show a popup if we downloaded any packages - if len(files_success) > 0 or len(files_failed) > 0: + if len(files_success) > 0 or len(files_failed) > 0 or len(outversioned_modules) > 0: if len(files_failed) > 0: fs = "" for filename in files_failed: @@ -800,16 +927,18 @@ def loadModules(splashscreen): msg = QMessageBox() msg.setWindowTitle("Downloaded Files") message = "" - if len(new_scenarios) > 0: - message = message + "New scenarios added: \n\n" - for name in new_scenarios: + if len(new_modules) > 0: + message = message + "New modules added: \n\n" + for name in new_modules: message = message + name + "\n" - if len(updated_scenarios) > 0: - message = message + "\nScenarios updated: \n" - for name in updated_scenarios: + if len(updated_modules) > 0: + message = message + "\nModules updated: \n" + for name in updated_modules: message = message + name + "\n" if len(files_failed) > 0: message = message + "\n\n" + str(len(files_failed)) + " files failed." + if len(outversioned_modules) > 0: + message = message + "\n\n" + str(len(outversioned_modules)) + " modules did not download because you need an required update." msg.setText(message) x = msg.exec_() else: diff --git a/Generator/MissionGeneratorScenario.py b/Generator/MissionGeneratorTemplates.py similarity index 79% rename from Generator/MissionGeneratorScenario.py rename to Generator/MissionGeneratorTemplates.py index 90a2a0e..d071414 100644 --- a/Generator/MissionGeneratorScenario.py +++ b/Generator/MissionGeneratorTemplates.py @@ -19,6 +19,8 @@ class Scenario: self.rating_qty = None self.packageID = None self.local_rating = None + self.author = "unknown" + def applyConfig(self, config): self.config = config @@ -31,8 +33,16 @@ class Scenario: if 'tags' in config: for tag in config['tags']: self.tags.append(tag) + if 'author' in config: + self.author = config["author"] + def getConfigValue(self, key, default): + if self.config and key in self.config: + return self.config[key] + else: + return default + def evaluateMiz(self): # check if we have the miz file @@ -116,3 +126,35 @@ class Scenario: +class Forces: + + def __init__(self, path, filename, config=None): + self.path = path + self.filename = filename + self.basename = filename.removesuffix('.miz') + self.name = filename.removesuffix('.miz') + self.author = "unknown" + + + if config: + if 'name' in config: + self.name = config["name"] + + if 'author' in config: + self.author = config["author"] + +class Import: + + def __init__(self, path, filename, config=None): + self.path = path + self.filename = filename + self.name = filename.removesuffix('.miz') + self.author = "unknown" + + + if config: + if 'name' in config: + self.name = config["name"] + + if 'author' in config: + self.author = config["author"] diff --git a/Generator/MissionGeneratorUI.py b/Generator/MissionGeneratorUI.py index 41fc35e..2a2dacf 100644 --- a/Generator/MissionGeneratorUI.py +++ b/Generator/MissionGeneratorUI.py @@ -34,7 +34,7 @@ class Ui_MainWindow(object): self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.logistics_crates_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.logistics_crates_checkBox.setGeometry(QtCore.QRect(990, 211, 251, 28)) + self.logistics_crates_checkBox.setGeometry(QtCore.QRect(980, 211, 251, 28)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -42,7 +42,7 @@ class Ui_MainWindow(object): self.logistics_crates_checkBox.setChecked(True) self.logistics_crates_checkBox.setObjectName("logistics_crates_checkBox") self.zone_sams_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.zone_sams_checkBox.setGeometry(QtCore.QRect(990, 320, 241, 28)) + self.zone_sams_checkBox.setGeometry(QtCore.QRect(980, 320, 241, 28)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -79,9 +79,9 @@ class Ui_MainWindow(object): self.description_textBrowser.setObjectName("description_textBrowser") self.defense_checkBox = QtWidgets.QCheckBox(self.centralwidget) self.defense_checkBox.setEnabled(True) - self.defense_checkBox.setGeometry(QtCore.QRect(470, 120, 156, 28)) + self.defense_checkBox.setGeometry(QtCore.QRect(470, 130, 156, 28)) font = QtGui.QFont() - font.setPointSize(10) + font.setPointSize(11) font.setBold(False) self.defense_checkBox.setFont(font) self.defense_checkBox.setCheckable(True) @@ -116,7 +116,7 @@ class Ui_MainWindow(object): self.scenario_label_8.setFont(font) self.scenario_label_8.setObjectName("scenario_label_8") self.slot_template_comboBox = QtWidgets.QComboBox(self.centralwidget) - self.slot_template_comboBox.setGeometry(QtCore.QRect(960, 384, 271, 33)) + self.slot_template_comboBox.setGeometry(QtCore.QRect(980, 474, 271, 33)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -216,7 +216,7 @@ class Ui_MainWindow(object): self.e_attack_helos_spinBox.setKeyboardTracking(True) self.e_attack_helos_spinBox.setMinimum(0) self.e_attack_helos_spinBox.setMaximum(8) - self.e_attack_helos_spinBox.setProperty("value", 2) + self.e_attack_helos_spinBox.setProperty("value", 1) self.e_attack_helos_spinBox.setObjectName("e_attack_helos_spinBox") self.scenario_label_7 = QtWidgets.QLabel(self.centralwidget) self.scenario_label_7.setGeometry(QtCore.QRect(570, 180, 271, 24)) @@ -226,20 +226,20 @@ class Ui_MainWindow(object): self.scenario_label_7.setFont(font) self.scenario_label_7.setObjectName("scenario_label_7") self.label_2 = QtWidgets.QLabel(self.centralwidget) - self.label_2.setGeometry(QtCore.QRect(840, 390, 111, 24)) + self.label_2.setGeometry(QtCore.QRect(860, 480, 111, 24)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.scenario_label_9 = QtWidgets.QLabel(self.centralwidget) - self.scenario_label_9.setGeometry(QtCore.QRect(490, 450, 251, 23)) + self.scenario_label_9.setGeometry(QtCore.QRect(480, 401, 251, 23)) font = QtGui.QFont() font.setPointSize(10) self.scenario_label_9.setFont(font) self.scenario_label_9.setObjectName("scenario_label_9") self.awacs_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.awacs_checkBox.setGeometry(QtCore.QRect(990, 246, 241, 28)) + self.awacs_checkBox.setGeometry(QtCore.QRect(980, 246, 241, 28)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -247,7 +247,7 @@ class Ui_MainWindow(object): self.awacs_checkBox.setChecked(True) self.awacs_checkBox.setObjectName("awacs_checkBox") self.tankers_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.tankers_checkBox.setGeometry(QtCore.QRect(990, 282, 241, 28)) + self.tankers_checkBox.setGeometry(QtCore.QRect(980, 282, 241, 28)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -255,21 +255,21 @@ class Ui_MainWindow(object): self.tankers_checkBox.setChecked(True) self.tankers_checkBox.setObjectName("tankers_checkBox") self.voiceovers_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.voiceovers_checkBox.setGeometry(QtCore.QRect(960, 517, 171, 24)) + self.voiceovers_checkBox.setGeometry(QtCore.QRect(500, 594, 171, 31)) font = QtGui.QFont() font.setPointSize(9) self.voiceovers_checkBox.setFont(font) self.voiceovers_checkBox.setChecked(True) self.voiceovers_checkBox.setObjectName("voiceovers_checkBox") self.smoke_pickup_zone_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.smoke_pickup_zone_checkBox.setGeometry(QtCore.QRect(960, 460, 271, 24)) + self.smoke_pickup_zone_checkBox.setGeometry(QtCore.QRect(500, 541, 231, 20)) font = QtGui.QFont() font.setPointSize(9) self.smoke_pickup_zone_checkBox.setFont(font) self.smoke_pickup_zone_checkBox.setChecked(False) self.smoke_pickup_zone_checkBox.setObjectName("smoke_pickup_zone_checkBox") self.game_status_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.game_status_checkBox.setGeometry(QtCore.QRect(960, 490, 271, 24)) + self.game_status_checkBox.setGeometry(QtCore.QRect(500, 570, 221, 21)) font = QtGui.QFont() font.setPointSize(9) self.game_status_checkBox.setFont(font) @@ -277,24 +277,24 @@ class Ui_MainWindow(object): self.game_status_checkBox.setTristate(False) self.game_status_checkBox.setObjectName("game_status_checkBox") self.label = QtWidgets.QLabel(self.centralwidget) - self.label.setGeometry(QtCore.QRect(570, 380, 261, 23)) + self.label.setGeometry(QtCore.QRect(570, 340, 261, 23)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) self.label.setFont(font) self.label.setObjectName("label") self.inf_spawn_spinBox = QtWidgets.QSpinBox(self.centralwidget) - self.inf_spawn_spinBox.setGeometry(QtCore.QRect(510, 380, 47, 31)) + self.inf_spawn_spinBox.setGeometry(QtCore.QRect(510, 340, 51, 31)) font = QtGui.QFont() font.setPointSize(12) self.inf_spawn_spinBox.setFont(font) self.inf_spawn_spinBox.setButtonSymbols(QtWidgets.QAbstractSpinBox.PlusMinus) self.inf_spawn_spinBox.setMinimum(0) self.inf_spawn_spinBox.setMaximum(20) - self.inf_spawn_spinBox.setProperty("value", 2) + self.inf_spawn_spinBox.setProperty("value", 0) self.inf_spawn_spinBox.setObjectName("inf_spawn_spinBox") self.troop_drop_spinBox = QtWidgets.QSpinBox(self.centralwidget) - self.troop_drop_spinBox.setGeometry(QtCore.QRect(510, 330, 47, 31)) + self.troop_drop_spinBox.setGeometry(QtCore.QRect(510, 300, 51, 31)) font = QtGui.QFont() font.setPointSize(12) self.troop_drop_spinBox.setFont(font) @@ -303,23 +303,23 @@ class Ui_MainWindow(object): self.troop_drop_spinBox.setMaximum(10) self.troop_drop_spinBox.setProperty("value", 4) self.troop_drop_spinBox.setObjectName("troop_drop_spinBox") - self.force_offroad_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.force_offroad_checkBox.setGeometry(QtCore.QRect(960, 548, 161, 24)) + self.random_weather_checkBox = QtWidgets.QCheckBox(self.centralwidget) + self.random_weather_checkBox.setGeometry(QtCore.QRect(980, 420, 211, 24)) font = QtGui.QFont() font.setPointSize(9) - self.force_offroad_checkBox.setFont(font) - self.force_offroad_checkBox.setChecked(False) - self.force_offroad_checkBox.setTristate(False) - self.force_offroad_checkBox.setObjectName("force_offroad_checkBox") + self.random_weather_checkBox.setFont(font) + self.random_weather_checkBox.setChecked(False) + self.random_weather_checkBox.setTristate(False) + self.random_weather_checkBox.setObjectName("random_weather_checkBox") self.label_3 = QtWidgets.QLabel(self.centralwidget) - self.label_3.setGeometry(QtCore.QRect(570, 330, 281, 23)) + self.label_3.setGeometry(QtCore.QRect(570, 300, 281, 23)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.apcs_spawn_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.apcs_spawn_checkBox.setGeometry(QtCore.QRect(990, 180, 251, 27)) + self.apcs_spawn_checkBox.setGeometry(QtCore.QRect(980, 180, 251, 27)) font = QtGui.QFont() font.setPointSize(10) font.setBold(False) @@ -328,7 +328,7 @@ class Ui_MainWindow(object): self.apcs_spawn_checkBox.setObjectName("apcs_spawn_checkBox") self.generateButton = QtWidgets.QPushButton(self.centralwidget) self.generateButton.setEnabled(True) - self.generateButton.setGeometry(QtCore.QRect(710, 600, 231, 51)) + self.generateButton.setGeometry(QtCore.QRect(750, 600, 231, 51)) font = QtGui.QFont() font.setPointSize(8) font.setBold(True) @@ -336,7 +336,7 @@ class Ui_MainWindow(object): self.generateButton.setStyleSheet("") self.generateButton.setObjectName("generateButton") self.farp_always = QtWidgets.QRadioButton(self.centralwidget) - self.farp_always.setGeometry(QtCore.QRect(510, 480, 261, 24)) + self.farp_always.setGeometry(QtCore.QRect(500, 431, 261, 24)) font = QtGui.QFont() font.setPointSize(9) self.farp_always.setFont(font) @@ -345,14 +345,14 @@ class Ui_MainWindow(object): self.farp_buttonGroup.setObjectName("farp_buttonGroup") self.farp_buttonGroup.addButton(self.farp_always) self.farp_never = QtWidgets.QRadioButton(self.centralwidget) - self.farp_never.setGeometry(QtCore.QRect(510, 540, 271, 24)) + self.farp_never.setGeometry(QtCore.QRect(500, 491, 271, 24)) font = QtGui.QFont() font.setPointSize(9) self.farp_never.setFont(font) self.farp_never.setObjectName("farp_never") self.farp_buttonGroup.addButton(self.farp_never) self.farp_gunits = QtWidgets.QRadioButton(self.centralwidget) - self.farp_gunits.setGeometry(QtCore.QRect(510, 509, 261, 24)) + self.farp_gunits.setGeometry(QtCore.QRect(500, 460, 261, 24)) font = QtGui.QFont() font.setPointSize(9) self.farp_gunits.setFont(font) @@ -397,7 +397,7 @@ class Ui_MainWindow(object): self.rateButton1.setText("") self.rateButton1.setObjectName("rateButton1") self.hotstart_checkBox = QtWidgets.QCheckBox(self.centralwidget) - self.hotstart_checkBox.setGeometry(QtCore.QRect(960, 430, 271, 24)) + self.hotstart_checkBox.setGeometry(QtCore.QRect(980, 520, 271, 24)) font = QtGui.QFont() font.setPointSize(9) self.hotstart_checkBox.setFont(font) @@ -440,6 +440,21 @@ class Ui_MainWindow(object): self.rateButton5.setStyleSheet("border-image:url(\'../assets/star_full.png\');") self.rateButton5.setText("") self.rateButton5.setObjectName("rateButton5") + self.time_comboBox = QtWidgets.QComboBox(self.centralwidget) + self.time_comboBox.setGeometry(QtCore.QRect(980, 370, 161, 33)) + font = QtGui.QFont() + font.setPointSize(10) + font.setBold(False) + self.time_comboBox.setFont(font) + self.time_comboBox.setObjectName("time_comboBox") + self.farp_spawn_checkBox = QtWidgets.QCheckBox(self.centralwidget) + self.farp_spawn_checkBox.setGeometry(QtCore.QRect(980, 550, 271, 24)) + font = QtGui.QFont() + font.setPointSize(9) + self.farp_spawn_checkBox.setFont(font) + self.farp_spawn_checkBox.setChecked(False) + self.farp_spawn_checkBox.setTristate(False) + self.farp_spawn_checkBox.setObjectName("farp_spawn_checkBox") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1280, 29)) @@ -564,10 +579,10 @@ class Ui_MainWindow(object): def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "RotorOps Mission Generator")) - self.logistics_crates_checkBox.setStatusTip(_translate("MainWindow", "Enable CTLD logistics crates for building ground units and air defenses. Pickup logistics containers to create new logistics sites.")) - self.logistics_crates_checkBox.setText(_translate("MainWindow", "Logistics")) - self.zone_sams_checkBox.setStatusTip(_translate("MainWindow", "Inactive conflict zones will be protected by SAMs. When a zone is cleared, SAMs at next active zone will be destroyed.")) - self.zone_sams_checkBox.setText(_translate("MainWindow", "Inactive Zone SAMs")) + self.logistics_crates_checkBox.setStatusTip(_translate("MainWindow", "Enable a base or FARP near the start position that can spawn CTLD crates for building ground units and air defenses. Sling load the logistics containers to create new logistics sites.")) + self.logistics_crates_checkBox.setText(_translate("MainWindow", "Logistics Base")) + self.zone_sams_checkBox.setStatusTip(_translate("MainWindow", "Inactive conflict zones will be protected by SAMs. When a zone is cleared, SAMs at next active zone will be destroyed. No effect if Blue on defense.")) + self.zone_sams_checkBox.setText(_translate("MainWindow", "Protect Inactive Zones")) self.red_forces_label.setText(_translate("MainWindow", "Red Forces:")) self.scenario_comboBox.setStatusTip(_translate("MainWindow", "Tip: You can create your own templates that include mission options like kneeboards, briefings, weather, static units, triggers, scripts, etc.")) self.description_textBrowser.setHtml(_translate("MainWindow", "\n" @@ -575,6 +590,7 @@ class Ui_MainWindow(object): "p, li { white-space: pre-wrap; }\n" "\n" "

Provide close air support for our convoys as we take back Las Vegas from the enemy!

")) + self.defense_checkBox.setStatusTip(_translate("MainWindow", "Turn the tables and defend your zones against the enemy\'s attack.")) self.defense_checkBox.setText(_translate("MainWindow", "Blue on Defense")) self.redqty_spinBox.setStatusTip(_translate("MainWindow", "Red vehicle groups per staging or conflict zone.")) self.redforces_comboBox.setStatusTip(_translate("MainWindow", "Tip: You can create your own custom ground forces groups to be automatically generated.")) @@ -602,20 +618,20 @@ class Ui_MainWindow(object): self.tankers_checkBox.setText(_translate("MainWindow", "Friendly Tankers")) self.voiceovers_checkBox.setStatusTip(_translate("MainWindow", "Voiceovers from the ground commander. Helps keep focus on the active zone.")) self.voiceovers_checkBox.setText(_translate("MainWindow", "Voiceovers")) - self.smoke_pickup_zone_checkBox.setStatusTip(_translate("MainWindow", "Infinite troop pickup zones will be marked with blue smoke.")) + self.smoke_pickup_zone_checkBox.setStatusTip(_translate("MainWindow", "Troop pickup zones and FARPs will be marked with blue smoke.")) self.smoke_pickup_zone_checkBox.setText(_translate("MainWindow", "Smoke at Troop Pickup Zones")) self.game_status_checkBox.setStatusTip(_translate("MainWindow", "Enable an onscreen zone status display. This helps keep focus on the active conflict zone.")) self.game_status_checkBox.setText(_translate("MainWindow", "Game Status Display")) - self.label.setStatusTip(_translate("MainWindow", "This value is multiplied by the number of spawn zones in the mission template.")) - self.label.setText(_translate("MainWindow", "Infantry Spawns per zone")) + self.label.setStatusTip(_translate("MainWindow", "Total number of infantry groups to spawn per game.")) + self.label.setText(_translate("MainWindow", "Infantry Spawns")) self.inf_spawn_spinBox.setStatusTip(_translate("MainWindow", "This value is multiplied by the number of spawn zones in the mission template.")) self.troop_drop_spinBox.setStatusTip(_translate("MainWindow", "The number of troop drops per transport helicopter flight.")) - self.force_offroad_checkBox.setStatusTip(_translate("MainWindow", "May help prevent long travel times or pathfinding issues. ")) - self.force_offroad_checkBox.setText(_translate("MainWindow", "Force Offroad")) + self.random_weather_checkBox.setStatusTip(_translate("MainWindow", "Random weather preset will be applied.")) + self.random_weather_checkBox.setText(_translate("MainWindow", "Random Weather")) self.label_3.setStatusTip(_translate("MainWindow", "The number of troop drops per transport helicopter flight.")) self.label_3.setText(_translate("MainWindow", "Transport Drop Points")) - self.apcs_spawn_checkBox.setStatusTip(_translate("MainWindow", "Friendly/enemy APCs will drop infantry when reaching a new conflict zone. Disables infinite troop pickups from conflict zones (you must pick up existing troops).")) - self.apcs_spawn_checkBox.setText(_translate("MainWindow", "Dynamic Troops")) + self.apcs_spawn_checkBox.setStatusTip(_translate("MainWindow", "Friendly/enemy APCs will drop infantry when reaching a new conflict zone. ")) + self.apcs_spawn_checkBox.setText(_translate("MainWindow", "APCs Spawn Infantry")) self.generateButton.setStatusTip(_translate("MainWindow", "Click to generate mission.")) self.generateButton.setText(_translate("MainWindow", "GENERATE MISSION")) self.farp_always.setStatusTip(_translate("MainWindow", "Always spawn a FARP in defeated conflict zones.")) @@ -627,12 +643,15 @@ class Ui_MainWindow(object): self.nextScenario_pushButton.setText(_translate("MainWindow", ">")) self.prevScenario_pushButton.setText(_translate("MainWindow", "<")) self.rateButton1.setStatusTip(_translate("MainWindow", "Submit a review for this mission scenario.")) - self.hotstart_checkBox.setStatusTip(_translate("MainWindow", "Player helicopters start with engines running on the ground. No effect if player slots says \'Locked to scenario\'")) + self.hotstart_checkBox.setStatusTip(_translate("MainWindow", "Player helicopters start with engines running on the ground. No effect for FARP spawns or if player slots says \'Locked to scenario\'")) self.hotstart_checkBox.setText(_translate("MainWindow", "Player Hotstart")) self.rateButton2.setStatusTip(_translate("MainWindow", "Submit a review for this mission scenario.")) self.rateButton3.setStatusTip(_translate("MainWindow", "Submit a review for this mission scenario.")) self.rateButton4.setStatusTip(_translate("MainWindow", "Submit a review for this mission scenario.")) self.rateButton5.setStatusTip(_translate("MainWindow", "Submit a review for this mission scenario.")) + self.time_comboBox.setStatusTip(_translate("MainWindow", "Mission start time of day. \'Default\' is the start time as defined by the mission template designer.")) + self.farp_spawn_checkBox.setStatusTip(_translate("MainWindow", "Add helicopter slots where zone FARPs will be built. Helicopters will be empty fuel, requiring the FARP to be established to refuel and rearm.")) + self.farp_spawn_checkBox.setText(_translate("MainWindow", "Spawns at zone FARPs")) self.menuMap.setTitle(_translate("MainWindow", "Map")) self.menuFilter.setTitle(_translate("MainWindow", "Filter")) self.menuPreferences.setTitle(_translate("MainWindow", "Preferences")) @@ -658,8 +677,8 @@ class Ui_MainWindow(object): self.action_downloadButton.setToolTip(_translate("MainWindow", "_downloadButton")) self.action_rateButton1.setText(_translate("MainWindow", "_rateButton1")) self.action_rateButton1.setToolTip(_translate("MainWindow", "_rateButton1")) - self.actionSingle_Player.setText(_translate("MainWindow", "Single-Player")) - self.actionCo_Op.setText(_translate("MainWindow", "Co-Op")) + self.actionSingle_Player.setText(_translate("MainWindow", "Single-Player Only")) + self.actionCo_Op.setText(_translate("MainWindow", "Co-Op Only")) self.actionMapMenu.setText(_translate("MainWindow", "actionMapMenu")) self.actionFilterMenu.setText(_translate("MainWindow", "FilterMenu")) self.action_rateButton2.setText(_translate("MainWindow", "_rateButton2")) diff --git a/Generator/MissionGeneratorUI.ui b/Generator/MissionGeneratorUI.ui index fd3dbd0..9efcc07 100644 --- a/Generator/MissionGeneratorUI.ui +++ b/Generator/MissionGeneratorUI.ui @@ -53,7 +53,7 @@ - 990 + 980 211 251 28 @@ -66,10 +66,10 @@ - Enable CTLD logistics crates for building ground units and air defenses. Pickup logistics containers to create new logistics sites. + Enable a base or FARP near the start position that can spawn CTLD crates for building ground units and air defenses. Sling load the logistics containers to create new logistics sites. - Logistics + Logistics Base true @@ -78,7 +78,7 @@ - 990 + 980 320 241 28 @@ -91,10 +91,10 @@ - Inactive conflict zones will be protected by SAMs. When a zone is cleared, SAMs at next active zone will be destroyed. + Inactive conflict zones will be protected by SAMs. When a zone is cleared, SAMs at next active zone will be destroyed. No effect if Blue on defense. - Inactive Zone SAMs + Protect Inactive Zones @@ -191,17 +191,20 @@ p, li { white-space: pre-wrap; } 470 - 120 + 130 156 28 - 10 + 11 false + + Turn the tables and defend your zones against the enemy's attack. + Blue on Defense @@ -289,8 +292,8 @@ p, li { white-space: pre-wrap; } - 960 - 384 + 980 + 474 271 33 @@ -564,7 +567,7 @@ p, li { white-space: pre-wrap; } 8 - 2 + 1 @@ -592,8 +595,8 @@ p, li { white-space: pre-wrap; } - 840 - 390 + 860 + 480 111 24 @@ -611,8 +614,8 @@ p, li { white-space: pre-wrap; } - 490 - 450 + 480 + 401 251 23 @@ -629,7 +632,7 @@ p, li { white-space: pre-wrap; } - 990 + 980 246 241 28 @@ -654,7 +657,7 @@ p, li { white-space: pre-wrap; } - 990 + 980 282 241 28 @@ -679,10 +682,10 @@ p, li { white-space: pre-wrap; } - 960 - 517 + 500 + 594 171 - 24 + 31 @@ -703,10 +706,10 @@ p, li { white-space: pre-wrap; } - 960 - 460 - 271 - 24 + 500 + 541 + 231 + 20 @@ -715,7 +718,7 @@ p, li { white-space: pre-wrap; } - Infinite troop pickup zones will be marked with blue smoke. + Troop pickup zones and FARPs will be marked with blue smoke. Smoke at Troop Pickup Zones @@ -727,10 +730,10 @@ p, li { white-space: pre-wrap; } - 960 - 490 - 271 - 24 + 500 + 570 + 221 + 21 @@ -755,7 +758,7 @@ p, li { white-space: pre-wrap; } 570 - 380 + 340 261 23 @@ -767,18 +770,18 @@ p, li { white-space: pre-wrap; } - This value is multiplied by the number of spawn zones in the mission template. + Total number of infantry groups to spawn per game. - Infantry Spawns per zone + Infantry Spawns 510 - 380 - 47 + 340 + 51 31 @@ -800,15 +803,15 @@ p, li { white-space: pre-wrap; } 20 - 2 + 0 510 - 330 - 47 + 300 + 51 31 @@ -833,12 +836,12 @@ p, li { white-space: pre-wrap; } 4 - + - 960 - 548 - 161 + 980 + 420 + 211 24 @@ -848,10 +851,10 @@ p, li { white-space: pre-wrap; } - May help prevent long travel times or pathfinding issues. + Random weather preset will be applied. - Force Offroad + Random Weather false @@ -864,7 +867,7 @@ p, li { white-space: pre-wrap; } 570 - 330 + 300 281 23 @@ -885,7 +888,7 @@ p, li { white-space: pre-wrap; } - 990 + 980 180 251 27 @@ -898,10 +901,10 @@ p, li { white-space: pre-wrap; } - Friendly/enemy APCs will drop infantry when reaching a new conflict zone. Disables infinite troop pickups from conflict zones (you must pick up existing troops). + Friendly/enemy APCs will drop infantry when reaching a new conflict zone. - Dynamic Troops + APCs Spawn Infantry true @@ -913,7 +916,7 @@ p, li { white-space: pre-wrap; } - 710 + 750 600 231 51 @@ -938,8 +941,8 @@ p, li { white-space: pre-wrap; } - 510 - 480 + 500 + 431 261 24 @@ -962,8 +965,8 @@ p, li { white-space: pre-wrap; } - 510 - 540 + 500 + 491 271 24 @@ -986,8 +989,8 @@ p, li { white-space: pre-wrap; } - 510 - 509 + 500 + 460 261 24 @@ -1131,8 +1134,8 @@ p, li { white-space: pre-wrap; } - 960 - 430 + 980 + 520 271 24 @@ -1143,7 +1146,7 @@ p, li { white-space: pre-wrap; } - Player helicopters start with engines running on the ground. No effect if player slots says 'Locked to scenario' + Player helicopters start with engines running on the ground. No effect for FARP spawns or if player slots says 'Locked to scenario' Player Hotstart @@ -1263,6 +1266,52 @@ p, li { white-space: pre-wrap; } + + + + 980 + 370 + 161 + 33 + + + + + 10 + false + + + + Mission start time of day. 'Default' is the start time as defined by the mission template designer. + + + + + + 980 + 550 + 271 + 24 + + + + + 9 + + + + Add helicopter slots where zone FARPs will be built. Helicopters will be empty fuel, requiring the FARP to be established to refuel and rearm. + + + Spawns at zone FARPs + + + false + + + false + + @@ -1471,7 +1520,7 @@ p, li { white-space: pre-wrap; } true - Single-Player + Single-Player Only @@ -1482,7 +1531,7 @@ p, li { white-space: pre-wrap; } true - Co-Op + Co-Op Only diff --git a/Generator/MissionGeneratorUI_bkup11.ui b/Generator/MissionGeneratorUI_bkup11.ui deleted file mode 100644 index b7458cf..0000000 --- a/Generator/MissionGeneratorUI_bkup11.ui +++ /dev/null @@ -1,1380 +0,0 @@ - - - MainWindow - - - - 0 - 0 - 1280 - 720 - - - - - 0 - 0 - - - - - 1280 - 720 - - - - - 1280 - 720 - - - - - 10 - - - - RotorOps Mission Generator - - - - assets/icon.icoassets/icon.ico - - - 4.000000000000000 - - - false - - - - - - - - - 990 - 211 - 251 - 28 - - - - - 10 - false - - - - Enable CTLD logistics crates for building ground units and air defenses. Pickup logistics containers to create new logistics sites. - - - Logistics - - - true - - - - - - 990 - 320 - 241 - 28 - - - - - 10 - false - - - - Inactive conflict zones will be protected by SAMs. When a zone is cleared, SAMs at next active zone will be destroyed. - - - Inactive Zone SAMs - - - - - - 470 - 80 - 171 - 27 - - - - - 10 - false - - - - Red Forces: - - - - - - 30 - 20 - 371 - 29 - - - - - 8 - true - - - - - - - -1 - - - Tip: You can create your own templates that include mission options like kneeboards, briefings, weather, static units, triggers, scripts, etc. - - - - - - QComboBox::AdjustToContentsOnFirstShow - - - true - - - - - - 40 - 410 - 361 - 251 - - - - - 9 - - - - padding: 5px; - - - QFrame::StyledPanel - - - QFrame::Plain - - - 1 - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> -<html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> -p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Arial'; font-size:9pt; font-weight:400; font-style:normal;"> -<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:10pt;">Provide close air support for our convoys as we take back Las Vegas from the enemy!</span></p></body></html> - - - - - true - - - - 470 - 120 - 156 - 28 - - - - - 10 - false - - - - Blue on Defense - - - true - - - - - - 1070 - 80 - 51 - 31 - - - - - 12 - - - - Red vehicle groups per staging or conflict zone. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 8 - - - 2 - - - - - - 660 - 80 - 391 - 33 - - - - - 0 - 0 - - - - - 9 - false - - - - Tip: You can create your own custom ground forces groups to be automatically generated. - - - - - - 570 - 220 - 271 - 24 - - - - - 10 - false - - - - Approximate number of enemy attack plane group spawns. - - - Enemy Attack Planes - - - - - - 960 - 384 - 271 - 33 - - - - - 10 - false - - - - Default player/client spawn locations at a friendly airport. - - - - - - 1130 - 40 - 131 - 18 - - - - - 8 - - - - Groups Per Zone - - - Qt::AlignCenter - - - - - - 470 - 30 - 161 - 27 - - - - - 10 - false - - - - Blue Forces: - - - - - - 1070 - 30 - 51 - 31 - - - - - 12 - - - - Blue vehicle groups per staging or conflict zone. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 8 - - - 3 - - - - - - 660 - 30 - 391 - 33 - - - - - 9 - false - - - - Tip: You can create your own custom ground forces groups to be automatically generated. - - - - - - 1130 - 90 - 131 - 18 - - - - - 8 - - - - Groups Per Zone - - - Qt::AlignCenter - - - - - - 1140 - 650 - 111 - 20 - - - - Version string - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - 570 - 260 - 271 - 24 - - - - - 10 - false - - - - Approximate number of enemy transport helicopter spawns. - - - Enemy Transport Helicopters - - - - - - 510 - 260 - 51 - 31 - - - - - 0 - 0 - - - - - 12 - - - - Approximate number of enemy transport helicopter spawns. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 8 - - - 1 - - - - - - 510 - 220 - 51 - 31 - - - - - 0 - 0 - - - - - 12 - - - - Approximate number of enemy attack plane group spawns. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 8 - - - 1 - - - - - - 510 - 180 - 51 - 31 - - - - - 0 - 0 - - - - - 12 - - - - Approximate number of enemy attack helicopter group spawns. - - - false - - - QAbstractSpinBox::PlusMinus - - - true - - - 0 - - - 8 - - - 2 - - - - - - 570 - 180 - 271 - 24 - - - - - 10 - false - - - - Approximate number of enemy attack helicopter group spawns. - - - Enemy Attack Helicopters - - - - - - 840 - 390 - 111 - 24 - - - - - 10 - false - - - - Player Slots: - - - - - - 490 - 450 - 251 - 23 - - - - - 10 - - - - Zone FARP Conditions: - - - - - - 990 - 246 - 241 - 28 - - - - - 10 - false - - - - Spawn a friendly AWACS with fighter escorts. - - - Friendly AWACS with escort - - - true - - - - - - 990 - 282 - 241 - 28 - - - - - 10 - false - - - - Spawn friendly tankers for both boom and basket refueling. - - - Friendly Tankers - - - true - - - - - - 960 - 455 - 271 - 24 - - - - - 9 - - - - Friendly/enemy APCs will drop infantry when reaching a new conflict zone. - - - Voiceovers on Infantry Spawn - - - true - - - - - - 960 - 517 - 171 - 24 - - - - - 9 - - - - Voiceovers from the ground commander. Helps keep focus on the active zone. - - - Voiceovers - - - true - - - - - - 960 - 424 - 271 - 24 - - - - - 9 - - - - Infinite troop pickup zones will be marked with blue smoke. - - - Smoke at Troop Pickup Zones - - - false - - - - - - 960 - 486 - 271 - 24 - - - - - 9 - - - - Enable an onscreen zone status display. This helps keep focus on the active conflict zone. - - - Game Status Display - - - true - - - false - - - - - - 570 - 380 - 261 - 23 - - - - - 10 - false - - - - This value is multiplied by the number of spawn zones in the mission template. - - - Infantry Spawns per zone - - - - - - 510 - 380 - 47 - 31 - - - - - 12 - - - - This value is multiplied by the number of spawn zones in the mission template. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 20 - - - 2 - - - - - - 510 - 330 - 47 - 31 - - - - - 12 - - - - The number of troop drops per transport helicopter flight. - - - QAbstractSpinBox::PlusMinus - - - 0 - - - 10 - - - 4 - - - - - - 960 - 548 - 161 - 24 - - - - - 9 - - - - May help prevent long travel times or pathfinding issues. - - - Force Offroad - - - false - - - false - - - - - - 570 - 330 - 281 - 23 - - - - - 10 - false - - - - The number of troop drops per transport helicopter flight. - - - Transport Drop Points - - - - - - 990 - 180 - 251 - 27 - - - - - 10 - false - - - - Friendly/enemy APCs will drop infantry when reaching a new conflict zone. Disables infinite troop pickups from conflict zones (you must pick up existing troops). - - - Dynamic Troops - - - true - - - - - - 710 - 600 - 231 - 51 - - - - - 8 - true - - - - Click to generate mission. - - - - - - GENERATE MISSION - - - - - - 510 - 480 - 261 - 24 - - - - - 9 - - - - Always spawn a FARP in defeated conflict zones. - - - Always - - - farp_buttonGroup - - - - - - 510 - 540 - 271 - 24 - - - - - 9 - - - - Never spawn FARPs in defeated conflict zones. - - - Never - - - farp_buttonGroup - - - - - - 510 - 509 - 261 - 24 - - - - - 9 - - - - Only spawn FARPs in defeated conflict zones if we have sufficient ground units remaining. - - - 20% Ground Units Remaining - - - true - - - farp_buttonGroup - - - - - true - - - - 60 - 80 - 300 - 300 - - - - - 0 - 0 - - - - - 300 - 300 - - - - - 16777215 - 16777215 - - - - - - - - - - ../assets/briefing1.png - - - true - - - false - - - - - - 370 - 210 - 31 - 51 - - - - > - - - - - - 20 - 210 - 31 - 51 - - - - < - - - - - - 1020 - 600 - 241 - 51 - - - - - - - ../assets/rotorops-dkgray.png - - - true - - - - - - - 0 - 0 - 1280 - 26 - - - - - Map Filter - - - - - - - - - - - Gametype Filter - - - - - - - Preferences - - - - - - - - - - - 9 - false - - - - false - - - - - - - - _generateMission - - - - - _scenarioSelected - - - - - _blueforcesSelected - - - - - _redforcesSelected - - - - - _defensiveModeChanged - - - - - _nextScenario - - - - - _prevScenario - - - - - Caucasus - - - - - Persian Gulf - - - - - Marianas - - - - - Nevada - - - - - Syria - - - - - true - - - true - - - All - - - - - false - - - Multiplayer - - - - - true - - - true - - - All - - - - - Save Directory - - - - - _slotChanged - - - - - - - generateButton - clicked() - action_generateMission - trigger() - - - 1030 - 616 - - - -1 - -1 - - - - - scenario_comboBox - currentIndexChanged(int) - action_scenarioSelected - trigger() - - - 285 - 71 - - - -1 - -1 - - - - - defense_checkBox - stateChanged(int) - action_defensiveModeChanged - trigger() - - - 560 - 173 - - - -1 - -1 - - - - - nextScenario_pushButton - clicked() - action_nextScenario - trigger() - - - 389 - 257 - - - -1 - -1 - - - - - prevScenario_pushButton - clicked() - action_prevScenario - trigger() - - - 35 - 261 - - - -1 - -1 - - - - - slot_template_comboBox - activated(int) - action_slotChanged - trigger() - - - 1095 - 426 - - - -1 - -1 - - - - - - - - diff --git a/Generator/RotorOpsConflict.py b/Generator/RotorOpsConflict.py index f255c5b..55f1d86 100644 --- a/Generator/RotorOpsConflict.py +++ b/Generator/RotorOpsConflict.py @@ -16,7 +16,6 @@ def triggerSetup(rops, options): # Add the first trigger trig = dcs.triggers.TriggerOnce(comment="RotorOps Setup Scripts") trig.rules.append(dcs.condition.TimeAfter(1)) - #trig.actions.append(dcs.action.DoScriptFile(rops.scripts["mist_4_4_90.lua"])) trig.actions.append(dcs.action.DoScriptFile(rops.scripts["mist_4_5_107_grimm.lua"])) trig.actions.append(dcs.action.DoScriptFile(rops.scripts["Splash_Damage_2_0.lua"])) trig.actions.append(dcs.action.DoScriptFile(rops.scripts["CTLD.lua"])) @@ -29,11 +28,13 @@ def triggerSetup(rops, options): "RotorOps.voice_overs = " + lb("voiceovers") + "\n\n" + "RotorOps.zone_status_display = " + lb("game_display") + "\n\n" + "RotorOps.inf_spawn_messages = true\n\n" + - "RotorOps.inf_spawns_per_zone = " + lb("inf_spawn_qty") + "\n\n" + + "RotorOps.inf_spawns_total = " + lb("inf_spawn_qty") + "\n\n" + "RotorOps.apcs_spawn_infantry = " + lb("apc_spawns_inf") + " \n\n") if not options["smoke_pickup_zones"]: script = script + 'RotorOps.pickup_zone_smoke = "none"\n\n' trig.actions.append(dcs.action.DoScript(dcs.action.String((script)))) + if options["script"]: + trig.actions.append(dcs.action.DoScript(dcs.action.String((options["script"])))) rops.m.triggerrules.triggers.append(trig) # Add the second trigger @@ -50,11 +51,12 @@ def triggerSetup(rops, options): rops.m.triggerrules.triggers.append(trig) - # Add the third trigger - trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict Start") - trig.rules.append(dcs.condition.TimeAfter(10)) - trig.actions.append(dcs.action.DoScript(dcs.action.String("RotorOps.startConflict(100)"))) - rops.m.triggerrules.triggers.append(trig) + # Add the start trigger + if options["start_trigger"] is not False: + trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict Start") + trig.rules.append(dcs.condition.TimeAfter(10)) + trig.actions.append(dcs.action.DoScript(dcs.action.String("RotorOps.startConflict(100)"))) + rops.m.triggerrules.triggers.append(trig) # Add generic zone-based triggers for index, zone_name in enumerate(rops.conflict_zones): @@ -81,6 +83,19 @@ def triggerSetup(rops, options): dcs.action.String("Group.destroy(Group.getByName('Static " + zone_name + " Protection SAM'))"))) rops.m.triggerrules.triggers.append(z_sams_trig) + # Deactivate zone FARPs and player slots in defensive mode: + # this will also deactivate players already in the air. + # if options["defending"]: + # for index, zone_name in enumerate(rops.conflict_zones): + # z_farps_trig = dcs.triggers.TriggerOnce(comment="Deactivate " + zone_name + " FARP") + # z_farps_trig.rules.append(dcs.condition.FlagEquals(game_flag, index + 1)) + # z_farps_trig.actions.append(dcs.action.DeactivateGroup(rops.m.country(jtf_blue).find_group(zone_name + " FARP Static").id)) + # for group in rops.all_zones[zone_name].player_helo_spawns: + # z_farps_trig.actions.append( + # dcs.action.DeactivateGroup( + # group.id)) + # rops.m.triggerrules.triggers.append(z_farps_trig) + # Zone FARPS always if options["zone_farps"] == "farp_always" and not options["defending"]: for index, zone_name in enumerate(rops.conflict_zones): @@ -92,9 +107,13 @@ def triggerSetup(rops, options): z_farps_trig.rules.append(dcs.condition.FlagEquals(game_flag, index + 1)) z_farps_trig.actions.append( dcs.action.ActivateGroup(rops.m.country(jtf_blue).find_group(previous_zone + " FARP Static").id)) - # z_farps_trig.actions.append(dcs.action.SoundToAll(str(rops.res_map['forward_base_established.ogg']))) + # Activate late-activated helicopters at FARPs. Doesn't work consistently + # for group in rops.all_zones[previous_zone].player_helo_spawns: + # z_farps_trig.actions.append( + # dcs.action.ActivateGroup( + # group.id)) z_farps_trig.actions.append(dcs.action.DoScript(dcs.action.String( - "RotorOps.farpEstablished(" + str(index) + ")"))) + "RotorOps.farpEstablished(" + str(index) + ", '" + previous_zone + "_FARP')"))) rops.m.triggerrules.triggers.append(z_farps_trig) # Zone FARPS conditional on staged units remaining @@ -111,9 +130,13 @@ def triggerSetup(rops, options): "--The 100 flag indicates which zone is active. The 111 flag value is the percentage of staged units remaining"))) z_farps_trig.actions.append( dcs.action.ActivateGroup(rops.m.country(jtf_blue).find_group(previous_zone + " FARP Static").id)) - # z_farps_trig.actions.append(dcs.action.SoundToAll(str(rops.res_map['forward_base_established.ogg']))) + # Activate late-activated helicopters at FARPs. Doesn't work consistently + # for group in rops.all_zones[previous_zone].player_helo_spawns: + # z_farps_trig.actions.append( + # dcs.action.ActivateGroup( + # group.id)) z_farps_trig.actions.append(dcs.action.DoScript(dcs.action.String( - "RotorOps.farpEstablished(" + str(index) + ")"))) + "RotorOps.farpEstablished(" + str(index) + ", '" + previous_zone + "_FARP')"))) rops.m.triggerrules.triggers.append(z_farps_trig) # Add attack helos triggers @@ -156,17 +179,23 @@ def triggerSetup(rops, options): rops.m.triggerrules.triggers.append(z_weak_trig) # Add game won/lost triggers - trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict WON") - trig.rules.append(dcs.condition.FlagEquals(game_flag, 99)) - trig.actions.append( - dcs.action.DoScript(dcs.action.String("---Add an action you want to happen when the game is WON"))) - trig.actions.append( - dcs.action.DoScript(dcs.action.String("RotorOps.gameMsg(RotorOps.gameMsgs.success)"))) - rops.m.triggerrules.triggers.append(trig) - trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict LOST") - trig.rules.append(dcs.condition.FlagEquals(game_flag, 98)) - trig.actions.append( - dcs.action.DoScript(dcs.action.String("---Add an action you want to happen when the game is LOST"))) - trig.actions.append( - dcs.action.DoScript(dcs.action.String("RotorOps.gameMsg(RotorOps.gameMsgs.failure)"))) - rops.m.triggerrules.triggers.append(trig) \ No newline at end of file + + + # Add game won triggers + trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict WON") + trig.rules.append(dcs.condition.FlagEquals(game_flag, 99)) + trig.actions.append( + dcs.action.DoScript(dcs.action.String("---Add an action you want to happen when the game is WON"))) + if options["end_trigger"] is not False: + trig.actions.append( + dcs.action.DoScript(dcs.action.String("RotorOps.gameMsg(RotorOps.gameMsgs.success)"))) + rops.m.triggerrules.triggers.append(trig) + + # Add game lost triggers + trig = dcs.triggers.TriggerOnce(comment="RotorOps Conflict LOST") + trig.rules.append(dcs.condition.FlagEquals(game_flag, 98)) + trig.actions.append( + dcs.action.DoScript(dcs.action.String("---Add an action you want to happen when the game is LOST"))) + if options["end_trigger"] is not False: + trig.actions.append(dcs.action.DoScript(dcs.action.String("RotorOps.gameMsg(RotorOps.gameMsgs.failure)"))) + rops.m.triggerrules.triggers.append(trig) \ No newline at end of file diff --git a/Generator/RotorOpsImport.py b/Generator/RotorOpsImport.py index af8aadb..b5c347d 100644 --- a/Generator/RotorOpsImport.py +++ b/Generator/RotorOpsImport.py @@ -1,12 +1,15 @@ import math import dcs from MissionGenerator import logger +import os class ImportObjects: def __init__(self, mizfile): - self.pad_unit = True #todo: use this to hold a unit for helicopter placement on ships ie flight_group_from_unit + self.pad_unit = True # todo: use this to hold a unit for helicopter placement on ships ie flight_group_from_unit + if not mizfile or not os.path.exists(mizfile): + raise Exception("Cannot find required file: " + str(mizfile)) logger.info("Importing objects from " + mizfile) self.source_mission = dcs.mission.Mission() self.source_mission.load_file(mizfile) @@ -32,7 +35,6 @@ class ImportObjects: self.copyVehicles(mission, dest_country_name, dest_name, dest_point, dest_heading), \ self.copyHelicopters(mission, dest_country_name, dest_name, dest_point, dest_heading) - def anchorByGroupName(self, group_name): group = self.source_mission.find_group(group_name) if group: @@ -49,24 +51,26 @@ class ImportObjects: coalition = self.source_mission.coalition.get(side) for country_name in coalition.countries: - group_types = [coalition.countries[country_name].static_group, coalition.countries[country_name].vehicle_group, coalition.countries[country_name].helicopter_group, coalition.countries[country_name].plane_group, + group_types = [coalition.countries[country_name].static_group, + coalition.countries[country_name].vehicle_group, + coalition.countries[country_name].helicopter_group, + coalition.countries[country_name].plane_group, coalition.countries[country_name].ship_group] for index, group_type in enumerate(group_types): for group in group_type: - if index == 0: # Statics + if index == 0: # Statics self.statics.append(group) elif index == 1: # Vehicles self.vehicles.append(group) - elif index == 2: # Helicopters + elif index == 2: # Helicopters self.helicopters.append(group) elif index == 3: logger.warn(group.name + ": Planes not available for import") elif index == 4: logger.warn(group.name + ": Ships not available for import") - def copyStatics(self, mission, dest_country_name, dest_name, dest_point=None, dest_heading=0): logger.info("Copying " + str(len(self.statics)) + " static objects as " + dest_name) new_groups = [] @@ -74,13 +78,11 @@ class ImportObjects: if not dest_point: dest_point = dcs.Point(mission.terrain.bullseye_blue["x"], mission.terrain.bullseye_blue["y"]) - #Statics + # Statics statics_copy = self.statics.copy() for group in statics_copy: - self.groupToPoint(group, self.source_point, dest_point, self.source_heading, dest_heading) - class temp(dcs.unittype.StaticType): id = group.units[0].type name = group.units[0].name @@ -89,7 +91,6 @@ class ImportObjects: can_cargo = group.units[0].can_cargo mass = group.units[0].mass - ng = mission.static_group(mission.country(dest_country_name), dest_name + " " + group.name, temp, @@ -104,9 +105,6 @@ class ImportObjects: return new_groups - - - def copyVehicles(self, mission, dest_country_name, dest_name, dest_point=None, dest_heading=0): logger.info("Copying " + str(len(self.vehicles)) + " vehicle groups as " + dest_name) new_groups = [] @@ -122,30 +120,30 @@ class ImportObjects: for i, unit in enumerate(group.units): if i == 0: ng = mission.vehicle_group(mission.country(dest_country_name), - dest_name + " " + group.name, - dcs.vehicles.vehicle_map[group.units[0].type], - group.units[0].position, - group.units[0].heading) + dest_name + " " + group.name, + dcs.vehicles.vehicle_map[group.units[0].type], + group.units[0].position, + group.units[0].heading) - new_groups.append(ng) # will this hold units we add later? + # ng.units[0].livery_id = group.units[0].livery_id + new_groups.append(ng) else: - u = mission.vehicle(dest_name + " " + group.units[i].name, dcs.vehicles.vehicle_map[group.units[i].type]) - u.position = group.units[i].position - u.heading = group.units[i].heading - ng.add_unit(u) + u = mission.vehicle(dest_name + " " + group.units[i].name, + dcs.vehicles.vehicle_map[group.units[i].type]) + u.position = group.units[i].position + u.heading = group.units[i].heading + # u.livery_id = group.units[i].livery_id + ng.add_unit(u) return new_groups - - def copyHelicopters(self, mission, dest_country_name, dest_name, dest_point=None, dest_heading=0): + def copyHelicopters(self, mission, dest_country_name, dest_name, dest_point, dest_heading=0, + start_type=dcs.mission.StartType.Cold): logger.info("Copying " + str(len(self.helicopters)) + " helicopters as " + dest_name) new_groups = [] - if not dest_point: - dest_point = dcs.Point(mission.terrain.bullseye_blue["x"], mission.terrain.bullseye_blue["y"]) - helicopters_copy = self.helicopters.copy() for group in helicopters_copy: @@ -158,39 +156,46 @@ class ImportObjects: # trying to move the units into position after adding the flight group moves the 2D graphic of the helicopter, but the unit marker remains stacked on top # of the unit marker in ME # farp = mission.country(country_name).find_group(self.pad_unit.name) + # + # farp = mission.farp(mission.country(dest_country_name), dest_name + " " + group.name + " Pad", group.units[0].position, hidden=True, dead=False, + # farp_type=dcs.unit.InvisibleFARP) + # + # + # ng = mission.flight_group_from_unit(mission.country(dest_country_name), + # dest_name + " " + group.name, + # dcs.helicopters.helicopter_map[group.units[0].type], + # farp, + # group_size=1, start_type=start_type) + ng = mission.flight_group(mission.country(dest_country_name), + dest_name + " " + group.name, + dcs.helicopters.helicopter_map[group.units[0].type], + airport=None, + position=group.units[0].position, + group_size=1, start_type=start_type) - farp = mission.farp(mission.country(dest_country_name), dest_name + " " + group.name + " Pad", group.units[0].position, hidden=True, dead=False, - farp_type=dcs.unit.InvisibleFARP) - - - - ng = mission.flight_group_from_unit(mission.country(dest_country_name), - dest_name + " " + group.name, - dcs.helicopters.helicopter_map[group.units[0].type], - farp, - group_size=1) - - ng.points[0].action = dcs.point.PointAction.FromGroundArea - ng.points[0].type = "TakeOffGround" + if start_type == dcs.mission.StartType.Warm: + ng.points[0].action = dcs.point.PointAction.FromGroundAreaHot + ng.points[0].type = "TakeOffGroundHot" + else: + ng.points[0].action = dcs.point.PointAction.FromGroundArea + ng.points[0].type = "TakeOffGround" ng.units[0].heading = group.units[0].heading ng.units[0].skill = group.units[0].skill ng.units[0].livery_id = group.units[0].livery_id ng.units[0].pylons = group.units[0].pylons - + ng.units[0].fuel = group.units[0].fuel + ng.units[0].gun = group.units[0].gun + ng.units[0].hardpoint_racks = group.units[0].hardpoint_racks new_groups.append(ng) else: logger.warn("No pad unit (ie FARP, carrier) found, so can't add helicopters.") return new_groups - - def copyVehiclesAsGroup(self, mission, dest_country_name, dest_name, dest_point=None, dest_heading=0): + def copyVehiclesAsGroup(self, mission, dest_country_name, dest_name, dest_point, dest_heading=0): logger.info("Copying " + str(len(self.vehicles)) + " vehicle groups as single group name: " + dest_name) new_group = None - if not dest_point: - dest_point = dcs.Point(mission.terrain.bullseye_blue["x"], mission.terrain.bullseye_blue["y"]) - unit_count = 0 vehicles_copy = self.vehicles.copy() for group in vehicles_copy: @@ -198,29 +203,32 @@ class ImportObjects: for i, unit in enumerate(group.units): if unit_count == 0: - print("Group:" + group.name) + # print("Group:" + group.name) new_group = mission.vehicle_group(mission.country(dest_country_name), dest_name, dcs.vehicles.vehicle_map[group.units[0].type], group.units[0].position, group.units[0].heading) unit_count = unit_count + 1 + # new_group.units[0].livery_id = group.units[0].livery_id else: - print("Unit:" + group.units[i].name) - u = mission.vehicle(dest_name + " " + group.units[i].name, dcs.vehicles.vehicle_map[group.units[i].type]) + # print("Unit:" + group.units[i].name) + u = mission.vehicle(dest_name + " " + group.units[i].name, + dcs.vehicles.vehicle_map[group.units[i].type]) u.position = group.units[i].position u.heading = group.units[i].heading + + # u.livery_id = group.units[i].livery_id new_group.add_unit(u) unit_count = unit_count + 1 print("Made a group with units: " + str(unit_count)) - print("group actually has units: " + str(len(new_group.units))) + # print("group actually has units: " + str(len(new_group.units))) return new_group - @staticmethod def groupToPoint(group, src_point, dest_point, src_heading=0, dest_heading=0): for unit in group.units: @@ -230,4 +238,4 @@ class ImportObjects: unit_distance = src_point.distance_to_point(unit.position) unit.position = dest_point.point_from_heading(new_heading_to_unit, unit_distance) unit.heading = unit.heading + dest_heading - return group \ No newline at end of file + return group diff --git a/Generator/RotorOpsMission.py b/Generator/RotorOpsMission.py index a2381ba..5b2f929 100644 --- a/Generator/RotorOpsMission.py +++ b/Generator/RotorOpsMission.py @@ -1,10 +1,10 @@ from tokenize import String import dcs +import dcs.cloud_presets import os import random - import RotorOpsGroups import RotorOpsUnits import RotorOpsUtils @@ -18,6 +18,7 @@ from MissionGenerator import directories jtf_red = "Combined Joint Task Forces Red" jtf_blue = "Combined Joint Task Forces Blue" + class RotorOpsMission: def __init__(self): @@ -26,10 +27,11 @@ class RotorOpsMission: self.conflict_zones = {} self.staging_zones = {} self.spawn_zones = {} + self.all_zones = {} self.scripts = {} self.res_map = {} - self.config = None - + self.config = None # not used + self.imports = None class RotorOpsZone: def __init__(self, name: str, flag: int, position: dcs.point, size: int): @@ -38,11 +40,13 @@ class RotorOpsMission: self.position = position self.size = size + self.player_helo_spawns = [] + self.base_position = position def getMission(self): return self.m - def setConfig(self,config): + def setConfig(self, config): self.config = config def addZone(self, zone_dict, zone: RotorOpsZone): @@ -58,12 +62,11 @@ class RotorOpsMission: for filename in dir_list: if filename.endswith(".ogg"): - #print(filename) + # print(filename) key = self.m.map_resource.add_resource_file(filename) self.res_map[filename] = key - - #add all of our lua scripts + # add all of our lua scripts os.chdir(script_directory) path = os.getcwd() dir_list = os.listdir(path) @@ -128,31 +131,54 @@ class RotorOpsMission: logger.info("Looking for mission files in " + os.getcwd()) window.statusBar().showMessage("Loading scenario mission", 10000) + self.m.load_file(options["scenario_file"]) + # Add countries if they're missing + if not self.m.country(jtf_red): + self.m.coalition.get("red").add_country(dcs.countries.CombinedJointTaskForcesRed()) + if not self.m.country(jtf_blue): + self.m.coalition.get("blue").add_country(dcs.countries.CombinedJointTaskForcesBlue()) + if not self.m.country( + dcs.countries.UnitedNationsPeacekeepers.name): + self.m.coalition.get("neutrals").add_country(dcs.countries.UnitedNationsPeacekeepers()) + if not self.m.country("Russia"): + self.m.coalition.get("red").add_country(dcs.countries.Russia()) + if not self.m.country("USA"): + self.m.coalition.get("blue").add_country(dcs.countries.USA()) + self.addMods() - self.importObjects() + self.importObjects(options) - #todo: test - self.m.coalition.get("neutrals").add_country(dcs.countries.UnitedNationsPeacekeepers()) - - if not self.m.country(jtf_red) or not self.m.country(jtf_blue) or not self.m.country(dcs.countries.UnitedNationsPeacekeepers.name): - failure_msg = "You must include a CombinedJointTaskForcesBlue and CombinedJointTaskForcesRed unit in the scenario template. See the instructions in " + directories.scenarios - return {"success": False, "failure_msg": failure_msg} - - # red_forces = self.getUnitsFromMiz(directories.forces + "/red/" + options["red_forces_filename"], "red") - # blue_forces = self.getUnitsFromMiz(directories.forces + "/blue/" + options["blue_forces_filename"], "blue") - red_forces = self.getUnitsFromMiz(directories.forces + "/" + options["red_forces_filename"], "both") - blue_forces = self.getUnitsFromMiz(directories.forces + "/" + options["blue_forces_filename"], "both") - - # Add coalitions (we may be able to add CJTF here instead of requiring templates to have objects of those coalitions) - self.m.coalition.get("red").add_country(dcs.countries.Russia()) - self.m.coalition.get("blue").add_country(dcs.countries.USA()) - # blue = self.m.coalition.get("blue") - # blue.add_country(dcs.countries.CombinedJointTaskForcesBlue()) + red_forces = self.getUnitsFromMiz(options["red_forces_path"], "both") + blue_forces = self.getUnitsFromMiz(options["blue_forces_path"], "both") + # add images to briefing self.m.add_picture_blue(directories.assets + '/briefing1.png') self.m.add_picture_blue(directories.assets + '/briefing2.png') + # get import objects for generic farps etc + self.imports = options["objects"]["imports"] + + activated_farp = None + defensive_farp = None + logistics_farp = None + logistics_base = None + zone_protect = None + + for i in self.imports: + if i.filename == ("FARP_ACTIVATED_ZONE.miz"): + activated_farp = i.path + if i.filename == ("FARP_DEFENSIVE_ZONE.miz"): + defensive_farp = i.path + if i.filename == ("FARP_LOGISTICS_ZONE.miz"): + logistics_farp = i.path + if i.filename == ("STAGING_LOGISTICS_BASE.miz"): + logistics_base = i.path + if i.filename == ("ZONE_ACTIVATED_DEFENSE.miz"): + zone_protect = i.path + + # it's possible to have import templates with the same filename, but we will let the latest override others + # todo: verify we have the required templates # add zones to target mission zone_names = ["ALPHA", "BRAVO", "CHARLIE", "DELTA"] @@ -160,150 +186,375 @@ class RotorOpsMission: for zone_name in zone_names: for zone in self.m.triggers.zones(): if zone.name == zone_name: - self.addZone(self.conflict_zones, self.RotorOpsZone(zone_name, zone_flag, zone.position, zone.radius)) + self.addZone(self.conflict_zones, + self.RotorOpsZone(zone_name, zone_flag, zone.position, zone.radius)) zone_flag = zone_flag + 1 - for zone in self.m.triggers.zones(): - if zone.name.rfind("STAGING") >= 0: + self.addZone(self.all_zones, self.RotorOpsZone(zone.name, None, zone.position, zone.radius)) + if zone_name == "STAGING": + self.addZone(self.staging_zones, self.RotorOpsZone(zone.name, None, zone.position, zone.radius)) + continue + if zone.name.rfind("STAGING") >= 0: # find additional staging zones self.addZone(self.staging_zones, self.RotorOpsZone(zone.name, None, zone.position, zone.radius)) elif zone.name.rfind("SPAWN") >= 0: self.addZone(self.spawn_zones, self.RotorOpsZone(zone.name, None, zone.position, zone.radius)) - blue_zones = self.staging_zones red_zones = self.conflict_zones if options["defending"]: blue_zones = self.conflict_zones red_zones = self.staging_zones - #swap airport sides + # swap airport sides self.swapSides(options) - - - #Populate Red zones with ground units + # Populate Red zones with ground units window.statusBar().showMessage("Populating units into mission...", 10000) + start_type = dcs.mission.StartType.Cold + if options["player_hotstart"]: + start_type = dcs.mission.StartType.Warm + + # Adds vehicles as a single group (for easy late activation), and helicopters if enabled in settings + # def addZoneFARP(_zone_name, country, file): + # + # farp_flag = self.m.find_group(_zone_name) + # + # if farp_flag: + # farp_position = farp_flag.units[0].position + # farp_heading = farp_flag.units[0].heading + # else: + # farp_position = self.all_zones[_zone_name].position + # farp_heading = 0 + # + # # Add the basic invisible farp object + # farp = self.m.farp(self.m.country(country), _zone_name + " FARP", farp_position, + # hidden=False, dead=False, + # farp_type=dcs.unit.InvisibleFARP) + # + # # Use alternate template file if it has been defined in scenario config + # if options["zone_farp_file"]: + # + # for i in imports: + # if i.filename.removesuffix('.miz') == options["zone_farp_file"]: + # file = i.path + # # if multiple files found, we want the latest file to override the first + # + # i = ImportObjects(file) + # i.anchorByGroupName("ANCHOR") + # farp_group = i.copyVehiclesAsGroup(self.m, country, _zone_name + " FARP Static", farp_position, + # farp_heading) + # # Add client helicopters + # if options["farp_spawns"]: + # helicopter_groups = i.copyHelicopters(self.m, jtf_blue, "ZONE " + _zone_name + " EMPTY ", farp_position, farp_heading) + # for group in helicopter_groups: + # self.all_zones[_zone_name].player_helo_spawns.append(group) + # + # return farp_group + + # # Adds statics, vehicles, and helicopters. Late activation is not possible + # def addLogisticsZone(_zone_name, country, file, config_name, helicopters=False): + # flag = self.m.find_group(_zone_name) + # if flag: + # position = flag.units[0].position + # heading = flag.units[0].heading + # else: + # position = self.all_zones[_zone_name].position + # heading = 0 + # + # # Use alternate template file if it has been defined in scenario config + # if options[config_name]: + # + # for i in imports: + # if i.filename.removesuffix('.miz') == options[config_name]: + # file = i.path + # # if multiple files found, we want the latest file to override the first + # + # # Import statics and vehicles + # i = ImportObjects(file) + # i.anchorByGroupName("ANCHOR") + # i.copyStatics(self.m, country, _zone_name + " Logistics Zone", + # position, heading) + # i.copyVehicles(self.m, country, _zone_name + " Logistics Zone", + # position, heading) + # + # # Add client helicopters + # if helicopters: + # helicopter_groups = i.copyHelicopters(self.m, jtf_blue, "ZONE " + _zone_name + " EMPTY ", position, + # heading) + # for group in helicopter_groups: + # self.all_zones[_zone_name].player_helo_spawns.append(group) + + # Adds statics, vehicles, and helicopters (if enabled). Late activation is not possible. + # def addDefensiveFARP(_zone_name, country, file): + # + # farp_flag = self.m.find_group(_zone_name) + # + # if farp_flag: + # farp_position = farp_flag.units[0].position + # farp_heading = farp_flag.units[0].heading + # else: + # farp_position = self.all_zones[_zone_name].position + # farp_heading = 0 + # + # # Add the basic invisible farp object + # farp = self.m.farp(self.m.country(country), _zone_name + " FARP", farp_position, + # hidden=False, dead=False, + # farp_type=dcs.unit.InvisibleFARP) + # + # # Use alternate template file if it has been defined in scenario config + # if options["defensive_farp_file"]: + # + # for i in imports: + # if i.filename.removesuffix('.miz') == options["defensive_farp_file"]: + # file = i.path + # # if multiple files found, we want the latest file to override the first + # + # # Import statics and vehicles + # i = ImportObjects(file) + # i.anchorByGroupName("ANCHOR") + # i.copyStatics(self.m, country, _zone_name + " Logistics Zone", + # farp_position, farp_heading) + # i.copyVehicles(self.m, country, _zone_name + " Logistics Zone", + # farp_position, farp_heading) + # + # # Import player helicopters + # if options["farp_spawns"]: + # helicopter_groups = i.copyHelicopters(self.m, jtf_blue, "ZONE " + _zone_name + " EMPTY ", farp_position, + # farp_heading) + # for group in helicopter_groups: + # self.all_zones[_zone_name].player_helo_spawns.append(group) for zone_name in red_zones: if red_forces["vehicles"]: - self.addGroundGroups(red_zones[zone_name], self.m.country(jtf_red), red_forces["vehicles"], options["red_quantity"]) - - #Add red FARPS + self.addGroundGroups(red_zones[zone_name], self.m.country(jtf_red), red_forces["vehicles"], + options["red_quantity"]) if options["zone_farps"] != "farp_never" and not options["defending"]: - # RotorOpsGroups.VehicleTemplate.CombinedJointTaskForcesBlue.zone_farp(self.m, self.m.country(jtf_blue), - # self.m.country(jtf_blue), - # red_zones[zone_name].position, - # 180, zone_name + " FARP", late_activation=True) - - #new_statics, new_vehicles, new_helicopters = i.copyAll(self.m, dcs.countries.UnitedNationsPeacekeepers.name, zone_name, red_zones[zone_name].position) - - farp_flag = self.m.find_group(zone_name) - - if farp_flag: - farp_position = farp_flag.units[0].position - farp_heading = farp_flag.units[0].heading - else: - farp_position = red_zones[zone_name].position - farp_heading = 0 - - farp = self.m.farp(self.m.country(jtf_blue), zone_name + " FARP", farp_position, - hidden=False, dead=False, - farp_type=dcs.unit.InvisibleFARP) - - os.chdir(directories.imports) - if self.config and self.config["zone_farp_file"]: - filename = self.config["zone_farp_file"] - else: - filename = "FARP_DEFAULT_ZONE.miz" - i = ImportObjects(filename) - i.anchorByGroupName("ANCHOR") - farp_group = i.copyVehiclesAsGroup(self.m, jtf_blue, zone_name + " FARP Static", farp_position, farp_heading) - farp_group.late_activation = True + helicopters = False + if options["farp_spawns"]: + helicopters = True + # Add red zone FARPS + vehicle_group = self.addZoneBase(options, zone_name, jtf_blue, + file=activated_farp, + config_name="zone_farp_file", + copy_helicopters=helicopters, + helicopters_name="ZONE " + zone_name + " EMPTY", + heli_start_type=dcs.mission.StartType.Cold, + copy_vehicles=True, + vehicles_name=zone_name + " FARP Static", + copy_statics=False, + statics_names="", + vehicles_single_group=True, + trigger_name=zone_name + "_FARP", + trigger_radius=110 + ) + vehicle_group.late_activation = True + # For SAMs: Add vehicles as a single group (for easy late activation) if options["zone_protect_sams"]: - self.m.vehicle_group( - self.m.country(jtf_red), - "Static " + zone_name + " Protection SAM", - random.choice(RotorOpsUnits.e_zone_sams), - red_zones[zone_name].position, - heading=random.randint(0, 359), - group_size=6, - formation=dcs.unitgroup.VehicleGroup.Formation.Star - ) + sam_group = self.addZoneBase(options, zone_name, jtf_red, + file=zone_protect, + config_name="zone_protect_file", + copy_vehicles=True, + vehicles_name=zone_name + " Protect Static", + vehicles_single_group=True + ) + # farp_flag = self.m.find_group(zone_name) + # + # if farp_flag: + # farp_position = farp_flag.units[0].position + # farp_heading = farp_flag.units[0].heading + # else: + # farp_position = self.all_zones[zone_name].position + # farp_heading = 0 + # + # i = ImportObjects(zone_protect) + # i.anchorByGroupName("ANCHOR") + # farp_group = i.copyVehiclesAsGroup(self.m, jtf_red, "Static " + zone_name + " Protection SAM", + # farp_position, + # farp_heading) - - - #Populate Blue zones with ground units - for zone_name in blue_zones: + # Populate Blue zones with ground units + for i, zone_name in enumerate(blue_zones): if blue_forces["vehicles"]: self.addGroundGroups(blue_zones[zone_name], self.m.country(jtf_blue), blue_forces["vehicles"], options["blue_quantity"]) - #Add blue FARPS + + # Add blue zone FARPS (not late activated) for defensive mode if options["zone_farps"] != "farp_never" and options["defending"]: - RotorOpsGroups.VehicleTemplate.CombinedJointTaskForcesBlue.zone_farp(self.m, self.m.country(jtf_blue), - self.m.country(jtf_blue), - blue_zones[zone_name].position, - 180, zone_name + " FARP", late_activation=False) - #add logistics sites - if options["crates"] and zone_name == "STAGING": - os.chdir(directories.imports) - staging_flag = self.m.find_group(zone_name) - if staging_flag: - staging_position = staging_flag.units[0].position - staging_heading = staging_flag.units[0].heading + helicopters = False + if options["farp_spawns"]: + helicopters = True + + if options["crates"] and i == len(blue_zones) - 1: + # add a logistics zone to the last conflict zone + # addLogisticsZone(zone_name, jtf_blue, logistics_farp, "logistics_farp_file", helicopters) + self.addZoneBase(options, zone_name, jtf_blue, + file=logistics_farp, + config_name="logistics_farp_file", + copy_helicopters=helicopters, + helicopters_name="ZONE " + zone_name + " LOGISTICS", + heli_start_type=start_type, + copy_vehicles=True, + vehicles_name=zone_name + " Logistics FARP", + copy_statics=True, + statics_names=zone_name + " Logistics FARP", + vehicles_single_group=False, + trigger_name=zone_name + "_FARP", + trigger_radius=110 + ) else: - staging_position = blue_zones[zone_name].position - staging_heading = 0 - i = ImportObjects("STAGING_LOGISTIC_HUB.miz") - i.anchorByGroupName("ANCHOR") - i.copyAll(self.m, jtf_blue, "Staging Logistics Zone", - staging_position, staging_heading) + # addDefensiveFARP(zone_name, jtf_blue, defensive_farp) + self.addZoneBase(options, zone_name, jtf_blue, + file=defensive_farp, + config_name="defensive_farp_file", + copy_helicopters=helicopters, + helicopters_name="ZONE " + zone_name + " EMPTY", + heli_start_type=dcs.mission.StartType.Cold, + copy_vehicles=True, + vehicles_name=zone_name + " Defensive FARP", + copy_statics=True, + statics_names=zone_name + " Defensive FARP", + vehicles_single_group=False, + trigger_name=zone_name + "_FARP", + trigger_radius=110 + ) - if options["zone_protect_sams"] and options["defending"]: - vg = self.m.vehicle_group( - self.m.country(jtf_blue), - "Static " + zone_name + " Protection SAM", - random.choice(RotorOpsUnits.e_zone_sams), - blue_zones[zone_name].position, - heading=random.randint(0, 359), - group_size=6, - formation=dcs.unitgroup.VehicleGroup.Formation.Star - ) + # add main logistics base + if options["crates"] and zone_name == "STAGING": + # addLogisticsZone(zone_name, jtf_blue, logistics_base, "staging_logistics_file", helicopters=True) + self.addZoneBase(options, zone_name, jtf_blue, + file=logistics_base, + config_name="staging_logistics_file", + copy_helicopters=True, + helicopters_name="ZONE " + zone_name + " LOGISTICS", + heli_start_type=start_type, + copy_vehicles=True, + vehicles_name=zone_name + " Logistics Base", + copy_statics=True, + statics_names=zone_name + " Logistics Base", + vehicles_single_group=False, + trigger_name="STAGING_BASE", + trigger_radius=170 + ) - - #Add player slots + # Add player slots window.statusBar().showMessage("Adding flights to mission...", 10000) if options["slots"] != "Locked to Scenario" and options["slots"] != "None": self.addPlayerHelos(options) - #Add AI Flights + # Add AI Flights self.addFlights(options, red_forces, blue_forces) - #Set the Editor Map View + # Set the Editor Map View self.m.map.position = self.conflict_zones["ALPHA"].position self.m.map.zoom = 100000 - #add files and triggers necessary for RotorOps.lua script + # add files and triggers necessary for RotorOps.lua script window.statusBar().showMessage("Adding resources to mission...", 10000) self.addResources(directories.sound, directories.scripts) RotorOpsConflict.triggerSetup(self, options) + # finalize the mission briefing + briefing = self.m.description_text() + '## RotorOps Credits ##\n\n' + options["credits"] + briefing = briefing + "\nFor more info on RotorOps, visit: DCS-HELICOPTERS.COM" + self.m.set_description_text(briefing) - #Save the mission file + # set the weather and time + + if options["random_weather"]: + # self.m.random_weather = True + max = len(dcs.cloud_presets.CLOUD_PRESETS) - 1 + preset_name = list(dcs.cloud_presets.CLOUD_PRESETS)[random.randint(0, max)] + cloud_preset = dcs.weather.CloudPreset.by_name(preset_name) + self.m.weather.clouds_base = random.randrange(cloud_preset.min_base, cloud_preset.max_base) + self.m.weather.clouds_preset = cloud_preset + wind_dir = random.randrange(0, 359) + 180 + wind_speed = random.randrange(5, 10) + self.m.weather.wind_at_ground.direction = (wind_dir + random.randrange(-90, 90) - 180) % 360 + self.m.weather.wind_at_ground.speed = wind_speed + random.randrange(-4, -1) + self.m.weather.wind_at_2000.direction = (wind_dir + random.randrange(-90, 90) - 180) % 360 + self.m.weather.wind_at_2000.speed = wind_speed + random.randrange(-2, 2) + self.m.weather.wind_at_8000.direction = (wind_dir + random.randrange(-90, 90) - 180) % 360 + self.m.weather.wind_at_8000.speed = wind_speed + random.randrange(-1, 10) + + logger.info("Cloud preset = " + cloud_preset.ui_name + ", ground windspeed = " + str( + self.m.weather.wind_at_ground.speed)) + + if options["time"] != "Default Time": + self.m.random_daytime(options["time"].lower()) + + # Save the mission file window.statusBar().showMessage("Saving mission...", 10000) if window.user_output_dir: - output_dir = window.user_output_dir # if user has set output dir + output_dir = window.user_output_dir # if user has set output dir else: - output_dir = directories.output # default dir + output_dir = directories.output # default dir os.chdir(output_dir) output_filename = options["scenario_name"] + " " + time.strftime('%a%H%M%S') + '.miz' success = self.m.save(output_filename) - return {"success": success, "filename": output_filename, "directory": output_dir} #let the UI know the result + return {"success": success, "filename": output_filename, "directory": output_dir} # let the UI know the result + + # Use the ImportObjects class to place farps and bases + def addZoneBase(self, options, _zone_name, country, file, config_name=None, copy_helicopters=False, + helicopters_name="", heli_start_type=dcs.mission.StartType.Cold, + copy_vehicles=False, vehicles_name="", copy_statics=False, statics_names="", + vehicles_single_group=False, trigger_name=None, trigger_radius=110, farp=True): + + # look for a marker object to position the base at a position other than zone center + flag = self.m.find_group(_zone_name) + if flag: + position = flag.units[0].position + heading = flag.units[0].heading + self.all_zones[_zone_name].base_position = position + else: + position = self.all_zones[_zone_name].position + heading = 0 + + if farp: + farp = self.m.farp(self.m.country(country), _zone_name + " FARP", + position, hidden=True, dead=False, farp_type=dcs.unit.InvisibleFARP) + + # Add a trigger zone + if trigger_name: + self.m.triggers.add_triggerzone(position, trigger_radius, False, trigger_name) + + # Use alternate template file if it has been defined in scenario config + if config_name and options[config_name]: + + for i in self.imports: + if i.filename.removesuffix('.miz') == options[config_name]: + file = i.path + # if multiple files found, we want the latest file to override the first + + # Import statics and vehicles + i = ImportObjects(file) + i.anchorByGroupName("ANCHOR") + + if copy_statics: + i.copyStatics(self.m, country, statics_names, + position, heading) + vehicle_group = None + if copy_vehicles: + if vehicles_single_group: + vehicle_group = i.copyVehiclesAsGroup(self.m, country, vehicles_name, position, + heading) + else: + i.copyVehicles(self.m, country, vehicles_name, + position, heading) + + # Add client helicopters and farp objects + if copy_helicopters: + helicopter_groups = i.copyHelicopters(self.m, jtf_blue, helicopters_name, position, + heading, heli_start_type) + for group in helicopter_groups: + self.all_zones[_zone_name].player_helo_spawns.append(group) + + return vehicle_group # for setting properties such as late activation def addGroundGroups(self, zone, _country, groups, quantity): for a in range(0, quantity): @@ -316,14 +567,13 @@ class RotorOpsMission: country = self.m.country(_country.name) self.m.vehicle_group_platoon( country, - zone.name + '-GND ' + str(a+1), + zone.name + '-GND ' + str(a + 1), unit_types, - zone.position.random_point_within(zone.size / 1.2, 100), + zone.position.random_point_within(zone.size / 1.3, 100), heading=random.randint(0, 359), formation=dcs.unitgroup.VehicleGroup.Formation.Scattered, ) - def getCoalitionAirports(self, side: str): coalition_airports = [] primary_airport = None @@ -335,7 +585,8 @@ class RotorOpsMission: coalition_airports.append(airportobj) start = self.staging_zones[list(self.staging_zones)[0]] - dist_from_start = dcs.mapping._distance(airportobj.position.x, airportobj.position.y, start.position.x, start.position.y) + dist_from_start = dcs.mapping._distance(airportobj.position.x, airportobj.position.y, start.position.x, + start.position.y) if dist_from_start < shortest_dist: primary_airport = airportobj @@ -346,10 +597,10 @@ class RotorOpsMission: def getParking(self, airport, aircraft, alt_airports=None, group_size=1): if len(airport.free_parking_slots(aircraft)) >= group_size: - if not (aircraft.id in dcs.planes.plane_map and (len(airport.runways) == 0 or airport.runways[0].ils is None)): + if not (aircraft.id in dcs.planes.plane_map and ( + len(airport.runways) == 0 or airport.runways[0].ils is None)): return airport - if alt_airports: for airport in alt_airports: if len(airport.free_parking_slots(aircraft)) >= group_size: @@ -359,14 +610,13 @@ class RotorOpsMission: logger.warn("No parking available for " + aircraft.id) return None - #Find parking spots on FARPs and carriers + # Find parking spots on FARPs and carriers def getUnitParking(self, aircraft): return - def swapSides(self, options): - #Swap airports + # Swap airports blue_airports, primary_blue = self.getCoalitionAirports("blue") red_airports, primary_red = self.getCoalitionAirports("red") @@ -379,8 +629,7 @@ class RotorOpsMission: combinedJointTaskForcesBlue = self.m.country(jtf_blue) combinedJointTaskForcesRed = self.m.country(jtf_red) - - #Swap ships + # Swap ships blue_ships = combinedJointTaskForcesBlue.ship_group.copy() red_ships = combinedJointTaskForcesRed.ship_group.copy() @@ -390,14 +639,11 @@ class RotorOpsMission: combinedJointTaskForcesRed.add_ship_group(group) combinedJointTaskForcesBlue.ship_group.remove(group) - for group in red_ships: combinedJointTaskForcesBlue.add_ship_group(group) combinedJointTaskForcesRed.ship_group.remove(group) - - - #Swap statics + # Swap statics blue_statics = combinedJointTaskForcesBlue.static_group.copy() red_statics = combinedJointTaskForcesRed.static_group.copy() @@ -410,8 +656,7 @@ class RotorOpsMission: combinedJointTaskForcesRed.static_group.remove(group) combinedJointTaskForcesBlue.add_static_group(group) - - #Swap vehicles + # Swap vehicles blue_vehicles = combinedJointTaskForcesBlue.vehicle_group.copy() red_vehicles = combinedJointTaskForcesRed.vehicle_group.copy() @@ -424,8 +669,7 @@ class RotorOpsMission: combinedJointTaskForcesRed.vehicle_group.remove(group) combinedJointTaskForcesBlue.add_vehicle_group(group) - - #Swap planes + # Swap planes blue_planes = combinedJointTaskForcesBlue.plane_group.copy() red_planes = combinedJointTaskForcesRed.plane_group.copy() @@ -438,7 +682,6 @@ class RotorOpsMission: combinedJointTaskForcesRed.plane_group.remove(group) combinedJointTaskForcesBlue.add_plane_group(group) - # Swap helicopters blue_helos = combinedJointTaskForcesBlue.helicopter_group.copy() @@ -452,12 +695,15 @@ class RotorOpsMission: combinedJointTaskForcesRed.helicopter_group.remove(group) combinedJointTaskForcesBlue.add_helicopter_group(group) - def addPlayerHelos(self, options): client_helos = RotorOpsUnits.client_helos + unslotted_count = 0 + slotted_count = 0 + for helicopter in dcs.helicopters.helicopter_map: if helicopter == options["slots"]: - client_helos = [dcs.helicopters.helicopter_map[helicopter]] #if out ui slot option matches a specific helicopter type name + client_helos = [dcs.helicopters.helicopter_map[ + helicopter]] # if out ui slot option matches a specific helicopter type name # get loadouts from miz file and put into a simple dict default_loadouts = {} @@ -468,7 +714,7 @@ class RotorOpsMission: default_loadouts[helicopter_group.units[0].unit_type.id]["livery_id"] = helicopter_group.units[0].livery_id default_loadouts[helicopter_group.units[0].unit_type.id]["fuel"] = helicopter_group.units[0].fuel - #find friendly carriers and farps + # find friendly carriers and farps carrier = self.m.country(jtf_blue).find_ship_group(name="HELO_CARRIER") if not carrier: carrier = self.m.country(jtf_blue).find_ship_group(name="HELO_CARRIER_1") @@ -476,62 +722,113 @@ class RotorOpsMission: farp = self.m.country(jtf_blue).find_static_group("HELO_FARP") if not farp: farp = self.m.country(jtf_blue).find_static_group("HELO_FARP_1") + heading = 0 + if farp: + farp_heading = farp.units[0].heading + heading = farp_heading friendly_airports, primary_f_airport = self.getCoalitionAirports("blue") - heading = 0 + group_size = 1 player_helicopters = [] if options["slots"] == "Multiple Slots": player_helicopters = options["player_slots"] else: - player_helicopters.append(options["slots"]) # single helicopter type + player_helicopters.append(options["slots"]) # single helicopter type if len(client_helos) == 1: - group_size = 2 #add a wingman if singleplayer + group_size = 2 # add a wingman if singleplayer + # Hot/Cold start options start_type = dcs.mission.StartType.Cold + start_type_string = "" + start_type_point_type = "TakeOffGround" + start_type_action = dcs.point.PointAction.FromGroundArea if options["player_hotstart"]: start_type = dcs.mission.StartType.Warm + start_type_string = "HOT " + start_type_point_type = "TakeOffGroundHot" + start_type_action = dcs.point.PointAction.FromGroundAreaHot farp_helicopter_count = 1 for helicopter_id in player_helicopters: + fg = None helotype = None if helicopter_id in dcs.helicopters.helicopter_map: helotype = dcs.helicopters.helicopter_map[helicopter_id] else: continue if carrier: - fg = self.m.flight_group_from_unit(self.m.country(jtf_blue), "CARRIER " + helotype.id, helotype, carrier, + fg = self.m.flight_group_from_unit(self.m.country(jtf_blue), + "CARRIER " + start_type_string + helotype.id, helotype, + carrier, dcs.task.CAS, group_size=group_size, start_type=start_type) + elif farp and farp_helicopter_count <= 4: - farp_helicopter_count = farp_helicopter_count + 1 - fg = self.m.flight_group_from_unit(self.m.country(jtf_blue), "FARP " + helotype.id, helotype, farp, - dcs.task.CAS, group_size=group_size, start_type=start_type) - #invisible farps need manual unit placement for multiple units - if farp.units[0].type == 'Invisible FARP': - fg.points[0].action = dcs.point.PointAction.FromGroundArea - fg.points[0].type = "TakeOffGround" - fg.units[0].position = fg.units[0].position.point_from_heading(heading, 20) + + #old ugly FARPs, or single player groups with wingman require fg from unit + if farp.units[0].type != 'Invisible FARP': + print("making flight group from unit") + fg = self.m.flight_group_from_unit(self.m.country(jtf_blue), + "FARP " + start_type_string + helotype.id, helotype, farp, + dcs.task.CAS, group_size=group_size, start_type=start_type) + + # invisible farps need manual unit placement for multiple units + elif farp.units[0].type == 'Invisible FARP': + print("making standard flight group") + pos = farp.units[0].position.point_from_heading(heading, 20) + farp_helicopter_count = farp_helicopter_count + 1 + + fg = self.m.flight_group(self.m.country(jtf_blue), "FARP " + start_type_string + helotype.id, + helotype, airport=None, position=pos, maintask=dcs.task.CAS, group_size=group_size, start_type=start_type) + + fg.units[0].heading = farp_heading + + if group_size > 1: + # move wingman if present + fg.units[1].position = farp.units[0].position.point_from_heading(180, 20) + fg.units[1].heading = farp_heading + + # change heading for next helicopter placement heading += 90 + + # hot or cold start + fg.points[0].action = start_type_action + fg.points[0].type = start_type_point_type else: - fg = self.m.flight_group_from_airport(self.m.country(jtf_blue), primary_f_airport.name + " " + helotype.id, helotype, - self.getParking(primary_f_airport, helotype), group_size=group_size, start_type=start_type) - fg.units[0].set_client() - #fg.load_task_default_loadout(dcs.task.CAS) - if helotype.id in default_loadouts: - fg.units[0].pylons = default_loadouts[helotype.id]["pylons"] - fg.units[0].livery_id = default_loadouts[helotype.id]["livery_id"] - fg.units[0].fuel = default_loadouts[helotype.id]["fuel"] + parking = self.getParking(primary_f_airport, helotype, friendly_airports, + group_size=group_size) + if parking: + fg = self.m.flight_group_from_airport(self.m.country(jtf_blue), + primary_f_airport.name + " " + start_type_string + helotype.id, + helotype, + parking, group_size=group_size, start_type=start_type) - #setup wingman for single player - if len(fg.units) == 2: - fg.units[1].skill = dcs.unit.Skill.High - fg.units[1].pylons = fg.units[0].pylons - fg.units[1].livery_id = fg.units[0].livery_id - fg.units[1].fuel = fg.units[0].fuel + # if we were able to find a slot and create a flight group + if fg: + slotted_count = slotted_count + 1 + fg.units[0].set_client() + # fg.load_task_default_loadout(dcs.task.CAS) + if helotype.id in default_loadouts: + fg.units[0].pylons = default_loadouts[helotype.id]["pylons"] + fg.units[0].livery_id = default_loadouts[helotype.id]["livery_id"] + fg.units[0].fuel = default_loadouts[helotype.id]["fuel"] + # setup wingman for single player + if len(fg.units) == 2: + fg.units[1].skill = dcs.unit.Skill.High + fg.units[1].pylons = fg.units[0].pylons + fg.units[1].livery_id = fg.units[0].livery_id + fg.units[1].fuel = fg.units[0].fuel + else: + logger.warn("No parking available for " + helotype.id) + unslotted_count = unslotted_count + 1 + + if unslotted_count > 0: + raise Exception("Player slots error: Unable to find parking for " + str( + unslotted_count) + " players. Maximum parking slots found was " + str(slotted_count)) class TrainingScenario(): @staticmethod @@ -546,10 +843,12 @@ class RotorOpsMission: @staticmethod def perpRacetrack(enemy_heading, friendly_pt, terrain): - heading = enemy_heading + random.randrange(70,110) + heading = enemy_heading + random.randrange(70, 110) race_dist = random.randrange(40 * 1000, 80 * 1000) - center_pt = dcs.mapping.point_from_heading(friendly_pt.x, friendly_pt.y, enemy_heading - random.randrange(140, 220), 10000) - pt1 = dcs.mapping.point_from_heading(center_pt[0], center_pt[1], enemy_heading - 90, random.randrange(20 * 1000, 40 * 1000)) + center_pt = dcs.mapping.point_from_heading(friendly_pt.x, friendly_pt.y, + enemy_heading - random.randrange(140, 220), 10000) + pt1 = dcs.mapping.point_from_heading(center_pt[0], center_pt[1], enemy_heading - 90, + random.randrange(20 * 1000, 40 * 1000)) return dcs.mapping.Point(pt1[0], pt1[1], terrain), heading, race_dist def addFlights(self, options, red_forces, blue_forces): @@ -558,7 +857,7 @@ class RotorOpsMission: friendly_airports, primary_f_airport = self.getCoalitionAirports("blue") enemy_airports, primary_e_airport = self.getCoalitionAirports("red") - #find enemy carriers and farps + # find enemy carriers and farps carrier = self.m.country(jtf_red).find_ship_group(name="HELO_CARRIER") if not carrier: carrier = self.m.country(jtf_red).find_ship_group(name="HELO_CARRIER_1") @@ -568,19 +867,21 @@ class RotorOpsMission: farp = self.m.country(jtf_red).find_static_group("HELO_FARP_1") e_airport_heading = dcs.mapping.heading_between_points( - friendly_airports[0].position.x, friendly_airports[0].position.y, enemy_airports[0].position.x, primary_e_airport.position.y + friendly_airports[0].position.x, friendly_airports[0].position.y, enemy_airports[0].position.x, + primary_e_airport.position.y ) e_airport_distance = dcs.mapping._distance( - primary_f_airport.position.x, primary_f_airport.position.y, primary_f_airport.position.x, primary_f_airport.position.y + primary_f_airport.position.x, primary_f_airport.position.y, primary_f_airport.position.x, + primary_f_airport.position.y ) - if options["f_awacs"]: awacs_name = "AWACS" awacs_freq = 266 - #pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) - pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, self.m.terrain) + # pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) + pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, + self.m.terrain) awacs = self.m.awacs_flight( combinedJointTaskForcesBlue, awacs_name, @@ -613,8 +914,7 @@ class RotorOpsMission: unit.pylons = source_plane.pylons unit.livery_id = source_plane.livery_id - - #add text to mission briefing with radio freq + # add text to mission briefing with radio freq briefing = self.m.description_text() + "\n\n" + awacs_name + " " + str(awacs_freq) + ".00 " + "\n" self.m.set_description_text(briefing) @@ -625,8 +925,9 @@ class RotorOpsMission: t2_name = "Tanker KC_135 Boom" t2_freq = 256 t2_tac = "101Y" - #pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) - pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, self.m.terrain) + # pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) + pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, + self.m.terrain) refuel_net = self.m.refuel_flight( combinedJointTaskForcesBlue, t1_name, @@ -641,8 +942,9 @@ class RotorOpsMission: frequency=t1_freq, tacanchannel=t1_tac) - #pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) - pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, self.m.terrain) + # pos, heading, race_dist = self.TrainingScenario.random_orbit(orbit_rect) + pos, heading, race_dist = self.TrainingScenario.perpRacetrack(e_airport_heading, primary_f_airport.position, + self.m.terrain) refuel_rod = self.m.refuel_flight( combinedJointTaskForcesBlue, t2_name, @@ -655,8 +957,9 @@ class RotorOpsMission: frequency=t2_freq, tacanchannel=t2_tac) - #add text to mission briefing - briefing = self.m.description_text() + "\n\n" + t1_name + " " + str(t1_freq) + ".00 " + t1_tac + "\n" + t2_name + " " + str(t2_freq) + ".00 " + t2_tac + "\n" + # add text to mission briefing + briefing = self.m.description_text() + "\n\n" + t1_name + " " + str( + t1_freq) + ".00 " + t1_tac + "\n" + t2_name + " " + str(t2_freq) + ".00 " + t2_tac + "\n\n" self.m.set_description_text(briefing) def zone_attack(fg, airport): @@ -676,9 +979,6 @@ class RotorOpsMission: fg.points[0].tasks.append(dcs.task.OptReactOnThreat(dcs.task.OptReactOnThreat.Values.EvadeFire)) fg.points[0].tasks.append(dcs.task.OptROE(dcs.task.OptROE.Values.OpenFire)) - - - if options["e_attack_helos"]: source_helo = None if red_forces["attack_helos"]: @@ -714,7 +1014,7 @@ class RotorOpsMission: farp, maintask=dcs.task.CAS, start_type=dcs.mission.StartType.Cold, - group_size=1) # more than one spawn on top of each other, setting group size to one for now + group_size=1) # more than one spawn on top of each other, setting group size to one for now zone_attack(afg, farp) elif airport: @@ -736,8 +1036,6 @@ class RotorOpsMission: unit.pylons = source_helo.pylons unit.livery_id = source_helo.livery_id - - if options["e_attack_planes"]: source_plane = None if red_forces["attack_planes"]: @@ -795,12 +1093,9 @@ class RotorOpsMission: unit.pylons = source_helo.pylons unit.livery_id = source_helo.livery_id + def importObjects(self, data): - - - def importObjects(self): - os.chdir(directories.imports) - logger.info("Looking for import .miz files in '" + os.getcwd()) + imports = data["objects"]["imports"] for side in "red", "blue", "neutrals": coalition = self.m.coalition.get(side) @@ -810,9 +1105,11 @@ class RotorOpsMission: if group.name.find(prefix) == 0: if group.units[0].name.find('IMPORT-') == 0: logger.error( - group.units[0].name + " IMPORT group's unit name cannot start with 'IMPORT'. Check the scenario template.") - raise Exception("Scenario file error: " + group.units[0].name + " IMPORT group's unit name cannot start with 'IMPORT'") - + group.units[ + 0].name + " IMPORT group's unit name cannot start with 'IMPORT'. Check the scenario template.") + raise Exception("Scenario file error: " + group.units[ + 0].name + " IMPORT group's unit name cannot start with 'IMPORT'") + # trim the groupname to our filename convention filename = group.name.removeprefix(prefix) i = filename.find('-') @@ -820,10 +1117,16 @@ class RotorOpsMission: filename = filename[0:i] print(filename) - filename = filename + ".miz" - i = ImportObjects(filename) - i.anchorByGroupName("ANCHOR") - new_statics, new_vehicles, new_helicopters = i.copyAll(self.m, country_name, group.units[0].name, group.units[0].position, group.units[0].heading) + for imp in imports: + if imp.filename == (filename + ".miz"): + i = ImportObjects(imp.path) + i.anchorByGroupName("ANCHOR") + new_statics, new_vehicles, new_helicopters = i.copyAll(self.m, country_name, + group.units[0].name, + group.units[0].position, + group.units[0].heading) + + break def addMods(self): dcs.helicopters.helicopter_map["UH-60L"] = aircraftMods.UH_60L diff --git a/Generator/requirements.txt b/Generator/requirements.txt index 51314dd..43c09aa 100644 Binary files a/Generator/requirements.txt and b/Generator/requirements.txt differ diff --git a/Generator/tests.py b/Generator/tests.py new file mode 100644 index 0000000..db6d03e --- /dev/null +++ b/Generator/tests.py @@ -0,0 +1,11 @@ +import dcs +import dcs.cloud_presets + +testm = dcs.mission.Mission() + +# testCloudPresets +for i in range(0, len(dcs.cloud_presets.CLOUD_PRESETS)): + preset_name = list(dcs.cloud_presets.CLOUD_PRESETS)[i] + cloud_preset = dcs.weather.CloudPreset.by_name(preset_name) + testm.weather.clouds_preset = cloud_preset + print("Cloud preset = " + cloud_preset.ui_name) \ No newline at end of file diff --git a/MissionOutput/.gitignore b/MissionOutput/.gitignore deleted file mode 100644 index e7a210e..0000000 --- a/MissionOutput/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -*/ -!.gitignore \ No newline at end of file diff --git a/config/default-config.yaml b/config/default-config.yaml index 7a41b49..c4ceff0 100644 --- a/config/default-config.yaml +++ b/config/default-config.yaml @@ -21,7 +21,7 @@ spinboxes: e_attack_planes_spinBox: 1 e_transport_helos_spinBox: 1 troop_drop_spinBox: 4 - inf_spawn_spinBox: 2 + inf_spawn_spinBox: 0 radiobuttons: farp_gunits, red_forces: "RED Default Armor (HARD)" blue_forces: "BLUE Default US Armor" diff --git a/config/user-data.yaml b/config/user-data.yaml deleted file mode 100644 index 3664bc3..0000000 --- a/config/user-data.yaml +++ /dev/null @@ -1,2 +0,0 @@ -local_ratings: - C:\RotorOps\templates\Scenarios\included\007d3d\Nevada Conflict - Vegas Tour (GRIMM).miz: 4 diff --git a/scripts/CTLD2.lua b/scripts/CTLD2.lua deleted file mode 100644 index c7a3c40..0000000 --- a/scripts/CTLD2.lua +++ /dev/null @@ -1,6427 +0,0 @@ ---[[ - Combat Troop and Logistics Drop - - Allows Huey, Mi-8 and C130 to transport troops internally and Helicopters to transport Logistic / Vehicle units to the field via sling-loads - without requiring external mods. - - Supports all of the original CTTS functionality such as AI auto troop load and unload as well as group spawning and preloading of troops into units. - - Supports deployment of Auto Lasing JTAC to the field - - See https://github.com/ciribob/DCS-CTLD for a user manual and the latest version - - Contributors: - - Steggles - https://github.com/Bob7heBuilder - - mvee - https://github.com/mvee - - jmontleon - https://github.com/jmontleon - - emilianomolina - https://github.com/emilianomolina - - davidp57 - https://github.com/veaf - - - Allow minimum distance from friendly logistics to be set - ]] - -ctld = {} -- DONT REMOVE! - ---- Identifier. All output in DCS.log will start with this. -ctld.Id = "CTLD - " - ---- Version. -ctld.Version = "20211113.01" - --- debug level, specific to this module -ctld.Debug = true --- trace level, specific to this module -ctld.Trace = true - -ctld.alreadyInitialized = false -- if true, ctld.initialize() will not run - --- ************************************************************************ --- ********************* USER CONFIGURATION ****************************** --- ************************************************************************ -ctld.staticBugWorkaround = false -- DCS had a bug where destroying statics would cause a crash. If this happens again, set this to TRUE - -ctld.disableAllSmoke = false -- if true, all smoke is diabled at pickup and drop off zones regardless of settings below. Leave false to respect settings below - -ctld.hoverPickup = true -- if set to false you can load crates with the F10 menu instead of hovering... Only if not using real crates! - -ctld.enableCrates = true -- if false, Helis will not be able to spawn or unpack crates so will be normal CTTS -ctld.slingLoad = false -- if false, crates can be used WITHOUT slingloading, by hovering above the crate, simulating slingloading but not the weight... --- There are some bug with Sling-loading that can cause crashes, if these occur set slingLoad to false --- to use the other method. --- Set staticBugFix to FALSE if use set ctld.slingLoad to TRUE - -ctld.enableSmokeDrop = true -- if false, helis and c-130 will not be able to drop smoke - -ctld.maxExtractDistance = 125 -- max distance from vehicle to troops to allow a group extraction -ctld.maximumDistanceLogistic = 200 -- max distance from vehicle to logistics to allow a loading or spawning operation -ctld.maximumSearchDistance = 4000 -- max distance for troops to search for enemy -ctld.maximumMoveDistance = 2000 -- max distance for troops to move from drop point if no enemy is nearby - -ctld.minimumDeployDistance = 1000 -- minimum distance from a friendly pickup zone where you can deploy a crate - -ctld.numberOfTroops = 10 -- default number of troops to load on a transport heli or C-130 - -- also works as maximum size of group that'll fit into a helicopter unless overridden -ctld.enableFastRopeInsertion = true -- allows you to drop troops by fast rope -ctld.fastRopeMaximumHeight = 18.28 -- in meters which is 60 ft max fast rope (not rappell) safe height - -ctld.vehiclesForTransportRED = { "BRDM-2", "BTR_D" } -- vehicles to load onto Il-76 - Alternatives {"Strela-1 9P31","BMP-1"} -ctld.vehiclesForTransportBLUE = { "M1045 HMMWV TOW", "M1043 HMMWV Armament" } -- vehicles to load onto c130 - Alternatives {"M1128 Stryker MGS","M1097 Avenger"} -ctld.vehiclesWeight = { - ["BRDM-2"] = 7000, - ["BTR_D"] = 8000, - ["M1045 HMMWV TOW"] = 3220, - ["M1043 HMMWV Armament"] = 2500 -} - -ctld.aaLaunchers = 3 -- controls how many launchers to add to the kub/buk when its spawned. -ctld.hawkLaunchers = 8 -- controls how many launchers to add to the hawk when its spawned. - -ctld.spawnRPGWithCoalition = true --spawns a friendly RPG unit with Coalition forces -ctld.spawnStinger = false -- spawns a stinger / igla soldier with a group of 6 or more soldiers! - -ctld.enabledFOBBuilding = true -- if true, you can load a crate INTO a C-130 than when unpacked creates a Forward Operating Base (FOB) which is a new place to spawn (crates) and carry crates from --- In future i'd like it to be a FARP but so far that seems impossible... --- You can also enable troop Pickup at FOBS - -ctld.cratesRequiredForFOB = 3 -- The amount of crates required to build a FOB. Once built, helis can spawn crates at this outpost to be carried and deployed in another area. --- The large crates can only be loaded and dropped by large aircraft, like the C-130 and listed in ctld.vehicleTransportEnabled --- Small FOB crates can be moved by helicopter. The FOB will require ctld.cratesRequiredForFOB larges crates and small crates are 1/3 of a large fob crate --- To build the FOB entirely out of small crates you will need ctld.cratesRequiredForFOB * 3 - -ctld.troopPickupAtFOB = true -- if true, troops can also be picked up at a created FOB - -ctld.buildTimeFOB = 120 --time in seconds for the FOB to be built - -ctld.crateWaitTime = 120 -- time in seconds to wait before you can spawn another crate - -ctld.forceCrateToBeMoved = true -- a crate must be picked up at least once and moved before it can be unpacked. Helps to reduce crate spam - -ctld.radioSound = "beacon.ogg" -- the name of the sound file to use for the FOB radio beacons. If this isnt added to the mission BEACONS WONT WORK! -ctld.radioSoundFC3 = "beaconsilent.ogg" -- name of the second silent radio file, used so FC3 aircraft dont hear ALL the beacon noises... :) - -ctld.deployedBeaconBattery = 30 -- the battery on deployed beacons will last for this number minutes before needing to be re-deployed - -ctld.enabledRadioBeaconDrop = true -- if its set to false then beacons cannot be dropped by units - -ctld.allowRandomAiTeamPickups = false -- Allows the AI to randomize the loading of infantry teams (specified below) at pickup zones - --- Simulated Sling load configuration - -ctld.minimumHoverHeight = 7.5 -- Lowest allowable height for crate hover -ctld.maximumHoverHeight = 12.0 -- Highest allowable height for crate hover -ctld.maxDistanceFromCrate = 5.5 -- Maximum distance from from crate for hover -ctld.hoverTime = 10 -- Time to hold hover above a crate for loading in seconds - --- end of Simulated Sling load configuration - --- AA SYSTEM CONFIG -- --- Sets a limit on the number of active AA systems that can be built for RED. --- A system is counted as Active if its fully functional and has all parts --- If a system is partially destroyed, it no longer counts towards the total --- When this limit is hit, a player will still be able to get crates for an AA system, just unable --- to unpack them - -ctld.AASystemLimitRED = 20 -- Red side limit - -ctld.AASystemLimitBLUE = 20 -- Blue side limit - ---END AA SYSTEM CONFIG -- - --- ***************** JTAC CONFIGURATION ***************** - -ctld.JTAC_LIMIT_RED = 10 -- max number of JTAC Crates for the RED Side -ctld.JTAC_LIMIT_BLUE = 10 -- max number of JTAC Crates for the BLUE Side - -ctld.JTAC_dropEnabled = true -- allow JTAC Crate spawn from F10 menu - -ctld.JTAC_maxDistance = 10000 -- How far a JTAC can "see" in meters (with Line of Sight) - -ctld.JTAC_smokeOn_RED = true -- enables marking of target with smoke for RED forces -ctld.JTAC_smokeOn_BLUE = true -- enables marking of target with smoke for BLUE forces - -ctld.JTAC_smokeColour_RED = 4 -- RED side smoke colour -- Green = 0 , Red = 1, White = 2, Orange = 3, Blue = 4 -ctld.JTAC_smokeColour_BLUE = 1 -- BLUE side smoke colour -- Green = 0 , Red = 1, White = 2, Orange = 3, Blue = 4 - -ctld.JTAC_jtacStatusF10 = true -- enables F10 JTAC Status menu - -ctld.JTAC_location = true -- shows location of target in JTAC message -ctld.location_DMS = false -- shows coordinates as Degrees Minutes Seconds instead of Degrees Decimal minutes - -ctld.JTAC_lock = "all" -- "vehicle" OR "troop" OR "all" forces JTAC to only lock vehicles or troops or all ground units - --- ***************** Pickup, dropoff and waypoint zones ***************** - --- Available colors (anything else like "none" disables smoke): "green", "red", "white", "orange", "blue", "none", - --- Use any of the predefined names or set your own ones - --- You can add number as a third option to limit the number of soldier or vehicle groups that can be loaded from a zone. --- Dropping back a group at a limited zone will add one more to the limit - --- If a zone isn't ACTIVE then you can't pickup from that zone until the zone is activated by ctld.activatePickupZone --- using the Mission editor - --- You can pickup from a SHIP by adding the SHIP UNIT NAME instead of a zone name - --- Side - Controls which side can load/unload troops at the zone - --- Flag Number - Optional last field. If set the current number of groups remaining can be obtained from the flag value - ---pickupZones = { "Zone name or Ship Unit Name", "smoke color", "limit (-1 unlimited)", "ACTIVE (yes/no)", "side (0 = Both sides / 1 = Red / 2 = Blue )", flag number (optional) } -ctld.pickupZones = { - { "pickzone1", "blue", -1, "yes", 0 }, - { "pickzone2", "red", -1, "yes", 0 }, - { "pickzone3", "none", -1, "yes", 0 }, - { "pickzone4", "none", -1, "yes", 0 }, - { "pickzone5", "none", -1, "yes", 0 }, - { "pickzone6", "none", -1, "yes", 0 }, - { "pickzone7", "none", -1, "yes", 0 }, - { "pickzone8", "none", -1, "yes", 0 }, - { "pickzone9", "none", 5, "yes", 1 }, -- limits pickup zone 9 to 5 groups of soldiers or vehicles, only red can pick up - { "pickzone10", "none", 10, "yes", 2 }, -- limits pickup zone 10 to 10 groups of soldiers or vehicles, only blue can pick up - - { "pickzone11", "blue", 20, "no", 2 }, -- limits pickup zone 11 to 20 groups of soldiers or vehicles, only blue can pick up. Zone starts inactive! - { "pickzone12", "red", 20, "no", 1 }, -- limits pickup zone 11 to 20 groups of soldiers or vehicles, only blue can pick up. Zone starts inactive! - { "pickzone13", "none", -1, "yes", 0 }, - { "pickzone14", "none", -1, "yes", 0 }, - { "pickzone15", "none", -1, "yes", 0 }, - { "pickzone16", "none", -1, "yes", 0 }, - { "pickzone17", "none", -1, "yes", 0 }, - { "pickzone18", "none", -1, "yes", 0 }, - { "pickzone19", "none", 5, "yes", 0 }, - { "pickzone20", "none", 10, "yes", 0, 1000 }, -- optional extra flag number to store the current number of groups available in - - { "USA Carrier", "blue", 10, "yes", 0, 1001 }, -- instead of a Zone Name you can also use the UNIT NAME of a ship -} - - --- dropOffZones = {"name","smoke colour",0,side 1 = Red or 2 = Blue or 0 = Both sides} -ctld.dropOffZones = { - { "dropzone1", "green", 2 }, - { "dropzone2", "blue", 2 }, - { "dropzone3", "orange", 2 }, - { "dropzone4", "none", 2 }, - { "dropzone5", "none", 1 }, - { "dropzone6", "none", 1 }, - { "dropzone7", "none", 1 }, - { "dropzone8", "none", 1 }, - { "dropzone9", "none", 1 }, - { "dropzone10", "none", 1 }, -} - - ---wpZones = { "Zone name", "smoke color", "ACTIVE (yes/no)", "side (0 = Both sides / 1 = Red / 2 = Blue )", } -ctld.wpZones = { - { "wpzone1", "green","yes", 2 }, - { "wpzone2", "blue","yes", 2 }, - { "wpzone3", "orange","yes", 2 }, - { "wpzone4", "none","yes", 2 }, - { "wpzone5", "none","yes", 2 }, - { "wpzone6", "none","yes", 1 }, - { "wpzone7", "none","yes", 1 }, - { "wpzone8", "none","yes", 1 }, - { "wpzone9", "none","yes", 1 }, - { "wpzone10", "none","no", 0 }, -- Both sides as its set to 0 -} - - --- ******************** Transports names ********************** - --- Use any of the predefined names or set your own ones -ctld.transportPilotNames = { - "helicargo1", - "helicargo2", - "helicargo3", - "helicargo4", - "helicargo5", - "helicargo6", - "helicargo7", - "helicargo8", - "helicargo9", - "helicargo10", - - "helicargo11", - "helicargo12", - "helicargo13", - "helicargo14", - "helicargo15", - "helicargo16", - "helicargo17", - "helicargo18", - "helicargo19", - "helicargo20", - - "helicargo21", - "helicargo22", - "helicargo23", - "helicargo24", - "helicargo25", - - "MEDEVAC #1", - "MEDEVAC #2", - "MEDEVAC #3", - "MEDEVAC #4", - "MEDEVAC #5", - "MEDEVAC #6", - "MEDEVAC #7", - "MEDEVAC #8", - "MEDEVAC #9", - "MEDEVAC #10", - "MEDEVAC #11", - "MEDEVAC #12", - "MEDEVAC #13", - "MEDEVAC #14", - "MEDEVAC #15", - "MEDEVAC #16", - - "MEDEVAC RED #1", - "MEDEVAC RED #2", - "MEDEVAC RED #3", - "MEDEVAC RED #4", - "MEDEVAC RED #5", - "MEDEVAC RED #6", - "MEDEVAC RED #7", - "MEDEVAC RED #8", - "MEDEVAC RED #9", - "MEDEVAC RED #10", - "MEDEVAC RED #11", - "MEDEVAC RED #12", - "MEDEVAC RED #13", - "MEDEVAC RED #14", - "MEDEVAC RED #15", - "MEDEVAC RED #16", - "MEDEVAC RED #17", - "MEDEVAC RED #18", - "MEDEVAC RED #19", - "MEDEVAC RED #20", - "MEDEVAC RED #21", - - "MEDEVAC BLUE #1", - "MEDEVAC BLUE #2", - "MEDEVAC BLUE #3", - "MEDEVAC BLUE #4", - "MEDEVAC BLUE #5", - "MEDEVAC BLUE #6", - "MEDEVAC BLUE #7", - "MEDEVAC BLUE #8", - "MEDEVAC BLUE #9", - "MEDEVAC BLUE #10", - "MEDEVAC BLUE #11", - "MEDEVAC BLUE #12", - "MEDEVAC BLUE #13", - "MEDEVAC BLUE #14", - "MEDEVAC BLUE #15", - "MEDEVAC BLUE #16", - "MEDEVAC BLUE #17", - "MEDEVAC BLUE #18", - "MEDEVAC BLUE #19", - "MEDEVAC BLUE #20", - "MEDEVAC BLUE #21", - - -- *** AI transports names (different names only to ease identification in mission) *** - - -- Use any of the predefined names or set your own ones - - "transport1", - "transport2", - "transport3", - "transport4", - "transport5", - "transport6", - "transport7", - "transport8", - "transport9", - "transport10", - - "transport11", - "transport12", - "transport13", - "transport14", - "transport15", - "transport16", - "transport17", - "transport18", - "transport19", - "transport20", - - "transport21", - "transport22", - "transport23", - "transport24", - "transport25", -} - --- *************** Optional Extractable GROUPS ***************** - --- Use any of the predefined names or set your own ones - -ctld.extractableGroups = { - "extract1", - "extract2", - "extract3", - "extract4", - "extract5", - "extract6", - "extract7", - "extract8", - "extract9", - "extract10", - - "extract11", - "extract12", - "extract13", - "extract14", - "extract15", - "extract16", - "extract17", - "extract18", - "extract19", - "extract20", - - "extract21", - "extract22", - "extract23", - "extract24", - "extract25", -} - --- ************** Logistics UNITS FOR CRATE SPAWNING ****************** - --- Use any of the predefined names or set your own ones --- When a logistic unit is destroyed, you will no longer be able to spawn crates - -ctld.logisticUnits = { - "logistic1", - "logistic2", - "logistic3", - "logistic4", - "logistic5", - "logistic6", - "logistic7", - "logistic8", - "logistic9", - "logistic10", -} - --- ************** UNITS ABLE TO TRANSPORT VEHICLES ****************** --- Add the model name of the unit that you want to be able to transport and deploy vehicles --- units db has all the names or you can extract a mission.miz file by making it a zip and looking --- in the contained mission file -ctld.vehicleTransportEnabled = { - "76MD", -- the il-76 mod doesnt use a normal - sign so il-76md wont match... !!!! GRR - "Hercules", -} - - --- ************** Maximum Units SETUP for UNITS ****************** - --- Put the name of the Unit you want to limit group sizes too --- i.e --- ["UH-1H"] = 10, --- --- Will limit UH1 to only transport groups with a size 10 or less --- Make sure the unit name is exactly right or it wont work - -ctld.unitLoadLimits = { - - -- Remove the -- below to turn on options - -- ["SA342Mistral"] = 4, - -- ["SA342L"] = 4, - -- ["SA342M"] = 4, - -} - - --- ************** Allowable actions for UNIT TYPES ****************** - --- Put the name of the Unit you want to limit actions for --- NOTE - the unit must've been listed in the transportPilotNames list above --- This can be used in conjunction with the options above for group sizes --- By default you can load both crates and troops unless overriden below --- i.e --- ["UH-1H"] = {crates=true, troops=false}, --- --- Will limit UH1 to only transport CRATES but NOT TROOPS --- --- ["SA342Mistral"] = {crates=fales, troops=true}, --- Will allow Mistral Gazelle to only transport crates, not troops - -ctld.unitActions = { - - -- Remove the -- below to turn on options - -- ["SA342Mistral"] = {crates=true, troops=true}, - -- ["SA342L"] = {crates=false, troops=true}, - -- ["SA342M"] = {crates=false, troops=true}, - -} - --- ************** WEIGHT CALCULATIONS FOR INFANTRY GROUPS ****************** - --- Infantry groups weight is calculated based on the soldiers' roles, and the weight of their kit --- Every soldier weights between 90% and 120% of ctld.SOLDIER_WEIGHT, and they all carry a backpack and their helmet (ctld.KIT_WEIGHT) --- Standard grunts have a rifle and ammo (ctld.RIFLE_WEIGHT) --- AA soldiers have a MANPAD tube (ctld.MANPAD_WEIGHT) --- Anti-tank soldiers have a RPG and a rocket (ctld.RPG_WEIGHT) --- Machine gunners have the squad MG and 200 bullets (ctld.MG_WEIGHT) --- JTAC have the laser sight, radio and binoculars (ctld.JTAC_WEIGHT) --- Mortar servants carry their tube and a few rounds (ctld.MORTAR_WEIGHT) - -ctld.SOLDIER_WEIGHT = 80 -- kg, will be randomized between 90% and 120% -ctld.KIT_WEIGHT = 20 -- kg -ctld.RIFLE_WEIGHT = 5 -- kg -ctld.MANPAD_WEIGHT = 18 -- kg -ctld.RPG_WEIGHT = 7.6 -- kg -ctld.MG_WEIGHT = 10 -- kg -ctld.MORTAR_WEIGHT = 26 -- kg -ctld.JTAC_WEIGHT = 15 -- kg - --- ************** INFANTRY GROUPS FOR PICKUP ****************** --- Unit Types --- inf is normal infantry --- mg is M249 --- at is RPG-16 --- aa is Stinger or Igla --- mortar is a 2B11 mortar unit --- jtac is a JTAC soldier, which will use JTACAutoLase --- You must add a name to the group for it to work --- You can also add an optional coalition side to limit the group to one side --- for the side - 2 is BLUE and 1 is RED -ctld.loadableGroups = { - {name = "Standard Group", inf = 6, mg = 2, at = 2 }, -- will make a loadable group with 6 infantry, 2 MGs and 2 anti-tank for both coalitions - {name = "Anti Air", inf = 2, aa = 3 }, - {name = "Anti Tank", inf = 2, at = 6 }, - {name = "Mortar Squad", mortar = 6 }, - {name = "JTAC Group", inf = 4, jtac = 1 }, -- will make a loadable group with 4 infantry and a JTAC soldier for both coalitions - {name = "Single JTAC", jtac = 1 }, -- will make a loadable group witha single JTAC soldier for both coalitions - -- {name = "Mortar Squad Red", inf = 2, mortar = 5, side =1 }, --would make a group loadable by RED only -} - --- ************** SPAWNABLE CRATES ****************** --- Weights must be unique as we use the weight to change the cargo to the correct unit --- when we unpack --- -ctld.spawnableCrates = { - -- name of the sub menu on F10 for spawning crates - ["Ground Forces"] = { - --crates you can spawn - -- weight in KG - -- Desc is the description on the F10 MENU - -- unit is the model name of the unit to spawn - -- cratesRequired - if set requires that many crates of the same type within 100m of each other in order build the unit - -- side is optional but 2 is BLUE and 1 is RED - -- dont use that option with the HAWK Crates - { weight = 500, desc = "HMMWV - TOW", unit = "M1045 HMMWV TOW", side = 2 }, - { weight = 505, desc = "HMMWV - MG", unit = "M1043 HMMWV Armament", side = 2 }, - - { weight = 510, desc = "BTR-D", unit = "BTR_D", side = 1 }, - { weight = 515, desc = "BRDM-2", unit = "BRDM-2", side = 1 }, - - { weight = 520, desc = "HMMWV - JTAC", unit = "Hummer", side = 2, }, -- used as jtac and unarmed, not on the crate list if JTAC is disabled - { weight = 525, desc = "SKP-11 - JTAC", unit = "SKP-11", side = 1, }, -- used as jtac and unarmed, not on the crate list if JTAC is disabled - - { weight = 100, desc = "2B11 Mortar", unit = "2B11 mortar" }, - - { weight = 250, desc = "SPH 2S19 Msta", unit = "SAU Msta", side = 1, cratesRequired = 3 }, - { weight = 255, desc = "M-109", unit = "M-109", side = 2, cratesRequired = 3 }, - - { weight = 252, desc = "Ural-375 Ammo Truck", unit = "Ural-375", side = 1, cratesRequired = 2 }, - { weight = 253, desc = "M-818 Ammo Truck", unit = "M 818", side = 2, cratesRequired = 2 }, - - { weight = 800, desc = "FOB Crate - Small", unit = "FOB-SMALL" }, -- Builds a FOB! - requires 3 * ctld.cratesRequiredForFOB - }, - ["AA short range"] = { - { weight = 50, desc = "Stinger", unit = "Soldier stinger", side = 2 }, - { weight = 55, desc = "Igla", unit = "SA-18 Igla manpad", side = 1 }, - - { weight = 405, desc = "Strela-1 9P31", unit = "Strela-1 9P31", side = 1, cratesRequired = 3 }, - { weight = 400, desc = "M1097 Avenger", unit = "M1097 Avenger", side = 2, cratesRequired = 3 }, - }, - ["AA mid range"] = { - -- HAWK System - { weight = 540, desc = "HAWK Launcher", unit = "Hawk ln", side = 2}, - { weight = 545, desc = "HAWK Search Radar", unit = "Hawk sr", side = 2 }, - { weight = 546, desc = "HAWK Track Radar", unit = "Hawk tr", side = 2 }, - { weight = 547, desc = "HAWK PCP", unit = "Hawk pcp" , side = 2 }, -- Remove this if on 1.2 - { weight = 548, desc = "HAWK CWAR", unit = "Hawk cwar" , side = 2 }, -- Remove this if on 2.5 - { weight = 549, desc = "HAWK Repair", unit = "HAWK Repair" , side = 2 }, - -- End of HAWK - - -- KUB SYSTEM - { weight = 560, desc = "KUB Launcher", unit = "Kub 2P25 ln", side = 1}, - { weight = 565, desc = "KUB Radar", unit = "Kub 1S91 str", side = 1 }, - { weight = 570, desc = "KUB Repair", unit = "KUB Repair", side = 1}, - -- End of KUB - - -- BUK System - -- { weight = 575, desc = "BUK Launcher", unit = "SA-11 Buk LN 9A310M1"}, - -- { weight = 580, desc = "BUK Search Radar", unit = "SA-11 Buk SR 9S18M1"}, - -- { weight = 585, desc = "BUK CC Radar", unit = "SA-11 Buk CC 9S470M1"}, - -- { weight = 590, desc = "BUK Repair", unit = "BUK Repair"}, - -- END of BUK - }, - ["AA long range"] = { - -- Patriot System - { weight = 555, desc = "Patriot Launcher", unit = "Patriot ln", side = 2 }, - { weight = 556, desc = "Patriot Radar", unit = "Patriot str" , side = 2 }, - { weight = 557, desc = "Patriot ECS", unit = "Patriot ECS", side = 2 }, - -- { weight = 553, desc = "Patriot ICC", unit = "Patriot cp", side = 2 }, - -- { weight = 554, desc = "Patriot EPP", unit = "Patriot EPP", side = 2 }, - { weight = 558, desc = "Patriot AMG (optional)", unit = "Patriot AMG" , side = 2 }, - { weight = 559, desc = "Patriot Repair", unit = "Patriot Repair" , side = 2 }, - -- End of Patriot - - { weight = 595, desc = "Early Warning Radar", unit = "1L13 EWR", side = 1 }, -- cant be used by BLUE coalition - }, -} - ---- 3D model that will be used to represent a loadable crate ; by default, a generator -ctld.spawnableCratesModel_load = { - ["category"] = "Fortifications", - ["shape_name"] = "GeneratorF", - ["type"] = "GeneratorF" -} - ---- 3D model that will be used to represent a slingable crate ; by default, a crate -ctld.spawnableCratesModel_sling = { - ["category"] = "Cargos", - ["shape_name"] = "bw_container_cargo", - ["type"] = "container_cargo" -} - ---[[ Placeholder for different type of cargo containers. Let's say pipes and trunks, fuel for FOB building - ["shape_name"] = "ab-212_cargo", - ["type"] = "uh1h_cargo" --new type for the container previously used - - ["shape_name"] = "ammo_box_cargo", - ["type"] = "ammo_cargo", - - ["shape_name"] = "barrels_cargo", - ["type"] = "barrels_cargo", - - ["shape_name"] = "bw_container_cargo", - ["type"] = "container_cargo", - - ["shape_name"] = "f_bar_cargo", - ["type"] = "f_bar_cargo", - - ["shape_name"] = "fueltank_cargo", - ["type"] = "fueltank_cargo", - - ["shape_name"] = "iso_container_cargo", - ["type"] = "iso_container", - - ["shape_name"] = "iso_container_small_cargo", - ["type"] = "iso_container_small", - - ["shape_name"] = "oiltank_cargo", - ["type"] = "oiltank_cargo", - - ["shape_name"] = "pipes_big_cargo", - ["type"] = "pipes_big_cargo", - - ["shape_name"] = "pipes_small_cargo", - ["type"] = "pipes_small_cargo", - - ["shape_name"] = "tetrapod_cargo", - ["type"] = "tetrapod_cargo", - - ["shape_name"] = "trunks_long_cargo", - ["type"] = "trunks_long_cargo", - - ["shape_name"] = "trunks_small_cargo", - ["type"] = "trunks_small_cargo", -]]-- - --- if the unit is on this list, it will be made into a JTAC when deployed -ctld.jtacUnitTypes = { - "SKP", "Hummer" -- there are some wierd encoding issues so if you write SKP-11 it wont match as the - sign is encoded differently... -} - - --- *************************************************************** --- **************** Mission Editor Functions ********************* --- *************************************************************** - - ------------------------------------------------------------------ --- Spawn group at a trigger and set them as extractable. Usage: --- ctld.spawnGroupAtTrigger("groupside", number, "triggerName", radius) --- Variables: --- "groupSide" = "red" for Russia "blue" for USA --- _number = number of groups to spawn OR Group description --- "triggerName" = trigger name in mission editor between commas --- _searchRadius = random distance for units to move from spawn zone (0 will leave troops at the spawn position - no search for enemy) --- --- Example: ctld.spawnGroupAtTrigger("red", 2, "spawn1", 1000) --- --- This example will spawn 2 groups of russians at the specified point --- and they will search for enemy or move randomly withing 1000m --- OR --- --- ctld.spawnGroupAtTrigger("blue", {mg=1,at=2,aa=3,inf=4,mortar=5},"spawn2", 2000) --- Spawns 1 machine gun, 2 anti tank, 3 anti air, 4 standard soldiers and 5 mortars --- -function ctld.spawnGroupAtTrigger(_groupSide, _number, _triggerName, _searchRadius) - local _spawnTrigger = trigger.misc.getZone(_triggerName) -- trigger to use as reference position - - if _spawnTrigger == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find trigger called " .. _triggerName, 10) - return - end - - local _country - if _groupSide == "red" then - _groupSide = 1 - _country = 0 - else - _groupSide = 2 - _country = 2 - end - - if _searchRadius < 0 then - _searchRadius = 0 - end - - local _pos2 = { x = _spawnTrigger.point.x, y = _spawnTrigger.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - local _groupDetails = ctld.generateTroopTypes(_groupSide, _number, _country) - - local _droppedTroops = ctld.spawnDroppedGroup(_pos3, _groupDetails, false, _searchRadius); - - if _groupSide == 1 then - table.insert(ctld.droppedTroopsRED, _droppedTroops:getName()) - else - table.insert(ctld.droppedTroopsBLUE, _droppedTroops:getName()) - end -end - - ------------------------------------------------------------------ --- Spawn group at a Vec3 Point and set them as extractable. Usage: --- ctld.spawnGroupAtPoint("groupside", number,Vec3 Point, radius) --- Variables: --- "groupSide" = "red" for Russia "blue" for USA --- _number = number of groups to spawn OR Group Description --- Vec3 Point = A vec3 point like {x=1,y=2,z=3}. Can be obtained from a unit like so: Unit.getName("Unit1"):getPoint() --- _searchRadius = random distance for units to move from spawn zone (0 will leave troops at the spawn position - no search for enemy) --- --- Example: ctld.spawnGroupAtPoint("red", 2, {x=1,y=2,z=3}, 1000) --- --- This example will spawn 2 groups of russians at the specified point --- and they will search for enemy or move randomly withing 1000m --- OR --- --- ctld.spawnGroupAtPoint("blue", {mg=1,at=2,aa=3,inf=4,mortar=5}, {x=1,y=2,z=3}, 2000) --- Spawns 1 machine gun, 2 anti tank, 3 anti air, 4 standard soldiers and 5 mortars -function ctld.spawnGroupAtPoint(_groupSide, _number, _point, _searchRadius) - - local _country - if _groupSide == "red" then - _groupSide = 1 - _country = 0 - else - _groupSide = 2 - _country = 2 - end - - if _searchRadius < 0 then - _searchRadius = 0 - end - - local _groupDetails = ctld.generateTroopTypes(_groupSide, _number, _country) - - local _droppedTroops = ctld.spawnDroppedGroup(_point, _groupDetails, false, _searchRadius); - - if _groupSide == 1 then - table.insert(ctld.droppedTroopsRED, _droppedTroops:getName()) - else - table.insert(ctld.droppedTroopsBLUE, _droppedTroops:getName()) - end -end - - --- Preloads a transport with troops or vehicles --- replaces any troops currently on board -function ctld.preLoadTransport(_unitName, _number, _troops) - - local _unit = ctld.getTransportUnit(_unitName) - - if _unit ~= nil then - - -- will replace any units currently on board - -- if not ctld.troopsOnboard(_unit,_troops) then - ctld.loadTroops(_unit, _troops, _number) - -- end - end -end - - --- Continuously counts the number of crates in a zone and sets the value of the passed in flag --- to the count amount --- This means you can trigger actions based on the count and also trigger messages before the count is reached --- Just pass in the zone name and flag number like so as a single (NOT Continuous) Trigger --- This will now work for Mission Editor and Spawned Crates --- e.g. ctld.cratesInZone("DropZone1", 5) -function ctld.cratesInZone(_zone, _flagNumber) - local _triggerZone = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _zonePos = mist.utils.zoneToVec3(_zone) - - --ignore side, if crate has been used its discounted from the count - local _crateTables = { ctld.spawnedCratesRED, ctld.spawnedCratesBLUE, ctld.missionEditorCargoCrates } - - local _crateCount = 0 - - for _, _crates in pairs(_crateTables) do - - for _crateName, _dontUse in pairs(_crates) do - - --get crate - local _crate = ctld.getCrateObject(_crateName) - - --in air seems buggy with crates so if in air is true, get the height above ground and the speed magnitude - if _crate ~= nil and _crate:getLife() > 0 - and (ctld.inAir(_crate) == false) then - - local _dist = ctld.getDistance(_crate:getPoint(), _zonePos) - - if _dist <= _triggerZone.radius then - _crateCount = _crateCount + 1 - end - end - end - end - - --set flag stuff - trigger.action.setUserFlag(_flagNumber, _crateCount) - - -- env.info("FLAG ".._flagNumber.." crates ".._crateCount) - - --retrigger in 5 seconds - timer.scheduleFunction(function(_args) - - ctld.cratesInZone(_args[1], _args[2]) - end, { _zone, _flagNumber }, timer.getTime() + 5) -end - --- Creates an extraction zone --- any Soldiers (not vehicles) dropped at this zone by a helicopter will disappear --- and be added to a running total of soldiers for a set flag number --- The idea is you can then drop say 20 troops in a zone and trigger an action using the mission editor triggers --- and the flag value --- --- The ctld.createExtractZone function needs to be called once in a trigger action do script. --- if you dont want smoke, pass -1 to the function. ---Green = 0 , Red = 1, White = 2, Orange = 3, Blue = 4, NO SMOKE = -1 --- --- e.g. ctld.createExtractZone("extractzone1", 2, -1) will create an extraction zone at trigger zone "extractzone1", store the number of troops dropped at --- the zone in flag 2 and not have smoke --- --- --- -function ctld.createExtractZone(_zone, _flagNumber, _smoke) - local _triggerZone = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _pos2 = { x = _triggerZone.point.x, y = _triggerZone.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - trigger.action.setUserFlag(_flagNumber, 0) --start at 0 - - local _details = { point = _pos3, name = _zone, smoke = _smoke, flag = _flagNumber, radius = _triggerZone.radius} - - ctld.extractZones[_zone.."-".._flagNumber] = _details - - if _smoke ~= nil and _smoke > -1 then - - local _smokeFunction - - _smokeFunction = function(_args) - - local _extractDetails = ctld.extractZones[_zone.."-".._flagNumber] - -- check zone is still active - if _extractDetails == nil then - -- stop refreshing smoke, zone is done - return - end - - - trigger.action.smoke(_args.point, _args.smoke) - --refresh in 5 minutes - timer.scheduleFunction(_smokeFunction, _args, timer.getTime() + 300) - end - - --run local function - _smokeFunction(_details) - end -end - - --- Removes an extraction zone --- --- The smoke will take up to 5 minutes to disappear depending on the last time the smoke was activated --- --- The ctld.removeExtractZone function needs to be called once in a trigger action do script. --- --- e.g. ctld.removeExtractZone("extractzone1", 2) will remove an extraction zone at trigger zone "extractzone1" --- that was setup with flag 2 --- --- --- -function ctld.removeExtractZone(_zone,_flagNumber) - - local _extractDetails = ctld.extractZones[_zone.."-".._flagNumber] - - if _extractDetails ~= nil then - --remove zone - ctld.extractZones[_zone.."-".._flagNumber] = nil - - end -end - --- CONTINUOUS TRIGGER FUNCTION --- This function will count the current number of extractable RED and BLUE --- GROUPS in a zone and store the values in two flags --- A group is only counted as being in a zone when the leader of that group --- is in the zone --- Use: ctld.countDroppedGroupsInZone("Zone Name", flagBlue, flagRed) -function ctld.countDroppedGroupsInZone(_zone, _blueFlag, _redFlag) - - local _triggerZone = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _zonePos = mist.utils.zoneToVec3(_zone) - - local _redCount = 0; - local _blueCount = 0; - - local _allGroups = {ctld.droppedTroopsRED,ctld.droppedTroopsBLUE,ctld.droppedVehiclesRED,ctld.droppedVehiclesBLUE} - for _, _extractGroups in pairs(_allGroups) do - for _,_groupName in pairs(_extractGroups) do - local _groupUnits = ctld.getGroup(_groupName) - - if #_groupUnits > 0 then - local _zonePos = mist.utils.zoneToVec3(_zone) - local _dist = ctld.getDistance(_groupUnits[1]:getPoint(), _zonePos) - - if _dist <= _triggerZone.radius then - - if (_groupUnits[1]:getCoalition() == 1) then - _redCount = _redCount + 1; - else - _blueCount = _blueCount + 1; - end - end - end - end - end - --set flag stuff - trigger.action.setUserFlag(_blueFlag, _blueCount) - trigger.action.setUserFlag(_redFlag, _redCount) - - -- env.info("Groups in zone ".._blueCount.." ".._redCount) - -end - --- CONTINUOUS TRIGGER FUNCTION --- This function will count the current number of extractable RED and BLUE --- UNITS in a zone and store the values in two flags - --- Use: ctld.countDroppedUnitsInZone("Zone Name", flagBlue, flagRed) -function ctld.countDroppedUnitsInZone(_zone, _blueFlag, _redFlag) - - local _triggerZone = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _zonePos = mist.utils.zoneToVec3(_zone) - - local _redCount = 0; - local _blueCount = 0; - - local _allGroups = {ctld.droppedTroopsRED,ctld.droppedTroopsBLUE,ctld.droppedVehiclesRED,ctld.droppedVehiclesBLUE} - - for _, _extractGroups in pairs(_allGroups) do - for _,_groupName in pairs(_extractGroups) do - local _groupUnits = ctld.getGroup(_groupName) - - if #_groupUnits > 0 then - - local _zonePos = mist.utils.zoneToVec3(_zone) - for _,_unit in pairs(_groupUnits) do - local _dist = ctld.getDistance(_unit:getPoint(), _zonePos) - - if _dist <= _triggerZone.radius then - - if (_unit:getCoalition() == 1) then - _redCount = _redCount + 1; - else - _blueCount = _blueCount + 1; - end - end - end - end - end - end - - - --set flag stuff - trigger.action.setUserFlag(_blueFlag, _blueCount) - trigger.action.setUserFlag(_redFlag, _redCount) - - -- env.info("Units in zone ".._blueCount.." ".._redCount) -end - - --- Creates a radio beacon on a random UHF - VHF and HF/FM frequency for homing --- This WILL NOT WORK if you dont add beacon.ogg and beaconsilent.ogg to the mission!!! --- e.g. ctld.createRadioBeaconAtZone("beaconZone","red", 1440,"Waypoint 1") will create a beacon at trigger zone "beaconZone" for the Red side --- that will last 1440 minutes (24 hours ) and named "Waypoint 1" in the list of radio beacons --- --- e.g. ctld.createRadioBeaconAtZone("beaconZoneBlue","blue", 20) will create a beacon at trigger zone "beaconZoneBlue" for the Blue side --- that will last 20 minutes -function ctld.createRadioBeaconAtZone(_zone, _coalition, _batteryLife, _name) - local _triggerZone = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _zonePos = mist.utils.zoneToVec3(_zone) - - ctld.beaconCount = ctld.beaconCount + 1 - - if _name == nil or _name == "" then - _name = "Beacon #" .. ctld.beaconCount - end - - if _coalition == "red" then - ctld.createRadioBeacon(_zonePos, 1, 0, _name, _batteryLife) --1440 - else - ctld.createRadioBeacon(_zonePos, 2, 2, _name, _batteryLife) --1440 - end -end - - --- Activates a pickup zone --- Activates a pickup zone when called from a trigger --- EG: ctld.activatePickupZone("pickzone3") --- This is enable pickzone3 to be used as a pickup zone for the team set -function ctld.activatePickupZone(_zoneName) - ctld.logDebug(string.format("ctld.activatePickupZone(_zoneName=%s)", ctld.p(_zoneName))) - - local _triggerZone = trigger.misc.getZone(_zoneName) -- trigger to use as reference position - - if _triggerZone == nil then - local _ship = ctld.getTransportUnit(_triggerZone) - - if _ship then - local _point = _ship:getPoint() - _triggerZone = {} - _triggerZone.point = _point - end - - end - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone or ship called " .. _zoneName, 10) - end - - for _, _zoneDetails in pairs(ctld.pickupZones) do - - if _zoneName == _zoneDetails[1] then - - --smoke could get messy if designer keeps calling this on an active zone, check its not active first - if _zoneDetails[4] == 1 then - -- they might have a continuous trigger so i've hidden the warning - --trigger.action.outText("CTLD.lua ERROR: Pickup Zone already active: " .. _zoneName, 10) - return - end - - _zoneDetails[4] = 1 --activate zone - - if ctld.disableAllSmoke == true then --smoke disabled - return - end - - if _zoneDetails[2] >= 0 then - - -- Trigger smoke marker - -- This will cause an overlapping smoke marker on next refreshsmoke call - -- but will only happen once - local _pos2 = { x = _triggerZone.point.x, y = _triggerZone.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - trigger.action.smoke(_pos3, _zoneDetails[2]) - end - end - end -end - - --- Deactivates a pickup zone --- Deactivates a pickup zone when called from a trigger --- EG: ctld.deactivatePickupZone("pickzone3") --- This is disables pickzone3 and can no longer be used to as a pickup zone --- These functions can be called by triggers, like if a set of buildings is used, you can trigger the zone to be 'not operational' --- once they are destroyed -function ctld.deactivatePickupZone(_zoneName) - - local _triggerZone = trigger.misc.getZone(_zoneName) -- trigger to use as reference position - - if _triggerZone == nil then - local _ship = ctld.getTransportUnit(_triggerZone) - - if _ship then - local _point = _ship:getPoint() - _triggerZone = {} - _triggerZone.point = _point - end - - end - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zoneName, 10) - return - end - - for _, _zoneDetails in pairs(ctld.pickupZones) do - - if _zoneName == _zoneDetails[1] then - - -- i'd just ignore it if its already been deactivated - -- if _zoneDetails[4] == 0 then --this really needed?? - -- trigger.action.outText("CTLD.lua ERROR: Pickup Zone already deactiveated: " .. _zoneName, 10) - -- return - -- end - - _zoneDetails[4] = 0 --deactivate zone - end - end -end - --- Change the remaining groups currently available for pickup at a zone --- e.g. ctld.changeRemainingGroupsForPickupZone("pickup1", 5) -- adds 5 groups --- ctld.changeRemainingGroupsForPickupZone("pickup1", -3) -- remove 3 groups -function ctld.changeRemainingGroupsForPickupZone(_zoneName, _amount) - local _triggerZone = trigger.misc.getZone(_zoneName) -- trigger to use as reference position - - if _triggerZone == nil then - local _ship = ctld.getTransportUnit(_triggerZone) - - if _ship then - local _point = _ship:getPoint() - _triggerZone = {} - _triggerZone.point = _point - end - - end - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ctld.changeRemainingGroupsForPickupZone ERROR: Cant find zone called " .. _zoneName, 10) - return - end - - for _, _zoneDetails in pairs(ctld.pickupZones) do - - if _zoneName == _zoneDetails[1] then - ctld.updateZoneCounter(_zoneName, _amount) - end - end - - -end - --- Activates a Waypoint zone --- Activates a Waypoint zone when called from a trigger --- EG: ctld.activateWaypointZone("pickzone3") --- This means that troops dropped within the radius of the zone will head to the center --- of the zone instead of searching for troops -function ctld.activateWaypointZone(_zoneName) - local _triggerZone = trigger.misc.getZone(_zoneName) -- trigger to use as reference position - - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zoneName, 10) - - return - end - - for _, _zoneDetails in pairs(ctld.wpZones) do - - if _zoneName == _zoneDetails[1] then - - --smoke could get messy if designer keeps calling this on an active zone, check its not active first - if _zoneDetails[3] == 1 then - -- they might have a continuous trigger so i've hidden the warning - --trigger.action.outText("CTLD.lua ERROR: Pickup Zone already active: " .. _zoneName, 10) - return - end - - _zoneDetails[3] = 1 --activate zone - - if ctld.disableAllSmoke == true then --smoke disabled - return - end - - if _zoneDetails[2] >= 0 then - - -- Trigger smoke marker - -- This will cause an overlapping smoke marker on next refreshsmoke call - -- but will only happen once - local _pos2 = { x = _triggerZone.point.x, y = _triggerZone.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - trigger.action.smoke(_pos3, _zoneDetails[2]) - end - end - end -end - - --- Deactivates a Waypoint zone --- Deactivates a Waypoint zone when called from a trigger --- EG: ctld.deactivateWaypointZone("wpzone3") --- This disables wpzone3 so that troops dropped in this zone will search for troops as normal --- These functions can be called by triggers -function ctld.deactivateWaypointZone(_zoneName) - - local _triggerZone = trigger.misc.getZone(_zoneName) - - if _triggerZone == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zoneName, 10) - return - end - - for _, _zoneDetails in pairs(ctld.pickupZones) do - - if _zoneName == _zoneDetails[1] then - - _zoneDetails[3] = 0 --deactivate zone - end - end -end - --- Continuous Trigger Function --- Causes an AI unit with the specified name to unload troops / vehicles when --- an enemy is detected within a specified distance --- The enemy must have Line or Sight to the unit to be detected -function ctld.unloadInProximityToEnemy(_unitName,_distance) - - local _unit = ctld.getTransportUnit(_unitName) - - if _unit ~= nil and _unit:getPlayerName() == nil then - - -- no player name means AI! - -- the findNearest visible enemy you'd want to modify as it'll find enemies quite far away - -- limited by ctld.JTAC_maxDistance - local _nearestEnemy = ctld.findNearestVisibleEnemy(_unit,"all",_distance) - - if _nearestEnemy ~= nil then - - if ctld.troopsOnboard(_unit, true) then - ctld.deployTroops(_unit, true) - return true - end - - if ctld.unitCanCarryVehicles(_unit) and ctld.troopsOnboard(_unit, false) then - ctld.deployTroops(_unit, false) - return true - end - end - end - - return false - -end - - - --- Unit will unload any units onboard if the unit is on the ground --- when this function is called -function ctld.unloadTransport(_unitName) - - local _unit = ctld.getTransportUnit(_unitName) - - if _unit ~= nil then - - if ctld.troopsOnboard(_unit, true) then - ctld.unloadTroops({_unitName,true}) - end - - if ctld.unitCanCarryVehicles(_unit) and ctld.troopsOnboard(_unit, false) then - ctld.unloadTroops({_unitName,false}) - end - end - -end - --- Loads Troops and Vehicles from a zone or picks up nearby troops or vehicles -function ctld.loadTransport(_unitName) - - local _unit = ctld.getTransportUnit(_unitName) - - if _unit ~= nil then - - ctld.loadTroopsFromZone({ _unitName, true,"",true }) - - if ctld.unitCanCarryVehicles(_unit) then - ctld.loadTroopsFromZone({ _unitName, false,"",true }) - end - - end - -end - --- adds a callback that will be called for many actions ingame -function ctld.addCallback(_callback) - - table.insert(ctld.callbacks,_callback) - -end - --- Spawns a sling loadable crate at a Trigger Zone --- --- Weights can be found in the ctld.spawnableCrates list --- e.g. ctld.spawnCrateAtZone("red", 500,"triggerzone1") -- spawn a humvee at triggerzone 1 for red side --- e.g. ctld.spawnCrateAtZone("blue", 505,"triggerzone1") -- spawn a tow humvee at triggerzone1 for blue side --- -function ctld.spawnCrateAtZone(_side, _weight,_zone) - local _spawnTrigger = trigger.misc.getZone(_zone) -- trigger to use as reference position - - if _spawnTrigger == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find zone called " .. _zone, 10) - return - end - - local _crateType = ctld.crateLookupTable[tostring(_weight)] - - if _crateType == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find crate with weight " .. _weight, 10) - return - end - - local _country - if _side == "red" then - _side = 1 - _country = 0 - else - _side = 2 - _country = 2 - end - - local _pos2 = { x = _spawnTrigger.point.x, y = _spawnTrigger.point.z } - local _alt = land.getHeight(_pos2) - local _point = { x = _pos2.x, y = _alt, z = _pos2.y } - - local _unitId = ctld.getNextUnitId() - - local _name = string.format("%s #%i", _crateType.desc, _unitId) - - local _spawnedCrate = ctld.spawnCrateStatic(_country, _unitId, _point, _name, _crateType.weight,_side) - -end - --- Spawns a sling loadable crate at a Point --- --- Weights can be found in the ctld.spawnableCrates list --- Points can be made by hand or obtained from a Unit position by Unit.getByName("PilotName"):getPoint() --- e.g. ctld.spawnCrateAtZone("red", 500,{x=1,y=2,z=3}) -- spawn a humvee at triggerzone 1 for red side at a specified point --- e.g. ctld.spawnCrateAtZone("blue", 505,{x=1,y=2,z=3}) -- spawn a tow humvee at triggerzone1 for blue side at a specified point --- --- -function ctld.spawnCrateAtPoint(_side, _weight,_point) - - - local _crateType = ctld.crateLookupTable[tostring(_weight)] - - if _crateType == nil then - trigger.action.outText("CTLD.lua ERROR: Cant find crate with weight " .. _weight, 10) - return - end - - local _country - if _side == "red" then - _side = 1 - _country = 0 - else - _side = 2 - _country = 2 - end - - local _unitId = ctld.getNextUnitId() - - local _name = string.format("%s #%i", _crateType.desc, _unitId) - - local _spawnedCrate = ctld.spawnCrateStatic(_country, _unitId, _point, _name, _crateType.weight,_side) - -end - --- *************************************************************** --- **************** BE CAREFUL BELOW HERE ************************ --- *************************************************************** - ---- Tells CTLD What multipart AA Systems there are and what parts they need --- A New system added here also needs the launcher added -ctld.AASystemTemplate = { - - { - name = "HAWK AA System", - count = 4, - parts = { - {name = "Hawk ln", desc = "HAWK Launcher", launcher = true}, - {name = "Hawk tr", desc = "HAWK Track Radar"}, - {name = "Hawk sr", desc = "HAWK Search Radar"}, - {name = "Hawk pcp", desc = "HAWK PCP"}, - {name = "Hawk cwar", desc = "HAWK CWAR"}, - }, - repair = "HAWK Repair", - }, - { - name = "Patriot AA System", - count = 4, - parts = { - {name = "Patriot ln", desc = "Patriot Launcher", launcher = true}, - {name = "Patriot ECS", desc = "Patriot Control Unit"}, - {name = "Patriot str", desc = "Patriot Search and Track Radar"}, - }, - repair = "Patriot Repair", - }, - { - name = "BUK AA System", - count = 3, - parts = { - {name = "SA-11 Buk LN 9A310M1", desc = "BUK Launcher" , launcher = true}, - {name = "SA-11 Buk CC 9S470M1", desc = "BUK CC Radar"}, - {name = "SA-11 Buk SR 9S18M1", desc = "BUK Search Radar"}, - }, - repair = "BUK Repair", - }, - { - name = "KUB AA System", - count = 2, - parts = { - {name = "Kub 2P25 ln", desc = "KUB Launcher", launcher = true}, - {name = "Kub 1S91 str", desc = "KUB Radar"}, - }, - repair = "KUB Repair", - }, -} - - -ctld.crateWait = {} -ctld.crateMove = {} - ----------------- INTERNAL FUNCTIONS ---------------- ---- ---- -------------------------------------------------------------------------------------------------------------------------------------------------------------- --- Utility methods -------------------------------------------------------------------------------------------------------------------------------------------------------------- - ---- print an object for a debugging log -function ctld.p(o, level) - local MAX_LEVEL = 20 - if level == nil then level = 0 end - if level > MAX_LEVEL then - ctld.logError("max depth reached in ctld.p : "..tostring(MAX_LEVEL)) - return "" - end - local text = "" - if (type(o) == "table") then - text = "\n" - for key,value in pairs(o) do - for i=0, level do - text = text .. " " - end - text = text .. ".".. key.."="..ctld.p(value, level+1) .. "\n" - end - elseif (type(o) == "function") then - text = "[function]" - elseif (type(o) == "boolean") then - if o == true then - text = "[true]" - else - text = "[false]" - end - else - if o == nil then - text = "[nil]" - else - text = tostring(o) - end - end - return text -end - -function ctld.logError(message) - env.info(" E - " .. ctld.Id .. message) -end - -function ctld.logInfo(message) - env.info(" I - " .. ctld.Id .. message) -end - -function ctld.logDebug(message) - if message and ctld.Debug then - env.info(" D - " .. ctld.Id .. message) - end -end - -function ctld.logTrace(message) - if message and ctld.Trace then - env.info(" T - " .. ctld.Id .. message) - end -end - -ctld.nextUnitId = 1; -ctld.getNextUnitId = function() - ctld.nextUnitId = ctld.nextUnitId + 1 - - return ctld.nextUnitId -end - -ctld.nextGroupId = 1; - -ctld.getNextGroupId = function() - ctld.nextGroupId = ctld.nextGroupId + 1 - - return ctld.nextGroupId -end - -function ctld.getTransportUnit(_unitName) - - if _unitName == nil then - return nil - end - - local _heli = Unit.getByName(_unitName) - - if _heli ~= nil and _heli:isActive() and _heli:getLife() > 0 then - - return _heli - end - - return nil -end - -function ctld.spawnCrateStatic(_country, _unitId, _point, _name, _weight,_side) - - local _crate - local _spawnedCrate - - if ctld.staticBugWorkaround and ctld.slingLoad == false then - local _groupId = ctld.getNextGroupId() - local _groupName = "Crate Group #".._groupId - - local _group = { - ["visible"] = false, - -- ["groupId"] = _groupId, - ["hidden"] = false, - ["units"] = {}, - -- ["y"] = _positions[1].z, - -- ["x"] = _positions[1].x, - ["name"] = _groupName, - ["task"] = {}, - } - - _group.units[1] = ctld.createUnit(_point.x , _point.z , 0, {type="UAZ-469",name=_name,unitId=_unitId}) - - --switch to MIST - _group.category = Group.Category.GROUND; - _group.country = _country; - - local _spawnedGroup = Group.getByName(mist.dynAdd(_group).name) - - -- Turn off AI - trigger.action.setGroupAIOff(_spawnedGroup) - - _spawnedCrate = Unit.getByName(_name) - else - - if ctld.slingLoad then - _crate = mist.utils.deepCopy(ctld.spawnableCratesModel_sling) - _crate["canCargo"] = true - else - _crate = mist.utils.deepCopy(ctld.spawnableCratesModel_load) - _crate["canCargo"] = false - end - - _crate["y"] = _point.z - _crate["x"] = _point.x - _crate["mass"] = _weight - _crate["name"] = _name - _crate["heading"] = 0 - _crate["country"] = _country - - ctld.logTrace(string.format("_crate=%s", ctld.p(_crate))) - mist.dynAddStatic(_crate) - - _spawnedCrate = StaticObject.getByName(_crate["name"]) - end - - - local _crateType = ctld.crateLookupTable[tostring(_weight)] - - if _side == 1 then - ctld.spawnedCratesRED[_name] =_crateType - else - ctld.spawnedCratesBLUE[_name] = _crateType - end - - return _spawnedCrate -end - -function ctld.spawnFOBCrateStatic(_country, _unitId, _point, _name) - - local _crate = { - ["category"] = "Fortifications", - ["shape_name"] = "konteiner_red1", - ["type"] = "Container red 1", - -- ["unitId"] = _unitId, - ["y"] = _point.z, - ["x"] = _point.x, - ["name"] = _name, - ["canCargo"] = false, - ["heading"] = 0, - } - - _crate["country"] = _country - - mist.dynAddStatic(_crate) - - local _spawnedCrate = StaticObject.getByName(_crate["name"]) - --local _spawnedCrate = coalition.addStaticObject(_country, _crate) - - return _spawnedCrate -end - - -function ctld.spawnFOB(_country, _unitId, _point, _name) - - local _crate = { - ["category"] = "Fortifications", - ["type"] = "outpost", - -- ["unitId"] = _unitId, - ["y"] = _point.z, - ["x"] = _point.x, - ["name"] = _name, - ["canCargo"] = false, - ["heading"] = 0, - } - - _crate["country"] = _country - mist.dynAddStatic(_crate) - local _spawnedCrate = StaticObject.getByName(_crate["name"]) - --local _spawnedCrate = coalition.addStaticObject(_country, _crate) - - local _id = ctld.getNextUnitId() - local _tower = { - ["type"] = "house2arm", - -- ["unitId"] = _id, - ["rate"] = 100, - ["y"] = _point.z + -36.57142857, - ["x"] = _point.x + 14.85714286, - ["name"] = "FOB Watchtower #" .. _id, - ["category"] = "Fortifications", - ["canCargo"] = false, - ["heading"] = 0, - } - --coalition.addStaticObject(_country, _tower) - _tower["country"] = _country - - mist.dynAddStatic(_tower) - - return _spawnedCrate -end - - -function ctld.spawnCrate(_arguments) - - local _status, _err = pcall(function(_args) - - -- use the cargo weight to guess the type of unit as no way to add description :( - - local _crateType = ctld.crateLookupTable[tostring(_args[2])] - local _heli = ctld.getTransportUnit(_args[1]) - - if _crateType ~= nil and _heli ~= nil and ctld.inAir(_heli) == false then - - if ctld.inLogisticsZone(_heli) == false then - - ctld.displayMessageToGroup(_heli, "You are not close enough to friendly logistics to get a crate!", 10) - - return - end - - if ctld.isJTACUnitType(_crateType.unit) then - - local _limitHit = false - - if _heli:getCoalition() == 1 then - - if ctld.JTAC_LIMIT_RED == 0 then - _limitHit = true - else - ctld.JTAC_LIMIT_RED = ctld.JTAC_LIMIT_RED - 1 - end - else - if ctld.JTAC_LIMIT_BLUE == 0 then - _limitHit = true - else - ctld.JTAC_LIMIT_BLUE = ctld.JTAC_LIMIT_BLUE - 1 - end - end - - if _limitHit then - ctld.displayMessageToGroup(_heli, "No more JTAC Crates Left!", 10) - return - end - end - - local _position = _heli:getPosition() - - -- check crate spam - if _heli:getPlayerName() ~= nil and ctld.crateWait[_heli:getPlayerName()] and ctld.crateWait[_heli:getPlayerName()] > timer.getTime() then - - ctld.displayMessageToGroup(_heli,"Sorry you must wait "..(ctld.crateWait[_heli:getPlayerName()] - timer.getTime()).. " seconds before you can get another crate", 20) - return - end - - if _heli:getPlayerName() ~= nil then - ctld.crateWait[_heli:getPlayerName()] = timer.getTime() + ctld.crateWaitTime - end - -- trigger.action.outText("Spawn Crate".._args[1].." ".._args[2],10) - - local _heli = ctld.getTransportUnit(_args[1]) - - local _point = ctld.getPointAt12Oclock(_heli, 30) - - local _unitId = ctld.getNextUnitId() - - local _side = _heli:getCoalition() - - local _name = string.format("%s #%i", _crateType.desc, _unitId) - - local _spawnedCrate = ctld.spawnCrateStatic(_heli:getCountry(), _unitId, _point, _name, _crateType.weight,_side) - - -- add to move table - ctld.crateMove[_name] = _name - - ctld.displayMessageToGroup(_heli, string.format("A %s crate weighing %s kg has been brought out and is at your 12 o'clock ", _crateType.desc, _crateType.weight), 20) - - else - env.info("Couldn't find crate item to spawn") - end - end, _arguments) - - if (not _status) then - env.error(string.format("CTLD ERROR: %s", _err)) - end -end - -function ctld.getPointAt12Oclock(_unit, _offset) - - local _position = _unit:getPosition() - local _angle = math.atan2(_position.x.z, _position.x.x) - local _xOffset = math.cos(_angle) * _offset - local _yOffset = math.sin(_angle) * _offset - - local _point = _unit:getPoint() - return { x = _point.x + _xOffset, z = _point.z + _yOffset, y = _point.y } -end - -function ctld.troopsOnboard(_heli, _troops) - - if ctld.inTransitTroops[_heli:getName()] ~= nil then - - local _onboard = ctld.inTransitTroops[_heli:getName()] - - if _troops then - - if _onboard.troops ~= nil and _onboard.troops.units ~= nil and #_onboard.troops.units > 0 then - return true - else - return false - end - else - - if _onboard.vehicles ~= nil and _onboard.vehicles.units ~= nil and #_onboard.vehicles.units > 0 then - return true - else - return false - end - end - - else - return false - end -end - --- if its dropped by AI then there is no player name so return the type of unit -function ctld.getPlayerNameOrType(_heli) - - if _heli:getPlayerName() == nil then - - return _heli:getTypeName() - else - return _heli:getPlayerName() - end -end - -function ctld.inExtractZone(_heli) - - local _heliPoint = _heli:getPoint() - - for _, _zoneDetails in pairs(ctld.extractZones) do - - --get distance to center - local _dist = ctld.getDistance(_heliPoint, _zoneDetails.point) - - if _dist <= _zoneDetails.radius then - return _zoneDetails - end - end - - return false -end - --- safe to fast rope if speed is less than 0.5 Meters per second -function ctld.safeToFastRope(_heli) - - if ctld.enableFastRopeInsertion == false then - return false - end - - --landed or speed is less than 8 km/h and height is less than fast rope height - if (ctld.inAir(_heli) == false or (ctld.heightDiff(_heli) <= ctld.fastRopeMaximumHeight + 3.0 and mist.vec.mag(_heli:getVelocity()) < 2.2)) then - return true - end -end - -function ctld.metersToFeet(_meters) - - local _feet = _meters * 3.2808399 - - return mist.utils.round(_feet) -end - -function ctld.inAir(_heli) - - if _heli:inAir() == false then - return false - end - - -- less than 5 cm/s a second so landed - -- BUT AI can hold a perfect hover so ignore AI - if mist.vec.mag(_heli:getVelocity()) < 0.05 and _heli:getPlayerName() ~= nil then - return false - end - return true -end - -function ctld.deployTroops(_heli, _troops) - - local _onboard = ctld.inTransitTroops[_heli:getName()] - - -- deloy troops - if _troops then - if _onboard.troops ~= nil and #_onboard.troops.units > 0 then - if ctld.inAir(_heli) == false or ctld.safeToFastRope(_heli) then - - -- check we're not in extract zone - local _extractZone = ctld.inExtractZone(_heli) - - if _extractZone == false then - - local _droppedTroops = ctld.spawnDroppedGroup(_heli:getPoint(), _onboard.troops, false) - ctld.logTrace(string.format("_onboard.troops=%s", ctld.p(_onboard.troops))) - if _onboard.troops.jtac or _droppedTroops:getName():lower():find("jtac") then - local _code = table.remove(ctld.jtacGeneratedLaserCodes, 1) - ctld.logTrace(string.format("_code=%s", ctld.p(_code))) - table.insert(ctld.jtacGeneratedLaserCodes, _code) - ctld.logTrace(string.format("_droppedTroops:getName()=%s", ctld.p(_droppedTroops:getName()))) - ctld.JTACAutoLase(_droppedTroops:getName(), _code) - end - - if _heli:getCoalition() == 1 then - - table.insert(ctld.droppedTroopsRED, _droppedTroops:getName()) - else - - table.insert(ctld.droppedTroopsBLUE, _droppedTroops:getName()) - end - - ctld.inTransitTroops[_heli:getName()].troops = nil - ctld.adaptWeightToCargo(_heli:getName()) - - if ctld.inAir(_heli) then - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " fast-ropped troops from " .. _heli:getTypeName() .. " into combat", 10) - else - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " dropped troops from " .. _heli:getTypeName() .. " into combat", 10) - end - - ctld.processCallback({unit = _heli, unloaded = _droppedTroops, action = "dropped_troops"}) - - - else - --extract zone! - local _droppedCount = trigger.misc.getUserFlag(_extractZone.flag) - - _droppedCount = (#_onboard.troops.units) + _droppedCount - - trigger.action.setUserFlag(_extractZone.flag, _droppedCount) - - ctld.inTransitTroops[_heli:getName()].troops = nil - ctld.adaptWeightToCargo(_heli:getName()) - - if ctld.inAir(_heli) then - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " troops fast-ropped from " .. _heli:getTypeName() .. " into " .. _extractZone.name, 10) - else - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " troops dropped from " .. _heli:getTypeName() .. " into " .. _extractZone.name, 10) - end - end - else - ctld.displayMessageToGroup(_heli, "Too high or too fast to drop troops into combat! Hover below " .. ctld.metersToFeet(ctld.fastRopeMaximumHeight) .. " feet or land.", 10) - end - end - - else - if ctld.inAir(_heli) == false then - if _onboard.vehicles ~= nil and #_onboard.vehicles.units > 0 then - - local _droppedVehicles = ctld.spawnDroppedGroup(_heli:getPoint(), _onboard.vehicles, true) - - if _heli:getCoalition() == 1 then - - table.insert(ctld.droppedVehiclesRED, _droppedVehicles:getName()) - else - - table.insert(ctld.droppedVehiclesBLUE, _droppedVehicles:getName()) - end - - ctld.inTransitTroops[_heli:getName()].vehicles = nil - ctld.adaptWeightToCargo(_heli:getName()) - - ctld.processCallback({unit = _heli, unloaded = _droppedVehicles, action = "dropped_vehicles"}) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " dropped vehicles from " .. _heli:getTypeName() .. " into combat", 10) - end - end - end -end - -function ctld.insertIntoTroopsArray(_troopType,_count,_troopArray,_troopName) - - for _i = 1, _count do - local _unitId = ctld.getNextUnitId() - table.insert(_troopArray, { type = _troopType, unitId = _unitId, name = string.format("Dropped %s #%i", _troopName or _troopType, _unitId) }) - end - - return _troopArray - -end - - -function ctld.generateTroopTypes(_side, _countOrTemplate, _country) - local _troops = {} - local _weight = 0 - local _hasJTAC = false - - local function getSoldiersWeight(count, additionalWeight) - local _weight = 0 - for i = 1, count do - local _soldierWeight = math.random(90, 120) * ctld.SOLDIER_WEIGHT / 100 - ctld.logTrace(string.format("_soldierWeight=%s", ctld.p(_soldierWeight))) - _weight = _weight + _soldierWeight + ctld.KIT_WEIGHT + additionalWeight - end - return _weight - end - - if type(_countOrTemplate) == "table" then - - if _countOrTemplate.aa then - ctld.logTrace(string.format("_countOrTemplate.aa=%s", ctld.p(_countOrTemplate.aa))) - if _side == 2 then - _troops = ctld.insertIntoTroopsArray("Soldier stinger",_countOrTemplate.aa,_troops) - else - _troops = ctld.insertIntoTroopsArray("SA-18 Igla manpad",_countOrTemplate.aa,_troops) - end - _weight = _weight + getSoldiersWeight(_countOrTemplate.aa, ctld.MANPAD_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - if _countOrTemplate.inf then - ctld.logTrace(string.format("_countOrTemplate.inf=%s", ctld.p(_countOrTemplate.inf))) - if _side == 2 then - _troops = ctld.insertIntoTroopsArray("Soldier M4 GRG",_countOrTemplate.inf,_troops) - else - _troops = ctld.insertIntoTroopsArray("Soldier AK",_countOrTemplate.inf,_troops) - end - _weight = _weight + getSoldiersWeight(_countOrTemplate.inf, ctld.RIFLE_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - if _countOrTemplate.mg then - ctld.logTrace(string.format("_countOrTemplate.mg=%s", ctld.p(_countOrTemplate.mg))) - if _side == 2 then - _troops = ctld.insertIntoTroopsArray("Soldier M249",_countOrTemplate.mg,_troops) - else - _troops = ctld.insertIntoTroopsArray("Paratrooper AKS-74",_countOrTemplate.mg,_troops) - end - _weight = _weight + getSoldiersWeight(_countOrTemplate.mg, ctld.MG_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - if _countOrTemplate.at then - ctld.logTrace(string.format("_countOrTemplate.at=%s", ctld.p(_countOrTemplate.at))) - _troops = ctld.insertIntoTroopsArray("Paratrooper RPG-16",_countOrTemplate.at,_troops) - _weight = _weight + getSoldiersWeight(_countOrTemplate.at, ctld.RPG_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - if _countOrTemplate.mortar then - ctld.logTrace(string.format("_countOrTemplate.mortar=%s", ctld.p(_countOrTemplate.mortar))) - _troops = ctld.insertIntoTroopsArray("2B11 mortar",_countOrTemplate.mortar,_troops) - _weight = _weight + getSoldiersWeight(_countOrTemplate.mortar, ctld.MORTAR_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - if _countOrTemplate.jtac then - ctld.logTrace(string.format("_countOrTemplate.jtac=%s", ctld.p(_countOrTemplate.jtac))) - if _side == 2 then - _troops = ctld.insertIntoTroopsArray("Soldier M4 GRG",_countOrTemplate.jtac,_troops, "JTAC") - else - _troops = ctld.insertIntoTroopsArray("Soldier AK",_countOrTemplate.jtac,_troops, "JTAC") - end - _hasJTAC = true - _weight = _weight + getSoldiersWeight(_countOrTemplate.jtac, ctld.JTAC_WEIGHT + ctld.RIFLE_WEIGHT) - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - end - - else - for _i = 1, _countOrTemplate do - - local _unitType = "Soldier AK" - - if _side == 2 then - if _i <=2 then - _unitType = "Soldier M249" - _weight = _weight + getSoldiersWeight(1, ctld.MG_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - elseif ctld.spawnRPGWithCoalition and _i > 2 and _i <= 4 then - _unitType = "Paratrooper RPG-16" - _weight = _weight + getSoldiersWeight(1, ctld.RPG_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - elseif ctld.spawnStinger and _i > 4 and _i <= 5 then - _unitType = "Soldier stinger" - _weight = _weight + getSoldiersWeight(1, ctld.MANPAD_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - else - _unitType = "Soldier M4 GRG" - _weight = _weight + getSoldiersWeight(1, ctld.RIFLE_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - end - else - if _i <=2 then - _unitType = "Paratrooper AKS-74" - _weight = _weight + getSoldiersWeight(1, ctld.MG_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - elseif ctld.spawnRPGWithCoalition and _i > 2 and _i <= 4 then - _unitType = "Paratrooper RPG-16" - _weight = _weight + getSoldiersWeight(1, ctld.RPG_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - elseif ctld.spawnStinger and _i > 4 and _i <= 5 then - _unitType = "SA-18 Igla manpad" - _weight = _weight + getSoldiersWeight(1, ctld.MANPAD_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - else - _unitType = "Infantry AK" - _weight = _weight + getSoldiersWeight(1, ctld.RIFLE_WEIGHT) - ctld.logTrace(string.format("_unitType=%s, _weight=%s", ctld.p(_unitType), ctld.p(_weight))) - end - end - - local _unitId = ctld.getNextUnitId() - - _troops[_i] = { type = _unitType, unitId = _unitId, name = string.format("Dropped %s #%i", _unitType, _unitId) } - end - end - - local _groupId = ctld.getNextGroupId() - local _groupName = "Dropped Group" - if _hasJTAC then - _groupName = "Dropped JTAC Group" - end - local _details = { units = _troops, groupId = _groupId, groupName = string.format("%s %i", _groupName, _groupId), side = _side, country = _country, weight = _weight, jtac = _hasJTAC } - ctld.logTrace(string.format("total weight=%s", ctld.p(_weight))) - - return _details -end - ---Special F10 function for players for troops -function ctld.unloadExtractTroops(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli == nil then - return false - end - - - local _extract = nil - if not ctld.inAir(_heli) then - if _heli:getCoalition() == 1 then - _extract = ctld.findNearestGroup(_heli, ctld.droppedTroopsRED) - else - _extract = ctld.findNearestGroup(_heli, ctld.droppedTroopsBLUE) - end - - end - - if _extract ~= nil and not ctld.troopsOnboard(_heli, true) then - -- search for nearest troops to pickup - return ctld.extractTroops({_heli:getName(), true}) - else - return ctld.unloadTroops({_heli:getName(),true,true}) - end - - -end - --- load troops onto vehicle -function ctld.loadTroops(_heli, _troops, _numberOrTemplate) - - -- load troops + vehicles if c130 or herc - -- "M1045 HMMWV TOW" - -- "M1043 HMMWV Armament" - local _onboard = ctld.inTransitTroops[_heli:getName()] - - --number doesnt apply to vehicles - if _numberOrTemplate == nil or (type(_numberOrTemplate) ~= "table" and type(_numberOrTemplate) ~= "number") then - _numberOrTemplate = ctld.numberOfTroops - end - - if _onboard == nil then - _onboard = { troops = {}, vehicles = {} } - end - - local _list - if _heli:getCoalition() == 1 then - _list = ctld.vehiclesForTransportRED - else - _list = ctld.vehiclesForTransportBLUE - end - - ctld.logTrace(string.format("_troops=%s", ctld.p(_troops))) - if _troops then - _onboard.troops = ctld.generateTroopTypes(_heli:getCoalition(), _numberOrTemplate, _heli:getCountry()) - ctld.logTrace(string.format("_onboard.troops=%s", ctld.p(_onboard.troops))) - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " loaded troops into " .. _heli:getTypeName(), 10) - - ctld.processCallback({unit = _heli, onboard = _onboard.troops, action = "load_troops"}) - else - - _onboard.vehicles = ctld.generateVehiclesForTransport(_heli:getCoalition(), _heli:getCountry()) - - local _count = #_list - - ctld.processCallback({unit = _heli, onboard = _onboard.vehicles, action = "load_vehicles"}) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " loaded " .. _count .. " vehicles into " .. _heli:getTypeName(), 10) - end - - ctld.inTransitTroops[_heli:getName()] = _onboard - ctld.logTrace(string.format("ctld.inTransitTroops=%s", ctld.p(ctld.inTransitTroops[_heli:getName()]))) - ctld.adaptWeightToCargo(_heli:getName()) -end - -function ctld.generateVehiclesForTransport(_side, _country) - - local _vehicles = {} - local _list - if _side == 1 then - _list = ctld.vehiclesForTransportRED - else - _list = ctld.vehiclesForTransportBLUE - end - - - for _i, _type in ipairs(_list) do - - local _unitId = ctld.getNextUnitId() - local _weight = ctld.vehiclesWeight[_type] or 2500 - _vehicles[_i] = { type = _type, unitId = _unitId, name = string.format("Dropped %s #%i", _type, _unitId), weight = _weight } - end - - - local _groupId = ctld.getNextGroupId() - local _details = { units = _vehicles, groupId = _groupId, groupName = string.format("Dropped Group %i", _groupId), side = _side, country = _country } - - return _details -end - -function ctld.loadUnloadFOBCrate(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _troops = _args[2] - - if _heli == nil then - return - end - - if ctld.inAir(_heli) == true then - return - end - - - local _side = _heli:getCoalition() - - local _inZone = ctld.inLogisticsZone(_heli) - local _crateOnboard = ctld.inTransitFOBCrates[_heli:getName()] ~= nil - - if _inZone == false and _crateOnboard == true then - - ctld.inTransitFOBCrates[_heli:getName()] = nil - - local _position = _heli:getPosition() - - --try to spawn at 6 oclock to us - local _angle = math.atan2(_position.x.z, _position.x.x) - local _xOffset = math.cos(_angle) * -60 - local _yOffset = math.sin(_angle) * -60 - - local _point = _heli:getPoint() - - local _side = _heli:getCoalition() - - local _unitId = ctld.getNextUnitId() - - local _name = string.format("FOB Crate #%i", _unitId) - - local _spawnedCrate = ctld.spawnFOBCrateStatic(_heli:getCountry(), ctld.getNextUnitId(), { x = _point.x + _xOffset, z = _point.z + _yOffset }, _name) - - if _side == 1 then - ctld.droppedFOBCratesRED[_name] = _name - else - ctld.droppedFOBCratesBLUE[_name] = _name - end - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " delivered a FOB Crate", 10) - - ctld.displayMessageToGroup(_heli, "Delivered FOB Crate 60m at 6'oclock to you", 10) - - elseif _inZone == true and _crateOnboard == true then - - ctld.displayMessageToGroup(_heli, "FOB Crate dropped back to base", 10) - - ctld.inTransitFOBCrates[_heli:getName()] = nil - - elseif _inZone == true and _crateOnboard == false then - ctld.displayMessageToGroup(_heli, "FOB Crate Loaded", 10) - - ctld.inTransitFOBCrates[_heli:getName()] = true - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " loaded a FOB Crate ready for delivery!", 10) - - else - - -- nearest Crate - local _crates = ctld.getCratesAndDistance(_heli) - local _nearestCrate = ctld.getClosestCrate(_heli, _crates, "FOB") - - if _nearestCrate ~= nil and _nearestCrate.dist < 150 then - - ctld.displayMessageToGroup(_heli, "FOB Crate Loaded", 10) - ctld.inTransitFOBCrates[_heli:getName()] = true - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " loaded a FOB Crate ready for delivery!", 10) - - if _side == 1 then - ctld.droppedFOBCratesRED[_nearestCrate.crateUnit:getName()] = nil - else - ctld.droppedFOBCratesBLUE[_nearestCrate.crateUnit:getName()] = nil - end - - --remove - _nearestCrate.crateUnit:destroy() - - else - ctld.displayMessageToGroup(_heli, "There are no friendly logistic units nearby to load a FOB crate from!", 10) - end - end -end - -function ctld.loadTroopsFromZone(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _troops = _args[2] - local _groupTemplate = _args[3] or "" - local _allowExtract = _args[4] - - if _heli == nil then - return false - end - - local _zone = ctld.inPickupZone(_heli) - - if ctld.troopsOnboard(_heli, _troops) then - - if _troops then - ctld.displayMessageToGroup(_heli, "You already have troops onboard.", 10) - else - ctld.displayMessageToGroup(_heli, "You already have vehicles onboard.", 10) - end - - return false - end - - local _extract - - if _allowExtract then - -- first check for extractable troops regardless of if we're in a zone or not - if _troops then - if _heli:getCoalition() == 1 then - _extract = ctld.findNearestGroup(_heli, ctld.droppedTroopsRED) - else - _extract = ctld.findNearestGroup(_heli, ctld.droppedTroopsBLUE) - end - else - - if _heli:getCoalition() == 1 then - _extract = ctld.findNearestGroup(_heli, ctld.droppedVehiclesRED) - else - _extract = ctld.findNearestGroup(_heli, ctld.droppedVehiclesBLUE) - end - end - end - - if _extract ~= nil then - -- search for nearest troops to pickup - return ctld.extractTroops({_heli:getName(), _troops}) - elseif _zone.inZone == true then - - if _zone.limit - 1 >= 0 then - -- decrease zone counter by 1 - ctld.updateZoneCounter(_zone.index, -1) - - ctld.loadTroops(_heli, _troops,_groupTemplate) - - return true - else - ctld.displayMessageToGroup(_heli, "This area has no more reinforcements available!", 20) - - return false - end - - else - if _allowExtract then - ctld.displayMessageToGroup(_heli, "You are not in a pickup zone and no one is nearby to extract", 10) - else - ctld.displayMessageToGroup(_heli, "You are not in a pickup zone", 10) - end - - return false - end -end - - - -function ctld.unloadTroops(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _troops = _args[2] - - if _heli == nil then - return false - end - - local _zone = ctld.inPickupZone(_heli) - if not ctld.troopsOnboard(_heli, _troops) then - - ctld.displayMessageToGroup(_heli, "No one to unload", 10) - - return false - else - - -- troops must be onboard to get here - if _zone.inZone == true then - - if _troops then - ctld.displayMessageToGroup(_heli, "Dropped troops back to base", 20) - - ctld.processCallback({unit = _heli, unloaded = ctld.inTransitTroops[_heli:getName()].troops, action = "unload_troops_zone"}) - - ctld.inTransitTroops[_heli:getName()].troops = nil - - else - ctld.displayMessageToGroup(_heli, "Dropped vehicles back to base", 20) - - ctld.processCallback({unit = _heli, unloaded = ctld.inTransitTroops[_heli:getName()].vehicles, action = "unload_vehicles_zone"}) - - ctld.inTransitTroops[_heli:getName()].vehicles = nil - end - - ctld.adaptWeightToCargo(_heli:getName()) - - -- increase zone counter by 1 - ctld.updateZoneCounter(_zone.index, 1) - - return true - - elseif ctld.troopsOnboard(_heli, _troops) then - - return ctld.deployTroops(_heli, _troops) - end - end - -end - -function ctld.extractTroops(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _troops = _args[2] - - if _heli == nil then - return false - end - - if ctld.inAir(_heli) then - return false - end - - if ctld.troopsOnboard(_heli, _troops) then - if _troops then - ctld.displayMessageToGroup(_heli, "You already have troops onboard.", 10) - else - ctld.displayMessageToGroup(_heli, "You already have vehicles onboard.", 10) - end - - return false - end - - local _onboard = ctld.inTransitTroops[_heli:getName()] - - if _onboard == nil then - _onboard = { troops = nil, vehicles = nil } - end - - local _extracted = false - - if _troops then - - local _extractTroops - - if _heli:getCoalition() == 1 then - _extractTroops = ctld.findNearestGroup(_heli, ctld.droppedTroopsRED) - else - _extractTroops = ctld.findNearestGroup(_heli, ctld.droppedTroopsBLUE) - end - - - if _extractTroops ~= nil then - - local _limit = ctld.getTransportLimit(_heli:getTypeName()) - - local _size = #_extractTroops.group:getUnits() - - if _limit < #_extractTroops.group:getUnits() then - - ctld.displayMessageToGroup(_heli, "Sorry - The group of ".._size.." is too large to fit. \n\nLimit is ".._limit.." for ".._heli:getTypeName(), 20) - - return - end - - _onboard.troops = _extractTroops.details - _onboard.troops.weight = #_extractTroops.group:getUnits() * 130 -- default to 130kg per soldier - - if _extractTroops.group:getName():lower():find("jtac") then - _onboard.troops.jtac = true - end - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " extracted troops in " .. _heli:getTypeName() .. " from combat", 10) - - if _heli:getCoalition() == 1 then - ctld.droppedTroopsRED[_extractTroops.group:getName()] = nil - else - ctld.droppedTroopsBLUE[_extractTroops.group:getName()] = nil - end - - ctld.processCallback({unit = _heli, extracted = _extractTroops, action = "extract_troops"}) - - --remove - _extractTroops.group:destroy() - - _extracted = true - else - _onboard.troops = nil - ctld.displayMessageToGroup(_heli, "No extractable troops nearby!", 20) - end - - else - - local _extractVehicles - - - if _heli:getCoalition() == 1 then - - _extractVehicles = ctld.findNearestGroup(_heli, ctld.droppedVehiclesRED) - else - - _extractVehicles = ctld.findNearestGroup(_heli, ctld.droppedVehiclesBLUE) - end - - if _extractVehicles ~= nil then - _onboard.vehicles = _extractVehicles.details - - if _heli:getCoalition() == 1 then - - ctld.droppedVehiclesRED[_extractVehicles.group:getName()] = nil - else - - ctld.droppedVehiclesBLUE[_extractVehicles.group:getName()] = nil - end - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " extracted vehicles in " .. _heli:getTypeName() .. " from combat", 10) - - ctld.processCallback({unit = _heli, extracted = _extractVehicles, action = "extract_vehicles"}) - --remove - _extractVehicles.group:destroy() - _extracted = true - - else - _onboard.vehicles = nil - ctld.displayMessageToGroup(_heli, "No extractable vehicles nearby!", 20) - end - end - - ctld.inTransitTroops[_heli:getName()] = _onboard - ctld.adaptWeightToCargo(_heli:getName()) - - return _extracted -end - - -function ctld.checkTroopStatus(_args) - local _unitName = _args[1] - --list onboard troops, if c130 - local _heli = ctld.getTransportUnit(_unitName) - - if _heli == nil then - return - end - - local _, _message = ctld.getWeightOfCargo(_unitName) - ctld.logTrace(string.format("_message=%s", ctld.p(_message))) - if _message and _message ~= "" then - ctld.displayMessageToGroup(_heli, _message, 10) - end -end - --- Removes troops from transport when it dies -function ctld.checkTransportStatus() - - timer.scheduleFunction(ctld.checkTransportStatus, nil, timer.getTime() + 3) - - for _, _name in ipairs(ctld.transportPilotNames) do - - local _transUnit = ctld.getTransportUnit(_name) - - if _transUnit == nil then - --env.info("CTLD Transport Unit Dead event") - ctld.inTransitTroops[_name] = nil - ctld.inTransitFOBCrates[_name] = nil - ctld.inTransitSlingLoadCrates[_name] = nil - end - end -end - -function ctld.adaptWeightToCargo(unitName) - local _weight = ctld.getWeightOfCargo(unitName) - trigger.action.setUnitInternalCargo(unitName, _weight) -end - -function ctld.getWeightOfCargo(unitName) - ctld.logDebug(string.format("ctld.getWeightOfCargo(%s)", ctld.p(unitName))) - - local FOB_CRATE_WEIGHT = 800 - local _weight = 0 - local _description = "" - - -- add troops weight - if ctld.inTransitTroops[unitName] then - ctld.logTrace("ctld.inTransitTroops = true") - local _inTransit = ctld.inTransitTroops[unitName] - if _inTransit then - ctld.logTrace(string.format("_inTransit=%s", ctld.p(_inTransit))) - local _troops = _inTransit.troops - if _troops and _troops.units then - ctld.logTrace(string.format("_troops.weight=%s", ctld.p(_troops.weight))) - _description = _description .. string.format("%s troops onboard (%s kg)\n", #_troops.units, _troops.weight) - _weight = _weight + _troops.weight - end - local _vehicles = _inTransit.vehicles - if _vehicles and _vehicles.units then - for _, _unit in pairs(_vehicles.units) do - _weight = _weight + _unit.weight - end - ctld.logTrace(string.format("_weight=%s", ctld.p(_weight))) - _description = _description .. string.format("%s vehicles onboard (%s kg)\n", #_vehicles.units, _weight) - end - end - end - ctld.logTrace(string.format("with troops and vehicles : weight = %s", tostring(_weight))) - - -- add FOB crates weight - if ctld.inTransitFOBCrates[unitName] then - ctld.logTrace("ctld.inTransitFOBCrates = true") - _weight = _weight + FOB_CRATE_WEIGHT - _description = _description .. string.format("1 FOB Crate oboard (%s kg)\n", FOB_CRATE_WEIGHT) - end - ctld.logTrace(string.format("with FOB crates : weight = %s", tostring(_weight))) - - -- add simulated slingload crates weight - local _crate = ctld.inTransitSlingLoadCrates[unitName] - if _crate then - ctld.logTrace(string.format("_crate=%s", ctld.p(_crate))) - if _crate.simulatedSlingload then - ctld.logTrace(string.format("_crate.weight=%s", ctld.p(_crate.weight))) - _weight = _weight + _crate.weight - _description = _description .. string.format("1 %s crate onboard (%s kg)\n", _crate.desc, _crate.weight) - end - end - ctld.logTrace(string.format("with simulated slingload crates : weight = %s", tostring(_weight))) - if _description ~= "" then - _description = _description .. string.format("Total weight of cargo : %s kg\n", _weight) - else - _description = "No cargo." - end - ctld.logTrace(string.format("_description = %s", tostring(_description))) - - return _weight, _description -end - -function ctld.checkHoverStatus() - --ctld.logDebug(string.format("ctld.checkHoverStatus()")) - timer.scheduleFunction(ctld.checkHoverStatus, nil, timer.getTime() + 1.0) - - local _status, _result = pcall(function() - - for _, _name in ipairs(ctld.transportPilotNames) do - - local _reset = true - local _transUnit = ctld.getTransportUnit(_name) - - --only check transports that are hovering and not planes - if _transUnit ~= nil and ctld.inTransitSlingLoadCrates[_name] == nil and ctld.inAir(_transUnit) and ctld.unitCanCarryVehicles(_transUnit) == false then - - --ctld.logTrace(string.format("%s - capable of slingloading", ctld.p(_name))) - - local _crates = ctld.getCratesAndDistance(_transUnit) - --ctld.logTrace(string.format("_crates = %s", ctld.p(_crates))) - - for _, _crate in pairs(_crates) do - --ctld.logTrace(string.format("_crate = %s", ctld.p(_crate))) - if _crate.dist < ctld.maxDistanceFromCrate and _crate.details.unit ~= "FOB" then - - --check height! - local _height = _transUnit:getPoint().y - _crate.crateUnit:getPoint().y - --env.info("HEIGHT " .. _name .. " " .. _height .. " " .. _transUnit:getPoint().y .. " " .. _crate.crateUnit:getPoint().y) - -- ctld.heightDiff(_transUnit) - --env.info("HEIGHT ABOVE GROUD ".._name.." ".._height.." ".._transUnit:getPoint().y.." ".._crate.crateUnit:getPoint().y) - --ctld.logTrace(string.format("_height = %s", ctld.p(_height))) - - if _height > ctld.minimumHoverHeight and _height <= ctld.maximumHoverHeight then - - local _time = ctld.hoverStatus[_transUnit:getName()] - --ctld.logTrace(string.format("_time = %s", ctld.p(_time))) - - if _time == nil then - ctld.hoverStatus[_transUnit:getName()] = ctld.hoverTime - _time = ctld.hoverTime - else - _time = ctld.hoverStatus[_transUnit:getName()] - 1 - ctld.hoverStatus[_transUnit:getName()] = _time - end - - if _time > 0 then - ctld.displayMessageToGroup(_transUnit, "Hovering above " .. _crate.details.desc .. " crate. \n\nHold hover for " .. _time .. " seconds! \n\nIf the countdown stops you're too far away!", 10,true) - else - ctld.hoverStatus[_transUnit:getName()] = nil - ctld.displayMessageToGroup(_transUnit, "Loaded " .. _crate.details.desc .. " crate!", 10,true) - - --crates been moved once! - ctld.crateMove[_crate.crateUnit:getName()] = nil - - if _transUnit:getCoalition() == 1 then - ctld.spawnedCratesRED[_crate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_crate.crateUnit:getName()] = nil - end - - _crate.crateUnit:destroy() - - local _copiedCrate = mist.utils.deepCopy(_crate.details) - _copiedCrate.simulatedSlingload = true - --ctld.logTrace(string.format("_copiedCrate = %s", ctld.p(_copiedCrate))) - ctld.inTransitSlingLoadCrates[_name] = _copiedCrate - ctld.adaptWeightToCargo(_name) - end - - _reset = false - - break - elseif _height <= ctld.minimumHoverHeight then - ctld.displayMessageToGroup(_transUnit, "Too low to hook " .. _crate.details.desc .. " crate.\n\nHold hover for " .. ctld.hoverTime .. " seconds", 5,true) - break - else - ctld.displayMessageToGroup(_transUnit, "Too high to hook " .. _crate.details.desc .. " crate.\n\nHold hover for " .. ctld.hoverTime .. " seconds", 5, true) - break - end - end - end - end - - if _reset then - ctld.hoverStatus[_name] = nil - end - end - end) - - if (not _status) then - env.error(string.format("CTLD ERROR: %s", _result)) - end -end - -function ctld.loadNearbyCrate(_name) - local _transUnit = ctld.getTransportUnit(_name) - - if _transUnit ~= nil then - - if ctld.inAir(_transUnit) then - ctld.displayMessageToGroup(_transUnit, "You must land before you can load a crate!", 10,true) - return - end - - if ctld.inTransitSlingLoadCrates[_name] == nil then - local _crates = ctld.getCratesAndDistance(_transUnit) - - for _, _crate in pairs(_crates) do - - if _crate.dist < 50.0 then - ctld.displayMessageToGroup(_transUnit, "Loaded " .. _crate.details.desc .. " crate!", 10,true) - - if _transUnit:getCoalition() == 1 then - ctld.spawnedCratesRED[_crate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_crate.crateUnit:getName()] = nil - end - - ctld.crateMove[_crate.crateUnit:getName()] = nil - - _crate.crateUnit:destroy() - - local _copiedCrate = mist.utils.deepCopy(_crate.details) - _copiedCrate.simulatedSlingload = true - ctld.inTransitSlingLoadCrates[_name] = _copiedCrate - ctld.adaptWeightToCargo(_name) - return - end - end - - ctld.displayMessageToGroup(_transUnit, "No Crates within 50m to load!", 10,true) - - else - -- crate onboard - ctld.displayMessageToGroup(_transUnit, "You already have a "..ctld.inTransitSlingLoadCrates[_name].desc.." crate onboard!", 10,true) - end - end - - -end - ---recreates beacons to make sure they work! -function ctld.refreshRadioBeacons() - - timer.scheduleFunction(ctld.refreshRadioBeacons, nil, timer.getTime() + 30) - - - for _index, _beaconDetails in ipairs(ctld.deployedRadioBeacons) do - - --trigger.action.outTextForCoalition(_beaconDetails.coalition,_beaconDetails.text,10) - if ctld.updateRadioBeacon(_beaconDetails) == false then - - --search used frequencies + remove, add back to unused - - for _i, _freq in ipairs(ctld.usedUHFFrequencies) do - if _freq == _beaconDetails.uhf then - - table.insert(ctld.freeUHFFrequencies, _freq) - table.remove(ctld.usedUHFFrequencies, _i) - end - end - - for _i, _freq in ipairs(ctld.usedVHFFrequencies) do - if _freq == _beaconDetails.vhf then - - table.insert(ctld.freeVHFFrequencies, _freq) - table.remove(ctld.usedVHFFrequencies, _i) - end - end - - for _i, _freq in ipairs(ctld.usedFMFrequencies) do - if _freq == _beaconDetails.fm then - - table.insert(ctld.freeFMFrequencies, _freq) - table.remove(ctld.usedFMFrequencies, _i) - end - end - - --clean up beacon table - table.remove(ctld.deployedRadioBeacons, _index) - end - end -end - -function ctld.getClockDirection(_heli, _crate) - - -- Source: Helicopter Script - Thanks! - - local _position = _crate:getPosition().p -- get position of crate - local _playerPosition = _heli:getPosition().p -- get position of helicopter - local _relativePosition = mist.vec.sub(_position, _playerPosition) - - local _playerHeading = mist.getHeading(_heli) -- the rest of the code determines the 'o'clock' bearing of the missile relative to the helicopter - - local _headingVector = { x = math.cos(_playerHeading), y = 0, z = math.sin(_playerHeading) } - - local _headingVectorPerpendicular = { x = math.cos(_playerHeading + math.pi / 2), y = 0, z = math.sin(_playerHeading + math.pi / 2) } - - local _forwardDistance = mist.vec.dp(_relativePosition, _headingVector) - - local _rightDistance = mist.vec.dp(_relativePosition, _headingVectorPerpendicular) - - local _angle = math.atan2(_rightDistance, _forwardDistance) * 180 / math.pi - - if _angle < 0 then - _angle = 360 + _angle - end - _angle = math.floor(_angle * 12 / 360 + 0.5) - if _angle == 0 then - _angle = 12 - end - - return _angle -end - - -function ctld.getCompassBearing(_ref, _unitPos) - - _ref = mist.utils.makeVec3(_ref, 0) -- turn it into Vec3 if it is not already. - _unitPos = mist.utils.makeVec3(_unitPos, 0) -- turn it into Vec3 if it is not already. - - local _vec = { x = _unitPos.x - _ref.x, y = _unitPos.y - _ref.y, z = _unitPos.z - _ref.z } - - local _dir = mist.utils.getDir(_vec, _ref) - - local _bearing = mist.utils.round(mist.utils.toDegree(_dir), 0) - - return _bearing -end - -function ctld.listNearbyCrates(_args) - - local _message = "" - - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli == nil then - - return -- no heli! - end - - local _crates = ctld.getCratesAndDistance(_heli) - - --sort - local _sort = function( a,b ) return a.dist < b.dist end - table.sort(_crates,_sort) - - for _, _crate in pairs(_crates) do - - if _crate.dist < 1000 and _crate.details.unit ~= "FOB" then - _message = string.format("%s\n%s crate - kg %i - %i m - %d o'clock", _message, _crate.details.desc, _crate.details.weight, _crate.dist, ctld.getClockDirection(_heli, _crate.crateUnit)) - end - end - - - local _fobMsg = "" - for _, _fobCrate in pairs(_crates) do - - if _fobCrate.dist < 1000 and _fobCrate.details.unit == "FOB" then - _fobMsg = _fobMsg .. string.format("FOB Crate - %d m - %d o'clock\n", _fobCrate.dist, ctld.getClockDirection(_heli, _fobCrate.crateUnit)) - end - end - - if _message ~= "" or _fobMsg ~= "" then - - local _txt = "" - - if _message ~= "" then - _txt = "Nearby Crates:\n" .. _message - end - - if _fobMsg ~= "" then - - if _message ~= "" then - _txt = _txt .. "\n\n" - end - - _txt = _txt .. "Nearby FOB Crates (Not Slingloadable):\n" .. _fobMsg - end - - ctld.displayMessageToGroup(_heli, _txt, 20) - - else - --no crates nearby - - local _txt = "No Nearby Crates" - - ctld.displayMessageToGroup(_heli, _txt, 20) - end -end - - -function ctld.listFOBS(_args) - - local _msg = "FOB Positions:" - - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli == nil then - - return -- no heli! - end - - -- get fob positions - - local _fobs = ctld.getSpawnedFobs(_heli) - - -- now check spawned fobs - for _, _fob in ipairs(_fobs) do - _msg = string.format("%s\nFOB @ %s", _msg, ctld.getFOBPositionString(_fob)) - end - - if _msg == "FOB Positions:" then - ctld.displayMessageToGroup(_heli, "Sorry, there are no active FOBs!", 20) - else - ctld.displayMessageToGroup(_heli, _msg, 20) - end -end - -function ctld.getFOBPositionString(_fob) - - local _lat, _lon = coord.LOtoLL(_fob:getPosition().p) - - local _latLngStr = mist.tostringLL(_lat, _lon, 3, ctld.location_DMS) - - -- local _mgrsString = mist.tostringMGRS(coord.LLtoMGRS(coord.LOtoLL(_fob:getPosition().p)), 5) - - local _message = _latLngStr - - local _beaconInfo = ctld.fobBeacons[_fob:getName()] - - if _beaconInfo ~= nil then - _message = string.format("%s - %.2f KHz ", _message, _beaconInfo.vhf / 1000) - _message = string.format("%s - %.2f MHz ", _message, _beaconInfo.uhf / 1000000) - _message = string.format("%s - %.2f MHz ", _message, _beaconInfo.fm / 1000000) - end - - return _message -end - - -function ctld.displayMessageToGroup(_unit, _text, _time,_clear) - - local _groupId = ctld.getGroupId(_unit) - if _groupId then - if _clear == true then - trigger.action.outTextForGroup(_groupId, _text, _time,_clear) - else - trigger.action.outTextForGroup(_groupId, _text, _time) - end - end -end - -function ctld.heightDiff(_unit) - - local _point = _unit:getPoint() - - -- env.info("heightunit " .. _point.y) - --env.info("heightland " .. land.getHeight({ x = _point.x, y = _point.z })) - - return _point.y - land.getHeight({ x = _point.x, y = _point.z }) -end - ---includes fob crates! -function ctld.getCratesAndDistance(_heli) - - local _crates = {} - - local _allCrates - if _heli:getCoalition() == 1 then - _allCrates = ctld.spawnedCratesRED - else - _allCrates = ctld.spawnedCratesBLUE - end - - for _crateName, _details in pairs(_allCrates) do - - --get crate - local _crate = ctld.getCrateObject(_crateName) - - --in air seems buggy with crates so if in air is true, get the height above ground and the speed magnitude - if _crate ~= nil and _crate:getLife() > 0 - and (ctld.inAir(_crate) == false) then - - local _dist = ctld.getDistance(_crate:getPoint(), _heli:getPoint()) - - local _crateDetails = { crateUnit = _crate, dist = _dist, details = _details } - - table.insert(_crates, _crateDetails) - end - end - - local _fobCrates - if _heli:getCoalition() == 1 then - _fobCrates = ctld.droppedFOBCratesRED - else - _fobCrates = ctld.droppedFOBCratesBLUE - end - - for _crateName, _details in pairs(_fobCrates) do - - --get crate - local _crate = ctld.getCrateObject(_crateName) - - if _crate ~= nil and _crate:getLife() > 0 then - - local _dist = ctld.getDistance(_crate:getPoint(), _heli:getPoint()) - - local _crateDetails = { crateUnit = _crate, dist = _dist, details = { unit = "FOB" }, } - - table.insert(_crates, _crateDetails) - end - end - - return _crates -end - - -function ctld.getClosestCrate(_heli, _crates, _type) - - local _closetCrate = nil - local _shortestDistance = -1 - local _distance = 0 - - for _, _crate in pairs(_crates) do - - if (_crate.details.unit == _type or _type == nil) then - _distance = _crate.dist - - if _distance ~= nil and (_shortestDistance == -1 or _distance < _shortestDistance) then - _shortestDistance = _distance - _closetCrate = _crate - end - end - end - - return _closetCrate -end - -function ctld.findNearestAASystem(_heli,_aaSystem) - - local _closestHawkGroup = nil - local _shortestDistance = -1 - local _distance = 0 - - for _groupName, _hawkDetails in pairs(ctld.completeAASystems) do - - local _hawkGroup = Group.getByName(_groupName) - - -- env.info(_groupName..": "..mist.utils.tableShow(_hawkDetails)) - if _hawkGroup ~= nil and _hawkGroup:getCoalition() == _heli:getCoalition() and _hawkDetails[1].system.name == _aaSystem.name then - - local _units = _hawkGroup:getUnits() - - for _, _leader in pairs(_units) do - - if _leader ~= nil and _leader:getLife() > 0 then - - _distance = ctld.getDistance(_leader:getPoint(), _heli:getPoint()) - - if _distance ~= nil and (_shortestDistance == -1 or _distance < _shortestDistance) then - _shortestDistance = _distance - _closestHawkGroup = _hawkGroup - end - - break - end - end - end - end - - if _closestHawkGroup ~= nil then - - return { group = _closestHawkGroup, dist = _shortestDistance } - end - return nil -end - -function ctld.getCrateObject(_name) - local _crate - - if ctld.staticBugWorkaround then - _crate = Unit.getByName(_name) - else - _crate = StaticObject.getByName(_name) - end - return _crate -end - - - -function ctld.unpackCrates(_arguments) - - local _status, _err = pcall(function(_args) - - -- trigger.action.outText("Unpack Crates".._args[1],10) - - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli ~= nil and ctld.inAir(_heli) == false then - - local _crates = ctld.getCratesAndDistance(_heli) - local _crate = ctld.getClosestCrate(_heli, _crates) - - - if ctld.inLogisticsZone(_heli) == true or ctld.farEnoughFromLogisticZone(_heli) == false then - - ctld.displayMessageToGroup(_heli, "You can't unpack that here! Take it to where it's needed!", 20) - - return - end - - - - if _crate ~= nil and _crate.dist < 750 - and (_crate.details.unit == "FOB" or _crate.details.unit == "FOB-SMALL") then - - ctld.unpackFOBCrates(_crates, _heli) - - return - - elseif _crate ~= nil and _crate.dist < 200 then - - if ctld.forceCrateToBeMoved and ctld.crateMove[_crate.crateUnit:getName()] then - ctld.displayMessageToGroup(_heli,"Sorry you must move this crate before you unpack it!", 20) - return - end - - - local _aaTemplate = ctld.getAATemplate(_crate.details.unit) - - if _aaTemplate then - - if _crate.details.unit == _aaTemplate.repair then - ctld.repairAASystem(_heli, _crate,_aaTemplate) - else - ctld.unpackAASystem(_heli, _crate, _crates,_aaTemplate) - end - - return -- stop processing - -- is multi crate? - elseif _crate.details.cratesRequired ~= nil and _crate.details.cratesRequired > 1 then - -- multicrate - - ctld.unpackMultiCrate(_heli, _crate, _crates) - - return - - else - -- single crate - local _cratePoint = _crate.crateUnit:getPoint() - local _crateName = _crate.crateUnit:getName() - - -- ctld.spawnCrateStatic( _heli:getCoalition(),ctld.getNextUnitId(),{x=100,z=100},_crateName,100) - - --remove crate - -- if ctld.slingLoad == false then - _crate.crateUnit:destroy() - -- end - - local _spawnedGroups = ctld.spawnCrateGroup(_heli, { _cratePoint }, { _crate.details.unit }) - - if _heli:getCoalition() == 1 then - ctld.spawnedCratesRED[_crateName] = nil - else - ctld.spawnedCratesBLUE[_crateName] = nil - end - - ctld.processCallback({unit = _heli, crate = _crate , spawnedGroup = _spawnedGroups, action = "unpack"}) - - if _crate.details.unit == "1L13 EWR" then - ctld.addEWRTask(_spawnedGroups) - - -- env.info("Added EWR") - end - - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " successfully deployed " .. _crate.details.desc .. " to the field", 10) - - if ctld.isJTACUnitType(_crate.details.unit) and ctld.JTAC_dropEnabled then - - local _code = table.remove(ctld.jtacGeneratedLaserCodes, 1) - --put to the end - table.insert(ctld.jtacGeneratedLaserCodes, _code) - - ctld.JTACAutoLase(_spawnedGroups:getName(), _code) --(_jtacGroupName, _laserCode, _smoke, _lock, _colour) - end - end - - else - - ctld.displayMessageToGroup(_heli, "No friendly crates close enough to unpack", 20) - end - end - end, _arguments) - - if (not _status) then - env.error(string.format("CTLD ERROR: %s", _err)) - end -end - - --- builds a fob! -function ctld.unpackFOBCrates(_crates, _heli) - - if ctld.inLogisticsZone(_heli) == true then - - ctld.displayMessageToGroup(_heli, "You can't unpack that here! Take it to where it's needed!", 20) - - return - end - - -- unpack multi crate - local _nearbyMultiCrates = {} - - local _bigFobCrates = 0 - local _smallFobCrates = 0 - local _totalCrates = 0 - - for _, _nearbyCrate in pairs(_crates) do - - if _nearbyCrate.dist < 750 then - - if _nearbyCrate.details.unit == "FOB" then - _bigFobCrates = _bigFobCrates + 1 - table.insert(_nearbyMultiCrates, _nearbyCrate) - elseif _nearbyCrate.details.unit == "FOB-SMALL" then - _smallFobCrates = _smallFobCrates + 1 - table.insert(_nearbyMultiCrates, _nearbyCrate) - end - - --catch divide by 0 - if _smallFobCrates > 0 then - _totalCrates = _bigFobCrates + (_smallFobCrates/3.0) - else - _totalCrates = _bigFobCrates - end - - if _totalCrates >= ctld.cratesRequiredForFOB then - break - end - end - end - - --- check crate count - if _totalCrates >= ctld.cratesRequiredForFOB then - - -- destroy crates - - local _points = {} - - for _, _crate in pairs(_nearbyMultiCrates) do - - if _heli:getCoalition() == 1 then - ctld.droppedFOBCratesRED[_crate.crateUnit:getName()] = nil - ctld.spawnedCratesRED[_crate.crateUnit:getName()] = nil - else - ctld.droppedFOBCratesBLUE[_crate.crateUnit:getName()] = nil - ctld.spawnedCratesBLUE[_crate.crateUnit:getName()] = nil - end - - table.insert(_points, _crate.crateUnit:getPoint()) - - --destroy - _crate.crateUnit:destroy() - end - - local _centroid = ctld.getCentroid(_points) - - timer.scheduleFunction(function(_args) - - local _unitId = ctld.getNextUnitId() - local _name = "Deployed FOB #" .. _unitId - - local _fob = ctld.spawnFOB(_args[2], _unitId, _args[1], _name) - - --make it able to deploy crates - table.insert(ctld.logisticUnits, _fob:getName()) - - ctld.beaconCount = ctld.beaconCount + 1 - - local _radioBeaconName = "FOB Beacon #" .. ctld.beaconCount - - local _radioBeaconDetails = ctld.createRadioBeacon(_args[1], _args[3], _args[2], _radioBeaconName, nil, true) - - ctld.fobBeacons[_name] = { vhf = _radioBeaconDetails.vhf, uhf = _radioBeaconDetails.uhf, fm = _radioBeaconDetails.fm } - - if ctld.troopPickupAtFOB == true then - table.insert(ctld.builtFOBS, _fob:getName()) - - trigger.action.outTextForCoalition(_args[3], "Finished building FOB! Crates and Troops can now be picked up.", 10) - else - trigger.action.outTextForCoalition(_args[3], "Finished building FOB! Crates can now be picked up.", 10) - end - end, { _centroid, _heli:getCountry(), _heli:getCoalition() }, timer.getTime() + ctld.buildTimeFOB) - - local _txt = string.format("%s started building FOB using %d FOB crates, it will be finished in %d seconds.\nPosition marked with smoke.", ctld.getPlayerNameOrType(_heli), _totalCrates, ctld.buildTimeFOB) - - ctld.processCallback({unit = _heli, position = _centroid, action = "fob"}) - - trigger.action.smoke(_centroid, trigger.smokeColor.Green) - - trigger.action.outTextForCoalition(_heli:getCoalition(), _txt, 10) - else - local _txt = string.format("Cannot build FOB!\n\nIt requires %d Large FOB crates ( 3 small FOB crates equal 1 large FOB Crate) and there are the equivalent of %d large FOB crates nearby\n\nOr the crates are not within 750m of each other", ctld.cratesRequiredForFOB, _totalCrates) - ctld.displayMessageToGroup(_heli, _txt, 20) - end -end - ---unloads the sling crate when the helicopter is on the ground or between 4.5 - 10 meters -function ctld.dropSlingCrate(_args) - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli == nil then - return -- no heli! - end - - local _currentCrate = ctld.inTransitSlingLoadCrates[_heli:getName()] - - if _currentCrate == nil then - if ctld.hoverPickup then - ctld.displayMessageToGroup(_heli, "You are not currently transporting any crates. \n\nTo Pickup a crate, hover for "..ctld.hoverTime.." seconds above the crate", 10) - else - ctld.displayMessageToGroup(_heli, "You are not currently transporting any crates. \n\nTo Pickup a crate - land and use F10 Crate Commands to load one.", 10) - end - else - - local _heli = ctld.getTransportUnit(_args[1]) - - local _point = _heli:getPoint() - - local _unitId = ctld.getNextUnitId() - - local _side = _heli:getCoalition() - - local _name = string.format("%s #%i", _currentCrate.desc, _unitId) - - - local _heightDiff = ctld.heightDiff(_heli) - - if ctld.inAir(_heli) == false or _heightDiff <= 7.5 then - ctld.displayMessageToGroup(_heli, _currentCrate.desc .. " crate has been safely unhooked and is at your 12 o'clock", 10) - _point = ctld.getPointAt12Oclock(_heli, 30) - -- elseif _heightDiff > 40.0 then - -- ctld.inTransitSlingLoadCrates[_heli:getName()] = nil - -- ctld.displayMessageToGroup(_heli, "You were too high! The crate has been destroyed", 10) - -- return - elseif _heightDiff > 7.5 and _heightDiff <= 40.0 then - ctld.displayMessageToGroup(_heli, _currentCrate.desc .. " crate has been safely dropped below you", 10) - else -- _heightDiff > 40.0 - ctld.inTransitSlingLoadCrates[_heli:getName()] = nil - ctld.displayMessageToGroup(_heli, "You were too high! The crate has been destroyed", 10) - return - end - - - --remove crate from cargo - ctld.inTransitSlingLoadCrates[_heli:getName()] = nil - ctld.adaptWeightToCargo(_heli:getName()) - local _spawnedCrate = ctld.spawnCrateStatic(_heli:getCountry(), _unitId, _point, _name, _currentCrate.weight,_side) - end -end - ---spawns a radio beacon made up of two units, --- one for VHF and one for UHF --- The units are set to to NOT engage -function ctld.createRadioBeacon(_point, _coalition, _country, _name, _batteryTime, _isFOB) - - local _uhfGroup = ctld.spawnRadioBeaconUnit(_point, _country, "UHF") - local _vhfGroup = ctld.spawnRadioBeaconUnit(_point, _country, "VHF") - local _fmGroup = ctld.spawnRadioBeaconUnit(_point, _country, "FM") - - local _freq = ctld.generateADFFrequencies() - - --create timeout - local _battery - - if _batteryTime == nil then - _battery = timer.getTime() + (ctld.deployedBeaconBattery * 60) - else - _battery = timer.getTime() + (_batteryTime * 60) - end - - local _lat, _lon = coord.LOtoLL(_point) - - local _latLngStr = mist.tostringLL(_lat, _lon, 3, ctld.location_DMS) - - --local _mgrsString = mist.tostringMGRS(coord.LLtoMGRS(coord.LOtoLL(_point)), 5) - - local _message = _name - - if _isFOB then - -- _message = "FOB " .. _message - _battery = -1 --never run out of power! - end - - _message = _message .. " - " .. _latLngStr - - -- env.info("GEN UHF: ".. _freq.uhf) - -- env.info("GEN VHF: ".. _freq.vhf) - - _message = string.format("%s - %.2f KHz", _message, _freq.vhf / 1000) - - _message = string.format("%s - %.2f MHz", _message, _freq.uhf / 1000000) - - _message = string.format("%s - %.2f MHz ", _message, _freq.fm / 1000000) - - - - local _beaconDetails = { - vhf = _freq.vhf, - vhfGroup = _vhfGroup:getName(), - uhf = _freq.uhf, - uhfGroup = _uhfGroup:getName(), - fm = _freq.fm, - fmGroup = _fmGroup:getName(), - text = _message, - battery = _battery, - coalition = _coalition, - } - ctld.updateRadioBeacon(_beaconDetails) - - table.insert(ctld.deployedRadioBeacons, _beaconDetails) - - return _beaconDetails -end - -function ctld.generateADFFrequencies() - - if #ctld.freeUHFFrequencies <= 3 then - ctld.freeUHFFrequencies = ctld.usedUHFFrequencies - ctld.usedUHFFrequencies = {} - end - - --remove frequency at RANDOM - local _uhf = table.remove(ctld.freeUHFFrequencies, math.random(#ctld.freeUHFFrequencies)) - table.insert(ctld.usedUHFFrequencies, _uhf) - - - if #ctld.freeVHFFrequencies <= 3 then - ctld.freeVHFFrequencies = ctld.usedVHFFrequencies - ctld.usedVHFFrequencies = {} - end - - local _vhf = table.remove(ctld.freeVHFFrequencies, math.random(#ctld.freeVHFFrequencies)) - table.insert(ctld.usedVHFFrequencies, _vhf) - - if #ctld.freeFMFrequencies <= 3 then - ctld.freeFMFrequencies = ctld.usedFMFrequencies - ctld.usedFMFrequencies = {} - end - - local _fm = table.remove(ctld.freeFMFrequencies, math.random(#ctld.freeFMFrequencies)) - table.insert(ctld.usedFMFrequencies, _fm) - - return { uhf = _uhf, vhf = _vhf, fm = _fm } - --- return {uhf=_uhf,vhf=_vhf} -end - - - -function ctld.spawnRadioBeaconUnit(_point, _country, _type) - - local _groupId = ctld.getNextGroupId() - - local _unitId = ctld.getNextUnitId() - - local _radioGroup = { - ["visible"] = false, - -- ["groupId"] = _groupId, - ["hidden"] = false, - ["units"] = { - [1] = { - ["y"] = _point.z, - ["type"] = "TACAN_beacon", - ["name"] = _type .. " Radio Beacon Unit #" .. _unitId, - -- ["unitId"] = _unitId, - ["heading"] = 0, - ["playerCanDrive"] = true, - ["skill"] = "Excellent", - ["x"] = _point.x, - } - }, - -- ["y"] = _positions[1].z, - -- ["x"] = _positions[1].x, - ["name"] = _type .. " Radio Beacon Group #" .. _groupId, - ["task"] = {}, - --added two fields below for MIST - ["category"] = Group.Category.GROUND, - ["country"] = _country - } - - -- return coalition.addGroup(_country, Group.Category.GROUND, _radioGroup) - return Group.getByName(mist.dynAdd(_radioGroup).name) -end - -function ctld.updateRadioBeacon(_beaconDetails) - - local _vhfGroup = Group.getByName(_beaconDetails.vhfGroup) - - local _uhfGroup = Group.getByName(_beaconDetails.uhfGroup) - - local _fmGroup = Group.getByName(_beaconDetails.fmGroup) - - local _radioLoop = {} - - if _vhfGroup ~= nil and _vhfGroup:getUnits() ~= nil and #_vhfGroup:getUnits() == 1 then - table.insert(_radioLoop, { group = _vhfGroup, freq = _beaconDetails.vhf, silent = false, mode = 0 }) - end - - if _uhfGroup ~= nil and _uhfGroup:getUnits() ~= nil and #_uhfGroup:getUnits() == 1 then - table.insert(_radioLoop, { group = _uhfGroup, freq = _beaconDetails.uhf, silent = true, mode = 0 }) - end - - if _fmGroup ~= nil and _fmGroup:getUnits() ~= nil and #_fmGroup:getUnits() == 1 then - table.insert(_radioLoop, { group = _fmGroup, freq = _beaconDetails.fm, silent = false, mode = 1 }) - end - - local _batLife = _beaconDetails.battery - timer.getTime() - - if (_batLife <= 0 and _beaconDetails.battery ~= -1) or #_radioLoop ~= 3 then - -- ran out of batteries - - if _vhfGroup ~= nil then - _vhfGroup:destroy() - end - if _uhfGroup ~= nil then - _uhfGroup:destroy() - end - if _fmGroup ~= nil then - _fmGroup:destroy() - end - - return false - end - - --fobs have unlimited battery life - -- if _battery ~= -1 then - -- _text = _text.." "..mist.utils.round(_batLife).." seconds of battery" - -- end - - for _, _radio in pairs(_radioLoop) do - - local _groupController = _radio.group:getController() - - local _sound = ctld.radioSound - if _radio.silent then - _sound = ctld.radioSoundFC3 - end - - _sound = "l10n/DEFAULT/".._sound - - _groupController:setOption(AI.Option.Ground.id.ROE, AI.Option.Ground.val.ROE.WEAPON_HOLD) - - trigger.action.radioTransmission(_sound, _radio.group:getUnit(1):getPoint(), _radio.mode, false, _radio.freq, 1000) - --This function doesnt actually stop transmitting when then sound is false. My hope is it will stop if a new beacon is created on the same - -- frequency... OR they fix the bug where it wont stop. - -- end - - -- - end - - return true - - -- trigger.action.radioTransmission(ctld.radioSound, _point, 1, true, _frequency, 1000) -end - -function ctld.listRadioBeacons(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _message = "" - - if _heli ~= nil then - - for _x, _details in pairs(ctld.deployedRadioBeacons) do - - if _details.coalition == _heli:getCoalition() then - _message = _message .. _details.text .. "\n" - end - end - - if _message ~= "" then - ctld.displayMessageToGroup(_heli, "Radio Beacons:\n" .. _message, 20) - else - ctld.displayMessageToGroup(_heli, "No Active Radio Beacons", 20) - end - end -end - -function ctld.dropRadioBeacon(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _message = "" - - if _heli ~= nil and ctld.inAir(_heli) == false then - - --deploy 50 m infront - --try to spawn at 12 oclock to us - local _point = ctld.getPointAt12Oclock(_heli, 50) - - ctld.beaconCount = ctld.beaconCount + 1 - local _name = "Beacon #" .. ctld.beaconCount - - local _radioBeaconDetails = ctld.createRadioBeacon(_point, _heli:getCoalition(), _heli:getCountry(), _name, nil, false) - - -- mark with flare? - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " deployed a Radio Beacon.\n\n" .. _radioBeaconDetails.text, 20) - - else - ctld.displayMessageToGroup(_heli, "You need to land before you can deploy a Radio Beacon!", 20) - end -end - ---remove closet radio beacon -function ctld.removeRadioBeacon(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - local _message = "" - - if _heli ~= nil and ctld.inAir(_heli) == false then - - -- mark with flare? - - local _closetBeacon = nil - local _shortestDistance = -1 - local _distance = 0 - - for _x, _details in pairs(ctld.deployedRadioBeacons) do - - if _details.coalition == _heli:getCoalition() then - - local _group = Group.getByName(_details.vhfGroup) - - if _group ~= nil and #_group:getUnits() == 1 then - - _distance = ctld.getDistance(_heli:getPoint(), _group:getUnit(1):getPoint()) - if _distance ~= nil and (_shortestDistance == -1 or _distance < _shortestDistance) then - _shortestDistance = _distance - _closetBeacon = _details - end - end - end - end - - if _closetBeacon ~= nil and _shortestDistance then - local _vhfGroup = Group.getByName(_closetBeacon.vhfGroup) - - local _uhfGroup = Group.getByName(_closetBeacon.uhfGroup) - - local _fmGroup = Group.getByName(_closetBeacon.fmGroup) - - if _vhfGroup ~= nil then - _vhfGroup:destroy() - end - if _uhfGroup ~= nil then - _uhfGroup:destroy() - end - if _fmGroup ~= nil then - _fmGroup:destroy() - end - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " removed a Radio Beacon.\n\n" .. _closetBeacon.text, 20) - else - ctld.displayMessageToGroup(_heli, "No Radio Beacons within 500m.", 20) - end - - else - ctld.displayMessageToGroup(_heli, "You need to land before remove a Radio Beacon", 20) - end -end - --- gets the center of a bunch of points! --- return proper DCS point with height -function ctld.getCentroid(_points) - local _tx, _ty = 0, 0 - for _index, _point in ipairs(_points) do - _tx = _tx + _point.x - _ty = _ty + _point.z - end - - local _npoints = #_points - - local _point = { x = _tx / _npoints, z = _ty / _npoints } - - _point.y = land.getHeight({ _point.x, _point.z }) - - return _point -end - -function ctld.getAATemplate(_unitName) - - for _,_system in pairs(ctld.AASystemTemplate) do - - if _system.repair == _unitName then - return _system - end - - for _,_part in pairs(_system.parts) do - - if _unitName == _part.name then - return _system - end - end - end - - return nil - -end - -function ctld.getLauncherUnitFromAATemplate(_aaTemplate) - for _,_part in pairs(_aaTemplate.parts) do - - if _part.launcher then - return _part.name - end - end - - return nil -end - -function ctld.rearmAASystem(_heli, _nearestCrate, _nearbyCrates, _aaSystemTemplate) - - -- are we adding to existing aa system? - -- check to see if the crate is a launcher - if ctld.getLauncherUnitFromAATemplate(_aaSystemTemplate) == _nearestCrate.details.unit then - - -- find nearest COMPLETE AA system - local _nearestSystem = ctld.findNearestAASystem(_heli, _aaSystemTemplate) - - if _nearestSystem ~= nil and _nearestSystem.dist < 300 then - - local _uniqueTypes = {} -- stores each unique part of system - local _types = {} - local _points = {} - - local _units = _nearestSystem.group:getUnits() - - if _units ~= nil and #_units > 0 then - - for x = 1, #_units do - if _units[x]:getLife() > 0 then - - --this allows us to count each type once - _uniqueTypes[_units[x]:getTypeName()] = _units[x]:getTypeName() - - table.insert(_points, _units[x]:getPoint()) - table.insert(_types, _units[x]:getTypeName()) - end - end - end - - -- do we have the correct number of unique pieces and do we have enough points for all the pieces - if ctld.countTableEntries(_uniqueTypes) == _aaSystemTemplate.count and #_points >= _aaSystemTemplate.count then - - -- rearm aa system - -- destroy old group - ctld.completeAASystems[_nearestSystem.group:getName()] = nil - - _nearestSystem.group:destroy() - - local _spawnedGroup = ctld.spawnCrateGroup(_heli, _points, _types) - - ctld.completeAASystems[_spawnedGroup:getName()] = ctld.getAASystemDetails(_spawnedGroup, _aaSystemTemplate) - - ctld.processCallback({unit = _heli, crate = _nearestCrate , spawnedGroup = _spawnedGroup, action = "rearm"}) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " successfully rearmed a full ".._aaSystemTemplate.name.." in the field", 10) - - if _heli:getCoalition() == 1 then - ctld.spawnedCratesRED[_nearestCrate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_nearestCrate.crateUnit:getName()] = nil - end - - -- remove crate - -- if ctld.slingLoad == false then - _nearestCrate.crateUnit:destroy() - -- end - - return true -- all done so quit - end - end - end - - return false -end - -function ctld.getAASystemDetails(_hawkGroup,_aaSystemTemplate) - - local _units = _hawkGroup:getUnits() - - local _hawkDetails = {} - - for _, _unit in pairs(_units) do - table.insert(_hawkDetails, { point = _unit:getPoint(), unit = _unit:getTypeName(), name = _unit:getName(), system =_aaSystemTemplate}) - end - - return _hawkDetails -end - -function ctld.countTableEntries(_table) - - if _table == nil then - return 0 - end - - - local _count = 0 - - for _key, _value in pairs(_table) do - - _count = _count + 1 - end - - return _count -end - -function ctld.unpackAASystem(_heli, _nearestCrate, _nearbyCrates,_aaSystemTemplate) - - if ctld.rearmAASystem(_heli, _nearestCrate, _nearbyCrates,_aaSystemTemplate) then - -- rearmed hawk - return - end - - -- are there all the pieces close enough together - local _systemParts = {} - - --initialise list of parts - for _,_part in pairs(_aaSystemTemplate.parts) do - _systemParts[_part.name] = {name = _part.name,desc = _part.desc,found = false} - end - - -- find all nearest crates and add them to the list if they're part of the AA System - for _, _nearbyCrate in pairs(_nearbyCrates) do - - if _nearbyCrate.dist < 500 then - - if _systemParts[_nearbyCrate.details.unit] ~= nil and _systemParts[_nearbyCrate.details.unit].found == false then - local _foundPart = _systemParts[_nearbyCrate.details.unit] - - _foundPart.found = true - _foundPart.crate = _nearbyCrate - - _systemParts[_nearbyCrate.details.unit] = _foundPart - end - end - end - - local _count = 0 - local _txt = "" - - local _posArray = {} - local _typeArray = {} - for _name, _systemPart in pairs(_systemParts) do - - if _systemPart.found == false then - _txt = _txt.."Missing ".._systemPart.desc.."\n" - else - - local _launcherPart = ctld.getLauncherUnitFromAATemplate(_aaSystemTemplate) - - --handle multiple launchers from one crate - if (_name == "Hawk ln" and ctld.hawkLaunchers > 1) - or (_launcherPart == _name and ctld.aaLaunchers > 1) then - - --add multiple launcher - local _launchers = ctld.aaLaunchers - - if _name == "Hawk ln" then - _launchers = ctld.hawkLaunchers - end - - for _i = 1, _launchers do - - -- spawn in a circle around the crate - local _angle = math.pi * 2 * (_i - 1) / _launchers - local _xOffset = math.cos(_angle) * 12 - local _yOffset = math.sin(_angle) * 12 - - local _point = _systemPart.crate.crateUnit:getPoint() - - _point = { x = _point.x + _xOffset, y = _point.y, z = _point.z + _yOffset } - - table.insert(_posArray, _point) - table.insert(_typeArray, _name) - end - else - table.insert(_posArray, _systemPart.crate.crateUnit:getPoint()) - table.insert(_typeArray, _name) - end - end - end - - local _activeLaunchers = ctld.countCompleteAASystems(_heli) - - local _allowed = ctld.getAllowedAASystems(_heli) - - env.info("Active: ".._activeLaunchers.." Allowed: ".._allowed) - - if _activeLaunchers + 1 > _allowed then - trigger.action.outTextForCoalition(_heli:getCoalition(), "Out of parts for AA Systems. Current limit is ".._allowed.." \n", 10) - return - end - - if _txt ~= "" then - ctld.displayMessageToGroup(_heli, "Cannot build ".._aaSystemTemplate.name.."\n" .. _txt .. "\n\nOr the crates are not close enough together", 20) - return - else - - -- destroy crates - for _name, _systemPart in pairs(_systemParts) do - - if _heli:getCoalition() == 1 then - ctld.spawnedCratesRED[_systemPart.crate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_systemPart.crate.crateUnit:getName()] = nil - end - - --destroy - -- if ctld.slingLoad == false then - _systemPart.crate.crateUnit:destroy() - --end - end - - -- HAWK / BUK READY! - local _spawnedGroup = ctld.spawnCrateGroup(_heli, _posArray, _typeArray) - - ctld.completeAASystems[_spawnedGroup:getName()] = ctld.getAASystemDetails(_spawnedGroup,_aaSystemTemplate) - - ctld.processCallback({unit = _heli, crate = _nearestCrate , spawnedGroup = _spawnedGroup, action = "unpack"}) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " successfully deployed a full ".._aaSystemTemplate.name.." to the field. \n\nAA Active System limit is: ".._allowed.."\nActive: "..(_activeLaunchers+1), 10) - - end -end - ---count the number of captured cities, sets the amount of allowed AA Systems -function ctld.getAllowedAASystems(_heli) - - if _heli:getCoalition() == 1 then - return ctld.AASystemLimitBLUE - else - return ctld.AASystemLimitRED - end - - -end - - -function ctld.countCompleteAASystems(_heli) - - local _count = 0 - - for _groupName, _hawkDetails in pairs(ctld.completeAASystems) do - - local _hawkGroup = Group.getByName(_groupName) - - -- env.info(_groupName..": "..mist.utils.tableShow(_hawkDetails)) - if _hawkGroup ~= nil and _hawkGroup:getCoalition() == _heli:getCoalition() then - - local _units = _hawkGroup:getUnits() - - if _units ~=nil and #_units > 0 then - --get the system template - local _aaSystemTemplate = _hawkDetails[1].system - - local _uniqueTypes = {} -- stores each unique part of system - local _types = {} - local _points = {} - - if _units ~= nil and #_units > 0 then - - for x = 1, #_units do - if _units[x]:getLife() > 0 then - - --this allows us to count each type once - _uniqueTypes[_units[x]:getTypeName()] = _units[x]:getTypeName() - - table.insert(_points, _units[x]:getPoint()) - table.insert(_types, _units[x]:getTypeName()) - end - end - end - - -- do we have the correct number of unique pieces and do we have enough points for all the pieces - if ctld.countTableEntries(_uniqueTypes) == _aaSystemTemplate.count and #_points >= _aaSystemTemplate.count then - _count = _count +1 - end - end - end - end - - return _count -end - - -function ctld.repairAASystem(_heli, _nearestCrate,_aaSystem) - - -- find nearest COMPLETE AA system - local _nearestHawk = ctld.findNearestAASystem(_heli,_aaSystem) - - - - if _nearestHawk ~= nil and _nearestHawk.dist < 300 then - - local _oldHawk = ctld.completeAASystems[_nearestHawk.group:getName()] - - --spawn new one - - local _types = {} - local _points = {} - - for _, _part in pairs(_oldHawk) do - table.insert(_points, _part.point) - table.insert(_types, _part.unit) - end - - --remove old system - ctld.completeAASystems[_nearestHawk.group:getName()] = nil - _nearestHawk.group:destroy() - - local _spawnedGroup = ctld.spawnCrateGroup(_heli, _points, _types) - - ctld.completeAASystems[_spawnedGroup:getName()] = ctld.getAASystemDetails(_spawnedGroup,_aaSystem) - - ctld.processCallback({unit = _heli, crate = _nearestCrate , spawnedGroup = _spawnedGroup, action = "repair"}) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " successfully repaired a full ".._aaSystem.name.." in the field", 10) - - if _heli:getCoalition() == 1 then - ctld.spawnedCratesRED[_nearestCrate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_nearestCrate.crateUnit:getName()] = nil - end - - -- remove crate - -- if ctld.slingLoad == false then - _nearestCrate.crateUnit:destroy() - -- end - - else - ctld.displayMessageToGroup(_heli, "Cannot repair ".._aaSystem.name..". No damaged ".._aaSystem.name.." within 300m", 10) - end -end - -function ctld.unpackMultiCrate(_heli, _nearestCrate, _nearbyCrates) - - -- unpack multi crate - local _nearbyMultiCrates = {} - - for _, _nearbyCrate in pairs(_nearbyCrates) do - - if _nearbyCrate.dist < 300 then - - if _nearbyCrate.details.unit == _nearestCrate.details.unit then - - table.insert(_nearbyMultiCrates, _nearbyCrate) - - if #_nearbyMultiCrates == _nearestCrate.details.cratesRequired then - break - end - end - end - end - - --- check crate count - if #_nearbyMultiCrates == _nearestCrate.details.cratesRequired then - - local _point = _nearestCrate.crateUnit:getPoint() - - -- destroy crates - for _, _crate in pairs(_nearbyMultiCrates) do - - if _point == nil then - _point = _crate.crateUnit:getPoint() - end - - if _heli:getCoalition() == 1 then - ctld.spawnedCratesRED[_crate.crateUnit:getName()] = nil - else - ctld.spawnedCratesBLUE[_crate.crateUnit:getName()] = nil - end - - --destroy - -- if ctld.slingLoad == false then - _crate.crateUnit:destroy() - -- end - end - - - local _spawnedGroup = ctld.spawnCrateGroup(_heli, { _point }, { _nearestCrate.details.unit }) - - ctld.processCallback({unit = _heli, crate = _nearestCrate , spawnedGroup = _spawnedGroup, action = "unpack"}) - - local _txt = string.format("%s successfully deployed %s to the field using %d crates", ctld.getPlayerNameOrType(_heli), _nearestCrate.details.desc, #_nearbyMultiCrates) - - trigger.action.outTextForCoalition(_heli:getCoalition(), _txt, 10) - - else - - local _txt = string.format("Cannot build %s!\n\nIt requires %d crates and there are %d \n\nOr the crates are not within 300m of each other", _nearestCrate.details.desc, _nearestCrate.details.cratesRequired, #_nearbyMultiCrates) - - ctld.displayMessageToGroup(_heli, _txt, 20) - end -end - - -function ctld.spawnCrateGroup(_heli, _positions, _types) - - local _id = ctld.getNextGroupId() - - local _groupName = _types[1] .. " #" .. _id - - local _side = _heli:getCoalition() - - local _group = { - ["visible"] = false, - -- ["groupId"] = _id, - ["hidden"] = false, - ["units"] = {}, - -- ["y"] = _positions[1].z, - -- ["x"] = _positions[1].x, - ["name"] = _groupName, - ["task"] = {}, - } - - if #_positions == 1 then - - local _unitId = ctld.getNextUnitId() - local _details = { type = _types[1], unitId = _unitId, name = string.format("Unpacked %s #%i", _types[1], _unitId) } - - _group.units[1] = ctld.createUnit(_positions[1].x + 5, _positions[1].z + 5, 120, _details) - - else - - for _i, _pos in ipairs(_positions) do - - local _unitId = ctld.getNextUnitId() - local _details = { type = _types[_i], unitId = _unitId, name = string.format("Unpacked %s #%i", _types[_i], _unitId) } - - _group.units[_i] = ctld.createUnit(_pos.x + 5, _pos.z + 5, 120, _details) - end - end - - --mist function - _group.category = Group.Category.GROUND - _group.country = _heli:getCountry() - - local _spawnedGroup = Group.getByName(mist.dynAdd(_group).name) - - return _spawnedGroup -end - - - --- spawn normal group -function ctld.spawnDroppedGroup(_point, _details, _spawnBehind, _maxSearch) - - local _groupName = _details.groupName - - local _group = { - ["visible"] = false, - -- ["groupId"] = _details.groupId, - ["hidden"] = false, - ["units"] = {}, - -- ["y"] = _positions[1].z, - -- ["x"] = _positions[1].x, - ["name"] = _groupName, - ["task"] = {}, - } - - - if _spawnBehind == false then - - -- spawn in circle around heli - - local _pos = _point - - for _i, _detail in ipairs(_details.units) do - - local _angle = math.pi * 2 * (_i - 1) / #_details.units - local _xOffset = math.cos(_angle) * 30 - local _yOffset = math.sin(_angle) * 30 - - _group.units[_i] = ctld.createUnit(_pos.x + _xOffset, _pos.z + _yOffset, _angle, _detail) - end - - else - - local _pos = _point - - --try to spawn at 6 oclock to us - local _angle = math.atan2(_pos.z, _pos.x) - local _xOffset = math.cos(_angle) * -30 - local _yOffset = math.sin(_angle) * -30 - - - for _i, _detail in ipairs(_details.units) do - _group.units[_i] = ctld.createUnit(_pos.x + (_xOffset + 10 * _i), _pos.z + (_yOffset + 10 * _i), _angle, _detail) - end - end - - --switch to MIST - _group.category = Group.Category.GROUND; - _group.country = _details.country; - - local _spawnedGroup = Group.getByName(mist.dynAdd(_group).name) - - --local _spawnedGroup = coalition.addGroup(_details.country, Group.Category.GROUND, _group) - - - -- find nearest enemy and head there - if _maxSearch == nil then - _maxSearch = ctld.maximumSearchDistance - end - - local _wpZone = ctld.inWaypointZone(_point,_spawnedGroup:getCoalition()) - - if _wpZone.inZone then - ctld.orderGroupToMoveToPoint(_spawnedGroup:getUnit(1), _wpZone.point) - env.info("Heading to waypoint - In Zone ".._wpZone.name) - else - local _enemyPos = ctld.findNearestEnemy(_details.side, _point, _maxSearch) - - ctld.orderGroupToMoveToPoint(_spawnedGroup:getUnit(1), _enemyPos) - end - - return _spawnedGroup -end - -function ctld.findNearestEnemy(_side, _point, _searchDistance) - - local _closestEnemy = nil - - local _groups - - local _closestEnemyDist = _searchDistance - - local _heliPoint = _point - - if _side == 2 then - _groups = coalition.getGroups(1, Group.Category.GROUND) - else - _groups = coalition.getGroups(2, Group.Category.GROUND) - end - - for _, _group in pairs(_groups) do - - if _group ~= nil then - local _units = _group:getUnits() - - if _units ~= nil and #_units > 0 then - - local _leader = nil - - -- find alive leader - for x = 1, #_units do - if _units[x]:getLife() > 0 then - _leader = _units[x] - break - end - end - - if _leader ~= nil then - local _leaderPos = _leader:getPoint() - local _dist = ctld.getDistance(_heliPoint, _leaderPos) - if _dist < _closestEnemyDist then - _closestEnemyDist = _dist - _closestEnemy = _leaderPos - end - end - end - end - end - - - -- no enemy - move to random point - if _closestEnemy ~= nil then - - -- env.info("found enemy") - return _closestEnemy - else - - local _x = _heliPoint.x + math.random(0, ctld.maximumMoveDistance) - math.random(0, ctld.maximumMoveDistance) - local _z = _heliPoint.z + math.random(0, ctld.maximumMoveDistance) - math.random(0, ctld.maximumMoveDistance) - local _y = _heliPoint.y + math.random(0, ctld.maximumMoveDistance) - math.random(0, ctld.maximumMoveDistance) - - return { x = _x, z = _z,y=_y } - end -end - -function ctld.findNearestGroup(_heli, _groups) - - local _closestGroupDetails = {} - local _closestGroup = nil - - local _closestGroupDist = ctld.maxExtractDistance - - local _heliPoint = _heli:getPoint() - - for _, _groupName in pairs(_groups) do - - local _group = Group.getByName(_groupName) - - if _group ~= nil then - local _units = _group:getUnits() - - if _units ~= nil and #_units > 0 then - - local _leader = nil - - local _groupDetails = { groupId = _group:getID(), groupName = _group:getName(), side = _group:getCoalition(), units = {} } - - -- find alive leader - for x = 1, #_units do - if _units[x]:getLife() > 0 then - - if _leader == nil then - _leader = _units[x] - -- set country based on leader - _groupDetails.country = _leader:getCountry() - end - - local _unitDetails = { type = _units[x]:getTypeName(), unitId = _units[x]:getID(), name = _units[x]:getName() } - - table.insert(_groupDetails.units, _unitDetails) - end - end - - if _leader ~= nil then - local _leaderPos = _leader:getPoint() - local _dist = ctld.getDistance(_heliPoint, _leaderPos) - if _dist < _closestGroupDist then - _closestGroupDist = _dist - _closestGroupDetails = _groupDetails - _closestGroup = _group - end - end - end - end - end - - - if _closestGroup ~= nil then - - return { group = _closestGroup, details = _closestGroupDetails } - else - - return nil - end -end - - -function ctld.createUnit(_x, _y, _angle, _details) - - local _newUnit = { - ["y"] = _y, - ["type"] = _details.type, - ["name"] = _details.name, - -- ["unitId"] = _details.unitId, - ["heading"] = _angle, - ["playerCanDrive"] = true, - ["skill"] = "Excellent", - ["x"] = _x, - } - - return _newUnit -end - -function ctld.addEWRTask(_group) - - -- delayed 2 second to work around bug - timer.scheduleFunction(function(_ewrGroup) - local _grp = ctld.getAliveGroup(_ewrGroup) - - if _grp ~= nil then - local _controller = _grp:getController(); - local _EWR = { - id = 'EWR', - auto = true, - params = { - } - } - _controller:setTask(_EWR) - end - end - , _group:getName(), timer.getTime() + 2) - -end - -function ctld.orderGroupToMoveToPoint(_leader, _destination) - - local _group = _leader:getGroup() - - local _path = {} - table.insert(_path, mist.ground.buildWP(_leader:getPoint(), 'Off Road', 50)) - table.insert(_path, mist.ground.buildWP(_destination, 'Off Road', 50)) - - local _mission = { - id = 'Mission', - params = { - route = { - points =_path - }, - }, - } - - - -- delayed 2 second to work around bug - timer.scheduleFunction(function(_arg) - local _grp = ctld.getAliveGroup(_arg[1]) - - if _grp ~= nil then - local _controller = _grp:getController(); - Controller.setOption(_controller, AI.Option.Ground.id.ALARM_STATE, AI.Option.Ground.val.ALARM_STATE.AUTO) - Controller.setOption(_controller, AI.Option.Ground.id.ROE, AI.Option.Ground.val.ROE.OPEN_FIRE) - _controller:setTask(_arg[2]) - end - end - , {_group:getName(), _mission}, timer.getTime() + 2) - -end - --- are we in pickup zone -function ctld.inPickupZone(_heli) - ctld.logDebug(string.format("ctld.inPickupZone(_heli=%s)", ctld.p(_heli))) - - if ctld.inAir(_heli) then - return { inZone = false, limit = -1, index = -1 } - end - - local _heliPoint = _heli:getPoint() - - for _i, _zoneDetails in pairs(ctld.pickupZones) do - ctld.logTrace(string.format("_zoneDetails=%s", ctld.p(_zoneDetails))) - - local _triggerZone = trigger.misc.getZone(_zoneDetails[1]) - - if _triggerZone == nil then - local _ship = ctld.getTransportUnit(_zoneDetails[1]) - - if _ship then - local _point = _ship:getPoint() - _triggerZone = {} - _triggerZone.point = _point - _triggerZone.radius = 200 -- should be big enough for ship - end - - end - - if _triggerZone ~= nil then - - --get distance to center - - local _dist = ctld.getDistance(_heliPoint, _triggerZone.point) - ctld.logTrace(string.format("_dist=%s", ctld.p(_dist))) - if _dist <= _triggerZone.radius then - local _heliCoalition = _heli:getCoalition() - if _zoneDetails[4] == 1 and (_zoneDetails[5] == _heliCoalition or _zoneDetails[5] == 0) then - return { inZone = true, limit = _zoneDetails[3], index = _i } - end - end - end - end - - local _fobs = ctld.getSpawnedFobs(_heli) - - -- now check spawned fobs - for _, _fob in ipairs(_fobs) do - - --get distance to center - - local _dist = ctld.getDistance(_heliPoint, _fob:getPoint()) - - if _dist <= 150 then - return { inZone = true, limit = 10000, index = -1 }; - end - end - - - - return { inZone = false, limit = -1, index = -1 }; -end - -function ctld.getSpawnedFobs(_heli) - - local _fobs = {} - - for _, _fobName in ipairs(ctld.builtFOBS) do - - local _fob = StaticObject.getByName(_fobName) - - if _fob ~= nil and _fob:isExist() and _fob:getCoalition() == _heli:getCoalition() and _fob:getLife() > 0 then - - table.insert(_fobs, _fob) - end - end - - return _fobs -end - --- are we in a dropoff zone -function ctld.inDropoffZone(_heli) - - if ctld.inAir(_heli) then - return false - end - - local _heliPoint = _heli:getPoint() - - for _, _zoneDetails in pairs(ctld.dropOffZones) do - - local _triggerZone = trigger.misc.getZone(_zoneDetails[1]) - - if _triggerZone ~= nil and (_zoneDetails[3] == _heli:getCoalition() or _zoneDetails[3]== 0) then - - --get distance to center - - local _dist = ctld.getDistance(_heliPoint, _triggerZone.point) - - if _dist <= _triggerZone.radius then - return true - end - end - end - - return false -end - --- are we in a waypoint zone -function ctld.inWaypointZone(_point,_coalition) - - for _, _zoneDetails in pairs(ctld.wpZones) do - - local _triggerZone = trigger.misc.getZone(_zoneDetails[1]) - - --right coalition and active? - if _triggerZone ~= nil and (_zoneDetails[4] == _coalition or _zoneDetails[4]== 0) and _zoneDetails[3] == 1 then - - --get distance to center - - local _dist = ctld.getDistance(_point, _triggerZone.point) - - if _dist <= _triggerZone.radius then - return {inZone = true, point = _triggerZone.point, name = _zoneDetails[1]} - end - end - end - - return {inZone = false} -end - --- are we near friendly logistics zone -function ctld.inLogisticsZone(_heli) - - if ctld.inAir(_heli) then - return false - end - - local _heliPoint = _heli:getPoint() - - for _, _name in pairs(ctld.logisticUnits) do - - local _logistic = StaticObject.getByName(_name) - - if _logistic ~= nil and _logistic:getCoalition() == _heli:getCoalition() then - - --get distance - local _dist = ctld.getDistance(_heliPoint, _logistic:getPoint()) - - if _dist <= ctld.maximumDistanceLogistic then - return true - end - end - end - - return false -end - - --- are far enough from a friendly logistics zone -function ctld.farEnoughFromLogisticZone(_heli) - - if ctld.inAir(_heli) then - return false - end - - local _heliPoint = _heli:getPoint() - - local _farEnough = true - - for _, _name in pairs(ctld.logisticUnits) do - - local _logistic = StaticObject.getByName(_name) - - if _logistic ~= nil and _logistic:getCoalition() == _heli:getCoalition() then - - --get distance - local _dist = ctld.getDistance(_heliPoint, _logistic:getPoint()) - -- env.info("DIST ".._dist) - if _dist <= ctld.minimumDeployDistance then - -- env.info("TOO CLOSE ".._dist) - _farEnough = false - end - end - end - - return _farEnough -end - -function ctld.refreshSmoke() - - if ctld.disableAllSmoke == true then - return - end - - for _, _zoneGroup in pairs({ ctld.pickupZones, ctld.dropOffZones }) do - - for _, _zoneDetails in pairs(_zoneGroup) do - - local _triggerZone = trigger.misc.getZone(_zoneDetails[1]) - - if _triggerZone == nil then - local _ship = ctld.getTransportUnit(_triggerZone) - - if _ship then - local _point = _ship:getPoint() - _triggerZone = {} - _triggerZone.point = _point - end - - end - - - --only trigger if smoke is on AND zone is active - if _triggerZone ~= nil and _zoneDetails[2] >= 0 and _zoneDetails[4] == 1 then - - -- Trigger smoke markers - - local _pos2 = { x = _triggerZone.point.x, y = _triggerZone.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - trigger.action.smoke(_pos3, _zoneDetails[2]) - end - end - end - - --waypoint zones - for _, _zoneDetails in pairs(ctld.wpZones) do - - local _triggerZone = trigger.misc.getZone(_zoneDetails[1]) - - --only trigger if smoke is on AND zone is active - if _triggerZone ~= nil and _zoneDetails[2] >= 0 and _zoneDetails[3] == 1 then - - -- Trigger smoke markers - - local _pos2 = { x = _triggerZone.point.x, y = _triggerZone.point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _pos2.x, y = _alt, z = _pos2.y } - - trigger.action.smoke(_pos3, _zoneDetails[2]) - end - end - - - --refresh in 5 minutes - timer.scheduleFunction(ctld.refreshSmoke, nil, timer.getTime() + 300) -end - -function ctld.dropSmoke(_args) - - local _heli = ctld.getTransportUnit(_args[1]) - - if _heli ~= nil then - - local _colour = "" - - if _args[2] == trigger.smokeColor.Red then - - _colour = "RED" - elseif _args[2] == trigger.smokeColor.Blue then - - _colour = "BLUE" - elseif _args[2] == trigger.smokeColor.Green then - - _colour = "GREEN" - elseif _args[2] == trigger.smokeColor.Orange then - - _colour = "ORANGE" - end - - local _point = _heli:getPoint() - - local _pos2 = { x = _point.x, y = _point.z } - local _alt = land.getHeight(_pos2) - local _pos3 = { x = _point.x, y = _alt, z = _point.z } - - trigger.action.smoke(_pos3, _args[2]) - - trigger.action.outTextForCoalition(_heli:getCoalition(), ctld.getPlayerNameOrType(_heli) .. " dropped " .. _colour .. " smoke ", 10) - end -end - -function ctld.unitCanCarryVehicles(_unit) - - local _type = string.lower(_unit:getTypeName()) - - for _, _name in ipairs(ctld.vehicleTransportEnabled) do - local _nameLower = string.lower(_name) - if string.match(_type, _nameLower) then - return true - end - end - - return false -end - -function ctld.isJTACUnitType(_type) - - _type = string.lower(_type) - - for _, _name in ipairs(ctld.jtacUnitTypes) do - local _nameLower = string.lower(_name) - if string.match(_type, _nameLower) then - return true - end - end - - return false -end - -function ctld.updateZoneCounter(_index, _diff) - - if ctld.pickupZones[_index] ~= nil then - - ctld.pickupZones[_index][3] = ctld.pickupZones[_index][3] + _diff - - if ctld.pickupZones[_index][3] < 0 then - ctld.pickupZones[_index][3] = 0 - end - - if ctld.pickupZones[_index][6] ~= nil then - trigger.action.setUserFlag(ctld.pickupZones[_index][6], ctld.pickupZones[_index][3]) - end - -- env.info(ctld.pickupZones[_index][1].." = " ..ctld.pickupZones[_index][3]) - end -end - -function ctld.processCallback(_callbackArgs) - - for _, _callback in pairs(ctld.callbacks) do - - local _status, _result = pcall(function() - - _callback(_callbackArgs) - - end) - - if (not _status) then - env.error(string.format("CTLD Callback Error: %s", _result)) - end - end -end - - --- checks the status of all AI troop carriers and auto loads and unloads troops --- as long as the troops are on the ground -function ctld.checkAIStatus() - - timer.scheduleFunction(ctld.checkAIStatus, nil, timer.getTime() + 2) - - - for _, _unitName in pairs(ctld.transportPilotNames) do - local status, error = pcall(function() - - local _unit = ctld.getTransportUnit(_unitName) - - -- no player name means AI! - if _unit ~= nil and _unit:getPlayerName() == nil then - local _zone = ctld.inPickupZone(_unit) - -- env.error("Checking.. ".._unit:getName()) - if _zone.inZone == true and not ctld.troopsOnboard(_unit, true) then - -- env.error("in zone, loading.. ".._unit:getName()) - - if ctld.allowRandomAiTeamPickups == true then - -- Random troop pickup implementation - local _team = nil - if _unit:getCoalition() == 1 then - _team = math.floor((math.random(#ctld.redTeams * 100) / 100) + 1) - ctld.loadTroopsFromZone({ _unitName, true,ctld.loadableGroups[ctld.redTeams[_team]],true }) - else - _team = math.floor((math.random(#ctld.blueTeams * 100) / 100) + 1) - ctld.loadTroopsFromZone({ _unitName, true,ctld.loadableGroups[ctld.blueTeams[_team]],true }) - end - else - ctld.loadTroopsFromZone({ _unitName, true,"",true }) - end - - elseif ctld.inDropoffZone(_unit) and ctld.troopsOnboard(_unit, true) then - -- env.error("in dropoff zone, unloading.. ".._unit:getName()) - ctld.unloadTroops( { _unitName, true }) - end - - if ctld.unitCanCarryVehicles(_unit) then - - if _zone.inZone == true and not ctld.troopsOnboard(_unit, false) then - - ctld.loadTroopsFromZone({ _unitName, false,"",true }) - - elseif ctld.inDropoffZone(_unit) and ctld.troopsOnboard(_unit, false) then - - ctld.unloadTroops( { _unitName, false }) - end - end - end - end) - - if (not status) then - env.error(string.format("Error with ai status: %s", error), false) - end - end - - -end - -function ctld.getTransportLimit(_unitType) - - if ctld.unitLoadLimits[_unitType] then - - return ctld.unitLoadLimits[_unitType] - end - - return ctld.numberOfTroops - -end - -function ctld.getUnitActions(_unitType) - - if ctld.unitActions[_unitType] then - return ctld.unitActions[_unitType] - end - - return {crates=true,troops=true} - -end - --- Adds menuitem to all heli units that are active -function ctld.addF10MenuOptions() - -- Loop through all Heli units - - timer.scheduleFunction(ctld.addF10MenuOptions, nil, timer.getTime() + 10) - - for _, _unitName in pairs(ctld.transportPilotNames) do - - local status, error = pcall(function() - - local _unit = ctld.getTransportUnit(_unitName) - - if _unit ~= nil then - - local _groupId = ctld.getGroupId(_unit) - - if _groupId then - - if ctld.addedTo[tostring(_groupId)] == nil then - - local _rootPath = missionCommands.addSubMenuForGroup(_groupId, "CTLD") - - local _unitActions = ctld.getUnitActions(_unit:getTypeName()) - ctld.logTrace(string.format("_unitActions=%s", ctld.p(_unitActions))) - - missionCommands.addCommandForGroup(_groupId, "Check Cargo", _rootPath, ctld.checkTroopStatus, { _unitName }) - - if _unitActions.troops then - - local _troopCommandsPath = missionCommands.addSubMenuForGroup(_groupId, "Troop Transport", _rootPath) - - missionCommands.addCommandForGroup(_groupId, "Unload / Extract Troops", _troopCommandsPath, ctld.unloadExtractTroops, { _unitName }) - - - -- local _loadPath = missionCommands.addSubMenuForGroup(_groupId, "Load From Zone", _troopCommandsPath) - local _transportLimit = ctld.getTransportLimit(_unit:getTypeName()) - ctld.logTrace(string.format("_transportLimit=%s", ctld.p(_transportLimit))) - for _,_loadGroup in pairs(ctld.loadableGroups) do - ctld.logTrace(string.format("_loadGroup=%s", ctld.p(_loadGroup))) - if not _loadGroup.side or _loadGroup.side == _unit:getCoalition() then - - -- check size & unit - if _transportLimit >= _loadGroup.total then - missionCommands.addCommandForGroup(_groupId, "Load ".._loadGroup.name, _troopCommandsPath, ctld.loadTroopsFromZone, { _unitName, true,_loadGroup,false }) - end - end - end - - if ctld.unitCanCarryVehicles(_unit) then - - local _vehicleCommandsPath = missionCommands.addSubMenuForGroup(_groupId, "Vehicle / FOB Transport", _rootPath) - - missionCommands.addCommandForGroup(_groupId, "Unload Vehicles", _vehicleCommandsPath, ctld.unloadTroops, { _unitName, false }) - missionCommands.addCommandForGroup(_groupId, "Load / Extract Vehicles", _vehicleCommandsPath, ctld.loadTroopsFromZone, { _unitName, false,"",true }) - - if ctld.enabledFOBBuilding and ctld.staticBugWorkaround == false then - - missionCommands.addCommandForGroup(_groupId, "Load / Unload FOB Crate", _vehicleCommandsPath, ctld.loadUnloadFOBCrate, { _unitName, false }) - end - missionCommands.addCommandForGroup(_groupId, "Check Cargo", _vehicleCommandsPath, ctld.checkTroopStatus, { _unitName }) - end - - end - - - if ctld.enableCrates and _unitActions.crates then - - if ctld.unitCanCarryVehicles(_unit) == false then - - -- local _cratePath = missionCommands.addSubMenuForGroup(_groupId, "Spawn Crate", _rootPath) - -- add menu for spawning crates - for _subMenuName, _crates in pairs(ctld.spawnableCrates) do - - local _cratePath = missionCommands.addSubMenuForGroup(_groupId, _subMenuName, _rootPath) - for _, _crate in pairs(_crates) do - - if ctld.isJTACUnitType(_crate.unit) == false - or (ctld.isJTACUnitType(_crate.unit) == true and ctld.JTAC_dropEnabled) then - if _crate.side == nil or (_crate.side == _unit:getCoalition()) then - - local _crateRadioMsg = _crate.desc - - --add in the number of crates required to build something - if _crate.cratesRequired ~= nil and _crate.cratesRequired > 1 then - _crateRadioMsg = _crateRadioMsg.." (".._crate.cratesRequired..")" - end - - missionCommands.addCommandForGroup(_groupId,_crateRadioMsg, _cratePath, ctld.spawnCrate, { _unitName, _crate.weight }) - end - end - end - end - end - end - - if (ctld.enabledFOBBuilding or ctld.enableCrates) and _unitActions.crates then - - local _crateCommands = missionCommands.addSubMenuForGroup(_groupId, "CTLD Commands", _rootPath) - if ctld.hoverPickup == false then - if ctld.slingLoad == false then - missionCommands.addCommandForGroup(_groupId, "Load Nearby Crate", _crateCommands, ctld.loadNearbyCrate, _unitName ) - end - end - - missionCommands.addCommandForGroup(_groupId, "Unpack Any Crate", _crateCommands, ctld.unpackCrates, { _unitName }) - - if ctld.slingLoad == false then - missionCommands.addCommandForGroup(_groupId, "Drop Crate", _crateCommands, ctld.dropSlingCrate, { _unitName }) - end - - missionCommands.addCommandForGroup(_groupId, "List Nearby Crates", _crateCommands, ctld.listNearbyCrates, { _unitName }) - - if ctld.enabledFOBBuilding then - missionCommands.addCommandForGroup(_groupId, "List FOBs", _crateCommands, ctld.listFOBS, { _unitName }) - end - end - - - if ctld.enableSmokeDrop then - local _smokeMenu = missionCommands.addSubMenuForGroup(_groupId, "Smoke Markers", _rootPath) - missionCommands.addCommandForGroup(_groupId, "Drop Red Smoke", _smokeMenu, ctld.dropSmoke, { _unitName, trigger.smokeColor.Red }) - missionCommands.addCommandForGroup(_groupId, "Drop Blue Smoke", _smokeMenu, ctld.dropSmoke, { _unitName, trigger.smokeColor.Blue }) - missionCommands.addCommandForGroup(_groupId, "Drop Orange Smoke", _smokeMenu, ctld.dropSmoke, { _unitName, trigger.smokeColor.Orange }) - missionCommands.addCommandForGroup(_groupId, "Drop Green Smoke", _smokeMenu, ctld.dropSmoke, { _unitName, trigger.smokeColor.Green }) - end - - if ctld.enabledRadioBeaconDrop then - local _radioCommands = missionCommands.addSubMenuForGroup(_groupId, "Radio Beacons", _rootPath) - missionCommands.addCommandForGroup(_groupId, "List Beacons", _radioCommands, ctld.listRadioBeacons, { _unitName }) - missionCommands.addCommandForGroup(_groupId, "Drop Beacon", _radioCommands, ctld.dropRadioBeacon, { _unitName }) - missionCommands.addCommandForGroup(_groupId, "Remove Closet Beacon", _radioCommands, ctld.removeRadioBeacon, { _unitName }) - elseif ctld.deployedRadioBeacons ~= {} then - local _radioCommands = missionCommands.addSubMenuForGroup(_groupId, "Radio Beacons", _rootPath) - missionCommands.addCommandForGroup(_groupId, "List Beacons", _radioCommands, ctld.listRadioBeacons, { _unitName }) - end - - ctld.addedTo[tostring(_groupId)] = true - end - end - else - -- env.info(string.format("unit nil %s",_unitName)) - end - end) - - if (not status) then - env.error(string.format("Error adding f10 to transport: %s", error), false) - end - end - - local status, error = pcall(function() - - -- now do any player controlled aircraft that ARENT transport units - if ctld.enabledRadioBeaconDrop then - -- get all BLUE players - ctld.addRadioListCommand(2) - - -- get all RED players - ctld.addRadioListCommand(1) - end - - - if ctld.JTAC_jtacStatusF10 then - -- get all BLUE players - ctld.addJTACRadioCommand(2) - - -- get all RED players - ctld.addJTACRadioCommand(1) - end - - end) - - if (not status) then - env.error(string.format("Error adding f10 to other players: %s", error), false) - end - - -end - ---add to all players that arent transport -function ctld.addRadioListCommand(_side) - - local _players = coalition.getPlayers(_side) - - if _players ~= nil then - - for _, _playerUnit in pairs(_players) do - - local _groupId = ctld.getGroupId(_playerUnit) - - if _groupId then - - if ctld.addedTo[tostring(_groupId)] == nil then - missionCommands.addCommandForGroup(_groupId, "List Radio Beacons", nil, ctld.listRadioBeacons, { _playerUnit:getName() }) - ctld.addedTo[tostring(_groupId)] = true - end - end - end - end -end - -function ctld.addJTACRadioCommand(_side) - - local _players = coalition.getPlayers(_side) - - if _players ~= nil then - - for _, _playerUnit in pairs(_players) do - - local _groupId = ctld.getGroupId(_playerUnit) - - if _groupId then - -- env.info("adding command for "..index) - if ctld.jtacRadioAdded[tostring(_groupId)] == nil then - -- env.info("about command for "..index) - missionCommands.addCommandForGroup(_groupId, "JTAC Status", nil, ctld.getJTACStatus, { _playerUnit:getName() }) - ctld.jtacRadioAdded[tostring(_groupId)] = true - -- env.info("Added command for " .. index) - end - end - - - end - end -end - -function ctld.getGroupId(_unit) - - local _unitDB = mist.DBs.unitsById[tonumber(_unit:getID())] - if _unitDB ~= nil and _unitDB.groupId then - return _unitDB.groupId - end - - return nil -end - ---get distance in meters assuming a Flat world -function ctld.getDistance(_point1, _point2) - - local xUnit = _point1.x - local yUnit = _point1.z - local xZone = _point2.x - local yZone = _point2.z - - local xDiff = xUnit - xZone - local yDiff = yUnit - yZone - - return math.sqrt(xDiff * xDiff + yDiff * yDiff) -end - - ------------- JTAC ----------- - - -ctld.jtacLaserPoints = {} -ctld.jtacIRPoints = {} -ctld.jtacSmokeMarks = {} -ctld.jtacUnits = {} -- list of JTAC units for f10 command -ctld.jtacStop = {} -- jtacs to tell to stop lasing -ctld.jtacCurrentTargets = {} -ctld.jtacRadioAdded = {} --keeps track of who's had the radio command added -ctld.jtacGeneratedLaserCodes = {} -- keeps track of generated codes, cycles when they run out -ctld.jtacLaserPointCodes = {} -ctld.jtacRadioData = {} - -function ctld.JTACAutoLase(_jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio) - ctld.logDebug(string.format("ctld.JTACAutoLase(_jtacGroupName=%s, _laserCode=%s", ctld.p(_jtacGroupName), ctld.p(_laserCode))) - - local _radio = _radio - if not _radio then - _radio = {} - if _laserCode then - local _laserCode = tonumber(_laserCode) - if _laserCode and _laserCode >= 1111 and _laserCode <= 1688 then - local _laserB = math.floor((_laserCode - 1000)/100) - local _laserCD = _laserCode - 1000 - _laserB*100 - local _frequency = tostring(30+_laserB+_laserCD*0.05) - ctld.logTrace(string.format("_laserB=%s", ctld.p(_laserB))) - ctld.logTrace(string.format("_laserCD=%s", ctld.p(_laserCD))) - ctld.logTrace(string.format("_frequency=%s", ctld.p(_frequency))) - _radio.freq = _frequency - _radio.mod = "fm" - end - end - end - - if _radio and not _radio.name then - _radio.name = _jtacGroupName - end - - if ctld.jtacStop[_jtacGroupName] == true then - ctld.jtacStop[_jtacGroupName] = nil -- allow it to be started again - ctld.cleanupJTAC(_jtacGroupName) - return - end - - if _lock == nil then - - _lock = ctld.JTAC_lock - end - - - ctld.jtacLaserPointCodes[_jtacGroupName] = _laserCode - ctld.jtacRadioData[_jtacGroupName] = _radio - - local _jtacGroup = ctld.getGroup(_jtacGroupName) - local _jtacUnit - - if _jtacGroup == nil or #_jtacGroup == 0 then - - --check not in a heli - if ctld.inTransitTroops then - for _, _onboard in pairs(ctld.inTransitTroops) do - if _onboard ~= nil then - if _onboard.troops ~= nil and _onboard.troops.groupName ~= nil and _onboard.troops.groupName == _jtacGroupName then - - --jtac soldier being transported by heli - ctld.cleanupJTAC(_jtacGroupName) - - env.info(_jtacGroupName .. ' in Transport - Waiting 10 seconds') - timer.scheduleFunction(ctld.timerJTACAutoLase, { _jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio }, timer.getTime() + 10) - return - end - - if _onboard.vehicles ~= nil and _onboard.vehicles.groupName ~= nil and _onboard.vehicles.groupName == _jtacGroupName then - --jtac vehicle being transported by heli - ctld.cleanupJTAC(_jtacGroupName) - - env.info(_jtacGroupName .. ' in Transport - Waiting 10 seconds') - timer.scheduleFunction(ctld.timerJTACAutoLase, { _jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio }, timer.getTime() + 10) - return - end - end - end - end - - - if ctld.jtacUnits[_jtacGroupName] ~= nil then - ctld.notifyCoalition("JTAC Group " .. _jtacGroupName .. " KIA!", 10, ctld.jtacUnits[_jtacGroupName].side, _radio) - end - - --remove from list - ctld.jtacUnits[_jtacGroupName] = nil - - ctld.cleanupJTAC(_jtacGroupName) - - return - else - - _jtacUnit = _jtacGroup[1] - --add to list - ctld.jtacUnits[_jtacGroupName] = { name = _jtacUnit:getName(), side = _jtacUnit:getCoalition(), radio = _radio } - - -- work out smoke colour - if _colour == nil then - - if _jtacUnit:getCoalition() == 1 then - _colour = ctld.JTAC_smokeColour_RED - else - _colour = ctld.JTAC_smokeColour_BLUE - end - end - - - if _smoke == nil then - - if _jtacUnit:getCoalition() == 1 then - _smoke = ctld.JTAC_smokeOn_RED - else - _smoke = ctld.JTAC_smokeOn_BLUE - end - end - end - - - -- search for current unit - - if _jtacUnit:isActive() == false then - - ctld.cleanupJTAC(_jtacGroupName) - - env.info(_jtacGroupName .. ' Not Active - Waiting 30 seconds') - timer.scheduleFunction(ctld.timerJTACAutoLase, { _jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio }, timer.getTime() + 30) - - return - end - - local _enemyUnit = ctld.getCurrentUnit(_jtacUnit, _jtacGroupName) - local targetDestroyed = false - local targetLost = false - - if _enemyUnit == nil and ctld.jtacCurrentTargets[_jtacGroupName] ~= nil then - - local _tempUnitInfo = ctld.jtacCurrentTargets[_jtacGroupName] - - -- env.info("TEMP UNIT INFO: " .. tempUnitInfo.name .. " " .. tempUnitInfo.unitType) - - local _tempUnit = Unit.getByName(_tempUnitInfo.name) - - if _tempUnit ~= nil and _tempUnit:getLife() > 0 and _tempUnit:isActive() == true then - targetLost = true - else - targetDestroyed = true - end - - --remove from smoke list - ctld.jtacSmokeMarks[_tempUnitInfo.name] = nil - - -- JTAC Unit: resume his route ------------ - trigger.action.groupContinueMoving(Group.getByName(_jtacGroupName)) - - -- remove from target list - ctld.jtacCurrentTargets[_jtacGroupName] = nil - - --stop lasing - ctld.cancelLase(_jtacGroupName) - end - - - if _enemyUnit == nil then - _enemyUnit = ctld.findNearestVisibleEnemy(_jtacUnit, _lock) - - if _enemyUnit ~= nil then - - -- store current target for easy lookup - ctld.jtacCurrentTargets[_jtacGroupName] = { name = _enemyUnit:getName(), unitType = _enemyUnit:getTypeName(), unitId = _enemyUnit:getID() } - local action = ", lasing new target, " - if targetLost then - action = ", target lost " .. action - targetLost = false - elseif targetDestroyed then - action = ", target destroyed " .. action - targetDestroyed = false - end - - local message = _jtacGroupName .. action .. _enemyUnit:getTypeName() - local fullMessage = message .. '. CODE: ' .. _laserCode .. ". POSITION: " .. ctld.getPositionString(_enemyUnit) - ctld.notifyCoalition(fullMessage, 10, _jtacUnit:getCoalition(), _radio, message) - - -- JTAC Unit stop his route ----------------- - trigger.action.groupStopMoving(Group.getByName(_jtacGroupName)) -- stop JTAC - - -- create smoke - if _smoke == true then - - --create first smoke - ctld.createSmokeMarker(_enemyUnit, _colour) - end - end - end - - if _enemyUnit ~= nil then - - ctld.laseUnit(_enemyUnit, _jtacUnit, _jtacGroupName, _laserCode) - - -- env.info('Timer timerSparkleLase '..jtacGroupName.." "..laserCode.." "..enemyUnit:getName()) - timer.scheduleFunction(ctld.timerJTACAutoLase, { _jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio }, timer.getTime() + 15) - - - if _smoke == true then - local _nextSmokeTime = ctld.jtacSmokeMarks[_enemyUnit:getName()] - - --recreate smoke marker after 5 mins - if _nextSmokeTime ~= nil and _nextSmokeTime < timer.getTime() then - - ctld.createSmokeMarker(_enemyUnit, _colour) - end - end - - else - -- env.info('LASE: No Enemies Nearby') - - -- stop lazing the old spot - ctld.cancelLase(_jtacGroupName) - -- env.info('Timer Slow timerSparkleLase '..jtacGroupName.." "..laserCode.." "..enemyUnit:getName()) - - timer.scheduleFunction(ctld.timerJTACAutoLase, { _jtacGroupName, _laserCode, _smoke, _lock, _colour, _radio }, timer.getTime() + 5) - end - - if targetLost then - ctld.notifyCoalition(_jtacGroupName .. ", target lost.", 10, _jtacUnit:getCoalition(), _radio) - elseif targetDestroyed then - ctld.notifyCoalition(_jtacGroupName .. ", target destroyed.", 10, _jtacUnit:getCoalition(), _radio) - end -end - -function ctld.JTACAutoLaseStop(_jtacGroupName) - ctld.jtacStop[_jtacGroupName] = true -end - --- used by the timer function -function ctld.timerJTACAutoLase(_args) - - ctld.JTACAutoLase(_args[1], _args[2], _args[3], _args[4], _args[5], _args[6]) -end - -function ctld.cleanupJTAC(_jtacGroupName) - -- clear laser - just in case - ctld.cancelLase(_jtacGroupName) - - -- Cleanup - ctld.jtacUnits[_jtacGroupName] = nil - - ctld.jtacCurrentTargets[_jtacGroupName] = nil - - ctld.jtacRadioData[_jtacGroupName] = nil -end - - ---- send a message to the coalition ---- if _radio is set, the message will be read out loud via SRS -function ctld.notifyCoalition(_message, _displayFor, _side, _radio, _shortMessage) - ctld.logDebug(string.format("ctld.notifyCoalition(_message=%s)", ctld.p(_message))) - ctld.logTrace(string.format("_radio=%s", ctld.p(_radio))) - - local _shortMessage = _shortMessage - if _shortMessage == nil then - _shortMessage = _message - end - - if STTS and STTS.TextToSpeech and _radio and _radio.freq then - local _freq = _radio.freq - local _modulation = _radio.mod or "FM" - local _volume = _radio.volume or "1.0" - local _name = _radio.name or "JTAC" - local _gender = _radio.gender or "male" - local _culture = _radio.culture or "en-US" - local _voice = _radio.voice - local _googleTTS = _radio.googleTTS or false - ctld.logTrace(string.format("calling STTS.TextToSpeech(%s)", ctld.p(_shortMessage))) - ctld.logTrace(string.format("_freq=%s", ctld.p(_freq))) - ctld.logTrace(string.format("_modulation=%s", ctld.p(_modulation))) - ctld.logTrace(string.format("_volume=%s", ctld.p(_volume))) - ctld.logTrace(string.format("_name=%s", ctld.p(_name))) - ctld.logTrace(string.format("_gender=%s", ctld.p(_gender))) - ctld.logTrace(string.format("_culture=%s", ctld.p(_culture))) - ctld.logTrace(string.format("_voice=%s", ctld.p(_voice))) - ctld.logTrace(string.format("_googleTTS=%s", ctld.p(_googleTTS))) - STTS.TextToSpeech(_shortMessage, _freq, _modulation, _volume, _name, _side, nil, 1, _gender, _culture, _voice, _googleTTS) - end - - trigger.action.outTextForCoalition(_side, _message, _displayFor) - trigger.action.outSoundForCoalition(_side, "radiobeep.ogg") -end - -function ctld.createSmokeMarker(_enemyUnit, _colour) - - --recreate in 5 mins - ctld.jtacSmokeMarks[_enemyUnit:getName()] = timer.getTime() + 300.0 - - -- move smoke 2 meters above target for ease - local _enemyPoint = _enemyUnit:getPoint() - trigger.action.smoke({ x = _enemyPoint.x, y = _enemyPoint.y + 2.0, z = _enemyPoint.z }, _colour) -end - -function ctld.cancelLase(_jtacGroupName) - - --local index = "JTAC_"..jtacUnit:getID() - - local _tempLase = ctld.jtacLaserPoints[_jtacGroupName] - - if _tempLase ~= nil then - Spot.destroy(_tempLase) - ctld.jtacLaserPoints[_jtacGroupName] = nil - - -- env.info('Destroy laze '..index) - - _tempLase = nil - end - - local _tempIR = ctld.jtacIRPoints[_jtacGroupName] - - if _tempIR ~= nil then - Spot.destroy(_tempIR) - ctld.jtacIRPoints[_jtacGroupName] = nil - - -- env.info('Destroy laze '..index) - - _tempIR = nil - end -end - -function ctld.laseUnit(_enemyUnit, _jtacUnit, _jtacGroupName, _laserCode) - - --cancelLase(jtacGroupName) - - local _spots = {} - - local _enemyVector = _enemyUnit:getPoint() - local _enemyVectorUpdated = { x = _enemyVector.x, y = _enemyVector.y + 2.0, z = _enemyVector.z } - - local _oldLase = ctld.jtacLaserPoints[_jtacGroupName] - local _oldIR = ctld.jtacIRPoints[_jtacGroupName] - - if _oldLase == nil or _oldIR == nil then - - -- create lase - - local _status, _result = pcall(function() - _spots['irPoint'] = Spot.createInfraRed(_jtacUnit, { x = 0, y = 2.0, z = 0 }, _enemyVectorUpdated) - _spots['laserPoint'] = Spot.createLaser(_jtacUnit, { x = 0, y = 2.0, z = 0 }, _enemyVectorUpdated, _laserCode) - return _spots - end) - - if not _status then - env.error('ERROR: ' .. _result, false) - else - if _result.irPoint then - - -- env.info(jtacUnit:getName() .. ' placed IR Pointer on '..enemyUnit:getName()) - - ctld.jtacIRPoints[_jtacGroupName] = _result.irPoint --store so we can remove after - end - if _result.laserPoint then - - -- env.info(jtacUnit:getName() .. ' is Lasing '..enemyUnit:getName()..'. CODE:'..laserCode) - - ctld.jtacLaserPoints[_jtacGroupName] = _result.laserPoint - end - end - - else - - -- update lase - - if _oldLase ~= nil then - _oldLase:setPoint(_enemyVectorUpdated) - end - - if _oldIR ~= nil then - _oldIR:setPoint(_enemyVectorUpdated) - end - end -end - --- get currently selected unit and check they're still in range -function ctld.getCurrentUnit(_jtacUnit, _jtacGroupName) - - - local _unit = nil - - if ctld.jtacCurrentTargets[_jtacGroupName] ~= nil then - _unit = Unit.getByName(ctld.jtacCurrentTargets[_jtacGroupName].name) - end - - local _tempPoint = nil - local _tempDist = nil - local _tempPosition = nil - - local _jtacPosition = _jtacUnit:getPosition() - local _jtacPoint = _jtacUnit:getPoint() - - if _unit ~= nil and _unit:getLife() > 0 and _unit:isActive() == true then - - -- calc distance - _tempPoint = _unit:getPoint() - -- tempPosition = unit:getPosition() - - _tempDist = ctld.getDistance(_unit:getPoint(), _jtacUnit:getPoint()) - if _tempDist < ctld.JTAC_maxDistance then - -- calc visible - - -- check slightly above the target as rounding errors can cause issues, plus the unit has some height anyways - local _offsetEnemyPos = { x = _tempPoint.x, y = _tempPoint.y + 2.0, z = _tempPoint.z } - local _offsetJTACPos = { x = _jtacPoint.x, y = _jtacPoint.y + 2.0, z = _jtacPoint.z } - - if land.isVisible(_offsetEnemyPos, _offsetJTACPos) then - return _unit - end - end - end - return nil -end - - --- Find nearest enemy to JTAC that isn't blocked by terrain -function ctld.findNearestVisibleEnemy(_jtacUnit, _targetType,_distance) - - --local startTime = os.clock() - - local _maxDistance = _distance or ctld.JTAC_maxDistance - - local _nearestDistance = _maxDistance - - local _jtacPoint = _jtacUnit:getPoint() - local _coa = _jtacUnit:getCoalition() - - local _offsetJTACPos = { x = _jtacPoint.x, y = _jtacPoint.y + 2.0, z = _jtacPoint.z } - - local _volume = { - id = world.VolumeType.SPHERE, - params = { - point = _offsetJTACPos, - radius = _maxDistance - } - } - - local _unitList = {} - - - local _search = function(_unit, _coa) - pcall(function() - - if _unit ~= nil - and _unit:getLife() > 0 - and _unit:isActive() - and _unit:getCoalition() ~= _coa - and not _unit:inAir() - and not ctld.alreadyTarget(_jtacUnit,_unit) then - - local _tempPoint = _unit:getPoint() - local _offsetEnemyPos = { x = _tempPoint.x, y = _tempPoint.y + 2.0, z = _tempPoint.z } - - if land.isVisible(_offsetJTACPos,_offsetEnemyPos ) then - - local _dist = ctld.getDistance(_offsetJTACPos, _offsetEnemyPos) - - if _dist < _maxDistance then - table.insert(_unitList,{unit=_unit, dist=_dist}) - - end - end - end - end) - - return true - end - - world.searchObjects(Object.Category.UNIT, _volume, _search, _coa) - - --log.info(string.format("JTAC Search elapsed time: %.4f\n", os.clock() - startTime)) - - -- generate list order by distance & visible - - -- first check - -- hpriority - -- priority - -- vehicle - -- unit - - local _sort = function( a,b ) return a.dist < b.dist end - table.sort(_unitList,_sort) - -- sort list - - -- check for hpriority - for _, _enemyUnit in ipairs(_unitList) do - local _enemyName = _enemyUnit.unit:getName() - - if string.match(_enemyName, "hpriority") then - return _enemyUnit.unit - end - end - - for _, _enemyUnit in ipairs(_unitList) do - local _enemyName = _enemyUnit.unit:getName() - - if string.match(_enemyName, "priority") then - return _enemyUnit.unit - end - end - - local result = nil - for _, _enemyUnit in ipairs(_unitList) do - local _enemyName = _enemyUnit.unit:getName() - --log.info(string.format("CTLD - checking _enemyName=%s", _enemyName)) - - -- check for air defenses - --log.info(string.format("CTLD - _enemyUnit.unit:getDesc()[attributes]=%s", ctld.p(_enemyUnit.unit:getDesc()["attributes"]))) - local airdefense = (_enemyUnit.unit:getDesc()["attributes"]["Air Defence"] ~= nil) - --log.info(string.format("CTLD - airdefense=%s", tostring(airdefense))) - - if (_targetType == "vehicle" and ctld.isVehicle(_enemyUnit.unit)) or _targetType == "all" then - if airdefense then - return _enemyUnit.unit - else - result = _enemyUnit.unit - end - - elseif (_targetType == "troop" and ctld.isInfantry(_enemyUnit.unit)) or _targetType == "all" then - if airdefense then - return _enemyUnit.unit - else - result = _enemyUnit.unit - end - end - end - - return result - -end - - -function ctld.listNearbyEnemies(_jtacUnit) - - local _maxDistance = ctld.JTAC_maxDistance - - local _jtacPoint = _jtacUnit:getPoint() - local _coa = _jtacUnit:getCoalition() - - local _offsetJTACPos = { x = _jtacPoint.x, y = _jtacPoint.y + 2.0, z = _jtacPoint.z } - - local _volume = { - id = world.VolumeType.SPHERE, - params = { - point = _offsetJTACPos, - radius = _maxDistance - } - } - local _enemies = nil - - local _search = function(_unit, _coa) - pcall(function() - - if _unit ~= nil - and _unit:getLife() > 0 - and _unit:isActive() - and _unit:getCoalition() ~= _coa - and not _unit:inAir() then - - local _tempPoint = _unit:getPoint() - local _offsetEnemyPos = { x = _tempPoint.x, y = _tempPoint.y + 2.0, z = _tempPoint.z } - - if land.isVisible(_offsetJTACPos,_offsetEnemyPos ) then - - if not _enemies then - _enemies = {} - end - - _enemies[_unit:getTypeName()] = _unit:getTypeName() - - end - end - end) - - return true - end - - world.searchObjects(Object.Category.UNIT, _volume, _search, _coa) - - return _enemies -end - --- tests whether the unit is targeted by another JTAC -function ctld.alreadyTarget(_jtacUnit, _enemyUnit) - - for _, _jtacTarget in pairs(ctld.jtacCurrentTargets) do - - if _jtacTarget.unitId == _enemyUnit:getID() then - -- env.info("ALREADY TARGET") - return true - end - end - - return false -end - - --- Returns only alive units from group but the group / unit may not be active - -function ctld.getGroup(groupName) - - local _groupUnits = Group.getByName(groupName) - - local _filteredUnits = {} --contains alive units - local _x = 1 - - if _groupUnits ~= nil and _groupUnits:isExist() then - - _groupUnits = _groupUnits:getUnits() - - if _groupUnits ~= nil and #_groupUnits > 0 then - for _x = 1, #_groupUnits do - if _groupUnits[_x]:getLife() > 0 then -- removed and _groupUnits[_x]:isExist() as isExist doesnt work on single units! - table.insert(_filteredUnits, _groupUnits[_x]) - end - end - end - end - - return _filteredUnits -end - -function ctld.getAliveGroup(_groupName) - - local _group = Group.getByName(_groupName) - - if _group and _group:isExist() == true and #_group:getUnits() > 0 then - return _group - end - - return nil -end - --- gets the JTAC status and displays to coalition units -function ctld.getJTACStatus(_args) - - --returns the status of all JTAC units - - local _playerUnit = ctld.getTransportUnit(_args[1]) - - if _playerUnit == nil then - return - end - - local _side = _playerUnit:getCoalition() - - local _jtacGroupName = nil - local _jtacUnit = nil - - local _message = "JTAC STATUS: \n\n" - - for _jtacGroupName, _jtacDetails in pairs(ctld.jtacUnits) do - - --look up units - _jtacUnit = Unit.getByName(_jtacDetails.name) - - if _jtacUnit ~= nil and _jtacUnit:getLife() > 0 and _jtacUnit:isActive() == true and _jtacUnit:getCoalition() == _side then - - local _enemyUnit = ctld.getCurrentUnit(_jtacUnit, _jtacGroupName) - - local _laserCode = ctld.jtacLaserPointCodes[_jtacGroupName] - - local _start = _jtacGroupName - if (_jtacDetails.radio) then - _start = _start .. ", available on ".._jtacDetails.radio.freq.." ".._jtacDetails.radio.mod .."," - end - - if _laserCode == nil then - _laserCode = "UNKNOWN" - end - - if _enemyUnit ~= nil and _enemyUnit:getLife() > 0 and _enemyUnit:isActive() == true then - _message = _message .. "" .. _start .. " targeting " .. _enemyUnit:getTypeName() .. " CODE: " .. _laserCode .. ctld.getPositionString(_enemyUnit) .. "\n" - - local _list = ctld.listNearbyEnemies(_jtacUnit) - - if _list then - _message = _message.."Visual On: " - - for _,_type in pairs(_list) do - _message = _message.._type.." " - end - _message = _message.."\n" - end - - else - _message = _message .. "" .. _start .. " searching for targets" .. ctld.getPositionString(_jtacUnit) .. "\n" - end - end - end - - if _message == "JTAC STATUS: \n\n" then - _message = "No Active JTACs" - end - - - ctld.notifyCoalition(_message, 10, _side) -end - - - -function ctld.isInfantry(_unit) - - local _typeName = _unit:getTypeName() - - --type coerce tostring - _typeName = string.lower(_typeName .. "") - - local _soldierType = { "infantry", "paratrooper", "stinger", "manpad", "mortar" } - - for _key, _value in pairs(_soldierType) do - if string.match(_typeName, _value) then - return true - end - end - - return false -end - --- assume anything that isnt soldier is vehicle -function ctld.isVehicle(_unit) - - if ctld.isInfantry(_unit) then - return false - end - - return true -end - --- The entered value can range from 1111 - 1788, --- -- but the first digit of the series must be a 1 or 2 --- -- and the last three digits must be between 1 and 8. --- The range used to be bugged so its not 1 - 8 but 0 - 7. --- function below will use the range 1-7 just incase -function ctld.generateLaserCode() - - ctld.jtacGeneratedLaserCodes = {} - - -- generate list of laser codes - local _code = 1111 - - local _count = 1 - - while _code < 1777 and _count < 30 do - - while true do - - _code = _code + 1 - - if not ctld.containsDigit(_code, 8) - and not ctld.containsDigit(_code, 9) - and not ctld.containsDigit(_code, 0) then - - table.insert(ctld.jtacGeneratedLaserCodes, _code) - - --env.info(_code.." Code") - break - end - end - _count = _count + 1 - end -end - -function ctld.containsDigit(_number, _numberToFind) - - local _thisNumber = _number - local _thisDigit = 0 - - while _thisNumber ~= 0 do - - _thisDigit = _thisNumber % 10 - _thisNumber = math.floor(_thisNumber / 10) - - if _thisDigit == _numberToFind then - return true - end - end - - return false -end - --- 200 - 400 in 10KHz --- 400 - 850 in 10 KHz --- 850 - 1250 in 50 KHz -function ctld.generateVHFrequencies() - - --ignore list - --list of all frequencies in KHZ that could conflict with - -- 191 - 1290 KHz, beacon range - local _skipFrequencies = { - 745, --Astrahan - 381, - 384, - 300.50, - 312.5, - 1175, - 342, - 735, - 300.50, - 353.00, - 440, - 795, - 525, - 520, - 690, - 625, - 291.5, - 300.50, - 435, - 309.50, - 920, - 1065, - 274, - 312.50, - 580, - 602, - 297.50, - 750, - 485, - 950, - 214, - 1025, 730, 995, 455, 307, 670, 329, 395, 770, - 380, 705, 300.5, 507, 740, 1030, 515, - 330, 309.5, - 348, 462, 905, 352, 1210, 942, 435, - 324, - 320, 420, 311, 389, 396, 862, 680, 297.5, - 920, 662, - 866, 907, 309.5, 822, 515, 470, 342, 1182, 309.5, 720, 528, - 337, 312.5, 830, 740, 309.5, 641, 312, 722, 682, 1050, - 1116, 935, 1000, 430, 577, - 326 -- Nevada - } - - ctld.freeVHFFrequencies = {} - local _start = 200000 - - -- first range - while _start < 400000 do - - -- skip existing NDB frequencies - local _found = false - for _, value in pairs(_skipFrequencies) do - if value * 1000 == _start then - _found = true - break - end - end - - - if _found == false then - table.insert(ctld.freeVHFFrequencies, _start) - end - - _start = _start + 10000 - end - - _start = 400000 - -- second range - while _start < 850000 do - - -- skip existing NDB frequencies - local _found = false - for _, value in pairs(_skipFrequencies) do - if value * 1000 == _start then - _found = true - break - end - end - - if _found == false then - table.insert(ctld.freeVHFFrequencies, _start) - end - - - _start = _start + 10000 - end - - _start = 850000 - -- third range - while _start <= 1250000 do - - -- skip existing NDB frequencies - local _found = false - for _, value in pairs(_skipFrequencies) do - if value * 1000 == _start then - _found = true - break - end - end - - if _found == false then - table.insert(ctld.freeVHFFrequencies, _start) - end - - _start = _start + 50000 - end -end - --- 220 - 399 MHZ, increments of 0.5MHZ -function ctld.generateUHFrequencies() - - ctld.freeUHFFrequencies = {} - local _start = 220000000 - - while _start < 399000000 do - table.insert(ctld.freeUHFFrequencies, _start) - _start = _start + 500000 - end -end - - --- 220 - 399 MHZ, increments of 0.5MHZ --- -- first digit 3-7MHz --- -- second digit 0-5KHz --- -- third digit 0-9 --- -- fourth digit 0 or 5 --- -- times by 10000 --- -function ctld.generateFMFrequencies() - - ctld.freeFMFrequencies = {} - local _start = 220000000 - - while _start < 399000000 do - - _start = _start + 500000 - end - - for _first = 3, 7 do - for _second = 0, 5 do - for _third = 0, 9 do - local _frequency = ((100 * _first) + (10 * _second) + _third) * 100000 --extra 0 because we didnt bother with 4th digit - table.insert(ctld.freeFMFrequencies, _frequency) - end - end - end -end - -function ctld.getPositionString(_unit) - - if ctld.JTAC_location == false then - return "" - end - - local _lat, _lon = coord.LOtoLL(_unit:getPosition().p) - - local _latLngStr = mist.tostringLL(_lat, _lon, 3, ctld.location_DMS) - - local _mgrsString = mist.tostringMGRS(coord.LLtoMGRS(coord.LOtoLL(_unit:getPosition().p)), 5) - - return " @ " .. _latLngStr .. " - MGRS " .. _mgrsString -end - - --- ***************** SETUP SCRIPT **************** -function ctld.initialize(force) - ctld.logInfo(string.format("Initializing version %s", ctld.Version)) - ctld.logTrace(string.format("ctld.alreadyInitialized=%s", ctld.p(ctld.alreadyInitialized))) - ctld.logTrace(string.format("force=%s", ctld.p(force))) - - if ctld.alreadyInitialized and not force then - ctld.logInfo(string.format("Bypassing initialization because ctld.alreadyInitialized = true")) - return - end - - assert(mist ~= nil, "\n\n** HEY MISSION-DESIGNER! **\n\nMiST has not been loaded!\n\nMake sure MiST 3.6 or higher is running\n*before* running this script!\n") - - ctld.addedTo = {} - ctld.spawnedCratesRED = {} -- use to store crates that have been spawned - ctld.spawnedCratesBLUE = {} -- use to store crates that have been spawned - - ctld.droppedTroopsRED = {} -- stores dropped troop groups - ctld.droppedTroopsBLUE = {} -- stores dropped troop groups - - ctld.droppedVehiclesRED = {} -- stores vehicle groups for c-130 / hercules - ctld.droppedVehiclesBLUE = {} -- stores vehicle groups for c-130 / hercules - - ctld.inTransitTroops = {} - - ctld.inTransitFOBCrates = {} - - ctld.inTransitSlingLoadCrates = {} -- stores crates that are being transported by helicopters for alternative to real slingload - - ctld.droppedFOBCratesRED = {} - ctld.droppedFOBCratesBLUE = {} - - ctld.builtFOBS = {} -- stores fully built fobs - - ctld.completeAASystems = {} -- stores complete spawned groups from multiple crates - - ctld.fobBeacons = {} -- stores FOB radio beacon details, refreshed every 60 seconds - - ctld.deployedRadioBeacons = {} -- stores details of deployed radio beacons - - ctld.beaconCount = 1 - - ctld.usedUHFFrequencies = {} - ctld.usedVHFFrequencies = {} - ctld.usedFMFrequencies = {} - - ctld.freeUHFFrequencies = {} - ctld.freeVHFFrequencies = {} - ctld.freeFMFrequencies = {} - - --used to lookup what the crate will contain - ctld.crateLookupTable = {} - - ctld.extractZones = {} -- stored extract zones - - ctld.missionEditorCargoCrates = {} --crates added by mission editor for triggering cratesinzone - ctld.hoverStatus = {} -- tracks status of a helis hover above a crate - - ctld.callbacks = {} -- function callback - - - -- Remove intransit troops when heli / cargo plane dies - --ctld.eventHandler = {} - --function ctld.eventHandler:onEvent(_event) - -- - -- if _event == nil or _event.initiator == nil then - -- env.info("CTLD null event") - -- elseif _event.id == 9 then - -- -- Pilot dead - -- ctld.inTransitTroops[_event.initiator:getName()] = nil - -- - -- elseif world.event.S_EVENT_EJECTION == _event.id or _event.id == 8 then - -- -- env.info("Event unit - Pilot Ejected or Unit Dead") - -- ctld.inTransitTroops[_event.initiator:getName()] = nil - -- - -- -- env.info(_event.initiator:getName()) - -- end - -- - --end - - -- create crate lookup table - for _subMenuName, _crates in pairs(ctld.spawnableCrates) do - - for _, _crate in pairs(_crates) do - -- convert number to string otherwise we'll have a pointless giant - -- table. String means 'hashmap' so it will only contain the right number of elements - ctld.crateLookupTable[tostring(_crate.weight)] = _crate - end - end - - - --sort out pickup zones - for _, _zone in pairs(ctld.pickupZones) do - - local _zoneName = _zone[1] - local _zoneColor = _zone[2] - local _zoneActive = _zone[4] - - if _zoneColor == "green" then - _zone[2] = trigger.smokeColor.Green - elseif _zoneColor == "red" then - _zone[2] = trigger.smokeColor.Red - elseif _zoneColor == "white" then - _zone[2] = trigger.smokeColor.White - elseif _zoneColor == "orange" then - _zone[2] = trigger.smokeColor.Orange - elseif _zoneColor == "blue" then - _zone[2] = trigger.smokeColor.Blue - else - _zone[2] = -1 -- no smoke colour - end - - -- add in counter for troops or units - if _zone[3] == -1 then - _zone[3] = 10000; - end - - -- change active to 1 / 0 - if _zoneActive == "yes" then - _zone[4] = 1 - else - _zone[4] = 0 - end - end - - --sort out dropoff zones - for _, _zone in pairs(ctld.dropOffZones) do - - local _zoneColor = _zone[2] - - if _zoneColor == "green" then - _zone[2] = trigger.smokeColor.Green - elseif _zoneColor == "red" then - _zone[2] = trigger.smokeColor.Red - elseif _zoneColor == "white" then - _zone[2] = trigger.smokeColor.White - elseif _zoneColor == "orange" then - _zone[2] = trigger.smokeColor.Orange - elseif _zoneColor == "blue" then - _zone[2] = trigger.smokeColor.Blue - else - _zone[2] = -1 -- no smoke colour - end - - --mark as active for refresh smoke logic to work - _zone[4] = 1 - end - - --sort out waypoint zones - for _, _zone in pairs(ctld.wpZones) do - - local _zoneColor = _zone[2] - - if _zoneColor == "green" then - _zone[2] = trigger.smokeColor.Green - elseif _zoneColor == "red" then - _zone[2] = trigger.smokeColor.Red - elseif _zoneColor == "white" then - _zone[2] = trigger.smokeColor.White - elseif _zoneColor == "orange" then - _zone[2] = trigger.smokeColor.Orange - elseif _zoneColor == "blue" then - _zone[2] = trigger.smokeColor.Blue - else - _zone[2] = -1 -- no smoke colour - end - - --mark as active for refresh smoke logic to work - -- change active to 1 / 0 - if _zone[3] == "yes" then - _zone[3] = 1 - else - _zone[3] = 0 - end - end - - -- Sort out extractable groups - for _, _groupName in pairs(ctld.extractableGroups) do - - local _group = Group.getByName(_groupName) - - if _group ~= nil then - - if _group:getCoalition() == 1 then - table.insert(ctld.droppedTroopsRED, _group:getName()) - else - table.insert(ctld.droppedTroopsBLUE, _group:getName()) - end - end - end - - - -- Seperate troop teams into red and blue for random AI pickups - if ctld.allowRandomAiTeamPickups == true then - ctld.redTeams = {} - ctld.blueTeams = {} - for _,_loadGroup in pairs(ctld.loadableGroups) do - if not _loadGroup.side then - table.insert(ctld.redTeams, _) - table.insert(ctld.blueTeams, _) - elseif _loadGroup.side == 1 then - table.insert(ctld.redTeams, _) - elseif _loadGroup.side == 2 then - table.insert(ctld.blueTeams, _) - end - end - end - - -- add total count - - for _,_loadGroup in pairs(ctld.loadableGroups) do - - _loadGroup.total = 0 - if _loadGroup.aa then - _loadGroup.total = _loadGroup.aa + _loadGroup.total - end - - if _loadGroup.inf then - _loadGroup.total = _loadGroup.inf + _loadGroup.total - end - - - if _loadGroup.mg then - _loadGroup.total = _loadGroup.mg + _loadGroup.total - end - - if _loadGroup.at then - _loadGroup.total = _loadGroup.at + _loadGroup.total - end - - if _loadGroup.mortar then - _loadGroup.total = _loadGroup.mortar + _loadGroup.total - end - - end - - - -- Scheduled functions (run cyclically) -- but hold execution for a second so we can override parts - - timer.scheduleFunction(ctld.checkAIStatus, nil, timer.getTime() + 1) - timer.scheduleFunction(ctld.checkTransportStatus, nil, timer.getTime() + 5) - - timer.scheduleFunction(function() - - timer.scheduleFunction(ctld.refreshRadioBeacons, nil, timer.getTime() + 5) - timer.scheduleFunction(ctld.refreshSmoke, nil, timer.getTime() + 5) - timer.scheduleFunction(ctld.addF10MenuOptions, nil, timer.getTime() + 5) - - if ctld.enableCrates == true and ctld.slingLoad == false and ctld.hoverPickup == true then - timer.scheduleFunction(ctld.checkHoverStatus, nil, timer.getTime() + 1) - end - - end,nil, timer.getTime()+1 ) - - --event handler for deaths - --world.addEventHandler(ctld.eventHandler) - - --env.info("CTLD event handler added") - - env.info("Generating Laser Codes") - ctld.generateLaserCode() - env.info("Generated Laser Codes") - - - - env.info("Generating UHF Frequencies") - ctld.generateUHFrequencies() - env.info("Generated UHF Frequencies") - - env.info("Generating VHF Frequencies") - ctld.generateVHFrequencies() - env.info("Generated VHF Frequencies") - - - env.info("Generating FM Frequencies") - ctld.generateFMFrequencies() - env.info("Generated FM Frequencies") - - -- Search for crates - -- Crates are NOT returned by coalition.getStaticObjects() for some reason - -- Search for crates in the mission editor instead - env.info("Searching for Crates") - for _coalitionName, _coalitionData in pairs(env.mission.coalition) do - - if (_coalitionName == 'red' or _coalitionName == 'blue') - and type(_coalitionData) == 'table' then - if _coalitionData.country then --there is a country table - for _, _countryData in pairs(_coalitionData.country) do - - if type(_countryData) == 'table' then - for _objectTypeName, _objectTypeData in pairs(_countryData) do - if _objectTypeName == "static" then - - if ((type(_objectTypeData) == 'table') - and _objectTypeData.group - and (type(_objectTypeData.group) == 'table') - and (#_objectTypeData.group > 0)) then - - for _groupId, _group in pairs(_objectTypeData.group) do - if _group and _group.units and type(_group.units) == 'table' then - for _unitNum, _unit in pairs(_group.units) do - if _unit.canCargo == true then - local _cargoName = env.getValueDictByKey(_unit.name) - ctld.missionEditorCargoCrates[_cargoName] = _cargoName - env.info("Crate Found: " .. _unit.name.." - Unit: ".._cargoName) - end - end - end - end - end - end - end - end - end - end - end - end - env.info("END search for crates") - - -- don't initialize more than once - ctld.alreadyInitialized = true - - env.info("CTLD READY") -end - - --- initialize the random number generator to make it almost random -math.random(); math.random(); math.random() - ---- Enable/Disable error boxes displayed on screen. -env.setErrorMessageBoxEnabled(false) - --- initialize CTLD in 2 seconds, so other scripts have a chance to modify the configuration before initialization -ctld.logInfo(string.format("Loading version %s in 2 seconds", ctld.Version)) -timer.scheduleFunction(ctld.initialize, nil, timer.getTime() + 2) - ---DEBUG FUNCTION --- for key, value in pairs(getmetatable(_spawnedCrate)) do --- env.info(tostring(key)) --- env.info(tostring(value)) --- end diff --git a/scripts/RotorOps.lua b/scripts/RotorOps.lua index ee44a99..642fa99 100644 --- a/scripts/RotorOps.lua +++ b/scripts/RotorOps.lua @@ -1,5 +1,5 @@ RotorOps = {} -RotorOps.version = "1.2.8" +RotorOps.version = "1.3.0" local debug = true @@ -8,7 +8,7 @@ local debug = true --- Protip: change these options from the mission editor rather than changing the script file itself. See documentation on github for details. ---RotorOps settings that are safe to change dynamically (ideally from the mission editor in DO SCRIPT for portability). You can change these while the script is running, at any time. +--RotorOps settings that can be changed dynamically (ideally from the mission editor in DO SCRIPT for portability). You can change these while the script is running, at any time. Be sure of your syntax and test...errors may crash the script. RotorOps.voice_overs = true RotorOps.ground_speed = 60 --max speed for ground vehicles moving between zones. Doesn't have much effect since always limited by slowest vehicle in group RotorOps.zone_status_display = true --constantly show units remaining and zone status on screen @@ -21,8 +21,14 @@ RotorOps.defending_vehicles_disperse = true RotorOps.inf_spawns_avail = 0 --this is the number of infantry group spawn events remaining in the active zone RotorOps.inf_spawn_chance = 25 -- 0-100 the chance of spawning infantry in an active zone spawn zone, per 'assessUnitsInZone' loop (10 seconds) RotorOps.inf_spawn_trigger_percent = 70 --infantry has a chance of spawning if the percentage of defenders remaining in zone is less than this value -RotorOps.inf_spawns_per_zone = 3 --number of infantry groups to spawn per zone +--RotorOps.inf_spawns_per_zone = 3 --number of infantry groups to spawn per zone RotorOps.inf_spawn_messages = true --voiceovers and messages for infantry spawns +RotorOps.inf_spawn_blue = {mg=1,at=0,aa=0,inf=4,mortar=0} --can be an integer quantity, or a ctld defined group table +RotorOps.inf_spawn_red = {mg=1,at=0,aa=0,inf=4,mortar=0} --can be an integer quantity, or a ctld defined group table +RotorOps.inf_apc_group = {mg=1,at=0,aa=0,inf=3,mortar=0} --can be an integer quantity, or a ctld defined group table +RotorOps.inf_spawns_total = 0 --number of infantry groups to spawn per game + +RotorOps.farp_smoke_color = 2 -- Green=0 Red=1 White=2 Orange=3 Blue=4 NONE= -1 --RotorOps settings that are safe to change only before calling setupConflict() @@ -31,8 +37,18 @@ RotorOps.CTLD_crates = false RotorOps.CTLD_sound_effects = true --sound effects for troop pickup/dropoffs RotorOps.exclude_ai_group_name = "Static" --include this somewhere in a group name to exclude the group from being tasked in the active zone RotorOps.pickup_zone_smoke = "blue" -RotorOps.apc_group = {mg=1,at=0,aa=0,inf=3,mortar=0} --not used yet, but we should define the CTLD groups - +RotorOps.ai_task_by_name = true --allow tasking all groups that include key strings in their group names eg 'Patrol' +RotorOps.ai_task_by_name_scheduler = true --continually search active groups for key strings and ai tasking +RotorOps.patrol_task_string = 'patrol' --default string to search group names for the patrol task. requires ai_task_by_name +RotorOps.aggressive_task_string = 'aggressive' --default string to search group names for the patrol task. requires ai_task_by_name +RotorOps.move_to_active_task_string = "activezone" --default string to search group names for the move to active zone task. requires ai_task_by_name +RotorOps.shift_task_string = "shift" +RotorOps.guard_task_string = "guard" +--RotorOps.patrol_task_radius = 100 --patrol search radius +--RotorOps.aggressive_task_radius = 1000 --aggressive search radius --not implementing for now until more time for testing +RotorOps.defending_vehicles_behavior = "shift" --available options: 'none', 'patrol', 'shift' +RotorOps.farp_pickups = true --allow ctld troop pickup at FARPs +RotorOps.enable_staging_pickzones = true ---[[END OF OPTIONS]]--- @@ -47,14 +63,13 @@ RotorOps.active_zone = "" --name of the active zone RotorOps.active_zone_index = 0 RotorOps.game_state_flag = 1 --user flag to store the game state RotorOps.staging_zones = {} -RotorOps.ctld_pickup_zones = {} --keep track of ctld zones we've added, mainly for map markup RotorOps.ai_defending_infantry_groups = {} RotorOps.ai_attacking_infantry_groups = {} RotorOps.ai_defending_vehicle_groups = {} RotorOps.ai_attacking_vehicle_groups = {} RotorOps.ai_tasks = {} RotorOps.defending = false -RotorOps.staged_units_flag = 111 +RotorOps.staged_units_flag = 111 -- shows a percentage of the units found in the staging zone when the game starts. you can also use 'ROPS_ATTACKERS' for readability trigger.action.outText("ROTOR OPS STARTED: "..RotorOps.version, 5) env.info("ROTOR OPS STARTED: "..RotorOps.version) @@ -74,6 +89,13 @@ local cooldown = { ["attack_plane_msg"] = 0, ["trans_helo_msg"] = 0, } +local zone_defenders_flags = { + 'ROPS_A_DEFENDERS', + 'ROPS_B_DEFENDERS', + 'ROPS_C_DEFENDERS', + 'ROPS_D_DEFENDERS', +} +RotorOps.farp_names = {} RotorOps.gameMsgs = { @@ -425,14 +447,14 @@ function RotorOps.getValidUnitFromGroup(grp) else group_obj = grp end - if not grp then + if not group_obj then return nil end - if grp:isExist() ~= true then + if group_obj:isExist() ~= true then return nil end local first_valid_unit - for index, unit in pairs(grp:getUnits()) + for index, unit in pairs(group_obj:getUnits()) do if unit:isExist() == true then first_valid_unit = unit @@ -443,7 +465,35 @@ function RotorOps.getValidUnitFromGroup(grp) return first_valid_unit end +--"static" in this case, is our groups/units that we don't want controlled by conflict zone tasks +local function isStaticUnit(unit) + local unit_obj + if type(unit) == 'string' then + unit_obj = Unit.getByName(unit) + else + unit_obj = unit + end + if string.find(unit_obj:getGroup():getName():lower(), RotorOps.exclude_ai_group_name:lower()) then + return true + else + return false + end +end +--"static" in this case, is our groups/units that we don't want controlled by conflict zone tasks +local function isStaticGroup(group) + local group_obj + if type(group) == 'string' then + group_obj = Group.getByName(group) + else + group_obj = group + end + if string.find(group_obj:getName():lower(), RotorOps.exclude_ai_group_name:lower()) then + return true + else + return false + end +end ----USEFUL PUBLIC FUNCTIONS FOR THE MISSION EDITOR--- @@ -500,21 +550,20 @@ end ---see list of tasks in aiExecute. Zone is optional for many tasks -function RotorOps.aiTask(grp, task, zone) +--see list of tasks in aiExecute. Zone/point is optional for many tasks. Works with group name or object/table +function RotorOps.aiTask(grp, task, zone, point) local group_name if type(grp) == 'string' then group_name = grp else group_name = Group.getName(grp) end - if string.find(group_name:lower(), RotorOps.exclude_ai_group_name:lower()) then --exclude groups that the user specifies with a special group name - return - end + if tableHasKey(RotorOps.ai_tasks, group_name) == true then --if we already have this group in our list to manage --debugMsg("timer already exists, updating task for "..group_name.." : ".. RotorOps.ai_tasks[group_name].ai_task.." to "..task) RotorOps.ai_tasks[group_name].ai_task = task RotorOps.ai_tasks[group_name].zone = zone + RotorOps.ai_tasks[group_name].point = point else local vars = {} vars.group_name = group_name @@ -522,8 +571,11 @@ function RotorOps.aiTask(grp, task, zone) if zone then vars.zone = zone end + if point then + vars.point = point + end local timer_id = timer.scheduleFunction(RotorOps.aiExecute, vars, timer.getTime() + 5) - RotorOps.ai_tasks[group_name] = {['timer_id'] = timer_id, ['ai_task'] = task, ['zone'] = zone} + RotorOps.ai_tasks[group_name] = {['timer_id'] = timer_id, ['ai_task'] = task, ['zone'] = zone, ['point'] = point} end end @@ -541,23 +593,24 @@ function RotorOps.tallyZone(zone_name) for index, unit in pairs(new_units) do if not hasValue(RotorOps.staged_units, unit) then - env.info("RotorOps adding new units to staged_units: "..#new_units) - table.insert(RotorOps.staged_units, unit) - RotorOps.aiTask(unit:getGroup(),"move_to_active_zone", RotorOps.zones[RotorOps.active_zone_index].name) + if not isStaticUnit(unit) then + env.info("RotorOps adding new units to staged_units: "..#new_units) + table.insert(RotorOps.staged_units, unit) + RotorOps.aiTask(unit:getGroup(),"move_to_active_zone", RotorOps.zones[RotorOps.active_zone_index].name) + end else --env.info("unit already in table") end end end --- --- for index, unit in pairs(RotorOps.staged_units) do --- if string.find(Unit.getGroup(unit):getName():lower(), RotorOps.exclude_ai_group_name:lower()) then --- RotorOps.staged_units[index] = nil --remove 'static' units --- end --- end + end +--display a text message to all players with a radio sound effect +function RotorOps.radioText(message) + RotorOps.gameMsg({message, 'radio_effect.ogg'}) +end ---AI CORE BEHAVIOR-- @@ -772,6 +825,138 @@ function RotorOps.patrolRadius(vars) end +function RotorOps.shiftPosition(vars) + --debugMsg("patrol radius: "..mist.utils.tableShow(vars.grp)) + local grp = vars.grp + local search_radius = vars.radius or 100 + local inner_radius = 50 --minimum distance to move for randpointincircle + local first_valid_unit + if grp:isExist() ~= true then return end + local start_point = vars.point + + if not start_point then + env.info("RotorOps: No point provided, getting current position.") + for index, unit in pairs(grp:getUnits()) do + if unit:isExist() == true then + first_valid_unit = unit + break + else --trigger.action.outText("a unit no longer exists", 15) + end + end + if first_valid_unit == nil then return end + start_point = first_valid_unit:getPoint() + end + + + local max_waypoints = 2 + + local urban = RotorOps.pointIsUrban(start_point, 100) + formation = 'Cone' + if urban then + formation = 'On Road' + end + + local path = {} + path[1] = mist.ground.buildWP(start_point, '', 5) + + for i = #path, max_waypoints, 1 do + for i = 1, 4, 1 do + local rand_point = mist.getRandPointInCircle(start_point, search_radius, inner_radius) + + if mist.isTerrainValid(rand_point, {'LAND', 'ROAD'}) == true then + path[#path + 1] = mist.ground.buildWP(rand_point, formation, 5) + env.info("point is valid, adding as waypoint with formation: " .. formation) + break + end + + end + end + + mist.goRoute(grp, path) +end + + +function RotorOps.guardPosition(vars) + --debugMsg("patrol radius: "..mist.utils.tableShow(vars.grp)) + local grp = vars.grp + local search_radius = vars.radius or 100 + local first_valid_unit + if grp:isExist() ~= true then return end + local start_point = vars.point + + if not start_point then + env.info("RotorOps: No point provided, getting current position.") + for index, unit in pairs(grp:getUnits()) do + if unit:isExist() == true then + first_valid_unit = unit + break + else --trigger.action.outText("a unit no longer exists", 15) + end + end + if first_valid_unit == nil then return end + start_point = first_valid_unit:getPoint() + end + local object_vol_thresh = 0 + local max_waypoints = 1 + local foundUnits = {} + + local volS = { + id = world.VolumeType.SPHERE, + params = { + point = grp:getUnit(1):getPoint(), --check if exists, maybe itterate through grp + radius = search_radius + } + } + + local ifFound = function(foundItem, val) + --trigger.action.outText("found item: "..foundItem:getTypeName(), 5) + if foundItem:hasAttribute("Infantry") ~= true then --disregard infantry...we only want objects that might provide cover + if getObjectVolume(foundItem) > object_vol_thresh then + foundUnits[#foundUnits + 1] = foundItem + --trigger.action.outText("valid cover item: "..foundItem:getTypeName(), 5) + else --debugMsg("object not large enough: "..foundItem:getTypeName()) + end + else --trigger.action.outText("object not the right type", 5) + end + return true + end + + world.searchObjects(1, volS, ifFound) + world.searchObjects(3, volS, ifFound) + world.searchObjects(5, volS, ifFound) + --world.searchObjects(Object.Category.BASE, volS, ifFound) + if #foundUnits > 0 then + local path = {} + path[1] = mist.ground.buildWP(start_point, '', 5) + local rand_index = math.random(1,#foundUnits) + path[#path + 1] = mist.ground.buildWP(foundUnits[rand_index]:getPoint(), '', 3) + mist.goRoute(grp, path) + end +end + +--helper function to try to determine a point is near many scenery objects +function RotorOps.pointIsUrban(_point, _radius) + local volS = { + id = world.VolumeType.SPHERE, + params = { + point = _point, + radius = _radius + } + } + local foundUnits = {} + local ifFound = function(foundItem, val) + foundUnits[#foundUnits + 1] = foundItem + end + + world.searchObjects(5, volS, ifFound) + --env.info("Found scenery objects: " .. #foundUnits) + if #foundUnits > 10 then + return true + end + return false +end + + function RotorOps.aiExecute(vars) local update_interval = 60 @@ -780,6 +965,7 @@ function RotorOps.aiExecute(vars) local group_name = vars.group_name local task = RotorOps.ai_tasks[group_name].ai_task local zone = RotorOps.ai_tasks[group_name].zone + local point = RotorOps.ai_tasks[group_name].point -- if vars.zone then zone = vars.zone end @@ -862,6 +1048,20 @@ function RotorOps.aiExecute(vars) local speed = RotorOps.ground_speed local force_offroad = RotorOps.force_offroad mist.groupToPoint(group_name, RotorOps.active_zone, formation, final_heading, speed, force_offroad) + elseif task == "shift" then + local vars = {} + vars.grp = Group.getByName(group_name) + vars.radius = 250 + vars.point = point + RotorOps.shiftPosition(vars) --takes a group object, not name + update_interval = math.random(60,360) + elseif task == "guard" then + local vars = {} + vars.grp = Group.getByName(group_name) + vars.radius = 100 + vars.point = point + RotorOps.guardPosition(vars) --takes a group object, not name + update_interval = math.random(60,120) end @@ -916,28 +1116,38 @@ function RotorOps.assessUnitsInZone(var) RotorOps.ai_defending_vehicle_groups = RotorOps.groupsFromUnits(defending_vehicles) RotorOps.ai_attacking_infantry_groups = RotorOps.groupsFromUnits(attacking_infantry) RotorOps.ai_attacking_vehicle_groups = RotorOps.groupsFromUnits(attacking_vehicles) + + for index, group in pairs(RotorOps.ai_defending_infantry_groups) do - if group then + if group and not isStaticGroup(group) then RotorOps.aiTask(group, "patrol") end end for index, group in pairs(RotorOps.ai_attacking_infantry_groups) do - if group then + if group and not isStaticGroup(group) then RotorOps.aiTask(group, "clear_zone", RotorOps.active_zone) end end for index, group in pairs(RotorOps.ai_attacking_vehicle_groups) do - if group then + if group and not isStaticGroup(group) then RotorOps.aiTask(group, "clear_zone", RotorOps.active_zone) end end for index, group in pairs(RotorOps.ai_defending_vehicle_groups) do - if group then + if group and not isStaticGroup(group) then Group.getByName(group):getController():setOption(AI.Option.Ground.id.DISPERSE_ON_ATTACK , RotorOps.defending_vehicles_disperse) + if RotorOps.defending_vehicles_behavior == "patrol" then + RotorOps.aiTask(group, "patrol") + elseif RotorOps.defending_vehicles_behavior == "shift" then + local unit = RotorOps.getValidUnitFromGroup(group) + if unit then + RotorOps.aiTask(group, "shift", nil, unit:getPoint()) + end + end end end @@ -953,13 +1163,20 @@ function RotorOps.assessUnitsInZone(var) --sort infantry spawn zones and spawn quantity inf_spawn_zones = {} + local total_spawn_zones = 0 for zone, zoneobj in pairs(mist.DBs.zonesByName) do if string.find(zone, RotorOps.active_zone) and string.find(zone:lower(), "spawn") then --if we find a zone that has the active zone name and the word spawn inf_spawn_zones[#inf_spawn_zones + 1] = zone env.info("ROTOR OPS: spawn zone found:"..zone) end + if string.find(zone:lower(), "spawn") then + total_spawn_zones = total_spawn_zones + 1 + end end - RotorOps.inf_spawns_avail = RotorOps.inf_spawns_per_zone * #inf_spawn_zones + --RotorOps.inf_spawns_avail = RotorOps.inf_spawns_per_zone * RotorOps.inf_spawn_multiplier[RotorOps.active_zone_index] + if total_spawn_zones > 0 then + RotorOps.inf_spawns_avail = (RotorOps.inf_spawns_total / total_spawn_zones) * #inf_spawn_zones + end env.info("ROTOR OPS: zone activated: "..RotorOps.active_zone..", inf spawns avail:"..RotorOps.inf_spawns_avail..", spawn zones:"..#inf_spawn_zones) end @@ -973,6 +1190,7 @@ function RotorOps.assessUnitsInZone(var) active_zone_initial_defenders = nil defenders_remaining_percent = 0 trigger.action.setUserFlag(defenders_status_flag, 0) --set the zone's flag to cleared + trigger.action.setUserFlag(zone_defenders_flags[RotorOps.active_zone_index], 0) --set the zone's flag to cleared if RotorOps.defending == true then RotorOps.gameMsg(RotorOps.gameMsgs.enemy_cleared_zone, RotorOps.active_zone_index) else @@ -984,6 +1202,7 @@ function RotorOps.assessUnitsInZone(var) else trigger.action.setUserFlag(defenders_status_flag, defenders_remaining_percent) --set the zones flag to indicate the status of remaining defenders + trigger.action.setUserFlag(zone_defenders_flags[RotorOps.active_zone_index], defenders_remaining_percent) end --are all zones clear? @@ -998,13 +1217,14 @@ function RotorOps.assessUnitsInZone(var) --update staged units remaining flag local staged_units_remaining = {} for index, unit in pairs(RotorOps.staged_units) do - if unit:isExist() then + if unit:isExist() and unit:getLife() > 0 then staged_units_remaining[#staged_units_remaining + 1] = unit end end local percent_staged_remain = 0 percent_staged_remain = math.floor((#staged_units_remaining / #RotorOps.staged_units) * 100) trigger.action.setUserFlag(RotorOps.staged_units_flag, percent_staged_remain) + trigger.action.setUserFlag('ROPS_ATTACKERS', percent_staged_remain) debugMsg("Staged units remaining percent: "..percent_staged_remain.."%") @@ -1013,9 +1233,11 @@ function RotorOps.assessUnitsInZone(var) if RotorOps.defending == true then RotorOps.game_state = RotorOps.game_states.lost trigger.action.setUserFlag(RotorOps.game_state_flag, RotorOps.game_states.lost) + trigger.action.setUserFlag('ROPS_GAMESTATE', RotorOps.game_states.lost) else RotorOps.game_state = RotorOps.game_states.won trigger.action.setUserFlag(RotorOps.game_state_flag, RotorOps.game_states.won) + trigger.action.setUserFlag('ROPS_GAMESTATE', RotorOps.game_states.won) end return --we won't reset our timer to fire this function again end @@ -1030,6 +1252,7 @@ function RotorOps.assessUnitsInZone(var) if RotorOps.defending and defending_game_won then RotorOps.game_state = RotorOps.game_states.won trigger.action.setUserFlag(RotorOps.game_state_flag, RotorOps.game_states.won) + trigger.action.setUserFlag('ROPS_GAMESTATE', RotorOps.game_states.won) return --we won't reset our timer to fire this function again end @@ -1064,7 +1287,7 @@ function RotorOps.assessUnitsInZone(var) local function timedDeploy() if vehicle:isExist() then env.info(vehicle:getName().." is deploying troops.") - RotorOps.deployTroops(4, vehicle:getGroup(), false) + RotorOps.deployTroops(RotorOps.inf_apc_group, vehicle:getGroup(), false) end end @@ -1086,9 +1309,9 @@ function RotorOps.assessUnitsInZone(var) local zone = inf_spawn_zones[rand_index] if RotorOps.defending then - ctld.spawnGroupAtTrigger("blue", 5, zone, 1000) + ctld.spawnGroupAtTrigger("blue", RotorOps.inf_spawn_blue, zone, 1000) else - ctld.spawnGroupAtTrigger("red", 5, zone, 1000) + ctld.spawnGroupAtTrigger("red", RotorOps.inf_spawn_red, zone, 1000) RotorOps.gameMsg(RotorOps.gameMsgs.infantry_spawned, math.random(1, #RotorOps.gameMsgs.infantry_spawned)) end @@ -1120,12 +1343,19 @@ function RotorOps.assessUnitsInZone(var) local message = "" local header = "" local body = "" + -- if RotorOps.defending == true then + -- header = "[DEFEND "..RotorOps.active_zone .. "] " + -- body = "RED: " ..#attacking_infantry.. " infantry, " .. #attacking_vehicles .. " vehicles. BLUE: "..#defending_infantry.. " infantry, " .. #defending_vehicles.." vehicles. ["..defenders_remaining_percent.."%]" + -- else + -- header = "[ATTACK "..RotorOps.active_zone .. "] " + -- body = "RED: " ..#defending_infantry.. " infantry, " .. #defending_vehicles .. " vehicles. BLUE: "..#attacking_infantry.. " infantry, " .. #attacking_vehicles.." vehicles. ["..defenders_remaining_percent.."%]" + -- end if RotorOps.defending == true then header = "[DEFEND "..RotorOps.active_zone .. "] " - body = "RED: " ..#attacking_infantry.. " infantry, " .. #attacking_vehicles .. " vehicles. BLUE: "..#defending_infantry.. " infantry, " .. #defending_vehicles.." vehicles. ["..defenders_remaining_percent.."%]" + body = "BLUE: "..#defending_infantry.. " infantry, " .. #defending_vehicles.." vehicles. RED CONVOY: " .. #staged_units_remaining .." vehicles. ["..percent_staged_remain.."%]" else header = "[ATTACK "..RotorOps.active_zone .. "] " - body = "RED: " ..#defending_infantry.. " infantry, " .. #defending_vehicles .. " vehicles. BLUE: "..#attacking_infantry.. " infantry, " .. #attacking_vehicles.." vehicles. ["..defenders_remaining_percent.."%]" + body = "RED: " ..#defending_infantry.. " infantry, " .. #defending_vehicles .. " vehicles. BLUE CONVOY: " .. #staged_units_remaining .." vehicles. ["..percent_staged_remain.."%]" end message = header .. body @@ -1169,29 +1399,49 @@ function RotorOps.drawZones() --this could use a lot of work, we should use tri trigger.action.textToAll(coalition, id + 100, point, color, text_fill_color, font_size, read_only, text) end - - for index, pickup_zone in pairs(RotorOps.ctld_pickup_zones) - do - for c_index, c_zone in pairs(ctld.pickupZones) - do - if pickup_zone == c_zone[1] then - --debugMsg("found our zone in ctld zones, status: "..c_zone[4]) - local ctld_zone_status = c_zone[4] - local point = trigger.misc.getZone(pickup_zone).point - local radius = trigger.misc.getZone(pickup_zone).radius - local coalition = -1 - local id = index + 150 --this must be UNIQUE! - local color = {1, 1, 1, 0.5} - local fill_color = {0, 0.8, 0, 0.1} - local line_type = 5 --1 Solid 2 Dashed 3 Dotted 4 Dot Dash 5 Long Dash 6 Two Dash - if ctld_zone_status == 'yes' or ctld_zone_status == 1 then - --debugMsg("draw the pickup zone") - trigger.action.circleToAll(coalition, id, point, radius, color, fill_color, line_type) - end - end - end + for index, cpz in pairs(ctld.pickupZones) do + env.info("CTLD pickzone name: " .. cpz[1]) + pickup_zone = trigger.misc.getZone(cpz[1]) + if pickup_zone then + env.info("found a ctld pickup zone") + local ctld_zone_status = cpz[4] + local point = pickup_zone.point + local radius = pickup_zone.radius + local coalition = -1 + local id = index + 150 --this must be UNIQUE! + local color = {1, 1, 1, 0.5} + local fill_color = {0, 0.8, 0, 0.1} + local line_type = 5 --1 Solid 2 Dashed 3 Dotted 4 Dot Dash 5 Long Dash 6 Two Dash + if ctld_zone_status == 'yes' or ctld_zone_status == 1 then + env.info("pickup zone is active, drawing it to the map") + trigger.action.circleToAll(coalition, id, point, radius, color, fill_color, line_type) + end + end end + + -- for index, pickup_zone in pairs(RotorOps.ctld_pickup_zones) + -- do + -- for c_index, c_zone in pairs(ctld.pickupZones) + -- do + -- if pickup_zone == c_zone[1] then + -- --debugMsg("found our zone in ctld zones, status: "..c_zone[4]) + -- local ctld_zone_status = c_zone[4] + -- local point = trigger.misc.getZone(pickup_zone).point + -- local radius = trigger.misc.getZone(pickup_zone).radius + -- local coalition = -1 + -- local id = index + 150 --this must be UNIQUE! + -- local color = {1, 1, 1, 0.5} + -- local fill_color = {0, 0.8, 0, 0.1} + -- local line_type = 5 --1 Solid 2 Dashed 3 Dotted 4 Dot Dash 5 Long Dash 6 Two Dash + -- if ctld_zone_status == 'yes' or ctld_zone_status == 1 then + -- --debugMsg("draw the pickup zone") + -- trigger.action.circleToAll(coalition, id, point, radius, color, fill_color, line_type) + -- end + -- end + -- end + -- end + end @@ -1211,17 +1461,17 @@ function RotorOps.setActiveZone(new_index) if new_index ~= old_index then --the active zone is changing - if not RotorOps.defending then + -- if not RotorOps.defending then - if old_index > 0 and RotorOps.apcs_spawn_infantry == false then - ctld.activatePickupZone(RotorOps.zones[old_index].name) --make the captured zone a pickup zone - end - ctld.deactivatePickupZone(RotorOps.zones[new_index].name) - end + -- if old_index > 0 and RotorOps.apcs_spawn_infantry == false then + -- ctld.activatePickupZone(RotorOps.farp_names[old_index]) --make the captured zone a pickup zone + -- end + -- ctld.deactivatePickupZone(RotorOps.farp_names[new_index]) + -- end RotorOps.game_state = new_index trigger.action.setUserFlag(RotorOps.game_state_flag, new_index) - + trigger.action.setUserFlag('ROPS_GAMESTATE', new_index) if new_index > old_index then if RotorOps.defending == true then RotorOps.gameMsg(RotorOps.gameMsgs.enemy_pushing, new_index) @@ -1288,6 +1538,28 @@ function RotorOps.setupCTLD() {name = "Small Platoon (16)", inf = 9, mg = 3, at = 3, aa = 1 }, {name = "Platoon (24)", inf = 10, mg = 5, at = 6, aa = 3 }, } + + + --add to CTLD default pickzone names. This could be done in a loop but this should be more readable + --pickupZones = { "Zone name or Ship Unit Name", "smoke color", "limit (-1 unlimited)", "ACTIVE (yes/no)", "side (0 = Both sides / 1 = Red / 2 = Blue )", flag number (optional) } + ctld.pickupZones[#ctld.pickupZones + 1] = { "STAGING", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "STAGING_BASE", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "ALPHA_FARP", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "BRAVO_FARP", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "CHARLIE_FARP", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "DELTA_FARP", RotorOps.pickup_zone_smoke, -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "HELO_CARRIER", "none", -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "HELO_CARRIER_1", "none", -1, "no", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops1", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops2", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops3", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops4", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops5", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops6", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops7", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops8", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops9", RotorOps.pickup_zone_smoke, -1, "yes", 0 } + ctld.pickupZones[#ctld.pickupZones + 1] = { "troops10", RotorOps.pickup_zone_smoke, -1, "yes", 0 } @@ -1310,8 +1582,13 @@ function RotorOps.addZone(_name, _zone_defenders_flag) end table.insert(RotorOps.zones, {name = _name, defenders_status_flag = _zone_defenders_flag}) trigger.action.setUserFlag(_zone_defenders_flag, 101) + trigger.action.setUserFlag(zone_defenders_flags[1], 101) + trigger.action.setUserFlag(zone_defenders_flags[2], 101) + trigger.action.setUserFlag(zone_defenders_flags[3], 101) + trigger.action.setUserFlag(zone_defenders_flags[4], 101) RotorOps.drawZones() - RotorOps.addPickupZone(_name, RotorOps.pickup_zone_smoke, -1, "no", 2) + local farp_name = _name .. "_FARP" + RotorOps.farp_names[#RotorOps.farp_names + 1] = farp_name end @@ -1320,7 +1597,7 @@ function RotorOps.addStagingZone(_name) trigger.action.outText(_name.." trigger zone missing! Check RotorOps setup!", 60) env.warning(_name.." trigger zone missing! Check RotorOps setup!") end - RotorOps.addPickupZone(_name, RotorOps.pickup_zone_smoke, -1, "no", 0) + RotorOps.staging_zones[#RotorOps.staging_zones + 1] = _name end @@ -1348,6 +1625,7 @@ function RotorOps.setupConflict(_game_state_flag) RotorOps.game_state = RotorOps.game_states.not_started processMsgBuffer() trigger.action.setUserFlag(RotorOps.game_state_flag, RotorOps.game_states.not_started) + trigger.action.setUserFlag('ROPS_GAMESTATE', RotorOps.game_states.not_started) trigger.action.outText("ALL TROOPS GET TO TRANSPORT AND PREPARE FOR DEPLOYMENT!" , 10, false) if RotorOps.CTLD_sound_effects == true then local timer_id = timer.scheduleFunction(RotorOps.registerCtldCallbacks, 1, timer.getTime() + 5) @@ -1355,8 +1633,7 @@ function RotorOps.setupConflict(_game_state_flag) end -function RotorOps.addPickupZone(zone_name, smoke, limit, active, side) - RotorOps.ctld_pickup_zones[#RotorOps.ctld_pickup_zones + 1] = zone_name +function RotorOps.addPickupZone(zone_name, smoke, limit, active, side) --depreciated, don't use ctld.pickupZones[#ctld.pickupZones + 1] = {zone_name, smoke, limit, active, side} end @@ -1370,14 +1647,14 @@ function RotorOps.startConflict() --missionCommands.removeItem(commandDB['start_conflict']) --commandDB['clear_zone'] = missionCommands.addCommand( "[CHEAT] Force Clear Zone" , conflict_zones_menu , RotorOps.clearActiveZone) - RotorOps.staged_units = mist.getUnitsInZones(mist.makeUnitTable({'[all][vehicle]'}), RotorOps.staging_zones) + local units_found = mist.getUnitsInZones(mist.makeUnitTable({'[all][vehicle]'}), RotorOps.staging_zones) --filter out 'static' units --- for index, unit in pairs(RotorOps.staged_units) do --- if string.find(Unit.getGroup(unit):getName():lower(), RotorOps.exclude_ai_group_name:lower()) then --- RotorOps.staged_units[index] = nil --remove 'static' units --- end --- end + for index, unit in pairs(units_found) do + if not isStaticUnit(unit) then + RotorOps.staged_units[#RotorOps.staged_units + 1] = unit + end + end if RotorOps.staged_units[1] == nil then @@ -1387,23 +1664,35 @@ function RotorOps.startConflict() end if RotorOps.staged_units[1]:getCoalition() == 1 then --check the coalition in the staging zone to see if we're defending + --DEFENSE + trigger.action.setUserFlag('ROPS_DEFENDING', 1) RotorOps.defending = true RotorOps.gameMsg(RotorOps.gameMsgs.start_defense) - ctld.activatePickupZone(RotorOps.zones[#RotorOps.zones].name) --make the last zone a pickup zone for defenders - for index, zone in pairs(RotorOps.staging_zones) do - ctld.deactivatePickupZone(zone) - end + ctld.activatePickupZone(RotorOps.farp_names[#RotorOps.farp_names]) --make the last zone a pickup zone for defenders else + --OFFENSE RotorOps.gameMsg(RotorOps.gameMsgs.start) - for index, zone in pairs(RotorOps.staging_zones) do - ctld.activatePickupZone(zone) - end - + if RotorOps.enable_staging_pickzones then + if trigger.misc.getZone("STAGING_BASE") then + ctld.activatePickupZone("STAGING_BASE") + else + ctld.activatePickupZone("STAGING") + end + end + end + + + + RotorOps.setActiveZone(1) + if RotorOps.ai_task_by_name then + RotorOps.taskByName() + end + local id = timer.scheduleFunction(RotorOps.assessUnitsInZone, 1, timer.getTime() + 5) world.addEventHandler(RotorOps.eventHandler) end @@ -1431,6 +1720,32 @@ function RotorOps.triggerSpawn(groupName, msg, resume_task) end +---Search for group names containing key strings to assign AI tasks +function RotorOps.taskByName() + env.info("RotorOps searching for groups to taskByName") + for group_name, data in pairs(mist.DBs.groupsByName) do + if string.find(group_name:lower(), RotorOps.patrol_task_string:lower()) then + RotorOps.aiTask(group_name, "patrol") + env.info("Tasking " .. group_name .. " as patrol.") + elseif string.find(group_name:lower(), RotorOps.aggressive_task_string:lower()) then + RotorOps.aiTask(group_name, "aggressive") + env.info("Tasking " .. group_name .. " as aggressive.") + elseif string.find(group_name:lower(), RotorOps.move_to_active_task_string:lower()) then + RotorOps.aiTask(group_name, "move_to_active_zone") + env.info("Tasking " .. group_name .. " to move to active zone.") + elseif string.find(group_name:lower(), RotorOps.shift_task_string:lower()) then + RotorOps.aiTask(group_name, "shift") + env.info("Tasking " .. group_name .. " to shift positions.") + elseif string.find(group_name:lower(), RotorOps.guard_task_string:lower()) then + RotorOps.aiTask(group_name, "guard") + env.info("Tasking " .. group_name .. " to guard positions.") + end + end + if RotorOps.ai_task_by_name_scheduler then + local timer_id = timer.scheduleFunction(RotorOps.taskByName, nil, timer.getTime() + 120) + end +end + function RotorOps.spawnAttackHelos() RotorOps.triggerSpawn("Enemy Attack Helicopters", RotorOps.gameMsgs.attack_helos_prep, true) @@ -1443,8 +1758,16 @@ end -function RotorOps.farpEstablished(index) +function RotorOps.farpEstablished(index, trigger_zone) env.info("RotorOps FARP established at "..RotorOps.zones[index].name) + if trigger_zone then + if RotorOps.farp_pickups then + ctld.activatePickupZone(trigger_zone) + end + if RotorOps.farp_smoke_color >= 0 and RotorOps.pickup_zone_smoke == 'none' then + trigger.action.smoke(trigger.misc.getZone(trigger_zone).point , RotorOps.farp_smoke_color) + end + end timer.scheduleFunction(function()RotorOps.gameMsg(RotorOps.gameMsgs.farp_established, index) end, {}, timer.getTime() + 15) end @@ -1562,6 +1885,7 @@ function RotorOps.spawnTranspHelos(troops, max_drops) end + --- USEFUL PUBLIC 'LUA PREDICATE' FUNCTIONS FOR MISSION EDITOR TRIGGERS (don't forget that DCS lua predicate functions should 'return' these function calls) --determine if any human players are above a defined ceiling above ground level. If 'above' parameter is false, function will return true if no players above ceiling diff --git a/scripts/Splash_Damage_2_0.lua b/scripts/Splash_Damage_2_0.lua index 1e2719a..a61dc9a 100644 --- a/scripts/Splash_Damage_2_0.lua +++ b/scripts/Splash_Damage_2_0.lua @@ -22,6 +22,18 @@ spencershepard (GRIMM): -damage model for ground units that will disable their weapons and ability to move with partial damage before they are killed -added options table to allow easy adjustments before release -general refactoring and restructure + + 31 December 2021 + spencershepard (GRIMM): +-added many new weapons +-added filter for weapons.shells events +-fixed mission weapon message option +-changed default for damage_model option + + 16 April 2022 + spencershepard (GRIMM): + added new/missing weapons to explTable + added new option rocket_multiplier --]] ----[[ ##### SCRIPT CONFIGURATION ##### ]]---- @@ -40,6 +52,7 @@ splash_damage_options = { ["infantry_cant_fire_health"] = 90, --if health is below this value after our explosions, set ROE to HOLD to simulate severe injury ["debug"] = false, --enable debugging messages ["weapon_missing_message"] = false, --false disables messages alerting you to weapons missing from the explTable + ["rocket_multiplier"] = 1.3, --multiplied by the explTable value for rockets } local script_enable = 1 @@ -156,8 +169,14 @@ explTable = { ["AB_250_2_SD_2"] = 100, --("AB 250-2 - 144 x SD-2, 250kg CBU with HE submunitions") ["AB_250_2_SD_10A"] = 100, --("AB 250-2 - 17 x SD-10A, 250kg CBU with 10kg Frag/HE submunitions") ["AB_500_1_SD_10A"] = 213, --("AB 500-1 - 34 x SD-10A, 500kg CBU with 10kg Frag/HE submunitions") - --["LTF_5B"] = 100, --("LTF 5b Aerial Torpedo") - --agm-65?? + ["AGM_114K"] = 10, + ["HYDRA_70_M229"] = 8, + ["AGM_65D"] = 130, + ["AGM_65E"] = 300, + ["AGM_65F"] = 300, + ["HOT3"] = 15, + ["AGR_20A"] = 8, + ["GBU_54_V_1B"] = 118, } @@ -253,9 +272,11 @@ function track_wpns() trigger.action.explosion(impactPoint, getWeaponExplosive(wpnData.name)) --trigger.action.smoke(impactPoint, 0) end - --if wpnData.cat == Weapon.Category.ROCKET then - blastWave(impactPoint, splash_damage_options.blast_search_radius, wpnData.ordnance, getWeaponExplosive(wpnData.name)) - --end + local explosive = getWeaponExplosive(wpnData.name) + if splash_damage_options.rocket_multiplier > 0 and wpnData.cat == Weapon.Category.ROCKET then + explosive = explosive * splash_damage_options.rocket_multiplier + end + blastWave(impactPoint, splash_damage_options.blast_search_radius, wpnData.ordnance, explosive) tracked_weapons[wpn_id_] = nil -- remove from tracked weapons first. end end diff --git a/sound/embedded/radio_effect.ogg b/sound/embedded/radio_effect.ogg new file mode 100644 index 0000000..e7bbf2b Binary files /dev/null and b/sound/embedded/radio_effect.ogg differ diff --git a/templates/Forces/BLUE Default US Armor.miz b/templates/Forces/BLUE Default US Armor.miz deleted file mode 100644 index fc9903a..0000000 Binary files a/templates/Forces/BLUE Default US Armor.miz and /dev/null differ diff --git a/templates/Forces/BLUE Greece Armor (Mr Nobody).miz b/templates/Forces/BLUE Greece Armor (Mr Nobody).miz deleted file mode 100644 index e3a6485..0000000 Binary files a/templates/Forces/BLUE Greece Armor (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/BLUE Iran Armor (Mr Nobody).miz b/templates/Forces/BLUE Iran Armor (Mr Nobody).miz deleted file mode 100644 index d9da8ed..0000000 Binary files a/templates/Forces/BLUE Iran Armor (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/BLUE Turkey Armor (Mr Nobody).miz b/templates/Forces/BLUE Turkey Armor (Mr Nobody).miz deleted file mode 100644 index 8f2ee4d..0000000 Binary files a/templates/Forces/BLUE Turkey Armor (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/BLUE UK Armor (Mr Nobody).miz b/templates/Forces/BLUE UK Armor (Mr Nobody).miz deleted file mode 100644 index 5a88e7d..0000000 Binary files a/templates/Forces/BLUE UK Armor (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/BLUE US 1970s Armor & Infantry (Mr Nobody).miz b/templates/Forces/BLUE US 1970s Armor & Infantry (Mr Nobody).miz deleted file mode 100644 index c5fe727..0000000 Binary files a/templates/Forces/BLUE US 1970s Armor & Infantry (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/RED Default Armor (HARD).miz b/templates/Forces/RED Default Armor (HARD).miz deleted file mode 100644 index b599356..0000000 Binary files a/templates/Forces/RED Default Armor (HARD).miz and /dev/null differ diff --git a/templates/Forces/RED Default Armor, Infantry & Artillery (MED).miz b/templates/Forces/RED Default Armor, Infantry & Artillery (MED).miz deleted file mode 100644 index f7a5175..0000000 Binary files a/templates/Forces/RED Default Armor, Infantry & Artillery (MED).miz and /dev/null differ diff --git a/templates/Forces/RED Default Trucks & Infantry (EASY).miz b/templates/Forces/RED Default Trucks & Infantry (EASY).miz deleted file mode 100644 index 5713a14..0000000 Binary files a/templates/Forces/RED Default Trucks & Infantry (EASY).miz and /dev/null differ diff --git a/templates/Forces/RED Greece Armor (Mr Nobody).miz b/templates/Forces/RED Greece Armor (Mr Nobody).miz deleted file mode 100644 index 7fa5bbb..0000000 Binary files a/templates/Forces/RED Greece Armor (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/RED Iran Armor & Infantry (Mr Nobody).miz b/templates/Forces/RED Iran Armor & Infantry (Mr Nobody).miz deleted file mode 100644 index 301eba9..0000000 Binary files a/templates/Forces/RED Iran Armor & Infantry (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/RED North Vietnam Armor & Infantry (Mr Nobody).miz b/templates/Forces/RED North Vietnam Armor & Infantry (Mr Nobody).miz deleted file mode 100644 index 5da964e..0000000 Binary files a/templates/Forces/RED North Vietnam Armor & Infantry (Mr Nobody).miz and /dev/null differ diff --git a/templates/Forces/_How to add your own templates.txt b/templates/Forces/_How to add your own templates.txt deleted file mode 100644 index c83d46e..0000000 --- a/templates/Forces/_How to add your own templates.txt +++ /dev/null @@ -1,24 +0,0 @@ -## Forces Templates - -The friendly/enemy forces templates available in the generator are simply .miz files in the Generator/Forces folder. - -A Forces template defines the groups of ground units available, AI aircraft, liveries, and loadouts. - -To create your own Forces template: - -1) Create an empty mission on Caucasus -2) Add ground unit groups. -3) Save the mission in this directory. - -Optional: - -4) Add helicopters with "CAS" main task for attack helicopters. -5) Add helicopters with "Transport" main task for transport helicopters. -6) Add planes with "CAS" main task for attack planes. -7) Add planes with "CAP" main task for fighters. -8) Configure loadouts, liveries, and skill for aircraft. - -Tips: -- The mission generator will only extract blue ground units from the template when selected from the "Blue Forces" menu, and vice versa. -- Only unit types are used from ground units. Liveries or other attributes are able to be copied. -- For aircraft, group size is currently capped at 2 units per group to help prevent issues with parking. Only the first unit in the group is used as a source. diff --git a/templates/Imports/FARP_DEFAULT_ZONE.miz b/templates/Imports/FARP_DEFAULT_ZONE.miz deleted file mode 100644 index 8ba07ee..0000000 Binary files a/templates/Imports/FARP_DEFAULT_ZONE.miz and /dev/null differ diff --git a/templates/Imports/FARP_MINIMUM_ROADSIDE_INVULNERABLE.miz b/templates/Imports/FARP_MINIMUM_ROADSIDE_INVULNERABLE.miz deleted file mode 100644 index b69db01..0000000 Binary files a/templates/Imports/FARP_MINIMUM_ROADSIDE_INVULNERABLE.miz and /dev/null differ diff --git a/templates/Imports/FARP_MINIMUM_ROADSIDE_STATICS.miz b/templates/Imports/FARP_MINIMUM_ROADSIDE_STATICS.miz deleted file mode 100644 index b40d8b2..0000000 Binary files a/templates/Imports/FARP_MINIMUM_ROADSIDE_STATICS.miz and /dev/null differ diff --git a/templates/Imports/FARP_MOBILE_ROADSIDE_INVULNERABLE.miz b/templates/Imports/FARP_MOBILE_ROADSIDE_INVULNERABLE.miz deleted file mode 100644 index 86ced3a..0000000 Binary files a/templates/Imports/FARP_MOBILE_ROADSIDE_INVULNERABLE.miz and /dev/null differ diff --git a/templates/Imports/FARP_MOBILE_ROADSIDE_STATICS.miz b/templates/Imports/FARP_MOBILE_ROADSIDE_STATICS.miz deleted file mode 100644 index dfae3b3..0000000 Binary files a/templates/Imports/FARP_MOBILE_ROADSIDE_STATICS.miz and /dev/null differ diff --git a/templates/Imports/FOB_16_SPWN_WIDE.miz b/templates/Imports/FOB_16_SPWN_WIDE.miz deleted file mode 100644 index 65859d8..0000000 Binary files a/templates/Imports/FOB_16_SPWN_WIDE.miz and /dev/null differ diff --git a/templates/Imports/FOB_8_SPWN.miz b/templates/Imports/FOB_8_SPWN.miz deleted file mode 100644 index be862f6..0000000 Binary files a/templates/Imports/FOB_8_SPWN.miz and /dev/null differ diff --git a/templates/Imports/How to use imports.txt b/templates/Imports/How to use imports.txt deleted file mode 100644 index 556d285..0000000 --- a/templates/Imports/How to use imports.txt +++ /dev/null @@ -1,20 +0,0 @@ -## Imports - -A breakthrough feature of mission design with RotorOps is the ability to import complex arrangements of statics and vehicles. This allows you to create reusable mission assets like bases, FARPs, objective sites, or just about anything you can imagine building in the mission editor. You can place these on any map, at your desired point, rotation and coalition! - -A selection of FOBs, FARPs, and other objects are available in the Imports folder. Included are multiplayer FOBs with up to 16 helicopter spawns! A guide to the included templates is available here: [RotorOps IMPORT Assets](http://dcs-helicopters.com/wp-content/uploads/2022/03/RotorOps_IMPORT_TEMPLATES-1.pdf) - - -To use an import template: -1) Place a static mark flag in the scenario template mission. -2) Change the group name to 'IMPORT-filename', where the filename is a .miz file in the Generator/Imports folder. -3) Change the flag coalition to CJTF Blue/Red or UN Peacekeepers. -4) Change the flag heading and position as desired. -5) Change the flag UNIT NAME to something relevant (ie. 'North Base') -6) For multiple imports of the same template, the import object GROUP NAME should end with '-01' etc - -To create a new import template: -1) Make an empty mission on Caucasus. -2) Place units/objects on the map. -3) Make one unit group name: 'ANCHOR' This will represent the point of insertion/rotation in the target mission. -4) Save the template .miz file in Generator/Imports \ No newline at end of file diff --git a/templates/Imports/INSURGENT_COMPOUND.miz b/templates/Imports/INSURGENT_COMPOUND.miz deleted file mode 100644 index b27911e..0000000 Binary files a/templates/Imports/INSURGENT_COMPOUND.miz and /dev/null differ diff --git a/templates/Imports/MARKET_PLACE.miz b/templates/Imports/MARKET_PLACE.miz deleted file mode 100644 index 28ee14c..0000000 Binary files a/templates/Imports/MARKET_PLACE.miz and /dev/null differ diff --git a/templates/Imports/STAGING_LOGISTIC_HUB.miz b/templates/Imports/STAGING_LOGISTIC_HUB.miz deleted file mode 100644 index b0497b9..0000000 Binary files a/templates/Imports/STAGING_LOGISTIC_HUB.miz and /dev/null differ diff --git a/templates/Imports/VILLA_GRIMM.miz b/templates/Imports/VILLA_GRIMM.miz deleted file mode 100644 index ab6d00d..0000000 Binary files a/templates/Imports/VILLA_GRIMM.miz and /dev/null differ