MegiRicky

NJBowTurret

Dec 19th, 2024 (edited)
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.85 KB | None | 0 0
  1. local modem = peripheral.wrap("right")
  2. local speaker = peripheral.find("speaker")
  3. local pitchMotor = peripheral.wrap("front")
  4. local yawMotor = peripheral.wrap("back")
  5. local cannon = peripheral.find("createbigcannons:cannon_mount")
  6.  
  7. pitchMotor.setTargetSpeed(0)
  8. yawMotor.setTargetSpeed(0)
  9.  
  10. local cannons = {}
  11. local targetInfo = {}
  12. local controlMode = "auto"
  13. local turnSpeed = 60 -- degrees per second (16 RPM)
  14. local directTurnThreshold = 16
  15.  
  16. local k = 1
  17. local nilCount = 0
  18. local i = 0
  19. local yawErrorSum = 0
  20. local lastYawError = 0
  21. local pitchErrorSum = 0
  22. local lastPitchError = 0
  23. local yawError = 0
  24. local yawIntegral = 0
  25. local yawPrevError = 0
  26. local pitchError = 0
  27. local pitchIntegral = 0
  28. local pitchPrevError = 0
  29. local lastTime = os.clock()
  30.  
  31. local Kp_yaw = 3
  32. local Ki_yaw = 0
  33. local Kd_yaw = 0.05
  34. local Kp_pitch = 4
  35. local Ki_pitch = 0.2
  36. local Kd_pitch = 0.05
  37. local dt = 0.1
  38.  
  39. print("Input the controlChannel number, default: 500")
  40. local controlChannel = io.read()
  41. if controlChannel == "" then
  42. controlChannel = 500
  43. end
  44. controlChannel = tonumber(controlChannel)
  45.  
  46. print("Input the cannon channel number, default: 902")
  47. local cannonChannel = io.read()
  48. if cannonChannel == "" then
  49. cannonChannel = 902
  50. end
  51. cannonChannel = tonumber(cannonChannel)
  52.  
  53. print("Enable pitch yaw limiter, yes/no, default: yes")
  54. local limitor = io.read()
  55. if limitor == "no" then
  56. limitor = false
  57. else
  58. limitor = true
  59. end
  60. local pitchUpperLimit = -6
  61.  
  62. print("Enter the yaw adjustment, default: 0 for NJ")
  63. local yawAdjustment = io.read()
  64. if yawAdjustment == "" then
  65. yawAdjustment = 0
  66. end
  67. local yawAdjustment = tonumber(yawAdjustment)
  68.  
  69. print("Do you want to use pitch, default: yes(for NJ)")
  70. local usePitch = io.read()
  71. if usePitch == "no" then
  72. usePitch = false
  73. else
  74. usePitch = true
  75. end
  76.  
  77. print("Input the muzzle velocity number, default: 840")
  78. local projectileSpeed = io.read()
  79. if projectileSpeed == "" then
  80. projectileSpeed = 840
  81. end
  82. projectileSpeed = tonumber(projectileSpeed)
  83.  
  84. print("Input the gravity acceleration per tick, default: 0.05")
  85. local g = io.read()
  86. if g == "" then
  87. g = 0.05
  88. end
  89. g = tonumber(g)
  90.  
  91. print("Input the drag per tick, default: 0.995")
  92. local cd = io.read()
  93. if cd == "" then
  94. cd = 0.995
  95. end
  96. cd = tonumber(cd)
  97.  
  98. print("input the height correction, default: 6")
  99. local heightCorrection = io.read()
  100. if heightCorrection == "" then
  101. heightCorrection = 6
  102. end
  103. heightCorrection = tonumber(heightCorrection)
  104.  
  105.  
  106. if modem then
  107. modem.open(cannonChannel)
  108. modem.open(controlChannel)
  109. end
  110.  
  111. -- Normalize a vector
  112. local function normalizeVector(v)
  113. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  114. if length == 0 then
  115. return {0, 0, 0}
  116. end
  117. return {v[1] / length, v[2] / length, v[3] / length}
  118. end
  119.  
  120. -- Normalize the rotation matrix
  121. local function normalizeRotationMatrix(rotMatrix)
  122. local normalizedMatrix = {}
  123. for i = 1, #rotMatrix do
  124. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  125. end
  126. return normalizedMatrix
  127. end
  128.  
  129. -- Get the pitch of the ship
  130. local function getPitch()
  131. local rotMatrix = ship.getTransformationMatrix()
  132. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  133. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  134. end
  135. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  136. -- Get the yaw of the ship
  137. local function getYaw()
  138. local rotMatrix = ship.getTransformationMatrix()
  139. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  140. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  141. end
  142.  
  143. -- Get the roll of the ship
  144. local function getRoll()
  145. local rotMatrix = ship.getTransformationMatrix()
  146. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  147. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  148. end
  149.  
  150. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  151. -- Calculate the proportional, integral, and derivative components
  152. local proportional = Kp * error
  153. integral = integral + error * dt -- Accumulate the error for the integral term
  154. local derivative = (error - prevError) / dt
  155.  
  156. -- Calculate the PID output
  157. local output = proportional + (Ki * integral) + (Kd * derivative)
  158.  
  159. -- Return the PID output, updated integral, and current error
  160. return output, integral, error
  161. end
  162.  
  163. -- Yaw control function using PID
  164. local lastYawTime = os.clock()
  165. -- Yaw control function using PID
  166. local function yawControl(deltaYaw, currentYaw)
  167. local now = os.clock()
  168. local dtThisFrame = now - lastYawTime
  169. lastYawTime = now
  170. if dtThisFrame <= 0 then
  171. dtThisFrame = 0.05
  172. end
  173. -- PID controller for yaw
  174. print(dtThisFrame)
  175. local yawSpeed, newIntegral, newPrevError = PIDController(Kp_yaw, Ki_yaw, Kd_yaw, deltaYaw, yawIntegral, yawPrevError, dtThisFrame)
  176.  
  177. -- 2) Update global PID state
  178. yawIntegral = newIntegral
  179. yawPrevError = newPrevError
  180.  
  181. -- Constrain the yaw speed to prevent runaway spinning
  182. yawSpeed = math.max(-10, math.min(10, yawSpeed))
  183.  
  184. yawSpeed = yawSpeed
  185.  
  186. print("deltaYaw: " .. deltaYaw)
  187. print("yawSpeed: " .. yawSpeed)
  188.  
  189. -- Set motor speed based on PID output
  190. yawMotor.setTargetSpeed(-yawSpeed)
  191. end
  192.  
  193. local lastPitchTime = os.clock()
  194. local function pitchControl(deltaPitch, currentPitch)
  195. local now = os.clock()
  196. local dtThisFrame = now - lastPitchTime
  197. lastPitchTime = now
  198. if dtThisFrame <= 0 then
  199. dtThisFrame = 0.05
  200. end
  201. -- PID controller for yaw
  202. local pitchSpeed, pitchIntegral, pitchPrevError = PIDController(Kp_pitch, Ki_pitch, Kd_pitch, deltaPitch, pitchIntegral, pitchPrevError, dtThisFrame)
  203.  
  204. -- Constrain the yaw speed to prevent runaway spinning
  205. pitchSpeed = math.max(-128, math.min(128, pitchSpeed))
  206.  
  207. print("deltaPitch: " .. deltaPitch)
  208. print("pitchSpeed: " .. pitchSpeed)
  209.  
  210. -- Set motor speed based on PID output
  211. pitchMotor.setTargetSpeed(-pitchSpeed)
  212. end
  213.  
  214. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  215.  
  216. local radians = math.rad(angle)
  217. local u = projectileSpeed/20
  218. local part1 = u * math.cos(radians) / math.log(cd)
  219.  
  220. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  221.  
  222. local XR = part1 * part2
  223.  
  224. return XR
  225. end
  226.  
  227. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  228. local bestLowPitch = nil
  229. local bestHighPitch = nil
  230. local bestLowDistance = math.huge
  231. local bestHighDistance = math.huge
  232. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  233. for pitch = 0, 70, 0.01 do -- Iterate over pitch angles
  234. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  235. local distanceDifference = math.abs(calculatedRange - targetDistance)
  236.  
  237. -- Find the low-angle solution
  238. if pitch <= 30 then
  239. if distanceDifference < bestLowDistance then
  240. bestLowDistance = distanceDifference
  241. bestLowPitch = pitch
  242. end
  243. -- Find the high-angle solution
  244. elseif pitch > 30 then
  245. if distanceDifference < bestHighDistance then
  246. bestHighDistance = distanceDifference
  247. bestHighPitch = pitch
  248. end
  249. end
  250. end
  251.  
  252. --prioritize the low-angle solution
  253. return bestLowPitch or bestLowPitch
  254. end
  255.  
  256. local function aimCannon(targetPos, targetVel, sourceX, sourceY, sourceZ)
  257. if sourceX and sourceY and sourceZ then
  258. local currentTime = os.clock()
  259. local dt = currentTime - lastTime
  260. if dt == 0 then return end -- Prevent division by zero
  261. lastTime = currentTime
  262.  
  263. local dx = targetPos.x - sourceX
  264. local dy = targetPos.y - sourceY
  265. local dz = targetPos.z - sourceZ
  266. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  267.  
  268. local estimateX = targetPos.x + targetVel.x * (distance / projectileSpeed)
  269. local estimateY = targetPos.y + targetVel.y * (distance / projectileSpeed)
  270. local estimateZ = targetPos.z + targetVel.z * (distance / projectileSpeed)
  271.  
  272. local dx = estimateX - sourceX
  273. local dy = estimateY - sourceY
  274. local dz = estimateZ - sourceZ
  275.  
  276. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  277. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  278. balisticPitch = findBestPitch(estimateX, estimateY, estimateZ, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  279. print("pitch: "..pitch)
  280. print("balisticPitch: "..balisticPitch)
  281. if balisticPitch > 30 then
  282. pitch = balisticPitch
  283. else
  284. pitch = pitch + balisticPitch
  285. end
  286.  
  287. local yaw = math.deg(math.atan2(-dx, dz))
  288. yaw = (yaw + 180) % 360
  289.  
  290. local currentYaw = math.deg(getYaw()) + yawAdjustment
  291.  
  292. local shipPitch = math.deg(getPitch())
  293. local shipRoll = math.deg(getRoll())
  294. cannonPitch = cannon.getPitch()
  295. --print("cannonPitch: "..cannonPitch)
  296. --print(" shipPitch: "..shipPitch)
  297. --print("shipRoll: "..shipRoll)
  298. local currentPitch = cannonPitch * math.sin(math.rad(90-shipRoll)) + shipPitch
  299. local yawAdjust = cannonPitch * math.cos(math.rad(90 - shipRoll))
  300. --print("yawAd: "..yawAdjust)
  301. if shipRoll < 0 then
  302. currentYaw = currentYaw + math.abs(yawAdjust)
  303. else
  304. currentYaw = currentYaw - math.abs(yawAdjust)
  305. end
  306. if yaw > 360 then yaw = yaw - 360 end
  307. if yaw < 0 then yaw = yaw + 360 end
  308.  
  309. -- Adjust pitch based on distance adjustments
  310. local deltaYaw = (yaw - currentYaw + 180) % 360 - 180
  311. local deltaPitch = pitch - currentPitch
  312.  
  313.  
  314. -- Turning and pitch adjustment logic
  315. parallel.waitForAll(
  316. function() yawControl(deltaYaw, currentYaw) end,
  317. function() pitchControl(deltaPitch, currentPitch) end
  318. )
  319.  
  320. lastCurrentYaw = currentYaw
  321. lastCurrentPitch = currentPitch
  322. end
  323. end
  324.  
  325. local function modemMessage()
  326. while true do
  327. if modem then
  328. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  329. if channel == cannonChannel then
  330. targetInfo = message
  331. elseif channel == controlChannel then
  332. controls = message
  333. end
  334. else
  335. sleep()
  336. end
  337. end
  338. end
  339.  
  340. local function main()
  341. while true do
  342. if not(hideCannon) then
  343. local source = ship.getWorldspacePosition()
  344. local sourceX = source.x
  345. local sourceY = source.y + heightCorrection
  346. local sourceZ = source.z
  347. print(textutils.serialize(targetInfo))
  348.  
  349. if targetInfo and targetInfo.targetPos and targetInfo.targetVel and controlMode == "auto" then
  350. aimCannon(targetInfo.targetPos, targetInfo.targetVel, sourceX, sourceY, sourceZ)
  351. end
  352. end
  353. sleep()
  354. end
  355. end
  356.  
  357. local function modeSwitch()
  358. while true do
  359. if redstone.getInput("back") then
  360. if controlMode == "auto" then
  361. controlMode = "manual"
  362. redstone.setOutput("top",false)
  363. redstone.setOutput("bottom",false)
  364. redstone.setOutput("left",false)
  365. redstone.setOutput("right",false)
  366. else
  367. controlMode = "auto"
  368. end
  369. end
  370. sleep()
  371. end
  372. end
  373.  
  374. parallel.waitForAny(
  375. modemMessage,
  376. main,
  377. modeSwitch
  378. )
  379.  
Advertisement
Add Comment
Please, Sign In to add comment