core.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. 'use strict'
  2. const {SkillID, Vec3} = require('tera-data-parser').types,
  3. subMod = require('./require'),
  4. skillsClient = require('../client_data/skills'),
  5. passivity = require('../client_data/passivity'),
  6. clientNocTan = require('../client_data/noctan'),
  7. epPerks = require('../client_data/ep'),
  8. skillPolishing = require('../client_data/polishing'),
  9. clientAbnormality = require('../client_data/abnormality')
  10. const TYPE_ACTION = 1,
  11. TYPE_REACTION = 2
  12. const END_REASONS = {
  13. stand: 5,
  14. lockonCast: 36
  15. }
  16. module.exports = function SPCore(mod) {
  17. const skills = require('../config/skills');
  18. const player = subMod(mod, './player'),
  19. ping = subMod(mod, './ping'),
  20. abnormality = subMod(mod, './abnormalities'),
  21. cooldowns = subMod(mod, './cooldowns')
  22. mod.game.initialize("party");
  23. // Global
  24. let sending = false,
  25. skillsCache = new Map(),
  26. nocTanWarning = false,
  27. // Player
  28. vehicleEx = null,
  29. alive = false,
  30. partyMembers = null,
  31. // Current skill
  32. delayNext = 0,
  33. delayedSkillTimeout = null,
  34. retryTimer = {},
  35. actionNumber = 0x80000000,
  36. myPosition = null,
  37. lastStartTime = 0,
  38. lastStartPos = null,
  39. lastEndPosition = null,
  40. oopsPosition = null,
  41. clientAction = null,
  42. serverAction = null,
  43. serverConfirmedAction = false,
  44. pendingNotifyLocation = null,
  45. storedCharge = 0,
  46. lastEndSkill = null,
  47. lastEndReason = 0,
  48. lastEndedId = 0,
  49. serverTimeout = null,
  50. effectsTimeouts = [],
  51. stageEnd = null,
  52. stageEndTime = 0,
  53. stageEndTimeout = null,
  54. debugActionTime = 0,
  55. ohsLock = false,
  56. // Projectiles
  57. clientProjectileId = 0,
  58. clientProjectiles = {},
  59. clientProjectileHits = [],
  60. serverProjectiles = {}
  61. mod.hook('S_LOGIN', 'raw', {order: 100, filter: {fake: null}}, event => { skillsCache.clear() })
  62. mod.hook('S_LOAD_TOPO', 'raw', () => {
  63. vehicleEx = null
  64. clientAction = null
  65. serverAction = null
  66. lastEndSkill = null
  67. lastEndReason = 0
  68. lastEndedId = 0
  69. sendActionEnd(37)
  70. })
  71. mod.hook('S_SPAWN_ME', 3, {order: 100, filter: {fake: null}}, event => {
  72. updatePosition(event)
  73. alive = event.alive
  74. })
  75. mod.hook('S_CREATURE_LIFE', 3, event => {
  76. if(isMe(event.gameId)) {
  77. updatePosition(event, false, true)
  78. alive = event.alive
  79. if(!alive) {
  80. oopsPosition = null
  81. sendActionEnd(10)
  82. }
  83. }
  84. })
  85. mod.game.party.on("list", (data) => { partyMembers = data.map(x=> x.gameId);});
  86. mod.game.party.on("leave", () => { partyMembers = null;});
  87. mod.hook('S_MOUNT_VEHICLE_EX', 1, event => { if(event.target === player.gameId) vehicleEx = event.vehicle })
  88. mod.hook('S_UNMOUNT_VEHICLE_EX', 1, event => { if(event.target === player.gameId) vehicleEx = null })
  89. mod.hook('C_PLAYER_LOCATION', 5, {order: 10, filter: {fake: null}}, event => {
  90. if(mod.settings.debug.loc) console.log('Location %d %d (%d %d %d %s) > (%d %d %d)', event.type, event.speed, Math.round(event.loc.x), Math.round(event.loc.y), Math.round(event.loc.z), degrees(event.w), Math.round(event.dest.x), Math.round(event.dest.y), Math.round(event.dest.z))
  91. if(clientAction) {
  92. const info = skillInfo(clientAction.skill)
  93. if(info && (info.distance || info.type === 'dynamicDistance')) return false
  94. }
  95. // This is not correct, but the midpoint location seems to be "close enough" for the client to not teleport the player
  96. updatePosition({loc: event.loc.addN(event.dest).scale(0.5), w: event.w})
  97. })
  98. for(let packet of [
  99. ['C_NOTIFY_LOCATION_IN_ACTION', 4],
  100. ['C_NOTIFY_LOCATION_IN_DASH', 4]
  101. ])
  102. mod.hook(...packet, {order: -10, filter: {fake: null}}, notifyLocation.bind(null, ...packet))
  103. function notifyLocation(type, version, event) {
  104. if(sending) return
  105. // Sometimes the client sends invalid packets for the previous stage after it has already ended
  106. if(!clientAction || !clientAction.skill.equals(event.skill) || clientAction.stage !== event.stage) return false
  107. updatePosition(event, true)
  108. const info = skillInfo(event.skill)
  109. if(info) {
  110. if(info.hasChains) // The server ignores packets with an incorrect skill, so correct and resend later if necessary
  111. if(serverConfirmedAction) {
  112. if(!serverAction) return false
  113. if(!event.skill.equals(serverAction.skill)) {
  114. event.skill = serverAction.skill
  115. return true
  116. }
  117. }
  118. else pendingNotifyLocation = [...arguments]
  119. retry('notify', info, () => toServerLocked(...arguments))
  120. }
  121. }
  122. function resendNotifyLocation(skill) {
  123. if(pendingNotifyLocation) {
  124. const [,,event] = pendingNotifyLocation
  125. if(!event.skill.equals(skill)) {
  126. event.skill = skill
  127. mod.send(...pendingNotifyLocation)
  128. }
  129. pendingNotifyLocation = null
  130. }
  131. }
  132. for(let packet of [
  133. ['C_START_SKILL', 7],
  134. ['C_START_TARGETED_SKILL', 7],
  135. ['C_START_COMBO_INSTANT_SKILL', 6],
  136. ['C_START_INSTANCE_SKILL', 7],
  137. ['C_START_INSTANCE_SKILL_EX', 5],
  138. ['C_PRESS_SKILL', 4],
  139. ['C_NOTIMELINE_SKILL', 3]
  140. ])
  141. mod.hook(packet[0], 'raw', {order: -10, filter: {fake: null}}, startSkill.bind(null, ...packet))
  142. function startSkill(type, version, code, data) {
  143. if(sending) return
  144. const event = mod.dispatch.fromRaw(type, version, data),
  145. info = skillInfo(event.skill)
  146. mod.clearTimeout(delayedSkillTimeout)
  147. handleDelay: {
  148. // These types do not need delay; and in the case of button release, must NOT be ignored
  149. if(type === 'C_NOTIMELINE_SKILL' || type === 'C_PRESS_SKILL' && !event.press && (!clientAction || clientAction.skill.equals(event.skill)))
  150. break handleDelay
  151. if(delayNext && Date.now() <= stageEndTime) {
  152. let delay = delayNext
  153. if(info && !info.noRetry && mod.settings.skills.retryCount) {
  154. delay -= mod.settings.skills.retryJittercomp
  155. if(delay < 0) delay = 0
  156. }
  157. if(delay) {
  158. delayedSkillTimeout = mod.setTimeout(() => {
  159. if(handleStartSkill(type, event, info, data) !== false) toServerLocked(data)
  160. }, delay)
  161. return false
  162. }
  163. }
  164. }
  165. return handleStartSkill(type, event, info, data)
  166. }
  167. function handleStartSkill(type, event, info, data) {
  168. serverConfirmedAction = false
  169. pendingNotifyLocation = null
  170. delayNext = 0
  171. const specialLoc = !!event.dest
  172. if(!info) {
  173. if(type !== 'C_PRESS_SKILL' || event.press)
  174. // Sometimes invalid (if this skill can't be used, but we have no way of knowing that)
  175. if(type !== 'C_NOTIMELINE_SKILL') updatePosition(event, false, specialLoc)
  176. return
  177. }
  178. let skill = event.skill.clone(),
  179. skillBase = Math.floor(skill.id / 10000),
  180. endReason = 0
  181. if(type === 'C_PRESS_SKILL' && !event.press) {
  182. if(clientAction && clientAction.skill.equals(skill)) {
  183. if(['defence', 'movingdefence', 'drain', 'presshit'].includes(info.dcType)) {
  184. updatePosition(event)
  185. if(info.cancelChain) {
  186. sendActionEnd(11)
  187. info = skillInfo(skill = modifyChain(skill, info.cancelChain))
  188. if(!info) return
  189. startAction({
  190. skill,
  191. info,
  192. stage: 0,
  193. speed: player.attackSpeed,
  194. effectScale: 1
  195. })
  196. }
  197. else sendActionEnd(['movingdefence', 'presshit'].includes(info.dcType) ? 51 : 10)
  198. }
  199. else if(info.dcType === 'movingcharge') {
  200. grantCharge(skill, info, clientAction.stage)
  201. return
  202. }
  203. }
  204. else if(info.keptMovingCharge) {
  205. grantCharge(skill, info, storedCharge)
  206. return
  207. }
  208. let releaseChain = info.releaseChain,
  209. doReleaseChain = false
  210. // Skill override (release chain)
  211. if(releaseChain && clientAction &&
  212. (!releaseChain.overcharge || clientAction.overcharge) &&
  213. (!releaseChain.connectSkills || clientAction.skill.type === TYPE_ACTION && releaseChain.connectSkills.includes(clientAction.skill.id))
  214. ) {
  215. const prevInfo = skillInfo(clientAction.skill)
  216. if(prevInfo && Date.now() - lastStartTime >= prevInfo.pendingStartTime / clientAction.speed) {
  217. info = skillInfo(skill = modifyChain(skill, releaseChain.chain))
  218. if(!info) {
  219. updatePosition(event, false, specialLoc)
  220. return
  221. }
  222. if(!cooldowns.check(skill.id)) {
  223. endReason = END_REASONS[info.dcType] || END_REASONS[info.type] || 4
  224. if(releaseChain.grant) {
  225. updatePosition(event, false, specialLoc)
  226. sendActionEnd(endReason)
  227. mod.send('S_GRANT_SKILL', 3, { skill })
  228. return
  229. }
  230. else doReleaseChain = true
  231. }
  232. }
  233. }
  234. if(!doReleaseChain) return
  235. }
  236. if(!alive || (mod.game.contract.active && mod.game.contract.id === 53)) {
  237. sendCannotStartSkill(event.skill)
  238. return false
  239. }
  240. if(!player.hasWeapon && !info.noWeapon) {
  241. sendCannotStartSkill(event.skill)
  242. sendSystemMessage('SMT_BATTLE_SKILL_NEED_WEAPON')
  243. return false
  244. }
  245. if(player.mounted) {
  246. sendCannotStartSkill(event.skill)
  247. sendSystemMessage('SMT_PROHIBITED_ACTION_ON_RIDE')
  248. return false
  249. }
  250. if (ohsLock && player.job === 2 && skillBase === 8) {
  251. sendCannotStartSkill(event.skill)
  252. return false
  253. }
  254. if(clientAction) {
  255. var currentSkill = clientAction.skill.id,
  256. currentSkillBase = Math.floor(currentSkill / 10000),
  257. currentSkillSub = currentSkill % 100
  258. if(clientAction.skill.type === TYPE_ACTION) {
  259. // If checkReset flag is true, prevent re-casting the same skill unless the server says cooldown reset
  260. if(currentSkill === skill.id && info.checkReset && !clientAction.reset) {
  261. sendCannotStartSkill(event.skill)
  262. return false
  263. }
  264. // The client doesn't always know what skills it can cast or not
  265. if(info.noInterrupt && (info.noInterrupt.includes(currentSkillBase) || info.noInterrupt.includes(currentSkillBase + '-' + currentSkillSub))) {
  266. let canInterrupt = false
  267. if (info.interruptibleWithAbnormal)
  268. for(let abnormal in info.interruptibleWithAbnormal)
  269. if(abnormality.exists(abnormal) && currentSkillBase === info.interruptibleWithAbnormal[abnormal])
  270. canInterrupt = true
  271. //
  272. if (info.interruptAllWithAbnormal)
  273. for (let abnormal in info.interruptAllWithAbnormal)
  274. if (abnormality.exists(abnormal) && currentSkillBase !== info.interruptAllWithAbnormal[abnormal])
  275. canInterrupt = true
  276. if(!canInterrupt) {
  277. sendCannotStartSkill(event.skill)
  278. return false
  279. }
  280. }
  281. if(info.keepMovingCharge) storedCharge = clientAction.stage
  282. }
  283. else if(clientAction.skill.type === TYPE_REACTION) {
  284. reaction: {
  285. if(clientAction.air) {
  286. if(info.useSkillWhileAirReaction) break reaction
  287. }
  288. else if(clientAction.skill.id === player.templateId*100 + 8) {
  289. if(info.useSkillWhileBulldozer) break reaction
  290. }
  291. else {
  292. if(clientAction.skill.id === player.kdId && info.dcType === 'stand') break reaction
  293. if(info.useSkillWhileReaction) break reaction
  294. }
  295. sendCannotStartSkill(event.skill)
  296. return false
  297. }
  298. }
  299. }
  300. // 'connect' type skills (chains)
  301. for(let i = 0, chain = info.userChain; i < 10; i++, chain = undefined) { // Limit recursion to prevent infinite loop
  302. // 1. Abnormality chains (prioritise in order of ID)
  303. if(chain == null)
  304. for(let id in info.abnormalChains)
  305. if(abnormality.exists(Number(id))) {
  306. chain = info.abnormalChains[id]
  307. break
  308. }
  309. // 2. Skill chains
  310. if(chain == null && clientAction) {
  311. const {categoryChains, chains} = info
  312. if(categoryChains) {
  313. const category = get(skillsClient, clientAction.templateId, clientAction.skill.id, 'category')
  314. if(category && category.length)
  315. for(let ids of Object.keys(categoryChains).sort()) // MUST be prioritised in order
  316. if(ids.split(',').every(id => category.includes(Number(id)))) {
  317. chain = categoryChains[ids]
  318. break
  319. }
  320. }
  321. else if(chains) { // Deprecated legacy chains (does not match server behavior)
  322. chain = chains[currentSkillBase + '-' + currentSkillSub]
  323. if(chain === undefined) chain = chains[currentSkillBase]
  324. }
  325. }
  326. if(chain != null) {
  327. const chainSkill = chain > 99 ? new SkillID(chain) : modifyChain(skill, chain)
  328. // Emulate server and ignore invalid chains
  329. if(chainSkill.equals(skill) || !get(skillsClient, player.templateId, chainSkill.id)) break
  330. info = skillInfo(skill = chainSkill)
  331. if(!info) {
  332. if(type !== 'C_NOTIMELINE_SKILL') updatePosition(event, false, specialLoc)
  333. return
  334. }
  335. endReason = END_REASONS[info.dcType] || END_REASONS[info.type] || 4
  336. }
  337. else {
  338. if(!endReason) endReason = END_REASONS[info.dcType] || END_REASONS[info.type] || 6
  339. break
  340. }
  341. }
  342. if(info.onlyDefenceSuccess)
  343. if(clientAction && clientAction.defendSuccess) endReason = 3
  344. else {
  345. sendCannotStartSkill(event.skill)
  346. sendSystemMessage('SMT_SKILL_ONLY_DEFENCE_SUCCESS')
  347. return false
  348. }
  349. if(info.onlyTarget && event.targets[0].gameId === 0n) {
  350. sendCannotStartSkill(event.skill)
  351. return false
  352. }
  353. // Skill is on cooldown
  354. if(cooldowns.check(skill.id)) {
  355. sendCannotStartSkill(event.skill)
  356. return false
  357. }
  358. // TODO: System Message, S_SKILL_CATEGORY emulation, DC abnormal integration
  359. if(info.requiredBuff) {
  360. if(Array.isArray(info.requiredBuff)) {
  361. let found = false
  362. for(let buff of info.requiredBuff)
  363. if(abnormality.exists(buff)) {
  364. found = true
  365. break
  366. }
  367. if(!found) {
  368. sendCannotStartSkill(event.skill)
  369. return false
  370. }
  371. }
  372. else if(!abnormality.exists(info.requiredBuff)) {
  373. sendCannotStartSkill(event.skill)
  374. return false
  375. }
  376. }
  377. // Calculate animation variables
  378. let nocTanMultiplier = 0,
  379. enabledCategories = new Set(),
  380. disabledCategories = new Set(),
  381. staminaA = info.stamina || 0,
  382. staminaB = 0,
  383. staminaC = 1,
  384. staminaD = 1,
  385. skillSpeed = player.attackSpeed,
  386. skillSpeedMult = 1,
  387. chargeSpeed = 0,
  388. effectScale = 1,
  389. distanceMult = 1,
  390. animSeq = null
  391. // Calculate passivities
  392. const currentSkillCategory = skillsClient[player.templateId]?.[skill.id]?.category
  393. function runAbnormal(abnormal) {
  394. if(!abnormal) return
  395. for(let effect of abnormal.effects)
  396. switch(effect.type) {
  397. case 29: if(effect.method === 3) chargeSpeed += effect.value - 1; break
  398. case 203:
  399. case 317:
  400. nocTanMultiplier = effect.type === 203 ? 1 : 1.5
  401. break
  402. case 209:
  403. for(let id of abnormal.bySkillCategory) enabledCategories.add(id)
  404. break
  405. case 210:
  406. for(let id of abnormal.bySkillCategory) disabledCategories.add(id)
  407. break
  408. case 235: if(hasOverlapCategory(abnormal.bySkillCategory)) skillSpeed *= effect.value; break
  409. case 236: if(hasOverlapCategory(abnormal.bySkillCategory)) chargeSpeed += effect.value - 1; break
  410. case 239:
  411. if(hasOverlapCategory(abnormal.bySkillCategory))
  412. switch(effect.method) {
  413. case 1: staminaA = effect.value; break
  414. case 2: staminaB += effect.value; break
  415. case 3: staminaC += effect.value - 1; break
  416. case 4: staminaD *= effect.value; break
  417. }
  418. break
  419. }
  420. }
  421. function hasOverlapCategory(category) {
  422. return currentSkillCategory.some(id => category.includes(id))
  423. }
  424. function runPassive(passive) {
  425. if(!passive || !currentSkillCategory.includes(passive.conditionCategory)) return
  426. switch(passive.type) {
  427. case 77: if(passive.method === 3) effectScale += Math.max(0, passive.value - 1); break
  428. case 82:
  429. switch(passive.method) {
  430. case 1: staminaA = passive.value; break
  431. case 2: staminaB += passive.value; break
  432. case 3: staminaC += passive.value - 1; break
  433. }
  434. break
  435. case 218: skillSpeedMult += passive.value - 1; break
  436. case 220: chargeSpeed += passive.value - 1; break
  437. }
  438. }
  439. if(currentSkillCategory) {
  440. for(let id in abnormality.myAbnormals) runAbnormal(clientAbnormality[id])
  441. if(currentSkillCategory.some(id => disabledCategories.has(id) && !enabledCategories.has(id))) {
  442. sendSystemMessage('SMT_SKILL_FAIL_CATEGORY')
  443. sendCannotStartSkill(event.skill)
  444. return false
  445. }
  446. // Apply skill speed from Noctenium Infusion
  447. if(nocTanMultiplier) {
  448. const effectRate = clientNocTan[player.job]?.[skill.id]
  449. if(effectRate) skillSpeed *= 1 + (effectRate - 1)*nocTanMultiplier
  450. if(player.hasNocTan && !nocTanWarning) {
  451. console.log(
  452. `[SkillPrediction] Noctenium Infusion detected in inventory.
  453. Please bank or discard it before using skills.
  454. (Server bug: Having Noctenium Infusion in inventory causes skill delays)`)
  455. nocTanWarning = true
  456. }
  457. }
  458. for(let id of player.crests) runPassive(passivity[id]) // Technically these are the wrong IDs, but so far they match up 1:1
  459. for(let id of player.epPerks) {
  460. const passives = epPerks[id]
  461. if(passives) for(let p of passives) runPassive(p)
  462. }
  463. for(let id of player.skillPolishing) {
  464. const passives = skillPolishing[id]
  465. if(passives) for(let id of passives) runPassive(passivity[id])
  466. }
  467. for(let id of player.itemPassives) runPassive(passivity[id])
  468. }
  469. else mod.log.warn(`Skill has no data: ${player.templateId} ${skillId(skill)}`)
  470. // Calculate legacy glyphs (TODO: Remove)
  471. if(info.glyphs)
  472. for(let id in info.glyphs)
  473. if(player.crests.has(Number(id))) {
  474. const glyph = info.glyphs[id]
  475. if(glyph.animSeq) animSeq = glyph.animSeq
  476. if(glyph.distance) distanceMult *= glyph.distance
  477. }
  478. // End calculations
  479. // Check skill start conditions
  480. // Check stamina
  481. const stamina = (staminaA + staminaB) * staminaC * staminaD
  482. if(stamina) {
  483. if(player.stamina < stamina) {
  484. sendCannotStartSkill(event.skill)
  485. //sendSystemMessage('SMT_BATTLE_SKILL_FAIL_LOW_STAMINA')
  486. return false
  487. }
  488. if(info.instantStamina) player.stamina -= stamina
  489. }
  490. // Update our position and end previous skill
  491. if(type !== 'C_NOTIMELINE_SKILL') updatePosition(event, false, specialLoc)
  492. lastStartPos = myPosition
  493. if(event.continue)
  494. clearStage()
  495. else if(endReason && clientAction) {
  496. if(!tryCancelSkill(endReason, info)) {
  497. sendCannotStartSkill(event.skill)
  498. return false
  499. }
  500. // Handle 2-part skills
  501. if(info.connectSkillArrow) {
  502. updatePosition(event, false, specialLoc)
  503. sendActionEnd(4)
  504. mod.send('S_CONNECT_SKILL_ARROW', 3, {
  505. templateId: player.templateId,
  506. skill,
  507. unk2: true // grant
  508. })
  509. return
  510. }
  511. }
  512. const instantStage = info.noChargeAbnormalityId && abnormality.exists(info.noChargeAbnormalityId) && info.length ? info.length.length || 1 : 0
  513. if(!ohsLock && player.job === 2 && skillBase === 8 ) {
  514. ohsLock = true;
  515. mod.setTimeout(()=>{ohsLock = false}, 500);
  516. }
  517. startAction({
  518. skill,
  519. info,
  520. stage: instantStage,
  521. speed: skillSpeed * skillSpeedMult,
  522. chargeSpeed,
  523. effectScale,
  524. animSeq,
  525. moving: type === 'C_START_SKILL' && event.moving,
  526. distanceMult,
  527. dest: event.dest,
  528. endpoints: event.endpoints,
  529. overcharge: instantStage > 0
  530. })
  531. // Normally the user can press the skill button again if it doesn't go off
  532. // However, once the animation starts this is no longer possible, so instead we simulate retrying each skill
  533. retry('skill', info, () => toServerLocked(data))
  534. }
  535. function tryCancelSkill(endReason, nextSkill) {
  536. if(!canCancelSkill(endReason, nextSkill))
  537. return false
  538. sendActionEnd(endReason)
  539. return true
  540. }
  541. function canCancelSkill(endReason, nextSkill) {
  542. return true
  543. }
  544. function toServerLocked(...args) {
  545. sending = true
  546. const success = mod.toServer(...args)
  547. sending = false
  548. return success
  549. }
  550. mod.hook('C_CANCEL_SKILL', 3, event => {
  551. if(clientAction) {
  552. const info = skillInfo(clientAction.skill) // event.skill can be wrong, so use the known current skill instead
  553. if(info && info.type === 'lockon') sendActionEnd(event.type)
  554. }
  555. })
  556. // This packet is sent *before* S_ACTION_STAGE, so we should have plenty of time to check if the skill reset or not before the user uses it again
  557. mod.hook('S_CREST_MESSAGE', 2, event => {
  558. if(event.type === 6 && clientAction && clientAction.skill.type === TYPE_ACTION && clientAction.skill.id === event.skill)
  559. clientAction.reset = true
  560. })
  561. mod.hook('S_ACTION_STAGE', 9, event => {
  562. if(isMe(event.gameId)) {
  563. if(mod.settings.debug.skills) {
  564. const duration = Date.now() - debugActionTime,
  565. strs = [skillInfo(event.skill) ? '<X' : '<-', 'S_ACTION_STAGE', skillId(event.skill), event.stage, decimal(event.speed, 3) + 'x', decimal(event.projectileSpeed, 3) + 'x']
  566. if(mod.settings.debug.skills.loc) strs.push(...[degrees(event.w), '(' + Math.round(event.loc.x), Math.round(event.loc.y), Math.round(event.loc.z) + ')'])
  567. strs.push(...[event.unk1, event.unk2, event.dest.toString(), event.target ? 1 : 0])
  568. if(serverAction)
  569. strs.push(...[
  570. decimal(serverAction.loc.dist2D(event.loc), 3) + 'u',
  571. duration + 'ms',
  572. `(${Math.round(duration * Math.max(serverAction.spDebugAspd, serverAction.speed))}ms)`
  573. ])
  574. if(event.animSeq.length) {
  575. const animSeq = []
  576. for(let e of event.animSeq)
  577. animSeq.push(e.duration + ' ' + e.xyRate + ' ' + e.zRate + ' ' + e.distance)
  578. strs.push('(' + animSeq.join(', ') + ')')
  579. }
  580. debug(strs.join(' '))
  581. debugActionTime = Date.now()
  582. }
  583. const info = skillInfo(event.skill)
  584. if(info) {
  585. if(clientAction && event.skill.type === clientAction.skill.type && Math.floor(event.skill.id / 100) === Math.floor(clientAction.skill.id / 100) && event.stage === clientAction.stage) {
  586. mod.clearTimeout(serverTimeout)
  587. serverConfirmedAction = true
  588. resendNotifyLocation(event.skill)
  589. if(mod.settings.skills.jitterCompensation && event.stage === 0) {
  590. let delay = Date.now() - lastStartTime - ping.min
  591. if(delay > 0 && delay < 1000) {
  592. if(info.dcType === 'movingcharge') delay = Math.max(delay, Math.min(ping.max - ping.min, mod.settings.skills.chargeJitterMax))
  593. delayNext = delay
  594. if(stageEnd) {
  595. stageEndTime += delay
  596. refreshStageEnd()
  597. }
  598. }
  599. }
  600. }
  601. if(info.forceClip && event.animSeq.length) {
  602. oopsPosition = applyDistance(lastStartPos, event.animSeq.map(s => s.distance).reduce((a, b) => a + b), (info.moveDir || 0) * Math.PI)
  603. if(!clientAction || !clientAction.skill.equals(event.skill)) sendInstantMove(oopsPosition)
  604. }
  605. // If the server sends 2 S_ACTION_STAGE in a row without a S_ACTION_END between them and the last one is an emulated skill,
  606. // this stops your character from being stuck in the first animation (although slight desync will occur)
  607. if(clientAction && clientAction === serverAction && !skillInfo(clientAction.skill)) sendActionEnd(6)
  608. if(player.attackSpeed > 1 && event.speed === 1 !== !!info.ignoreAttackSpeed && !info.ignoreAttackSpeedWarning) {
  609. console.log(`[SkillPrediction] data mismatch: ${player.templateId} ${skillId(event.skill)} (ignoreAttackSpeed=${event.speed === 1})`)
  610. info.ignoreAttackSpeedWarning = true
  611. }
  612. serverAction = event
  613. serverAction.spDebugAspd = player.attackSpeed
  614. return false
  615. }
  616. serverAction = event
  617. serverAction.spDebugAspd = player.attackSpeed
  618. if(event.id === lastEndedId) return false
  619. if(clientAction && skillInfo(clientAction.skill))
  620. sendActionEnd(clientAction.skill.equals(lastEndSkill) && lastEndReason || (event.skill.type === TYPE_ACTION ? 6 : 9))
  621. clientAction = event
  622. updatePosition()
  623. }
  624. })
  625. mod.hook('S_GRANT_SKILL', 3, event => skillInfo(event.skill) ? false : undefined)
  626. mod.hook('S_CONNECT_SKILL_ARROW', 3, event => skillInfo(event.skill) ? false : undefined)
  627. mod.hook('S_INSTANT_DASH', 3, event => {
  628. if(isMe(event.gameId)) {
  629. if(mod.settings.debug.skills) {
  630. const duration = Date.now() - debugActionTime,
  631. strs = [(serverAction && skillInfo(serverAction.skill)) ? '<X' : '<-', 'S_INSTANT_DASH', event.unk1, event.unk2, event.unk3]
  632. if(mod.settings.debug.skills.loc) strs.push(...[degrees(event.w), '(' + Math.round(event.loc.x), Math.round(event.loc.y), Math.round(event.loc.z) + ')'])
  633. strs.push(...[
  634. decimal(serverAction.loc.dist2D(event.loc), 3) + 'u',
  635. duration + 'ms',
  636. `(${Math.round(duration * Math.max(serverAction.spDebugAspd, serverAction.speed))}ms)`
  637. ])
  638. debug(strs.join(' '))
  639. }
  640. if(serverAction && skillInfo(serverAction.skill)) return false
  641. }
  642. })
  643. mod.hook('S_INSTANT_MOVE', 3, event => {
  644. if(isMe(event.gameId)) {
  645. if(mod.settings.debug.skills) {
  646. const duration = Date.now() - debugActionTime,
  647. strs = ['<- S_INSTANT_MOVE']
  648. if(mod.settings.debug.skills.loc) strs.push(...[degrees(event.w), '(' + Math.round(event.loc.x), Math.round(event.loc.y), Math.round(event.loc.z) + ')'])
  649. if(serverAction)
  650. strs.push(...[
  651. decimal(serverAction.loc.dist2D(event.loc), 3) + 'u',
  652. duration + 'ms',
  653. `(${Math.round(duration * Math.max(serverAction.spDebugAspd, serverAction.speed))}ms)`
  654. ])
  655. debug(strs.join(' '))
  656. }
  657. updatePosition(event, true)
  658. const info = serverAction && skillInfo(serverAction.skill)
  659. if(info && info.dcType === 'shorttel' && clientAction && clientAction.skill.equals(serverAction.skill))
  660. oopsPosition = myPosition
  661. }
  662. })
  663. mod.hook('S_ACTION_END', 5, event => {
  664. if(isMe(event.gameId)) {
  665. if(mod.settings.debug.skills) {
  666. const duration = Date.now() - debugActionTime,
  667. strs = [(event.id === lastEndedId || skillInfo(event.skill)) ? '<X' : '<-', 'S_ACTION_END', skillId(event.skill), event.type]
  668. if(mod.settings.debug.skills.loc) strs.push(...[degrees(event.w), '(' + Math.round(event.loc.x), Math.round(event.loc.y), Math.round(event.loc.z) + ')'])
  669. if(serverAction)
  670. strs.push(...[
  671. decimal(serverAction.loc.dist2D(event.loc), 3) + 'u',
  672. duration + 'ms',
  673. `(${Math.round(duration * Math.max(serverAction.spDebugAspd, serverAction.speed))}ms)`
  674. ])
  675. else strs.push('???')
  676. debug(strs.join(' '))
  677. }
  678. serverAction = null
  679. lastEndSkill = event.skill
  680. lastEndReason = event.type
  681. if(event.id === lastEndedId) {
  682. lastEndedId = 0
  683. return false
  684. }
  685. const info = skillInfo(event.skill)
  686. if(info) {
  687. if(info.dcType === 'dash')
  688. // If the skill ends early then there should be no significant error
  689. if(clientAction && event.skill.equals(clientAction.skill)) {
  690. updatePosition(event)
  691. sendActionEnd(event.type)
  692. }
  693. // Worst case scenario, teleport the player back if the error was large enough for the client to act on it
  694. else if(!lastEndPosition || lastEndPosition.loc.dist3D(event.loc) >= 100)
  695. sendInstantMove(event)
  696. // These end types are hard to emulate, so we use server response instead
  697. // This may cause bugs with very high ping and casting the same skill multiple times
  698. if(clientAction && event.skill.equals(clientAction.skill) && [2, 9, 13, 25, 29, 43].includes(event.type)) {
  699. updatePosition(event)
  700. sendActionEnd(event.type)
  701. }
  702. return false
  703. }
  704. if(!clientAction)
  705. console.log(`[SkillPrediction] (S_ACTION_END) clientAction is null: ${skillId(event.skill)}`)
  706. else if(!event.skill.equals(clientAction.skill))
  707. console.log(`[SkillPrediction] (S_ACTION_END) skill mismatch: ${skillId(event.skill)} (expected ${skillId(clientAction.skill)})`)
  708. clientAction = null
  709. }
  710. })
  711. mod.hook('S_EACH_SKILL_RESULT', mod.majorPatchVersion >= 86 ? 14 : 13, event => {
  712. const {reaction} = event
  713. if(isMe(event.target) && reaction.enable) {
  714. if(mod.settings.debug.skills) {
  715. const duration = Date.now() - debugActionTime,
  716. strs = ['<- S_EACH_SKILL_RESULT.reaction', skillId(reaction.skill), reaction.stage, '[' + Number(reaction.instantPush), Number(reaction.air), Number(reaction.airChain) + ']']
  717. if(mod.settings.debug.skills.loc) strs.push(...[degrees(reaction.w), '(' + Math.round(reaction.loc.x), Math.round(reaction.loc.y), Math.round(reaction.loc.z) + ')'])
  718. debug(strs.join(' '))
  719. }
  720. // Just in case we started an emulated skill right after the previous one ended
  721. if(clientAction && skillInfo(clientAction.skill)) sendActionEnd(9)
  722. clientAction = serverAction = reaction
  723. serverAction.spDebugAspd = player.attackSpeed
  724. updatePosition()
  725. }
  726. })
  727. mod.hook('S_DEFEND_SUCCESS', 3, event => {
  728. if(isMe(event.gameId))
  729. if(!serverAction) return false // Due to a bug, server sometimes sends this packet outside of an action
  730. else if(clientAction && clientAction.skill.equals(serverAction.skill)) clientAction.defendSuccess = true
  731. else if(mod.settings.skills.defendSuccessStrict || player.job !== 10) return false
  732. })
  733. mod.hook('S_CANNOT_START_SKILL', 4, event => {
  734. if(skillInfo(event.skill.id)) {
  735. if(mod.settings.skills.delayOnFail && mod.settings.skills.retryCount && clientAction && (!serverAction || !clientAction.skill.equals(serverAction.skill)) && event.skill.id === clientAction.skill.id)
  736. delayNext += mod.settings.skills.retryMs
  737. return false
  738. }
  739. })
  740. mod.hook('C_CAN_LOCKON_TARGET', 3, event => {
  741. const info = skillInfo(event.skill)
  742. if(info) {
  743. let success = true
  744. if(info.partyOnly) {
  745. success = false
  746. if(partyMembers)
  747. for(let member of partyMembers)
  748. if(member === event.target) {
  749. success = true
  750. break
  751. }
  752. }
  753. mod.toClient('S_CAN_LOCKON_TARGET', 3, Object.assign({success}, event))
  754. }
  755. })
  756. mod.hook('S_CAN_LOCKON_TARGET', 3, event => skillInfo(event.skill) ? false : undefined)
  757. if(mod.settings.debug.skills.projectiles) {
  758. mod.hook('S_SPAWN_PROJECTILE', 5, event => {
  759. if(!isMe(event.gameId)) return
  760. debug(`<- S_SPAWN_PROJECTILE ${skillId(event.skill)} ${event.unk1} ${event.loc.x} ${event.loc.y} ${event.loc.z} ${event.dest.x} ${event.dest.y} ${event.dest.z} ${event.moving} ${event.speed} ${event.unk2} ${event.unk3} ${event.w}`)
  761. if(skillInfo(event.skill)) {
  762. serverProjectiles[event.id.toString()] = event.skill
  763. return false
  764. }
  765. })
  766. mod.hook('S_DESPAWN_PROJECTILE', 2, event => {
  767. debug(`<- S_DESPAWN_PROJECTILE ${event.unk1} ${event.unk2}`)
  768. const idStr = event.id.toString()
  769. if(serverProjectiles[idStr]) {
  770. delete serverProjectiles[idStr]
  771. return false
  772. }
  773. })
  774. mod.hook('S_START_USER_PROJECTILE', 9, event => {
  775. if(!isMe(event.gameId)) return
  776. debug(`<- S_START_USER_PROJECTILE ${skillId(event.skill)} ${event.loc.x} ${event.loc.y} ${event.loc.z} ${event.dest.x} ${event.dest.y} ${event.dest.z} ${event.speed} ${event.distance} ${event.curve}`)
  777. if(skillInfo(event.skill)) {
  778. const skill = new SkillID(event.skill)
  779. serverProjectiles[event.id.toString()] = skill
  780. applyProjectileHits(event.id, skill)
  781. return false
  782. }
  783. })
  784. mod.hook('S_END_USER_PROJECTILE', 4, event => {
  785. debug(`<- S_END_USER_PROJECTILE ${event.unk1} ${event.unk2} ${event.target ? 1 : 0}`)
  786. const idStr = event.id.toString()
  787. if(serverProjectiles[idStr]) {
  788. delete serverProjectiles[idStr]
  789. return false
  790. }
  791. })
  792. mod.hook('C_HIT_USER_PROJECTILE', 4, event => {
  793. debug(`-> C_HIT_USER_PROJECTILE ${event.targets.length} ${event.end}`)
  794. const idStr = event.id.toString(),
  795. skill = clientProjectiles[idStr]
  796. if(skill) {
  797. // Your own projectiles can hit you while moving, in which case we ignore this packet
  798. if(event.targets.length === 1 && event.targets[0].gameId === player.gameId) return false
  799. if(event.end || skillInfo(skill).explodeOnHit)
  800. removeProjectile(event.id, true, event.targets.length ? event.targets[0].gameId : true)
  801. for(let id in serverProjectiles)
  802. if(serverProjectiles[id] === skill) {
  803. event.id = BigInt(id)
  804. return true
  805. }
  806. clientProjectileHits.push(Object.assign(event, {
  807. skill,
  808. time: Date.now()
  809. }))
  810. return false
  811. }
  812. })
  813. function applyProjectileHits(id, skill) {
  814. // Garbage collect expired hits
  815. for(let i = 0, expiry = Date.now() - getServerTimeout(); i < clientProjectileHits.length; i++)
  816. if(clientProjectileHits[i].time <= expiry)
  817. clientProjectileHits.splice(i--, 1)
  818. for(let i = 0; i < clientProjectileHits.length; i++) {
  819. const event = clientProjectileHits[i]
  820. if(event.skill === skill) {
  821. clientProjectileHits.splice(i--, 1)
  822. event.id = id
  823. mod.toServer('C_HIT_USER_PROJECTILE', 4, event)
  824. if(event.end) {
  825. delete serverProjectiles[id.toString()]
  826. return
  827. }
  828. }
  829. }
  830. }
  831. }
  832. function startAction(opts) {
  833. const info = opts.info,
  834. // Must clone opts before sendActionStage() modifes it
  835. fxOpts = opts.stage || info.dcType === 'dash' || info.projectiles ? Object.assign({}, opts) : null
  836. if(info.consumeAbnormal)
  837. if(Array.isArray(info.consumeAbnormal))
  838. for(let id of info.consumeAbnormal)
  839. abnormality.remove(id)
  840. else
  841. abnormality.remove(info.consumeAbnormal)
  842. sendActionStage(opts)
  843. if(fxOpts) {
  844. fxOpts.pos = Object.assign({}, myPosition)
  845. effectsTimeouts.push(mod.setTimeout(sendActionEffects, 25, fxOpts)) // Emulate server tick delay
  846. }
  847. if(info.triggerAbnormal)
  848. for(let id in info.triggerAbnormal) {
  849. const abnormal = info.triggerAbnormal[id]
  850. if(Array.isArray(abnormal))
  851. abnormality.add(id, abnormal[0], abnormal[1])
  852. else
  853. abnormality.add(id, abnormal, 1)
  854. }
  855. lastStartTime = Date.now()
  856. }
  857. function sendActionStage(opts) {
  858. mod.clearTimeout(serverTimeout)
  859. const info = opts.info,
  860. multiStage = Array.isArray(info.length),
  861. moveDir = (info.moveDir || 0) * Math.PI
  862. let animSpeed = opts.speed,
  863. realSpeed = opts.speed
  864. if(info.dcType === 'movingcharge') realSpeed = (realSpeed + opts.chargeSpeed) * info.timeRate
  865. if(info.ignoreAttackSpeed) {
  866. animSpeed = 1
  867. if(!['movingdefence', 'movingskill', 'shootingmovingskill'].includes(info.dcType)) realSpeed = 1
  868. }
  869. if(mod.settings.debug.skills) debug(`<* S_ACTION_STAGE ${skillId(opts.skill)} ${opts.stage} ${decimal(animSpeed, 3)}x ${decimal(realSpeed, 3)}x`)
  870. opts.stage = opts.stage || 0
  871. opts.distanceMult = opts.distanceMult || 1
  872. movePlayer(opts.distance * opts.distanceMult, moveDir) // Apply movement from previous stage
  873. myPosition.action = false
  874. let animSeq = opts.animSeq
  875. if(multiStage)
  876. animSeq = animSeq && animSeq[opts.stage] || !opts.moving && info.inPlace?.animSeq?.[opts.stage] || info.animSeq?.[opts.stage] || []
  877. else
  878. animSeq = animSeq || !opts.moving && info.inPlace?.animSeq || info.animSeq || []
  879. mod.send('S_ACTION_STAGE', 9, clientAction = {
  880. gameId: myChar(),
  881. loc: myPosition.loc,
  882. w: myPosition.w,
  883. templateId: player.templateId,
  884. skill: opts.skill,
  885. stage: opts.stage,
  886. speed: animSpeed,
  887. projectileSpeed: info.ignoreAttackSpeed ? 1 : realSpeed,
  888. id: actionNumber,
  889. effectScale: opts.effectScale,
  890. moving: false,
  891. dest: info.setEndpointStage === opts.stage ? opts.endpoints[0].loc : undefined,
  892. target: 0,
  893. animSeq,
  894. // Meta
  895. defendSuccess: opts.stage > 0 && !!clientAction && clientAction.skill === opts.skill ? clientAction.defendSuccess : false,
  896. overcharge: opts.overcharge || !!clientAction && clientAction.overcharge
  897. })
  898. opts.distance = info.distance?.[opts.stage] ?? info.distance ?? 0
  899. stageEnd = null
  900. let noTimeout = false
  901. if(serverAction && Math.floor(serverAction.skill.id / 100) === Math.floor(opts.skill.id / 100) && serverAction.stage >= opts.stage)
  902. noTimeout = true
  903. if(info.type === 'dynamicDistance') {
  904. opts.distance = myPosition.loc.dist2D(opts.dest)
  905. }
  906. else if(info.dcType === 'shorttel') {
  907. if(!info.length || !(info.length.length > opts.stage + 1)) { // Trigger teleport on last stage
  908. opts.distance = Math.max(0, myPosition.loc.dist2D(opts.dest) - 15) // Client is approx. 15 units off
  909. applyDistance(myPosition, opts.distance)
  910. myPosition.loc.z = opts.dest.z
  911. sendInstantMove()
  912. opts.distance = 0
  913. }
  914. }
  915. if(['defence', 'movingdefence', 'movingcharge', 'presshit'].includes(info.dcType) && opts.stage === ((info.length && (info.length.length || 1)) || 0)) {
  916. if(info.dcType === 'movingcharge' && info.autoRelease !== undefined) {
  917. stageEnd = () => {
  918. toServerLocked('C_PRESS_SKILL', 4, {
  919. skill: opts.skill,
  920. press: false,
  921. loc: myPosition.loc,
  922. w: myPosition.w
  923. })
  924. grantCharge(opts.skill, info, opts.stage)
  925. }
  926. if(info.autoRelease === 0) {
  927. stageEnd()
  928. stageEnd = null
  929. }
  930. else stageEndTimeout = mod.setTimeout(stageEnd, Math.round(info.autoRelease / realSpeed))
  931. }
  932. effectsTimeouts.push(mod.setTimeout(() => { clientAction.overcharge = true }, Math.round(info.overcharge / realSpeed)))
  933. if(!noTimeout) serverTimeout = mod.setTimeout(sendActionEnd, getServerTimeout(), 6)
  934. return
  935. }
  936. let length = Math.round((multiStage ? info.length[opts.stage] : info.length) / realSpeed)
  937. if(!noTimeout) {
  938. let serverTimeoutTime = getServerTimeout()
  939. if(length > serverTimeoutTime) serverTimeout = mod.setTimeout(sendActionEnd, serverTimeoutTime, 6)
  940. }
  941. if(multiStage) {
  942. if(!opts.moving) {
  943. let inPlaceDistance = info.inPlace?.distance?.[opts.stage]
  944. if(inPlaceDistance !== undefined) opts.distance = inPlaceDistance
  945. }
  946. if(opts.stage + 1 < info.length.length) {
  947. opts.stage += 1
  948. stageEnd = sendActionStage.bind(null, opts)
  949. stageEndTime = Date.now() + length
  950. stageEndTimeout = mod.setTimeout(stageEnd, length)
  951. return
  952. }
  953. }
  954. else
  955. if(!opts.moving) {
  956. const inPlaceDistance = info.inPlace?.distance
  957. if(inPlaceDistance !== undefined) opts.distance = inPlaceDistance
  958. }
  959. if(info.dcType === 'dash' && opts.distance) {
  960. const distance = lastStartPos.loc.dist2D(opts.dest)
  961. if(distance < opts.distance) {
  962. length *= distance / opts.distance
  963. opts.distance = distance
  964. }
  965. }
  966. if(['defence', 'movingdefence', 'movingcharge', 'presshit'].includes(info.dcType)) {
  967. opts.stage += 1
  968. stageEnd = sendActionStage.bind(null, opts)
  969. stageEndTime = Date.now() + length
  970. stageEndTimeout = mod.setTimeout(stageEnd, length)
  971. return
  972. }
  973. stageEnd = sendActionEnd.bind(null, info.dcType === 'dash' ? 39 : 0, opts.distance * opts.distanceMult, moveDir)
  974. stageEndTime = Date.now() + length
  975. stageEndTimeout = mod.setTimeout(stageEnd, length)
  976. }
  977. function sendActionEffects(opts) {
  978. const info = opts.info
  979. if(opts.stage) grantCharge(opts.skill, opts.info, opts.stage)
  980. if(info.dcType === 'dash') sendInstantDash(opts.dest)
  981. if(mod.settings.debug.skills.projectiles && info.projectiles)
  982. for(let chain of info.projectiles) {
  983. castProjectile({
  984. skill: modifyChain(opts.skill, chain),
  985. pos: opts.pos,
  986. dest: opts.dest
  987. })
  988. }
  989. }
  990. function clearEffects() {
  991. if(!effectsTimeouts.length) return
  992. for(let t of effectsTimeouts) mod.clearTimeout(t)
  993. effectsTimeouts = []
  994. }
  995. function clearStage() {
  996. mod.clearTimeout(serverTimeout)
  997. clearEffects()
  998. mod.clearTimeout(stageEndTimeout)
  999. }
  1000. function refreshStageEnd() {
  1001. mod.clearTimeout(stageEndTimeout)
  1002. stageEndTimeout = mod.setTimeout(stageEnd, stageEndTime - Date.now())
  1003. }
  1004. function grantCharge(skill, info, stage) {
  1005. const levels = info.chargeLevels,
  1006. chain = levels ? levels[stage] : 10 + stage
  1007. if(chain == null) {
  1008. sendActionEnd(2)
  1009. return
  1010. }
  1011. mod.send('S_GRANT_SKILL', 3, {
  1012. skill: chain > 99 ? new SkillID(chain) : modifyChain(skill, chain)
  1013. })
  1014. }
  1015. function castProjectile(opts) {
  1016. const info = skillInfo(opts.skill)
  1017. if(info.delay) effectsTimeouts.push(mod.setTimeout(addProjectile, info.delay, opts))
  1018. else addProjectile(opts)
  1019. }
  1020. function addProjectile(opts) {
  1021. const skill = opts.skill,
  1022. info = skillInfo(skill)
  1023. if(!info) return
  1024. const id = 0xffffffff00000000n + BigInt(clientProjectileId = clientProjectileId + 1 >>> 0)
  1025. clientProjectiles[id.toString()] = skill
  1026. mod.setTimeout(removeProjectile, 5000, id, info.type === 'userProjectile', true)
  1027. if(info.type === 'userProjectile') {
  1028. const {loc} = applyDistance({
  1029. loc: opts.pos.loc.addN({z: 30}),
  1030. w: opts.pos.w,
  1031. }, 15)
  1032. mod.toClient('S_START_USER_PROJECTILE', 9, {
  1033. gameId: player.gameId,
  1034. templateId: player.templateId,
  1035. unk1: 0,
  1036. id,
  1037. skill,
  1038. loc,
  1039. dest: opts.dest,
  1040. speed: info.flyingSpeed,
  1041. distance: info.flyingDistance,
  1042. curve: !!info.flyingDistance
  1043. })
  1044. }
  1045. }
  1046. function removeProjectile(id, user, explode) {
  1047. delete clientProjectiles[id.toString()]
  1048. if(user) {
  1049. const target = typeof explode === 'object' ? explode : 0
  1050. explode = !!explode
  1051. mod.toClient('S_END_USER_PROJECTILE', 4, {
  1052. id: id,
  1053. unk1: explode && !target,
  1054. unk2: explode,
  1055. target,
  1056. unk3: 0,
  1057. unk4: 0,
  1058. unk5: 0
  1059. })
  1060. }
  1061. }
  1062. function sendInstantDash(dest) {
  1063. mod.toClient('S_INSTANT_DASH', 3, {
  1064. gameId: myChar(),
  1065. target: 0,
  1066. unk: 0,
  1067. loc: dest,
  1068. w: myPosition.w
  1069. })
  1070. }
  1071. function sendInstantMove(event) {
  1072. if(event) updatePosition(event)
  1073. mod.toClient('S_INSTANT_MOVE', 3, {
  1074. gameId: myChar(),
  1075. loc: myPosition.loc,
  1076. w: myPosition.w
  1077. })
  1078. }
  1079. function sendActionEnd(type, distance, dir) {
  1080. clearStage()
  1081. if(!clientAction) return
  1082. if(mod.settings.debug.skills) debug(['<* S_ACTION_END', skillId(clientAction.skill), type || 0, degrees(myPosition.w), (distance || 0) + 'u'].join(' '))
  1083. if(oopsPosition && (mod.settings.skills.forceClipStrict || !myPosition.action)) sendInstantMove(oopsPosition)
  1084. else movePlayer(distance, dir)
  1085. mod.toClient('S_ACTION_END', 5, {
  1086. gameId: myChar(),
  1087. loc: myPosition.loc,
  1088. w: myPosition.w,
  1089. templateId: player.templateId,
  1090. skill: clientAction.skill,
  1091. type: type || 0,
  1092. id: clientAction.id
  1093. })
  1094. if(clientAction.id === actionNumber) { // Emulated skill
  1095. const info = skillInfo(clientAction.skill)
  1096. if(info) {
  1097. if(info.consumeAbnormalEnd)
  1098. if(Array.isArray(info.consumeAbnormalEnd))
  1099. for(let id of info.consumeAbnormalEnd)
  1100. abnormality.remove(id)
  1101. else
  1102. abnormality.remove(info.consumeAbnormalEnd)
  1103. if(info.cooldownEnd && !cooldowns.check(clientAction.skill.id))
  1104. cooldowns.set(clientAction.skill.id, info.cooldownEnd)
  1105. if(info.dcType === 'dash') lastEndPosition = myPosition
  1106. }
  1107. }
  1108. else lastEndedId = clientAction.id
  1109. actionNumber++
  1110. if(actionNumber > 0xffffffff) actionNumber = 0x80000000
  1111. oopsPosition = clientAction = null
  1112. }
  1113. function sendCannotStartSkill(skill) { mod.toClient('S_CANNOT_START_SKILL', 4, { skill: new SkillID({id: skill.id}) }) }
  1114. function sendSystemMessage(type, vars) { mod.toClient('S_SYSTEM_MESSAGE', 1, { message: mod.buildSystemMessage(type, vars) }) }
  1115. function updatePosition(event, action, special) {
  1116. event = event ?? clientAction
  1117. myPosition = {
  1118. loc: event.loc,
  1119. w: special ? event.w || myPosition.w : event.w, // Should be a skill flag maybe?
  1120. action
  1121. }
  1122. }
  1123. function retry(type, skill, cb) {
  1124. mod.clearTimeout(retryTimer[type])
  1125. if(skill.noRetry) return
  1126. const thisSkill = clientAction.skill,
  1127. count = mod.settings.skills[skill.longRetry ? 'longRetryCount' : 'retryCount'],
  1128. ms = mod.settings.skills[skill.longRetry ? 'longRetryMs' : 'retryMs']
  1129. let iter = 0
  1130. function retryIter() {
  1131. if(++iter > count) {
  1132. retryTimer[type] = null
  1133. return
  1134. }
  1135. retryTimer[type] = mod.setTimeout(() => { if(clientAction && clientAction.skill.equals(thisSkill) && cb()) retryIter() }, ms)
  1136. }
  1137. retryIter()
  1138. }
  1139. function movePlayer(distance, dir) {
  1140. if(distance && !myPosition.action) applyDistance(myPosition, distance, dir)
  1141. }
  1142. function applyDistance(pos, dist, dir = 0) {
  1143. pos.loc.add(new Vec3(dist, 0, 0).rotate(pos.w + dir))
  1144. return pos
  1145. }
  1146. // Modifies the chain part (last 2 digits) of a skill ID
  1147. function modifyChain(skill, chain) {
  1148. (skill = skill.clone()).id += chain - (skill.id % 100)
  1149. return skill
  1150. }
  1151. function skillInfo(skill) {
  1152. if(!(skill instanceof SkillID)) skill = new SkillID(skill)
  1153. if(skill.type !== TYPE_ACTION) return null
  1154. const id = skill.id
  1155. let cached = skillsCache.get(id)
  1156. if(cached !== undefined) return cached
  1157. const race = player.race,
  1158. job = player.job,
  1159. group = Math.floor(id / 10000),
  1160. level = (Math.floor(id / 100) % 100) - 1,
  1161. sub = id % 100
  1162. if (get(skillsClient, "9999", skill.id)) {
  1163. skillsCache.set(id, null)
  1164. return null
  1165. }
  1166. let info = [ // Ordered by least specific < most specific
  1167. get(skillsClient, player.templateId, skill.id),
  1168. get(skills, '*', skill.id),
  1169. get(skills, job, '*'),
  1170. get(skills, job, '*', 'level', level),
  1171. get(skills, job, '*', 'race', race),
  1172. get(skills, job, '*', 'race', race, 'level', level),
  1173. get(skills, job, group, '*'),
  1174. get(skills, job, group, '*', 'level', level),
  1175. get(skills, job, group, '*', 'race', race),
  1176. get(skills, job, group, '*', 'race', race, 'level', level),
  1177. get(skills, job, group, sub),
  1178. get(skills, job, group, sub, 'level', level),
  1179. get(skills, job, group, sub, 'race', race),
  1180. get(skills, job, group, sub, 'race', race, 'level', level)
  1181. ]
  1182. // Note: Exact skill (or group + sub) must be specified for prediction to be enabled. This helps to avoid breakage for edge cases
  1183. // TODO: Warn if skill has no client data
  1184. if(info[0] && (info[1] || info[10])) {
  1185. skillsCache.set(id, cached = Object.assign({}, ...info))
  1186. // Sanitize to reduce memory usage
  1187. delete cached.race
  1188. delete cached.level
  1189. return cached
  1190. }
  1191. skillsCache.set(id, null)
  1192. return null
  1193. }
  1194. function isMe(id) { return player.gameId === id || vehicleEx && vehicleEx === id }
  1195. function myChar() { return vehicleEx ? vehicleEx : player.gameId }
  1196. function getServerTimeout() {
  1197. // Assume packet loss (3 round trips) + maximum number of retries
  1198. return Math.min(ping.min*6, ping.max*3) // TODO: Fix ping library (ping.max should ignore packet loss)
  1199. + (mod.settings.skills.retryCount * mod.settings.skills.retryMs)
  1200. + mod.settings.skills.serverTimeout
  1201. }
  1202. }
  1203. // Utilities
  1204. function get(obj, ...keys) {
  1205. if(obj === undefined) return
  1206. for(let key of keys)
  1207. if((obj = obj[key]) === undefined)
  1208. return
  1209. return obj
  1210. }
  1211. // Debug Utilities
  1212. function debug(msg) {
  1213. console.log(`[${(Date.now() % 10000).toString().padStart(4, '0')}] ${msg}`)
  1214. }
  1215. function degrees(w) { return Math.round(w / Math.PI * 180) + '\xb0' }
  1216. function decimal(n, p) {
  1217. p = 10 ** p
  1218. return Math.round(n * p) / p
  1219. }
  1220. function skillId(skill) {
  1221. if(!(skill instanceof SkillID)) skill = new SkillID(skill)
  1222. let str = skill.reserved ? `[X${skill.reserved.toString(16)}]` : ''
  1223. switch(skill.type) {
  1224. case 1: str += 'A'; break
  1225. case 2: str += 'R'; break
  1226. default: str += `[T${skill.type}]`; break
  1227. }
  1228. if(skill.npc) {
  1229. if(skill.type === 1) return `${str}${skill.huntingZoneId}:${skill.id}`
  1230. return str + skill.id
  1231. }
  1232. const id = skill.id.toString()
  1233. switch(skill.type) {
  1234. case 1: return str + [id.slice(0, -4), id.slice(-4, -2), id.slice(-2)].join('-')
  1235. case 2: return str + [id.slice(0, -2), id.slice(-2)].join('-')
  1236. default: return str + id
  1237. }
  1238. }