MegiRicky

55aCIWS.lua

Nov 30th, 2024 (edited)
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.31 KB | None | 0 0
  1. local radar = peripheral.find("sp_radar")
  2. local modem = peripheral.find("modem")
  3.  
  4. local friendlyIDs
  5. local friendlyIDFile = "friendly_ids.txt"
  6. local scanInterval = 0.01
  7.  
  8. local mode = "auto" --Auto targeting mode, target the cloeset target
  9. local redstoneTimeout = 30
  10. local cycleIndex = 1
  11. local lastRedstoneInputTime = os.clock()
  12.  
  13. local yawErrorSum = 0
  14. local lastYawError = 0
  15. local pitchErrorSum = 0
  16. local lastPitchError = 0
  17. local yawError = 0
  18. local yawIntegral = 0
  19. local yawPrevError = 0
  20. local pitchError = 0
  21. local pitchIntegral = 0
  22. local pitchPrevError = 0
  23. local lastTime = os.clock()
  24.  
  25. local Kp_yaw = 7
  26. local Ki_yaw = 0
  27. local Kd_yaw = 0.05
  28. local Kp_pitch = 0.5
  29. local Ki_pitch = 0
  30. local Kd_pitch = 0.01
  31. local dt = 0.1
  32. local dt1,dt2
  33. local accelerationFactor = 0.2
  34. local velocityFactor = 1
  35.  
  36. local spreadYawRange = 1 -- Max spread angle for yaw (in degrees)
  37. local spreadPitchRange = 1 -- Max spread angle for pitch (in degrees)
  38.  
  39. local controls = {}
  40.  
  41. local cannon = peripheral.find("cbc_cannon_mount")
  42. if not(cannon) then
  43. cannon = peripheral.find("cbcmf_compact_cannon_mount")
  44. end
  45.  
  46. print("press enter to assemble cannons")
  47. cannon.assemble()
  48.  
  49. local function readFriendlyIDs(filename)
  50. if not fs.exists(filename) then
  51. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  52. local file = fs.open(filename, "w")
  53. print("Input friendly IDs (player names) separated by commas:")
  54. local ids = io.read()
  55. file.write(ids)
  56. file.close()
  57. else
  58. print("Do you want to edit the friendly player id config? (yes/no),press enter to skip")
  59. local editChoice = io.read()
  60. if editChoice == "" then
  61. editChoice = "no"
  62. end
  63. if editChoice:lower() == "yes" then
  64. if fs.exists(filename) then
  65. fs.delete(filename)
  66. print("Friendly IDs file '" .. filename .. "' does not exist. Creating it.")
  67. local file = fs.open(filename, "w")
  68. print("Input friendly IDs (player names) separated by commas:")
  69. local ids = io.read()
  70. file.write(ids)
  71. file.close()
  72. end
  73. end
  74. end
  75.  
  76. local file = fs.open(filename, "r")
  77. local friendlyIDs = {}
  78. if file then
  79. local line = file.readLine()
  80. while line do
  81. print("Line read: " .. line) -- Debug print for the line
  82.  
  83. -- Split the line by commas and insert each name into the friendlyIDs table
  84. for name in string.gmatch(line, '([^,]+)') do
  85. print("Friendly ID (Name): " .. name) -- Debug print for each name
  86. table.insert(friendlyIDs, name) -- Store the player name
  87. end
  88. line = file.readLine() -- Read the next line
  89. end
  90. file.close()
  91. end
  92. return friendlyIDs
  93. end
  94.  
  95. -- Function to check if a player ID is friendly
  96. local function isFriendly(playerID)
  97. for _, friendlyID in ipairs(friendlyIDs) do
  98. if playerID == friendlyID then
  99. return true
  100. end
  101. end
  102. return false
  103. end
  104.  
  105. -- Read friendly IDs from the file
  106. local function saveSettingsToFile(filename, settings)
  107. local file = fs.open(filename, "w")
  108. if file then
  109. file.write(textutils.serialize(settings))
  110. file.close()
  111. print("Settings saved to '" .. filename .. "'")
  112. else
  113. print("Failed to save settings.")
  114. end
  115. end
  116.  
  117. local function loadSettingsFromFile(filename)
  118. if not fs.exists(filename) then
  119. return nil
  120. end
  121.  
  122. local file = fs.open(filename, "r")
  123. local settings = textutils.unserialize(file.readAll())
  124. file.close()
  125. return settings
  126. end
  127.  
  128. local function askForInput(prompt, defaultValue)
  129. print(prompt .. " (default: " .. defaultValue .. "):")
  130. local input = io.read()
  131. if input == "" then
  132. return defaultValue
  133. else
  134. return tonumber(input) or input
  135. end
  136. end
  137.  
  138. local function createSettings()
  139. local settings = {}
  140. settings.auto = askForInput("Enable auto fire, yes/no note that you need redstone input to anyside of the computer (safetly measure)", "yes") == "yes"
  141. --settings.velocityFactor = askForInput("Input the velocityFactor", 1)
  142. settings.controlChannel = askForInput("Input the control channel",500)
  143. settings.projectileSpeed = askForInput("Input the muzzle velocity number", 160)
  144. settings.g = askForInput("Input the gravity acceleration per tick", 0.025)
  145. settings.cd = askForInput("Input the drag per tick", 0.99)
  146. settings.autoSpread = askForInput("Enable automatic spread, yes/no", "yes") == "yes"
  147. settings.lengthCorrection = askForInput("Enter cannon source ship length correction", 35)
  148. settings.heightCorrection = askForInput("Enter cannon source ship height correction", 5)
  149. settings.widthCorrection = askForInput("Enter the cannon source ship width correction, positive if the ship is at the right side",0)
  150. settings.limitor = askForInput("Enable pitch yaw limiter, yes/no", "yes") == "yes"
  151. settings.pitchLowerLimit = askForInput("Ignore the follwing if no limitr. Input the pitch lower limit, default: -10",-10)
  152. settings.pitchUpperLimit = askForInput("Input the pitch lower limit, default: 90",90)
  153. settings.yawLowerLimit = askForInput("Input the yaw lower limit, default: -120",-120)
  154. settings.yawUpperLimit = askForInput("Input the pitch lower limit, default: 120",120)
  155.  
  156. return settings
  157. end
  158.  
  159. local function createPresetSettings()
  160. local presets = {
  161. {
  162. filename = "ussNJport1CIWS_settings.txt",
  163. settings = {
  164. controlsChannel = 500,
  165. velocityFactor = 1,
  166. projectileSpeed = 160,
  167. g = 0.005,
  168. cd = 1,
  169. autoSpread = true,
  170. lengthCorrection = 17,
  171. heightCorrection = 24,
  172. widthCorrection = -7,
  173. limitor = true,
  174. pitchLowerLimit = -10,
  175. pitchUpperLimit = 90,
  176. yawLowerLimit = -150,
  177. yawUpperLimit = 0,
  178. auto = true
  179. }
  180. },
  181. {
  182. filename = "ussNJstarboard1CIWS_settings.txt",
  183. settings = {
  184. controlsChannel = 500,
  185. velocityFactor = 1,
  186. projectileSpeed = 160,
  187. g = 0.005,
  188. cd = 1,
  189. autoSpread = true,
  190. lengthCorrection = 17,
  191. heightCorrection = 24,
  192. widthCorrection = 7,
  193. limitor = true,
  194. pitchLowerLimit = -10,
  195. pitchUpperLimit = 90,
  196. yawLowerLimit = 0,
  197. yawUpperLimit = 150,
  198. auto = true
  199. }
  200. },
  201. {
  202. filename = "ussNJport2CIWS_settings.txt",
  203. settings = {
  204. controlsChannel = 500,
  205. velocityFactor = 1,
  206. projectileSpeed = 160,
  207. g = 0.005,
  208. cd = 1,
  209. autoSpread = true,
  210. lengthCorrection = -14,
  211. heightCorrection = 21,
  212. widthCorrection = -6,
  213. limitor = true,
  214. pitchLowerLimit = -10,
  215. pitchUpperLimit = 90,
  216. yawLowerLimit = -180,
  217. yawUpperLimit = -20,
  218. auto = true
  219. }
  220. },
  221. {
  222. filename = "ussNJstarboard2CIWS_settings.txt",
  223. settings = {
  224. controlsChannel = 500,
  225. velocityFactor = 1,
  226. projectileSpeed = 160,
  227. g = 0.005,
  228. cd = 1,
  229. autoSpread = true,
  230. lengthCorrection = -14,
  231. heightCorrection = 21,
  232. widthCorrection = 6,
  233. limitor = true,
  234. pitchLowerLimit = -10,
  235. pitchUpperLimit = 90,
  236. yawLowerLimit = 0,
  237. yawUpperLimit = 200,
  238. auto = true
  239. }
  240. },
  241. {
  242. filename = "type55BowCIWS_settings.txt",
  243. settings = {
  244. controlsChannel = 500,
  245. velocityFactor = 1,
  246. projectileSpeed = 200,
  247. g = 0.005,
  248. cd = 1,
  249. autoSpread = true,
  250. lengthCorrection = 34,
  251. heightCorrection = 9,
  252. widthCorrection = 0,
  253. pitchLowerLimit = -10,
  254. pitchUpperLimit = 90,
  255. yawLowerLimit = -120,
  256. yawUpperLimit = 120,
  257. limitor = true,
  258. auto = true
  259. }
  260. },
  261. {
  262. filename = "type55port1_settings.txt",
  263. settings = {
  264. controlsChannel = 500,
  265. velocityFactor = 1,
  266. projectileSpeed = 200,
  267. g = 0.005,
  268. cd = 1,
  269. autoSpread = true,
  270. lengthCorrection = -42,
  271. heightCorrection = 12,
  272. widthCorrection = -8,
  273. pitchLowerLimit = -20,
  274. pitchUpperLimit = 90,
  275. yawLowerLimit = -160,
  276. yawUpperLimit = -20,
  277. limitor = true,
  278. auto = true
  279. }
  280. },
  281. {
  282. filename = "type55port2_settings.txt",
  283. settings = {
  284. controlsChannel = 500,
  285. velocityFactor = 1,
  286. projectileSpeed = 200,
  287. g = 0.005,
  288. cd = 1,
  289. autoSpread = true,
  290. lengthCorrection = -52,
  291. heightCorrection = 12,
  292. widthCorrection = -8,
  293. pitchLowerLimit = -20,
  294. pitchUpperLimit = 90,
  295. yawLowerLimit = -200,
  296. yawUpperLimit = -20,
  297. limitor = true,
  298. auto = true
  299. }
  300. },
  301. {
  302. filename = "type55starboard1_settings.txt",
  303. settings = {
  304. controlsChannel = 500,
  305. velocityFactor = 1,
  306. projectileSpeed = 200,
  307. g = 0.005,
  308. cd = 1,
  309. autoSpread = true,
  310. lengthCorrection = -42,
  311. heightCorrection = 12,
  312. widthCorrection = 8,
  313. pitchLowerLimit = -20,
  314. pitchUpperLimit = 90,
  315. yawLowerLimit = 20,
  316. yawUpperLimit = 160,
  317. limitor = true,
  318. auto = true
  319. }
  320. },
  321. {
  322. filename = "type55starboard2_settings.txt",
  323. settings = {
  324. controlsChannel = 500,
  325. velocityFactor = 1,
  326. projectileSpeed = 200,
  327. g = 0.005,
  328. cd = 1,
  329. autoSpread = true,
  330. lengthCorrection = -52,
  331. heightCorrection = 12,
  332. widthCorrection = 8,
  333. pitchLowerLimit = -20,
  334. pitchUpperLimit = 90,
  335. yawLowerLimit = 20,
  336. yawUpperLimit = 160,
  337. limitor = true,
  338. auto = true
  339. }
  340. },
  341. {
  342. filename = "TuoCChiangCIWS_settings.txt",
  343. settings = {
  344. controlsChannel = 500,
  345. velocityFactor = 1,
  346. projectileSpeed = 120,
  347. g = 0.005,
  348. cd = 1,
  349. autoSpread = true,
  350. lengthCorrection = -10,
  351. heightCorrection = 7,
  352. widthCorrection = 0,
  353. pitchLowerLimit = -20,
  354. pitchUpperLimit = 90,
  355. yawLowerLimit = 60,
  356. yawUpperLimit = 300,
  357. limitor = false,
  358. auto = true
  359. }
  360. },
  361. {
  362. filename = "ZTZ99CIWS_settings.txt",
  363. settings = {
  364. controlsChannel = 500,
  365. velocityFactor = 1,
  366. projectileSpeed = 160,
  367. g = 0.005,
  368. cd = 1,
  369. autoSpread = true,
  370. lengthCorrection = -1,
  371. heightCorrection = 1.5,
  372. widthCorrection = 1,
  373. limitor = true,
  374. pitchLowerLimit = -12,
  375. pitchUpperLimit = 90,
  376. yawLowerLimit = -360,
  377. yawUpperLimit = 360,
  378. auto = true
  379. }
  380. },
  381. {
  382. filename = "YunBao_settings.txt",
  383. settings = {
  384. controlsChannel = 500,
  385. velocityFactor = 1,
  386. projectileSpeed = 160,
  387. g = 0.005,
  388. cd = 1,
  389. autoSpread = true,
  390. lengthCorrection = 0,
  391. heightCorrection = 1.2,
  392. widthCorrection = 1,
  393. limitor = true,
  394. pitchLowerLimit = -8,
  395. pitchUpperLimit = 90,
  396. yawLowerLimit = -360,
  397. yawUpperLimit = 360,
  398. auto = true
  399. }
  400. },
  401. {
  402. filename = "EMBTCIWS_settings.txt",
  403. settings = {
  404. controlsChannel = 2000,
  405. velocityFactor = 1,
  406. projectileSpeed = 160,
  407. g = 0.005,
  408. cd = 1,
  409. autoSpread = true,
  410. lengthCorrection = -0.5,
  411. heightCorrection = 1.5,
  412. widthCorrection = 1,
  413. limitor = true,
  414. pitchLowerLimit = -12,
  415. pitchUpperLimit = 90,
  416. yawLowerLimit = -360,
  417. yawUpperLimit = 360,
  418. auto = true
  419. }
  420. },
  421. {
  422. filename = "CIWStruck_settings.txt",
  423. settings = {
  424. controlsChannel = 500,
  425. velocityFactor = 1,
  426. projectileSpeed = 160,
  427. g = 0.005,
  428. cd = 1,
  429. autoSpread = false,
  430. lengthCorrection = 0,
  431. heightCorrection = 0,
  432. widthCorrection = 0,
  433. limitor = true,
  434. auto = false
  435. }
  436. }
  437. }
  438.  
  439. for _, preset in ipairs(presets) do
  440. if true then
  441. saveSettingsToFile(preset.filename, preset.settings)
  442. print("Created preset settings: " .. preset.filename)
  443. end
  444. end
  445. end
  446.  
  447. local function handleSettings()
  448. print("Checking for existing settings...")
  449. createPresetSettings()
  450.  
  451. -- List available settings
  452. local settingsFiles = fs.list("/")
  453. local settingsFilesFound = false
  454. local settingsFilesList = {}
  455.  
  456. for _, file in ipairs(settingsFiles) do
  457. if string.match(file, "_settings.txt") then
  458. table.insert(settingsFilesList, file)
  459. settingsFilesFound = true
  460. end
  461. end
  462.  
  463. if not settingsFilesFound then
  464. print("No settings found. Please create a new one.")
  465. local filename = askForInput("Enter a name for the new settings file", "example_settings.txt")
  466. local settings = createSettings()
  467. saveSettingsToFile(filename, settings)
  468. return settings
  469. else
  470. print("Available settings:")
  471.  
  472. local pageSize = 10 -- Number of settings to display per page
  473. local totalFiles = #settingsFilesList
  474. local currentPage = 1
  475. local totalPages = math.ceil(totalFiles / pageSize)
  476.  
  477. while currentPage <= totalPages do
  478. local startIdx = (currentPage - 1) * pageSize + 1
  479. local endIdx = math.min(startIdx + pageSize - 1, totalFiles)
  480.  
  481. -- Display a batch of settings files
  482. for i = startIdx, endIdx do
  483. print(i .. ". " .. settingsFilesList[i])
  484. end
  485.  
  486. if currentPage < totalPages then
  487. print("\nPress Enter to see more settings...")
  488. io.read() -- Wait for the user to press Enter
  489. end
  490.  
  491. currentPage = currentPage + 1
  492. end
  493.  
  494. local selection = askForInput("Select an existing setting to load or create a new one (1-" .. totalFiles .. " or new)", "new")
  495.  
  496. if selection == "new" then
  497. local filename = askForInput("Enter a name for the new settings file", "settings.txt")
  498. local settings = createSettings()
  499. saveSettingsToFile(filename, settings)
  500. return settings
  501. else
  502. local filename = settingsFilesList[tonumber(selection)]
  503. local settings = loadSettingsFromFile(filename)
  504. print("Loaded settings from '" .. filename .. "'")
  505.  
  506. local editChoice = askForInput("Do you want to edit this setting? (yes/no)", "no")
  507. if editChoice == "yes" then
  508. local newSettings = createSettings()
  509. saveSettingsToFile(filename, newSettings)
  510. return newSettings
  511. else
  512. return settings
  513. end
  514. end
  515. end
  516. end
  517.  
  518. -- Normalize a vector
  519. local function normalizeVector(v)
  520. local length = math.sqrt(v[1]^2 + v[2]^2 + v[3]^2)
  521. if length == 0 then
  522. return {0, 0, 0}
  523. end
  524. return {v[1] / length, v[2] / length, v[3] / length}
  525. end
  526.  
  527. -- Normalize the rotation matrix
  528. local function normalizeRotationMatrix(rotMatrix)
  529. local normalizedMatrix = {}
  530. for i = 1, #rotMatrix do
  531. normalizedMatrix[i] = normalizeVector(rotMatrix[i])
  532. end
  533. return normalizedMatrix
  534. end
  535.  
  536. -- Get the pitch of the ship
  537. local function getPitch()
  538. local rotMatrix = ship.getTransformationMatrix()
  539. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  540. return math.asin(normalizedMatrix[2][3]) -- Extract pitch from the matrix
  541. end
  542. --pitch = math.deg(math.asin(ship.getTransformationMatrix()[2][3]))
  543. -- Get the yaw of the ship
  544. local function getYaw()
  545. local rotMatrix = ship.getTransformationMatrix()
  546. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  547. return math.atan2(-normalizedMatrix[3][1], -normalizedMatrix[3][3]) -- Extract yaw from the matrix
  548. end
  549.  
  550. -- Get the roll of the ship
  551. local function getRoll()
  552. local rotMatrix = ship.getTransformationMatrix()
  553. local normalizedMatrix = normalizeRotationMatrix(rotMatrix)
  554. return math.atan2(normalizedMatrix[2][1], normalizedMatrix[2][2]) -- Extract roll from the matrix
  555. end
  556.  
  557. -- Main execution
  558. local settings = handleSettings()
  559.  
  560. -- Use the settings in your code
  561. print("Using settings:")
  562. print(textutils.serialize(settings))
  563. velocityFactor = tonumber(askForInput("Input the velocity factor (for compensating physic speed lag)",1))
  564. g = tonumber(settings.g)
  565. lengthCorrection = tonumber(settings.lengthCorrection)
  566. heightCorrection = tonumber(settings.heightCorrection)
  567. widthCorrection = tonumber(settings.widthCorrection)
  568. cd = tonumber(settings.cd)
  569. projectileSpeed = tonumber(settings.projectileSpeed)
  570. auto = settings.auto
  571. limitor = settings.limitor
  572. autoSpread = settings.autoSpread
  573.  
  574. if modem then
  575. modem.open(settings.controlsChannel)
  576. end
  577.  
  578. friendlyIDs = readFriendlyIDs(friendlyIDFile)
  579. print("Friendly IDs: " .. textutils.serialize(friendlyIDs)) -- Debug print
  580.  
  581. if cannon.assemble() then
  582. print("asseble failed, press enter to contiue")
  583. io.read()
  584. end
  585.  
  586. local function PIDController(Kp, Ki, Kd, error, integral, prevError, dt)
  587. -- Calculate the proportional, integral, and derivative components
  588. local proportional = Kp * error
  589. integral = integral + error * dt -- Accumulate the error for the integral term
  590. local derivative = (error - prevError) / dt
  591.  
  592. -- Calculate the PID output
  593. local output = proportional + (Ki * integral) + (Kd * derivative)
  594.  
  595. -- Return the PID output, updated integral, and current error
  596. return output, integral, error
  597. end
  598.  
  599. local function calculateVelocity(pos1, pos2, dt)
  600. local vx = (pos2[1] - pos1[1]) / dt
  601. local vy = (pos2[2] - pos1[2]) / dt
  602. local vz = (pos2[3] - pos1[3]) / dt
  603. return {x=vx, y=0, z=vz}
  604. end
  605.  
  606. local function calculateAcceleration(vel1, vel2, dt)
  607. local ax = (vel2.x - vel1.x) / dt
  608. local ay = (vel2.y - vel1.y) / dt
  609. local az = (vel2.z - vel1.z) / dt
  610. return {x = ax, y = ay, z = az}
  611. end
  612.  
  613. local function estimatePosition(pos, velocity, acceleration, time)
  614. local shipVelocity = ship.getVelocity()
  615. local estX = pos.x + (velocity.x - shipVelocity.x) * velocityFactor * time + 0.5 * acceleration.x * time^2
  616. local estY = pos.y + (velocity.y - shipVelocity.y) * velocityFactor * time + 0.5 * acceleration.y * time^2
  617. local estZ = pos.z + (velocity.z - shipVelocity.z) * velocityFactor * time + 0.5 * acceleration.z * time^2
  618. return {x = estX, y = estY, z = estZ}
  619. end
  620.  
  621. local function findRelativeAngle(targetYaw,targetPitch)
  622. rot = ship.getQuaternion()
  623. cacheYaw = math.pi - math.rad(targetYaw)
  624. cachePitch = - math.rad(targetPitch)
  625. rotMatAdj11 = 1 - 2*(rot.x^2 + rot.y^2)
  626. rotMatAdj12 = 2*(rot.z * rot.x + rot.y * rot.w)
  627. rotMatAdj13 = 2*(rot.z * rot.y - rot.x * rot.w)
  628. rotMatAdj21 = 2*(rot.z * rot.x - rot.y * rot.w)
  629. rotMatAdj22 = 1 - 2*(rot.z^2 + rot.y^2)
  630. rotMatAdj23 = 2*(rot.x * rot.y + rot.z * rot.w)
  631. rotMatAdj31 = 2*(rot.z * rot.y + rot.x * rot.w)
  632. rotMatAdj32 = 2*(rot.x * rot.y - rot.z * rot.w)
  633. rotMatAdj33 = 1 - 2*(rot.z^2 + rot.x^2)
  634.  
  635. rotMatTGT11 = math.cos(cacheYaw) * math.cos(cachePitch)
  636. rotMatTGT21 = math.sin(cacheYaw) * math.cos(cachePitch)
  637. rotMatTGT31 = - math.sin(cachePitch)
  638.  
  639. rotMatRSLT11 = rotMatAdj11 * rotMatTGT11 + rotMatAdj12 * rotMatTGT21 + rotMatAdj13 * rotMatTGT31
  640. rotMatRSLT21 = rotMatAdj21 * rotMatTGT11 + rotMatAdj22 * rotMatTGT21 + rotMatAdj23 * rotMatTGT31
  641. rotMatRSLT31 = rotMatAdj31 * rotMatTGT11 + rotMatAdj32 * rotMatTGT21 + rotMatAdj33 * rotMatTGT31
  642.  
  643. turretYaw = math.atan2(rotMatRSLT21, rotMatRSLT11)
  644. barrelPitch = math.asin(-rotMatRSLT31)
  645. return math.deg(-turretYaw),math.deg(-barrelPitch)
  646. end
  647.  
  648. local function calculateRange(angle, u, cd, g, c_est, projectileSpeed)
  649. local radians = math.rad(angle)
  650. local u = projectileSpeed/20
  651. local part1 = u * math.cos(radians) / math.log(cd)
  652. local part2 = ((g * cd) / (g * cd + (1 - cd) * u * math.sin(radians))) ^ (2 + c_est * projectileSpeed * math.sin(radians)) - 1
  653. local XR = part1 * part2
  654.  
  655. return XR
  656. end
  657.  
  658. local function findBestPitch(targetX, targetY, targetZ, sourceX, sourceY, sourceZ, initialVelocity, g, cd, c_est, projectileSpeed)
  659. local bestLowPitch = nil
  660. local bestHighPitch = nil
  661. local bestLowDistance = math.huge
  662. local bestHighDistance = math.huge
  663. local targetDistance = math.sqrt((targetX - sourceX)^2 + (targetZ - sourceZ)^2)
  664.  
  665. for pitch = 0, 90, 0.1 do -- Iterate over pitch angles
  666. local calculatedRange = calculateRange(pitch, initialVelocity, cd, g, c_est, projectileSpeed)
  667. local distanceDifference = math.abs(calculatedRange - targetDistance)
  668.  
  669. -- Find the low-angle solution
  670. if pitch <= 30 then
  671. if distanceDifference < bestLowDistance then
  672. bestLowDistance = distanceDifference
  673. bestLowPitch = pitch
  674. end
  675. -- Find the high-angle solution
  676. elseif pitch > 30 then
  677. if distanceDifference < bestHighDistance then
  678. bestHighDistance = distanceDifference
  679. bestHighPitch = pitch
  680. end
  681. end
  682. end
  683.  
  684. -- If the target is within 400 blocks, prioritize the low-angle solution
  685. return bestLowPitch
  686. end
  687.  
  688. local function applySpread(targetYaw, targetPitch, distance)
  689. -- Avoid division by zero
  690. if distance < 1 then distance = 1 end
  691.  
  692. -- Adjust angle spread inversely with distance (constant spatial spread)
  693. -- Example: spreadAngle = atan(spreadSize / distance)
  694. -- Let’s assume a constant spread size of 1 block/metre
  695. local spatialSpreadSize = 1 -- change as needed
  696. local effectiveYawSpread = math.deg(math.atan(spatialSpreadSize / distance)) * spreadYawRange
  697. local effectivePitchSpread = math.deg(math.atan(spatialSpreadSize / distance)) * spreadPitchRange
  698.  
  699. -- Apply the adjusted spread
  700. local yawSpread = (math.random() * 2 - 1) * effectiveYawSpread
  701. local pitchSpread = (math.random() * 2 - 1) * effectivePitchSpread
  702.  
  703. local newYaw = targetYaw + yawSpread
  704. local newPitch = targetPitch + pitchSpread
  705.  
  706. return newYaw, newPitch
  707. end
  708.  
  709. local lastTargetPos, lastTargetVelocity, predictedTargetVelocity, predictedTargetAcceleration
  710. local lastTargetAqquireTime = os.clock()
  711.  
  712. local function predictFuturePosition(targetPos, targetVel, sourceX, sourceY, sourceZ)
  713. local currentTime = os.clock()
  714. local dt = currentTime - lastTargetAqquireTime
  715.  
  716. -- Initialize predictedVelocity & predictedAcceleration if needed
  717. if not lastTargetPos then
  718. lastTargetPos = targetPos
  719. lastTargetVelocity = targetVel
  720. predictedTargetVelocity = targetVel
  721. predictedTargetAcceleration = {x = 0, y = 0, z = 0}
  722. lastTargetAqquireTime = currentTime
  723. elseif dt >= 0.5 then
  724. -- Estimate velocity
  725. predictedTargetVelocity = {
  726. x = (targetPos.x - lastTargetPos.x) / dt,
  727. y = (targetPos.y - lastTargetPos.y) / dt,
  728. z = (targetPos.z - lastTargetPos.z) / dt
  729. }
  730.  
  731. -- Estimate acceleration
  732. predictedTargetAcceleration = {
  733. x = (predictedTargetVelocity.x - lastTargetVelocity.x) / dt,
  734. y = (predictedTargetVelocity.y - lastTargetVelocity.y) / dt,
  735. z = (predictedTargetVelocity.z - lastTargetVelocity.z) / dt
  736. }
  737.  
  738. -- Update previous values
  739. lastTargetPos = targetPos
  740. lastTargetVelocity = predictedTargetVelocity
  741. lastTargetAqquireTime = currentTime
  742. end
  743.  
  744. -- Compute initial distance to target
  745. local dx = targetPos.x - sourceX
  746. local dy = targetPos.y - sourceY
  747. local dz = targetPos.z - sourceZ
  748. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  749.  
  750. -- Get ship's velocity
  751. local shipVelocity = ship.getVelocity()
  752.  
  753. -- Initial estimate for travel time
  754. local estimateTime = distance / projectileSpeed + 0.2
  755.  
  756. -- Predict future position using velocity and acceleration
  757. local estimateX = targetPos.x
  758. + (predictedTargetVelocity.x * velocityFactor - shipVelocity.x) * estimateTime
  759. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  760.  
  761. local estimateY = targetPos.y
  762. + (predictedTargetVelocity.y * velocityFactor - shipVelocity.y) * estimateTime
  763. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  764.  
  765. local estimateZ = targetPos.z
  766. + (predictedTargetVelocity.z * velocityFactor - shipVelocity.z) * estimateTime
  767. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  768.  
  769. -- Recalculate distance after initial estimate
  770. dx = estimateX - sourceX
  771. dy = estimateY - sourceY
  772. dz = estimateZ - sourceZ
  773. distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  774.  
  775. -- Refine estimateTime
  776. estimateTime = distance / projectileSpeed + 0.2
  777.  
  778. -- Recompute future position with refined time
  779. estimateX = targetPos.x
  780. + (predictedTargetVelocity.x * velocityFactor - shipVelocity.x) * estimateTime
  781. + 0.5 * predictedTargetAcceleration.x * estimateTime * estimateTime
  782.  
  783. estimateY = targetPos.y
  784. + (predictedTargetVelocity.y * velocityFactor - shipVelocity.y) * estimateTime
  785. + 0.5 * predictedTargetAcceleration.y * estimateTime * estimateTime
  786.  
  787. estimateZ = targetPos.z
  788. + (predictedTargetVelocity.z * velocityFactor - shipVelocity.z) * estimateTime
  789. + 0.5 * predictedTargetAcceleration.z * estimateTime * estimateTime
  790.  
  791. return {x = estimateX, y = estimateY, z = estimateZ}
  792. end
  793.  
  794.  
  795. local requiredRelativePitch,requiredRelativeYaw = 0,0
  796. local function aimCannon(targetPos, targetVel, targetAcc, sourceX, sourceY, sourceZ)
  797. if sourceX and sourceY and sourceZ then
  798. local futurePos = predictFuturePosition(targetPos, targetVel, sourceX, sourceY, sourceZ)
  799. --print(textutils.serialize(futurePos))
  800. -- Calculate the new dx, dy, dz for the predicted future position
  801. dx = futurePos.x - sourceX
  802. dy = futurePos.y - sourceY
  803. dz = futurePos.z - sourceZ
  804.  
  805. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  806. local horizontalDistance = math.sqrt(dx * dx + dz * dz)
  807. local pitch = math.deg(math.atan2(dy, horizontalDistance))
  808.  
  809. local yaw = math.deg(math.atan2(-dx, dz))
  810. yaw = (yaw + 180) % 360
  811.  
  812. --Adjust pitch based on distance adjustments
  813. pitch = pitch + findBestPitch(futurePos.x, futurePos.y, futurePos.z, sourceX, sourceY, sourceZ, projectileSpeed, g, cd, 0.0028, projectileSpeed)
  814. local shipYaw = math.deg(getYaw())
  815. if shipYaw < 0 then shipYaw = shipYaw + 360 end
  816.  
  817. requiredRelativeYaw = yaw - shipYaw
  818. if requiredRelativeYaw > 180 then
  819. requiredRelativeYaw = requiredRelativeYaw - 360
  820. elseif requiredRelativeYaw < -180 then
  821. requiredRelativeYaw = requiredRelativeYaw + 360
  822. end
  823.  
  824. yaw, pitch = applySpread(yaw, pitch, distance)
  825.  
  826. requiredRelativeYaw,requiredRelativePitch = findRelativeAngle(yaw,pitch)
  827. locked = true
  828. if limitor then
  829. if requiredRelativeYaw < settings.yawLowerLimit then
  830. requiredRelativeYaw = settings.yawLowerLimit
  831. locked = false
  832. elseif requiredRelativeYaw > settings.yawUpperLimit then
  833. requiredRelativeYaw = settings.yawUpperLimit
  834. locked = false
  835. end
  836. if requiredRelativePitch < settings.pitchLowerLimit then
  837. requiredRelativePitch = settings.pitchLowerLimit
  838. locked = false
  839. elseif requiredRelativePitch > settings.pitchUpperLimit then
  840. requiredRelativePitch = settings.pitchUpperLimit
  841. locked = false
  842. end
  843. end
  844.  
  845. end
  846. end
  847.  
  848. local function setPitchYaw()
  849. while true do
  850. if requiredRelativeYaw and requiredRelativePitch then
  851. --print("setting angle yaw: "..requiredRelativeYaw.." pitch: "..requiredRelativePitch)
  852. cannon.setPitch(requiredRelativePitch)
  853. cannon.setYaw(requiredRelativeYaw)
  854. end
  855. sleep()
  856. end
  857. end
  858.  
  859. local function calculateSpeed(velocity)
  860. return math.sqrt(velocity.x^2 + velocity.y^2 + velocity.z^2)
  861. end
  862.  
  863. local function calculateAcceleration(vel1, vel2, dt)
  864. local ax = (vel2.x - vel1.x) / dt * accelerationFactor
  865. local ay = (vel2.y - vel1.y) / dt * accelerationFactor
  866. local az = (vel2.z - vel1.z) / dt * accelerationFactor
  867. return {x = ax, y = ay, z = az}
  868. end
  869.  
  870. local function estimatePosition(pos, velocity, acceleration, time)
  871. local estX = pos.x + velocity.x * velocityFactor * time + 0.5 * acceleration.x * time^2
  872. local estY = pos.y + velocity.y * velocityFactor * time + 0.5 * acceleration.y * time^2
  873. local estZ = pos.z + velocity.z * velocityFactor * time + 0.5 * acceleration.z * time^2
  874. return {x = estX, y = estY, z = estZ}
  875. end
  876.  
  877. local function updateMode()
  878. if redstone.getInput("top") or (controls and controls.targetSwitch) then
  879. lastRedstoneInputTime = os.clock()
  880. mode = "cycle"
  881. elseif os.clock() - lastRedstoneInputTime > redstoneTimeout then
  882. mode = "auto"
  883. end
  884. end
  885.  
  886. -- Function to get the closest target (players or ships)
  887. local function getClosestTarget()
  888. local targetScan1 = radar.scanForPlayers(400)
  889. local shipScan1 = radar.scanForShips(400) -- Scan for ships (e.g., missiles) within 1000 units
  890.  
  891. -- Variables to hold the closest target data
  892. local closestTarget = nil
  893. local closestDistance = math.huge
  894. local targetPos1 = nil
  895. local targetInfo = nil
  896. local targets = {}
  897. local highestSpeed = 0
  898.  
  899. for _, player in pairs(targetScan1) do
  900. if player and player.pos then
  901. local dx = player.pos[1] - shipPos.x
  902. local dy = player.pos[2] - shipPos.y
  903. local dz = player.pos[3] - shipPos.z
  904. local distance = math.sqrt(dx * dx + dy * dy + dz * dz)
  905.  
  906. -- If this player is closer than the current closest, update the closest target
  907. if not isFriendly(player.nickname) then
  908. closestDistance = distance
  909. targetPos1 = player.pos
  910.  
  911. table.insert(targets, {type = "player", pos = player.pos, distance = distance, nickname = player.nickname})
  912. end
  913. end
  914. end
  915.  
  916. -- Loop through each ship detected in the first ship scan
  917. local closestDistance = math.huge
  918. for _, ship in pairs(shipScan1) do
  919. if ship and ship.pos then
  920. local dx = ship.pos.x - shipPos.x
  921. local dy = ship.pos.y - shipPos.y
  922. local dz = ship.pos.z - shipPos.z
  923. local CIWSdistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  924.  
  925. -- Calculate speed of the ship
  926. local shipSpeed = calculateSpeed(ship.velocity)
  927.  
  928. --calculate distance with ship source
  929.  
  930. local dx = ship.pos.x - vesselPos.x
  931. local dy = ship.pos.y - vesselPos.y
  932. local dz = ship.pos.z - vesselPos.z
  933. local shipDistance = math.sqrt(dx * dx + dy * dy + dz * dz)
  934.  
  935. --check velocity difference to see if the target is on the same vessel
  936.  
  937. local speedError = math.abs(ship.velocity.x - vesselVelocity.x) + math.abs(ship.velocity.y - vesselVelocity.y) + math.abs(ship.velocity.z - vesselVelocity.z)
  938.  
  939. -- If the ship is moving fast (e.g., a missile), prioritize it
  940. --if shipSpeed > 4 and not( isFriendly(ship.id)) and (CIWSdistance > 15 or shipDistance > 15 ) and speedError > 2 then
  941. if shipSpeed > 4 and not( isFriendly(ship.id)) and (CIWSdistance > 15 or shipDistance > 15 ) and speedError > 2 then
  942. closestDistance = CIWSdistance
  943. highestSpeed = shipSpeed
  944. targetPos1 = ship.pos
  945. table.insert(targets, {type = "ship", pos = ship.pos, distance = distance, velocity = ship.velocity, id = ship.id})
  946. end
  947. end
  948. end
  949.  
  950. table.sort(targets, function(a, b)
  951. if not a.distance or not b.distance then
  952. return false -- Safeguard against nil values
  953. end
  954.  
  955. if a.type == "ship" and b.type == "player" then
  956. return true
  957. elseif a.type == "player" and b.type == "ship" then
  958. return false
  959. else
  960. return a.distance < b.distance
  961. end
  962. end)
  963.  
  964. return targets
  965. end
  966.  
  967. local function main()
  968. while true do
  969. local startTime = os.clock()
  970. shipPos = ship.getWorldspacePosition()
  971. vesselPos = shipPos
  972. vesselVelocity = ship.getVelocity()
  973.  
  974. shipPos.x = shipPos.x + lengthCorrection * math.cos(getYaw() - math.pi/2) + widthCorrection * math.cos(getYaw())
  975. shipPos.y = shipPos.y + heightCorrection
  976. shipPos.z = shipPos.z + lengthCorrection * math.sin(getYaw() - math.pi/2) + widthCorrection * math.sin(getYaw())
  977.  
  978. updateMode()
  979. local firstScanEndTime = os.clock()
  980. local dt1 = firstScanEndTime - startTime
  981.  
  982. -- Get all targets
  983. local targets = getClosestTarget()
  984. print(textutils.serialize(controls))
  985. -- Determine the target based on the mode
  986. local targetInfo
  987. if mode == "auto" then
  988. -- In auto mode, lock on to the closest target
  989. if #targets > 0 then
  990. targetInfo = targets[1]
  991. end
  992. cycleIndex = 1
  993. elseif mode == "cycle" then
  994. -- In cycle mode, switch to the next target on redstone input
  995. if redstone.getInput("top") or (controls and controls.targetSwitch) then
  996. cycleIndex = cycleIndex + 1 -- Cycle to the next target
  997. print("Cycling to next target.")
  998. end
  999. if cycleIndex > #targets then
  1000. cycleIndex = 1
  1001. end
  1002. if #targets > 0 then
  1003. targetInfo = targets[cycleIndex]
  1004. end
  1005. end
  1006. -- Wait for a short period (scanInterval) to perform the second scan
  1007. if targetInfo and targetInfo.pos then
  1008. -- Perform second scan for both players and ships
  1009. if targetInfo.type == "player" then
  1010. sleep(scanInterval)
  1011. local targetScan2 = radar.scanForPlayers(400)
  1012. local targetPos2 = nil
  1013.  
  1014. for _, player in pairs(targetScan2) do
  1015. if player and player.pos and player.nickname == targetInfo.nickname then
  1016. targetPos2 = player.pos
  1017. break
  1018. end
  1019. end
  1020.  
  1021. -- If both positions are available, calculate velocity for the player
  1022. if targetInfo.pos and targetPos2 then
  1023. targetInfo.velocity = calculateVelocity(targetInfo.pos, targetPos2, scanInterval*4)
  1024. targetInfo.pos.x = targetPos2[1]
  1025. targetInfo.pos.y = targetPos2[2]
  1026. targetInfo.pos.z = targetPos2[3]
  1027. else
  1028. targetInfo.velocity = {x=0, y=0, z=0} -- Default velocity if we cannot calculate it
  1029. end
  1030.  
  1031. if targetInfo.pos and targetInfo.pos.x and targetInfo.velocity then
  1032. print("aiming cannon")
  1033. aimCannon(targetInfo.pos, targetInfo.velocity, {x=0,y=0,z=0}, shipPos.x, shipPos.y, shipPos.z)
  1034. else
  1035. locked = false
  1036. redstone.setOutput("back",false)
  1037. end
  1038. elseif targetInfo.type == "ship" then
  1039. sleep(scanInterval)
  1040.  
  1041. local shipScan2 = radar.scanForShips(400)
  1042. local shipPos2, shipVelocity2 = nil, nil
  1043.  
  1044. -- Find the same ship in the second scan based on its ID
  1045. for _, ship in pairs(shipScan2) do
  1046. if ship.id == targetInfo.id then
  1047. shipPos2 = ship.pos
  1048. shipVelocity2 = ship.velocity
  1049. break
  1050. end
  1051. end
  1052.  
  1053. local dt2 = os.clock() - firstScanEndTime
  1054. if targetInfo.velocity and shipVelocity2 then
  1055. -- Calculate acceleration
  1056. local acceleration = calculateAcceleration(targetInfo.velocity, shipVelocity2, dt2)
  1057. -- Update velocity for next scan
  1058. targetInfo.velocity = shipVelocity2
  1059. -- Aim the cannon considering acceleration
  1060. aimCannon(targetInfo.pos, targetInfo.velocity, acceleration, shipPos.x, shipPos.y, shipPos.z)
  1061. else
  1062. locked = false
  1063. end
  1064. else
  1065. locked = false
  1066. redstone.setOutput("back",false)
  1067. end
  1068. else
  1069. locked = false
  1070. redstone.setOutput("back",false)
  1071. end
  1072. os.sleep()
  1073. end
  1074. end
  1075.  
  1076. local function autoFire()
  1077. while true do
  1078. safetyOff = redstone.getInput("left") or redstone.getInput("right") or redstone.getInput("bottom") or redstone.getInput("back") or (controls and controls.fireAutocannon)
  1079. if locked and auto and safetyOff then
  1080. cannon.fire()
  1081. cannon.fire()
  1082. cannon.fire()
  1083. cannon.fire()
  1084. redstone.setOutput("front",true)
  1085. else
  1086. redstone.setOutput("front",false)
  1087. end
  1088. sleep()
  1089. end
  1090. end
  1091.  
  1092. local function modemMessage()
  1093. while true do
  1094. if modem then
  1095. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  1096. if channel == settings.controlsChannel then
  1097. controls = message
  1098. end
  1099. else
  1100. sleep()
  1101. end
  1102. end
  1103. end
  1104.  
  1105. parallel.waitForAny(
  1106. main,
  1107. autoFire,
  1108. modemMessage,
  1109. setPitchYaw
  1110. )
Advertisement
Add Comment
Please, Sign In to add comment