···11+# These are supported funding model platforms
22+33+github: Jericho1060
44+patreon: # Replace with a single Patreon username
55+open_collective: # Replace with a single Open Collective username
66+ko_fi: jericho1060
77+tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
88+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
99+liberapay: # Replace with a single Liberapay username
1010+issuehunt: # Replace with a single IssueHunt username
1111+otechie: # Replace with a single Otechie username
1212+custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+57
README.MD
···11+# DU-ELEVATOR
22+33+A Generic Elevator script for Dual universe
44+55+# Guilded Server (better than Discord)
66+77+You can join me on Guilded for help or suggestions or requests by following that link : https://guilded.jericho.dev
88+99+# Discord Server
1010+1111+You can join me on Discord for help or suggestions or requests by following that link : https://discord.gg/qkdjyqDZQZ
1212+1313+# Instalation
1414+1515+### Important notice
1616+1717+- the script was only tested on a remote control
1818+1919+### Links
2020+2121+You must link the following elements to the remote control (order doesn't matter, the script will detect them automatically):
2222+- Link the core to the remote control
2323+- Link the fuel tank to the remote control (only if you want to see the fuel gauge)
2424+2525+### Setup
2626+2727+- you need at least a vertical engine pointing the bottom
2828+- you need at least one engine on each horizontal direction (forward, right, left, backward)
2929+- you need at least 3 adjustors on each angles of the construct : (see picture below)
3030+ - one pointing up (this one is used for autoroll and autopitch)
3131+ - one pointing on one side (this one is used for autoyaw)
3232+ - one pointing on the orther side of the angle (this one is used for autoyaw)
3333+ - 
3434+3535+### Installation of the script
3636+3737+- copy the content of the config.json file and paste it on the remote control (right click on the remote control -> advanced -> paste lua configuration from clipboard)
3838+3939+### Lua parameters
4040+4141+- `DEBUG` : if set to true, the script will print debug messages in the chat
4242+- `BaseAltitude` : the default altitude of the elevator when landed on the floor
4343+- `StrafeSpeedFactor` : the speed multiplier when strafing. adjust it depending on how many engines you have on the sides
4444+4545+### Usage
4646+4747+- open the "lua" chat channel and type `goto:<altitude>` to go to the specified altitude with `<altitude>` the altitude in meters, if the altitude is missing or invalid, it will send you the `BaseAltitude`
4848+4949+# Coming Soon
5050+5151+- Bookmark system: you will be able to name and store your favorite floors and go to them with a key press
5252+- support for emitter to be able to send a signal to a specific channel to close a door to lock the elevator in position
5353+- dedicated HUD with more informations and with some customizations possible (AR View of the position of the elevator, custom fuel gauge, etc...)
5454+5555+# Support or donation
5656+5757+if you like it, [<img src="https://github.com/Jericho1060/DU-Industry-HUD/blob/main/ressources/images/ko-fi.png?raw=true" width="150">](https://ko-fi.com/jericho1060)
···11+--[[
22+ DU-ELEVATOR by Jericho
33+]]
44+55+__DEBUG = false --export: Debug mode, will print more information in the console
66+77+--[[
88+ Version Management
99+]]
1010+1111+local version = "V 1.0.0"
1212+local log_split = "================================================="
1313+--printing version in lua chat
1414+system.print(log_split)local a=""local b=math.ceil((50-#version-2)/2)for c=1,b,1 do a=a..'='end;a=a.." "..version.." "for c=1,b,1 do a=a..'='end;system.print(a)system.print(log_split)
1515+1616+--[[
1717+ Detecting elements linked
1818+]]
1919+core = nil
2020+fuelTanks = {}
2121+2222+for slot_name, slot in pairs(unit) do
2323+ if
2424+ type(slot) == "table"
2525+ and type(slot.export) == "table"
2626+ and slot.getClass
2727+ then
2828+ local class = slot.getClass():lower()
2929+ if class:find("coreunit") then
3030+ core = slot
3131+ elseif class:find("fuelcontainer") then
3232+ table.insert(fuelTanks, slot)
3333+ end
3434+ end
3535+end
3636+3737+--[[
3838+ stopping the script if required elements are not linked
3939+]]
4040+if core == nil then
4141+ system.print('Core unit is not linked, exiting the script')
4242+ unit.exit()
4343+end
4444+4545+--[[
4646+ Default Unit Start Mechanics
4747+]]
4848+pitchInput = 0
4949+pitchInputFromDevice = 0
5050+rollInput = 0
5151+yawInput = 0
5252+verticalStrafeInput = 0
5353+lateralStrafeInput = 0
5454+brakeInput = 1 --braking by default
5555+goingBack = false
5656+goingForward = false
5757+shiftPressed = false
5858+jumpDelta = 0
5959+baseAcceleration = 0.8
6060+6161+Nav = Navigator.new(system, core, unit)
6262+Nav.axisCommandManager:setupCustomTargetSpeedRanges(axisCommandId.longitudinal, {100, 500, 1000, 2000,3000, 5000})
6363+Nav.axisCommandManager:setTargetGroundAltitude(0)
6464+unit.deactivateGroundEngineAltitudeStabilization()
6565+6666+-- Parenting widget
6767+parentingPanelId = system.createWidgetPanel("Docking")
6868+parentingWidgetId = system.createWidget(parentingPanelId,"parenting")
6969+system.addDataToWidget(unit.getWidgetDataId(),parentingWidgetId)
7070+7171+-- Fuel widget generation (Updated code By Jericho)
7272+--TODO: replace by custom HUD
7373+if (#fuelTanks > 0) then
7474+ fuelTankPanelId = system.createWidgetPanel("Fuel Tanks")
7575+ fuelTankWidgetId = system.createWidget(fuelTankPanelId,"fuel_container")
7676+ for _,tank in pairs(fuelTanks) do
7777+ system.addDataToWidget(tank.getWidgetDataId(),fuelTankWidgetId)
7878+ end
7979+end
8080+8181+--[[
8282+ Storing base position and orientation of the elevator
8383+]]
8484+ConstructInitPos = construct.getWorldPosition()
8585+--replace that pos by a hand written value to be sure the construct will always realign the same position
8686+--ConstructInitPos = {-1231538.185042, 1201297.6879598, -2617220.2766464}
8787+if __DEBUG then system.print('ConstructInitPos: ' .. json.encode(ConstructInitPos)) end
8888+BaseForward = vec3(construct.getWorldForward())
8989+if __DEBUG then system.print('BaseForward: ' .. json.encode(BaseForward)) end
9090+BaseAltitute = 285 --export: the start altitude of the elevator (lower position altitude)
9191+9292+--TODO: to replace with a computing in flush from the current acceleration and the friction acceleration (construct.getWorldAirFrictionAcceleration)
9393+MaxSpeed = construct.getFrictionBurnSpeed() -- for security to avoid burning if going too fast
9494+if __DEBUG then system.print('MaxSpeed: ' .. MaxSpeed) end
9595+9696+--init a value to store the target altitude
9797+TargetAltitude = core.getAltitude() --by default to the start altitude to avoid falling down if in the air
9898+9999+--[[
100100+ Kinematics functions by Jaylebreak
101101+ Source available at https://gitlab.com/JayleBreak/dualuniverse/-/blob/master/DUflightfiles/autoconf/custom/kinematics.lua
102102+]]
103103+function computeAccelerationTime(initial, acceleration, final) return (final - initial)/acceleration end
104104+function computeDistanceAndTime(initial, final, mass, thrust, t50, brakeThrust)
105105+ t50 = t50 or 0
106106+ brakeThrust = brakeThrust or 0
107107+ local speedUp = initial < final
108108+ local a0 = thrust / (speedUp and mass or -mass)
109109+ local b0 = -brakeThrust/mass
110110+ local totA = a0+b0
111111+ if initial == final then
112112+ return 0, 0
113113+ elseif speedUp and totA <= 0 or not speedUp and totA >= 0 then
114114+ return -1, -1
115115+ end
116116+ local distanceToMax, timeToMax = 0, 0
117117+ if a0 ~= 0 and t50 > 0 then
118118+ local c1 = math.pi/t50/2
119119+ local v = function(t)
120120+ return a0*(t/2 - t50*math.sin(c1*t)/math.pi) + b0*t + initial
121121+ end
122122+ local speedchk = speedUp and function(s) return s >= final end or function(s) return s <= final end
123123+ timeToMax = 2*t50
124124+ if speedchk(v(timeToMax)) then
125125+ local lasttime = 0
126126+ while math.abs(timeToMax - lasttime) > 0.25 do
127127+ local t = (timeToMax + lasttime)/2
128128+ if speedchk(v(t)) then
129129+ timeToMax = t
130130+ else
131131+ lasttime = t
132132+ end
133133+ end
134134+ end
135135+ local K = 2*a0*t50^2/math.pi^2
136136+ distanceToMax = K*(math.cos(c1*timeToMax) - 1) + (a0+2*b0)*timeToMax^2/4 + initial*timeToMax
137137+ if timeToMax < 2*t50 then
138138+ return distanceToMax, timeToMax
139139+ end
140140+ initial = v(timeToMax)
141141+ end
142142+ local a = a0+b0
143143+ local t = computeAccelerationTime(initial, a, final)
144144+ local d = initial*t + a*t*t/2
145145+ return distanceToMax+d, timeToMax+t
146146+end
147147+148148+--[[
149149+ Commpute angle betwwen vectors by Jericho
150150+]]
151151+function signedAngleBetween(vec1, vec2, planeNormal)
152152+ local normVec1 = vec1:project_on_plane(planeNormal):normalize()
153153+ local normVec2 = vec2:normalize()
154154+ local v1v2dot = normVec1:dot(normVec2)
155155+ local angle = math.acos(utils.clamp(v1v2dot,-1,1))
156156+ local crossProduct = vec1:cross(vec2)
157157+ if crossProduct:dot(planeNormal) < 0 then
158158+ return -angle
159159+ end
160160+ return angle
161161+end
162162+163163+--[[
164164+ DU-LUA-Framework by Jericho
165165+ Permit to code easier by grouping most of the code in a single event Unit > Start
166166+ Unminified Source available here: https://github.com/Jericho1060/du-lua-framework
167167+]]--
168168+local a=system.print;local b=error;local c=pcall;local d=assert;local e=coroutine;local f=e.create;local g=e.status;local h=e.resume;local i="dead"local j="suspended"function runFunction(k,l,...)local m,n=c(k,...)if not m then b(l..n)end end;local o={__index={cos={update={},flush={}},fns={update={},flush={},action={start={},stop={},loop={}},inputText=nil,start=nil,stop=nil},ACTIONS={FORWARD="forward",BACKWARD="backward",YAW_LEFT="yawleft",YAW_RIGHT="yawright",STRAFE_LEFT="strafeleft",STRAFE_RIGHT="straferight",LEFT="left",RIGHT="right",UP="up",DOWN="down",GROUND_ALTITUDE_UP="groundaltitudeup",GROUND_ALTITUDE_DOWN="groundaltitudedown",LEFT_ALT="lalt",LEFT_SHIFT="lshift",GEAR="gear",LIGHT="light",BRAKE="brake",OPTION_1="option1",OPTION_2="option2",OPTION_3="option3",OPTION_4="option4",OPTION_5="option5",OPTION_6="option6",OPTION_7="option7",OPTION_8="option8",OPTION_9="option9",OPTION_10="option10",OPTION_11="option11",OPTION_12="option12",OPTION_13="option13",OPTION_14="option14",OPTION_15="option15",OPTION_16="option16",OPTION_17="option17",OPTION_18="option18",OPTION_19="option19",OPTION_20="option20",OPTION_21="option21",OPTION_22="option22",OPTION_23="option23",OPTION_24="option24",OPTION_25="option25",OPTION_26="option26",OPTION_27="option27",OPTION_28="option28",OPTION_29="option29",LEFT_MOUSE="leftmouse",STOP_ENGINES="stopengines",SPEED_UP="speedup",SPEED_DOWN="speeddown",ANTIGRAVITY="antigravity",BOOSTER="booster"},main={update=f(function()end),flush=f(function()end)},update=function(self)local p=g(self.main.update)if p==i then self.main.update=f(function()self:runUpdate()end)elseif p==j then d(h(self.main.update))end end,flush=function(self)local p=g(self.main.flush)if p==i then self.main.flush=f(function()self:runFlush()end)elseif p==j then d(h(self.main.flush))end end,action=function(self,q,r)if self.fns.action[q][r]then runFunction(self.fns.action[q][r],"System Action "..q.." Error: ")end end,actionStart=function(self,r)self:action('start',r)end,actionStop=function(self,r)self:action('stop',r)end,actionLoop=function(self,r)self:action('loop',r)end,inputText=function(self,s)if self.fns.inputText then runFunction(self.fns.inputText,"System Input Text Error: ",s)end end,runUpdate=function(self)for t,u in pairs(self.cos.update)do local m=g(u)if m==i then self.cos.update[t]=f(self.fns.update[t])elseif m==j then d(h(u))end end end,runFlush=function(self)for t,u in pairs(self.cos.flush)do local m=g(u)if m==i then self.cos.flush[t]=f(self.fns.flush[t])elseif m==j then d(h(u))end end end,onUpdate=function(self,v)for t,w in pairs(v)do self.fns.update[t]=w;self.cos.update[t]=f(w)end end,onFlush=function(self,v)for t,w in pairs(v)do self.fns.flush[t]=w;self.cos.flush[t]=f(w)end end,onAction=function(self,q,v)for t,w in pairs(v)do self.fns.action[q][t]=w end end,onActionStart=function(self,v)self:onAction("start",v)end,onActionStop=function(self,v)self:onAction("stop",v)end,onActionLoop=function(self,v)self:onAction("loop",v)end,onInputText=function(self,k)self.fns.inputText=k end}}local x={__index={timers={},stopFn=function()end,timer=function(self,y)if self.timers[y]then runFunction(self.timers[y],"Unit Timer "..y.." Error: ")end end,setTimer=function(self,y,z,k)self.timers[y]=k;unit.setTimer(y,z)end,stopTimer=function(self,y)unit.stopTimer(y)self.timers[y]=nil end,onStop=function(self,k)self.stopFn=k end,stop=function(self)if self.stopFn then runFunction(self.stopFn,"Unit Stop Error: ")end end}}local A={__index={parentChangedFn=function(B,C)end,onParentChange=function(self,k)self.parentChangedFn=k end,parentChanged=function(self,B,C)if self.parentChangedFn then runFunction(self.parentChangedFn,"Player Parent Changed Error: ",B,C)end end}}local D={__index={dockedFn=function(E)end,onDocked=function(self,k)self.dockedFn=k end,docked=function(self,E)if self.dockedFn then runFunction(self.dockedFn,"Construct Docked Error: ",E)end end,undockedFn=function(E)end,onUndocked=function(self,k)self.undockedFn=k end,undocked=function(self,E)if self.undockedFn then runFunction(self.undockedFn,"Construct Undocked Error: ",E)end end,playerBoardedFn=function(E)end,onPlayerBoarded=function(self,k)self.playerBoardedFn=k end,playerBoarded=function(self,E)if self.playerBoardedFn then runFunction(self.playerBoardedFn,"Construct Player Boarded Error: ",E)end end,VRStationEnteredFn=function(E)end,onVRStationEntered=function(self,k)self.VRStationEnteredFn=k end,VRStationEntered=function(self,E)if self.VRStationEnteredFn then runFunction(self.VRStationEnteredFn,"Construct VR Station Entered Error: ",E)end end,constructDockedFn=function(E)end,onConstructDocked=function(self,k)self.constructDockedFn=k end,constructDocked=function(self,E)if self.constructDockedFn then runFunction(self.constructDockedFn,"Construct Construct Docked Error: ",E)end end,PvPTimerFn=function(F)end,onPvPTimer=function(self,k)self.PvPTimerFn=k end,PvPTimer=function(self,F)if self.PvPTimerFn then runFunction(self.PvPTimerFn,"Construct PvP Timer Error: ",F)end end}}DU_Framework={__index={system=setmetatable({},o),unit=setmetatable({},x),player=setmetatable({},A),construct=setmetatable({},D)}}
169169+170170+Script = {}
171171+setmetatable(Script, DU_Framework)
172172+173173+--[[
174174+ String Helpers For Lua By Jericho
175175+]]
176176+String = {
177177+ __index = {
178178+ split = function(self, delimiter)
179179+ local result = {}
180180+ for match in (self..delimiter):gmatch("(.-)"..delimiter) do
181181+ table.insert(result, match)
182182+ end
183183+ return result
184184+ end
185185+ }
186186+}
187187+string = setmetatable(string, String)
188188+string.__index = string
189189+190190+local systemOnUpdate = {
191191+ function ()
192192+ Nav:update()
193193+ end
194194+}
195195+196196+local systemOnFlush = {
197197+ function()
198198+ local yawSpeedFactor = 1.5
199199+ local yawAccelerationFactor = 3
200200+ local lateralAntiDriftFactor = 1
201201+ local lateralStrafeFactor = 5
202202+ local brakeSpeedFactor = 1
203203+ local brakeFlatFactor = 4
204204+ local autoBrakeSpeed = 15
205205+ -- validate params
206206+ brakeSpeedFactor = math.max(brakeSpeedFactor, 0.01)
207207+ brakeFlatFactor = math.max(brakeFlatFactor, 0.01)
208208+ yawSpeedFactor = math.max(yawSpeedFactor, 0.01)
209209+ yawAccelerationFactor = math.max(yawAccelerationFactor, 0.01)
210210+ --init all the PIDs as global if first flush
211211+ if (rollPID == nil) then rollPID = pid.new(0.2, 0, 10) end
212212+ if (pitchPID == nil) then pitchPID = pid.new(0.2, 0, 10) end
213213+ if (yawPID == nil) then yawPID = pid.new(0.2, 0, 10) end
214214+ if (lateralPID == nil) then lateralPID = pid.new(0.2, 0, 10) end
215215+ if (longitudinalPID == nil) then longitudinalPID = pid.new(0.2, 0, 10) end
216216+ if (distancePID == nil) then distancePID = pid.new(0.2, 0, 10) end
217217+218218+ -- final inputs
219219+ if unit.isMouseDirectControlActivated() then
220220+ -- in direct control, we tweak the pitch to behave inbetween virtual joystick and direct control
221221+ -- this helps a lot for ground construct control
222222+ pitchInputFromDevice = utils.clamp(pitchInputFromDevice + system.getControlDeviceForwardInput() * system.getActionUpdateDeltaTime(), -1.0, 1.0)
223223+ else
224224+ pitchInputFromDevice = system.getControlDeviceForwardInput()
225225+ end
226226+ local finalPitchInput = pitchInput + pitchInputFromDevice
227227+ local finalRollInput = rollInput + system.getControlDeviceYawInput()
228228+ local finalYawInput = yawInput - system.getControlDeviceLeftRightInput()
229229+ local combinedRollYawInput = utils.clamp(finalRollInput - finalYawInput, -1.0, 1.0);
230230+ local finalVerticalStrafeInput = verticalStrafeInput
231231+ local finalLateralStrafeInput = lateralStrafeInput;
232232+ local finalBrakeInput = brakeInput
233233+234234+ -- Axis
235235+ local worldVertical = vec3(core.getWorldVertical())
236236+ local constructUp = vec3(construct.getWorldOrientationUp())
237237+ local constructForward = vec3(construct.getWorldOrientationForward())
238238+ local constructRight = vec3(construct.getWorldOrientationRight())
239239+ local constructVelocity = vec3(construct.getWorldVelocity())
240240+ local constructVelocityDir = vec3(construct.getWorldVelocity()):normalize()
241241+ local constructAngularVelocity = vec3(construct.getWorldAngularVelocity())
242242+ local constructYawVelocity = constructAngularVelocity:dot(constructUp)
243243+ local constructWorldPosition = vec3(construct.getWorldPosition())
244244+ local constructTargetPosition = vec3(ConstructInitPos)
245245+246246+ -- Engine commands
247247+ local keepCollinearity = 0 -- for easier reading
248248+ local dontKeepCollinearity = 1 -- for easier reading
249249+ local tolerancePercentToSkipOtherPriorities = 1 -- if we are within this tolerance (in%), we don't go to the next priorities
250250+251251+ -- keeping the start position alignement
252252+ local StrafeSpeedFactor = 50 --export: useg to increase the force of the alignement, decrease the value if the alignement is too strong or increase it if it's too slow
253253+ local positionDifference = constructTargetPosition - constructWorldPosition
254254+ local lateralOffset = positionDifference:project_on(constructRight):len() * utils.sign(positionDifference:dot(constructRight))
255255+ local longitudinalOffset = positionDifference:project_on(constructForward):len() * utils.sign(positionDifference:dot(constructForward))
256256+ lateralPID:inject(lateralOffset)
257257+ Nav.axisCommandManager:setThrottleCommand(axisCommandId.lateral, lateralPID:get() * StrafeSpeedFactor)
258258+ longitudinalPID:inject(longitudinalOffset)
259259+ Nav.axisCommandManager:setThrottleCommand(axisCommandId.longitudinal, longitudinalPID:get() * StrafeSpeedFactor)
260260+261261+ -- Rotation
262262+ local currentRollDeg = getRoll(worldVertical, constructForward, constructRight)
263263+ local currentPitchDeg = -math.asin(constructForward:dot(worldVertical)) * constants.rad2deg
264264+ local targetRollDeg = 0
265265+ local targetPitchDeg = 0
266266+ local targetYawDeg = signedAngleBetween(BaseForward,constructForward,constructUp)*180/math.pi
267267+ rollPID:inject(targetRollDeg - currentRollDeg)
268268+ pitchPID:inject(targetPitchDeg - currentPitchDeg)
269269+ yawPID:inject(-targetYawDeg*yawSpeedFactor)
270270+271271+ local constructYawTargetVelocity = -combinedRollYawInput * yawSpeedFactor
272272+ local constructYawTargetAcceleration = yawAccelerationFactor * (constructYawTargetVelocity - constructYawVelocity)
273273+ local constructTargetAngularVelocity = rollPID:get() * constructForward + pitchPID:get() * constructRight + constructYawTargetAcceleration * constructUp
274274+275275+ Nav:setEngineTorqueCommand('torque', constructTargetAngularVelocity, keepCollinearity, 'airfoil', '', '', tolerancePercentToSkipOtherPriorities)
276276+277277+ -- moving up or down from TargetAltitude
278278+ local verticalSpeed = constructVelocity:project_on(worldVertical):len()
279279+ local verticalSpeedSigned = verticalSpeed * -utils.sign(constructVelocity:dot(worldVertical))
280280+ local brakeDistance = 0
281281+ local maxBrake = construct.getMaxBrake()
282282+ if maxBrake ~= nil then
283283+ brakeDistance, _ = computeDistanceAndTime(verticalSpeed, 0, construct.getInertialMass(), 0, 0, maxBrake - (core.getGravityIntensity() * construct.getInertialMass()) * utils.sign(verticalSpeedSigned))
284284+ end
285285+ local coreAltitude = core.getAltitude()
286286+ local distance = TargetAltitude - coreAltitude
287287+ local targetDistance = utils.sign(distance) * (math.abs(distance)-brakeDistance)
288288+ distancePID:inject(targetDistance)
289289+ if distancePID:get() > 0.5 or verticalSpeedSigned < -MaxSpeed then --using a 0.5 meter deadband for stabilizing
290290+ Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, 1)
291291+ elseif distancePID:get() < -0.5 or verticalSpeedSigned > MaxSpeed then
292292+ Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, -1)
293293+ else
294294+ Nav.axisCommandManager:resetCommand(axisCommandId.vertical)
295295+ end
296296+297297+ --Brakes
298298+ if
299299+ (math.abs(distance) < verticalSpeed)
300300+ or verticalSpeed > MaxSpeed
301301+ or (brakeDistance > math.abs(distance))
302302+ or (finalBrakeInput == 0 and autoBrakeSpeed > 0 and Nav.axisCommandManager.throttle == 0 and constructVelocity:len() < autoBrakeSpeed)
303303+ then
304304+ finalBrakeInput = 1
305305+ end
306306+ local brakeAcceleration = -finalBrakeInput * (brakeSpeedFactor * constructVelocity + brakeFlatFactor * constructVelocityDir)
307307+308308+ Nav:setEngineForceCommand('brake', brakeAcceleration)
309309+310310+ -- AutoNavigation regroups all the axis command by 'TargetSpeed'
311311+ local autoNavigationEngineTags = ''
312312+ local autoNavigationAcceleration = vec3()
313313+ local autoNavigationUseBrake = false
314314+315315+ -- Longitudinal Translation
316316+ local longitudinalEngineTags = 'thrust analog longitudinal'
317317+ local longitudinalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.longitudinal)
318318+ if (longitudinalCommandType == axisCommandType.byThrottle) then
319319+ local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(longitudinalEngineTags,axisCommandId.longitudinal)
320320+ Nav:setEngineForceCommand(longitudinalEngineTags, longitudinalAcceleration, keepCollinearity)
321321+ elseif (longitudinalCommandType == axisCommandType.byTargetSpeed) then
322322+ local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.longitudinal)
323323+ autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. longitudinalEngineTags
324324+ autoNavigationAcceleration = autoNavigationAcceleration + longitudinalAcceleration
325325+ if (Nav.axisCommandManager:getTargetSpeed(axisCommandId.longitudinal) == 0 or -- we want to stop
326326+ Nav.axisCommandManager:getCurrentToTargetDeltaSpeed(axisCommandId.longitudinal) < - Nav.axisCommandManager:getTargetSpeedCurrentStep(axisCommandId.longitudinal) * 0.5) -- if the longitudinal velocity would need some braking
327327+ then
328328+ autoNavigationUseBrake = true
329329+ end
330330+ end
331331+332332+ -- Lateral Translation
333333+ local lateralStrafeEngineTags = 'thrust analog lateral'
334334+ local lateralCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.lateral)
335335+ if (lateralCommandType == axisCommandType.byThrottle) then
336336+ local lateralStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(lateralStrafeEngineTags,axisCommandId.lateral)
337337+ Nav:setEngineForceCommand(lateralStrafeEngineTags, lateralStrafeAcceleration, keepCollinearity)
338338+ elseif (lateralCommandType == axisCommandType.byTargetSpeed) then
339339+ local lateralAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.lateral)
340340+ autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. lateralStrafeEngineTags
341341+ autoNavigationAcceleration = autoNavigationAcceleration + lateralAcceleration
342342+ end
343343+344344+ -- Vertical Translation
345345+ local verticalStrafeEngineTags = 'thrust analog vertical'
346346+ local verticalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.vertical)
347347+ if (verticalCommandType == axisCommandType.byThrottle) then
348348+ local verticalStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(verticalStrafeEngineTags,axisCommandId.vertical)
349349+ Nav:setEngineForceCommand(verticalStrafeEngineTags, verticalStrafeAcceleration, keepCollinearity, 'airfoil', 'ground', '', tolerancePercentToSkipOtherPriorities)
350350+ elseif (verticalCommandType == axisCommandType.byTargetSpeed) then
351351+ local verticalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.vertical)
352352+ autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. verticalStrafeEngineTags
353353+ autoNavigationAcceleration = autoNavigationAcceleration + verticalAcceleration
354354+ end
355355+356356+ -- Auto Navigation (Cruise Control)
357357+ if (autoNavigationAcceleration:len() > constants.epsilon) then
358358+ if (brakeInput ~= 0 or autoNavigationUseBrake or math.abs(constructVelocityDir:dot(constructForward)) < 0.95) -- if the velocity is not properly aligned with the forward
359359+ then
360360+ autoNavigationEngineTags = autoNavigationEngineTags .. ', brake'
361361+ end
362362+ Nav:setEngineForceCommand(autoNavigationEngineTags, autoNavigationAcceleration, dontKeepCollinearity, '', '', '', tolerancePercentToSkipOtherPriorities)
363363+ end
364364+365365+ -- Rockets
366366+ Nav:setBoosterCommand('rocket_engine')
367367+ end
368368+}
369369+370370+371371+Script.system:onUpdate(systemOnUpdate)
372372+Script.system:onFlush(systemOnFlush)
373373+374374+--[[
375375+ Chat Commands
376376+]]
377377+378378+Script.system:onInputText(function (text)
379379+ if text:lower():find('goto:') then
380380+ TargetAltitude = tonumber(text:split(':')[2]) or BaseAltitute
381381+ brakeInput = 0
382382+ system.print('Target Altitude set to ' .. TargetAltitude .. 'm')
383383+ else
384384+ system.print('Unknown command')
385385+ end
386386+end)
···11+{"events":[],"handlers":[{"code":"Script.system:update()","filter":{"args":[],"signature":"onUpdate()","slotKey":"-4"},"key":"9"},{"code":"Script.system:inputText(text)","filter":{"args":[{"variable":"*"}],"signature":"onInputText(text)","slotKey":"-4"},"key":"10"},{"code":"Script.system:flush()","filter":{"args":[],"signature":"onFlush()","slotKey":"-4"},"key":"11"},{"code":"Script.system:actionStop(action)","filter":{"args":[{"variable":"*"}],"signature":"onActionStop(action)","slotKey":"-4"},"key":"12"},{"code":"Script.system:actionStart(action)","filter":{"args":[{"variable":"*"}],"signature":"onActionStart(action)","slotKey":"-4"},"key":"13"},{"code":"Script.system:actionLoop(action)","filter":{"args":[{"variable":"*"}],"signature":"onActionLoop(action)","slotKey":"-4"},"key":"14"},{"code":"Script.player:parentChanged(oldId, newId)","filter":{"args":[{"variable":"*"},{"variable":"*"}],"signature":"onParentChanged(oldId,newId)","slotKey":"-3"},"key":"3"},{"code":"Script.construct:VRStationEntered(id)","filter":{"args":[{"variable":"*"}],"signature":"onVRStationEntered(id)","slotKey":"-2"},"key":"4"},{"code":"Script.construct:undocked(id)","filter":{"args":[{"variable":"*"}],"signature":"onUndocked(id)","slotKey":"-2"},"key":"5"},{"code":"Script.construct:PvPTimer(active)","filter":{"args":[{"variable":"*"}],"signature":"onPvPTimer(active)","slotKey":"-2"},"key":"6"},{"code":"Script.construct:playerBoarded(id)","filter":{"args":[{"variable":"*"}],"signature":"onPlayerBoarded(id)","slotKey":"-2"},"key":"7"},{"code":"Script.construct:constructDocked(id)","filter":{"args":[{"variable":"*"}],"signature":"onConstructDocked(id)","slotKey":"-2"},"key":"8"},{"code":"Script.unit:timer(tag)","filter":{"args":[{"variable":"*"}],"signature":"onTimer(tag)","slotKey":"-1"},"key":"0"},{"code":"Script.unit:stop()","filter":{"args":[],"signature":"onStop()","slotKey":"-1"},"key":"1"},{"code":"--[[\r\n DU-ELEVATOR by Jericho\r\n]]\r\n\r\n__DEBUG = false --export: Debug mode, will print more information in the console\r\n\r\n--[[\r\n Version Management\r\n]]\r\n\r\nlocal version = \"V 1.0.0\"\r\nlocal log_split = \"=================================================\"\r\n--printing version in lua chat\r\nsystem.print(log_split)local a=\"\"local b=math.ceil((50-#version-2)/2)for c=1,b,1 do a=a..'='end;a=a..\" \"..version..\" \"for c=1,b,1 do a=a..'='end;system.print(a)system.print(log_split)\r\n\r\n--[[\r\n Detecting elements linked\r\n]]\r\ncore = nil\r\nfuelTanks = {}\r\n\r\nfor slot_name, slot in pairs(unit) do\r\n if\r\n type(slot) == \"table\"\r\n and type(slot.export) == \"table\"\r\n and slot.getClass\r\n then\r\n local class = slot.getClass():lower()\r\n if class:find(\"coreunit\") then\r\n core = slot\r\n elseif class:find(\"fuelcontainer\") then\r\n table.insert(fuelTanks, slot)\r\n end\r\n end\r\nend\r\n\r\n--[[\r\n stopping the script if required elements are not linked\r\n]]\r\nif core == nil then\r\n system.print('Core unit is not linked, exiting the script')\r\n unit.exit()\r\nend\r\n\r\n--[[\r\n Default Unit Start Mechanics\r\n]]\r\npitchInput = 0\r\npitchInputFromDevice = 0\r\nrollInput = 0\r\nyawInput = 0\r\nverticalStrafeInput = 0\r\nlateralStrafeInput = 0\r\nbrakeInput = 1 --braking by default\r\ngoingBack = false\r\ngoingForward = false\r\nshiftPressed = false\r\njumpDelta = 0\r\nbaseAcceleration = 0.8\r\n\r\nNav = Navigator.new(system, core, unit)\r\nNav.axisCommandManager:setupCustomTargetSpeedRanges(axisCommandId.longitudinal, {100, 500, 1000, 2000,3000, 5000})\r\nNav.axisCommandManager:setTargetGroundAltitude(0)\r\nunit.deactivateGroundEngineAltitudeStabilization()\r\n\r\n-- Parenting widget\r\nparentingPanelId = system.createWidgetPanel(\"Docking\")\r\nparentingWidgetId = system.createWidget(parentingPanelId,\"parenting\")\r\nsystem.addDataToWidget(unit.getWidgetDataId(),parentingWidgetId)\r\n\r\n-- Fuel widget generation (Updated code By Jericho)\r\n--TODO: replace by custom HUD\r\nif (#fuelTanks > 0) then\r\n fuelTankPanelId = system.createWidgetPanel(\"Fuel Tanks\")\r\n fuelTankWidgetId = system.createWidget(fuelTankPanelId,\"fuel_container\")\r\n for _,tank in pairs(fuelTanks) do\r\n system.addDataToWidget(tank.getWidgetDataId(),fuelTankWidgetId)\r\n end\r\nend\r\n\r\n--[[\r\n Storing base position and orientation of the elevator\r\n]]\r\nConstructInitPos = construct.getWorldPosition()\r\n--replace that pos by a hand written value to be sure the construct will always realign the same position\r\n--ConstructInitPos = {-1231538.185042, 1201297.6879598, -2617220.2766464}\r\nif __DEBUG then system.print('ConstructInitPos: ' .. json.encode(ConstructInitPos)) end\r\nBaseForward = vec3(construct.getWorldForward())\r\nif __DEBUG then system.print('BaseForward: ' .. json.encode(BaseForward)) end\r\nBaseAltitute = 285 --export: the start altitude of the elevator (lower position altitude)\r\n\r\n--TODO: to replace with a computing in flush from the current acceleration and the friction acceleration (construct.getWorldAirFrictionAcceleration)\r\nMaxSpeed = construct.getFrictionBurnSpeed() -- for security to avoid burning if going too fast\r\nif __DEBUG then system.print('MaxSpeed: ' .. MaxSpeed) end\r\n\r\n--init a value to store the target altitude\r\nTargetAltitude = core.getAltitude() --by default to the start altitude to avoid falling down if in the air\r\n\r\n--[[\r\n Kinematics functions by Jaylebreak\r\n Source available at https://gitlab.com/JayleBreak/dualuniverse/-/blob/master/DUflightfiles/autoconf/custom/kinematics.lua\r\n]] \r\nfunction computeAccelerationTime(initial, acceleration, final) return (final - initial)/acceleration end\r\nfunction computeDistanceAndTime(initial, final, mass, thrust, t50, brakeThrust)\r\n t50 = t50 or 0\r\n brakeThrust = brakeThrust or 0\r\n local speedUp = initial < final\r\n local a0 = thrust / (speedUp and mass or -mass)\r\n local b0 = -brakeThrust/mass\r\n local totA = a0+b0\r\n if initial == final then\r\n return 0, 0\r\n elseif speedUp and totA <= 0 or not speedUp and totA >= 0 then\r\n return -1, -1\r\n end\r\n local distanceToMax, timeToMax = 0, 0\r\n if a0 ~= 0 and t50 > 0 then\r\n local c1 = math.pi/t50/2\r\n local v = function(t)\r\n return a0*(t/2 - t50*math.sin(c1*t)/math.pi) + b0*t + initial\r\n end\r\n local speedchk = speedUp and function(s) return s >= final end or function(s) return s <= final end\r\n timeToMax = 2*t50\r\n if speedchk(v(timeToMax)) then\r\n local lasttime = 0\r\n while math.abs(timeToMax - lasttime) > 0.25 do\r\n local t = (timeToMax + lasttime)/2\r\n if speedchk(v(t)) then\r\n timeToMax = t \r\n else\r\n lasttime = t\r\n end\r\n end\r\n end\r\n local K = 2*a0*t50^2/math.pi^2\r\n distanceToMax = K*(math.cos(c1*timeToMax) - 1) + (a0+2*b0)*timeToMax^2/4 + initial*timeToMax\r\n if timeToMax < 2*t50 then\r\n return distanceToMax, timeToMax\r\n end\r\n initial = v(timeToMax)\r\n end\r\n local a = a0+b0\r\n local t = computeAccelerationTime(initial, a, final)\r\n local d = initial*t + a*t*t/2\r\n return distanceToMax+d, timeToMax+t\r\nend\r\n\r\n--[[\r\n Commpute angle betwwen vectors by Jericho\r\n]]\r\nfunction signedAngleBetween(vec1, vec2, planeNormal)\r\n local normVec1 = vec1:project_on_plane(planeNormal):normalize()\r\n local normVec2 = vec2:normalize()\r\n local v1v2dot = normVec1:dot(normVec2)\r\n local angle = math.acos(utils.clamp(v1v2dot,-1,1))\r\n local crossProduct = vec1:cross(vec2)\r\n if crossProduct:dot(planeNormal) < 0 then\r\n return -angle\r\n end\r\n return angle\r\nend\r\n\r\n--[[\r\n DU-LUA-Framework by Jericho\r\n Permit to code easier by grouping most of the code in a single event Unit > Start\r\n Unminified Source available here: https://github.com/Jericho1060/du-lua-framework\r\n]]--\r\nlocal a=system.print;local b=error;local c=pcall;local d=assert;local e=coroutine;local f=e.create;local g=e.status;local h=e.resume;local i=\"dead\"local j=\"suspended\"function runFunction(k,l,...)local m,n=c(k,...)if not m then b(l..n)end end;local o={__index={cos={update={},flush={}},fns={update={},flush={},action={start={},stop={},loop={}},inputText=nil,start=nil,stop=nil},ACTIONS={FORWARD=\"forward\",BACKWARD=\"backward\",YAW_LEFT=\"yawleft\",YAW_RIGHT=\"yawright\",STRAFE_LEFT=\"strafeleft\",STRAFE_RIGHT=\"straferight\",LEFT=\"left\",RIGHT=\"right\",UP=\"up\",DOWN=\"down\",GROUND_ALTITUDE_UP=\"groundaltitudeup\",GROUND_ALTITUDE_DOWN=\"groundaltitudedown\",LEFT_ALT=\"lalt\",LEFT_SHIFT=\"lshift\",GEAR=\"gear\",LIGHT=\"light\",BRAKE=\"brake\",OPTION_1=\"option1\",OPTION_2=\"option2\",OPTION_3=\"option3\",OPTION_4=\"option4\",OPTION_5=\"option5\",OPTION_6=\"option6\",OPTION_7=\"option7\",OPTION_8=\"option8\",OPTION_9=\"option9\",OPTION_10=\"option10\",OPTION_11=\"option11\",OPTION_12=\"option12\",OPTION_13=\"option13\",OPTION_14=\"option14\",OPTION_15=\"option15\",OPTION_16=\"option16\",OPTION_17=\"option17\",OPTION_18=\"option18\",OPTION_19=\"option19\",OPTION_20=\"option20\",OPTION_21=\"option21\",OPTION_22=\"option22\",OPTION_23=\"option23\",OPTION_24=\"option24\",OPTION_25=\"option25\",OPTION_26=\"option26\",OPTION_27=\"option27\",OPTION_28=\"option28\",OPTION_29=\"option29\",LEFT_MOUSE=\"leftmouse\",STOP_ENGINES=\"stopengines\",SPEED_UP=\"speedup\",SPEED_DOWN=\"speeddown\",ANTIGRAVITY=\"antigravity\",BOOSTER=\"booster\"},main={update=f(function()end),flush=f(function()end)},update=function(self)local p=g(self.main.update)if p==i then self.main.update=f(function()self:runUpdate()end)elseif p==j then d(h(self.main.update))end end,flush=function(self)local p=g(self.main.flush)if p==i then self.main.flush=f(function()self:runFlush()end)elseif p==j then d(h(self.main.flush))end end,action=function(self,q,r)if self.fns.action[q][r]then runFunction(self.fns.action[q][r],\"System Action \"..q..\" Error: \")end end,actionStart=function(self,r)self:action('start',r)end,actionStop=function(self,r)self:action('stop',r)end,actionLoop=function(self,r)self:action('loop',r)end,inputText=function(self,s)if self.fns.inputText then runFunction(self.fns.inputText,\"System Input Text Error: \",s)end end,runUpdate=function(self)for t,u in pairs(self.cos.update)do local m=g(u)if m==i then self.cos.update[t]=f(self.fns.update[t])elseif m==j then d(h(u))end end end,runFlush=function(self)for t,u in pairs(self.cos.flush)do local m=g(u)if m==i then self.cos.flush[t]=f(self.fns.flush[t])elseif m==j then d(h(u))end end end,onUpdate=function(self,v)for t,w in pairs(v)do self.fns.update[t]=w;self.cos.update[t]=f(w)end end,onFlush=function(self,v)for t,w in pairs(v)do self.fns.flush[t]=w;self.cos.flush[t]=f(w)end end,onAction=function(self,q,v)for t,w in pairs(v)do self.fns.action[q][t]=w end end,onActionStart=function(self,v)self:onAction(\"start\",v)end,onActionStop=function(self,v)self:onAction(\"stop\",v)end,onActionLoop=function(self,v)self:onAction(\"loop\",v)end,onInputText=function(self,k)self.fns.inputText=k end}}local x={__index={timers={},stopFn=function()end,timer=function(self,y)if self.timers[y]then runFunction(self.timers[y],\"Unit Timer \"..y..\" Error: \")end end,setTimer=function(self,y,z,k)self.timers[y]=k;unit.setTimer(y,z)end,stopTimer=function(self,y)unit.stopTimer(y)self.timers[y]=nil end,onStop=function(self,k)self.stopFn=k end,stop=function(self)if self.stopFn then runFunction(self.stopFn,\"Unit Stop Error: \")end end}}local A={__index={parentChangedFn=function(B,C)end,onParentChange=function(self,k)self.parentChangedFn=k end,parentChanged=function(self,B,C)if self.parentChangedFn then runFunction(self.parentChangedFn,\"Player Parent Changed Error: \",B,C)end end}}local D={__index={dockedFn=function(E)end,onDocked=function(self,k)self.dockedFn=k end,docked=function(self,E)if self.dockedFn then runFunction(self.dockedFn,\"Construct Docked Error: \",E)end end,undockedFn=function(E)end,onUndocked=function(self,k)self.undockedFn=k end,undocked=function(self,E)if self.undockedFn then runFunction(self.undockedFn,\"Construct Undocked Error: \",E)end end,playerBoardedFn=function(E)end,onPlayerBoarded=function(self,k)self.playerBoardedFn=k end,playerBoarded=function(self,E)if self.playerBoardedFn then runFunction(self.playerBoardedFn,\"Construct Player Boarded Error: \",E)end end,VRStationEnteredFn=function(E)end,onVRStationEntered=function(self,k)self.VRStationEnteredFn=k end,VRStationEntered=function(self,E)if self.VRStationEnteredFn then runFunction(self.VRStationEnteredFn,\"Construct VR Station Entered Error: \",E)end end,constructDockedFn=function(E)end,onConstructDocked=function(self,k)self.constructDockedFn=k end,constructDocked=function(self,E)if self.constructDockedFn then runFunction(self.constructDockedFn,\"Construct Construct Docked Error: \",E)end end,PvPTimerFn=function(F)end,onPvPTimer=function(self,k)self.PvPTimerFn=k end,PvPTimer=function(self,F)if self.PvPTimerFn then runFunction(self.PvPTimerFn,\"Construct PvP Timer Error: \",F)end end}}DU_Framework={__index={system=setmetatable({},o),unit=setmetatable({},x),player=setmetatable({},A),construct=setmetatable({},D)}}\r\n\r\nScript = {}\r\nsetmetatable(Script, DU_Framework)\r\n\r\n--[[\r\n String Helpers For Lua By Jericho\r\n]]\r\nString = {\r\n __index = {\r\n split = function(self, delimiter)\r\n local result = {}\r\n for match in (self..delimiter):gmatch(\"(.-)\"..delimiter) do\r\n table.insert(result, match)\r\n end\r\n return result\r\n end\r\n }\r\n}\r\nstring = setmetatable(string, String)\r\nstring.__index = string\r\n\r\nlocal systemOnUpdate = {\r\n function ()\r\n Nav:update()\r\n end\r\n}\r\n\r\nlocal systemOnFlush = {\r\n function()\r\n local yawSpeedFactor = 1.5\r\n local yawAccelerationFactor = 3\r\n local lateralAntiDriftFactor = 1\r\n local lateralStrafeFactor = 5\r\n local brakeSpeedFactor = 1\r\n local brakeFlatFactor = 4 \r\n local autoBrakeSpeed = 15\r\n -- validate params\r\n brakeSpeedFactor = math.max(brakeSpeedFactor, 0.01)\r\n brakeFlatFactor = math.max(brakeFlatFactor, 0.01)\r\n yawSpeedFactor = math.max(yawSpeedFactor, 0.01)\r\n yawAccelerationFactor = math.max(yawAccelerationFactor, 0.01)\r\n --init all the PIDs as global if first flush\r\n if (rollPID == nil) then rollPID = pid.new(0.2, 0, 10) end\r\n if (pitchPID == nil) then pitchPID = pid.new(0.2, 0, 10) end\r\n if (yawPID == nil) then yawPID = pid.new(0.2, 0, 10) end\r\n if (lateralPID == nil) then lateralPID = pid.new(0.2, 0, 10) end\r\n if (longitudinalPID == nil) then longitudinalPID = pid.new(0.2, 0, 10) end\r\n if (distancePID == nil) then distancePID = pid.new(0.2, 0, 10) end\r\n\r\n -- final inputs\r\n if unit.isMouseDirectControlActivated() then\r\n -- in direct control, we tweak the pitch to behave inbetween virtual joystick and direct control\r\n -- this helps a lot for ground construct control\r\n pitchInputFromDevice = utils.clamp(pitchInputFromDevice + system.getControlDeviceForwardInput() * system.getActionUpdateDeltaTime(), -1.0, 1.0)\r\n else\r\n pitchInputFromDevice = system.getControlDeviceForwardInput()\r\n end\r\n local finalPitchInput = pitchInput + pitchInputFromDevice\r\n local finalRollInput = rollInput + system.getControlDeviceYawInput()\r\n local finalYawInput = yawInput - system.getControlDeviceLeftRightInput()\r\n local combinedRollYawInput = utils.clamp(finalRollInput - finalYawInput, -1.0, 1.0);\r\n local finalVerticalStrafeInput = verticalStrafeInput\r\n local finalLateralStrafeInput = lateralStrafeInput;\r\n local finalBrakeInput = brakeInput\r\n\r\n -- Axis\r\n local worldVertical = vec3(core.getWorldVertical())\r\n local constructUp = vec3(construct.getWorldOrientationUp())\r\n local constructForward = vec3(construct.getWorldOrientationForward())\r\n local constructRight = vec3(construct.getWorldOrientationRight())\r\n local constructVelocity = vec3(construct.getWorldVelocity())\r\n local constructVelocityDir = vec3(construct.getWorldVelocity()):normalize()\r\n local constructAngularVelocity = vec3(construct.getWorldAngularVelocity())\r\n local constructYawVelocity = constructAngularVelocity:dot(constructUp)\r\n local constructWorldPosition = vec3(construct.getWorldPosition())\r\n local constructTargetPosition = vec3(ConstructInitPos)\r\n\r\n -- Engine commands\r\n local keepCollinearity = 0 -- for easier reading\r\n local dontKeepCollinearity = 1 -- for easier reading\r\n local tolerancePercentToSkipOtherPriorities = 1 -- if we are within this tolerance (in%), we don't go to the next priorities\r\n\r\n -- keeping the start position alignement\r\n local StrafeSpeedFactor = 50 --export: useg to increase the force of the alignement, decrease the value if the alignement is too strong or increase it if it's too slow\r\n local positionDifference = constructTargetPosition - constructWorldPosition\r\n local lateralOffset = positionDifference:project_on(constructRight):len() * utils.sign(positionDifference:dot(constructRight))\r\n local longitudinalOffset = positionDifference:project_on(constructForward):len() * utils.sign(positionDifference:dot(constructForward))\r\n lateralPID:inject(lateralOffset)\r\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.lateral, lateralPID:get() * StrafeSpeedFactor)\r\n longitudinalPID:inject(longitudinalOffset)\r\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.longitudinal, longitudinalPID:get() * StrafeSpeedFactor)\r\n\r\n -- Rotation\r\n local currentRollDeg = getRoll(worldVertical, constructForward, constructRight)\r\n local currentPitchDeg = -math.asin(constructForward:dot(worldVertical)) * constants.rad2deg\r\n local targetRollDeg = 0\r\n local targetPitchDeg = 0\r\n local targetYawDeg = signedAngleBetween(BaseForward,constructForward,constructUp)*180/math.pi\r\n rollPID:inject(targetRollDeg - currentRollDeg)\r\n pitchPID:inject(targetPitchDeg - currentPitchDeg)\r\n yawPID:inject(-targetYawDeg*yawSpeedFactor)\r\n\r\n local constructYawTargetVelocity = -combinedRollYawInput * yawSpeedFactor\r\n local constructYawTargetAcceleration = yawAccelerationFactor * (constructYawTargetVelocity - constructYawVelocity)\r\n local constructTargetAngularVelocity = rollPID:get() * constructForward + pitchPID:get() * constructRight + constructYawTargetAcceleration * constructUp\r\n\r\n Nav:setEngineTorqueCommand('torque', constructTargetAngularVelocity, keepCollinearity, 'airfoil', '', '', tolerancePercentToSkipOtherPriorities)\r\n\r\n -- moving up or down from TargetAltitude\r\n local verticalSpeed = constructVelocity:project_on(worldVertical):len()\r\n local verticalSpeedSigned = verticalSpeed * -utils.sign(constructVelocity:dot(worldVertical))\r\n local brakeDistance = 0\r\n local maxBrake = construct.getMaxBrake()\r\n if maxBrake ~= nil then\r\n brakeDistance, _ = computeDistanceAndTime(verticalSpeed, 0, construct.getInertialMass(), 0, 0, maxBrake - (core.getGravityIntensity() * construct.getInertialMass()) * utils.sign(verticalSpeedSigned))\r\n end\r\n local coreAltitude = core.getAltitude()\r\n local distance = TargetAltitude - coreAltitude\r\n local targetDistance = utils.sign(distance) * (math.abs(distance)-brakeDistance)\r\n distancePID:inject(targetDistance)\r\n if distancePID:get() > 0.5 or verticalSpeedSigned < -MaxSpeed then --using a 0.5 meter deadband for stabilizing\r\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, 1)\r\n elseif distancePID:get() < -0.5 or verticalSpeedSigned > MaxSpeed then\r\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, -1)\r\n else\r\n Nav.axisCommandManager:resetCommand(axisCommandId.vertical)\r\n end\r\n\r\n --Brakes\r\n if\r\n (math.abs(distance) < verticalSpeed)\r\n or verticalSpeed > MaxSpeed\r\n or (brakeDistance > math.abs(distance))\r\n or (finalBrakeInput == 0 and autoBrakeSpeed > 0 and Nav.axisCommandManager.throttle == 0 and constructVelocity:len() < autoBrakeSpeed)\r\n then\r\n finalBrakeInput = 1\r\n end\r\n local brakeAcceleration = -finalBrakeInput * (brakeSpeedFactor * constructVelocity + brakeFlatFactor * constructVelocityDir)\r\n \r\n Nav:setEngineForceCommand('brake', brakeAcceleration)\r\n\r\n -- AutoNavigation regroups all the axis command by 'TargetSpeed'\r\n local autoNavigationEngineTags = ''\r\n local autoNavigationAcceleration = vec3()\r\n local autoNavigationUseBrake = false\r\n\r\n -- Longitudinal Translation\r\n local longitudinalEngineTags = 'thrust analog longitudinal'\r\n local longitudinalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.longitudinal)\r\n if (longitudinalCommandType == axisCommandType.byThrottle) then\r\n local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(longitudinalEngineTags,axisCommandId.longitudinal)\r\n Nav:setEngineForceCommand(longitudinalEngineTags, longitudinalAcceleration, keepCollinearity)\r\n elseif (longitudinalCommandType == axisCommandType.byTargetSpeed) then\r\n local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.longitudinal)\r\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. longitudinalEngineTags\r\n autoNavigationAcceleration = autoNavigationAcceleration + longitudinalAcceleration\r\n if (Nav.axisCommandManager:getTargetSpeed(axisCommandId.longitudinal) == 0 or -- we want to stop\r\n Nav.axisCommandManager:getCurrentToTargetDeltaSpeed(axisCommandId.longitudinal) < - Nav.axisCommandManager:getTargetSpeedCurrentStep(axisCommandId.longitudinal) * 0.5) -- if the longitudinal velocity would need some braking\r\n then\r\n autoNavigationUseBrake = true\r\n end\r\n end\r\n\r\n -- Lateral Translation\r\n local lateralStrafeEngineTags = 'thrust analog lateral'\r\n local lateralCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.lateral)\r\n if (lateralCommandType == axisCommandType.byThrottle) then\r\n local lateralStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(lateralStrafeEngineTags,axisCommandId.lateral)\r\n Nav:setEngineForceCommand(lateralStrafeEngineTags, lateralStrafeAcceleration, keepCollinearity)\r\n elseif (lateralCommandType == axisCommandType.byTargetSpeed) then\r\n local lateralAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.lateral)\r\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. lateralStrafeEngineTags\r\n autoNavigationAcceleration = autoNavigationAcceleration + lateralAcceleration\r\n end\r\n\r\n -- Vertical Translation\r\n local verticalStrafeEngineTags = 'thrust analog vertical'\r\n local verticalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.vertical)\r\n if (verticalCommandType == axisCommandType.byThrottle) then\r\n local verticalStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(verticalStrafeEngineTags,axisCommandId.vertical)\r\n Nav:setEngineForceCommand(verticalStrafeEngineTags, verticalStrafeAcceleration, keepCollinearity, 'airfoil', 'ground', '', tolerancePercentToSkipOtherPriorities)\r\n elseif (verticalCommandType == axisCommandType.byTargetSpeed) then\r\n local verticalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.vertical)\r\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. verticalStrafeEngineTags\r\n autoNavigationAcceleration = autoNavigationAcceleration + verticalAcceleration\r\n end\r\n\r\n -- Auto Navigation (Cruise Control)\r\n if (autoNavigationAcceleration:len() > constants.epsilon) then\r\n if (brakeInput ~= 0 or autoNavigationUseBrake or math.abs(constructVelocityDir:dot(constructForward)) < 0.95) -- if the velocity is not properly aligned with the forward\r\n then\r\n autoNavigationEngineTags = autoNavigationEngineTags .. ', brake'\r\n end\r\n Nav:setEngineForceCommand(autoNavigationEngineTags, autoNavigationAcceleration, dontKeepCollinearity, '', '', '', tolerancePercentToSkipOtherPriorities)\r\n end\r\n\r\n -- Rockets\r\n Nav:setBoosterCommand('rocket_engine')\r\n end\r\n}\r\n\r\n\r\nScript.system:onUpdate(systemOnUpdate)\r\nScript.system:onFlush(systemOnFlush)\r\n\r\n--[[\r\n Chat Commands\r\n]]\r\n\r\nScript.system:onInputText(function (text)\r\n if text:lower():find('goto:') then\r\n TargetAltitude = tonumber(text:split(':')[2]) or BaseAltitute\r\n brakeInput = 0\r\n system.print('Target Altitude set to ' .. TargetAltitude .. 'm')\r\n else\r\n system.print('Unknown command')\r\n end\r\nend)","filter":{"args":[],"signature":"onStart()","slotKey":"-1"},"key":"2"}],"methods":[],"slots":{"0":{"name":"slot1","type":{"events":[],"methods":[]}},"1":{"name":"slot2","type":{"events":[],"methods":[]}},"2":{"name":"slot3","type":{"events":[],"methods":[]}},"3":{"name":"slot4","type":{"events":[],"methods":[]}},"4":{"name":"slot5","type":{"events":[],"methods":[]}},"5":{"name":"slot6","type":{"events":[],"methods":[]}},"6":{"name":"slot7","type":{"events":[],"methods":[]}},"7":{"name":"slot8","type":{"events":[],"methods":[]}},"8":{"name":"slot9","type":{"events":[],"methods":[]}},"9":{"name":"slot10","type":{"events":[],"methods":[]}},"-5":{"name":"library","type":{"events":[],"methods":[]}},"-4":{"name":"system","type":{"events":[],"methods":[]}},"-3":{"name":"player","type":{"events":[],"methods":[]}},"-2":{"name":"construct","type":{"events":[],"methods":[]}},"-1":{"name":"unit","type":{"events":[],"methods":[]}}}}