|
Lua-экспорт в LockOn
Квалифицированные пользователи LockOn имеют возможность получать некоторые имитационные данные из LockOn и передавать некоторые управляющие входные команды LockOn, используя специальный скрипт ConfigExportExport.lua в рабочем каталоге LockOn. LockOn использует скриптовый язык Lua ( www.lua.org) для экспорта некоторых своих внутренних функций. Lua - это язык программирования, поэтому экспортные возможности предназначены только для программистов. Однако Lua настолько прост, что каждый может разобраться в простейших скриптах Lua. Они являются текстовыми файлами, поэтому вы можете просматривать и редактировать их с помощью Windows Notepad или любого другого текстового редактора.
LockOn предоставляет файлы...
LockOn активизирует скрипт...
Для уменьшения сетевого трафика...
Некоторые аналоговые команды...
В версии 1.1 экспортный скрипт значительно изменен...
Начиная с версии 1.12...
LockOn предоставляет файлы LuaSocket 2.0 Beta в папке ScriptsLuaSocket в каталоге установки LockOn. Вы можете применять LuaSocket для установки стандартных сетевых соединений между скриптом Export.lua и вашей локальной или удаленной программой.
Загляните в папку ScriptsLuaSocket и найдите файлы Listener.lua и Talker.lua. Вы можете использовать их в качестве самостоятельных примеров сетевого взаимодействия скриптов Lua.
Введите в командной строке Windows:
Lua.exe Listener.lua
Появится окно с сообщением:
Binding to host '*' and port 8080...
Waiting connection from talker on 0.0.0.0:8080...
Затем введите в командной строке Windows:
Lua.exe Talker.lua
Появится еще одно окно с приглашением ввода:
Attempting connection to host 'localhost' and port 8080...
Connected! Please type stuff (empty line to stop):
Введите любой текст во втором окне и нажмите Enter - текст появится и во втором окне тоже.
Затем попробуйте проделать то же самое на двух компьютерах. Измените строку
host = host or "localhost"
в файле Talker.lua на компьютере, где он будет запущен, на строку с IP-адресом компьютера, где будет запущен Listener.lua, например:
host = "195.111.222.333"
и затем введите в командной строке Windows на втором компьютере:
Lua.exe Listener.lua
И после появления уже знакомого нам окна, введите в командной строке Windows на первом компьютере:
Lua.exe Talker.lua
Затем введите любой текст в окне Talker - он появится и в окне Listener на втором компьютере. Поздравляем! Вы организовали ваш первый сетевой сеанс с помощью LuaSocket. Это просто, не так ли?
Теперь вернемся к скрипту Export.lua и обсудим его функции. В его начале вы видите некоторые комментарии:
-- Data export scripts
-- Copyright (C) 2004, Eagle Dynamics.
-- -
В языке Lua используются два последовательных минуса "--" в качестве начала однострочного комментария, который продолжается до конца строки. Если вам нужно закомментировать несколько строк, то можно использовать скобки "--[[" и "--]]":
-- Uncomment this function to enable data export!
--[[
function LuaExportStart()
-- Works once just before mission start.
-- Make initializations of your files or connections here.
-- For example:
-- 1) File
-- local file = io.open("./Temp/Export.log", "w")
-- if file then
-- io.output(file)
-- end
-- 2) Socket
-- dofile "lua.lua"
-- socket = require("socket")
-- host = host or "localhost"
-- port = port or 8080
-- c = socket.try(socket.connect(host, port)) -- connect to the listener socket
-- c:setoption("tcp-nodelay",true) -- set immediate transmission mode
end
--]]
LockOn активизирует скрипт Config\Export\Export.lua при каждом старте миссии. Вы должны раскомментировать функцию LuaExportStart для её активизации и для активизации всех остальных экспортных функций. Для этого добавьте один минус "-" непосредственно перед открывающей скобкой мульти-строчного комментария "--[[", чтобы преобразовать его в однострочный комментарий "---[[". Таким образом, закрывающая скобка мульти-строчного комментария без открывающей скобки также становится однострочным комментарием. Если вы захотите снова отключить экспортные функции, то удалите дополнительный третий минус, чтобы комментарий снова стал мульти-строчным.
Если LockOn не находит функцию LuaExportStart, то он выдаёт сообщение в файл TempError.log:
LuaExport::Lua data export disabled.
LockOn также выдаёт в файл Error.log все другие сообщения об ошибках в скрипте Export.lua.
LockOn вызывает функции скрипта для каждой имитации миссии. Он вызывает функцию LuaExportStart непосредственно перед стартом миссии для выполнения пользовательских инициализаций. Например, для открытия выходного файла:
local file = io.open("./Temp/Export.log", "w")
if file then
io.output(file)
end
или для установки сетевого соединения:
dofile "lua.lua"
socket = require("socket")
host = host or "localhost"
port = port or 8080
c = socket.try(socket.connect(host, port)) -- connect to the listener socket
c:setoption("tcp-nodelay",true) -- set immediate transmission mode
LockOn вызывает функцию LuaExportStop непосредственно после выхода из миссии для выполнения завершающих действий пользователя. Например, для закрытия выходного файла:
io.close()
или для разрыва сетевого соединения
socket.try(c:send("quit")) -- to close the listener socket
c:close()
LockOn вызывает функцию LuaExportBeforeNextFrame непосредственно перед каждым кадром имитации. Поэтому, если вам нужно выдавать LockOnу некоторые входные команды управления, то вы должны делать это здесь. Например:
LoSetCommand(3, 0.25) -- rudder 0.25 right
LoSetCommand(64) -- increase thrust
Имеются дискретные и аналоговые входные управляющие команды. У дискретных команд имеется только код:
LoSetCommand(64) -- increase thrust
У аналоговых команд имеются код и значение:
LoSetCommand(3, 0.25) -- rudder 0.25 right
LockOn вызывает функцию LuaExportAfterNextFrame каждый раз, когда кадр имитации завершается. Поэтому здесь вы должны кодировать ваши действия по получению результатов имитации в кадре. Например:
local t = LoGetModelTime()
local name = LoGetPilotName()
local altBar = LoGetAltitudeAboveSeaLevel()
local altRad = LoGetAltitudeAboveGroundLevel()
local pitch, bank, yaw = LoGetADIPitchBankYaw()
Затем вы можете переслать данные в ваш файл:
io.write(string.format("t = %.2f, name = %s, altBar = %.2f, altRad = %.2f, pitch = %.2f, bank = %.2f, yaw = %.2fn", t, name, altBar, altRad, pitch, bank, yaw))
или в вашу принимающую сетевую программу:
socket.try(c:send(string.format("t = %.2f, name = %s, altBar = %.2f, alrRad = %.2f, pitch = %.2f, bank = %.2f, yaw = %.2fn", t, name, altRad, altBar, pitch, bank, yaw)))
Для уменьшения сетевого трафика вам может понадобиться получать данные не после каждого кадра, а в некоторые моменты модельного времени. Вы можете использовать функцию LuaExportActivityNextEvent для программирования момента модельного времени tNext для вашего следующего экспортного события. Параметр t данной функции содержит текущее модельное время. Если tNext не увеличивает его значения, то функция LuaExportActivityNextEvent в текущей имитации больше не вызывается. Например, давайте получать данные об объектах с интервалом в секунду модельного времени и выводить их в наш файл:
local tNext = t
local o = LoGetWorldObjects()
for k,v in pairs(o) do
io.write(string.format("t = %.2f, ID = %d, name = %s, country = %s(%s), LatLongAlt = (%f, %f, %f), heading = %fn", t, k, v.Name, v.Country, v.Coalition, v.LatLongAlt.Lat, v.LatLongAlt.Long, v.LatLongAlt.Alt, v.Heading))
end
tNext = tNext + 1.0
return tNext
или в сетевое соединение:
local tNext = t
local o = LoGetWorldObjects()
for k,v in pairs(o) do
socket.try(c:send(string.format("t = %.2f, ID = %d, name = %s, country = %s(%s), LatLongAlt = (%f, %f, %f), heading = %fn", t, k, v.Name, v.Country, v.Coalition, v.LatLongAlt.x, v.LatLongAlt.Long, v.LatLongAlt.Alt, v.Heading)))
end
tNext = tNext + 1.0
return tNext
Вы можете зарегистрированные в LockOnе внутренние экспортные функции использовать в данном скрипте и в ваших скриптах, вызываемых из данного скрипта. Все возвращаемые значения являются числами Lua, если не оговорен другой тип.
Вывод:
LoGetModelTime() -- returns current model time (args - 0, results - 1 (sec))
LoGetMissionStartTime() -- returns mission start time (args - 0, results - 1 (sec))
LoGetPilotName() -- (args - 0, results - 1 (text string))
LoGetIndicatedAirSpeed() -- (args - 0, results - 1 (knots))
LoGetTrueAirSpeed() -- (args - 0, results - 1 (knots))
LoGetAltitudeAboveSeaLevel() -- (args - 0, results - 1 (feet))
LoGetAltitudeAboveGroundLevel() -- (args - 0, results - 1 (feet))
LoGetAngleOfAttack() -- (args - 0, results - 1 (degrees))
LoGetAccelerationUnits() -- (args - 0, results - 1 (G))
LoGetVerticalVelocity() -- (args - 0, results - 1(feet per sec))
LoGetADIPitchBankYaw() -- (args - 0, results - 3 (degrees))
LoGetMCPState() -- (args - 0, results - 1 (table of key(string).value(boolean))
returned table keys for LoGetMCPState():
"LeftEngineFailure"
"RightEngineFailure"
"HydraulicsFailure"
"ACSFailure"
"AutopilotFailure"
"AutopilotOn"
"MasterWarning"
"LeftTailPlaneFailure"
"RightTailPlaneFailure"
"LeftAileronFailure"
"RightAileronFailure"
"CanopyOpen"
"CannonFailure"
"StallSignalization"
"LeftMainPumpFailure"
"RightMainPumpFailure"
"LeftWingPumpFailure"
"RightWingPumpFailure"
"RadarFailure"
"EOSFailure"
"MLWSFailure"
"RWSFailure"
"ECMFailure"
"GearFailure"
"MFDFailure"
"HUDFailure"
"HelmetFailure"
"FuelTankDamage"
LoGetWorldObjects() -- (args - 0, results - 1 (table of object tables))
Ввод:
LoSetCommand(command, value) -- (args - 2, results - 0)
-1.0 <= value <= 1.0
Некоторые аналоговые команды (джойстик, TrackIR, мышь):
command = 1 -- Joystick pitch
command = 2 -- Joystick roll
command = 3 -- Joystick rudder
-- Thrust values are inverted for some internal reasons, sorry.
command = 4 -- Joystick thrust (both engines)
command = 5 -- Joystick left engine thrust
command = 6 -- Joystick right engine thrust
command = 7 -- Mouse camera rotate left/right
command = 8 -- Mouse camera rotate up/down
command = 9 -- Mouse camera zoom
command = 10 -- Joystick camera rotate left/right
command = 11 -- Joystick camera rotate up/down
command = 12 -- Joystick camera zoom
command = 13 -- Mouse pitch
command = 14 -- Mouse roll
command = 15 -- Mouse rudder
-- Thrust values are inverted for some internal reasons, sorry.
command = 16 -- Mouse thrust (both engines)
command = 17 -- Mouse left engine thrust
command = 18 -- Mouse right engine thrust
command = 19 -- Mouse trim pitch
command = 20 -- Mouse trim roll
command = 21 -- Mouse trim rudder
command = 22 -- Joystick trim pitch
command = 23 -- Joystick trim roll
command = 24 v Joystick trim rudder
command = 25 -- Mouse rotate radar antenna left/right
command = 26 -- Mouse rotate radar antenna up/down
command = 27 -- Joystick rotate radar antenna left/right
command = 28 -- Joystick rotate radar antenna up/down
command = 29 -- Mouse MFD zoom
command = 30 -- Joystick MFD zoom
command = 31 -- Mouse move selecter left/right
command = 32 -- Mouse move selecter up/down
command = 33 -- Joystick move selecter left/right
command = 34 -- Joystick move selecter up/down
Некоторые дискретные команды (значение отсутствует):
command = 7
command = 8
command = 9
command = 10 -- Ground units view
command = 11 -- Civilian transport view
command = 12 -- Chase view
command = 13 -- Navy view
command = 14 -- Close air combat view
command = 15 -- Theater view
command = 16 -- Airfield (free camera) view
command = 17 -- Instruments panel view on
command = 18 -- Instruments panel view off
command = 19 -- Padlock toggle
command = 20 -- Stop padlock (in cockpit only)
command = 21 -- External view for my plane
command = 22 -- Automatic chase mode for launched weapon
command = 23 -- View allies only filter
command = 24 -- View enemies only filter
command = 26 -- View allies & enemies filter
command = 28 -- Rotate the camera left fast
command = 29 -- Rotate the camera right fast
command = 30 -- Rotate the camera up fast
command = 31 -- Rotate the camera down fast
command = 32 -- Rotate the camera left slow
command = 33 -- Rotate the camera right slow
command = 34 -- Rotate the camera up slow
command = 35 -- Rotate the camera down slow
command = 36 -- Return the camera to default position
command = 37 -- View zoom in fast
command = 38 -- View zoom out fast
command = 39 -- View zoom in slow
command = 40 -- View zoom out slow
command = 41 -- Pan the camera left
command = 42 -- Pan the camera right
command = 43 -- Pan the camera up
command = 44 -- Pan the camera down
command = 45 -- Pan the camera left slow
command = 46 -- Pan the camera right slow
command = 47 -- Pan the camera up slow
command = 48 -- Pan the camera down slow
command = 49 -- Disable panning the camera
command = 50 -- Allies chat
command = 51 -- Mission quit
command = 52 -- Suspend/resume model time
command = 53 -- Accelerate model time
command = 54 -- Step by step simulation when model time is suspended
command = 55 -- Take control in the track
command = 57 -- Common chat
command = 59 -- Altitude stabilization
command = 62 -- Autopilot
command = 63 -- Auto-thrust
command = 64 -- Power up
command = 65 -- Power down
command = 68 -- Gear
command = 69 -- Hook
command = 70 -- Pack wings
command = 71 -- Canopy
command = 72 -- Flaps
command = 73 -- Air brake
command = 74 -- Wheel brakes on
command = 75 -- Wheel brakes off
command = 76 -- Release drogue chute
command = 77 -- Drop snar
command = 78 -- Wingtip smoke
command = 79 -- Refuel on
command = 80 -- Refuel off
command = 81 -- Salvo
command = 82 -- Jettison weapons
command = 83 -- Eject
command = 84 -- Fire on
command = 85 -- Fire off
command = 86 -- Radar
command = 87 -- EOS
command = 88 -- Rotate the radar antenna left
command = 89 -- Rotate the radar antenna right
command = 90 -- Rotate the radar antenna up
command = 91 -- Rotate the radar antenna down
command = 92 -- Center the radar antenna
command = 93 -- Trim left
command = 94 -- Trim right
command = 95 -- Trim up
command = 96 -- Trim down
command = 97 -- Cancel trimming
command = 98 -- Trim the rudder left
command = 99 -- Trim the rudder right
command = 100 -- Lock the target
command = 101 -- Change weapon
command = 102 -- Change target
command = 103 -- MFD zoom in
command = 104 -- MFD zoom out
command = 105 -- Navigation mode
command = 106 -- BVR mode
command = 107 -- VS
command = 108 -- Bore mode
command = 109 -- Helmet mode
command = 110 -- FI0 mode
command = 111 -- A2G mode
command = 112 -- Grid mode
command = 113 -- Cannon
command = 114 -- Dispatch wingman - complete mission and RTB
command = 115 -- Dispatch wingman - complete mission and rejoin
command = 116 -- Dispatch wingman - toggle formation
command = 117 -- Dispatch wingman - join up formation
command = 118 -- Dispatch wingman - attack my target
command = 119 -- Dispatch wingman - cover my six
command = 120 -- Take off from ship
command = 121 -- Cobra
command = 122 -- Sound on/off
command = 123 -- Sound recording on
command = 124 -- Sound recording off
command = 125 -- View right mirror on
command = 126 -- View right mirror off
command = 127 -- View left mirror on
command = 128 -- View left mirror off
command = 129 -- Natural head movement view
command = 131 -- LSO view
command = 135 -- Weapon to target view
command = 136 -- Active jamming
command = 137 -- Increase details level
command = 138 -- Decrease details level
command = 139 -- Scan zone left
command = 140 -- Scan zone right
command = 141 -- Scan zone up
command = 142 -- Scan zone down
command = 143 -- Unlock target
command = 144 -- Reset master warning
command = 145 -- Flaps on
command = 146 -- Flaps off
command = 147 -- Air brake on
command = 148 -- Air brake off
command = 149 -- Weapons view
command = 150 -- Static objects view
command = 151 -- Mission targets view
command = 152 -- Info bar details
command = 155 -- Refueling boom
command = 156 -- HUD color selection
command = 158 -- Jump to terrain view
command = 159 -- Starts moving F11 camera forward
command = 160 -- Starts moving F11 camera backward
command = 161 -- Power up left engine
command = 162 -- Power down left engine
command = 163 -- Power up right engine
command = 164 -- Power down right engine
command = 169 -- Immortal mode
command = 175 -- On-board lights
command = 176 -- Drop snar once
command = 177 -- Default cockpit angle of view
command = 178 -- Jettison fuel tanks
command = 179 -- Wingmen commands panel
command = 180 -- Reverse objects switching in views
command = 181 -- Forward objects switching in views
command = 182 -- Ignore current object in views
command = 183 -- View all ignored objects in views again
command = 184 -- Padlock terrain point
command = 185 -- Reverse the camera
command = 186 -- Plane up
command = 187 -- Plane down
command = 188 -- Bank left
command = 189 -- Bank right
command = 190 -- Local camera rotation mode
command = 191 -- Decelerate model time
command = 192 -- Jump into the other plane
command = 193 -- Nose down
command = 194 -- Nose down end
command = 195 -- Nose up
command = 196 -- Nose up end
command = 197 -- Bank left
command = 198 -- Bank left end
command = 199 -- Bank right
command = 200 -- Bank right end
command = 201 -- Rudder left
command = 202 -- Rudder left end
command = 203 -- Rudder right
command = 204 -- Rudder right end
command = 205 -- View up right
command = 206 -- View down right
command = 207 -- View down left
command = 208 -- View up left
command = 209 -- View stop
command = 210 -- View up right slow
command = 211 -- View down right slow
command = 212 -- View down left slow
command = 213 -- View up left slow
command = 214 -- View stop slow
command = 215 -- Stop trimming
command = 226 -- Scan zone up right
command = 227 -- Scan zone down right
command = 228 -- Scan zone down left
command = 229 -- Scan zone up left
command = 230 -- Scan zone stop
command = 231 -- Radar antenna up right
command = 232 -- Radar antenna down right
command = 233 -- Radar antenna down left
command = 234 -- Radar antenna up left
command = 235 -- Radar antenna stop
command = 236 -- Save snap view angles
command = 237 -- Cockpit panel view toggle
command = 245 -- Coordinates units toggle
command = 246 -- Disable model time acceleration
command = 252 -- Automatic spin recovery
command = 253 -- Speed retention
command = 254 -- Easy landing
command = 258 -- Threat missile padlock
command = 259 -- All missiles padlock
command = 261 -- Marker state
command = 262 -- Decrease radar scan area
command = 263 -- Increase radar scan area
command = 264 -- Marker state plane
command = 265 -- Marker state rocket
command = 266 -- Marker state plane ship
command = 267 -- Ask AWACS home airbase
command = 268 -- Ask AWACS available tanker
command = 269 -- Ask AWACS nearest target
command = 270 -- Ask AWACS declare target
command = 271 -- Easy radar
command = 272 -- Auto lock on nearest aircraft
command = 273 -- Auto lock on center aircraft
command = 274 -- Auto lock on next aircraft
command = 275 -- Auto lock on previous aircraft
command = 276 -- Auto lock on nearest surface target
command = 277 -- Auto lock on center surface target
command = 278 -- Auto lock on next surface target
command = 279 -- Auto lock on previous surface target
command = 280 -- Change cannon rate of fire
command = 281 -- Change ripple quantity
command = 282 -- Change ripple interval
command = 283 -- Switch master arm
command = 284 -- Change release mode
command = 285 -- Change radar mode RWS/TWS
command = 286 -- Change RWR/SPO mode
command = 288 -- Flight clock reset
command = 289 -- Zoom in slow stop
command = 290 -- Zoom out slow stop
command = 291 -- Zoom in stop
command = 292 -- Zoom out stop
command = 295 -- View horizontal stop
command = 296 -- View vertical stop
command = 298 -- Jump to fly-by view
command = 299 -- Camera jiggle
command = 300 -- Cockpit illumination
command = 308 -- Change ripple interval down
command = 309 -- Engines start
command = 310 -- Engines stop
command = 311 -- Left engine start
command = 312 -- Right engine start
command = 313 -- Left engine stop
command = 314 -- Right engine stop
command = 315 -- Power on/off
command = 316 -- Altimeter pressure increase
command = 317 -- Altimeter pressure decrease
command = 318 -- Altimeter pressure stop
command = 321 -- Fast mouse in views
command = 322 -- Slow mouse in views
command = 323 -- Normal mouse in views
command = 326 -- HUD only view
command = 327 -- Recover my plane
command = 328 -- Toggle gear light Near/Far/Off
command = 331 -- Fast keyboard in views
command = 332 -- Slow keyboard in views
command = 333 -- Normal keyboard in views
command = 334 -- Zoom in for external views
command = 335 -- Stop zoom in for external views
command = 336 -- Zoom out for external views
command = 337 -- Stop zoom out for external views
command = 338 -- Default zoom in external views
command = 341 -- A2G combat view
command = 342 -- Camera view up-left
command = 343 -- Camera view up-right
command = 344 -- Camera view down-left
command = 345 -- Camera view down right
command = 346 -- Camera pan mode toggle
command = 347 -- Return the camera
command = 348 -- Trains/cars toggle
command = 349 -- Launch permission override
command = 350 -- Release weapon
command = 351 -- Stop release weapon
command = 352 -- Return camera base
command = 353 -- Camera view up-left slow
command = 354 -- Camera view up-right slow
command = 355 -- Camera view down-left slow
command = 356 -- Camera view down-right slow
command = 357 -- Drop flare once
command = 358 -- Drop chaff once
command = 359 -- Rear view
command = 360 -- Scores window
Продолжение следует...
В версии 1.1 экспортный скрипт значительно изменён и расширен.
Далее приводится текст бета-версии данного скрипта.
-- Data export script for LockOn version 1.1.
-- Copyright (C) 2004, Eagle Dynamics.
-- See http://www.lua.org for Lua script system info
-- We recommend to use the LuaSocket addon (http://www.tecgraf.puc-rio.br/luasocket)
-- to use standard network protocols in Lua scripts.
-- LuaSocket 2.0 Beta files (*.dll and *.lua) are supplied in the Scripts/LuaSocket folder
-- and in the installation folder of the LockOn version 1.1.
-- Expand the functionality of following functions for your external application needs.
-- Look into ./Temp/Error.log for this script errors, please.
-- Uncomment this function to enable data export!
--[[
function LuaExportStart()
-- Works once just before mission start.
-- Make initializations of your files or connections here.
-- For example:
-- 1) File
-- local file = io.open("./Temp/Export.log", "w")
-- if file then
-- io.output(file)
-- end
-- 2) Socket
-- dofile "lua.lua"
-- socket = require("socket")
-- host = host or "localhost"
-- port = port or 8080
-- c = socket.try(socket.connect(host, port)) -- connect to the listener socket
-- c:setoption("tcp-nodelay",true) -- set immediate transmission mode
end
--]]
function LuaExportBeforeNextFrame()
-- Works just before every simulation frame.
-- Call Lo*() functions to set data to LockOn here
-- For example:
-- LoSetCommand(3, 0.25) -- rudder 0.25 right
-- LoSetCommand(64) -- increase thrust
end
function LuaExportAfterNextFrame()
-- Works just after every simulation frame.
-- Call Lo*() functions to get data from LockOn here.
-- For example:
-- local t = LoGetModelTime()
-- local name = LoGetPilotName()
-- local altBar = LoGetAltitudeAboveSeaLevel()
-- local altRad = LoGetAltitudeAboveGroundLevel()
-- local pitch, bank, yaw = LoGetADIPitchBankYaw()
-- local engine = LoGetEngineInfo()
-- local HSI = LoGetControlPanel_HSI()
-- Then send data to your file or to your receiving program:
-- 1) File
-- io.write(string.format("t = %.2f, name = %s, altBar = %.2f, altRad = %.2f, pitch = %.2f, bank = %.2f, yaw = %.2fn", t, name, altBar, altRad, 57.3*pitch, 57.3*bank, 57.3*yaw))
-- io.write(string.format("t = %.2f ,RPM left = %f fuel = %f n",t,engine.RPM.left,engine.fuel))
-- io.write(string.format("ADF = %f RMI = %fn ",57.3*HSI.ADF,57.3*HSI.RMI))
-- 2) Socket
-- socket.try(c:send(string.format("t = %.2f, name = %s, altBar = %.2f, alrRad = %.2f, pitch = %.2f, bank = %.2f, yaw = %.2fn", t, name, altRad, altBar, pitch, bank, yaw)))
end
function LuaExportStop()
-- Works once just after mission stop.
-- Close files and/or connections here.
-- For example:
-- 1) File
-- io.close()
-- 2) Socket
-- socket.try(c:send("quit")) -- to close the listener socket
-- c:close()
end
function LuaExportActivityNextEvent(t)
local tNext = t
-- Put your event code here and increase tNext for the next event
-- so this function will be called automatically at your custom
-- model times.
-- If tNext == t then the activity will be terminated.
-- For example:
-- 1) File
-- local o = LoGetWorldObjects()
-- for k,v in pairs(o) do
-- io.write(string.format("t = %.2f, ID = %d, name = %s, country = %s(%s), LatLongAlt = (%f, %f, %f), heading = %fn", t, k, v.Name, v.Country, v.Coalition, v.LatLongAlt.Lat, v.LatLongAlt.Long, v.LatLongAlt.Alt, v.Heading))
-- end
-- local trg = LoGetLockedTargetInformation()
-- io.write(string.format("locked targets ,time = %.2fn",t))
-- for i,cur in pairs(trg) do
-- io.write(string.format("ID = %d, position = (%f,%f,%f) , V = (%f,%f,%f), flags = 0x%xn", cur.ID,cur.position.p.x, cur.position.p.y, cur.position.p.z, cur.velocity.x, cur.velocity.y,cur.velocity.z, cur.flags))
-- end
-- local route = LoGetRoute()
-- io.write(string.format("t = %fn",t))
-- if route then
-- io.write(string.format("Goto_point :n point_num = %d ,wpt_pos = (%f, %f ,%f) ,next %dn",route.goto_point.this_point_num,route.goto_point.world_point.x,route. goto_point.world_point.y,route.goto_point.world_point.z,route.goto_point.next_point_num))
-- io.write(string.format("Route points:n"))
-- for num,wpt in pairs(route.route) do
-- io.write(string.format("point_num = %d ,wpt_pos = (%f, %f ,%f) , next %dn", wpt.this_point_num, wpt.world_point.x, wpt.world_point.y, wpt.world_point.z, wpt.next_point_num))
-- end
-- end
-- tNext = tNext + 1.0
-- 2) Socket
-- local o = LoGetWorldObjects()
-- for k,v in pairs(o) do
-- socket.try(c:send(string.format("t = %.2f, ID = %d, name = %s, country = %s(%s), LatLongAlt = (%f, %f, %f), heading = %fn", t, k, v.Name, v.Country, v.Coalition, v.LatLongAlt.x, v.LatLongAlt.Long, v.LatLongAlt.Alt, v.Heading)))
-- end
-- tNext = tNext + 1.0
return tNext
end
--[[ You can use registered LockOn internal data exporting functions in this script
and in your scripts called from this script.
Note: following functions are implemented for exporting technology experiments only,
so they may be changed or removed in the future by developers.
All returned values are Lua numbers if not pointed other type.
Output:
LoGetModelTime() -- returns current model time (args - 0, results - 1 (sec))
LoGetMissionStartTime() -- returns mission start time (args - 0, results - 1 (sec))
LoGetPilotName() -- (args - 0, results - 1 (text string))
LoGetPlayerPlaneId() -- (args - 0, results - 1 (number))
LoGetIndicatedAirSpeed() -- (args - 0, results - 1 (m/s))
LoGetTrueAirSpeed() -- (args - 0, results - 1 (m/s))
LoGetAltitudeAboveSeaLevel() -- (args - 0, results - 1 (meters))
LoGetAltitudeAboveGroundLevel() -- (args - 0, results - 1 (meterst))
LoGetAngleOfAttack() -- (args - 0, results - 1 (rad))
LoGetAccelerationUnits() -- (args - 0, results - 1 (G))
LoGetVerticalVelocity() -- (args - 0, results - 1(m/s))
LoGetADIPitchBankYaw() -- (args - 0, results - 3 (rad))
LoGetMagneticYaw() -- (args - 0, results - 1 (rad)
LoGetGlideDeviation() -- (args - 0,results - 1)( -1 < result < 1)
LoGetSideDeviation() -- (args - 0,results - 1)( -1 < result < 1)
LoGetSlipBallPosition() -- (args - 0,results - 1)( -1 < result < 1)
LoGetBasicAtmospherePressure() -- (args - 0,results - 1) (mm hg)
LoGetControlPanel_HSI() -- (args - 0,results - table)
result =
{
ADF , (rad)
RMI , (rad)
Compass,(rad)
}
LoGetEngineInfo() -- (args - 0 ,results = table)
engineinfo =
{
RPM = {left, right},(%)
Temperature = { left, right}, (Celcium degrees)
HydraulicPressure = {left ,right},kg per square centimeter
fuel X -- fuel quantity kg
}
LoGetRoute() -- (args - 0,results = table)
get_route_result =
{
goto_point, -- next waypoint
route -- all waypoints of route (or approach route if arrival or landing)
}
waypoint_table =
{
this_point_num, -- number of point ( >= 0)
world_point = {x,y,z}, -- world position in meters
speed_req, -- speed at point m/s
estimated_time, -- sec
next_point_num, -- if -1 that's the end of route
}
LoGetMCPState() -- (args - 0, results - 1 (table of key(string).value(boolean))
returned table keys for LoGetMCPState():
"LeftEngineFailure"
"RightEngineFailure"
"HydraulicsFailure"
"ACSFailure"
"AutopilotFailure"
"AutopilotOn"
"MasterWarning"
"LeftTailPlaneFailure"
"RightTailPlaneFailure"
"LeftAileronFailure"
"RightAileronFailure"
"CanopyOpen"
"CannonFailure"
"StallSignalization"
"LeftMainPumpFailure"
"RightMainPumpFailure"
"LeftWingPumpFailure"
"RightWingPumpFailure"
"RadarFailure"
"EOSFailure"
"MLWSFailure"
"RWSFailure"
"ECMFailure"
"GearFailure"
"MFDFailure"
"HUDFailure"
"HelmetFailure"
"FuelTankDamage"
LoGetObjectById() -- (args - 1 (number), results - 1 (table))
Returned object table structure:
{
Name =
Type =
Subtype =
Country =
Coalition =
LatLongAlt = { Lat = , Long = , Alt = }
Heading =
Object types:
Air = 1 (Subtypes: Airplane = 1, Helicopter = 2)
Ground = 2 (Subtypes: Moving = 8, Standing = 9, Tank = 17, SAM = 16)
Navy = 3 (Subtypes: Ship = 12)
Weapon = 4 (Subtypes: Missile = 4, Bomb = 5, Shell = 6, Rocket = 7)
Static = 5 (Subtypes: Airdrome = 13)
LoGetWorldObjects() -- (args - 0, results - 1 (table of object tables))
Returned table index = object identificator
Returned object table structure (see LoGetObjectById())
-- Weapon Control System
LoGetTargetInformation() -- (args - 0, results - 1 (table of current targets tables))
LoGetLockedTargetInformation() -- (args - 0, results - 1 (table of current locked targets tables))
this functions return the table of the next target data
target =
{
ID , X -- world ID (may be 0 ,when ground point track)
type = {level1,level2,level3,level4}, -- world database classification
country = , -- object country
position = {x = {x,y,z}, -- orientation X ort
y = {x,y,z}, -- orientation Y ort
z = {x,y,z}, -- orientation Z ort
p = {x,y,z}} -- position of the center
velocity = {x,y,z}, -- world velocity vector m/s
distance = , -- distance in meters
convergence_velocity = , -- closing speed in m/s
mach = , -- M number
delta_psi = , -- aspect angle rad
fim = , -- viewing angle horizontal (in your body axis) rad
fin = , -- viewing angle vertical (in your body axis) rad
flags = , -- field with constants detemining method of the tracking
-- whTargetRadarView
-- whTargetEOSView
-- whTargetRadarLock
-- whTargetEOSLock
-- whTargetRadarTrack
-- whTargetEOSTrack
-- whTargetNetHumanPlane = 0x0200;
-- whTargetAutoLockOn = 0x0400;
-- whTargetLockOnJammer = 0x0800;
reflection = , -- target cross section square meters
course = , -- target course rad
isjamming = , -- target ECM on or not
start_of_lock = , -- time of the beginning of lock
forces = { x,y,z}, -- vector of the acceleration units
updates_number = , -- number of the radar updates
}
Input:
LoSetCommand(command, value) -- (args - 2, results - 0)
-1.0 <= value <= 1.0
Some analogous joystick/mouse input commands:
command = 1 - joystick pitch
command = 2 - joystick roll
command = 3 - joystick rudder
-- Thrust values are inverted for some internal reasons, sorry.
command = 4 - joystick thrust (both engines)
command = 5 - joystick left engine thrust
command = 6 - joystick right engine thrust
command = 7 - mouse camera rotate left/right
command = 8 - mouse camera rotate up/down
command = 9 - mouse camera zoom
command = 10 - joystick camera rotate left/right
command = 11 - joystick camera rotate up/down
command = 12 - joystick camera zoom
command = 13 - mouse pitch
command = 14 - mouse roll
command = 15 - mouse rudder
-- Thrust values are inverted for some internal reasons, sorry.
command = 16 - mouse thrust (both engines)
command = 17 - mouse left engine thrust
command = 18 - mouse right engine thrust
command = 19 - mouse trim pitch
command = 20 - mouse trim roll
command = 21 - mouse trim rudder
command = 22 - joystick trim pitch
command = 23 - joystick trim roll
command = 24 - trim rudder
command = 25 - mouse rotate radar antenna left/right
command = 26 - mouse rotate radar antenna up/down
command = 27 - joystick rotate radar antenna left/right
command = 28 - joystick rotate radar antenna up/down
command = 29 - mouse MFD zoom
command = 30 - joystick MFD zoom
command = 31 - mouse move selecter left/right
command = 32 - mouse move selecter up/down
command = 33 - joystick move selecter left/right
command = 34 - joystick move selecter up/down
-- Some discrete keyboard input commands (value is absent):
command = 7 -- Cockpit view
command = 8 -- External
command = 9 -- Fly-by view
command = 10 -- Ground units view
command = 11 -- Civilian transport view
command = 12 -- Chase view
command = 13 -- Navy view
command = 14 -- Close air combat view
command = 15 -- Theater view
command = 16 -- Airfield (free camera) view
command = 17 -- Instruments panel view on
command = 18 -- Instruments panel view off
command = 19 -- Padlock toggle
command = 20 -- Stop padlock (in cockpit only)
command = 21 -- External view for my plane
command = 22 -- Automatic chase mode for launched weapon
command = 23 -- View allies only filter
command = 24 -- View enemies only filter
command = 26 -- View allies & enemies filter
command = 28 -- Rotate the camera left fast
command = 29 -- Rotate the camera right fast
command = 30 -- Rotate the camera up fast
command = 31 -- Rotate the camera down fast
command = 32 -- Rotate the camera left slow
command = 33 -- Rotate the camera right slow
command = 34 -- Rotate the camera up slow
command = 35 -- Rotate the camera down slow
command = 36 -- Return the camera to default position
command = 37 -- View zoom in fast
command = 38 -- View zoom out fast
command = 39 -- View zoom in slow
command = 40 -- View zoom out slow
command = 41 -- Pan the camera left
command = 42 -- Pan the camera right
command = 43 -- Pan the camera up
command = 44 -- Pan the camera down
command = 45 -- Pan the camera left slow
command = 46 -- Pan the camera right slow
command = 47 -- Pan the camera up slow
command = 48 -- Pan the camera down slow
command = 49 -- Disable panning the camera
command = 50 -- Allies chat
command = 51 -- Mission quit
command = 52 -- Suspend/resume model time
command = 53 -- Accelerate model time
command = 54 -- Step by step simulation when model time is suspended
command = 55 -- Take control in the track
command = 57 -- Common chat
command = 59 -- Altitude stabilization
command = 62 -- Autopilot
command = 63 -- Auto-thrust
command = 64 -- Power up
command = 65 -- Power down
command = 68 -- Gear
command = 69 -- Hook
command = 70 -- Pack wings
command = 71 -- Canopy
command = 72 -- Flaps
command = 73 -- Air brake
command = 74 -- Wheel brakes on
command = 75 -- Wheel brakes off
command = 76 -- Release drogue chute
command = 77 -- Drop snar
command = 78 -- Wingtip smoke
command = 79 -- Refuel on
command = 80 -- Refuel off
command = 81 -- Salvo
command = 82 -- Jettison weapons
command = 83 -- Eject
command = 84 -- Fire on
command = 85 -- Fire off
command = 86 -- Radar
command = 87 -- EOS
command = 88 -- Rotate the radar antenna left
command = 89 -- Rotate the radar antenna right
command = 90 -- Rotate the radar antenna up
command = 91 -- Rotate the radar antenna down
command = 92 -- Center the radar antenna
command = 93 -- Trim left
command = 94 -- Trim right
command = 95 -- Trim up
command = 96 -- Trim down
command = 97 -- Cancel trimming
command = 98 -- Trim the rudder left
command = 99 -- Trim the rudder right
command = 100 -- Lock the target
command = 101 -- Change weapon
command = 102 -- Change target
command = 103 -- MFD zoom in
command = 104 -- MFD zoom out
command = 105 -- Navigation mode
command = 106 -- BVR mode
command = 107 -- VS mode
command = 108 -- Bore mode
command = 109 -- Helmet mode
command = 110 -- FI0 mode
command = 111 -- A2G mode
command = 112 -- Grid mode
command = 113 -- Cannon
command = 114 -- Dispatch wingman - complete mission and RTB
command = 115 -- Dispatch wingman - complete mission and rejoin
command = 116 -- Dispatch wingman - toggle formation
command = 117 -- Dispatch wingman - join up formation
command = 118 -- Dispatch wingman - attack my target
command = 119 -- Dispatch wingman - cover my six
command = 120 -- Take off from ship
command = 121 -- Cobra
command = 122 -- Sound on/off
command = 123 -- Sound recording on
command = 124 -- Sound recording off
command = 125 -- View right mirror on
command = 126 -- View right mirror off
command = 127 -- View left mirror on
command = 128 -- View left mirror off
command = 129 -- Natural head movement view
command = 131 -- LSO view
command = 135 -- Weapon to target view
command = 136 -- Active jamming
command = 137 -- Increase details level
command = 138 -- Decrease details level
command = 139 -- Scan zone left
command = 140 -- Scan zone right
command = 141 -- Scan zone up
command = 142 -- Scan zone down
command = 143 -- Unlock target
command = 144 -- Reset master warning
command = 145 -- Flaps on
command = 146 -- Flaps off
command = 147 -- Air brake on
command = 148 -- Air brake off
command = 149 -- Weapons view
command = 150 -- Static objects view
command = 151 -- Mission targets view
command = 152 -- Info bar details
command = 155 -- Refueling boom
command = 156 -- HUD color selection
command = 158 -- Jump to terrain view
command = 159 -- Starts moving F11 camera forward
command = 160 -- Starts moving F11 camera backward
command = 161 -- Power up left engine
command = 162 -- Power down left engine
command = 163 -- Power up right engine
command = 164 -- Power down right engine
command = 169 -- Immortal mode
command = 175 -- On-board lights
command = 176 -- Drop snar once
command = 177 -- Default cockpit angle of view
command = 178 -- Jettison fuel tanks
command = 179 -- Wingmen commands panel
command = 180 -- Reverse objects switching in views
command = 181 -- Forward objects switching in views
command = 182 -- Ignore current object in views
command = 183 -- View all ignored objects in views again
command = 184 -- Padlock terrain point
command = 185 -- Reverse the camera
command = 186 -- Plane up
command = 187 -- Plane down
command = 188 -- Bank left
command = 189 -- Bank right
command = 190 -- Local camera rotation mode
command = 191 -- Decelerate model time
command = 192 -- Jump into the other plane
command = 193 -- Nose down
command = 194 -- Nose down end
command = 195 -- Nose up
command = 196 -- Nose up end
command = 197 -- Bank left
command = 198 -- Bank left end
command = 199 -- Bank right
command = 200 -- Bank right end
command = 201 -- Rudder left
command = 202 -- Rudder left end
command = 203 -- Rudder right
command = 204 -- Rudder right end
command = 205 -- View up right
command = 206 -- View down right
command = 207 -- View down left
command = 208 -- View up left
command = 209 -- View stop
command = 210 -- View up right slow
command = 211 -- View down right slow
command = 212 -- View down left slow
command = 213 -- View up left slow
command = 214 -- View stop slow
command = 215 -- Stop trimming
command = 226 -- Scan zone up right
command = 227 -- Scan zone down right
command = 228 -- Scan zone down left
command = 229 -- Scan zone up left
command = 230 -- Scan zone stop
command = 231 -- Radar antenna up right
command = 232 -- Radar antenna down right
command = 233 -- Radar antenna down left
command = 234 -- Radar antenna up left
command = 235 -- Radar antenna stop
command = 236 -- Save snap view angles
command = 237 -- Cockpit panel view toggle
command = 245 -- Coordinates units toggle
command = 246 -- Disable model time acceleration
command = 252 -- Automatic spin recovery
command = 253 -- Speed retention
command = 254 -- Easy landing
command = 258 -- Threat missile padlock
command = 259 -- All missiles padlock
command = 261 -- Marker state
command = 262 -- Decrease radar scan area
command = 263 -- Increase radar scan area
command = 264 -- Marker state plane
command = 265 -- Marker state rocket
command = 266 -- Marker state plane ship
command = 267 -- Ask AWACS home airbase
command = 268 -- Ask AWACS available tanker
command = 269 -- Ask AWACS nearest target
command = 270 -- Ask AWACS declare target
command = 271 -- Easy radar
command = 272 -- Auto lock on nearest aircraft
command = 273 -- Auto lock on center aircraft
command = 274 -- Auto lock on next aircraft
command = 275 -- Auto lock on previous aircraft
command = 276 -- Auto lock on nearest surface target
command = 277 -- Auto lock on center surface target
command = 278 -- Auto lock on next surface target
command = 279 -- Auto lock on previous surface target
command = 280 -- Change cannon rate of fire
command = 281 -- Change ripple quantity
command = 282 -- Change ripple interval
command = 283 -- Switch master arm
command = 284 -- Change release mode
command = 285 -- Change radar mode RWS/TWS
command = 286 -- Change RWR/SPO mode
command = 288 -- Flight clock reset
command = 289 -- Zoom in slow stop
command = 290 -- Zoom out slow stop
command = 291 -- Zoom in stop
command = 292 -- Zoom out stop
command = 295 -- View horizontal stop
command = 296 -- View vertical stop
command = 298 -- Jump to fly-by view
command = 299 -- Camera jiggle
command = 300 -- Cockpit illumination
command = 308 -- Change ripple interval down
command = 309 -- Engines start
command = 310 -- Engines stop
command = 311 -- Left engine start
command = 312 -- Right engine start
command = 313 -- Left engine stop
command = 314 -- Right engine stop
command = 315 -- Power on/off
command = 316 -- Altimeter pressure increase
command = 317 -- Altimeter pressure decrease
command = 318 -- Altimeter pressure stop
command = 321 -- Fast mouse in views
command = 322 -- Slow mouse in views
command = 323 -- Normal mouse in views
command = 326 -- HUD only view
command = 327 -- Recover my plane
command = 328 -- Toggle gear light Near/Far/Off
command = 331 -- Fast keyboard in views
command = 332 -- Slow keyboard in views
command = 333 -- Normal keyboard in views
command = 334 -- Zoom in for external views
command = 335 -- Stop zoom in for external views
command = 336 -- Zoom out for external views
command = 337 -- Stop zoom out for external views
command = 338 -- Default zoom in external views
command = 341 -- A2G combat view
command = 342 -- Camera view up-left
command = 343 -- Camera view up-right
command = 344 -- Camera view down-left
command = 345 -- Camera view down right
command = 346 -- Camera pan mode toggle
command = 347 -- Return the camera
command = 348 -- Trains/cars toggle
command = 349 -- Launch permission override
command = 350 -- Release weapon
command = 351 -- Stop release weapon
command = 352 -- Return camera base
command = 353 -- Camera view up-left slow
command = 354 -- Camera view up-right slow
command = 355 -- Camera view down-left slow
command = 356 -- Camera view down-right slow
command = 357 -- Drop flare once
command = 358 -- Drop chaff once
command = 359 -- Rear view
command = 360 -- Scores window
command = 386 -- PlaneStabPitchBank
command = 387 -- PlaneStabHbarBank
command = 388 -- PlaneStabHorizont
command = 389 -- PlaneStabHbar
command = 390 -- PlaneStabHrad
command = 391 -- Active IR jamming on/off
command = 392 -- Laser range-finder on/off
command = 393 -- Night TV on/off(IR or LLTV)
command = 394 -- Change radar PRF
command = 395 -- Keep F11 camera altitude over terrain
command = 396 -- SnapView0
command = 397 -- SnapView1
command = 398 -- SnapView2
command = 399 -- SnapView3
command = 400 -- SnapView4
command = 401 -- SnapView5
command = 402 -- SnapView6
command = 403 -- SnapView7
command = 404 -- SnapView8
command = 405 -- SnapView9
command = 406 -- SnapViewStop
command = 407 -- F11 view binocular mode
command = 408 -- PlaneStabCancel
command = 409 -- ThreatWarnSoundVolumeDown
command = 410 -- ThreatWarnSoundVolumeUp
command = 411 -- F11 binocular view laser illumination on/off
command = 412 -- PlaneIncreaseBase_Distance
command = 413 -- PlaneDecreaseBase_Distance
command = 414 -- PlaneStopBase_Distance
command = 415 -- F11 binocular view range-finder on
command = 416 -- F11 view range-finder off
command = 425 -- F11 binocular view IR mode on/off
command = 426 -- F8 view player targets / all targets
command = 427 -- Plane autopilot override on
command = 428 -- Plane autopilot override off
To be continued...
--]]
Начиная с версии 1.12, LockOn поддерживает сопрограммы Lua с помощью внутренней функции LoCreateCoroutineActivity(), доступной из экспортного lua_State, и скриптовой функции CoroutineResume(), определённой в файле Config/Export/Export.lua. Далее приводятся фрагменты из данного файла, относящиеся к поддержке сопрограмм:
Глобальная таблица сопрограмм:
Coroutines = {}
Глобальный индекс последней созданной сопрограммы:
CoroutineIndex = 0
Данная функция будет вызываться модельным таймером LockOnа для продолжения работы сопрограммы и выяснения её статуса
function CoroutineResume(index, tCurrent)
coroutine.resume(Coroutines[index], tCurrent)
return coroutine.status(Coroutines[index]) ~= "dead"
end
Пример функции, работающей в режиме сопрограммы, с использованием coroutine.yield() для приостановки выполнения и приёма значения текущего модельного времени.
function f(t)
local tNext = t
local file = io.open("./Temp/Coroutine.log", "w")
io.output(file)
io.write(string.format("t = %f, started\n", tNext))
tNext = coroutine.yield()
for i = 1,10 do
io.write(string.format("t = %f, continued\n", tNext))
tNext = coroutine.yield()
end
io.write(string.format("t = %f, finished\n", tNext))
io.close()
end
Создаём сопрограмму и запоминаем её в таблице сопрограмм под соответствующим индексом:
CoroutineIndex = CoroutineIndex + 1
Coroutines[CoroutineIndex] = coroutine.create(f)
Планируем выполнение сопрограммы, начиная с секунды 1.0, с последующим продолжением с периодом в 3.0 секунды:
LoCreateCoroutineActivity(CoroutineIndex, 1.0, 3.0)
Результаты работы сопрограммы в файле Temp/Coroutine.log:
t = 1.000000, started
t = 4.000000, continued
t = 7.000000, continued
t = 10.000000, continued
t = 13.000000, continued
t = 16.000000, continued
t = 19.000000, continued
t = 22.000000, continued
t = 25.000000, continued
t = 28.000000, continued
t = 31.000000, continued
t = 34.000000, finished
Таким образом, с помощью описанных средств предоставляется возможность использовать скрипты Lua, не опасаясь заметных притормаживаний, характерных для сложных интерпретируемых программ. Можно как-бы равномерно "размазать" выполнение сопрограммы Lua по модельному времени симулятора с заданным периодом.
|