unit.cpp 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "unit.hpp"
  4. #include <cstdlib>
  5. #include <cstring>
  6. #include <common/db.hpp>
  7. #include <common/ers.hpp> // ers_destroy
  8. #include <common/malloc.hpp>
  9. #include <common/nullpo.hpp>
  10. #include <common/random.hpp>
  11. #include <common/showmsg.hpp>
  12. #include <common/socket.hpp>
  13. #include <common/timer.hpp>
  14. #include <common/utils.hpp>
  15. #include "achievement.hpp"
  16. #include "battle.hpp"
  17. #include "battleground.hpp"
  18. #include "channel.hpp"
  19. #include "chat.hpp"
  20. #include "clif.hpp"
  21. #include "duel.hpp"
  22. #include "elemental.hpp"
  23. #include "guild.hpp"
  24. #include "homunculus.hpp"
  25. #include "intif.hpp"
  26. #include "map.hpp"
  27. #include "mercenary.hpp"
  28. #include "mob.hpp"
  29. #include "npc.hpp"
  30. #include "party.hpp"
  31. #include "path.hpp"
  32. #include "pc.hpp"
  33. #include "pet.hpp"
  34. #include "storage.hpp"
  35. #include "trade.hpp"
  36. using namespace rathena;
  37. #ifndef MAX_SHADOW_SCAR
  38. #define MAX_SHADOW_SCAR 100 /// Max Shadow Scars
  39. #endif
  40. // How many milliseconds need to pass before we calculated the exact position of a unit
  41. // Calculation will only happen on demand and when at least the time defined here has passed
  42. #ifndef MIN_POS_INTERVAL
  43. #define MIN_POS_INTERVAL 20
  44. #endif
  45. // Directions values
  46. // 1 0 7
  47. // 2 . 6
  48. // 3 4 5
  49. // See also path.cpp walk_choices
  50. const int16 dirx[DIR_MAX]={0,-1,-1,-1,0,1,1,1}; ///lookup to know where will move to x according dir
  51. const int16 diry[DIR_MAX]={1,1,0,-1,-1,-1,0,1}; ///lookup to know where will move to y according dir
  52. //early declaration
  53. static TIMER_FUNC(unit_attack_timer);
  54. static TIMER_FUNC(unit_walktoxy_timer);
  55. int32 unit_unattackable(struct block_list *bl);
  56. /**
  57. * Get the unit_data related to the bl
  58. * @param bl : Object to get the unit_data from
  59. * valid type are : BL_PC|BL_MOB|BL_PET|BL_NPC|BL_HOM|BL_MER|BL_ELEM
  60. * @return unit_data of bl or nullptr
  61. */
  62. struct unit_data* unit_bl2ud(struct block_list *bl)
  63. {
  64. if( bl == nullptr) return nullptr;
  65. switch(bl->type){
  66. case BL_PC: return &((map_session_data*)bl)->ud;
  67. case BL_MOB: return &((struct mob_data*)bl)->ud;
  68. case BL_PET: return &((struct pet_data*)bl)->ud;
  69. case BL_NPC: return &((struct npc_data*)bl)->ud;
  70. case BL_HOM: return &((struct homun_data*)bl)->ud;
  71. case BL_MER: return &((s_mercenary_data*)bl)->ud;
  72. case BL_ELEM: return &((s_elemental_data*)bl)->ud;
  73. default : return nullptr;
  74. }
  75. }
  76. /**
  77. * Updates chase depending on situation:
  78. * If target in attack range -> attack
  79. * If target out of sight -> drop target
  80. * Otherwise update chase path
  81. * @param bl: Moving bl
  82. * @param tick: Current tick
  83. * @param fullcheck: If false, only check for attack, don't drop target or update chase path
  84. * @return Whether the chase path was updated (true) or current movement can continue (false)
  85. */
  86. bool unit_update_chase(block_list& bl, t_tick tick, bool fullcheck) {
  87. unit_data* ud = unit_bl2ud(&bl);
  88. if (ud == nullptr)
  89. return true;
  90. block_list* tbl = nullptr;
  91. if (ud->target_to != 0)
  92. tbl = map_id2bl(ud->target_to);
  93. // Reached destination, start attacking
  94. if (tbl != nullptr && tbl->type != BL_ITEM && tbl->m == bl.m && ud->walkpath.path_pos > 0 && check_distance_bl(&bl, tbl, ud->chaserange)) {
  95. // We need to make sure the walkpath is cleared here so a monster doesn't continue walking in case it unlocks its target
  96. unit_stop_walking(&bl, USW_FIXPOS|USW_FORCE_STOP|USW_RELEASE_TARGET);
  97. if (ud->state.attack_continue)
  98. unit_attack(&bl, tbl->id, ud->state.attack_continue);
  99. return true;
  100. }
  101. // Cancel chase
  102. else if (tbl == nullptr || (fullcheck && !status_check_visibility(&bl, tbl, (bl.type == BL_MOB)))) {
  103. // Looted items will have no tbl but target ID is still set, that's why we need to check for the ID here
  104. if (ud->target_to != 0 && bl.type == BL_MOB) {
  105. mob_data& md = reinterpret_cast<mob_data&>(bl);
  106. if (tbl != nullptr) {
  107. int32 warp = mob_warpchase(&md, tbl);
  108. // Do warp chase
  109. if (warp == 1)
  110. return true;
  111. // Continue moving to warp
  112. else if (warp == 2)
  113. return false;
  114. }
  115. // Make sure monsters properly unlock their target, but still continue movement
  116. mob_unlocktarget(&md, tick);
  117. return false;
  118. }
  119. unit_stop_walking(&bl, USW_FIXPOS|USW_FORCE_STOP|USW_RELEASE_TARGET);
  120. return true;
  121. }
  122. // Update chase path
  123. else if (fullcheck && ud->walkpath.path_pos > 0 && DIFF_TICK(ud->canmove_tick, tick) <= 0) {
  124. // We call this only when we know there is no walk delay to prevent it pre-planning a chase
  125. // If the call here fails, the unit should continue its current path
  126. if(unit_walktobl(&bl, tbl, ud->chaserange, ud->state.walk_easy | (ud->state.attack_continue ? 2 : 0)))
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Handles everything that happens when movement to the next cell is initiated
  133. * @param bl: Moving bl
  134. * @param sendMove: Whether move packet should be sent or not
  135. * @param tick: Current tick
  136. * @return Whether movement was initialized (true) or not (false)
  137. */
  138. bool unit_walktoxy_nextcell(block_list& bl, bool sendMove, t_tick tick) {
  139. unit_data* ud = unit_bl2ud(&bl);
  140. if (ud == nullptr)
  141. return true;
  142. // Reached end of walkpath
  143. if (ud->walkpath.path_pos >= ud->walkpath.path_len)
  144. return false;
  145. // Monsters first check for a chase skill and if they didn't use one if their target is in range each cell after checking for a chase skill
  146. if (bl.type == BL_MOB) {
  147. mob_data& md = reinterpret_cast<mob_data&>(bl);
  148. // Walk skills are triggered regardless of target due to the idle-walk mob state.
  149. // But avoid triggering when already reached the end of the walkpath.
  150. // Monsters use walk/chase skills every second, but we only get here every "speed" ms
  151. // To make sure we check one skill per second on average, we substract half the speed as ms
  152. if (!ud->state.force_walk &&
  153. DIFF_TICK(tick, md.last_skillcheck) > MOB_SKILL_INTERVAL - md.status.speed / 2 &&
  154. mobskill_use(&md, tick, -1)) {
  155. if ((ud->skill_id != NPC_SPEEDUP || md.trickcasting == 0) //Stop only when trickcasting expired
  156. && ud->skill_id != NPC_EMOTION && ud->skill_id != NPC_EMOTION_ON //NPC_EMOTION doesn't make the monster stop
  157. && md.state.skillstate != MSS_WALK) //Walk skills are supposed to be used while walking
  158. {
  159. // Skill used, abort walking
  160. // Fix position as walk has been cancelled.
  161. clif_fixpos(bl);
  162. // Movement was initialized, so we need to return true even though it was stopped
  163. // Monsters only start moving or drop target when they stop using chase skills that stop them
  164. return true;
  165. }
  166. // Resend walk packet for proper Self Destruction display
  167. sendMove = true;
  168. }
  169. if (ud->target_to != 0) {
  170. // Monsters update their chase path one cell before reaching their final destination
  171. if (unit_update_chase(bl, tick, (ud->walkpath.path_pos == ud->walkpath.path_len - 1)))
  172. return true;
  173. }
  174. }
  175. // Get current speed
  176. int32 speed;
  177. if (direction_diagonal(ud->walkpath.path[ud->walkpath.path_pos]))
  178. speed = status_get_speed(&bl) * MOVE_DIAGONAL_COST / MOVE_COST;
  179. else
  180. speed = status_get_speed(&bl);
  181. // Make sure there is no active walktimer
  182. if (ud->walktimer != INVALID_TIMER) {
  183. delete_timer(ud->walktimer, unit_walktoxy_timer);
  184. ud->walktimer = INVALID_TIMER;
  185. }
  186. ud->walktimer = add_timer(tick + speed, unit_walktoxy_timer, bl.id, speed);
  187. if (sendMove)
  188. clif_move(*ud);
  189. return true;
  190. }
  191. /**
  192. * Tells a unit to walk to a specific coordinate
  193. * @param bl: Unit to walk [ALL]
  194. * @return 1: Success 0: Fail
  195. */
  196. int32 unit_walktoxy_sub(struct block_list *bl)
  197. {
  198. nullpo_retr(1, bl);
  199. unit_data *ud = unit_bl2ud(bl);
  200. if (ud == nullptr)
  201. return 0;
  202. walkpath_data wpd = { 0 };
  203. if( !path_search(&wpd,bl->m,bl->x,bl->y,ud->to_x,ud->to_y,ud->state.walk_easy,CELL_CHKNOPASS) )
  204. return 0;
  205. #ifdef OFFICIAL_WALKPATH
  206. if( bl->type != BL_NPC // If type is a NPC, please disregard.
  207. && wpd.path_len > 14 // Official number of walkable cells is 14 if and only if there is an obstacle between. [malufett]
  208. && !path_search_long(nullptr, bl->m, bl->x, bl->y, ud->to_x, ud->to_y, CELL_CHKNOPASS) ) // Check if there is an obstacle between
  209. return 0;
  210. #endif
  211. ud->walkpath = wpd;
  212. int32 i;
  213. // Monsters always target an adjacent tile even if ranged, no need to shorten the path
  214. if (ud->target_to != 0 && ud->chaserange > 1 && bl->type != BL_MOB) {
  215. // Generally speaking, the walk path is already to an adjacent tile
  216. // so we only need to shorten the path if the range is greater than 1.
  217. // Trim the last part of the path to account for range,
  218. // but always move at least one cell when requested to move.
  219. for (i = (ud->chaserange*10)-10; i > 0 && ud->walkpath.path_len>1;) {
  220. ud->walkpath.path_len--;
  221. enum directions dir = ud->walkpath.path[ud->walkpath.path_len];
  222. if (direction_diagonal(dir))
  223. i -= MOVE_COST * 2; //When chasing, units will target a diamond-shaped area in range [Playtester]
  224. else
  225. i -= MOVE_COST;
  226. ud->to_x -= dirx[dir];
  227. ud->to_y -= diry[dir];
  228. }
  229. }
  230. ud->state.change_walk_target=0;
  231. if (bl->type == BL_PC) {
  232. map_session_data *sd = BL_CAST(BL_PC, bl);
  233. sd->head_dir = DIR_NORTH;
  234. clif_walkok(*sd);
  235. }
  236. #if PACKETVER >= 20170726
  237. // If this is a walking NPC and it will use a player sprite
  238. else if( bl->type == BL_NPC && pcdb_checkid( status_get_viewdata( bl )->class_ ) ){
  239. // Respawn the NPC as player unit
  240. unit_refresh( bl, true );
  241. }
  242. #endif
  243. // Set mobstate here already as chase skills can be used on the first frame of movement
  244. // If we don't set it now the monster will always move a full cell before checking
  245. else if (bl->type == BL_MOB && ud->state.attack_continue) {
  246. mob_data& md = reinterpret_cast<mob_data&>(*bl);
  247. mob_setstate(md, MSS_RUSH);
  248. }
  249. unit_walktoxy_nextcell(*bl, true, gettick());
  250. return 1;
  251. }
  252. /**
  253. * Retrieve the direct master of a bl if one exists.
  254. * @param bl: char to get his master [HOM|ELEM|PET|MER]
  255. * @return map_session_data of master or nullptr
  256. */
  257. TBL_PC* unit_get_master(struct block_list *bl)
  258. {
  259. if(bl)
  260. switch(bl->type) {
  261. case BL_HOM: return (((TBL_HOM *)bl)->master);
  262. case BL_ELEM: return (((TBL_ELEM *)bl)->master);
  263. case BL_PET: return (((TBL_PET *)bl)->master);
  264. case BL_MER: return (((TBL_MER *)bl)->master);
  265. }
  266. return nullptr;
  267. }
  268. /**
  269. * Retrieve a unit's master's teleport timer
  270. * @param bl: char to get his master's teleport timer [HOM|ELEM|PET|MER]
  271. * @return timer or nullptr
  272. */
  273. int32* unit_get_masterteleport_timer(struct block_list *bl)
  274. {
  275. if(bl)
  276. switch(bl->type) {
  277. case BL_HOM: return &(((TBL_HOM *)bl)->masterteleport_timer);
  278. case BL_ELEM: return &(((TBL_ELEM *)bl)->masterteleport_timer);
  279. case BL_PET: return &(((TBL_PET *)bl)->masterteleport_timer);
  280. case BL_MER: return &(((TBL_MER *)bl)->masterteleport_timer);
  281. }
  282. return nullptr;
  283. }
  284. /**
  285. * Warps a unit to its master if the master has gone out of sight (3 second default)
  286. * Can be any object with a master [MOB|PET|HOM|MER|ELEM]
  287. * @param tid: Timer
  288. * @param tick: tick (unused)
  289. * @param id: Unit to warp
  290. * @param data: Data transferred from timer call
  291. * @return 0
  292. */
  293. TIMER_FUNC(unit_teleport_timer){
  294. struct block_list *bl = map_id2bl(id);
  295. int32 *mast_tid = unit_get_masterteleport_timer(bl);
  296. if(tid == INVALID_TIMER || mast_tid == nullptr)
  297. return 0;
  298. else if(*mast_tid != tid || bl == nullptr)
  299. return 0;
  300. else {
  301. map_session_data* msd = unit_get_master( bl );
  302. if( msd != nullptr && !check_distance_bl( &msd->bl, bl, static_cast<int32>( data ) ) ){
  303. *mast_tid = INVALID_TIMER;
  304. unit_warp(bl, msd->bl.m, msd->bl.x, msd->bl.y, CLR_TELEPORT );
  305. } else // No timer needed
  306. *mast_tid = INVALID_TIMER;
  307. }
  308. return 0;
  309. }
  310. /**
  311. * Checks if a slave unit is outside their max distance from master
  312. * If so, starts a timer (default: 3 seconds) which will teleport the unit back to master
  313. * @param sbl: Object with a master [MOB|PET|HOM|MER|ELEM]
  314. * @return 0
  315. */
  316. int32 unit_check_start_teleport_timer(struct block_list *sbl)
  317. {
  318. TBL_PC *msd = nullptr;
  319. int32 max_dist = 0;
  320. switch(sbl->type) {
  321. case BL_HOM:
  322. case BL_ELEM:
  323. case BL_PET:
  324. case BL_MER:
  325. msd = unit_get_master(sbl);
  326. break;
  327. default:
  328. return 0;
  329. }
  330. switch(sbl->type) {
  331. case BL_HOM: max_dist = AREA_SIZE; break;
  332. case BL_ELEM: max_dist = MAX_ELEDISTANCE; break;
  333. case BL_PET: max_dist = AREA_SIZE; break;
  334. case BL_MER: max_dist = MAX_MER_DISTANCE; break;
  335. }
  336. // If there is a master and it's a valid type
  337. if(msd && max_dist) {
  338. int32 *msd_tid = unit_get_masterteleport_timer(sbl);
  339. if(msd_tid == nullptr)
  340. return 0;
  341. if (!check_distance_bl(&msd->bl, sbl, max_dist)) {
  342. if(*msd_tid == INVALID_TIMER || *msd_tid == 0)
  343. *msd_tid = add_timer(gettick()+3000,unit_teleport_timer,sbl->id,max_dist);
  344. } else {
  345. if(*msd_tid && *msd_tid != INVALID_TIMER)
  346. delete_timer(*msd_tid,unit_teleport_timer);
  347. *msd_tid = INVALID_TIMER; // Cancel recall
  348. }
  349. }
  350. return 0;
  351. }
  352. /**
  353. * Triggered on full step if stepaction is true and executes remembered action.
  354. * @param tid: Timer ID
  355. * @param tick: Unused
  356. * @param id: ID of bl to do the action
  357. * @param data: Not used
  358. * @return 1: Success 0: Fail (No valid bl)
  359. */
  360. TIMER_FUNC(unit_step_timer){
  361. struct block_list *bl;
  362. struct unit_data *ud;
  363. int32 target_id;
  364. bl = map_id2bl(id);
  365. if (!bl || bl->prev == nullptr)
  366. return 0;
  367. ud = unit_bl2ud(bl);
  368. if(!ud)
  369. return 0;
  370. if(ud->steptimer != tid) {
  371. ShowError("unit_step_timer mismatch %d != %d\n",ud->steptimer,tid);
  372. return 0;
  373. }
  374. ud->steptimer = INVALID_TIMER;
  375. if(!ud->stepaction)
  376. return 0;
  377. //Set to false here because if an error occurs, it should not be executed again
  378. ud->stepaction = false;
  379. if(!ud->target_to)
  380. return 0;
  381. //Flush target_to as it might contain map coordinates which should not be used by other functions
  382. target_id = ud->target_to;
  383. ud->target_to = 0;
  384. //If stepaction is set then we remembered a client request that should be executed on the next step
  385. //Execute request now if target is in attack range
  386. if(ud->stepskill_id && skill_get_inf(ud->stepskill_id) & INF_GROUND_SKILL) {
  387. //Execute ground skill
  388. struct map_data *md = &map[bl->m];
  389. unit_skilluse_pos(bl, target_id%md->xs, target_id/md->xs, ud->stepskill_id, ud->stepskill_lv);
  390. } else {
  391. //If a player has target_id set and target is in range, attempt attack
  392. struct block_list *tbl = map_id2bl(target_id);
  393. if (tbl == nullptr || !status_check_visibility(bl, tbl, false)) {
  394. return 0;
  395. }
  396. if(ud->stepskill_id == 0) {
  397. //Execute normal attack
  398. unit_attack(bl, tbl->id, (ud->state.attack_continue) + 2);
  399. } else {
  400. //Execute non-ground skill
  401. unit_skilluse_id(bl, tbl->id, ud->stepskill_id, ud->stepskill_lv);
  402. }
  403. }
  404. return 1;
  405. }
  406. int32 unit_walktoxy_ontouch(struct block_list *bl, va_list ap)
  407. {
  408. struct npc_data *nd;
  409. nullpo_ret(bl);
  410. nullpo_ret(nd = va_arg(ap,struct npc_data *));
  411. switch( bl->type ) {
  412. case BL_PC:
  413. TBL_PC *sd = (TBL_PC*)bl;
  414. if (sd == nullptr)
  415. return 1;
  416. if (sd->state.block_action & PCBLOCK_NPCCLICK)
  417. return 1;
  418. // Remove NPCs that are no longer within the OnTouch area
  419. for (size_t i = 0; i < sd->areanpc.size(); i++) {
  420. struct npc_data *nd = map_id2nd(sd->areanpc[i]);
  421. if (!nd || nd->subtype != NPCTYPE_SCRIPT || !(nd->bl.m == bl->m && bl->x >= nd->bl.x - nd->u.scr.xs && bl->x <= nd->bl.x + nd->u.scr.xs && bl->y >= nd->bl.y - nd->u.scr.ys && bl->y <= nd->bl.y + nd->u.scr.ys))
  422. rathena::util::erase_at(sd->areanpc, i);
  423. }
  424. npc_touchnext_areanpc(sd, false);
  425. if (map_getcell(bl->m, bl->x, bl->y, CELL_CHKNPC) == 0)
  426. return 1;
  427. npc_touch_areanpc(sd, bl->m, bl->x, bl->y, nd);
  428. break;
  429. // case BL_MOB: // unsupported
  430. }
  431. return 0;
  432. }
  433. /**
  434. * Defines when to refresh the walking character to object and restart the timer if applicable
  435. * Also checks for speed update, target location, and slave teleport timers
  436. * @param tid: Timer ID
  437. * @param tick: Current tick to decide next timer update
  438. * @param data: Data used in timer calls
  439. * @return 0 or unit_walktoxy_sub() or unit_walktoxy()
  440. */
  441. static TIMER_FUNC(unit_walktoxy_timer)
  442. {
  443. block_list *bl = map_id2bl(id);
  444. if(bl == nullptr)
  445. return 0;
  446. unit_data *ud = unit_bl2ud(bl);
  447. if(ud == nullptr)
  448. return 0;
  449. if(ud->walktimer != tid) {
  450. ShowError("unit_walk_timer mismatch %d != %d\n",ud->walktimer,tid);
  451. return 0;
  452. }
  453. ud->walktimer = INVALID_TIMER;
  454. // As movement to next cell finished, set sub-cell position to center
  455. ud->sx = 8;
  456. ud->sy = 8;
  457. if (bl->prev == nullptr)
  458. return 0; // Stop moved because it is missing from the block_list
  459. if(ud->walkpath.path_pos>=ud->walkpath.path_len)
  460. return 0;
  461. enum directions dir = ud->walkpath.path[ud->walkpath.path_pos];
  462. if( dir <= DIR_CENTER || dir >= DIR_MAX ){
  463. return 0;
  464. }
  465. unit_setdir(bl, dir, false);
  466. int32 dx = dirx[dir];
  467. int32 dy = diry[dir];
  468. map_session_data *sd = nullptr;
  469. mob_data *md = nullptr;
  470. npc_data *nd = nullptr;
  471. // Get icewall walk block depending on Status Immune mode (players can't be trapped)
  472. unsigned char icewall_walk_block = 0;
  473. switch(bl->type) { // avoid useless cast, we can only be 1 type
  474. case BL_PC: sd = BL_CAST(BL_PC, bl); break;
  475. case BL_MOB:
  476. md = BL_CAST(BL_MOB, bl);
  477. if (status_has_mode(&md->status,MD_STATUSIMMUNE))
  478. icewall_walk_block = battle_config.boss_icewall_walk_block;
  479. else
  480. icewall_walk_block = battle_config.mob_icewall_walk_block;
  481. break;
  482. case BL_NPC: nd = BL_CAST(BL_NPC, bl); break;
  483. }
  484. int32 x = bl->x;
  485. int32 y = bl->y;
  486. //Monsters will walk into an icewall from the west and south if they already started walking
  487. if(map_getcell(bl->m,x+dx,y+dy,CELL_CHKNOPASS)
  488. && (icewall_walk_block == 0 || dx < 0 || dy < 0 || !map_getcell(bl->m,x+dx,y+dy,CELL_CHKICEWALL)))
  489. return unit_walktoxy_sub(bl);
  490. //Monsters can only leave icewalls to the west and south
  491. //But if movement fails more than icewall_walk_block times, they can ignore this rule
  492. if(md && !ud->state.force_walk && md->walktoxy_fail_count < icewall_walk_block && map_getcell(bl->m,x,y,CELL_CHKICEWALL) && (dx > 0 || dy > 0)) {
  493. //Needs to be done here so that rudeattack skills are invoked
  494. md->walktoxy_fail_count++;
  495. clif_fixpos( *bl );
  496. // Monsters in this situation will unlock target
  497. mob_unlocktarget(md, tick);
  498. return 0;
  499. }
  500. // Refresh view for all those we lose sight
  501. map_foreachinmovearea(clif_outsight, bl, AREA_SIZE, dx, dy, sd?BL_ALL:BL_PC, bl);
  502. x += dx;
  503. y += dy;
  504. map_moveblock(bl, x, y, tick);
  505. if (bl->x != x || bl->y != y || ud->walktimer != INVALID_TIMER)
  506. return 0; // map_moveblock has altered the object beyond what we expected (moved/warped it)
  507. ud->walktimer = CLIF_WALK_TIMER; // Arbitrary non-INVALID_TIMER value to make the clif code send walking packets
  508. map_foreachinmovearea(clif_insight, bl, AREA_SIZE, -dx, -dy, sd?BL_ALL:BL_PC, bl);
  509. ud->walktimer = INVALID_TIMER;
  510. if (bl->x == ud->to_x && bl->y == ud->to_y) {
  511. #if PACKETVER >= 20170726
  512. // If this was a walking NPC and it used a player sprite
  513. if( bl->type == BL_NPC && pcdb_checkid( status_get_viewdata( bl )->class_ ) ){
  514. // Respawn the NPC as NPC unit
  515. unit_refresh( bl, false );
  516. }
  517. #endif
  518. // Remove any possible escape states present for mobs once they stopped moving.
  519. if (md != nullptr) {
  520. md->state.can_escape = 0;
  521. }
  522. ud->state.force_walk = false;
  523. if (ud->walk_done_event[0]){
  524. char walk_done_event[EVENT_NAME_LENGTH];
  525. // Copying is required in case someone uses unitwalkto inside the event code
  526. safestrncpy(walk_done_event, ud->walk_done_event, EVENT_NAME_LENGTH);
  527. //Clear the event
  528. ud->walk_done_event[0] = 0;
  529. ud->state.walk_script = true;
  530. // Execute the event
  531. npc_event_do_id(walk_done_event,bl->id);
  532. ud->state.walk_script = false;
  533. // Check if the unit was killed
  534. if( status_isdead(*bl) ){
  535. struct mob_data* md = BL_CAST(BL_MOB, bl);
  536. if( md && !md->spawn ){
  537. unit_free(bl, CLR_OUTSIGHT);
  538. }
  539. return 0;
  540. }
  541. }
  542. }
  543. switch(bl->type) {
  544. case BL_PC:
  545. if( !sd->npc_ontouch_.empty() )
  546. npc_touchnext_areanpc(sd,false);
  547. if(map_getcell(bl->m,x,y,CELL_CHKNPC)) {
  548. npc_touch_area_allnpc(sd,bl->m,x,y);
  549. if (bl->prev == nullptr) // Script could have warped char, abort remaining of the function.
  550. return 0;
  551. } else
  552. sd->areanpc.clear();
  553. pc_cell_basilica(sd);
  554. break;
  555. case BL_MOB:
  556. //Movement was successful, reset walktoxy_fail_count
  557. md->walktoxy_fail_count = 0;
  558. if( map_getcell(bl->m,x,y,CELL_CHKNPC) ) {
  559. if( npc_touch_areanpc2(md) )
  560. return 0; // Warped
  561. } else
  562. md->areanpc_id = 0;
  563. break;
  564. case BL_NPC:
  565. if (nd->is_invisible)
  566. break;
  567. int32 xs = -1, ys = -1;
  568. switch (nd->subtype) {
  569. case NPCTYPE_SCRIPT:
  570. xs = nd->u.scr.xs;
  571. ys = nd->u.scr.ys;
  572. break;
  573. case NPCTYPE_WARP:
  574. xs = nd->u.warp.xs;
  575. ys = nd->u.warp.ys;
  576. break;
  577. }
  578. if (xs > -1 && ys > -1)
  579. map_foreachinmap(unit_walktoxy_ontouch, nd->bl.m, BL_PC, nd);
  580. break;
  581. }
  582. if(tid == INVALID_TIMER) // A directly invoked timer is from battle_stop_walking, therefore the rest is irrelevant.
  583. return 0;
  584. int32 speed;
  585. //If stepaction is set then we remembered a client request that should be executed on the next step
  586. if (ud->stepaction && ud->target_to) {
  587. //Delete old stepaction even if not executed yet, the latest command is what counts
  588. if(ud->steptimer != INVALID_TIMER) {
  589. delete_timer(ud->steptimer, unit_step_timer);
  590. ud->steptimer = INVALID_TIMER;
  591. }
  592. //Delay stepactions by half a step (so they are executed at full step)
  593. if( direction_diagonal( ud->walkpath.path[ud->walkpath.path_pos] ) )
  594. speed = status_get_speed(bl)*MOVE_DIAGONAL_COST/MOVE_COST/2;
  595. else
  596. speed = status_get_speed(bl)/2;
  597. ud->steptimer = add_timer(tick+speed, unit_step_timer, bl->id, 0);
  598. }
  599. if(ud->state.change_walk_target) {
  600. if(unit_walktoxy_sub(bl)) {
  601. return 1;
  602. } else {
  603. clif_fixpos( *bl );
  604. return 0;
  605. }
  606. }
  607. ud->walkpath.path_pos++;
  608. if(unit_walktoxy_nextcell(*bl, (md != nullptr && DIFF_TICK(tick, md->dmgtick) < 3000), tick)) {
  609. // Nothing else needs to be done
  610. } else if(ud->state.running) { // Keep trying to run.
  611. if (!(unit_run(bl, nullptr, SC_RUN) || unit_run(bl, sd, SC_WUGDASH)) )
  612. ud->state.running = 0;
  613. } else {
  614. if (!ud->stepaction && ud->target_to > 0) {
  615. // Update target trajectory.
  616. if(unit_update_chase(*bl, tick, true))
  617. return 0;
  618. }
  619. // Stopped walking. Update to_x and to_y to current location
  620. ud->to_x = bl->x;
  621. ud->to_y = bl->y;
  622. if (bl->type != BL_NPC // walking npc ignores cell stack limit
  623. && !ud->state.ignore_cell_stack_limit
  624. && battle_config.official_cell_stack_limit > 0
  625. && map_count_oncell(bl->m, x, y, BL_CHAR|BL_NPC, 1) > battle_config.official_cell_stack_limit) {
  626. //Walked on occupied cell, call unit_walktoxy again
  627. if(unit_walktoxy(bl, x, y, 8)) {
  628. //Execute step timer on next step instead
  629. if (ud->steptimer != INVALID_TIMER) {
  630. //Execute step timer on next step instead
  631. delete_timer(ud->steptimer, unit_step_timer);
  632. ud->steptimer = INVALID_TIMER;
  633. }
  634. return 1;
  635. }
  636. }
  637. }
  638. return 0;
  639. }
  640. /**
  641. * Delays an xy timer
  642. * @param tid: Timer ID
  643. * @param tick: Unused
  644. * @param id: ID of bl to delay timer on
  645. * @param data: Data used in timer calls
  646. * @return 1: Success 0: Fail (No valid bl)
  647. */
  648. TIMER_FUNC(unit_delay_walktoxy_timer){
  649. struct block_list *bl = map_id2bl(id);
  650. if (!bl || bl->prev == nullptr)
  651. return 0;
  652. unit_walktoxy(bl, (int16)((data>>16)&0xffff), (int16)(data&0xffff), 0);
  653. return 1;
  654. }
  655. /**
  656. * Delays an walk-to-bl timer
  657. * @param tid: Timer ID
  658. * @param tick: Unused
  659. * @param id: ID of bl to delay timer on
  660. * @param data: Data used in timer calls (target bl)
  661. * @return 1: Success 0: Fail (No valid bl or target)
  662. */
  663. TIMER_FUNC(unit_delay_walktobl_timer){
  664. block_list* bl = map_id2bl( id );
  665. block_list* tbl = map_id2bl( static_cast<int32>( data ) );
  666. if(!bl || bl->prev == nullptr || tbl == nullptr)
  667. return 0;
  668. else {
  669. struct unit_data* ud = unit_bl2ud(bl);
  670. unit_walktobl(bl, tbl, 0, 0);
  671. ud->target_to = 0;
  672. }
  673. return 1;
  674. }
  675. /**
  676. * Begins the function of walking a unit to an x,y location
  677. * This is where the path searches and unit can_move checks are done
  678. * @param bl: Object to send to x,y coordinate
  679. * @param x: X coordinate where the object will be walking to
  680. * @param y: Y coordinate where the object will be walking to
  681. * @param flag: Parameter to decide how to walk
  682. * &1: Easy walk (fail if CELL_CHKNOPASS is in direct path)
  683. * &2: Force walking (override can_move)
  684. * &4: Delay walking for can_move
  685. * &8: Search for an unoccupied cell and cancel if none available
  686. * @return 1: Success 0: Fail or unit_walktoxy_sub()
  687. */
  688. int32 unit_walktoxy( struct block_list *bl, int16 x, int16 y, unsigned char flag)
  689. {
  690. nullpo_ret(bl);
  691. unit_data* ud = unit_bl2ud(bl);
  692. if (ud == nullptr)
  693. return 0;
  694. if ((flag&8) && !map_nearby_freecell(bl->m, x, y, BL_CHAR|BL_NPC, 1)) //This might change x and y
  695. return 0;
  696. walkpath_data wpd = { 0 };
  697. if (!path_search(&wpd, bl->m, bl->x, bl->y, x, y, flag&1, CELL_CHKNOPASS)) // Count walk path cells
  698. return 0;
  699. // NPCs do not need to fulfill the following checks
  700. if( bl->type != BL_NPC ){
  701. if( wpd.path_len > battle_config.max_walk_path ){
  702. return 0;
  703. }
  704. #ifdef OFFICIAL_WALKPATH
  705. // Official number of walkable cells is 14 if and only if there is an obstacle between.
  706. if( wpd.path_len > 14 && !path_search_long( nullptr, bl->m, bl->x, bl->y, x, y, CELL_CHKNOPASS ) ){
  707. return 0;
  708. }
  709. #endif
  710. }
  711. if (flag&4) {
  712. unit_unattackable(bl);
  713. unit_stop_attack(bl);
  714. if(DIFF_TICK(ud->canmove_tick, gettick()) > 0 && DIFF_TICK(ud->canmove_tick, gettick()) < 2000) { // Delay walking command. [Skotlex]
  715. add_timer(ud->canmove_tick+1, unit_delay_walktoxy_timer, bl->id, (x<<16)|(y&0xFFFF));
  716. return 1;
  717. }
  718. }
  719. if(!(flag&2) && (!status_bl_has_mode(bl,MD_CANMOVE) || !unit_can_move(bl)))
  720. return 0;
  721. ud->state.walk_easy = flag&1;
  722. ud->to_x = x;
  723. ud->to_y = y;
  724. unit_stop_attack(bl); //Sets target to 0
  725. status_change* sc = status_get_sc(bl);
  726. if (sc && sc->getSCE(SC_CONFUSION)) // Randomize the target position
  727. map_random_dir(bl, &ud->to_x, &ud->to_y);
  728. if(ud->walktimer != INVALID_TIMER) {
  729. // When you come to the center of the grid because the change of destination while you're walking right now
  730. // Call a function from a timer unit_walktoxy_sub
  731. ud->state.change_walk_target = 1;
  732. return 1;
  733. }
  734. TBL_PC *sd = BL_CAST(BL_PC, bl);
  735. // Start timer to recall summon
  736. if( sd != nullptr ){
  737. if (sd->md != nullptr)
  738. unit_check_start_teleport_timer(&sd->md->bl);
  739. if (sd->ed != nullptr)
  740. unit_check_start_teleport_timer(&sd->ed->bl);
  741. if (sd->hd != nullptr)
  742. unit_check_start_teleport_timer(&sd->hd->bl);
  743. if (sd->pd != nullptr)
  744. unit_check_start_teleport_timer(&sd->pd->bl);
  745. }
  746. return unit_walktoxy_sub(bl);
  747. }
  748. /**
  749. * Timer to walking a unit to another unit's location
  750. * Calls unit_walktoxy_sub once determined the unit can move
  751. * @param tid: Object's timer ID
  752. * @param id: Object's ID
  753. * @param data: Data passed through timer function (target)
  754. * @return 0
  755. */
  756. static TIMER_FUNC(unit_walktobl_sub){
  757. struct block_list *bl = map_id2bl(id);
  758. struct unit_data *ud = bl?unit_bl2ud(bl):nullptr;
  759. if (ud != nullptr && ud->walktimer == INVALID_TIMER && ud->target_to != 0 && ud->target_to == data) {
  760. if (DIFF_TICK(ud->canmove_tick, tick) > 0) // Keep waiting?
  761. add_timer(ud->canmove_tick+1, unit_walktobl_sub, id, data);
  762. else if (unit_can_move(bl))
  763. unit_walktoxy_sub(bl);
  764. }
  765. return 0;
  766. }
  767. /**
  768. * Tells a unit to walk to a target's location (chase)
  769. * @param bl: Object that is walking to target
  770. * @param tbl: Target object
  771. * @param range: How close to get to target (or attack range if flag&2)
  772. * @param flag: Extra behaviour
  773. * &1: Use easy path seek (obstacles will not be walked around)
  774. * &2: Start attacking upon arrival within range, otherwise just walk to target
  775. * @return 1: Started walking or set timer 0: Failed
  776. */
  777. int32 unit_walktobl(struct block_list *bl, struct block_list *tbl, int32 range, unsigned char flag)
  778. {
  779. nullpo_ret(bl);
  780. nullpo_ret(tbl);
  781. unit_data *ud = unit_bl2ud(bl);
  782. if(ud == nullptr)
  783. return 0;
  784. if (!status_bl_has_mode(bl,MD_CANMOVE))
  785. return 0;
  786. if (!unit_can_reach_bl(bl, tbl, distance_bl(bl, tbl)+1, flag&1, &ud->to_x, &ud->to_y)) {
  787. ud->to_x = bl->x;
  788. ud->to_y = bl->y;
  789. ud->target_to = 0;
  790. return 0;
  791. } else if (range == 0) {
  792. //Should walk on the same cell as target (for looters)
  793. ud->to_x = tbl->x;
  794. ud->to_y = tbl->y;
  795. //Because of the change of target position the easy walkpath could fail
  796. //Note: Easy walking is no longer used by default, but we keep this to prevent endless loops [Playtester]
  797. flag &= ~1;
  798. }
  799. ud->state.walk_easy = flag&1;
  800. ud->target_to = tbl->id;
  801. ud->chaserange = range; // Note that if flag&2, this SHOULD be attack-range
  802. ud->state.attack_continue = flag&2?1:0; // Chase to attack.
  803. unit_stop_attack(bl); //Sets target to 0
  804. status_change *sc = status_get_sc(bl);
  805. if (sc && sc->getSCE(SC_CONFUSION)) // Randomize the target position
  806. map_random_dir(bl, &ud->to_x, &ud->to_y);
  807. if(ud->walktimer != INVALID_TIMER) {
  808. ud->state.change_walk_target = 1;
  809. // New target, make sure a monster is still in chase state
  810. if (bl->type == BL_MOB && ud->state.attack_continue) {
  811. mob_data& md = reinterpret_cast<mob_data&>(*bl);
  812. mob_setstate(md, MSS_RUSH);
  813. }
  814. return 1;
  815. }
  816. if(DIFF_TICK(ud->canmove_tick, gettick()) > 0) { // Can't move, wait a bit before invoking the movement.
  817. add_timer(ud->canmove_tick+1, unit_walktobl_sub, bl->id, ud->target_to);
  818. return 1;
  819. }
  820. if(!unit_can_move(bl))
  821. return 0;
  822. if (unit_walktoxy_sub(bl))
  823. return 1;
  824. return 0;
  825. }
  826. /**
  827. * Called by unit_run when an object is hit.
  828. * @param sd Required only when using SC_WUGDASH
  829. */
  830. void unit_run_hit(struct block_list *bl, status_change *sc, map_session_data *sd, enum sc_type type)
  831. {
  832. int32 lv = sc->getSCE(type)->val1;
  833. // If you can't run forward, you must be next to a wall, so bounce back. [Skotlex]
  834. if (type == SC_RUN)
  835. clif_status_change(bl, EFST_TING, 1, 0, 0, 0, 0);
  836. // Set running to 0 beforehand so status_change_end knows not to enable spurt [Kevin]
  837. unit_bl2ud(bl)->state.running = 0;
  838. status_change_end(bl, type);
  839. if (type == SC_RUN) {
  840. skill_blown(bl, bl, skill_get_blewcount(TK_RUN, lv), unit_getdir(bl), BLOWN_NONE);
  841. clif_status_change(bl, EFST_TING, 0, 0, 0, 0, 0);
  842. } else if (sd) {
  843. clif_fixpos( *bl );
  844. skill_castend_damage_id(bl, &sd->bl, RA_WUGDASH, lv, gettick(), SD_LEVEL);
  845. }
  846. return;
  847. }
  848. /**
  849. * Set a unit to run, checking for obstacles
  850. * @param bl: Object that is running
  851. * @param sd: Required only when using SC_WUGDASH
  852. * @return true: Success (Finished running) false: Fail (Hit an object/Couldn't run)
  853. */
  854. bool unit_run(struct block_list *bl, map_session_data *sd, enum sc_type type)
  855. {
  856. status_change *sc;
  857. int16 to_x, to_y, dir_x, dir_y;
  858. int32 i;
  859. nullpo_retr(false, bl);
  860. sc = status_get_sc(bl);
  861. if (!(sc && sc->getSCE(type)))
  862. return false;
  863. if (!unit_can_move(bl)) {
  864. status_change_end(bl, type);
  865. return false;
  866. }
  867. dir_x = dirx[sc->getSCE(type)->val2];
  868. dir_y = diry[sc->getSCE(type)->val2];
  869. // Determine destination cell
  870. to_x = bl->x;
  871. to_y = bl->y;
  872. // Search for available path
  873. for(i = 0; i < AREA_SIZE; i++) {
  874. if(!map_getcell(bl->m, to_x + dir_x, to_y + dir_y, CELL_CHKPASS))
  875. break;
  876. // If sprinting and there's a PC/Mob/NPC, block the path [Kevin]
  877. if(map_count_oncell(bl->m, to_x + dir_x, to_y + dir_y, BL_PC|BL_MOB|BL_NPC, 0))
  878. break;
  879. to_x += dir_x;
  880. to_y += dir_y;
  881. }
  882. // Can't run forward.
  883. if( (to_x == bl->x && to_y == bl->y) || (to_x == (bl->x + 1) || to_y == (bl->y + 1)) || (to_x == (bl->x - 1) || to_y == (bl->y - 1))) {
  884. unit_run_hit(bl, sc, sd, type);
  885. return false;
  886. }
  887. if (unit_walktoxy(bl, to_x, to_y, 1))
  888. return true;
  889. // There must be an obstacle nearby. Attempt walking one cell at a time.
  890. do {
  891. to_x -= dir_x;
  892. to_y -= dir_y;
  893. } while (--i > 0 && !unit_walktoxy(bl, to_x, to_y, 1));
  894. if (i == 0) {
  895. unit_run_hit(bl, sc, sd, type);
  896. return false;
  897. }
  898. return true;
  899. }
  900. /**
  901. * Returns duration of an object's current walkpath
  902. * @param bl: Object that is moving
  903. * @return Duration of the walkpath
  904. */
  905. t_tick unit_get_walkpath_time(struct block_list& bl)
  906. {
  907. t_tick time = 0;
  908. uint16 speed = status_get_speed(&bl);
  909. struct unit_data* ud = unit_bl2ud(&bl);
  910. // The next walk start time is calculated.
  911. for (uint8 i = 0; i < ud->walkpath.path_len; i++) {
  912. if (direction_diagonal(ud->walkpath.path[i]))
  913. time += speed * MOVE_DIAGONAL_COST / MOVE_COST;
  914. else
  915. time += speed;
  916. }
  917. return time;
  918. }
  919. /**
  920. * Makes unit attempt to run away from target in a straight line or using hard paths
  921. * @param bl: Object that is running away from target
  922. * @param target: Target
  923. * @param dist: How far bl should run
  924. * @param flag: unit_walktoxy flag (&1 = straight line escape)
  925. * @return The duration the unit will run (0 on fail)
  926. */
  927. t_tick unit_escape(struct block_list *bl, struct block_list *target, int16 dist, uint8 flag)
  928. {
  929. uint8 dir = map_calc_dir(target, bl->x, bl->y);
  930. if (flag&1) {
  931. // Straight line escape
  932. // Keep moving until we hit an unreachable cell
  933. for (int16 i = 1; i <= dist; i++) {
  934. if (map_getcell(bl->m, bl->x + i*dirx[dir], bl->y + i*diry[dir], CELL_CHKNOREACH))
  935. dist = i - 1;
  936. }
  937. } else {
  938. // Find the furthest reachable cell (then find a walkpath to it)
  939. while( dist > 0 && map_getcell(bl->m, bl->x + dist*dirx[dir], bl->y + dist*diry[dir], CELL_CHKNOREACH) )
  940. dist--;
  941. }
  942. if (dist > 0 && unit_walktoxy(bl, bl->x + dist * dirx[dir], bl->y + dist * diry[dir], flag))
  943. return unit_get_walkpath_time(*bl);
  944. return 0;
  945. }
  946. /**
  947. * Instant warps a unit to x,y coordinate
  948. * @param bl: Object to instant warp
  949. * @param dst_x: X coordinate to warp to
  950. * @param dst_y: Y coordinate to warp to
  951. * @param easy:
  952. * 0: Hard path check (attempt to go around obstacle)
  953. * 1: Easy path check (no obstacle on movement path)
  954. * 2: Long path check (no obstacle on line from start to destination)
  955. * @param checkpath: Whether or not to do a cell and path check for NOPASS and NOREACH
  956. * @return True: Success False: Fail
  957. */
  958. bool unit_movepos(struct block_list *bl, int16 dst_x, int16 dst_y, int32 easy, bool checkpath)
  959. {
  960. int16 dx,dy;
  961. struct unit_data *ud = nullptr;
  962. map_session_data *sd = nullptr;
  963. nullpo_retr(false,bl);
  964. sd = BL_CAST(BL_PC, bl);
  965. ud = unit_bl2ud(bl);
  966. if(ud == nullptr)
  967. return false;
  968. unit_stop_walking( bl, USW_FIXPOS );
  969. unit_stop_attack(bl);
  970. if( checkpath && (map_getcell(bl->m,dst_x,dst_y,CELL_CHKNOPASS) || !path_search(nullptr,bl->m,bl->x,bl->y,dst_x,dst_y,easy,CELL_CHKNOREACH)) )
  971. return false; // Unreachable
  972. ud->to_x = dst_x;
  973. ud->to_y = dst_y;
  974. unit_setdir(bl, map_calc_dir(bl, dst_x, dst_y), false);
  975. dx = dst_x - bl->x;
  976. dy = dst_y - bl->y;
  977. map_foreachinmovearea(clif_outsight, bl, AREA_SIZE, dx, dy, (sd ? BL_ALL : BL_PC), bl);
  978. map_moveblock(bl, dst_x, dst_y, gettick());
  979. ud->walktimer = CLIF_WALK_TIMER; // Arbitrary non-INVALID_TIMER value to make the clif code send walking packets
  980. map_foreachinmovearea(clif_insight, bl, AREA_SIZE, -dx, -dy, (sd ? BL_ALL : BL_PC), bl);
  981. ud->walktimer = INVALID_TIMER;
  982. if(sd) {
  983. if( !sd->npc_ontouch_.empty() )
  984. npc_touchnext_areanpc(sd,false);
  985. if(map_getcell(bl->m,bl->x,bl->y,CELL_CHKNPC)) {
  986. npc_touch_area_allnpc(sd, bl->m, bl->x, bl->y);
  987. if (bl->prev == nullptr) // Script could have warped char, abort remaining of the function.
  988. return false;
  989. } else
  990. sd->areanpc.clear();
  991. if( sd->status.pet_id > 0 && sd->pd && sd->pd->pet.intimate > PET_INTIMATE_NONE ) {
  992. // Check if pet needs to be teleported. [Skotlex]
  993. int32 flag = 0;
  994. struct block_list* pbl = &sd->pd->bl;
  995. if( !checkpath && !path_search(nullptr,pbl->m,pbl->x,pbl->y,dst_x,dst_y,0,CELL_CHKNOPASS) )
  996. flag = 1;
  997. else if (!check_distance_bl(&sd->bl, pbl, AREA_SIZE)) // Too far, teleport.
  998. flag = 2;
  999. if( flag ) {
  1000. unit_movepos(pbl,sd->bl.x,sd->bl.y, 0, 0);
  1001. clif_slide(*pbl,pbl->x,pbl->y);
  1002. }
  1003. }
  1004. }
  1005. return true;
  1006. }
  1007. /**
  1008. * Sets direction of a unit
  1009. * @param bl: Object to set direction
  1010. * @param dir: Direction (0-7)
  1011. * @param send_update: Update the client area of direction (default: true)
  1012. * @return True on success or False on failure
  1013. */
  1014. bool unit_setdir(block_list *bl, uint8 dir, bool send_update)
  1015. {
  1016. nullpo_ret(bl);
  1017. unit_data *ud = unit_bl2ud(bl);
  1018. if (ud == nullptr)
  1019. return false;
  1020. ud->dir = dir;
  1021. if (bl->type == BL_PC) {
  1022. map_session_data *sd = BL_CAST(BL_PC, bl);
  1023. sd->head_dir = DIR_NORTH;
  1024. sd->status.body_direction = ud->dir;
  1025. }
  1026. if (send_update)
  1027. clif_changed_dir(*bl, AREA);
  1028. return true;
  1029. }
  1030. /**
  1031. * Gets direction of a unit
  1032. * @param bl: Object to get direction
  1033. * @return direction (0-7)
  1034. */
  1035. uint8 unit_getdir(struct block_list *bl)
  1036. {
  1037. struct unit_data *ud;
  1038. nullpo_ret(bl);
  1039. ud = unit_bl2ud(bl);
  1040. if (!ud)
  1041. return 0;
  1042. return ud->dir;
  1043. }
  1044. /**
  1045. * Pushes a unit in a direction by a given amount of cells
  1046. * There is no path check, only map cell restrictions are respected
  1047. * @param bl: Object to push
  1048. * @param dx: Destination cell X
  1049. * @param dy: Destination cell Y
  1050. * @param count: How many cells to push bl
  1051. * @param flag: See skill.hpp::e_skill_blown
  1052. * @return count (can be modified due to map cell restrictions)
  1053. */
  1054. int32 unit_blown(struct block_list* bl, int32 dx, int32 dy, int32 count, enum e_skill_blown flag)
  1055. {
  1056. if(count) {
  1057. map_session_data* sd;
  1058. struct skill_unit* su = nullptr;
  1059. int32 nx, ny, result;
  1060. sd = BL_CAST(BL_PC, bl);
  1061. su = BL_CAST(BL_SKILL, bl);
  1062. result = path_blownpos(bl->m, bl->x, bl->y, dx, dy, count);
  1063. nx = result>>16;
  1064. ny = result&0xffff;
  1065. if(!su)
  1066. unit_stop_walking( bl, USW_NONE );
  1067. if( sd ) {
  1068. unit_stop_stepaction(bl); //Stop stepaction when knocked back
  1069. sd->ud.to_x = nx;
  1070. sd->ud.to_y = ny;
  1071. }
  1072. dx = nx-bl->x;
  1073. dy = ny-bl->y;
  1074. if(dx || dy) {
  1075. map_foreachinmovearea(clif_outsight, bl, AREA_SIZE, dx, dy, bl->type == BL_PC ? BL_ALL : BL_PC, bl);
  1076. if(su) {
  1077. if (su->group && skill_get_unit_flag(su->group->skill_id, UF_KNOCKBACKGROUP))
  1078. skill_unit_move_unit_group(su->group, bl->m, dx, dy);
  1079. else
  1080. skill_unit_move_unit(bl, nx, ny);
  1081. } else
  1082. map_moveblock(bl, nx, ny, gettick());
  1083. map_foreachinmovearea(clif_insight, bl, AREA_SIZE, -dx, -dy, bl->type == BL_PC ? BL_ALL : BL_PC, bl);
  1084. if(!(flag&BLOWN_DONT_SEND_PACKET))
  1085. clif_blown(bl);
  1086. if(sd) {
  1087. if(!sd->npc_ontouch_.empty())
  1088. npc_touchnext_areanpc(sd, false);
  1089. if(map_getcell(bl->m, bl->x, bl->y, CELL_CHKNPC))
  1090. npc_touch_area_allnpc(sd, bl->m, bl->x, bl->y);
  1091. else
  1092. sd->areanpc.clear();
  1093. }
  1094. }
  1095. count = distance(dx, dy);
  1096. }
  1097. return count; // Return amount of knocked back cells
  1098. }
  1099. /**
  1100. * Checks if unit can be knocked back / stopped by skills.
  1101. * @param bl: Object to check
  1102. * @param flag
  1103. * 0x1 - Offensive (not set: self skill, e.g. Backslide)
  1104. * 0x2 - Knockback type (not set: Stop type, e.g. Ankle Snare)
  1105. * 0x4 - Boss attack
  1106. * 0x8 - Ignore target player 'special_state.no_knockback'
  1107. * @return reason for immunity
  1108. * UB_KNOCKABLE - can be knocked back / stopped
  1109. * UB_NO_KNOCKBACK_MAP - at WOE/BG map
  1110. * UB_MD_KNOCKBACK_IMMUNE - target is MD_KNOCKBACK_IMMUNE
  1111. * UB_TARGET_BASILICA - target is in Basilica area (Pre-Renewal)
  1112. * UB_TARGET_NO_KNOCKBACK - target has 'special_state.no_knockback'
  1113. * UB_TARGET_TRAP - target is trap that cannot be knocked back
  1114. */
  1115. enum e_unit_blown unit_blown_immune(struct block_list* bl, uint8 flag)
  1116. {
  1117. if ((flag&0x1)
  1118. && (map_flag_gvg2(bl->m) || map_getmapflag(bl->m, MF_BATTLEGROUND))
  1119. && ((flag&0x2) || !(battle_config.skill_trap_type&0x1)))
  1120. return UB_NO_KNOCKBACK_MAP; // No knocking back in WoE / BG
  1121. switch (bl->type) {
  1122. case BL_MOB:
  1123. // Immune can't be knocked back
  1124. if (((flag&0x1) && status_bl_has_mode(bl,MD_KNOCKBACKIMMUNE))
  1125. && ((flag&0x2) || !(battle_config.skill_trap_type&0x2)))
  1126. return UB_MD_KNOCKBACK_IMMUNE;
  1127. break;
  1128. case BL_PC: {
  1129. map_session_data *sd = BL_CAST(BL_PC, bl);
  1130. #ifndef RENEWAL
  1131. // Basilica caster can't be knocked-back by normal monsters.
  1132. if( !(flag&0x4) && sd->sc.getSCE(SC_BASILICA) && sd->sc.getSCE(SC_BASILICA)->val4 == sd->bl.id)
  1133. return UB_TARGET_BASILICA;
  1134. #endif
  1135. // Target has special_state.no_knockback (equip)
  1136. if( (flag&(0x1|0x2)) && !(flag&0x8) && sd->special_state.no_knockback )
  1137. return UB_TARGET_NO_KNOCKBACK;
  1138. }
  1139. break;
  1140. case BL_SKILL: {
  1141. struct skill_unit* su = (struct skill_unit *)bl;
  1142. // Trap cannot be knocked back
  1143. if (su && su->group && skill_get_unit_flag(su->group->skill_id, UF_NOKNOCKBACK))
  1144. return UB_TARGET_TRAP;
  1145. }
  1146. break;
  1147. }
  1148. //Object can be knocked back / stopped
  1149. return UB_KNOCKABLE;
  1150. }
  1151. /**
  1152. * Warps a unit to a map/position
  1153. * pc_setpos is used for player warping
  1154. * This function checks for "no warp" map flags, so it's safe to call without doing nowarpto/nowarp checks
  1155. * @param bl: Object to warp
  1156. * @param m: Map ID from bl structure (NOT index)
  1157. * @param x: Destination cell X
  1158. * @param y: Destination cell Y
  1159. * @param type: Clear type used in clif_clearunit_area()
  1160. * @return Success(0); Failed(1); Error(2); unit_remove_map() Failed(3); map_addblock Failed(4)
  1161. */
  1162. int32 unit_warp(struct block_list *bl,int16 m,int16 x,int16 y,clr_type type)
  1163. {
  1164. struct unit_data *ud;
  1165. nullpo_ret(bl);
  1166. ud = unit_bl2ud(bl);
  1167. if(bl->prev==nullptr || !ud)
  1168. return 1;
  1169. if (type == CLR_DEAD)
  1170. // Type 1 is invalid, since you shouldn't warp a bl with the "death"
  1171. // animation, it messes up with unit_remove_map! [Skotlex]
  1172. return 1;
  1173. if( m < 0 )
  1174. m = bl->m;
  1175. switch (bl->type) {
  1176. case BL_MOB:
  1177. if (map_getmapflag(bl->m, MF_MONSTER_NOTELEPORT) && ((TBL_MOB*)bl)->master_id == 0)
  1178. return 1;
  1179. if (m != bl->m && map_getmapflag(m, MF_NOBRANCH) && battle_config.mob_warp&4 && !(((TBL_MOB *)bl)->master_id))
  1180. return 1;
  1181. break;
  1182. case BL_PC:
  1183. if (map_getmapflag(bl->m, MF_NOTELEPORT))
  1184. return 1;
  1185. break;
  1186. }
  1187. if (x < 0 || y < 0) { // Random map position.
  1188. if (!map_search_freecell(nullptr, m, &x, &y, -1, -1, 1)) {
  1189. ShowWarning("unit_warp failed. Unit Id:%d/Type:%d, target position map %d (%s) at [%d,%d]\n", bl->id, bl->type, m, map[m].name, x, y);
  1190. return 2;
  1191. }
  1192. } else if ( bl->type != BL_NPC && map_getcell(m,x,y,CELL_CHKNOREACH)) { // Invalid target cell
  1193. ShowWarning("unit_warp: Specified non-walkable target cell: %d (%s) at [%d,%d]\n", m, map[m].name, x,y);
  1194. if (!map_search_freecell(nullptr, m, &x, &y, 4, 4, 1)) { // Can't find a nearby cell
  1195. ShowWarning("unit_warp failed. Unit Id:%d/Type:%d, target position map %d (%s) at [%d,%d]\n", bl->id, bl->type, m, map[m].name, x, y);
  1196. return 2;
  1197. }
  1198. }
  1199. if (bl->type == BL_PC) // Use pc_setpos
  1200. return pc_setpos((TBL_PC*)bl, map_id2index(m), x, y, type);
  1201. if (!unit_remove_map(bl, type))
  1202. return 3;
  1203. if (bl->m != m && battle_config.clear_unit_onwarp &&
  1204. battle_config.clear_unit_onwarp&bl->type)
  1205. skill_clear_unitgroup(bl);
  1206. bl->x = ud->to_x = x;
  1207. bl->y = ud->to_y = y;
  1208. bl->m = m;
  1209. switch (bl->type) {
  1210. case BL_NPC:
  1211. {
  1212. TBL_NPC* nd = reinterpret_cast<npc_data*>(bl);
  1213. map_addnpc(m, nd);
  1214. npc_setcells(nd);
  1215. break;
  1216. }
  1217. case BL_MOB:
  1218. {
  1219. TBL_MOB* md = reinterpret_cast<mob_data*>(bl);
  1220. // If slaves are set to stick with their master they should drop target if recalled at range
  1221. if (battle_config.slave_stick_with_master && md->target_id != 0) {
  1222. block_list* tbl = map_id2bl(md->target_id);
  1223. if (tbl == nullptr || !check_distance_bl(bl, tbl, AREA_SIZE)) {
  1224. md->target_id = 0;
  1225. }
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. if(map_addblock(bl))
  1231. return 4; //error on adding bl to map
  1232. clif_spawn(bl);
  1233. skill_unit_move(bl,gettick(),1);
  1234. if (!battle_config.slave_stick_with_master && bl->type == BL_MOB && mob_countslave(bl) > 0)
  1235. mob_warpslave(bl,MOB_SLAVEDISTANCE);
  1236. return 0;
  1237. }
  1238. /**
  1239. * Calculates the exact coordinates of a bl considering the walktimer
  1240. * This is needed because we only update X/Y when finishing movement to the next cell
  1241. * Officially, however, the coordinates update when crossing the border to the next cell
  1242. * The coordinates are stored in unit_data.pos together with the tick based on which they were calculated
  1243. * Access to these coordinates is only allowed through corresponding unit_data class functions
  1244. * This function makes sure calculation only happens when it's needed to save performance
  1245. * @param tick: Tick based on which we calculate the coordinates
  1246. */
  1247. void unit_data::update_pos(t_tick tick)
  1248. {
  1249. // Check if coordinates are still up-to-date
  1250. if (DIFF_TICK(tick, this->pos.tick) < MIN_POS_INTERVAL)
  1251. return;
  1252. if (this->bl == nullptr)
  1253. return;
  1254. // Set initial coordinates
  1255. this->pos.x = this->bl->x;
  1256. this->pos.y = this->bl->y;
  1257. this->pos.sx = 8;
  1258. this->pos.sy = 8;
  1259. // Remember time at which we did the last calculation
  1260. this->pos.tick = tick;
  1261. if (this->walkpath.path_pos >= this->walkpath.path_len)
  1262. return;
  1263. if (this->walktimer == INVALID_TIMER)
  1264. return;
  1265. const TimerData* td = get_timer(this->walktimer);
  1266. if (td == nullptr)
  1267. return;
  1268. // Get how much percent we traversed on the timer
  1269. double cell_percent = 1.0 - ((double)DIFF_TICK(td->tick, tick) / (double)td->data);
  1270. if (cell_percent > 0.0 && cell_percent < 1.0) {
  1271. // Set subcell coordinates according to timer
  1272. // This gives a value between 8 and 39
  1273. this->pos.sx = static_cast<uint8>(24.0 + dirx[this->walkpath.path[this->walkpath.path_pos]] * 16.0 * cell_percent);
  1274. this->pos.sy = static_cast<uint8>(24.0 + diry[this->walkpath.path[this->walkpath.path_pos]] * 16.0 * cell_percent);
  1275. // 16-31 reflect sub position 0-15 on the current cell
  1276. // 8-15 reflect sub position 8-15 at -1 main coordinate
  1277. // 32-39 reflect sub position 0-7 at +1 main coordinate
  1278. if (this->pos.sx < 16 || this->pos.sy < 16 || this->pos.sx > 31 || this->pos.sy > 31) {
  1279. if (this->pos.sx < 16) this->pos.x--;
  1280. if (this->pos.sy < 16) this->pos.y--;
  1281. if (this->pos.sx > 31) this->pos.x++;
  1282. if (this->pos.sy > 31) this->pos.y++;
  1283. }
  1284. this->pos.sx %= 16;
  1285. this->pos.sy %= 16;
  1286. }
  1287. else if (cell_percent >= 1.0) {
  1288. // Assume exactly one cell moved
  1289. this->pos.x += dirx[this->walkpath.path[this->walkpath.path_pos]];
  1290. this->pos.y += diry[this->walkpath.path[this->walkpath.path_pos]];
  1291. }
  1292. }
  1293. /**
  1294. * Helper function to get the exact X coordinate
  1295. * This ensures that the coordinate is calculated when needed
  1296. * @param tick: Tick based on which we calculate the coordinate
  1297. * @return The exact X coordinate
  1298. */
  1299. int16 unit_data::getx(t_tick tick) {
  1300. // Make sure exact coordinates are up-to-date
  1301. this->update_pos(tick);
  1302. return this->pos.x;
  1303. }
  1304. /**
  1305. * Helper function to get the exact Y coordinate
  1306. * This ensures that the coordinate is calculated when needed
  1307. * @param tick: Tick based on which we calculate the coordinate
  1308. * @return The exact Y coordinate
  1309. */
  1310. int16 unit_data::gety(t_tick tick) {
  1311. // Make sure exact coordinates are up-to-date
  1312. this->update_pos(tick);
  1313. return this->pos.y;
  1314. }
  1315. /**
  1316. * Helper function to get exact coordinates
  1317. * This ensures that the coordinates are calculated when needed
  1318. * @param x: Will be set to the exact X value of the bl
  1319. * @param y: Will be set to the exact Y value of the bl
  1320. * @param sx: Will be set to the exact subcell X value of the bl
  1321. * @param sy: Will be set to the exact subcell Y value of the bl
  1322. * @param tick: Tick based on which we calculate the coordinate
  1323. * @return The exact Y coordinate
  1324. */
  1325. void unit_data::getpos(int16 &x, int16 &y, uint8 &sx, uint8 &sy, t_tick tick) {
  1326. // Make sure exact coordinates are up-to-date
  1327. this->update_pos(tick);
  1328. x = this->pos.x;
  1329. y = this->pos.y;
  1330. sx = this->pos.sx;
  1331. sy = this->pos.sy;
  1332. }
  1333. /**
  1334. * Updates the walkpath of a unit to end after 0.5-1.5 cells moved
  1335. * Sends required packet for proper display on the client using subcoordinates
  1336. * @param bl: Object to stop walking
  1337. */
  1338. void unit_stop_walking_soon(struct block_list& bl, t_tick tick)
  1339. {
  1340. struct unit_data* ud = unit_bl2ud(&bl);
  1341. if (ud == nullptr)
  1342. return;
  1343. int16 ox = bl.x, oy = bl.y; // Remember original x and y coordinates
  1344. int16 path_remain = 1; // Remaining path to walk
  1345. bool shortened = false;
  1346. if (ud->walkpath.path_pos + 1 >= ud->walkpath.path_len) {
  1347. // Less than 1 cell left to walk so no need to shorten the path
  1348. // Since we don't need to resend the move packet, we don't need to calculate the exact coordinates
  1349. path_remain = ud->walkpath.path_len - ud->walkpath.path_pos;
  1350. }
  1351. else {
  1352. // Set coordinates to exact coordinates
  1353. ud->getpos(bl.x, bl.y, ud->sx, ud->sy, tick);
  1354. // If x or y already changed, we need to move one more cell
  1355. if (ox != bl.x || oy != bl.y)
  1356. path_remain = 2;
  1357. // Shorten walkpath
  1358. if (ud->walkpath.path_pos + path_remain < ud->walkpath.path_len) {
  1359. ud->walkpath.path_len = ud->walkpath.path_pos + path_remain;
  1360. shortened = true;
  1361. }
  1362. }
  1363. // Make sure to_x and to_y match the walk path even if not shortened in case they were modified
  1364. ud->to_x = ox;
  1365. ud->to_y = oy;
  1366. for (int32 i = 0; i < path_remain; i++) {
  1367. ud->to_x += dirx[ud->walkpath.path[ud->walkpath.path_pos + i]];
  1368. ud->to_y += diry[ud->walkpath.path[ud->walkpath.path_pos + i]];
  1369. }
  1370. // To prevent sending a pointless walk command
  1371. ud->state.change_walk_target = 0;
  1372. // Send movement packet with calculated coordinates and subcoordinates
  1373. // Only need to send if walkpath was shortened
  1374. if (shortened)
  1375. clif_move(*ud);
  1376. // Reset coordinates
  1377. bl.x = ox;
  1378. bl.y = oy;
  1379. ud->sx = 8;
  1380. ud->sy = 8;
  1381. }
  1382. /**
  1383. * Stops a unit from walking
  1384. * @param bl: Object to stop walking
  1385. * @param type: Options, see e_unit_stop_walking
  1386. * @return Success(true); Failed(false);
  1387. */
  1388. bool unit_stop_walking( block_list* bl, int32 type, t_tick canmove_delay ){
  1389. struct unit_data *ud;
  1390. const struct TimerData* td = nullptr;
  1391. t_tick tick;
  1392. if( bl == nullptr ){
  1393. return false;
  1394. }
  1395. ud = unit_bl2ud(bl);
  1396. if(!ud || (!(type&USW_FORCE_STOP) && ud->walktimer == INVALID_TIMER))
  1397. return false;
  1398. // NOTE: We are using timer data after deleting it because we know the
  1399. // delete_timer function does not mess with it. If the function's
  1400. // behaviour changes in the future, this code could break!
  1401. if (ud->walktimer != INVALID_TIMER) {
  1402. td = get_timer(ud->walktimer);
  1403. delete_timer(ud->walktimer, unit_walktoxy_timer);
  1404. ud->walktimer = INVALID_TIMER;
  1405. }
  1406. ud->state.change_walk_target = 0;
  1407. tick = gettick();
  1408. if( (type&USW_MOVE_ONCE && !ud->walkpath.path_pos) // Force moving at least one cell.
  1409. || (type&USW_MOVE_FULL_CELL && td && DIFF_TICK(td->tick, tick) <= td->data/2) // Enough time has passed to cover half-cell
  1410. ) {
  1411. ud->walkpath.path_len = ud->walkpath.path_pos+1;
  1412. unit_walktoxy_timer(INVALID_TIMER, tick, bl->id, ud->walkpath.path_pos);
  1413. }
  1414. if (type&USW_FIXPOS) {
  1415. // Stop on cell center
  1416. ud->sx = 8;
  1417. ud->sy = 8;
  1418. clif_fixpos(*bl);
  1419. }
  1420. ud->walkpath.path_len = 0;
  1421. ud->walkpath.path_pos = 0;
  1422. ud->to_x = bl->x;
  1423. ud->to_y = bl->y;
  1424. if (type&USW_RELEASE_TARGET)
  1425. ud->target_to = 0;
  1426. if( canmove_delay > 0 ){
  1427. ud->canmove_tick = gettick() + canmove_delay;
  1428. }
  1429. // Re-added, the check in unit_set_walkdelay means dmg during running won't fall through to this place in code [Kevin]
  1430. if (ud->state.running) {
  1431. status_change_end(bl, SC_RUN);
  1432. status_change_end(bl, SC_WUGDASH);
  1433. }
  1434. return true;
  1435. }
  1436. /**
  1437. * Initiates a skill use by a unit
  1438. * @param src: Source object initiating skill use
  1439. * @param target_id: Target ID (bl->id)
  1440. * @param skill_id: Skill ID
  1441. * @param skill_lv: Skill Level
  1442. * @return unit_skilluse_id2()
  1443. */
  1444. int32 unit_skilluse_id(struct block_list *src, int32 target_id, uint16 skill_id, uint16 skill_lv)
  1445. {
  1446. return unit_skilluse_id2(
  1447. src, target_id, skill_id, skill_lv,
  1448. skill_castfix(src, skill_id, skill_lv),
  1449. skill_get_castcancel(skill_id)
  1450. );
  1451. }
  1452. /**
  1453. * Checks if a unit is walking
  1454. * @param bl: Object to check walk status
  1455. * @return Walking(1); Not Walking(0)
  1456. */
  1457. int32 unit_is_walking(struct block_list *bl)
  1458. {
  1459. struct unit_data *ud = unit_bl2ud(bl);
  1460. nullpo_ret(bl);
  1461. if(!ud)
  1462. return 0;
  1463. return (ud->walktimer != INVALID_TIMER);
  1464. }
  1465. /**
  1466. * Checks if a unit is able to move based on status changes
  1467. * View the StatusChangeStateTable in status.cpp for a list of statuses
  1468. * Some statuses are still checked here due too specific variables
  1469. * @author [Skotlex]
  1470. * @param bl: Object to check
  1471. * @return True - can move; False - can't move
  1472. */
  1473. bool unit_can_move(struct block_list *bl) {
  1474. map_session_data *sd;
  1475. struct unit_data *ud;
  1476. status_change *sc;
  1477. nullpo_ret(bl);
  1478. ud = unit_bl2ud(bl);
  1479. sc = status_get_sc(bl);
  1480. sd = BL_CAST(BL_PC, bl);
  1481. if (!ud)
  1482. return false;
  1483. if (ud->skilltimer != INVALID_TIMER && ud->skill_id != LG_EXEEDBREAK && (!sd || !pc_checkskill(sd, SA_FREECAST) || skill_get_inf2(ud->skill_id, INF2_ISGUILD)))
  1484. return false; // Prevent moving while casting
  1485. if (DIFF_TICK(ud->canmove_tick, gettick()) > 0)
  1486. return false;
  1487. if ((sd && (pc_issit(sd) || sd->state.vending || sd->state.buyingstore || (sd->state.block_action & PCBLOCK_MOVE) || sd->state.mail_writing)) || ud->state.blockedmove)
  1488. return false; // Can't move
  1489. // Status changes that block movement
  1490. if (sc && sc->cant.move)
  1491. return false;
  1492. // Icewall walk block special trapped monster mode
  1493. if(bl->type == BL_MOB) {
  1494. struct mob_data *md = BL_CAST(BL_MOB, bl);
  1495. if(md && ((status_has_mode(&md->status,MD_STATUSIMMUNE) && battle_config.boss_icewall_walk_block == 1 && map_getcell(bl->m,bl->x,bl->y,CELL_CHKICEWALL))
  1496. || (!status_has_mode(&md->status,MD_STATUSIMMUNE) && battle_config.mob_icewall_walk_block == 1 && map_getcell(bl->m,bl->x,bl->y,CELL_CHKICEWALL)))) {
  1497. md->walktoxy_fail_count = 1; //Make sure rudeattacked skills are invoked
  1498. return false;
  1499. }
  1500. }
  1501. return true;
  1502. }
  1503. /**
  1504. * Resumes running (RA_WUGDASH or TK_RUN) after a walk delay
  1505. * @param tid: Timer ID
  1506. * @param id: Object ID
  1507. * @param data: Data passed through timer function (unit_data)
  1508. * @return 0
  1509. */
  1510. TIMER_FUNC(unit_resume_running){
  1511. struct unit_data *ud = (struct unit_data *)data;
  1512. TBL_PC *sd = map_id2sd(id);
  1513. if (sd && pc_isridingwug(sd))
  1514. clif_skill_nodamage(ud->bl,*ud->bl,RA_WUGDASH,ud->skill_lv,sc_start4(ud->bl,ud->bl,SC_WUGDASH,100,ud->skill_lv,unit_getdir(ud->bl),0,0,0));
  1515. else
  1516. clif_skill_nodamage(ud->bl,*ud->bl,TK_RUN,ud->skill_lv,sc_start4(ud->bl,ud->bl,SC_RUN,100,ud->skill_lv,unit_getdir(ud->bl),0,0,0));
  1517. if (sd)
  1518. clif_walkok(*sd);
  1519. return 0;
  1520. }
  1521. /**
  1522. * Sets the delays that prevent attacks and skill usage considering the bl type
  1523. * TODO: Currently this function is only called for normal attacks and parry events and is a work-in-progress
  1524. * @param bl Object to apply attack delay to
  1525. * @param tick Current tick
  1526. * @param event The event that resulted in calling this function
  1527. */
  1528. void unit_set_attackdelay(block_list& bl, t_tick tick, e_delay_event event)
  1529. {
  1530. unit_data* ud = unit_bl2ud(&bl);
  1531. if (ud == nullptr)
  1532. return;
  1533. switch (bl.type) {
  1534. case BL_PC:
  1535. switch (event) {
  1536. case DELAY_EVENT_ATTACK:
  1537. case DELAY_EVENT_PARRY:
  1538. // TODO: This should also happen on cast begin
  1539. // Officially for players it just remembers the last attack time here and applies the delays during the comparison
  1540. // But we pre-calculate the delays instead and store them in attackabletime and canact_tick
  1541. ud->attackabletime = tick + status_get_adelay(&bl);
  1542. // A fixed delay is added here which is equal to the minimum attack motion you can get
  1543. // This ensures that at max ASPD attackabletime and canact_tick are equal
  1544. ud->canact_tick = tick + status_get_amotion(&bl) + (pc_maxaspd(reinterpret_cast<map_session_data*>(&bl)) / AMOTION_DIVIDER_PC);
  1545. break;
  1546. }
  1547. break;
  1548. default:
  1549. switch (event) {
  1550. case DELAY_EVENT_ATTACK:
  1551. // This represents setting of attack delay (recharge time) that happens for non-PCs
  1552. ud->attackabletime = tick + status_get_adelay(&bl);
  1553. break;
  1554. }
  1555. break;
  1556. }
  1557. }
  1558. /**
  1559. * Applies a walk delay to a unit
  1560. * @param bl: Object to apply walk delay to
  1561. * @param tick: Current tick
  1562. * @param delay: Amount of time to set walk delay
  1563. * @param type: Type of delay
  1564. * 0: Damage induced delay; Do not change previous delay
  1565. * 1: Skill induced delay; Walk delay can only be increased, not decreased
  1566. * @return Success(1); Fail(0);
  1567. */
  1568. int32 unit_set_walkdelay(struct block_list *bl, t_tick tick, t_tick delay, int32 type)
  1569. {
  1570. struct unit_data *ud = unit_bl2ud(bl);
  1571. if (delay <= 0 || !ud)
  1572. return 0;
  1573. if (type) {
  1574. //Bosses can ignore skill induced walkdelay (but not damage induced)
  1575. if(bl->type == BL_MOB && status_has_mode(status_get_status_data(*bl),MD_STATUSIMMUNE))
  1576. return 0;
  1577. //Make sure walk delay is not decreased
  1578. if (DIFF_TICK(ud->canmove_tick, tick+delay) > 0)
  1579. return 0;
  1580. } else {
  1581. if (bl->type == BL_MOB) {
  1582. mob_data& md = *reinterpret_cast<mob_data*>(bl);
  1583. // Mob needs to escape, don't stop it
  1584. if (md.state.can_escape == 1)
  1585. return 0;
  1586. }
  1587. // Don't set walk delays when already trapped.
  1588. if (!unit_can_move(bl)) {
  1589. // Unit might still be moving even though it can't move
  1590. unit_stop_walking( bl, USW_MOVE_FULL_CELL );
  1591. return 0;
  1592. }
  1593. //Immune to being stopped for double the flinch time
  1594. if (DIFF_TICK(ud->canmove_tick, tick-delay) > 0)
  1595. return 0;
  1596. }
  1597. ud->canmove_tick = tick + delay;
  1598. if (ud->walktimer != INVALID_TIMER) { // Stop walking, if chasing, readjust timers.
  1599. if (delay == 1) // Minimal delay (walk-delay) disabled. Just stop walking.
  1600. unit_stop_walking( bl, USW_NONE );
  1601. else {
  1602. // Resume running after can move again [Kevin]
  1603. if(ud->state.running)
  1604. add_timer(ud->canmove_tick, unit_resume_running, bl->id, (intptr_t)ud);
  1605. else {
  1606. unit_stop_walking( bl, USW_MOVE_FULL_CELL );
  1607. if(ud->target_to != 0)
  1608. add_timer(ud->canmove_tick+1, unit_walktobl_sub, bl->id, ud->target_to);
  1609. }
  1610. }
  1611. }
  1612. return 1;
  1613. }
  1614. /**
  1615. * Performs checks for a unit using a skill and executes after cast time completion
  1616. * @param src: Object using skill
  1617. * @param target_id: Target ID (bl->id)
  1618. * @param skill_id: Skill ID
  1619. * @param skill_lv: Skill Level
  1620. * @param casttime: Initial cast time before cast time reductions
  1621. * @param castcancel: Whether or not the skill can be cancelled by interruption (hit)
  1622. * @return Success(1); Fail(0);
  1623. */
  1624. int32 unit_skilluse_id2(struct block_list *src, int32 target_id, uint16 skill_id, uint16 skill_lv, int32 casttime, int32 castcancel, bool ignore_range)
  1625. {
  1626. struct unit_data *ud;
  1627. status_change *sc;
  1628. map_session_data *sd = nullptr;
  1629. struct block_list * target = nullptr;
  1630. t_tick tick = gettick();
  1631. int32 combo = 0, range;
  1632. nullpo_ret(src);
  1633. if(status_isdead(*src))
  1634. return 0; // Do not continue source is dead
  1635. sd = BL_CAST(BL_PC, src);
  1636. ud = unit_bl2ud(src);
  1637. if(ud == nullptr)
  1638. return 0;
  1639. if (ud && ud->state.blockedskill)
  1640. return 0;
  1641. sc = status_get_sc(src);
  1642. if (sc != nullptr && sc->empty())
  1643. sc = nullptr; // Unneeded
  1644. int32 inf = skill_get_inf(skill_id);
  1645. std::shared_ptr<s_skill_db> skill = skill_db.find(skill_id);
  1646. if (!skill)
  1647. return 0;
  1648. // temp: used to signal combo-skills right now.
  1649. if (sc && sc->getSCE(SC_COMBO) &&
  1650. skill_is_combo(skill_id) &&
  1651. (sc->getSCE(SC_COMBO)->val1 == skill_id ||
  1652. (sd?skill_check_condition_castbegin(*sd,skill_id,skill_lv):0) )) {
  1653. if (skill_is_combo(skill_id) == 2 && target_id == src->id && ud->target > 0)
  1654. target_id = ud->target;
  1655. else if (sc->getSCE(SC_COMBO)->val2)
  1656. target_id = sc->getSCE(SC_COMBO)->val2;
  1657. else if (target_id == src->id || ud->target > 0)
  1658. target_id = ud->target;
  1659. if (inf&INF_SELF_SKILL && skill->nk[NK_NODAMAGE])// exploit fix
  1660. target_id = src->id;
  1661. combo = 1;
  1662. } else if (target_id == src->id && inf&INF_SELF_SKILL && skill->inf2[INF2_NOTARGETSELF]) {
  1663. target_id = ud->target; // Auto-select target. [Skotlex]
  1664. combo = 1;
  1665. }
  1666. if (sd) {
  1667. // Target_id checking.
  1668. if(skill_isNotOk(skill_id, *sd))
  1669. return 0;
  1670. switch(skill_id) { // Check for skills that auto-select target
  1671. case MO_CHAINCOMBO:
  1672. if (sc && sc->getSCE(SC_BLADESTOP)) {
  1673. if ((target=map_id2bl(sc->getSCE(SC_BLADESTOP)->val4)) == nullptr)
  1674. return 0;
  1675. }
  1676. break;
  1677. case GC_WEAPONCRUSH:
  1678. if (sc && sc->getSCE(SC_WEAPONBLOCK_ON)) {
  1679. if ((target = map_id2bl(sc->getSCE(SC_WEAPONBLOCK_ON)->val1)) == nullptr)
  1680. return 0;
  1681. combo = 1;
  1682. }
  1683. break;
  1684. case RL_QD_SHOT:
  1685. if (sc && sc->getSCE(SC_QD_SHOT_READY)) {
  1686. if ((target = map_id2bl(sc->getSCE(SC_QD_SHOT_READY)->val1)) == nullptr)
  1687. return 0;
  1688. combo = 1;
  1689. }
  1690. break;
  1691. case WE_MALE:
  1692. case WE_FEMALE:
  1693. if (!sd->status.partner_id)
  1694. return 0;
  1695. target = (struct block_list*)map_charid2sd(sd->status.partner_id);
  1696. if (!target) {
  1697. clif_skill_fail( *sd, skill_id );
  1698. return 0;
  1699. }
  1700. break;
  1701. }
  1702. if (target)
  1703. target_id = target->id;
  1704. } else if (src->type == BL_HOM) {
  1705. switch(skill_id) { // Homun-auto-target skills.
  1706. case HLIF_HEAL:
  1707. case HLIF_AVOID:
  1708. case HAMI_DEFENCE:
  1709. case HAMI_CASTLE:
  1710. target = battle_get_master(src);
  1711. if (!target)
  1712. return 0;
  1713. target_id = target->id;
  1714. break;
  1715. case MH_SONIC_CRAW:
  1716. case MH_TINDER_BREAKER: {
  1717. int32 skill_id2 = ((skill_id==MH_SONIC_CRAW)?MH_MIDNIGHT_FRENZY:MH_EQC);
  1718. if(sc->getSCE(SC_COMBO) && sc->getSCE(SC_COMBO)->val1 == skill_id2) { // It's a combo
  1719. target_id = sc->getSCE(SC_COMBO)->val2;
  1720. combo = 1;
  1721. casttime = -1;
  1722. }
  1723. break;
  1724. }
  1725. }
  1726. }
  1727. if( !target ) // Choose default target
  1728. target = map_id2bl(target_id);
  1729. if( !target || src->m != target->m || !src->prev || !target->prev )
  1730. return 0;
  1731. if( battle_config.ksprotection && sd && mob_ksprotected(src, target) )
  1732. return 0;
  1733. // Normally not needed because clif.cpp checks for it, but the at/char/script commands don't! [Skotlex]
  1734. if(ud->skilltimer != INVALID_TIMER && skill_id != SA_CASTCANCEL && skill_id != SO_SPELLFIST)
  1735. return 0;
  1736. if(skill->inf2[INF2_NOTARGETSELF] && src->id == target_id)
  1737. return 0;
  1738. if(!status_check_skilluse(src, target, skill_id, 0))
  1739. return 0;
  1740. // Fail if the targetted skill is near NPC [Cydh]
  1741. if(skill->inf2[INF2_DISABLENEARNPC] && !ignore_range && skill_isNotOk_npcRange(src,skill_id,skill_lv,target->x,target->y)) {
  1742. if (sd)
  1743. clif_skill_fail( *sd, skill_id );
  1744. return 0;
  1745. }
  1746. status_data* tstatus = status_get_status_data(*target);
  1747. // Record the status of the previous skill)
  1748. if(sd) {
  1749. switch(skill_id) {
  1750. case SA_CASTCANCEL:
  1751. if(ud->skill_id != skill_id) {
  1752. sd->skill_id_old = ud->skill_id;
  1753. sd->skill_lv_old = ud->skill_lv;
  1754. }
  1755. break;
  1756. case BD_ENCORE:
  1757. // Prevent using the dance skill if you no longer have the skill in your tree.
  1758. if(!sd->skill_id_dance || pc_checkskill(sd,sd->skill_id_dance)<=0) {
  1759. clif_skill_fail( *sd, skill_id );
  1760. return 0;
  1761. }
  1762. sd->skill_id_old = skill_id;
  1763. break;
  1764. case WL_WHITEIMPRISON:
  1765. if( battle_check_target(src,target,BCT_SELF|BCT_ENEMY) < 0 ) {
  1766. clif_skill_fail( *sd, skill_id, USESKILL_FAIL_TOTARGET );
  1767. return 0;
  1768. }
  1769. break;
  1770. case MG_FIREBOLT:
  1771. case MG_LIGHTNINGBOLT:
  1772. case MG_COLDBOLT:
  1773. sd->skill_id_old = skill_id;
  1774. sd->skill_lv_old = skill_lv;
  1775. break;
  1776. case CR_DEVOTION:
  1777. if (target->type == BL_PC) {
  1778. uint8 i = 0, count = min(skill_lv, MAX_DEVOTION);
  1779. ARR_FIND(0, count, i, sd->devotion[i] == target_id);
  1780. if (i == count) {
  1781. ARR_FIND(0, count, i, sd->devotion[i] == 0);
  1782. if (i == count) { // No free slots, skill Fail
  1783. clif_skill_fail( *sd, skill_id );
  1784. return 0;
  1785. }
  1786. }
  1787. }
  1788. break;
  1789. case RL_C_MARKER: {
  1790. uint8 i = 0;
  1791. ARR_FIND(0, MAX_SKILL_CRIMSON_MARKER, i, sd->c_marker[i] == target_id);
  1792. if (i == MAX_SKILL_CRIMSON_MARKER) {
  1793. ARR_FIND(0, MAX_SKILL_CRIMSON_MARKER, i, sd->c_marker[i] == 0);
  1794. if (i == MAX_SKILL_CRIMSON_MARKER) { // No free slots, skill Fail
  1795. clif_skill_fail( *sd, skill_id );
  1796. return 0;
  1797. }
  1798. }
  1799. }
  1800. break;
  1801. case DK_SERVANT_W_SIGN: {
  1802. uint8 i = 0, count = min(skill_lv, MAX_SERVANT_SIGN);
  1803. ARR_FIND( 0, count, i, sd->servant_sign[i] == target_id );
  1804. // Already targetted
  1805. if( i < count ){
  1806. break;
  1807. }
  1808. ARR_FIND( 0, count, i, sd->servant_sign[i] == 0 );
  1809. // No free slots
  1810. if( i == count ){
  1811. clif_skill_fail( *sd, skill_id );
  1812. return 0;
  1813. }
  1814. }
  1815. break;
  1816. case TR_RETROSPECTION:
  1817. // Prevent using the song skill if you no longer have the skill in your tree.
  1818. if (!sd->skill_id_song || pc_checkskill(sd, sd->skill_id_song) <= 0) {
  1819. clif_skill_fail( *sd, skill_id );
  1820. return 0;
  1821. }
  1822. sd->skill_id_old = skill_id;
  1823. break;
  1824. }
  1825. if (!skill_check_condition_castbegin(*sd, skill_id, skill_lv))
  1826. return 0;
  1827. }
  1828. if( src->type == BL_MOB ) {
  1829. switch( skill_id ) {
  1830. case NPC_SUMMONSLAVE:
  1831. case NPC_SUMMONMONSTER:
  1832. case NPC_DEATHSUMMON:
  1833. case AL_TELEPORT:
  1834. if( ((TBL_MOB*)src)->master_id && ((TBL_MOB*)src)->special_state.ai )
  1835. return 0;
  1836. }
  1837. }
  1838. range = skill_get_range2(src, skill_id, skill_lv, true); // Skill cast distance from database
  1839. // New action request received, delete previous action request if not executed yet
  1840. if(ud->stepaction || ud->steptimer != INVALID_TIMER)
  1841. unit_stop_stepaction(src);
  1842. // Remember the skill request from the client while walking to the next cell
  1843. if(src->type == BL_PC && ud->walktimer != INVALID_TIMER && (!battle_check_range(src, target, range-1) || ignore_range)) {
  1844. ud->stepaction = true;
  1845. ud->target_to = target_id;
  1846. ud->stepskill_id = skill_id;
  1847. ud->stepskill_lv = skill_lv;
  1848. return 0; // Attacking will be handled by unit_walktoxy_timer in this case
  1849. }
  1850. // Check range when not using skill on yourself or is a combo-skill during attack
  1851. // (these are supposed to always have the same range as your attack)
  1852. if( src->type != BL_NPC && !ignore_range && src->id != target_id && (!combo || ud->attacktimer == INVALID_TIMER) ) {
  1853. if( skill_get_state(ud->skill_id) == ST_MOVE_ENABLE ) {
  1854. if( !unit_can_reach_bl(src, target, range + 1, 1, nullptr, nullptr) )
  1855. return 0; // Walk-path check failed.
  1856. } else if( src->type == BL_MER && skill_id == MA_REMOVETRAP ) {
  1857. if( !battle_check_range(battle_get_master(src), target, range + 1) )
  1858. return 0; // Aegis calc remove trap based on Master position, ignoring mercenary O.O
  1859. } else if( !battle_check_range(src, target, range) )
  1860. return 0; // Arrow-path check failed.
  1861. }
  1862. if (!combo) // Stop attack on non-combo skills [Skotlex]
  1863. unit_stop_attack(src);
  1864. else if(ud->attacktimer != INVALID_TIMER) // Elsewise, delay current attack sequence
  1865. ud->attackabletime = tick + status_get_adelay(src);
  1866. ud->state.skillcastcancel = castcancel;
  1867. // Combo: Used to signal force cast now.
  1868. combo = 0;
  1869. switch(skill_id) {
  1870. case ALL_RESURRECTION:
  1871. if(battle_check_undead(tstatus->race,tstatus->def_ele))
  1872. combo = 1;
  1873. else if (!status_isdead(*target))
  1874. return 0; // Can't cast on non-dead characters.
  1875. break;
  1876. #ifndef RENEWAL
  1877. case MO_FINGEROFFENSIVE:
  1878. if(sd)
  1879. casttime += casttime * min(skill_lv, sd->spiritball);
  1880. break;
  1881. #endif
  1882. case MO_EXTREMITYFIST:
  1883. if (sc && sc->getSCE(SC_COMBO) &&
  1884. (sc->getSCE(SC_COMBO)->val1 == MO_COMBOFINISH ||
  1885. sc->getSCE(SC_COMBO)->val1 == CH_TIGERFIST ||
  1886. sc->getSCE(SC_COMBO)->val1 == CH_CHAINCRUSH))
  1887. casttime = -1;
  1888. combo = 1;
  1889. break;
  1890. case SR_GATEOFHELL:
  1891. case SR_TIGERCANNON:
  1892. if (sc && sc->getSCE(SC_COMBO) &&
  1893. sc->getSCE(SC_COMBO)->val1 == SR_FALLENEMPIRE)
  1894. casttime = -1;
  1895. combo = 1;
  1896. break;
  1897. case SA_SPELLBREAKER:
  1898. combo = 1;
  1899. break;
  1900. #ifndef RENEWAL_CAST
  1901. case ST_CHASEWALK:
  1902. if (sc && sc->getSCE(SC_CHASEWALK))
  1903. casttime = -1;
  1904. break;
  1905. #endif
  1906. case TK_RUN:
  1907. if (sc && sc->getSCE(SC_RUN))
  1908. casttime = -1;
  1909. break;
  1910. #ifndef RENEWAL
  1911. case HP_BASILICA:
  1912. if( sc && sc->getSCE(SC_BASILICA) )
  1913. casttime = -1; // No Casting time on basilica cancel
  1914. break;
  1915. #endif
  1916. #ifndef RENEWAL_CAST
  1917. case KN_CHARGEATK:
  1918. {
  1919. uint32 k = (distance_bl(src,target)-1)/3; //Range 0-3: 500ms, Range 4-6: 1000ms, Range 7+: 1500ms
  1920. if(k > 2)
  1921. k = 2;
  1922. casttime += casttime * k;
  1923. }
  1924. break;
  1925. #endif
  1926. case GD_EMERGENCYCALL: // Emergency Call double cast when the user has learned Leap [Daegaladh]
  1927. if (sd && (pc_checkskill(sd,TK_HIGHJUMP) || pc_checkskill(sd,SU_LOPE) >= 3))
  1928. casttime *= 2;
  1929. break;
  1930. case RA_WUGDASH:
  1931. if (sc && sc->getSCE(SC_WUGDASH))
  1932. casttime = -1;
  1933. break;
  1934. case DK_SERVANT_W_PHANTOM: { // Stops servants from being consumed on unmarked targets.
  1935. status_change *tsc = status_get_sc(target);
  1936. // Only allow to attack if the enemy has a sign mark given by the caster.
  1937. if( tsc == nullptr || tsc->getSCE(SC_SERVANT_SIGN) == nullptr || tsc->getSCE(SC_SERVANT_SIGN)->val1 != src->id ){
  1938. if (sd)
  1939. clif_skill_fail( *sd, skill_id, USESKILL_FAIL );
  1940. return 0;
  1941. }
  1942. }
  1943. break;
  1944. case EL_WIND_SLASH:
  1945. case EL_HURRICANE:
  1946. case EL_TYPOON_MIS:
  1947. case EL_STONE_HAMMER:
  1948. case EL_ROCK_CRUSHER:
  1949. case EL_STONE_RAIN:
  1950. case EL_ICE_NEEDLE:
  1951. case EL_WATER_SCREW:
  1952. case EL_TIDAL_WEAPON:
  1953. if( src->type == BL_ELEM ) {
  1954. sd = BL_CAST(BL_PC, battle_get_master(src));
  1955. if( sd && sd->skill_id_old == SO_EL_ACTION ) {
  1956. casttime = -1;
  1957. sd->skill_id_old = 0;
  1958. }
  1959. }
  1960. break;
  1961. }
  1962. // Moved here to prevent Suffragium from ending if skill fails
  1963. #ifndef RENEWAL_CAST
  1964. casttime = skill_castfix_sc(src, casttime, skill_get_castnodex(skill_id));
  1965. #else
  1966. casttime = skill_vfcastfix(src, casttime, skill_id, skill_lv);
  1967. #endif
  1968. // Need TK_RUN or WUGDASH handler to be done before that, see bugreport:6026
  1969. if(!ud->state.running){
  1970. // Even though this is not how official works but this will do the trick. bugreport:6829
  1971. unit_stop_walking( src, USW_FIXPOS );
  1972. }
  1973. // SC_MAGICPOWER needs to switch states at start of cast
  1974. #ifndef RENEWAL
  1975. skill_toggle_magicpower(src, skill_id);
  1976. #endif
  1977. // In official this is triggered even if no cast time.
  1978. clif_skillcasting(src, src->id, target_id, 0,0, skill_id, skill_lv, skill_get_ele(skill_id, skill_lv), casttime);
  1979. if (sd && target->type == BL_MOB) {
  1980. TBL_MOB *md = (TBL_MOB*)target;
  1981. mobskill_event(md, src, tick, -1); // Cast targetted skill event.
  1982. if ((status_has_mode(tstatus,MD_CASTSENSORIDLE) || status_has_mode(tstatus,MD_CASTSENSORCHASE)) && battle_check_target(target, src, BCT_ENEMY) > 0 && !ignore_range) {
  1983. switch (md->state.skillstate) {
  1984. case MSS_RUSH:
  1985. case MSS_FOLLOW:
  1986. if (!status_has_mode(tstatus,MD_CASTSENSORCHASE))
  1987. break;
  1988. md->target_id = src->id;
  1989. md->state.aggressive = status_has_mode(tstatus,MD_ANGRY)?1:0;
  1990. break;
  1991. case MSS_IDLE:
  1992. case MSS_WALK:
  1993. if (!status_has_mode(tstatus,MD_CASTSENSORIDLE))
  1994. break;
  1995. md->target_id = src->id;
  1996. md->state.aggressive = status_has_mode(tstatus,MD_ANGRY)?1:0;
  1997. break;
  1998. }
  1999. }
  2000. }
  2001. if( casttime <= 0 )
  2002. ud->state.skillcastcancel = 0;
  2003. if (!sd || sd->skillitem != skill_id || skill_get_cast(skill_id, skill_lv))
  2004. ud->canact_tick = tick + i64max(casttime, max(status_get_amotion(src), battle_config.min_skill_delay_limit)) + SECURITY_CASTTIME;
  2005. if( sd ) {
  2006. switch( skill_id ) {
  2007. case CG_ARROWVULCAN:
  2008. sd->canequip_tick = tick + casttime;
  2009. break;
  2010. }
  2011. }
  2012. ud->skilltarget = target_id;
  2013. ud->skillx = 0;
  2014. ud->skilly = 0;
  2015. ud->skill_id = skill_id;
  2016. ud->skill_lv = skill_lv;
  2017. if( sc ) {
  2018. // These 3 status do not stack, so it's efficient to use if-else
  2019. if( sc->getSCE(SC_CLOAKING) && !(sc->getSCE(SC_CLOAKING)->val4&4) && skill_id != AS_CLOAKING && skill_id != SHC_SHADOW_STAB) {
  2020. status_change_end(src, SC_CLOAKING);
  2021. if (!src->prev)
  2022. return 0; // Warped away!
  2023. } else if( sc->getSCE(SC_CLOAKINGEXCEED) && !(sc->getSCE(SC_CLOAKINGEXCEED)->val4&4) && skill_id != GC_CLOAKINGEXCEED && skill_id != SHC_SHADOW_STAB && skill_id != SHC_SAVAGE_IMPACT ) {
  2024. status_change_end(src,SC_CLOAKINGEXCEED);
  2025. if (!src->prev)
  2026. return 0;
  2027. } else if (sc->getSCE(SC_NEWMOON) && skill_id != SJ_NEWMOONKICK) {
  2028. status_change_end(src, SC_NEWMOON);
  2029. if (!src->prev)
  2030. return 0; // Warped away!
  2031. }
  2032. }
  2033. if( casttime > 0 ) {
  2034. ud->skilltimer = add_timer( tick+casttime, skill_castend_id, src->id, 0 );
  2035. if( sd && (pc_checkskill(sd,SA_FREECAST) > 0 || skill_id == LG_EXEEDBREAK) )
  2036. status_calc_bl(&sd->bl, { SCB_SPEED, SCB_ASPD });
  2037. } else
  2038. skill_castend_id(ud->skilltimer,tick,src->id,0);
  2039. if( sd && battle_config.prevent_logout_trigger&PLT_SKILL )
  2040. sd->canlog_tick = gettick();
  2041. return 1;
  2042. }
  2043. /**
  2044. * Initiates a placement (ground/non-targeted) skill
  2045. * @param src: Object using skill
  2046. * @param skill_x: X coordinate where skill is being casted (center)
  2047. * @param skill_y: Y coordinate where skill is being casted (center)
  2048. * @param skill_id: Skill ID
  2049. * @param skill_lv: Skill Level
  2050. * @return unit_skilluse_pos2()
  2051. */
  2052. int32 unit_skilluse_pos(struct block_list *src, int16 skill_x, int16 skill_y, uint16 skill_id, uint16 skill_lv)
  2053. {
  2054. return unit_skilluse_pos2(
  2055. src, skill_x, skill_y, skill_id, skill_lv,
  2056. skill_castfix(src, skill_id, skill_lv),
  2057. skill_get_castcancel(skill_id)
  2058. );
  2059. }
  2060. /**
  2061. * Performs checks for a unit using a skill and executes after cast time completion
  2062. * @param src: Object using skill
  2063. * @param skill_x: X coordinate where skill is being casted (center)
  2064. * @param skill_y: Y coordinate where skill is being casted (center)
  2065. * @param skill_id: Skill ID
  2066. * @param skill_lv: Skill Level
  2067. * @param casttime: Initial cast time before cast time reductions
  2068. * @param castcancel: Whether or not the skill can be cancelled by interuption (hit)
  2069. * @return Success(1); Fail(0);
  2070. */
  2071. int32 unit_skilluse_pos2( struct block_list *src, int16 skill_x, int16 skill_y, uint16 skill_id, uint16 skill_lv, int32 casttime, int32 castcancel, bool ignore_range)
  2072. {
  2073. map_session_data *sd = nullptr;
  2074. struct unit_data *ud = nullptr;
  2075. status_change *sc;
  2076. struct block_list bl;
  2077. t_tick tick = gettick();
  2078. int32 range;
  2079. nullpo_ret(src);
  2080. if (!src->prev)
  2081. return 0; // Not on the map
  2082. if(status_isdead(*src))
  2083. return 0;
  2084. sd = BL_CAST(BL_PC, src);
  2085. ud = unit_bl2ud(src);
  2086. if(ud == nullptr)
  2087. return 0;
  2088. if (ud && ud->state.blockedskill)
  2089. return 0;
  2090. if(ud->skilltimer != INVALID_TIMER) // Normally not needed since clif.cpp checks for it, but at/char/script commands don't! [Skotlex]
  2091. return 0;
  2092. sc = status_get_sc(src);
  2093. if (sc != nullptr && sc->empty())
  2094. sc = nullptr;
  2095. if (!skill_db.find(skill_id))
  2096. return 0;
  2097. if( sd ) {
  2098. if( skill_isNotOk(skill_id, *sd) || !skill_check_condition_castbegin(*sd, skill_id, skill_lv) )
  2099. return 0;
  2100. if (skill_id == MG_FIREWALL && !skill_pos_maxcount_check(src, skill_x, skill_y, skill_id, skill_lv, BL_PC, true))
  2101. return 0; // Special check for Firewall only
  2102. }
  2103. if( (skill_id >= SC_MANHOLE && skill_id <= SC_FEINTBOMB) && map_getcell(src->m, skill_x, skill_y, CELL_CHKMAELSTROM) ) {
  2104. if (sd)
  2105. clif_skill_fail( *sd, skill_id );
  2106. return 0;
  2107. }
  2108. if (!status_check_skilluse(src, nullptr, skill_id, 0))
  2109. return 0;
  2110. // Fail if the targetted skill is near NPC [Cydh]
  2111. if(skill_get_inf2(skill_id, INF2_DISABLENEARNPC) && !ignore_range && skill_isNotOk_npcRange(src,skill_id,skill_lv,skill_x,skill_y)) {
  2112. if (sd)
  2113. clif_skill_fail( *sd, skill_id );
  2114. return 0;
  2115. }
  2116. // Check range and obstacle
  2117. bl.type = BL_NUL;
  2118. bl.m = src->m;
  2119. bl.x = skill_x;
  2120. bl.y = skill_y;
  2121. if (src->type == BL_NPC) // NPC-objects can override cast distance
  2122. range = AREA_SIZE; // Maximum visible distance before NPC goes out of sight
  2123. else
  2124. range = skill_get_range2(src, skill_id, skill_lv, true); // Skill cast distance from database
  2125. // New action request received, delete previous action request if not executed yet
  2126. if(ud->stepaction || ud->steptimer != INVALID_TIMER)
  2127. unit_stop_stepaction(src);
  2128. // Remember the skill request from the client while walking to the next cell
  2129. if(src->type == BL_PC && ud->walktimer != INVALID_TIMER && (!battle_check_range(src, &bl, range-1) || ignore_range)) {
  2130. struct map_data *md = &map[src->m];
  2131. // Convert coordinates to target_to so we can use it as target later
  2132. ud->stepaction = true;
  2133. ud->target_to = (skill_x + skill_y*md->xs);
  2134. ud->stepskill_id = skill_id;
  2135. ud->stepskill_lv = skill_lv;
  2136. return 0; // Attacking will be handled by unit_walktoxy_timer in this case
  2137. }
  2138. if (!ignore_range) {
  2139. if( skill_get_state(ud->skill_id) == ST_MOVE_ENABLE ) {
  2140. if( !unit_can_reach_bl(src, &bl, range + 1, 1, nullptr, nullptr) )
  2141. return 0; // Walk-path check failed.
  2142. }else if( !battle_check_range(src, &bl, range) )
  2143. return 0; // Arrow-path check failed.
  2144. }
  2145. unit_stop_attack(src);
  2146. // Moved here to prevent Suffragium from ending if skill fails
  2147. #ifndef RENEWAL_CAST
  2148. casttime = skill_castfix_sc(src, casttime, skill_get_castnodex(skill_id));
  2149. #else
  2150. casttime = skill_vfcastfix(src, casttime, skill_id, skill_lv );
  2151. #endif
  2152. ud->state.skillcastcancel = castcancel&&casttime>0?1:0;
  2153. if (!sd || sd->skillitem != skill_id || skill_get_cast(skill_id, skill_lv))
  2154. ud->canact_tick = tick + i64max(casttime, max(status_get_amotion(src), battle_config.min_skill_delay_limit)) + SECURITY_CASTTIME;
  2155. // if( sd )
  2156. // {
  2157. // switch( skill_id )
  2158. // {
  2159. // case ????:
  2160. // sd->canequip_tick = tick + casttime;
  2161. // }
  2162. // }
  2163. ud->skill_id = skill_id;
  2164. ud->skill_lv = skill_lv;
  2165. ud->skillx = skill_x;
  2166. ud->skilly = skill_y;
  2167. ud->skilltarget = 0;
  2168. if( sc ) {
  2169. // These 3 status do not stack, so it's efficient to use if-else
  2170. if (sc->getSCE(SC_CLOAKING) && !(sc->getSCE(SC_CLOAKING)->val4&4)) {
  2171. status_change_end(src, SC_CLOAKING);
  2172. if (!src->prev)
  2173. return 0; // Warped away!
  2174. } else if (sc->getSCE(SC_CLOAKINGEXCEED) && !(sc->getSCE(SC_CLOAKINGEXCEED)->val4&4)) {
  2175. status_change_end(src, SC_CLOAKINGEXCEED);
  2176. if (!src->prev)
  2177. return 0;
  2178. } else if (sc->getSCE(SC_NEWMOON)) {
  2179. status_change_end(src, SC_NEWMOON);
  2180. if (!src->prev)
  2181. return 0;
  2182. }
  2183. }
  2184. unit_stop_walking( src, USW_FIXPOS );
  2185. // SC_MAGICPOWER needs to switch states at start of cast
  2186. #ifndef RENEWAL
  2187. skill_toggle_magicpower(src, skill_id);
  2188. #endif
  2189. // In official this is triggered even if no cast time.
  2190. clif_skillcasting(src, src->id, 0, skill_x, skill_y, skill_id, skill_lv, skill_get_ele(skill_id, skill_lv), casttime);
  2191. if( casttime > 0 ) {
  2192. ud->skilltimer = add_timer( tick+casttime, skill_castend_pos, src->id, 0 );
  2193. if( (sd && pc_checkskill(sd,SA_FREECAST) > 0) || skill_id == LG_EXEEDBREAK)
  2194. status_calc_bl(&sd->bl, { SCB_SPEED, SCB_ASPD });
  2195. } else {
  2196. ud->skilltimer = INVALID_TIMER;
  2197. skill_castend_pos(ud->skilltimer,tick,src->id,0);
  2198. }
  2199. if( sd && battle_config.prevent_logout_trigger&PLT_SKILL )
  2200. sd->canlog_tick = gettick();
  2201. return 1;
  2202. }
  2203. /**
  2204. * Update a unit's attack target
  2205. * @param ud: Unit data
  2206. * @param target_id: Target ID (bl->id)
  2207. * @return 0
  2208. */
  2209. int32 unit_set_target(struct unit_data* ud, int32 target_id)
  2210. {
  2211. nullpo_ret(ud);
  2212. if( ud->target != target_id ) {
  2213. struct unit_data * ux;
  2214. struct block_list* target;
  2215. if (ud->target && (target = map_id2bl(ud->target)) && (ux = unit_bl2ud(target)) && ux->target_count > 0)
  2216. ux->target_count--;
  2217. if (target_id && (target = map_id2bl(target_id)) && (ux = unit_bl2ud(target)) && ux->target_count < 255)
  2218. ux->target_count++;
  2219. }
  2220. ud->target = target_id;
  2221. return 0;
  2222. }
  2223. /**
  2224. * Helper function used in foreach calls to stop auto-attack timers
  2225. * @param bl: Block object
  2226. * @param ap: func* with va_list values
  2227. * Parameter: '0' - everyone, 'id' - only those attacking someone with that id
  2228. * @return 1 on success or 0 otherwise
  2229. */
  2230. int32 unit_stopattack(struct block_list *bl, va_list ap)
  2231. {
  2232. struct unit_data *ud = unit_bl2ud(bl);
  2233. int32 id = va_arg(ap, int32);
  2234. if (ud && ud->attacktimer != INVALID_TIMER && (!id || id == ud->target)) {
  2235. unit_stop_attack(bl);
  2236. return 1;
  2237. }
  2238. return 0;
  2239. }
  2240. /**
  2241. * Stop a unit's attacks
  2242. * @param bl: Object to stop
  2243. */
  2244. void unit_stop_attack(struct block_list *bl)
  2245. {
  2246. struct unit_data *ud;
  2247. nullpo_retv(bl);
  2248. ud = unit_bl2ud(bl);
  2249. nullpo_retv(ud);
  2250. //Clear target
  2251. unit_set_target(ud, 0);
  2252. if(ud->attacktimer == INVALID_TIMER)
  2253. return;
  2254. //Clear timer
  2255. delete_timer(ud->attacktimer, unit_attack_timer);
  2256. ud->attacktimer = INVALID_TIMER;
  2257. }
  2258. /**
  2259. * Stop a unit's step action
  2260. * @param bl: Object to stop
  2261. */
  2262. void unit_stop_stepaction(struct block_list *bl)
  2263. {
  2264. struct unit_data *ud;
  2265. nullpo_retv(bl);
  2266. ud = unit_bl2ud(bl);
  2267. nullpo_retv(ud);
  2268. //Clear remembered step action
  2269. ud->stepaction = false;
  2270. ud->target_to = 0;
  2271. ud->stepskill_id = 0;
  2272. ud->stepskill_lv = 0;
  2273. if(ud->steptimer == INVALID_TIMER)
  2274. return;
  2275. //Clear timer
  2276. delete_timer(ud->steptimer, unit_step_timer);
  2277. ud->steptimer = INVALID_TIMER;
  2278. }
  2279. /**
  2280. * Removes a unit's target due to being unattackable
  2281. * @param bl: Object to unlock target
  2282. * @return 0
  2283. */
  2284. int32 unit_unattackable(struct block_list *bl)
  2285. {
  2286. struct unit_data *ud = unit_bl2ud(bl);
  2287. if (ud) {
  2288. ud->state.attack_continue = 0;
  2289. ud->state.step_attack = 0;
  2290. ud->target_to = 0;
  2291. unit_set_target(ud, 0);
  2292. }
  2293. if(bl->type == BL_MOB)
  2294. mob_unlocktarget((struct mob_data*)bl, gettick());
  2295. else if(bl->type == BL_PET)
  2296. pet_unlocktarget((struct pet_data*)bl);
  2297. return 0;
  2298. }
  2299. /**
  2300. * Requests a unit to attack a target
  2301. * @param src: Object initiating attack
  2302. * @param target_id: Target ID (bl->id)
  2303. * @param continuous:
  2304. * 0x1 - Whether or not the attack is ongoing
  2305. * 0x2 - Whether function was called from unit_step_timer or not
  2306. * @return Success(0); Fail(1);
  2307. */
  2308. int32 unit_attack(struct block_list *src,int32 target_id,int32 continuous)
  2309. {
  2310. struct block_list *target;
  2311. struct unit_data *ud;
  2312. int32 range;
  2313. nullpo_ret(ud = unit_bl2ud(src));
  2314. target = map_id2bl(target_id);
  2315. if( target == nullptr || status_isdead(*target) ) {
  2316. unit_unattackable(src);
  2317. return 1;
  2318. }
  2319. if( src->type == BL_PC &&
  2320. target->type == BL_NPC ) {
  2321. // Monster npcs [Valaris]
  2322. npc_click((TBL_PC*)src,(TBL_NPC*)target);
  2323. return 0;
  2324. }
  2325. if( !unit_can_attack(src, target_id) ) {
  2326. unit_stop_attack(src);
  2327. return 0;
  2328. }
  2329. if( battle_check_target(src,target,BCT_ENEMY) <= 0 || !status_check_skilluse(src, target, 0, 0) ) {
  2330. unit_unattackable(src);
  2331. return 1;
  2332. }
  2333. ud->state.attack_continue = (continuous&1)?1:0;
  2334. ud->state.step_attack = (continuous&2)?1:0;
  2335. unit_set_target(ud, target_id);
  2336. range = status_get_range(src);
  2337. if (continuous) // If you're to attack continously, set to auto-chase character
  2338. ud->chaserange = range;
  2339. // Just change target/type. [Skotlex]
  2340. if(ud->attacktimer != INVALID_TIMER)
  2341. return 0;
  2342. // New action request received, delete previous action request if not executed yet
  2343. if(ud->stepaction || ud->steptimer != INVALID_TIMER)
  2344. unit_stop_stepaction(src);
  2345. // Remember the attack request from the client while walking to the next cell
  2346. if(src->type == BL_PC && ud->walktimer != INVALID_TIMER && !battle_check_range(src, target, range-1)) {
  2347. ud->stepaction = true;
  2348. ud->target_to = ud->target;
  2349. ud->stepskill_id = 0;
  2350. ud->stepskill_lv = 0;
  2351. return 0; // Attacking will be handled by unit_walktoxy_timer in this case
  2352. }
  2353. if(DIFF_TICK(ud->attackabletime, gettick()) > 0) // Do attack next time it is possible. [Skotlex]
  2354. ud->attacktimer=add_timer(ud->attackabletime,unit_attack_timer,src->id,0);
  2355. else // Attack NOW.
  2356. unit_attack_timer(INVALID_TIMER, gettick(), src->id, 0);
  2357. // Monster state is set regardless of whether the attack is executed now or later
  2358. // The check is here because unit_attack can be called from both the monster AI and the walking logic
  2359. if (src->type == BL_MOB) {
  2360. mob_data& md = reinterpret_cast<mob_data&>(*src);
  2361. mob_setstate(md, MSS_BERSERK);
  2362. }
  2363. return 0;
  2364. }
  2365. /**
  2366. * Cancels an ongoing combo, resets attackable time, and restarts the
  2367. * attack timer to resume attack after amotion time
  2368. * @author [Skotlex]
  2369. * @param bl: Object to cancel combo
  2370. * @return Success(1); Fail(0);
  2371. */
  2372. int32 unit_cancel_combo(struct block_list *bl)
  2373. {
  2374. struct unit_data *ud;
  2375. if (!status_change_end(bl, SC_COMBO))
  2376. return 0; // Combo wasn't active.
  2377. ud = unit_bl2ud(bl);
  2378. nullpo_ret(ud);
  2379. ud->attackabletime = gettick() + status_get_amotion(bl);
  2380. if (ud->attacktimer == INVALID_TIMER)
  2381. return 1; // Nothing more to do.
  2382. delete_timer(ud->attacktimer, unit_attack_timer);
  2383. ud->attacktimer=add_timer(ud->attackabletime,unit_attack_timer,bl->id,0);
  2384. return 1;
  2385. }
  2386. /**
  2387. * Does a path_search to check if a position can be reached
  2388. * @param bl: Object to check path
  2389. * @param x: X coordinate that will be path searched
  2390. * @param y: Y coordinate that will be path searched
  2391. * @param easy: Easy(1) or Hard(0) path check (hard attempts to go around obstacles)
  2392. * @return true or false
  2393. */
  2394. bool unit_can_reach_pos(struct block_list *bl,int32 x,int32 y, int32 easy)
  2395. {
  2396. nullpo_retr(false, bl);
  2397. if (bl->x == x && bl->y == y) // Same place
  2398. return true;
  2399. return path_search(nullptr,bl->m,bl->x,bl->y,x,y,easy,CELL_CHKNOREACH);
  2400. }
  2401. /**
  2402. * Does a path_search to check if a unit can be reached
  2403. * @param bl: Object to check path
  2404. * @param tbl: Target to be checked for available path
  2405. * @param range: The number of cells away from bl that the path should be checked
  2406. * @param easy: Easy(1) or Hard(0) path check (hard attempts to go around obstacles)
  2407. * @param x: Pointer storing a valid X coordinate around tbl that can be reached
  2408. * @param y: Pointer storing a valid Y coordinate around tbl that can be reached
  2409. * @return true or false
  2410. */
  2411. bool unit_can_reach_bl(struct block_list *bl,struct block_list *tbl, int32 range, int32 easy, int16 *x, int16 *y)
  2412. {
  2413. struct walkpath_data wpd;
  2414. int16 dx, dy;
  2415. nullpo_retr(false, bl);
  2416. nullpo_retr(false, tbl);
  2417. if( bl->m != tbl->m)
  2418. return false;
  2419. if( bl->x == tbl->x && bl->y == tbl->y )
  2420. return true;
  2421. if(range > 0 && !check_distance_bl(bl, tbl, range))
  2422. return false;
  2423. // It judges whether it can adjoin or not.
  2424. dx = tbl->x - bl->x;
  2425. dy = tbl->y - bl->y;
  2426. dx = (dx > 0) ? 1 : ((dx < 0) ? -1 : 0);
  2427. dy = (dy > 0) ? 1 : ((dy < 0) ? -1 : 0);
  2428. if (map_getcell(tbl->m,tbl->x-dx,tbl->y-dy,CELL_CHKNOPASS)) { // Look for a suitable cell to place in.
  2429. int32 i;
  2430. for(i = 0; i < 8 && map_getcell(tbl->m,tbl->x-dirx[i],tbl->y-diry[i],CELL_CHKNOPASS); i++);
  2431. if (i == 8)
  2432. return false; // No valid cells.
  2433. dx = dirx[i];
  2434. dy = diry[i];
  2435. }
  2436. if (x)
  2437. *x = tbl->x-dx;
  2438. if (y)
  2439. *y = tbl->y-dy;
  2440. if (!path_search(&wpd,bl->m,bl->x,bl->y,tbl->x-dx,tbl->y-dy,easy,CELL_CHKNOREACH))
  2441. return false;
  2442. #ifdef OFFICIAL_WALKPATH
  2443. if( bl->type != BL_NPC // If type is a NPC, please disregard.
  2444. && wpd.path_len > 14 // Official number of walkable cells is 14 if and only if there is an obstacle between. [malufett]
  2445. && !path_search_long(nullptr, bl->m, bl->x, bl->y, tbl->x-dx, tbl->y-dy, CELL_CHKNOPASS) ) // Check if there is an obstacle between
  2446. return false;
  2447. #endif
  2448. return true;
  2449. }
  2450. /**
  2451. * Calculates position of Pet/Mercenary/Homunculus/Elemental
  2452. * @param bl: Object to calculate position
  2453. * @param tx: X coordinate to go to
  2454. * @param ty: Y coordinate to go to
  2455. * @param dir: Direction which to be 2 cells from master's position
  2456. * @return Success(0); Fail(1);
  2457. */
  2458. int32 unit_calc_pos(struct block_list *bl, int32 tx, int32 ty, uint8 dir)
  2459. {
  2460. int32 dx, dy, x, y;
  2461. struct unit_data *ud = unit_bl2ud(bl);
  2462. nullpo_ret(ud);
  2463. if(dir >= DIR_MAX || dir <= DIR_CENTER)
  2464. return 1;
  2465. ud->to_x = tx;
  2466. ud->to_y = ty;
  2467. // 2 cells from Master Position
  2468. dx = -dirx[dir] * 2;
  2469. dy = -diry[dir] * 2;
  2470. x = tx + dx;
  2471. y = ty + dy;
  2472. if( !unit_can_reach_pos(bl, x, y, 0) ) {
  2473. if( dx > 0 )
  2474. x--;
  2475. else if( dx < 0 )
  2476. x++;
  2477. if( dy > 0 )
  2478. y--;
  2479. else if( dy < 0 )
  2480. y++;
  2481. if( !unit_can_reach_pos(bl, x, y, 0) ) {
  2482. int32 i;
  2483. for( i = 0; i < 12; i++ ) {
  2484. int32 k = rnd_value<int32>(DIR_NORTH, DIR_NORTHEAST); // Pick a Random Dir
  2485. dx = -dirx[k] * 2;
  2486. dy = -diry[k] * 2;
  2487. x = tx + dx;
  2488. y = ty + dy;
  2489. if( unit_can_reach_pos(bl, x, y, 0) )
  2490. break;
  2491. else {
  2492. if( dx > 0 )
  2493. x--;
  2494. else if( dx < 0 )
  2495. x++;
  2496. if( dy > 0 )
  2497. y--;
  2498. else if( dy < 0 )
  2499. y++;
  2500. if( unit_can_reach_pos(bl, x, y, 0) )
  2501. break;
  2502. }
  2503. }
  2504. if( i == 12 ) {
  2505. x = tx; y = tx; // Exactly Master Position
  2506. if( !unit_can_reach_pos(bl, x, y, 0) )
  2507. return 1;
  2508. }
  2509. }
  2510. }
  2511. ud->to_x = x;
  2512. ud->to_y = y;
  2513. return 0;
  2514. }
  2515. /**
  2516. * Function timer to continuously attack
  2517. * @param src: Object to continuously attack
  2518. * @param tid: Timer ID
  2519. * @param tick: Current tick
  2520. * @return Attackable(1); Unattackable(0);
  2521. */
  2522. static int32 unit_attack_timer_sub(struct block_list* src, int32 tid, t_tick tick)
  2523. {
  2524. struct block_list *target;
  2525. struct unit_data *ud;
  2526. map_session_data *sd = nullptr;
  2527. struct mob_data *md = nullptr;
  2528. int32 range;
  2529. if( (ud = unit_bl2ud(src)) == nullptr )
  2530. return 0;
  2531. if( ud->attacktimer != tid ) {
  2532. ShowError("unit_attack_timer %d != %d\n",ud->attacktimer,tid);
  2533. return 0;
  2534. }
  2535. sd = BL_CAST(BL_PC, src);
  2536. md = BL_CAST(BL_MOB, src);
  2537. // Make sure attacktimer is removed before doing anything else
  2538. ud->attacktimer = INVALID_TIMER;
  2539. // Note: Officially there is no such thing as an attack timer. All actions are driven by the client or the AI.
  2540. // We use the continuous attack timers to have accurate attack timings that don't depend on the AI interval.
  2541. // However, for a clean implementation we still should channel through the whole AI code so the same rules
  2542. // apply as usual and we don't need to code extra rules. Currently we resolved this only for monsters.
  2543. // We don't want this to trigger on direct calls of the timer function as that should just execute the attack.
  2544. if (md != nullptr && tid != INVALID_TIMER)
  2545. return mob_ai_sub_hard_attacktimer(*md, tick);
  2546. target = map_id2bl(ud->target);
  2547. if( src == nullptr || src->prev == nullptr || target==nullptr || target->prev == nullptr )
  2548. return 0;
  2549. if( status_isdead(*src) || status_isdead(*target) ||
  2550. battle_check_target(src,target,BCT_ENEMY) <= 0 || !status_check_skilluse(src, target, 0, 0)
  2551. #ifdef OFFICIAL_WALKPATH
  2552. || !path_search_long(nullptr, src->m, src->x, src->y, target->x, target->y, CELL_CHKWALL)
  2553. #endif
  2554. || !unit_can_attack(src, target->id) )
  2555. return 0; // Can't attack under these conditions
  2556. if( ud->skilltimer != INVALID_TIMER && !(sd && pc_checkskill(sd,SA_FREECAST) > 0) )
  2557. return 0; // Can't attack while casting
  2558. if( !battle_config.sdelay_attack_enable && DIFF_TICK(ud->canact_tick,tick) > 0 && !(sd && pc_checkskill(sd,SA_FREECAST) > 0) ) {
  2559. // Attacking when under cast delay has restrictions:
  2560. if( tid == INVALID_TIMER ) { // Requested attack.
  2561. if(sd)
  2562. clif_skill_fail( *sd, 1, USESKILL_FAIL_SKILLINTERVAL );
  2563. return 0;
  2564. }
  2565. // Otherwise, we are in a combo-attack, delay this until your canact time is over. [Skotlex]
  2566. if( ud->state.attack_continue ) {
  2567. if( DIFF_TICK(ud->canact_tick, ud->attackabletime) > 0 )
  2568. ud->attackabletime = ud->canact_tick;
  2569. ud->attacktimer=add_timer(ud->attackabletime,unit_attack_timer,src->id,0);
  2570. }
  2571. return 1;
  2572. }
  2573. status_data* sstatus = status_get_status_data(*src);
  2574. range = sstatus->rhw.range;
  2575. if( (unit_is_walking(target) || ud->state.step_attack)
  2576. && (target->type == BL_PC || !map_getcell(target->m,target->x,target->y,CELL_CHKICEWALL)) )
  2577. range++; // Extra range when chasing (does not apply to mobs locked in an icewall)
  2578. if(sd && !check_distance_client_bl(src,target,range)) {
  2579. // Player tries to attack but target is too far, notify client
  2580. clif_movetoattack( *sd, *target );
  2581. return 1;
  2582. } else if(md && !check_distance_bl(src,target,range)) {
  2583. // Monster: Chase if required
  2584. unit_walktobl(src,target,ud->chaserange,ud->state.walk_easy|2);
  2585. return 1;
  2586. }
  2587. if( !battle_check_range(src,target,range) ) {
  2588. // Within range, but no direct line of attack
  2589. // This code can usually only be reached if OFFICIAL_WALKPATH is disabled
  2590. if (ud->state.attack_continue && ud->chaserange > 1) {
  2591. ud->chaserange = std::max(1, ud->chaserange - 2);
  2592. // Walk closer / around the obstacle and start attacking once you are in range
  2593. return unit_walktobl(src,target,ud->chaserange,ud->state.walk_easy|2);
  2594. }
  2595. // Can't attack even though next to the target? Giving up here.
  2596. return 0;
  2597. }
  2598. // Sync packet only for players.
  2599. // Non-players use the sync packet on the walk timer. [Skotlex]
  2600. if (tid == INVALID_TIMER && sd)
  2601. clif_fixpos( *src );
  2602. if( DIFF_TICK(ud->attackabletime,tick) <= 0 ) {
  2603. if (battle_config.attack_direction_change && (src->type&battle_config.attack_direction_change))
  2604. unit_setdir(src, map_calc_dir(src, target->x, target->y), false);
  2605. if(ud->walktimer != INVALID_TIMER)
  2606. unit_stop_walking( src, USW_FIXPOS );
  2607. if(md) {
  2608. if (status_has_mode(sstatus,MD_ASSIST) && DIFF_TICK(tick, md->last_linktime) >= MIN_MOBLINKTIME) {
  2609. // Link monsters nearby [Skotlex]
  2610. md->last_linktime = tick;
  2611. map_foreachinshootrange(mob_linksearch, src, battle_config.assist_range, BL_MOB, md->mob_id, target->id, tick);
  2612. }
  2613. }
  2614. if(src->type == BL_PET && pet_attackskill((TBL_PET*)src, target->id))
  2615. return 1;
  2616. map_freeblock_lock();
  2617. ud->attacktarget_lv = battle_weapon_attack(src,target,tick,0);
  2618. if(sd && sd->status.pet_id > 0 && sd->pd && battle_config.pet_attack_support)
  2619. pet_target_check(sd->pd,target,0);
  2620. map_freeblock_unlock();
  2621. /**
  2622. * Applied when you're unable to attack (e.g. out of ammo)
  2623. * We should stop here otherwise timer keeps on and this happens endlessly
  2624. */
  2625. if( ud->attacktarget_lv == ATK_NONE )
  2626. return 1;
  2627. unit_set_attackdelay(*src, tick, DELAY_EVENT_ATTACK);
  2628. // Only reset skill_id here if no skilltimer is currently ongoing
  2629. if (ud->skilltimer == INVALID_TIMER)
  2630. ud->skill_id = 0;
  2631. // You can't move during your attack motion
  2632. if (src->type&battle_config.attack_walk_delay) {
  2633. // Monsters set their AI inactive instead of having a walkdelay
  2634. if (md != nullptr)
  2635. md->next_thinktime = tick + status_get_amotion(src);
  2636. else
  2637. unit_set_walkdelay(src, tick, sstatus->amotion, 1);
  2638. }
  2639. }
  2640. if(ud->state.attack_continue) {
  2641. if (src->type == BL_PC && battle_config.idletime_option&IDLE_ATTACK)
  2642. ((TBL_PC*)src)->idletime = last_tick;
  2643. ud->attacktimer = add_timer(ud->attackabletime,unit_attack_timer,src->id,0);
  2644. }
  2645. if( sd && battle_config.prevent_logout_trigger&PLT_ATTACK )
  2646. sd->canlog_tick = gettick();
  2647. return 1;
  2648. }
  2649. /**
  2650. * Timer function to cancel attacking if unit has become unattackable
  2651. * @param tid: Timer ID
  2652. * @param tick: Current tick
  2653. * @param id: Object to cancel attack if applicable
  2654. * @param data: Data passed from timer call
  2655. * @return 0
  2656. */
  2657. static TIMER_FUNC(unit_attack_timer){
  2658. struct block_list *bl;
  2659. bl = map_id2bl(id);
  2660. if (bl != nullptr) {
  2661. // Execute attack
  2662. if (unit_attack_timer_sub(bl, tid, tick) == 0)
  2663. unit_unattackable(bl);
  2664. }
  2665. return 0;
  2666. }
  2667. /**
  2668. * Determines whether a player can attack based on status changes
  2669. * Why not use status_check_skilluse?
  2670. * "src MAY be null to indicate we shouldn't check it, this is a ground-based skill attack."
  2671. * Even ground-based attacks should be blocked by these statuses
  2672. * Called from unit_attack and unit_attack_timer_sub
  2673. * @retval true Can attack
  2674. **/
  2675. bool unit_can_attack(struct block_list *bl, int32 target_id) {
  2676. nullpo_retr(false, bl);
  2677. if (bl->type == BL_PC) {
  2678. map_session_data *sd = ((TBL_PC *)bl);
  2679. if (sd && ((sd->state.block_action & PCBLOCK_ATTACK) || pc_isridingwug(sd)))
  2680. return false;
  2681. }
  2682. status_change *sc;
  2683. if (!(sc = status_get_sc(bl)))
  2684. return true;
  2685. if (sc->cant.attack || (sc->getSCE(SC_VOICEOFSIREN) && sc->getSCE(SC_VOICEOFSIREN)->val2 == target_id))
  2686. return false;
  2687. return true;
  2688. }
  2689. /**
  2690. * Cancels a skill's cast
  2691. * @param bl: Object to cancel cast
  2692. * @param type: Cancel check flag
  2693. * &1: Cast-Cancel invoked
  2694. * &2: Cancel only if skill is cancellable
  2695. * @return Success(1); Fail(0);
  2696. */
  2697. int32 unit_skillcastcancel(struct block_list *bl, char type)
  2698. {
  2699. map_session_data *sd = nullptr;
  2700. struct unit_data *ud = unit_bl2ud( bl);
  2701. t_tick tick = gettick();
  2702. int32 ret = 0, skill_id;
  2703. nullpo_ret(bl);
  2704. if (!ud || ud->skilltimer == INVALID_TIMER)
  2705. return 0; // Nothing to cancel.
  2706. sd = BL_CAST(BL_PC, bl);
  2707. if (type&2) { // See if it can be cancelled.
  2708. if (!ud->state.skillcastcancel)
  2709. return 0;
  2710. if (sd && (sd->special_state.no_castcancel2 ||
  2711. ((sd->sc.getSCE(SC_UNLIMITEDHUMMINGVOICE) || sd->special_state.no_castcancel) && !map_flag_gvg2(bl->m) && !map_getmapflag(bl->m, MF_BATTLEGROUND)))) // fixed flags being read the wrong way around [blackhole89]
  2712. return 0;
  2713. }
  2714. ud->canact_tick = tick;
  2715. if(type&1 && sd)
  2716. skill_id = sd->skill_id_old;
  2717. else
  2718. skill_id = ud->skill_id;
  2719. if (skill_get_inf(skill_id) & INF_GROUND_SKILL)
  2720. ret=delete_timer( ud->skilltimer, skill_castend_pos );
  2721. else
  2722. ret=delete_timer( ud->skilltimer, skill_castend_id );
  2723. if(ret < 0)
  2724. ShowError("delete timer error : skill_id : %d\n",ret);
  2725. ud->skilltimer = INVALID_TIMER;
  2726. if( sd && (pc_checkskill(sd,SA_FREECAST) > 0 || skill_id == LG_EXEEDBREAK) )
  2727. status_calc_bl(&sd->bl, { SCB_SPEED, SCB_ASPD });
  2728. if( sd ) {
  2729. switch( skill_id ) {
  2730. case CG_ARROWVULCAN:
  2731. sd->canequip_tick = tick;
  2732. break;
  2733. }
  2734. }
  2735. if (bl->type == BL_MOB) {
  2736. mob_data& md = reinterpret_cast<mob_data&>(*bl);
  2737. // Sets cooldowns and attack delay
  2738. // This needs to happen even if the cast was cancelled
  2739. mobskill_end(md, tick);
  2740. md.skill_idx = -1;
  2741. }
  2742. clif_skillcastcancel( *bl );
  2743. return 1;
  2744. }
  2745. /**
  2746. * Initialized data on a unit
  2747. * @param bl: Object to initialize data on
  2748. */
  2749. void unit_dataset(struct block_list *bl)
  2750. {
  2751. struct unit_data *ud;
  2752. nullpo_retv(ud = unit_bl2ud(bl));
  2753. memset( ud, 0, sizeof( struct unit_data) );
  2754. ud->bl = bl;
  2755. ud->walktimer = INVALID_TIMER;
  2756. ud->skilltimer = INVALID_TIMER;
  2757. ud->attacktimer = INVALID_TIMER;
  2758. ud->steptimer = INVALID_TIMER;
  2759. ud->attackabletime =
  2760. ud->canact_tick =
  2761. ud->canmove_tick = gettick();
  2762. ud->sx = 8;
  2763. ud->sy = 8;
  2764. }
  2765. /**
  2766. * Returns the remaining max amount of skill units per object for a specific skill
  2767. * @param ud: Unit data
  2768. * @param skill_id: Skill to search for
  2769. * @param maxcount: Maximum amount of placeable units
  2770. */
  2771. void unit_skillunit_maxcount(unit_data& ud, uint16 skill_id, int& maxcount) {
  2772. for (const auto su : ud.skillunits) {
  2773. if (su->skill_id == skill_id && --maxcount == 0 )
  2774. break;
  2775. }
  2776. }
  2777. /**
  2778. * Gets the number of units attacking another unit
  2779. * @param bl: Object to check amount of targets
  2780. * @return number of targets or 0
  2781. */
  2782. int32 unit_counttargeted(struct block_list* bl)
  2783. {
  2784. struct unit_data* ud;
  2785. if( bl && (ud = unit_bl2ud(bl)) )
  2786. return ud->target_count;
  2787. return 0;
  2788. }
  2789. /**
  2790. * Makes 'bl' that attacking 'src' switch to attack 'target'
  2791. * @param bl
  2792. * @param ap
  2793. * @param src Current target
  2794. * @param target New target
  2795. **/
  2796. int32 unit_changetarget(block_list *bl, va_list ap) {
  2797. if (bl == nullptr)
  2798. return 1;
  2799. unit_data *ud = unit_bl2ud(bl);
  2800. block_list *src = va_arg(ap, block_list *);
  2801. block_list *target = va_arg(ap, block_list *);
  2802. if (ud == nullptr || src == nullptr || target == nullptr || ud->target == target->id)
  2803. return 1;
  2804. if (ud->target <= 0 && ud->target_to <= 0)
  2805. return 1;
  2806. if (ud->target != src->id && ud->target_to != src->id)
  2807. return 1;
  2808. unit_changetarget_sub(*ud, *target);
  2809. //unit_attack(bl, target->id, ud->state.attack_continue);
  2810. return 0;
  2811. }
  2812. /**
  2813. * Changes the target of a unit
  2814. * @param ud: Unit data
  2815. * @param target: New target data
  2816. **/
  2817. void unit_changetarget_sub(unit_data& ud, block_list& target) {
  2818. if (status_isdead(target))
  2819. return;
  2820. if (ud.bl->type == BL_MOB)
  2821. reinterpret_cast<mob_data*>(ud.bl)->target_id = target.id;
  2822. if (ud.target_to > 0)
  2823. ud.target_to = target.id;
  2824. if (ud.skilltarget > 0)
  2825. ud.skilltarget = target.id;
  2826. unit_set_target(&ud, target.id);
  2827. }
  2828. /**
  2829. * Removes a bl/ud from the map
  2830. * On kill specifics are not performed here, check status_damage()
  2831. * @param bl: Object to remove from map
  2832. * @param clrtype: How bl is being removed
  2833. * 0: Assume bl is being warped
  2834. * 1: Death, appropriate cleanup performed
  2835. * @param file, line, func: Call information for debug purposes
  2836. * @return Success(1); Couldn't be removed or bl was free'd(0)
  2837. */
  2838. int32 unit_remove_map_(struct block_list *bl, clr_type clrtype, const char* file, int32 line, const char* func)
  2839. {
  2840. struct unit_data *ud = unit_bl2ud(bl);
  2841. status_change *sc = status_get_sc(bl);
  2842. nullpo_ret(ud);
  2843. if(bl->prev == nullptr)
  2844. return 0; // Already removed?
  2845. map_freeblock_lock();
  2846. if (ud->walktimer != INVALID_TIMER)
  2847. unit_stop_walking(bl,USW_RELEASE_TARGET);
  2848. if (clrtype == CLR_DEAD)
  2849. ud->state.blockedmove = true;
  2850. if (ud->skilltimer != INVALID_TIMER)
  2851. unit_skillcastcancel(bl,0);
  2852. //Clear target even if there is no timer
  2853. if (ud->target || ud->attacktimer != INVALID_TIMER)
  2854. unit_stop_attack(bl);
  2855. //Clear stepaction even if there is no timer
  2856. if (ud->stepaction || ud->steptimer != INVALID_TIMER)
  2857. unit_stop_stepaction(bl);
  2858. // Do not reset can-act delay. [Skotlex]
  2859. ud->attackabletime = ud->canmove_tick /*= ud->canact_tick*/ = gettick();
  2860. if(sc != nullptr && !sc->empty() ) { // map-change/warp dispells.
  2861. status_db.removeByStatusFlag(bl, { SCF_REMOVEONCHANGEMAP });
  2862. // Ensure the bl is a PC; if so, we'll handle the removal of cloaking and cloaking exceed later
  2863. if ( bl->type != BL_PC ) {
  2864. status_change_end(bl, SC_CLOAKING);
  2865. status_change_end(bl, SC_CLOAKINGEXCEED);
  2866. }
  2867. if (sc->getSCE(SC_GOSPEL) && sc->getSCE(SC_GOSPEL)->val4 == BCT_SELF)
  2868. status_change_end(bl, SC_GOSPEL);
  2869. if (sc->getSCE(SC_PROVOKE) && sc->getSCE(SC_PROVOKE)->val4 == 1)
  2870. status_change_end(bl, SC_PROVOKE); //End infinite provoke to prevent exploit
  2871. }
  2872. switch( bl->type ) {
  2873. case BL_PC: {
  2874. map_session_data *sd = (map_session_data*)bl;
  2875. if(sd->shadowform_id) { // If shadow target has leave the map
  2876. struct block_list *d_bl = map_id2bl(sd->shadowform_id);
  2877. if( d_bl )
  2878. status_change_end(d_bl,SC__SHADOWFORM);
  2879. }
  2880. // Leave/reject all invitations.
  2881. if(sd->chatID)
  2882. chat_leavechat(sd,0);
  2883. if(sd->trade_partner.id > 0)
  2884. trade_tradecancel(sd);
  2885. searchstore_close(*sd);
  2886. if (sd->menuskill_id != AL_TELEPORT) { //bugreport:8027
  2887. if (sd->state.storage_flag == 1)
  2888. storage_storage_quit(sd,0);
  2889. else if (sd->state.storage_flag == 2)
  2890. storage_guild_storage_quit(sd, 0);
  2891. else if (sd->state.storage_flag == 3)
  2892. storage_premiumStorage_quit(sd);
  2893. sd->state.storage_flag = 0; //Force close it when being warped.
  2894. }
  2895. if(sd->party_invite > 0)
  2896. party_reply_invite( *sd, sd->party_invite, 0 );
  2897. if(sd->guild_invite > 0)
  2898. guild_reply_invite( *sd, sd->guild_invite, 0 );
  2899. if(sd->guild_alliance > 0)
  2900. guild_reply_reqalliance(sd,sd->guild_alliance_account,0);
  2901. if(sd->menuskill_id)
  2902. sd->menuskill_id = sd->menuskill_val = 0;
  2903. if( !sd->npc_ontouch_.empty() )
  2904. npc_touchnext_areanpc(sd,true);
  2905. // Check if warping and not changing the map.
  2906. if ( sd->state.warping && !sd->state.changemap ) {
  2907. status_change_end(bl, SC_CLOAKING);
  2908. status_change_end(bl, SC_CLOAKINGEXCEED);
  2909. }
  2910. sd->npc_shopid = 0;
  2911. sd->adopt_invite = 0;
  2912. if(sd->pvp_timer != INVALID_TIMER) {
  2913. delete_timer(sd->pvp_timer,pc_calc_pvprank_timer);
  2914. sd->pvp_timer = INVALID_TIMER;
  2915. sd->pvp_rank = 0;
  2916. }
  2917. if(sd->duel_group > 0)
  2918. duel_leave(sd->duel_group, sd);
  2919. if(pc_issit(sd) && pc_setstand(sd, false))
  2920. skill_sit(sd, false);
  2921. party_send_dot_remove(sd);// minimap dot fix [Kevin]
  2922. guild_send_dot_remove(sd);
  2923. bg_send_dot_remove(sd);
  2924. if( map[bl->m].users <= 0 || sd->state.debug_remove_map ) {
  2925. // This is only place where map users is decreased, if the mobs were removed
  2926. // too soon then this function was executed too many times [FlavioJS]
  2927. if( sd->debug_file == nullptr || !(sd->state.debug_remove_map) ) {
  2928. sd->debug_file = "";
  2929. sd->debug_line = 0;
  2930. sd->debug_func = "";
  2931. }
  2932. ShowDebug("unit_remove_map: unexpected state when removing player AID/CID:%d/%d"
  2933. " (active=%d connect_new=%d rewarp=%d changemap=%d debug_remove_map=%d)"
  2934. " from map=%s (users=%d)."
  2935. " Previous call from %s:%d(%s), current call from %s:%d(%s)."
  2936. " Please report this!!!\n",
  2937. sd->status.account_id, sd->status.char_id,
  2938. sd->state.active, sd->state.connect_new, sd->state.rewarp, sd->state.changemap, sd->state.debug_remove_map,
  2939. map[bl->m].name, map[bl->m].users,
  2940. sd->debug_file, sd->debug_line, sd->debug_func, file, line, func);
  2941. }
  2942. else if (--map[bl->m].users == 0 && battle_config.dynamic_mobs)
  2943. map_removemobs(bl->m);
  2944. if( !pc_isinvisible(sd) ) // Decrement the number of active pvp players on the map
  2945. --map[bl->m].users_pvp;
  2946. if( sd->state.hpmeter_visible ) {
  2947. map[bl->m].hpmeter_visible--;
  2948. sd->state.hpmeter_visible = 0;
  2949. }
  2950. sd->state.debug_remove_map = 1; // Temporary state to track double remove_map's [FlavioJS]
  2951. sd->debug_file = file;
  2952. sd->debug_line = line;
  2953. sd->debug_func = func;
  2954. break;
  2955. }
  2956. case BL_MOB: {
  2957. struct mob_data *md = (struct mob_data*)bl;
  2958. // Drop previous target mob_slave_keep_target: no.
  2959. if (!battle_config.mob_slave_keep_target)
  2960. md->target_id=0;
  2961. // When a monster is removed from map, its spotted log is cleared
  2962. for (int32 i = 0; i < DAMAGELOG_SIZE; i++)
  2963. md->spotted_log[i] = 0;
  2964. md->attacked_id=0;
  2965. mob_setstate(*md, MSS_IDLE);
  2966. break;
  2967. }
  2968. case BL_PET: {
  2969. struct pet_data *pd = (struct pet_data*)bl;
  2970. if( pd->pet.intimate <= PET_INTIMATE_NONE && !(pd->master && !pd->master->state.active) ) {
  2971. // If logging out, this is deleted on unit_free
  2972. clif_clearunit_area( *bl, clrtype );
  2973. map_delblock(bl);
  2974. unit_free(bl,CLR_OUTSIGHT);
  2975. map_freeblock_unlock();
  2976. return 0;
  2977. }
  2978. break;
  2979. }
  2980. case BL_HOM: {
  2981. struct homun_data *hd = (struct homun_data *)bl;
  2982. ud->canact_tick = ud->canmove_tick; // It appears HOM do reset the can-act tick.
  2983. if( !hd->homunculus.intimacy && !(hd->master && !hd->master->state.active) ) {
  2984. // If logging out, this is deleted on unit_free
  2985. clif_clearunit_area( *bl, clrtype );
  2986. map_delblock(bl);
  2987. unit_free(bl,CLR_OUTSIGHT);
  2988. map_freeblock_unlock();
  2989. return 0;
  2990. }
  2991. break;
  2992. }
  2993. case BL_MER: {
  2994. s_mercenary_data *md = (s_mercenary_data *)bl;
  2995. ud->canact_tick = ud->canmove_tick;
  2996. if( mercenary_get_lifetime(md) <= 0 && !(md->master && !md->master->state.active) ) {
  2997. clif_clearunit_area( *bl, clrtype );
  2998. map_delblock(bl);
  2999. unit_free(bl,CLR_OUTSIGHT);
  3000. map_freeblock_unlock();
  3001. return 0;
  3002. }
  3003. break;
  3004. }
  3005. case BL_ELEM: {
  3006. s_elemental_data *ed = (s_elemental_data *)bl;
  3007. ud->canact_tick = ud->canmove_tick;
  3008. if( elemental_get_lifetime(ed) <= 0 && !(ed->master && !ed->master->state.active) ) {
  3009. clif_clearunit_area( *bl, clrtype );
  3010. map_delblock(bl);
  3011. unit_free(bl,CLR_OUTSIGHT);
  3012. map_freeblock_unlock();
  3013. return 0;
  3014. }
  3015. break;
  3016. }
  3017. case BL_NPC:
  3018. if (npc_remove_map( (TBL_NPC*)bl ) != 0)
  3019. return 0;
  3020. break;
  3021. default:
  3022. break;// do nothing
  3023. }
  3024. if (bl->type&(BL_CHAR|BL_PET)) {
  3025. skill_unit_move(bl,gettick(),4);
  3026. skill_cleartimerskill(bl);
  3027. }
  3028. switch (bl->type) {
  3029. case BL_NPC:
  3030. // already handled by npc_remove_map
  3031. break;
  3032. case BL_MOB:
  3033. // /BL_MOB is handled by mob_dead unless the monster is not dead.
  3034. if (status_isdead(*bl)) {
  3035. map_delblock(bl);
  3036. break;
  3037. }
  3038. [[fallthrough]];
  3039. default:
  3040. clif_clearunit_area( *bl, clrtype );
  3041. map_delblock(bl);
  3042. break;
  3043. }
  3044. map_freeblock_unlock();
  3045. return 1;
  3046. }
  3047. /**
  3048. * Refresh the area with a change in display of a unit.
  3049. * @bl: Object to update
  3050. */
  3051. void unit_refresh(struct block_list *bl, bool walking) {
  3052. nullpo_retv(bl);
  3053. if (bl->m < 0)
  3054. return;
  3055. struct map_data *mapdata = map_getmapdata(bl->m);
  3056. // Using CLR_TRICKDEAD because other flags show effects
  3057. // Probably need to use another flag or other way to refresh it
  3058. if (mapdata->users) {
  3059. clif_clearunit_area( *bl, CLR_TRICKDEAD ); // Fade out
  3060. clif_spawn(bl,walking); // Fade in
  3061. }
  3062. }
  3063. /**
  3064. * Removes units of a master when the master is removed from map
  3065. * @param sd: Player
  3066. * @param clrtype: How bl is being removed
  3067. * 0: Assume bl is being warped
  3068. * 1: Death, appropriate cleanup performed
  3069. */
  3070. void unit_remove_map_pc(map_session_data *sd, clr_type clrtype)
  3071. {
  3072. unit_remove_map(&sd->bl,clrtype);
  3073. //CLR_RESPAWN is the warp from logging out, CLR_TELEPORT is the warp from teleporting, but pets/homunc need to just 'vanish' instead of showing the warping animation.
  3074. if (clrtype == CLR_RESPAWN || clrtype == CLR_TELEPORT)
  3075. clrtype = CLR_OUTSIGHT;
  3076. if(sd->pd)
  3077. unit_remove_map(&sd->pd->bl, clrtype);
  3078. if(hom_is_active(sd->hd))
  3079. unit_remove_map(&sd->hd->bl, clrtype);
  3080. if(sd->md)
  3081. unit_remove_map(&sd->md->bl, clrtype);
  3082. if(sd->ed)
  3083. unit_remove_map(&sd->ed->bl, clrtype);
  3084. }
  3085. /**
  3086. * Frees units of a player when is removed from map
  3087. * Also free his pets/homon/mercenary/elemental/etc if he have any
  3088. * @param sd: Player
  3089. */
  3090. void unit_free_pc(map_session_data *sd)
  3091. {
  3092. if (sd->pd)
  3093. unit_free(&sd->pd->bl,CLR_OUTSIGHT);
  3094. if (sd->hd)
  3095. unit_free(&sd->hd->bl,CLR_OUTSIGHT);
  3096. if (sd->md)
  3097. unit_free(&sd->md->bl,CLR_OUTSIGHT);
  3098. if (sd->ed)
  3099. unit_free(&sd->ed->bl,CLR_OUTSIGHT);
  3100. unit_free(&sd->bl,CLR_TELEPORT);
  3101. }
  3102. /**
  3103. * Frees all related resources to the unit
  3104. * @param bl: Object being removed from map
  3105. * @param clrtype: How bl is being removed
  3106. * 0: Assume bl is being warped
  3107. * 1: Death, appropriate cleanup performed
  3108. * @return 0
  3109. */
  3110. int32 unit_free(struct block_list *bl, clr_type clrtype)
  3111. {
  3112. struct unit_data *ud = unit_bl2ud( bl );
  3113. nullpo_ret(ud);
  3114. map_freeblock_lock();
  3115. if( bl->prev ) // Players are supposed to logout with a "warp" effect.
  3116. unit_remove_map(bl, clrtype);
  3117. switch( bl->type ) {
  3118. case BL_PC: {
  3119. map_session_data *sd = (map_session_data*)bl;
  3120. int32 i;
  3121. if( status_isdead(*bl) )
  3122. pc_setrestartvalue(sd,2);
  3123. pc_delinvincibletimer(sd);
  3124. pc_delautobonus(*sd, sd->autobonus, false);
  3125. pc_delautobonus(*sd, sd->autobonus2, false);
  3126. pc_delautobonus(*sd, sd->autobonus3, false);
  3127. if( sd->followtimer != INVALID_TIMER )
  3128. pc_stop_following(sd);
  3129. if( sd->duel_invite > 0 )
  3130. duel_reject(sd->duel_invite, sd);
  3131. channel_pcquit(sd,0xF); // Leave all chan
  3132. skill_blockpc_clear(*sd); // Clear all skill cooldown related
  3133. // Notify friends that this char logged out.
  3134. if( battle_config.friend_auto_add ){
  3135. for( const s_friend& my_friend : sd->status.friends ){
  3136. // Cancel early
  3137. if( my_friend.char_id == 0 ){
  3138. break;
  3139. }
  3140. if( map_session_data* tsd = map_charid2sd( my_friend.char_id ); tsd != nullptr ){
  3141. for( const s_friend& their_friend : tsd->status.friends ){
  3142. // Cancel early
  3143. if( their_friend.char_id == 0 ){
  3144. break;
  3145. }
  3146. if( their_friend.account_id != sd->status.account_id ){
  3147. continue;
  3148. }
  3149. if( their_friend.char_id != sd->status.char_id ){
  3150. continue;
  3151. }
  3152. clif_friendslist_toggle( *tsd, their_friend, false );
  3153. break;
  3154. }
  3155. }
  3156. }
  3157. }else{
  3158. map_foreachpc( clif_friendslist_toggle_sub, sd->status.account_id, sd->status.char_id, static_cast<int32>( false ) );
  3159. }
  3160. party_send_logout(sd);
  3161. guild_send_memberinfoshort(sd,0);
  3162. pc_cleareventtimer(sd);
  3163. pc_inventory_rental_clear(sd);
  3164. pc_delspiritball(sd, sd->spiritball, 1);
  3165. pc_delspiritcharm(sd, sd->spiritcharm, sd->spiritcharm_type);
  3166. mob_removeslaves(&sd->bl);
  3167. if( sd->st && sd->st->state != RUN ) {// free attached scripts that are waiting
  3168. script_free_state(sd->st);
  3169. sd->st = nullptr;
  3170. sd->npc_id = 0;
  3171. }
  3172. if( !sd->npc_id_dynamic.empty() ){
  3173. for (const auto &it : sd->npc_id_dynamic) {
  3174. struct npc_data* nd = map_id2nd( it );
  3175. if( nd != nullptr ){
  3176. // Erase the owner first to prevent loops from npc_unload
  3177. nd->dynamicnpc.owner_char_id = 0;
  3178. // Delete the NPC
  3179. npc_unload( nd, true );
  3180. }
  3181. }
  3182. // Update NPC event database
  3183. npc_read_event_script();
  3184. sd->npc_id_dynamic.clear();
  3185. }
  3186. sd->combos.clear();
  3187. if( sd->sc_display_count ) { /* [Ind] */
  3188. for( i = 0; i < sd->sc_display_count; i++ )
  3189. ers_free(pc_sc_display_ers, sd->sc_display[i]);
  3190. sd->sc_display_count = 0;
  3191. aFree(sd->sc_display);
  3192. sd->sc_display = nullptr;
  3193. }
  3194. if( sd->quest_log != nullptr ) {
  3195. aFree(sd->quest_log);
  3196. sd->quest_log = nullptr;
  3197. sd->num_quests = sd->avail_quests = 0;
  3198. }
  3199. sd->qi_display.clear();
  3200. #if PACKETVER_MAIN_NUM >= 20150507 || PACKETVER_RE_NUM >= 20150429 || defined(PACKETVER_ZERO)
  3201. sd->hatEffects.clear();
  3202. #endif
  3203. if (sd->achievement_data.achievements)
  3204. achievement_free(sd);
  3205. // Clearing...
  3206. if (sd->bonus_script.head)
  3207. pc_bonus_script_clear(sd, BSF_REM_ALL);
  3208. skill_clear_unitgroup(bl);
  3209. status_change_clear(bl,1);
  3210. // Do not call the destructor here, it will be done in chrif_auth_delete
  3211. // sd->~map_session_data();
  3212. break;
  3213. }
  3214. case BL_PET: {
  3215. struct pet_data *pd = (struct pet_data*)bl;
  3216. map_session_data *sd = pd->master;
  3217. pet_delautobonus(*sd, pd->autobonus, false);
  3218. pet_delautobonus(*sd, pd->autobonus2, false);
  3219. pet_delautobonus(*sd, pd->autobonus3, false);
  3220. pet_hungry_timer_delete(pd);
  3221. pet_clear_support_bonuses(sd);
  3222. if( pd->pet.intimate > PET_INTIMATE_NONE )
  3223. intif_save_petdata(pd->pet.account_id,&pd->pet);
  3224. else { // Remove pet.
  3225. intif_delete_petdata(pd->pet.pet_id);
  3226. if (sd)
  3227. sd->status.pet_id = 0;
  3228. }
  3229. if( sd )
  3230. sd->pd = nullptr;
  3231. pd->master = nullptr;
  3232. skill_clear_unitgroup(bl);
  3233. status_change_clear(bl,1);
  3234. pd->~pet_data();
  3235. break;
  3236. }
  3237. case BL_MOB: {
  3238. struct mob_data *md = (struct mob_data*)bl;
  3239. mob_free_dynamic_viewdata( md );
  3240. if( md->spawn_timer != INVALID_TIMER ) {
  3241. delete_timer(md->spawn_timer,mob_delayspawn);
  3242. md->spawn_timer = INVALID_TIMER;
  3243. }
  3244. if( md->deletetimer != INVALID_TIMER ) {
  3245. delete_timer(md->deletetimer,mob_timer_delete);
  3246. md->deletetimer = INVALID_TIMER;
  3247. }
  3248. if (md->lootitems) {
  3249. aFree(md->lootitems);
  3250. md->lootitems = nullptr;
  3251. }
  3252. if( md->guardian_data ) {
  3253. std::shared_ptr<guild_castle> gc = md->guardian_data->castle;
  3254. if( md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
  3255. gc->guardian[md->guardian_data->number].id = 0;
  3256. else {
  3257. int32 i;
  3258. ARR_FIND(0, gc->temp_guardians_max, i, gc->temp_guardians[i] == md->bl.id);
  3259. if( i < gc->temp_guardians_max )
  3260. gc->temp_guardians[i] = 0;
  3261. }
  3262. md->guardian_data->~guardian_data();
  3263. aFree(md->guardian_data);
  3264. md->guardian_data = nullptr;
  3265. }
  3266. if( md->spawn ) {
  3267. md->spawn->active--;
  3268. if( !md->spawn->state.dynamic ) { // Permanently remove the mob
  3269. if( --md->spawn->num == 0 ) { // Last freed mob is responsible for deallocating the group's spawn data.
  3270. aFree(md->spawn);
  3271. md->spawn = nullptr;
  3272. }
  3273. }
  3274. }
  3275. if( md->base_status) {
  3276. aFree(md->base_status);
  3277. md->base_status = nullptr;
  3278. }
  3279. skill_clear_unitgroup(bl);
  3280. status_change_clear(bl,1);
  3281. if( mob_is_clone(md->mob_id) )
  3282. mob_clone_delete(md);
  3283. if( md->tomb_nid )
  3284. mvptomb_destroy(md);
  3285. md->~mob_data();
  3286. break;
  3287. }
  3288. case BL_HOM:
  3289. {
  3290. struct homun_data *hd = (TBL_HOM*)bl;
  3291. map_session_data *sd = hd->master;
  3292. hom_hungry_timer_delete(hd);
  3293. if( hd->homunculus.intimacy > 0 )
  3294. hom_save(hd);
  3295. else {
  3296. intif_homunculus_requestdelete(hd->homunculus.hom_id);
  3297. if( sd )
  3298. sd->status.hom_id = 0;
  3299. #ifdef RENEWAL
  3300. status_change_end(&sd->bl, SC_HOMUN_TIME);
  3301. #endif
  3302. }
  3303. skill_blockhomun_clear(*hd); // Clear all skill cooldown related
  3304. if( sd )
  3305. sd->hd = nullptr;
  3306. hd->master = nullptr;
  3307. skill_clear_unitgroup(bl);
  3308. status_change_clear(bl,1);
  3309. hd->~homun_data();
  3310. break;
  3311. }
  3312. case BL_MER: {
  3313. s_mercenary_data *md = (TBL_MER*)bl;
  3314. map_session_data *sd = md->master;
  3315. if( mercenary_get_lifetime(md) > 0 )
  3316. mercenary_save(md);
  3317. else {
  3318. intif_mercenary_delete(md->mercenary.mercenary_id);
  3319. if( sd )
  3320. sd->status.mer_id = 0;
  3321. }
  3322. if( sd )
  3323. sd->md = nullptr;
  3324. skill_blockmerc_clear(*md); // Clear all skill cooldown related
  3325. mercenary_contract_stop(md);
  3326. md->master = nullptr;
  3327. skill_clear_unitgroup(bl);
  3328. status_change_clear(bl,1);
  3329. md->~s_mercenary_data();
  3330. break;
  3331. }
  3332. case BL_ELEM: {
  3333. s_elemental_data *ed = (TBL_ELEM*)bl;
  3334. map_session_data *sd = ed->master;
  3335. if( elemental_get_lifetime(ed) > 0 )
  3336. elemental_save(ed);
  3337. else {
  3338. intif_elemental_delete(ed->elemental.elemental_id);
  3339. if( sd )
  3340. sd->status.ele_id = 0;
  3341. }
  3342. if( sd )
  3343. sd->ed = nullptr;
  3344. elemental_summon_stop(ed);
  3345. ed->master = nullptr;
  3346. skill_clear_unitgroup(bl);
  3347. status_change_clear(bl,1);
  3348. ed->~s_elemental_data();
  3349. break;
  3350. }
  3351. }
  3352. map_deliddb(bl);
  3353. if( bl->type != BL_PC ) // Players are handled by map_quit
  3354. map_freeblock(bl);
  3355. map_freeblock_unlock();
  3356. return 0;
  3357. }
  3358. static TIMER_FUNC(unit_shadowscar_timer) {
  3359. block_list *bl = map_id2bl(id);
  3360. if (bl == nullptr)
  3361. return 1;
  3362. unit_data *ud = unit_bl2ud(bl);
  3363. if (ud == nullptr)
  3364. return 1;
  3365. std::vector<int32>::iterator it = ud->shadow_scar_timer.begin();
  3366. while (it != ud->shadow_scar_timer.end()) {
  3367. if (*it == tid) {
  3368. ud->shadow_scar_timer.erase(it);
  3369. break;
  3370. }
  3371. it++;
  3372. }
  3373. if (ud->shadow_scar_timer.empty())
  3374. status_change_end( bl, SC_SHADOW_SCAR );
  3375. return 0;
  3376. }
  3377. /**
  3378. * Adds a Shadow Scar to unit for 'interval' ms.
  3379. * @param ud: Unit data
  3380. * @param interval: Duration
  3381. */
  3382. void unit_addshadowscar(unit_data &ud, int32 interval) {
  3383. if (ud.shadow_scar_timer.size() >= MAX_SHADOW_SCAR) {
  3384. ShowWarning("unit_addshadowscar: Unit %s (%d) has reached the maximum amount of Shadow Scars (%d).\n", status_get_name(*ud.bl), ud.bl->id, MAX_SHADOW_SCAR);
  3385. return;
  3386. }
  3387. ud.shadow_scar_timer.push_back(add_timer(gettick() + interval, unit_shadowscar_timer, ud.bl->id, 0));
  3388. status_change *sc = status_get_sc(ud.bl);
  3389. if (sc != nullptr) {
  3390. if (sc->getSCE(SC_SHADOW_SCAR) != nullptr) {
  3391. sc->getSCE(SC_SHADOW_SCAR)->val1 = static_cast<int32>(ud.shadow_scar_timer.size());
  3392. } else {
  3393. sc_start(ud.bl, ud.bl, SC_SHADOW_SCAR, 100, 1, INFINITE_TICK);
  3394. }
  3395. clif_enchantingshadow_spirit(ud);
  3396. }
  3397. }
  3398. /**
  3399. * Initialization function for unit on map start
  3400. * called in map::do_init
  3401. */
  3402. void do_init_unit(void){
  3403. add_timer_func_list(unit_attack_timer, "unit_attack_timer");
  3404. add_timer_func_list(unit_walktoxy_timer,"unit_walktoxy_timer");
  3405. add_timer_func_list(unit_walktobl_sub, "unit_walktobl_sub");
  3406. add_timer_func_list(unit_delay_walktoxy_timer,"unit_delay_walktoxy_timer");
  3407. add_timer_func_list(unit_delay_walktobl_timer,"unit_delay_walktobl_timer");
  3408. add_timer_func_list(unit_teleport_timer,"unit_teleport_timer");
  3409. add_timer_func_list(unit_step_timer,"unit_step_timer");
  3410. add_timer_func_list(unit_shadowscar_timer, "unit_shadowscar_timer");
  3411. }
  3412. /**
  3413. * Unit module destructor, (thing to do before closing the module)
  3414. * called in map::do_final
  3415. * @return 0
  3416. */
  3417. void do_final_unit(void){
  3418. // Nothing to do
  3419. }