[READ-ONLY] Mirror of https://github.com/thoda-dev/du-elevator. a generic elevator script for Dual Universe
0

Configure Feed

Select the types of activity you want to include in your feed.

v1.0.1 - fix autoyaw

Thomas (Jul 22, 2023, 10:32 PM +0200) d543ff4b 08306a16

+2 -2
+1 -1
Source/Unit/OnStart.lua
··· 270 270 271 271 local constructYawTargetVelocity = -combinedRollYawInput * yawSpeedFactor 272 272 local constructYawTargetAcceleration = yawAccelerationFactor * (constructYawTargetVelocity - constructYawVelocity) 273 - local constructTargetAngularVelocity = rollPID:get() * constructForward + pitchPID:get() * constructRight + constructYawTargetAcceleration * constructUp 273 + local constructTargetAngularVelocity = rollPID:get() * constructForward + pitchPID:get() * constructRight + yawPID:get() * constructUp 274 274 275 275 Nav:setEngineTorqueCommand('torque', constructTargetAngularVelocity, keepCollinearity, 'airfoil', '', '', tolerancePercentToSkipOtherPriorities) 276 276
+1 -1
config.json
··· 1 - {"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":[]}}}} 1 + {"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":"--[[\n DU-ELEVATOR by Jericho\n]]\n\n__DEBUG = false --export: Debug mode, will print more information in the console\n\n--[[\n Version Management\n]]\n\nlocal version = \"V 1.0.1\"\nlocal log_split = \"=================================================\"\n--printing version in lua chat\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)\n\n--[[\n Detecting elements linked\n]]\ncore = nil\nfuelTanks = {}\n\nfor slot_name, slot in pairs(unit) do\n if\n type(slot) == \"table\"\n and type(slot.export) == \"table\"\n and slot.getClass\n then\n local class = slot.getClass():lower()\n if class:find(\"coreunit\") then\n core = slot\n elseif class:find(\"fuelcontainer\") then\n table.insert(fuelTanks, slot)\n end\n end\nend\n\n--[[\n stopping the script if required elements are not linked\n]]\nif core == nil then\n system.print('Core unit is not linked, exiting the script')\n unit.exit()\nend\n\n--[[\n Default Unit Start Mechanics\n]]\npitchInput = 0\npitchInputFromDevice = 0\nrollInput = 0\nyawInput = 0\nverticalStrafeInput = 0\nlateralStrafeInput = 0\nbrakeInput = 1 --braking by default\ngoingBack = false\ngoingForward = false\nshiftPressed = false\njumpDelta = 0\nbaseAcceleration = 0.8\n\nNav = Navigator.new(system, core, unit)\nNav.axisCommandManager:setupCustomTargetSpeedRanges(axisCommandId.longitudinal, {100, 500, 1000, 2000,3000, 5000})\nNav.axisCommandManager:setTargetGroundAltitude(0)\nunit.deactivateGroundEngineAltitudeStabilization()\n\n-- Parenting widget\nparentingPanelId = system.createWidgetPanel(\"Docking\")\nparentingWidgetId = system.createWidget(parentingPanelId,\"parenting\")\nsystem.addDataToWidget(unit.getWidgetDataId(),parentingWidgetId)\n\n-- Fuel widget generation (Updated code By Jericho)\n--TODO: replace by custom HUD\nif (#fuelTanks > 0) then\n fuelTankPanelId = system.createWidgetPanel(\"Fuel Tanks\")\n fuelTankWidgetId = system.createWidget(fuelTankPanelId,\"fuel_container\")\n for _,tank in pairs(fuelTanks) do\n system.addDataToWidget(tank.getWidgetDataId(),fuelTankWidgetId)\n end\nend\n\n--[[\n Storing base position and orientation of the elevator\n]]\nConstructInitPos = construct.getWorldPosition()\n--replace that pos by a hand written value to be sure the construct will always realign the same position\n--ConstructInitPos = {-1231538.185042, 1201297.6879598, -2617220.2766464}\nif __DEBUG then system.print('ConstructInitPos: ' .. json.encode(ConstructInitPos)) end\nBaseForward = vec3(construct.getWorldForward())\nif __DEBUG then system.print('BaseForward: ' .. json.encode(BaseForward)) end\nBaseAltitute = 285 --export: the start altitude of the elevator (lower position altitude)\n\n--TODO: to replace with a computing in flush from the current acceleration and the friction acceleration (construct.getWorldAirFrictionAcceleration)\nMaxSpeed = construct.getFrictionBurnSpeed() -- for security to avoid burning if going too fast\nif __DEBUG then system.print('MaxSpeed: ' .. MaxSpeed) end\n\n--init a value to store the target altitude\nTargetAltitude = core.getAltitude() --by default to the start altitude to avoid falling down if in the air\n\n--[[\n Kinematics functions by Jaylebreak\n Source available at https://gitlab.com/JayleBreak/dualuniverse/-/blob/master/DUflightfiles/autoconf/custom/kinematics.lua\n]] \nfunction computeAccelerationTime(initial, acceleration, final) return (final - initial)/acceleration end\nfunction computeDistanceAndTime(initial, final, mass, thrust, t50, brakeThrust)\n t50 = t50 or 0\n brakeThrust = brakeThrust or 0\n local speedUp = initial < final\n local a0 = thrust / (speedUp and mass or -mass)\n local b0 = -brakeThrust/mass\n local totA = a0+b0\n if initial == final then\n return 0, 0\n elseif speedUp and totA <= 0 or not speedUp and totA >= 0 then\n return -1, -1\n end\n local distanceToMax, timeToMax = 0, 0\n if a0 ~= 0 and t50 > 0 then\n local c1 = math.pi/t50/2\n local v = function(t)\n return a0*(t/2 - t50*math.sin(c1*t)/math.pi) + b0*t + initial\n end\n local speedchk = speedUp and function(s) return s >= final end or function(s) return s <= final end\n timeToMax = 2*t50\n if speedchk(v(timeToMax)) then\n local lasttime = 0\n while math.abs(timeToMax - lasttime) > 0.25 do\n local t = (timeToMax + lasttime)/2\n if speedchk(v(t)) then\n timeToMax = t \n else\n lasttime = t\n end\n end\n end\n local K = 2*a0*t50^2/math.pi^2\n distanceToMax = K*(math.cos(c1*timeToMax) - 1) + (a0+2*b0)*timeToMax^2/4 + initial*timeToMax\n if timeToMax < 2*t50 then\n return distanceToMax, timeToMax\n end\n initial = v(timeToMax)\n end\n local a = a0+b0\n local t = computeAccelerationTime(initial, a, final)\n local d = initial*t + a*t*t/2\n return distanceToMax+d, timeToMax+t\nend\n\n--[[\n Commpute angle betwwen vectors by Jericho\n]]\nfunction signedAngleBetween(vec1, vec2, planeNormal)\n local normVec1 = vec1:project_on_plane(planeNormal):normalize()\n local normVec2 = vec2:normalize()\n local v1v2dot = normVec1:dot(normVec2)\n local angle = math.acos(utils.clamp(v1v2dot,-1,1))\n local crossProduct = vec1:cross(vec2)\n if crossProduct:dot(planeNormal) < 0 then\n return -angle\n end\n return angle\nend\n\n--[[\n DU-LUA-Framework by Jericho\n Permit to code easier by grouping most of the code in a single event Unit > Start\n Unminified Source available here: https://github.com/Jericho1060/du-lua-framework\n]]--\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)}}\n\nScript = {}\nsetmetatable(Script, DU_Framework)\n\n--[[\n String Helpers For Lua By Jericho\n]]\nString = {\n __index = {\n split = function(self, delimiter)\n local result = {}\n for match in (self..delimiter):gmatch(\"(.-)\"..delimiter) do\n table.insert(result, match)\n end\n return result\n end\n }\n}\nstring = setmetatable(string, String)\nstring.__index = string\n\nlocal systemOnUpdate = {\n function ()\n Nav:update()\n end\n}\n\nlocal systemOnFlush = {\n function()\n local yawSpeedFactor = 1.5\n local yawAccelerationFactor = 3\n local lateralAntiDriftFactor = 1\n local lateralStrafeFactor = 5\n local brakeSpeedFactor = 1\n local brakeFlatFactor = 4 \n local autoBrakeSpeed = 15\n -- validate params\n brakeSpeedFactor = math.max(brakeSpeedFactor, 0.01)\n brakeFlatFactor = math.max(brakeFlatFactor, 0.01)\n yawSpeedFactor = math.max(yawSpeedFactor, 0.01)\n yawAccelerationFactor = math.max(yawAccelerationFactor, 0.01)\n --init all the PIDs as global if first flush\n if (rollPID == nil) then rollPID = pid.new(0.2, 0, 10) end\n if (pitchPID == nil) then pitchPID = pid.new(0.2, 0, 10) end\n if (yawPID == nil) then yawPID = pid.new(0.2, 0, 10) end\n if (lateralPID == nil) then lateralPID = pid.new(0.2, 0, 10) end\n if (longitudinalPID == nil) then longitudinalPID = pid.new(0.2, 0, 10) end\n if (distancePID == nil) then distancePID = pid.new(0.2, 0, 10) end\n\n -- final inputs\n if unit.isMouseDirectControlActivated() then\n -- in direct control, we tweak the pitch to behave inbetween virtual joystick and direct control\n -- this helps a lot for ground construct control\n pitchInputFromDevice = utils.clamp(pitchInputFromDevice + system.getControlDeviceForwardInput() * system.getActionUpdateDeltaTime(), -1.0, 1.0)\n else\n pitchInputFromDevice = system.getControlDeviceForwardInput()\n end\n local finalPitchInput = pitchInput + pitchInputFromDevice\n local finalRollInput = rollInput + system.getControlDeviceYawInput()\n local finalYawInput = yawInput - system.getControlDeviceLeftRightInput()\n local combinedRollYawInput = utils.clamp(finalRollInput - finalYawInput, -1.0, 1.0);\n local finalVerticalStrafeInput = verticalStrafeInput\n local finalLateralStrafeInput = lateralStrafeInput;\n local finalBrakeInput = brakeInput\n\n -- Axis\n local worldVertical = vec3(core.getWorldVertical())\n local constructUp = vec3(construct.getWorldOrientationUp())\n local constructForward = vec3(construct.getWorldOrientationForward())\n local constructRight = vec3(construct.getWorldOrientationRight())\n local constructVelocity = vec3(construct.getWorldVelocity())\n local constructVelocityDir = vec3(construct.getWorldVelocity()):normalize()\n local constructAngularVelocity = vec3(construct.getWorldAngularVelocity())\n local constructYawVelocity = constructAngularVelocity:dot(constructUp)\n local constructWorldPosition = vec3(construct.getWorldPosition())\n local constructTargetPosition = vec3(ConstructInitPos)\n\n -- Engine commands\n local keepCollinearity = 0 -- for easier reading\n local dontKeepCollinearity = 1 -- for easier reading\n local tolerancePercentToSkipOtherPriorities = 1 -- if we are within this tolerance (in%), we don't go to the next priorities\n\n -- keeping the start position alignement\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\n local positionDifference = constructTargetPosition - constructWorldPosition\n local lateralOffset = positionDifference:project_on(constructRight):len() * utils.sign(positionDifference:dot(constructRight))\n local longitudinalOffset = positionDifference:project_on(constructForward):len() * utils.sign(positionDifference:dot(constructForward))\n lateralPID:inject(lateralOffset)\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.lateral, lateralPID:get() * StrafeSpeedFactor)\n longitudinalPID:inject(longitudinalOffset)\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.longitudinal, longitudinalPID:get() * StrafeSpeedFactor)\n\n -- Rotation\n local currentRollDeg = getRoll(worldVertical, constructForward, constructRight)\n local currentPitchDeg = -math.asin(constructForward:dot(worldVertical)) * constants.rad2deg\n local targetRollDeg = 0\n local targetPitchDeg = 0\n local targetYawDeg = signedAngleBetween(BaseForward,constructForward,constructUp)*180/math.pi\n rollPID:inject(targetRollDeg - currentRollDeg)\n pitchPID:inject(targetPitchDeg - currentPitchDeg)\n yawPID:inject(-targetYawDeg*yawSpeedFactor)\n \n local constructTargetAngularVelocity = rollPID:get() * constructForward + pitchPID:get() * constructRight + yawPID:get() * constructUp\n\n Nav:setEngineTorqueCommand('torque', constructTargetAngularVelocity, keepCollinearity, 'airfoil', '', '', tolerancePercentToSkipOtherPriorities)\n\n -- moving up or down from TargetAltitude\n local verticalSpeed = constructVelocity:project_on(worldVertical):len()\n local verticalSpeedSigned = verticalSpeed * -utils.sign(constructVelocity:dot(worldVertical))\n local brakeDistance = 0\n local maxBrake = construct.getMaxBrake()\n if maxBrake ~= nil then\n brakeDistance, _ = computeDistanceAndTime(verticalSpeed, 0, construct.getInertialMass(), 0, 0, maxBrake - (core.getGravityIntensity() * construct.getInertialMass()) * utils.sign(verticalSpeedSigned))\n end\n local coreAltitude = core.getAltitude()\n local distance = TargetAltitude - coreAltitude\n local targetDistance = utils.sign(distance) * (math.abs(distance)-brakeDistance)\n distancePID:inject(targetDistance)\n if distancePID:get() > 0.5 or verticalSpeedSigned < -MaxSpeed then --using a 0.5 meter deadband for stabilizing\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, 1)\n elseif distancePID:get() < -0.5 or verticalSpeedSigned > MaxSpeed then\n Nav.axisCommandManager:setThrottleCommand(axisCommandId.vertical, -1)\n else\n Nav.axisCommandManager:resetCommand(axisCommandId.vertical)\n end\n\n --Brakes\n if\n (math.abs(distance) < verticalSpeed)\n or verticalSpeed > MaxSpeed\n or (brakeDistance > math.abs(distance))\n or (finalBrakeInput == 0 and autoBrakeSpeed > 0 and Nav.axisCommandManager.throttle == 0 and constructVelocity:len() < autoBrakeSpeed)\n then\n finalBrakeInput = 1\n end\n local brakeAcceleration = -finalBrakeInput * (brakeSpeedFactor * constructVelocity + brakeFlatFactor * constructVelocityDir)\n \n Nav:setEngineForceCommand('brake', brakeAcceleration)\n\n -- AutoNavigation regroups all the axis command by 'TargetSpeed'\n local autoNavigationEngineTags = ''\n local autoNavigationAcceleration = vec3()\n local autoNavigationUseBrake = false\n\n -- Longitudinal Translation\n local longitudinalEngineTags = 'thrust analog longitudinal'\n local longitudinalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.longitudinal)\n if (longitudinalCommandType == axisCommandType.byThrottle) then\n local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(longitudinalEngineTags,axisCommandId.longitudinal)\n Nav:setEngineForceCommand(longitudinalEngineTags, longitudinalAcceleration, keepCollinearity)\n elseif (longitudinalCommandType == axisCommandType.byTargetSpeed) then\n local longitudinalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.longitudinal)\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. longitudinalEngineTags\n autoNavigationAcceleration = autoNavigationAcceleration + longitudinalAcceleration\n if (Nav.axisCommandManager:getTargetSpeed(axisCommandId.longitudinal) == 0 or -- we want to stop\n Nav.axisCommandManager:getCurrentToTargetDeltaSpeed(axisCommandId.longitudinal) < - Nav.axisCommandManager:getTargetSpeedCurrentStep(axisCommandId.longitudinal) * 0.5) -- if the longitudinal velocity would need some braking\n then\n autoNavigationUseBrake = true\n end\n end\n\n -- Lateral Translation\n local lateralStrafeEngineTags = 'thrust analog lateral'\n local lateralCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.lateral)\n if (lateralCommandType == axisCommandType.byThrottle) then\n local lateralStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(lateralStrafeEngineTags,axisCommandId.lateral)\n Nav:setEngineForceCommand(lateralStrafeEngineTags, lateralStrafeAcceleration, keepCollinearity)\n elseif (lateralCommandType == axisCommandType.byTargetSpeed) then\n local lateralAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.lateral)\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. lateralStrafeEngineTags\n autoNavigationAcceleration = autoNavigationAcceleration + lateralAcceleration\n end\n\n -- Vertical Translation\n local verticalStrafeEngineTags = 'thrust analog vertical'\n local verticalCommandType = Nav.axisCommandManager:getAxisCommandType(axisCommandId.vertical)\n if (verticalCommandType == axisCommandType.byThrottle) then\n local verticalStrafeAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromThrottle(verticalStrafeEngineTags,axisCommandId.vertical)\n Nav:setEngineForceCommand(verticalStrafeEngineTags, verticalStrafeAcceleration, keepCollinearity, 'airfoil', 'ground', '', tolerancePercentToSkipOtherPriorities)\n elseif (verticalCommandType == axisCommandType.byTargetSpeed) then\n local verticalAcceleration = Nav.axisCommandManager:composeAxisAccelerationFromTargetSpeed(axisCommandId.vertical)\n autoNavigationEngineTags = autoNavigationEngineTags .. ' , ' .. verticalStrafeEngineTags\n autoNavigationAcceleration = autoNavigationAcceleration + verticalAcceleration\n end\n\n -- Auto Navigation (Cruise Control)\n if (autoNavigationAcceleration:len() > constants.epsilon) then\n if (brakeInput ~= 0 or autoNavigationUseBrake or math.abs(constructVelocityDir:dot(constructForward)) < 0.95) -- if the velocity is not properly aligned with the forward\n then\n autoNavigationEngineTags = autoNavigationEngineTags .. ', brake'\n end\n Nav:setEngineForceCommand(autoNavigationEngineTags, autoNavigationAcceleration, dontKeepCollinearity, '', '', '', tolerancePercentToSkipOtherPriorities)\n end\n\n -- Rockets\n Nav:setBoosterCommand('rocket_engine')\n end\n}\n\n\nScript.system:onUpdate(systemOnUpdate)\nScript.system:onFlush(systemOnFlush)\n\n--[[\n Chat Commands\n]]\n\nScript.system:onInputText(function (text)\n if text:lower():find('goto:') then\n TargetAltitude = tonumber(text:split(':')[2]) or BaseAltitute\n brakeInput = 0\n system.print('Target Altitude set to ' .. TargetAltitude .. 'm')\n else\n system.print('Unknown command')\n end\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":[]}}}}