L2Character.java 196 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961
  1. /*
  2. * Copyright (C) 2004-2014 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.model.actor;
  20. import static com.l2jserver.gameserver.ai.CtrlIntention.AI_INTENTION_ACTIVE;
  21. import static com.l2jserver.gameserver.ai.CtrlIntention.AI_INTENTION_ATTACK;
  22. import static com.l2jserver.gameserver.ai.CtrlIntention.AI_INTENTION_FOLLOW;
  23. import java.util.ArrayList;
  24. import java.util.Collection;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Queue;
  28. import java.util.Set;
  29. import java.util.concurrent.ConcurrentHashMap;
  30. import java.util.concurrent.Future;
  31. import java.util.concurrent.LinkedBlockingDeque;
  32. import java.util.concurrent.locks.ReentrantLock;
  33. import java.util.logging.Level;
  34. import java.util.logging.Logger;
  35. import javolution.util.FastList;
  36. import javolution.util.FastMap;
  37. import javolution.util.WeakFastSet;
  38. import com.l2jserver.Config;
  39. import com.l2jserver.gameserver.GameTimeController;
  40. import com.l2jserver.gameserver.GeoData;
  41. import com.l2jserver.gameserver.ThreadPoolManager;
  42. import com.l2jserver.gameserver.ai.CtrlEvent;
  43. import com.l2jserver.gameserver.ai.CtrlIntention;
  44. import com.l2jserver.gameserver.ai.L2AttackableAI;
  45. import com.l2jserver.gameserver.ai.L2CharacterAI;
  46. import com.l2jserver.gameserver.datatables.CategoryData;
  47. import com.l2jserver.gameserver.datatables.DoorTable;
  48. import com.l2jserver.gameserver.datatables.ItemTable;
  49. import com.l2jserver.gameserver.enums.CategoryType;
  50. import com.l2jserver.gameserver.enums.InstanceType;
  51. import com.l2jserver.gameserver.enums.Race;
  52. import com.l2jserver.gameserver.enums.ShotType;
  53. import com.l2jserver.gameserver.enums.Team;
  54. import com.l2jserver.gameserver.instancemanager.InstanceManager;
  55. import com.l2jserver.gameserver.instancemanager.MapRegionManager;
  56. import com.l2jserver.gameserver.instancemanager.TerritoryWarManager;
  57. import com.l2jserver.gameserver.model.CharEffectList;
  58. import com.l2jserver.gameserver.model.L2AccessLevel;
  59. import com.l2jserver.gameserver.model.L2Clan;
  60. import com.l2jserver.gameserver.model.L2Object;
  61. import com.l2jserver.gameserver.model.L2Party;
  62. import com.l2jserver.gameserver.model.L2World;
  63. import com.l2jserver.gameserver.model.L2WorldRegion;
  64. import com.l2jserver.gameserver.model.Location;
  65. import com.l2jserver.gameserver.model.PcCondOverride;
  66. import com.l2jserver.gameserver.model.TeleportWhereType;
  67. import com.l2jserver.gameserver.model.TimeStamp;
  68. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  69. import com.l2jserver.gameserver.model.actor.instance.L2PetInstance;
  70. import com.l2jserver.gameserver.model.actor.instance.L2RiftInvaderInstance;
  71. import com.l2jserver.gameserver.model.actor.knownlist.CharKnownList;
  72. import com.l2jserver.gameserver.model.actor.stat.CharStat;
  73. import com.l2jserver.gameserver.model.actor.status.CharStatus;
  74. import com.l2jserver.gameserver.model.actor.tasks.character.FlyToLocationTask;
  75. import com.l2jserver.gameserver.model.actor.tasks.character.HitTask;
  76. import com.l2jserver.gameserver.model.actor.tasks.character.MagicUseTask;
  77. import com.l2jserver.gameserver.model.actor.tasks.character.NotifyAITask;
  78. import com.l2jserver.gameserver.model.actor.tasks.character.QueuedMagicUseTask;
  79. import com.l2jserver.gameserver.model.actor.tasks.character.UsePotionTask;
  80. import com.l2jserver.gameserver.model.actor.templates.L2CharTemplate;
  81. import com.l2jserver.gameserver.model.actor.transform.Transform;
  82. import com.l2jserver.gameserver.model.actor.transform.TransformTemplate;
  83. import com.l2jserver.gameserver.model.effects.EffectFlag;
  84. import com.l2jserver.gameserver.model.effects.L2EffectType;
  85. import com.l2jserver.gameserver.model.entity.Instance;
  86. import com.l2jserver.gameserver.model.events.Containers;
  87. import com.l2jserver.gameserver.model.events.EventDispatcher;
  88. import com.l2jserver.gameserver.model.events.EventType;
  89. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureAttack;
  90. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureAttackAvoid;
  91. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureAttacked;
  92. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureDamageDealt;
  93. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureDamageReceived;
  94. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureKill;
  95. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureSkillUse;
  96. import com.l2jserver.gameserver.model.events.impl.character.OnCreatureTeleported;
  97. import com.l2jserver.gameserver.model.events.impl.character.npc.OnNpcSkillSee;
  98. import com.l2jserver.gameserver.model.events.listeners.AbstractEventListener;
  99. import com.l2jserver.gameserver.model.events.returns.TerminateReturn;
  100. import com.l2jserver.gameserver.model.holders.InvulSkillHolder;
  101. import com.l2jserver.gameserver.model.holders.SkillHolder;
  102. import com.l2jserver.gameserver.model.holders.SkillUseHolder;
  103. import com.l2jserver.gameserver.model.interfaces.IDeletable;
  104. import com.l2jserver.gameserver.model.interfaces.ILocational;
  105. import com.l2jserver.gameserver.model.interfaces.ISkillsHolder;
  106. import com.l2jserver.gameserver.model.itemcontainer.Inventory;
  107. import com.l2jserver.gameserver.model.items.L2Item;
  108. import com.l2jserver.gameserver.model.items.L2Weapon;
  109. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  110. import com.l2jserver.gameserver.model.items.type.WeaponType;
  111. import com.l2jserver.gameserver.model.options.OptionsSkillHolder;
  112. import com.l2jserver.gameserver.model.options.OptionsSkillType;
  113. import com.l2jserver.gameserver.model.skills.AbnormalType;
  114. import com.l2jserver.gameserver.model.skills.AbnormalVisualEffect;
  115. import com.l2jserver.gameserver.model.skills.BuffInfo;
  116. import com.l2jserver.gameserver.model.skills.CommonSkill;
  117. import com.l2jserver.gameserver.model.skills.EffectScope;
  118. import com.l2jserver.gameserver.model.skills.Skill;
  119. import com.l2jserver.gameserver.model.skills.SkillChannelized;
  120. import com.l2jserver.gameserver.model.skills.SkillChannelizer;
  121. import com.l2jserver.gameserver.model.skills.targets.L2TargetType;
  122. import com.l2jserver.gameserver.model.stats.BaseStats;
  123. import com.l2jserver.gameserver.model.stats.Calculator;
  124. import com.l2jserver.gameserver.model.stats.Formulas;
  125. import com.l2jserver.gameserver.model.stats.Stats;
  126. import com.l2jserver.gameserver.model.stats.functions.AbstractFunction;
  127. import com.l2jserver.gameserver.model.zone.ZoneId;
  128. import com.l2jserver.gameserver.network.SystemMessageId;
  129. import com.l2jserver.gameserver.network.serverpackets.AbstractNpcInfo;
  130. import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
  131. import com.l2jserver.gameserver.network.serverpackets.Attack;
  132. import com.l2jserver.gameserver.network.serverpackets.ChangeMoveType;
  133. import com.l2jserver.gameserver.network.serverpackets.ChangeWaitType;
  134. import com.l2jserver.gameserver.network.serverpackets.ExRotation;
  135. import com.l2jserver.gameserver.network.serverpackets.L2GameServerPacket;
  136. import com.l2jserver.gameserver.network.serverpackets.MagicSkillCanceld;
  137. import com.l2jserver.gameserver.network.serverpackets.MagicSkillLaunched;
  138. import com.l2jserver.gameserver.network.serverpackets.MagicSkillUse;
  139. import com.l2jserver.gameserver.network.serverpackets.MoveToLocation;
  140. import com.l2jserver.gameserver.network.serverpackets.Revive;
  141. import com.l2jserver.gameserver.network.serverpackets.ServerObjectInfo;
  142. import com.l2jserver.gameserver.network.serverpackets.SetupGauge;
  143. import com.l2jserver.gameserver.network.serverpackets.SocialAction;
  144. import com.l2jserver.gameserver.network.serverpackets.StatusUpdate;
  145. import com.l2jserver.gameserver.network.serverpackets.StopMove;
  146. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  147. import com.l2jserver.gameserver.network.serverpackets.TeleportToLocation;
  148. import com.l2jserver.gameserver.pathfinding.AbstractNodeLoc;
  149. import com.l2jserver.gameserver.pathfinding.PathFinding;
  150. import com.l2jserver.gameserver.taskmanager.AttackStanceTaskManager;
  151. import com.l2jserver.gameserver.util.Util;
  152. import com.l2jserver.util.EmptyQueue;
  153. import com.l2jserver.util.Rnd;
  154. /**
  155. * Mother class of all character objects of the world (PC, NPC...)<br>
  156. * L2Character:<br>
  157. * <ul>
  158. * <li>L2DoorInstance</li>
  159. * <li>L2Playable</li>
  160. * <li>L2Npc</li>
  161. * <li>L2StaticObjectInstance</li>
  162. * <li>L2Trap</li>
  163. * <li>L2Vehicle</li>
  164. * </ul>
  165. * <br>
  166. * <b>Concept of L2CharTemplate:</b><br>
  167. * Each L2Character owns generic and static properties (ex : all Keltir have the same number of HP...).<br>
  168. * All of those properties are stored in a different template for each type of L2Character.<br>
  169. * Each template is loaded once in the server cache memory (reduce memory use).<br>
  170. * When a new instance of L2Character is spawned, server just create a link between the instance and the template.<br>
  171. * This link is stored in {@link #_template}
  172. * @version $Revision: 1.53.2.45.2.34 $ $Date: 2005/04/11 10:06:08 $
  173. */
  174. public abstract class L2Character extends L2Object implements ISkillsHolder, IDeletable
  175. {
  176. public static final Logger _log = Logger.getLogger(L2Character.class.getName());
  177. private volatile Set<L2Character> _attackByList;
  178. private volatile boolean _isCastingNow = false;
  179. private volatile boolean _isCastingSimultaneouslyNow = false;
  180. private Skill _lastSkillCast;
  181. private Skill _lastSimultaneousSkillCast;
  182. private boolean _isDead = false;
  183. private boolean _isImmobilized = false;
  184. private boolean _isOverloaded = false; // the char is carrying too much
  185. private boolean _isParalyzed = false;
  186. private boolean _isPendingRevive = false;
  187. private boolean _isRunning = false;
  188. private boolean _isNoRndWalk = false; // Is no random walk
  189. protected boolean _showSummonAnimation = false;
  190. protected boolean _isTeleporting = false;
  191. private boolean _isInvul = false;
  192. private boolean _isMortal = true; // Char will die when HP decreased to 0
  193. private boolean _isFlying = false;
  194. private CharStat _stat;
  195. private CharStatus _status;
  196. private L2CharTemplate _template; // The link on the L2CharTemplate object containing generic and static properties of this L2Character type (ex : Max HP, Speed...)
  197. private String _title;
  198. public static final double MAX_HP_BAR_PX = 352.0;
  199. private double _hpUpdateIncCheck = .0;
  200. private double _hpUpdateDecCheck = .0;
  201. private double _hpUpdateInterval = .0;
  202. /** Table of Calculators containing all used calculator */
  203. private Calculator[] _calculators;
  204. /** Map containing all skills of this character. */
  205. private final Map<Integer, Skill> _skills = new FastMap<Integer, Skill>().shared();
  206. /** Map containing the skill reuse time stamps. */
  207. private volatile Map<Integer, TimeStamp> _reuseTimeStampsSkills = null;
  208. /** Map containing the item reuse time stamps. */
  209. private volatile Map<Integer, TimeStamp> _reuseTimeStampsItems = null;
  210. /** Map containing all the disabled skills. */
  211. private volatile Map<Integer, Long> _disabledSkills = null;
  212. private boolean _allSkillsDisabled;
  213. private final byte[] _zones = new byte[ZoneId.getZoneCount()];
  214. protected byte _zoneValidateCounter = 4;
  215. private L2Character _debugger = null;
  216. private final ReentrantLock _teleportLock = new ReentrantLock();
  217. private final ReentrantLock _attackLock = new ReentrantLock();
  218. private Team _team = Team.NONE;
  219. protected long _exceptions = 0L;
  220. private boolean _lethalable = true;
  221. private volatile Map<Integer, OptionsSkillHolder> _triggerSkills;
  222. private volatile Map<Integer, InvulSkillHolder> _invulAgainst;
  223. /** Creatures effect list. */
  224. private final CharEffectList _effectList = new CharEffectList(this);
  225. /** The character that summons this character. */
  226. private L2Character _summoner = null;
  227. private SkillChannelizer _channelizer = null;
  228. private SkillChannelized _channelized = null;
  229. /** Map 32 bits, containing all abnormal visual effects in progress. */
  230. private int _abnormalVisualEffects;
  231. /** Map 32 bits, containing all special abnormal visual effects in progress. */
  232. private int _abnormalVisualEffectsSpecial;
  233. /** Map 32 bits, containing all event abnormal visual effects in progress. */
  234. private int _abnormalVisualEffectsEvent;
  235. /** Movement data of this L2Character */
  236. protected MoveData _move;
  237. /** This creature's target. */
  238. private L2Object _target;
  239. // set by the start of attack, in game ticks
  240. private volatile long _attackEndTime;
  241. private int _disableBowAttackEndTime;
  242. private int _disableCrossBowAttackEndTime;
  243. private int _castInterruptTime;
  244. /** Table of calculators containing all standard NPC calculator (ex : ACCURACY_COMBAT, EVASION_RATE) */
  245. private static final Calculator[] NPC_STD_CALCULATOR = Formulas.getStdNPCCalculators();
  246. private volatile L2CharacterAI _ai = null;
  247. /** Future Skill Cast */
  248. protected Future<?> _skillCast;
  249. protected Future<?> _skillCast2;
  250. public final CharEffectList getEffectList()
  251. {
  252. return _effectList;
  253. }
  254. /**
  255. * Verify if this character is under debug.
  256. * @return {@code true} if this character is under debug, {@code false} otherwise
  257. */
  258. public boolean isDebug()
  259. {
  260. return _debugger != null;
  261. }
  262. /**
  263. * Sets character instance, to which debug packets will be send.
  264. * @param debugger the character debugging this character
  265. */
  266. public void setDebug(L2Character debugger)
  267. {
  268. _debugger = debugger;
  269. }
  270. /**
  271. * Send debug packet.
  272. * @param pkt
  273. */
  274. public void sendDebugPacket(L2GameServerPacket pkt)
  275. {
  276. if (_debugger != null)
  277. {
  278. _debugger.sendPacket(pkt);
  279. }
  280. }
  281. /**
  282. * Send debug text string
  283. * @param msg
  284. */
  285. public void sendDebugMessage(String msg)
  286. {
  287. if (_debugger != null)
  288. {
  289. _debugger.sendMessage(msg);
  290. }
  291. }
  292. /**
  293. * @return character inventory, default null, overridden in L2Playable types and in L2NPcInstance
  294. */
  295. public Inventory getInventory()
  296. {
  297. return null;
  298. }
  299. public boolean destroyItemByItemId(String process, int itemId, long count, L2Object reference, boolean sendMessage)
  300. {
  301. // Default: NPCs consume virtual items for their skills
  302. // TODO: should be logged if even happens.. should be false
  303. return true;
  304. }
  305. public boolean destroyItem(String process, int objectId, long count, L2Object reference, boolean sendMessage)
  306. {
  307. // Default: NPCs consume virtual items for their skills
  308. // TODO: should be logged if even happens.. should be false
  309. return true;
  310. }
  311. /**
  312. * Check if the character is in the given zone Id.
  313. * @param zone the zone Id to check
  314. * @return {code true} if the character is in that zone
  315. */
  316. @Override
  317. public final boolean isInsideZone(ZoneId zone)
  318. {
  319. Instance instance = InstanceManager.getInstance().getInstance(getInstanceId());
  320. switch (zone)
  321. {
  322. case PVP:
  323. if ((instance != null) && instance.isPvPInstance())
  324. {
  325. return true;
  326. }
  327. return (_zones[ZoneId.PVP.ordinal()] > 0) && (_zones[ZoneId.PEACE.ordinal()] == 0);
  328. case PEACE:
  329. if ((instance != null) && instance.isPvPInstance())
  330. {
  331. return false;
  332. }
  333. }
  334. return _zones[zone.ordinal()] > 0;
  335. }
  336. /**
  337. * @param zone
  338. * @param state
  339. */
  340. public final void setInsideZone(ZoneId zone, final boolean state)
  341. {
  342. synchronized (_zones)
  343. {
  344. if (state)
  345. {
  346. _zones[zone.ordinal()]++;
  347. }
  348. else if (_zones[zone.ordinal()] > 0)
  349. {
  350. _zones[zone.ordinal()]--;
  351. }
  352. }
  353. }
  354. /**
  355. * This will return true if the player is transformed,<br>
  356. * but if the player is not transformed it will return false.
  357. * @return transformation status
  358. */
  359. public boolean isTransformed()
  360. {
  361. return false;
  362. }
  363. public Transform getTransformation()
  364. {
  365. return null;
  366. }
  367. /**
  368. * This will untransform a player if they are an instance of L2Pcinstance and if they are transformed.
  369. */
  370. public void untransform()
  371. {
  372. // Just a place holder
  373. }
  374. /**
  375. * This will return true if the player is GM,<br>
  376. * but if the player is not GM it will return false.
  377. * @return GM status
  378. */
  379. public boolean isGM()
  380. {
  381. return false;
  382. }
  383. /**
  384. * Overridden in L2PcInstance.
  385. * @return the access level.
  386. */
  387. public L2AccessLevel getAccessLevel()
  388. {
  389. return null;
  390. }
  391. /**
  392. * Constructor of L2Character.<br>
  393. * <B><U>Concept</U>:</B><br>
  394. * Each L2Character owns generic and static properties (ex : all Keltir have the same number of HP...).<br>
  395. * All of those properties are stored in a different template for each type of L2Character. Each template is loaded once in the server cache memory (reduce memory use).<br>
  396. * When a new instance of L2Character is spawned, server just create a link between the instance and the template This link is stored in <B>_template</B><br>
  397. * <B><U> Actions</U>:</B>
  398. * <ul>
  399. * <li>Set the _template of the L2Character</li>
  400. * <li>Set _overloaded to false (the character can take more items)</li>
  401. * <li>If L2Character is a L2NPCInstance, copy skills from template to object</li>
  402. * <li>If L2Character is a L2NPCInstance, link _calculators to NPC_STD_CALCULATOR</li>
  403. * <li>If L2Character is NOT a L2NPCInstance, create an empty _skills slot</li>
  404. * <li>If L2Character is a L2PcInstance or L2Summon, copy basic Calculator set to object</li>
  405. * </ul>
  406. * @param objectId Identifier of the object to initialized
  407. * @param template The L2CharTemplate to apply to the object
  408. */
  409. public L2Character(int objectId, L2CharTemplate template)
  410. {
  411. super(objectId);
  412. if (template == null)
  413. {
  414. throw new NullPointerException("Template is null!");
  415. }
  416. setInstanceType(InstanceType.L2Character);
  417. initCharStat();
  418. initCharStatus();
  419. // Set its template to the new L2Character
  420. _template = template;
  421. if (isDoor())
  422. {
  423. _calculators = Formulas.getStdDoorCalculators();
  424. }
  425. else if (isNpc())
  426. {
  427. // Copy the Standard Calculators of the L2NPCInstance in _calculators
  428. _calculators = NPC_STD_CALCULATOR;
  429. // Copy the skills of the L2NPCInstance from its template to the L2Character Instance
  430. // The skills list can be affected by spell effects so it's necessary to make a copy
  431. // to avoid that a spell affecting a L2NpcInstance, affects others L2NPCInstance of the same type too.
  432. for (Skill skill : template.getSkills().values())
  433. {
  434. addSkill(skill);
  435. }
  436. }
  437. else
  438. {
  439. // If L2Character is a L2PcInstance or a L2Summon, create the basic calculator set
  440. _calculators = new Calculator[Stats.NUM_STATS];
  441. if (isSummon())
  442. {
  443. // Copy the skills of the L2Summon from its template to the L2Character Instance
  444. // The skills list can be affected by spell effects so it's necessary to make a copy
  445. // to avoid that a spell affecting a L2Summon, affects others L2Summon of the same type too.
  446. for (Skill skill : template.getSkills().values())
  447. {
  448. addSkill(skill);
  449. }
  450. }
  451. Formulas.addFuncsToNewCharacter(this);
  452. }
  453. setIsInvul(true);
  454. }
  455. protected void initCharStatusUpdateValues()
  456. {
  457. _hpUpdateIncCheck = getMaxHp();
  458. _hpUpdateInterval = _hpUpdateIncCheck / MAX_HP_BAR_PX;
  459. _hpUpdateDecCheck = _hpUpdateIncCheck - _hpUpdateInterval;
  460. }
  461. /**
  462. * Remove the L2Character from the world when the decay task is launched.<br>
  463. * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method DOESN'T REMOVE the object from _allObjects of L2World </B></FONT><BR>
  464. * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method DOESN'T SEND Server->Client packets to players</B></FONT>
  465. */
  466. public void onDecay()
  467. {
  468. decayMe();
  469. final L2WorldRegion reg = getWorldRegion();
  470. if (reg != null)
  471. {
  472. reg.removeFromZones(this);
  473. }
  474. }
  475. @Override
  476. public void onSpawn()
  477. {
  478. super.onSpawn();
  479. revalidateZone(true);
  480. }
  481. public void onTeleported()
  482. {
  483. if (!_teleportLock.tryLock())
  484. {
  485. return;
  486. }
  487. try
  488. {
  489. if (!isTeleporting())
  490. {
  491. return;
  492. }
  493. spawnMe(getX(), getY(), getZ());
  494. setIsTeleporting(false);
  495. EventDispatcher.getInstance().notifyEventAsync(new OnCreatureTeleported(this), this);
  496. }
  497. finally
  498. {
  499. _teleportLock.unlock();
  500. }
  501. }
  502. /**
  503. * Add L2Character instance that is attacking to the attacker list.
  504. * @param player The L2Character that attacks this one
  505. */
  506. public void addAttackerToAttackByList(L2Character player)
  507. {
  508. // DS: moved to L2Attackable
  509. }
  510. /**
  511. * Send a packet to the L2Character AND to all L2PcInstance in the _KnownPlayers of the L2Character.<br>
  512. * <B><U>Concept</U>:</B><br>
  513. * L2PcInstance in the detection area of the L2Character are identified in <B>_knownPlayers</B>.<br>
  514. * In order to inform other players of state modification on the L2Character, server just need to go through _knownPlayers to send Server->Client Packet
  515. * @param mov
  516. */
  517. public void broadcastPacket(L2GameServerPacket mov)
  518. {
  519. mov.setInvisible(isInvisible());
  520. Collection<L2PcInstance> plrs = getKnownList().getKnownPlayers().values();
  521. for (L2PcInstance player : plrs)
  522. {
  523. if (player != null)
  524. {
  525. player.sendPacket(mov);
  526. }
  527. }
  528. }
  529. /**
  530. * Send a packet to the L2Character AND to all L2PcInstance in the radius (max knownlist radius) from the L2Character.<br>
  531. * <B><U>Concept</U>:</B><br>
  532. * L2PcInstance in the detection area of the L2Character are identified in <B>_knownPlayers</B>.<br>
  533. * In order to inform other players of state modification on the L2Character, server just need to go through _knownPlayers to send Server->Client Packet
  534. * @param mov
  535. * @param radiusInKnownlist
  536. */
  537. public void broadcastPacket(L2GameServerPacket mov, int radiusInKnownlist)
  538. {
  539. mov.setInvisible(isInvisible());
  540. Collection<L2PcInstance> plrs = getKnownList().getKnownPlayers().values();
  541. for (L2PcInstance player : plrs)
  542. {
  543. if ((player != null) && isInsideRadius(player, radiusInKnownlist, false, false))
  544. {
  545. player.sendPacket(mov);
  546. }
  547. }
  548. }
  549. /**
  550. * @return true if hp update should be done, false if not
  551. */
  552. protected boolean needHpUpdate()
  553. {
  554. double currentHp = getCurrentHp();
  555. double maxHp = getMaxHp();
  556. if ((currentHp <= 1.0) || (maxHp < MAX_HP_BAR_PX))
  557. {
  558. return true;
  559. }
  560. if ((currentHp < _hpUpdateDecCheck) || (Math.abs(currentHp - _hpUpdateDecCheck) <= 1e-6) || (currentHp > _hpUpdateIncCheck) || (Math.abs(currentHp - _hpUpdateIncCheck) <= 1e-6))
  561. {
  562. if (Math.abs(currentHp - maxHp) <= 1e-6)
  563. {
  564. _hpUpdateIncCheck = currentHp + 1;
  565. _hpUpdateDecCheck = currentHp - _hpUpdateInterval;
  566. }
  567. else
  568. {
  569. double doubleMulti = currentHp / _hpUpdateInterval;
  570. int intMulti = (int) doubleMulti;
  571. _hpUpdateDecCheck = _hpUpdateInterval * (doubleMulti < intMulti ? intMulti-- : intMulti);
  572. _hpUpdateIncCheck = _hpUpdateDecCheck + _hpUpdateInterval;
  573. }
  574. return true;
  575. }
  576. return false;
  577. }
  578. /**
  579. * Send the Server->Client packet StatusUpdate with current HP and MP to all other L2PcInstance to inform.<br>
  580. * <B><U>Actions</U>:</B>
  581. * <ul>
  582. * <li>Create the Server->Client packet StatusUpdate with current HP and MP</li>
  583. * <li>Send the Server->Client packet StatusUpdate with current HP and MP to all L2Character called _statusListener that must be informed of HP/MP updates of this L2Character</li>
  584. * </ul>
  585. * <FONT COLOR=#FF0000><B><U>Caution</U>: This method DOESN'T SEND CP information</B></FONT>
  586. */
  587. public void broadcastStatusUpdate()
  588. {
  589. if (getStatus().getStatusListener().isEmpty() || !needHpUpdate())
  590. {
  591. return;
  592. }
  593. // Create the Server->Client packet StatusUpdate with current HP
  594. StatusUpdate su = new StatusUpdate(this);
  595. su.addAttribute(StatusUpdate.MAX_HP, getMaxHp());
  596. su.addAttribute(StatusUpdate.CUR_HP, (int) getCurrentHp());
  597. // Go through the StatusListener
  598. // Send the Server->Client packet StatusUpdate with current HP and MP
  599. for (L2Character temp : getStatus().getStatusListener())
  600. {
  601. if (temp != null)
  602. {
  603. temp.sendPacket(su);
  604. }
  605. }
  606. }
  607. /**
  608. * @param text
  609. */
  610. public void sendMessage(String text)
  611. {
  612. // default implementation
  613. }
  614. /**
  615. * Teleport a L2Character and its pet if necessary.<br>
  616. * <B><U>Actions</U>:</B>
  617. * <ul>
  618. * <li>Stop the movement of the L2Character</li>
  619. * <li>Set the x,y,z position of the L2Object and if necessary modify its _worldRegion</li>
  620. * <li>Send a Server->Client packet TeleportToLocationt to the L2Character AND to all L2PcInstance in its _KnownPlayers</li>
  621. * <li>Modify the position of the pet if necessary</li>
  622. * </ul>
  623. * @param x
  624. * @param y
  625. * @param z
  626. * @param heading
  627. * @param instanceId
  628. * @param randomOffset
  629. */
  630. public void teleToLocation(int x, int y, int z, int heading, int instanceId, int randomOffset)
  631. {
  632. setInstanceId(instanceId);
  633. if (_isPendingRevive)
  634. {
  635. doRevive();
  636. }
  637. stopMove(null, false);
  638. abortAttack();
  639. abortCast();
  640. setIsTeleporting(true);
  641. setTarget(null);
  642. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  643. if (Config.OFFSET_ON_TELEPORT_ENABLED && (randomOffset > 0))
  644. {
  645. x += Rnd.get(-randomOffset, randomOffset);
  646. y += Rnd.get(-randomOffset, randomOffset);
  647. }
  648. z += 5;
  649. // Send a Server->Client packet TeleportToLocationt to the L2Character AND to all L2PcInstance in the _KnownPlayers of the L2Character
  650. broadcastPacket(new TeleportToLocation(this, x, y, z, heading));
  651. // remove the object from its old location
  652. decayMe();
  653. // Set the x,y,z position of the L2Object and if necessary modify its _worldRegion
  654. setXYZ(x, y, z);
  655. // temporary fix for heading on teleports
  656. if (heading != 0)
  657. {
  658. setHeading(heading);
  659. }
  660. // allow recall of the detached characters
  661. if (!isPlayer() || ((getActingPlayer().getClient() != null) && getActingPlayer().getClient().isDetached()))
  662. {
  663. onTeleported();
  664. }
  665. revalidateZone(true);
  666. }
  667. public void teleToLocation(int x, int y, int z, int heading, int instanceId, boolean randomOffset)
  668. {
  669. teleToLocation(x, y, z, heading, instanceId, (randomOffset) ? Config.MAX_OFFSET_ON_TELEPORT : 0);
  670. }
  671. public void teleToLocation(int x, int y, int z, int heading, int instanceId)
  672. {
  673. teleToLocation(x, y, z, heading, instanceId, 0);
  674. }
  675. public void teleToLocation(int x, int y, int z, int heading, boolean randomOffset)
  676. {
  677. teleToLocation(x, y, z, heading, -1, (randomOffset) ? Config.MAX_OFFSET_ON_TELEPORT : 0);
  678. }
  679. public void teleToLocation(int x, int y, int z, int heading)
  680. {
  681. teleToLocation(x, y, z, heading, -1, 0);
  682. }
  683. public void teleToLocation(int x, int y, int z, boolean randomOffset)
  684. {
  685. teleToLocation(x, y, z, 0, -1, (randomOffset) ? Config.MAX_OFFSET_ON_TELEPORT : 0);
  686. }
  687. public void teleToLocation(int x, int y, int z)
  688. {
  689. teleToLocation(x, y, z, 0, -1, 0);
  690. }
  691. public void teleToLocation(ILocational loc, int randomOffset)
  692. {
  693. teleToLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), loc.getInstanceId(), randomOffset);
  694. }
  695. public void teleToLocation(ILocational loc, boolean randomOffset)
  696. {
  697. teleToLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), loc.getInstanceId(), (randomOffset) ? Config.MAX_OFFSET_ON_TELEPORT : 0);
  698. }
  699. public void teleToLocation(ILocational loc)
  700. {
  701. teleToLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), loc.getInstanceId(), 0);
  702. }
  703. public void teleToLocation(TeleportWhereType teleportWhere)
  704. {
  705. teleToLocation(MapRegionManager.getInstance().getTeleToLocation(this, teleportWhere), true);
  706. }
  707. /**
  708. * Launch a physical attack against a target (Simple, Bow, Pole or Dual).<br>
  709. * <B><U>Actions</U>:</B>
  710. * <ul>
  711. * <li>Get the active weapon (always equipped in the right hand)</li>
  712. * <li>If weapon is a bow, check for arrows, MP and bow re-use delay (if necessary, equip the L2PcInstance with arrows in left hand)</li>
  713. * <li>If weapon is a bow, consume MP and set the new period of bow non re-use</li>
  714. * <li>Get the Attack Speed of the L2Character (delay (in milliseconds) before next attack)</li>
  715. * <li>Select the type of attack to start (Simple, Bow, Pole or Dual) and verify if SoulShot are charged then start calculation</li>
  716. * <li>If the Server->Client packet Attack contains at least 1 hit, send the Server->Client packet Attack to the L2Character AND to all L2PcInstance in the _KnownPlayers of the L2Character</li>
  717. * <li>Notify AI with EVT_READY_TO_ACT</li>
  718. * </ul>
  719. * @param target The L2Character targeted
  720. */
  721. protected void doAttack(L2Character target)
  722. {
  723. if (!_attackLock.tryLock())
  724. {
  725. return;
  726. }
  727. try
  728. {
  729. if ((target == null) || isAttackingDisabled())
  730. {
  731. return;
  732. }
  733. // Notify to scripts
  734. final TerminateReturn attackReturn = EventDispatcher.getInstance().notifyEvent(new OnCreatureAttack(this, target), this, TerminateReturn.class);
  735. if ((attackReturn != null) && attackReturn.terminate())
  736. {
  737. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  738. sendPacket(ActionFailed.STATIC_PACKET);
  739. return;
  740. }
  741. // Notify to scripts
  742. final TerminateReturn attackedReturn = EventDispatcher.getInstance().notifyEvent(new OnCreatureAttacked(this, target), target, TerminateReturn.class);
  743. if ((attackedReturn != null) && attackedReturn.terminate())
  744. {
  745. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  746. sendPacket(ActionFailed.STATIC_PACKET);
  747. return;
  748. }
  749. if (!isAlikeDead())
  750. {
  751. if ((isNpc() && target.isAlikeDead()) || !getKnownList().knowsObject(target))
  752. {
  753. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  754. sendPacket(ActionFailed.STATIC_PACKET);
  755. return;
  756. }
  757. else if (isPlayer())
  758. {
  759. if (target.isDead())
  760. {
  761. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  762. sendPacket(ActionFailed.STATIC_PACKET);
  763. return;
  764. }
  765. final L2PcInstance actor = getActingPlayer();
  766. if (actor.isTransformed() && !actor.getTransformation().canAttack())
  767. {
  768. sendPacket(ActionFailed.STATIC_PACKET);
  769. return;
  770. }
  771. }
  772. }
  773. // Check if attacker's weapon can attack
  774. if (getActiveWeaponItem() != null)
  775. {
  776. L2Weapon wpn = getActiveWeaponItem();
  777. if (!wpn.isAttackWeapon() && !isGM())
  778. {
  779. if (wpn.getItemType() == WeaponType.FISHINGROD)
  780. {
  781. sendPacket(SystemMessageId.CANNOT_ATTACK_WITH_FISHING_POLE);
  782. }
  783. else
  784. {
  785. sendPacket(SystemMessageId.THAT_WEAPON_CANT_ATTACK);
  786. }
  787. sendPacket(ActionFailed.STATIC_PACKET);
  788. return;
  789. }
  790. }
  791. if (getActingPlayer() != null)
  792. {
  793. if (getActingPlayer().inObserverMode())
  794. {
  795. sendPacket(SystemMessageId.OBSERVERS_CANNOT_PARTICIPATE);
  796. sendPacket(ActionFailed.STATIC_PACKET);
  797. return;
  798. }
  799. else if ((target.getActingPlayer() != null) && (getActingPlayer().getSiegeState() > 0) && isInsideZone(ZoneId.SIEGE) && (target.getActingPlayer().getSiegeState() == getActingPlayer().getSiegeState()) && (target.getActingPlayer() != this) && (target.getActingPlayer().getSiegeSide() == getActingPlayer().getSiegeSide()))
  800. {
  801. if (TerritoryWarManager.getInstance().isTWInProgress())
  802. {
  803. sendPacket(SystemMessageId.YOU_CANNOT_ATTACK_A_MEMBER_OF_THE_SAME_TERRITORY);
  804. }
  805. else
  806. {
  807. sendPacket(SystemMessageId.FORCED_ATTACK_IS_IMPOSSIBLE_AGAINST_SIEGE_SIDE_TEMPORARY_ALLIED_MEMBERS);
  808. }
  809. sendPacket(ActionFailed.STATIC_PACKET);
  810. return;
  811. }
  812. // Checking if target has moved to peace zone
  813. else if (target.isInsidePeaceZone(getActingPlayer()))
  814. {
  815. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  816. sendPacket(ActionFailed.STATIC_PACKET);
  817. return;
  818. }
  819. }
  820. else if (isInsidePeaceZone(this, target))
  821. {
  822. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  823. sendPacket(ActionFailed.STATIC_PACKET);
  824. return;
  825. }
  826. stopEffectsOnAction();
  827. // Get the active weapon item corresponding to the active weapon instance (always equipped in the right hand)
  828. L2Weapon weaponItem = getActiveWeaponItem();
  829. // GeoData Los Check here (or dz > 1000)
  830. if (!GeoData.getInstance().canSeeTarget(this, target))
  831. {
  832. sendPacket(SystemMessageId.CANT_SEE_TARGET);
  833. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  834. sendPacket(ActionFailed.STATIC_PACKET);
  835. return;
  836. }
  837. // BOW and CROSSBOW checks
  838. if ((weaponItem != null) && !isTransformed())
  839. {
  840. if (weaponItem.getItemType() == WeaponType.BOW)
  841. {
  842. // Check for arrows and MP
  843. if (isPlayer())
  844. {
  845. // Checking if target has moved to peace zone - only for player-bow attacks at the moment
  846. // Other melee is checked in movement code and for offensive spells a check is done every time
  847. if (target.isInsidePeaceZone(getActingPlayer()))
  848. {
  849. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  850. sendPacket(ActionFailed.STATIC_PACKET);
  851. return;
  852. }
  853. // Equip arrows needed in left hand and send a Server->Client packet ItemList to the L2PcInstance then return True
  854. if (!checkAndEquipArrows())
  855. {
  856. // Cancel the action because the L2PcInstance have no arrow
  857. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  858. sendPacket(ActionFailed.STATIC_PACKET);
  859. sendPacket(SystemMessageId.NOT_ENOUGH_ARROWS);
  860. return;
  861. }
  862. // Verify if the bow can be use
  863. if (_disableBowAttackEndTime <= GameTimeController.getInstance().getGameTicks())
  864. {
  865. // Verify if L2PcInstance owns enough MP
  866. int mpConsume = weaponItem.getMpConsume();
  867. if ((weaponItem.getReducedMpConsume() > 0) && (Rnd.get(100) < weaponItem.getReducedMpConsumeChance()))
  868. {
  869. mpConsume = weaponItem.getReducedMpConsume();
  870. }
  871. mpConsume = (int) calcStat(Stats.BOW_MP_CONSUME_RATE, mpConsume, null, null);
  872. if (getCurrentMp() < mpConsume)
  873. {
  874. // If L2PcInstance doesn't have enough MP, stop the attack
  875. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
  876. sendPacket(SystemMessageId.NOT_ENOUGH_MP);
  877. sendPacket(ActionFailed.STATIC_PACKET);
  878. return;
  879. }
  880. // If L2PcInstance have enough MP, the bow consumes it
  881. if (mpConsume > 0)
  882. {
  883. getStatus().reduceMp(mpConsume);
  884. }
  885. // Set the period of bow no re-use
  886. _disableBowAttackEndTime = (5 * GameTimeController.TICKS_PER_SECOND) + GameTimeController.getInstance().getGameTicks();
  887. }
  888. else
  889. {
  890. // Cancel the action because the bow can't be re-use at this moment
  891. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
  892. sendPacket(ActionFailed.STATIC_PACKET);
  893. return;
  894. }
  895. }
  896. }
  897. if (weaponItem.getItemType() == WeaponType.CROSSBOW)
  898. {
  899. // Check for bolts
  900. if (isPlayer())
  901. {
  902. // Checking if target has moved to peace zone - only for player-crossbow attacks at the moment
  903. // Other melee is checked in movement code and for offensive spells a check is done every time
  904. if (target.isInsidePeaceZone(getActingPlayer()))
  905. {
  906. getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE);
  907. sendPacket(ActionFailed.STATIC_PACKET);
  908. return;
  909. }
  910. // Equip bolts needed in left hand and send a Server->Client packet ItemList to the L2PcINstance then return True
  911. if (!checkAndEquipBolts())
  912. {
  913. // Cancel the action because the L2PcInstance have no arrow
  914. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  915. sendPacket(ActionFailed.STATIC_PACKET);
  916. sendPacket(SystemMessageId.NOT_ENOUGH_BOLTS);
  917. return;
  918. }
  919. // Verify if the crossbow can be use
  920. if (_disableCrossBowAttackEndTime <= GameTimeController.getInstance().getGameTicks())
  921. {
  922. // Verify if L2PcInstance owns enough MP
  923. int mpConsume = weaponItem.getMpConsume();
  924. if ((weaponItem.getReducedMpConsume() > 0) && (Rnd.get(100) < weaponItem.getReducedMpConsumeChance()))
  925. {
  926. mpConsume = weaponItem.getReducedMpConsume();
  927. }
  928. mpConsume = (int) calcStat(Stats.BOW_MP_CONSUME_RATE, mpConsume, null, null);
  929. if (getCurrentMp() < mpConsume)
  930. {
  931. // If L2PcInstance doesn't have enough MP, stop the attack
  932. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
  933. sendPacket(SystemMessageId.NOT_ENOUGH_MP);
  934. sendPacket(ActionFailed.STATIC_PACKET);
  935. return;
  936. }
  937. // If L2PcInstance have enough MP, the bow consumes it
  938. if (mpConsume > 0)
  939. {
  940. getStatus().reduceMp(mpConsume);
  941. }
  942. // Set the period of crossbow no re-use
  943. _disableCrossBowAttackEndTime = (5 * GameTimeController.TICKS_PER_SECOND) + GameTimeController.getInstance().getGameTicks();
  944. }
  945. else
  946. {
  947. // Cancel the action because the crossbow can't be re-use at this moment
  948. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
  949. sendPacket(ActionFailed.STATIC_PACKET);
  950. return;
  951. }
  952. }
  953. else if (isNpc())
  954. {
  955. if (_disableCrossBowAttackEndTime > GameTimeController.getInstance().getGameTicks())
  956. {
  957. return;
  958. }
  959. }
  960. }
  961. }
  962. // Add the L2PcInstance to _knownObjects and _knownPlayer of the target
  963. target.getKnownList().addKnownObject(this);
  964. // Reduce the current CP if TIREDNESS configuration is activated
  965. if (Config.ALT_GAME_TIREDNESS)
  966. {
  967. setCurrentCp(getCurrentCp() - 10);
  968. }
  969. // Verify if soulshots are charged.
  970. final boolean wasSSCharged = isChargedShot(ShotType.SOULSHOTS);
  971. // Get the Attack Speed of the L2Character (delay (in milliseconds) before next attack)
  972. final int timeAtk = calculateTimeBetweenAttacks(target, weaponItem);
  973. // the hit is calculated to happen halfway to the animation - might need further tuning e.g. in bow case
  974. final int timeToHit = timeAtk / 2;
  975. _attackEndTime = System.currentTimeMillis() + timeAtk;
  976. final int ssGrade = (weaponItem != null) ? weaponItem.getItemGradeSPlus().getId() : 0;
  977. // Create a Server->Client packet Attack
  978. Attack attack = new Attack(this, target, wasSSCharged, ssGrade);
  979. // Make sure that char is facing selected target
  980. // also works: setHeading(Util.convertDegreeToClientHeading(Util.calculateAngleFrom(this, target)));
  981. setHeading(Util.calculateHeadingFrom(this, target));
  982. // Get the Attack Reuse Delay of the L2Weapon
  983. int reuse = calculateReuseTime(target, weaponItem);
  984. boolean hitted = false;
  985. switch (getAttackType())
  986. {
  987. case BOW:
  988. {
  989. hitted = doAttackHitByBow(attack, target, timeAtk, reuse);
  990. break;
  991. }
  992. case CROSSBOW:
  993. {
  994. hitted = doAttackHitByCrossBow(attack, target, timeAtk, reuse);
  995. break;
  996. }
  997. case POLE:
  998. {
  999. hitted = doAttackHitByPole(attack, target, timeToHit);
  1000. break;
  1001. }
  1002. case FIST:
  1003. {
  1004. if (!isPlayer())
  1005. {
  1006. hitted = doAttackHitSimple(attack, target, timeToHit);
  1007. break;
  1008. }
  1009. }
  1010. case DUAL:
  1011. case DUALFIST:
  1012. case DUALDAGGER:
  1013. {
  1014. hitted = doAttackHitByDual(attack, target, timeToHit);
  1015. break;
  1016. }
  1017. default:
  1018. {
  1019. hitted = doAttackHitSimple(attack, target, timeToHit);
  1020. break;
  1021. }
  1022. }
  1023. // Flag the attacker if it's a L2PcInstance outside a PvP area
  1024. final L2PcInstance player = getActingPlayer();
  1025. if (player != null)
  1026. {
  1027. AttackStanceTaskManager.getInstance().addAttackStanceTask(player);
  1028. if (player.getSummon() != target)
  1029. {
  1030. player.updatePvPStatus(target);
  1031. }
  1032. }
  1033. // Check if hit isn't missed
  1034. if (!hitted)
  1035. {
  1036. abortAttack(); // Abort the attack of the L2Character and send Server->Client ActionFailed packet
  1037. }
  1038. else
  1039. {
  1040. // If we didn't miss the hit, discharge the shoulshots, if any
  1041. setChargedShot(ShotType.SOULSHOTS, false);
  1042. if (player != null)
  1043. {
  1044. if (player.isCursedWeaponEquipped())
  1045. {
  1046. // If hit by a cursed weapon, CP is reduced to 0
  1047. if (!target.isInvul())
  1048. {
  1049. target.setCurrentCp(0);
  1050. }
  1051. }
  1052. else if (player.isHero())
  1053. {
  1054. // If a cursed weapon is hit by a Hero, CP is reduced to 0
  1055. if (target.isPlayer() && target.getActingPlayer().isCursedWeaponEquipped())
  1056. {
  1057. target.setCurrentCp(0);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. // If the Server->Client packet Attack contains at least 1 hit, send the Server->Client packet Attack
  1063. // to the L2Character AND to all L2PcInstance in the _KnownPlayers of the L2Character
  1064. if (attack.hasHits())
  1065. {
  1066. broadcastPacket(attack);
  1067. }
  1068. // Notify AI with EVT_READY_TO_ACT
  1069. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), timeAtk + reuse);
  1070. }
  1071. finally
  1072. {
  1073. _attackLock.unlock();
  1074. }
  1075. }
  1076. /**
  1077. * Launch a Bow attack.<br>
  1078. * <B><U>Actions</U>:</B>
  1079. * <ul>
  1080. * <li>Calculate if hit is missed or not</li>
  1081. * <li>Consume arrows</li>
  1082. * <li>If hit isn't missed, calculate if shield defense is efficient</li>
  1083. * <li>If hit isn't missed, calculate if hit is critical</li>
  1084. * <li>If hit isn't missed, calculate physical damages</li>
  1085. * <li>If the L2Character is a L2PcInstance, Send a Server->Client packet SetupGauge</li>
  1086. * <li>Create a new hit task with Medium priority</li>
  1087. * <li>Calculate and set the disable delay of the bow in function of the Attack Speed</li>
  1088. * <li>Add this hit to the Server-Client packet Attack</li>
  1089. * </ul>
  1090. * @param attack Server->Client packet Attack in which the hit will be added
  1091. * @param target The L2Character targeted
  1092. * @param sAtk The Attack Speed of the attacker
  1093. * @param reuse
  1094. * @return True if the hit isn't missed
  1095. */
  1096. private boolean doAttackHitByBow(Attack attack, L2Character target, int sAtk, int reuse)
  1097. {
  1098. int damage1 = 0;
  1099. byte shld1 = 0;
  1100. boolean crit1 = false;
  1101. // Calculate if hit is missed or not
  1102. boolean miss1 = Formulas.calcHitMiss(this, target);
  1103. // Consume arrows
  1104. reduceArrowCount(false);
  1105. _move = null;
  1106. // Check if hit isn't missed
  1107. if (!miss1)
  1108. {
  1109. // Calculate if shield defense is efficient
  1110. shld1 = Formulas.calcShldUse(this, target);
  1111. // Calculate if hit is critical
  1112. crit1 = Formulas.calcCrit(getStat().getCriticalHit(target, null), false, target);
  1113. // Calculate physical damages
  1114. damage1 = (int) Formulas.calcPhysDam(this, target, null, shld1, crit1, attack.hasSoulshot());
  1115. // Bows Ranged Damage Formula (Damage gradually decreases when 60% or lower than full hit range, and increases when 60% or higher).
  1116. // full hit range is 500 which is the base bow range, and the 60% of this is 800.
  1117. damage1 *= (calculateDistance(target, true, false) / 4000) + 0.8;
  1118. }
  1119. // Check if the L2Character is a L2PcInstance
  1120. if (isPlayer())
  1121. {
  1122. sendPacket(new SetupGauge(SetupGauge.RED, sAtk + reuse));
  1123. }
  1124. // Create a new hit task with Medium priority
  1125. ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
  1126. // Calculate and set the disable delay of the bow in function of the Attack Speed
  1127. _disableBowAttackEndTime = ((sAtk + reuse) / GameTimeController.MILLIS_IN_TICK) + GameTimeController.getInstance().getGameTicks();
  1128. // Add this hit to the Server-Client packet Attack
  1129. attack.addHit(target, damage1, miss1, crit1, shld1);
  1130. // Return true if hit isn't missed
  1131. return !miss1;
  1132. }
  1133. /**
  1134. * Launch a CrossBow attack.<br>
  1135. * <B><U>Actions</U>:</B>
  1136. * <ul>
  1137. * <li>Calculate if hit is missed or not</li>
  1138. * <li>Consume bolts</li>
  1139. * <li>If hit isn't missed, calculate if shield defense is efficient</li>
  1140. * <li>If hit isn't missed, calculate if hit is critical</li>
  1141. * <li>If hit isn't missed, calculate physical damages</li>
  1142. * <li>If the L2Character is a L2PcInstance, Send a Server->Client packet SetupGauge</li>
  1143. * <li>Create a new hit task with Medium priority</li>
  1144. * <li>Calculate and set the disable delay of the crossbow in function of the Attack Speed</li>
  1145. * <li>Add this hit to the Server-Client packet Attack</li>
  1146. * @param attack Server->Client packet Attack in which the hit will be added
  1147. * @param target The L2Character targeted
  1148. * @param sAtk The Attack Speed of the attacker
  1149. * @param reuse
  1150. * @return True if the hit isn't missed
  1151. */
  1152. private boolean doAttackHitByCrossBow(Attack attack, L2Character target, int sAtk, int reuse)
  1153. {
  1154. int damage1 = 0;
  1155. byte shld1 = 0;
  1156. boolean crit1 = false;
  1157. // Calculate if hit is missed or not
  1158. boolean miss1 = Formulas.calcHitMiss(this, target);
  1159. // Consume bolts
  1160. reduceArrowCount(true);
  1161. _move = null;
  1162. // Check if hit isn't missed
  1163. if (!miss1)
  1164. {
  1165. // Calculate if shield defense is efficient
  1166. shld1 = Formulas.calcShldUse(this, target);
  1167. // Calculate if hit is critical
  1168. crit1 = Formulas.calcCrit(getStat().getCriticalHit(target, null), false, target);
  1169. // Calculate physical damages
  1170. damage1 = (int) Formulas.calcPhysDam(this, target, null, shld1, crit1, attack.hasSoulshot());
  1171. }
  1172. // Check if the L2Character is a L2PcInstance
  1173. if (isPlayer())
  1174. {
  1175. // Send a system message
  1176. sendPacket(SystemMessageId.CROSSBOW_PREPARING_TO_FIRE);
  1177. // Send a Server->Client packet SetupGauge
  1178. SetupGauge sg = new SetupGauge(SetupGauge.RED, sAtk + reuse);
  1179. sendPacket(sg);
  1180. }
  1181. // Create a new hit task with Medium priority
  1182. ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
  1183. // Calculate and set the disable delay of the bow in function of the Attack Speed
  1184. _disableCrossBowAttackEndTime = ((sAtk + reuse) / GameTimeController.MILLIS_IN_TICK) + GameTimeController.getInstance().getGameTicks();
  1185. // Add this hit to the Server-Client packet Attack
  1186. attack.addHit(target, damage1, miss1, crit1, shld1);
  1187. // Return true if hit isn't missed
  1188. return !miss1;
  1189. }
  1190. /**
  1191. * Launch a Dual attack.<br>
  1192. * <B><U>Actions</U>:</B>
  1193. * <ul>
  1194. * <li>Calculate if hits are missed or not</li>
  1195. * <li>If hits aren't missed, calculate if shield defense is efficient</li>
  1196. * <li>If hits aren't missed, calculate if hit is critical</li>
  1197. * <li>If hits aren't missed, calculate physical damages</li>
  1198. * <li>Create 2 new hit tasks with Medium priority</li>
  1199. * <li>Add those hits to the Server-Client packet Attack</li>
  1200. * </ul>
  1201. * @param attack Server->Client packet Attack in which the hit will be added
  1202. * @param target The L2Character targeted
  1203. * @param sAtk
  1204. * @return True if hit 1 or hit 2 isn't missed
  1205. */
  1206. private boolean doAttackHitByDual(Attack attack, L2Character target, int sAtk)
  1207. {
  1208. int damage1 = 0;
  1209. int damage2 = 0;
  1210. byte shld1 = 0;
  1211. byte shld2 = 0;
  1212. boolean crit1 = false;
  1213. boolean crit2 = false;
  1214. // Calculate if hits are missed or not
  1215. boolean miss1 = Formulas.calcHitMiss(this, target);
  1216. boolean miss2 = Formulas.calcHitMiss(this, target);
  1217. // Check if hit 1 isn't missed
  1218. if (!miss1)
  1219. {
  1220. // Calculate if shield defense is efficient against hit 1
  1221. shld1 = Formulas.calcShldUse(this, target);
  1222. // Calculate if hit 1 is critical
  1223. crit1 = Formulas.calcCrit(getStat().getCriticalHit(target, null), false, target);
  1224. // Calculate physical damages of hit 1
  1225. damage1 = (int) Formulas.calcPhysDam(this, target, null, shld1, crit1, attack.hasSoulshot());
  1226. damage1 /= 2;
  1227. }
  1228. // Check if hit 2 isn't missed
  1229. if (!miss2)
  1230. {
  1231. // Calculate if shield defense is efficient against hit 2
  1232. shld2 = Formulas.calcShldUse(this, target);
  1233. // Calculate if hit 2 is critical
  1234. crit2 = Formulas.calcCrit(getStat().getCriticalHit(target, null), false, target);
  1235. // Calculate physical damages of hit 2
  1236. damage2 = (int) Formulas.calcPhysDam(this, target, null, shld2, crit2, attack.hasSoulshot());
  1237. damage2 /= 2;
  1238. }
  1239. // Create a new hit task with Medium priority for hit 1
  1240. ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk / 2);
  1241. // Create a new hit task with Medium priority for hit 2 with a higher delay
  1242. ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage2, crit2, miss2, attack.hasSoulshot(), shld2), sAtk);
  1243. // Add those hits to the Server-Client packet Attack
  1244. attack.addHit(target, damage1, miss1, crit1, shld1);
  1245. attack.addHit(target, damage2, miss2, crit2, shld2);
  1246. // Return true if hit 1 or hit 2 isn't missed
  1247. return (!miss1 || !miss2);
  1248. }
  1249. /**
  1250. * Launch a Pole attack.<br>
  1251. * <B><U>Actions</U>:</B>
  1252. * <ul>
  1253. * <li>Get all visible objects in a spherical area near the L2Character to obtain possible targets</li>
  1254. * <li>If possible target is the L2Character targeted, launch a simple attack against it</li>
  1255. * <li>If possible target isn't the L2Character targeted but is attackable, launch a simple attack against it</li>
  1256. * </ul>
  1257. * @param attack Server->Client packet Attack in which the hit will be added
  1258. * @param target
  1259. * @param sAtk
  1260. * @return True if one hit isn't missed
  1261. */
  1262. private boolean doAttackHitByPole(Attack attack, L2Character target, int sAtk)
  1263. {
  1264. // double angleChar;
  1265. int maxRadius = getStat().getPhysicalAttackRange();
  1266. int maxAngleDiff = getStat().getPhysicalAttackAngle();
  1267. // o1 x: 83420 y: 148158 (Giran)
  1268. // o2 x: 83379 y: 148081 (Giran)
  1269. // dx = -41
  1270. // dy = -77
  1271. // distance between o1 and o2 = 87.24
  1272. // arctan2 = -120 (240) degree (excel arctan2(dx, dy); java arctan2(dy, dx))
  1273. //
  1274. // o2
  1275. //
  1276. // o1 ----- (heading)
  1277. // In the diagram above:
  1278. // o1 has a heading of 0/360 degree from horizontal (facing East)
  1279. // Degree of o2 in respect to o1 = -120 (240) degree
  1280. //
  1281. // o2 / (heading)
  1282. // /
  1283. // o1
  1284. // In the diagram above
  1285. // o1 has a heading of -80 (280) degree from horizontal (facing north east)
  1286. // Degree of o2 in respect to 01 = -40 (320) degree
  1287. // Get char's heading degree
  1288. // angleChar = Util.convertHeadingToDegree(getHeading());
  1289. // H5 Changes: without Polearm Mastery (skill 216) max simultaneous attacks is 3 (1 by default + 2 in skill 3599).
  1290. int attackRandomCountMax = (int) getStat().calcStat(Stats.ATTACK_COUNT_MAX, 1, null, null);
  1291. int attackcount = 0;
  1292. // if (angleChar <= 0) angleChar += 360;
  1293. boolean hitted = doAttackHitSimple(attack, target, 100, sAtk);
  1294. double attackpercent = 85;
  1295. L2Character temp;
  1296. Collection<L2Object> objs = getKnownList().getKnownObjects().values();
  1297. for (L2Object obj : objs)
  1298. {
  1299. if (obj == target)
  1300. {
  1301. continue; // do not hit twice
  1302. }
  1303. // Check if the L2Object is a L2Character
  1304. if (obj instanceof L2Character)
  1305. {
  1306. if (obj.isPet() && isPlayer() && (((L2PetInstance) obj).getOwner() == getActingPlayer()))
  1307. {
  1308. continue;
  1309. }
  1310. if (!Util.checkIfInRange(maxRadius, this, obj, false))
  1311. {
  1312. continue;
  1313. }
  1314. // otherwise hit too high/low. 650 because mob z coord
  1315. // sometimes wrong on hills
  1316. if (Math.abs(obj.getZ() - getZ()) > 650)
  1317. {
  1318. continue;
  1319. }
  1320. if (!isFacing(obj, maxAngleDiff))
  1321. {
  1322. continue;
  1323. }
  1324. if (isAttackable() && obj.isPlayer() && getTarget().isAttackable())
  1325. {
  1326. continue;
  1327. }
  1328. if (isAttackable() && obj.isAttackable() && !((L2Attackable) this).isChaos())
  1329. {
  1330. continue;
  1331. }
  1332. temp = (L2Character) obj;
  1333. // Launch a simple attack against the L2Character targeted
  1334. if (!temp.isAlikeDead())
  1335. {
  1336. if ((temp == getAI().getAttackTarget()) || temp.isAutoAttackable(this))
  1337. {
  1338. hitted |= doAttackHitSimple(attack, temp, attackpercent, sAtk);
  1339. attackpercent /= 1.15;
  1340. attackcount++;
  1341. if (attackcount > attackRandomCountMax)
  1342. {
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. }
  1348. }
  1349. // Return true if one hit isn't missed
  1350. return hitted;
  1351. }
  1352. /**
  1353. * Launch a simple attack.<br>
  1354. * <B><U>Actions</U>:</B>
  1355. * <ul>
  1356. * <li>Calculate if hit is missed or not</li>
  1357. * <li>If hit isn't missed, calculate if shield defense is efficient</li>
  1358. * <li>If hit isn't missed, calculate if hit is critical</li>
  1359. * <li>If hit isn't missed, calculate physical damages</li>
  1360. * <li>Create a new hit task with Medium priority</li>
  1361. * <li>Add this hit to the Server-Client packet Attack</li>
  1362. * </ul>
  1363. * @param attack Server->Client packet Attack in which the hit will be added
  1364. * @param target The L2Character targeted
  1365. * @param sAtk
  1366. * @return True if the hit isn't missed
  1367. */
  1368. private boolean doAttackHitSimple(Attack attack, L2Character target, int sAtk)
  1369. {
  1370. return doAttackHitSimple(attack, target, 100, sAtk);
  1371. }
  1372. private boolean doAttackHitSimple(Attack attack, L2Character target, double attackpercent, int sAtk)
  1373. {
  1374. int damage1 = 0;
  1375. byte shld1 = 0;
  1376. boolean crit1 = false;
  1377. // Calculate if hit is missed or not
  1378. boolean miss1 = Formulas.calcHitMiss(this, target);
  1379. // Check if hit isn't missed
  1380. if (!miss1)
  1381. {
  1382. // Calculate if shield defense is efficient
  1383. shld1 = Formulas.calcShldUse(this, target);
  1384. // Calculate if hit is critical
  1385. crit1 = Formulas.calcCrit(getStat().getCriticalHit(target, null), false, target);
  1386. // Calculate physical damages
  1387. damage1 = (int) Formulas.calcPhysDam(this, target, null, shld1, crit1, attack.hasSoulshot());
  1388. if (attackpercent != 100)
  1389. {
  1390. damage1 = (int) ((damage1 * attackpercent) / 100);
  1391. }
  1392. }
  1393. // Create a new hit task with Medium priority
  1394. ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
  1395. // Add this hit to the Server-Client packet Attack
  1396. attack.addHit(target, damage1, miss1, crit1, shld1);
  1397. // Return true if hit isn't missed
  1398. return !miss1;
  1399. }
  1400. /**
  1401. * Manage the casting task (casting and interrupt time, re-use delay...) and display the casting bar and animation on client.<br>
  1402. * <B><U>Actions</U>:</B>
  1403. * <ul>
  1404. * <li>Verify the possibility of the the cast : skill is a spell, caster isn't muted...</li>
  1405. * <li>Get the list of all targets (ex : area effects) and define the L2Charcater targeted (its stats will be used in calculation)</li>
  1406. * <li>Calculate the casting time (base + modifier of MAtkSpd), interrupt time and re-use delay</li>
  1407. * <li>Send a Server->Client packet MagicSkillUser (to display casting animation), a packet SetupGauge (to display casting bar) and a system message</li>
  1408. * <li>Disable all skills during the casting time (create a task EnableAllSkills)</li>
  1409. * <li>Disable the skill during the re-use delay (create a task EnableSkill)</li>
  1410. * <li>Create a task MagicUseTask (that will call method onMagicUseTimer) to launch the Magic Skill at the end of the casting time</li>
  1411. * </ul>
  1412. * @param skill The L2Skill to use
  1413. */
  1414. public void doCast(Skill skill)
  1415. {
  1416. beginCast(skill, false);
  1417. }
  1418. public void doSimultaneousCast(Skill skill)
  1419. {
  1420. beginCast(skill, true);
  1421. }
  1422. public void doCast(Skill skill, L2Character target, L2Object[] targets)
  1423. {
  1424. if (!checkDoCastConditions(skill))
  1425. {
  1426. setIsCastingNow(false);
  1427. return;
  1428. }
  1429. // Override casting type
  1430. if (skill.isSimultaneousCast())
  1431. {
  1432. doSimultaneousCast(skill, target, targets);
  1433. return;
  1434. }
  1435. stopEffectsOnAction();
  1436. // Recharge AutoSoulShot
  1437. // this method should not used with L2Playable
  1438. beginCast(skill, false, target, targets);
  1439. }
  1440. public void doSimultaneousCast(Skill skill, L2Character target, L2Object[] targets)
  1441. {
  1442. if (!checkDoCastConditions(skill))
  1443. {
  1444. setIsCastingSimultaneouslyNow(false);
  1445. return;
  1446. }
  1447. stopEffectsOnAction();
  1448. beginCast(skill, true, target, targets);
  1449. }
  1450. private void beginCast(Skill skill, boolean simultaneously)
  1451. {
  1452. if (!checkDoCastConditions(skill))
  1453. {
  1454. if (simultaneously)
  1455. {
  1456. setIsCastingSimultaneouslyNow(false);
  1457. }
  1458. else
  1459. {
  1460. setIsCastingNow(false);
  1461. }
  1462. if (isPlayer())
  1463. {
  1464. getAI().setIntention(AI_INTENTION_ACTIVE);
  1465. }
  1466. return;
  1467. }
  1468. // Override casting type
  1469. if (skill.isSimultaneousCast() && !simultaneously)
  1470. {
  1471. simultaneously = true;
  1472. }
  1473. stopEffectsOnAction();
  1474. // Set the target of the skill in function of Skill Type and Target Type
  1475. L2Character target = null;
  1476. // Get all possible targets of the skill in a table in function of the skill target type
  1477. L2Object[] targets = skill.getTargetList(this);
  1478. boolean doit = false;
  1479. // AURA skills should always be using caster as target
  1480. switch (skill.getTargetType())
  1481. {
  1482. case AREA_SUMMON: // We need it to correct facing
  1483. target = getSummon();
  1484. break;
  1485. case AURA:
  1486. case AURA_CORPSE_MOB:
  1487. case FRONT_AURA:
  1488. case BEHIND_AURA:
  1489. case GROUND:
  1490. target = this;
  1491. break;
  1492. case SELF:
  1493. case PET:
  1494. case SERVITOR:
  1495. case SUMMON:
  1496. case OWNER_PET:
  1497. case PARTY:
  1498. case CLAN:
  1499. case PARTY_CLAN:
  1500. case COMMAND_CHANNEL:
  1501. doit = true;
  1502. default:
  1503. if (targets.length == 0)
  1504. {
  1505. if (simultaneously)
  1506. {
  1507. setIsCastingSimultaneouslyNow(false);
  1508. }
  1509. else
  1510. {
  1511. setIsCastingNow(false);
  1512. }
  1513. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1514. if (isPlayer())
  1515. {
  1516. sendPacket(ActionFailed.STATIC_PACKET);
  1517. getAI().setIntention(AI_INTENTION_ACTIVE);
  1518. }
  1519. return;
  1520. }
  1521. if ((skill.isContinuous() && !skill.isDebuff()) || skill.hasEffectType(L2EffectType.CPHEAL, L2EffectType.HEAL))
  1522. {
  1523. doit = true;
  1524. }
  1525. if (doit)
  1526. {
  1527. target = (L2Character) targets[0];
  1528. }
  1529. else
  1530. {
  1531. target = (L2Character) getTarget();
  1532. }
  1533. }
  1534. beginCast(skill, simultaneously, target, targets);
  1535. }
  1536. private void beginCast(Skill skill, boolean simultaneously, L2Character target, L2Object[] targets)
  1537. {
  1538. if (target == null)
  1539. {
  1540. if (simultaneously)
  1541. {
  1542. setIsCastingSimultaneouslyNow(false);
  1543. }
  1544. else
  1545. {
  1546. setIsCastingNow(false);
  1547. }
  1548. if (isPlayer())
  1549. {
  1550. sendPacket(ActionFailed.STATIC_PACKET);
  1551. getAI().setIntention(AI_INTENTION_ACTIVE);
  1552. }
  1553. return;
  1554. }
  1555. final TerminateReturn term = EventDispatcher.getInstance().notifyEvent(new OnCreatureSkillUse(this, skill, simultaneously, target, targets), this, TerminateReturn.class);
  1556. if ((term != null) && term.terminate())
  1557. {
  1558. if (simultaneously)
  1559. {
  1560. setIsCastingSimultaneouslyNow(false);
  1561. }
  1562. else
  1563. {
  1564. setIsCastingNow(false);
  1565. }
  1566. if (isPlayer())
  1567. {
  1568. sendPacket(ActionFailed.STATIC_PACKET);
  1569. getAI().setIntention(AI_INTENTION_ACTIVE);
  1570. }
  1571. return;
  1572. }
  1573. // TODO: Unhardcode using event listeners!
  1574. if (skill.hasEffectType(L2EffectType.RESURRECTION))
  1575. {
  1576. if (isResurrectionBlocked() || target.isResurrectionBlocked())
  1577. {
  1578. sendPacket(SystemMessageId.REJECT_RESURRECTION); // Reject resurrection
  1579. target.sendPacket(SystemMessageId.REJECT_RESURRECTION); // Reject resurrection
  1580. if (simultaneously)
  1581. {
  1582. setIsCastingSimultaneouslyNow(false);
  1583. }
  1584. else
  1585. {
  1586. setIsCastingNow(false);
  1587. }
  1588. if (isPlayer())
  1589. {
  1590. getAI().setIntention(AI_INTENTION_ACTIVE);
  1591. sendPacket(ActionFailed.STATIC_PACKET);
  1592. }
  1593. return;
  1594. }
  1595. }
  1596. // Get the Identifier of the skill
  1597. int magicId = skill.getId();
  1598. // Get the Base Casting Time of the Skills.
  1599. int skillTime = (skill.getHitTime() + skill.getCoolTime());
  1600. if (!skill.isChanneling() || (skill.getChannelingSkillId() == 0))
  1601. {
  1602. // Calculate the Casting Time of the "Non-Static" Skills (with caster PAtk/MAtkSpd).
  1603. if (!skill.isStatic())
  1604. {
  1605. skillTime = Formulas.calcAtkSpd(this, skill, skillTime);
  1606. }
  1607. // Calculate the Casting Time of Magic Skills (reduced in 40% if using SPS/BSPS)
  1608. if (skill.isMagic() && (isChargedShot(ShotType.SPIRITSHOTS) || isChargedShot(ShotType.BLESSED_SPIRITSHOTS)))
  1609. {
  1610. skillTime = (int) (0.6 * skillTime);
  1611. }
  1612. }
  1613. // Avoid broken Casting Animation.
  1614. // Client can't handle less than 550ms Casting Animation in Magic Skills with more than 550ms base.
  1615. if (skill.isMagic() && ((skill.getHitTime() + skill.getCoolTime()) > 550) && (skillTime < 550))
  1616. {
  1617. skillTime = 550;
  1618. }
  1619. // Client can't handle less than 500ms Casting Animation in Physical Skills with 500ms base or more.
  1620. else if (!skill.isStatic() && ((skill.getHitTime() + skill.getCoolTime()) >= 500) && (skillTime < 500))
  1621. {
  1622. skillTime = 500;
  1623. }
  1624. // queue herbs and potions
  1625. if (isCastingSimultaneouslyNow() && simultaneously)
  1626. {
  1627. ThreadPoolManager.getInstance().scheduleAi(new UsePotionTask(this, skill), 100);
  1628. return;
  1629. }
  1630. // Set the _castInterruptTime and casting status (L2PcInstance already has this true)
  1631. if (simultaneously)
  1632. {
  1633. setIsCastingSimultaneouslyNow(true);
  1634. }
  1635. else
  1636. {
  1637. setIsCastingNow(true);
  1638. }
  1639. if (!simultaneously)
  1640. {
  1641. _castInterruptTime = -2 + GameTimeController.getInstance().getGameTicks() + (skillTime / GameTimeController.MILLIS_IN_TICK);
  1642. setLastSkillCast(skill);
  1643. }
  1644. else
  1645. {
  1646. setLastSimultaneousSkillCast(skill);
  1647. }
  1648. // Calculate the Reuse Time of the Skill
  1649. int reuseDelay;
  1650. if (skill.isStaticReuse() || skill.isStatic())
  1651. {
  1652. reuseDelay = (skill.getReuseDelay());
  1653. }
  1654. else if (skill.isMagic())
  1655. {
  1656. reuseDelay = (int) (skill.getReuseDelay() * calcStat(Stats.MAGIC_REUSE_RATE, 1, null, null));
  1657. }
  1658. else if (skill.isPhysical())
  1659. {
  1660. reuseDelay = (int) (skill.getReuseDelay() * calcStat(Stats.P_REUSE, 1, null, null));
  1661. }
  1662. else
  1663. {
  1664. reuseDelay = (int) (skill.getReuseDelay() * calcStat(Stats.DANCE_REUSE, 1, null, null));
  1665. }
  1666. boolean skillMastery = Formulas.calcSkillMastery(this, skill);
  1667. // Skill reuse check
  1668. if ((reuseDelay > 30000) && !skillMastery)
  1669. {
  1670. addTimeStamp(skill, reuseDelay);
  1671. }
  1672. // Check if this skill consume mp on start casting
  1673. int initmpcons = getStat().getMpInitialConsume(skill);
  1674. if (initmpcons > 0)
  1675. {
  1676. getStatus().reduceMp(initmpcons);
  1677. StatusUpdate su = new StatusUpdate(this);
  1678. su.addAttribute(StatusUpdate.CUR_MP, (int) getCurrentMp());
  1679. sendPacket(su);
  1680. }
  1681. // Disable the skill during the re-use delay and create a task EnableSkill with Medium priority to enable it at the end of the re-use delay
  1682. if (reuseDelay > 10)
  1683. {
  1684. if (skillMastery)
  1685. {
  1686. reuseDelay = 100;
  1687. if (getActingPlayer() != null)
  1688. {
  1689. getActingPlayer().sendPacket(SystemMessageId.SKILL_READY_TO_USE_AGAIN);
  1690. }
  1691. }
  1692. disableSkill(skill, reuseDelay);
  1693. }
  1694. // Make sure that char is facing selected target
  1695. if (target != this)
  1696. {
  1697. setHeading(Util.calculateHeadingFrom(this, target));
  1698. broadcastPacket(new ExRotation(getObjectId(), getHeading()));
  1699. }
  1700. if (isPlayable())
  1701. {
  1702. if (skill.getItemConsumeId() > 0)
  1703. {
  1704. if (!destroyItemByItemId("Consume", skill.getItemConsumeId(), skill.getItemConsumeCount(), null, true))
  1705. {
  1706. getActingPlayer().sendPacket(SystemMessageId.NOT_ENOUGH_ITEMS);
  1707. abortCast();
  1708. return;
  1709. }
  1710. }
  1711. // reduce talisman mana on skill use
  1712. if ((skill.getReferenceItemId() > 0) && (ItemTable.getInstance().getTemplate(skill.getReferenceItemId()).getBodyPart() == L2Item.SLOT_DECO))
  1713. {
  1714. for (L2ItemInstance item : getInventory().getItemsByItemId(skill.getReferenceItemId()))
  1715. {
  1716. if (item.isEquipped())
  1717. {
  1718. item.decreaseMana(false, item.useSkillDisTime());
  1719. break;
  1720. }
  1721. }
  1722. }
  1723. }
  1724. // Send a Server->Client packet MagicSkillUser with target, displayId, level, skillTime, reuseDelay
  1725. // to the L2Character AND to all L2PcInstance in the _KnownPlayers of the L2Character
  1726. broadcastPacket(new MagicSkillUse(this, target, skill.getDisplayId(), skill.getDisplayLevel(), skillTime, reuseDelay));
  1727. // Send a system message to the player.
  1728. if (isPlayer() && !skill.isAbnormalInstant())
  1729. {
  1730. SystemMessage sm = null;
  1731. switch (magicId)
  1732. {
  1733. case 1312: // Fishing
  1734. {
  1735. // Done in L2PcInstance.startFishing()
  1736. break;
  1737. }
  1738. case 2046: // Wolf Collar
  1739. {
  1740. sm = SystemMessage.getSystemMessage(SystemMessageId.SUMMON_A_PET);
  1741. break;
  1742. }
  1743. default:
  1744. {
  1745. sm = SystemMessage.getSystemMessage(SystemMessageId.USE_S1);
  1746. sm.addSkillName(skill);
  1747. break;
  1748. }
  1749. }
  1750. sendPacket(sm);
  1751. }
  1752. if (skill.hasEffects(EffectScope.START))
  1753. {
  1754. skill.applyEffectScope(EffectScope.START, new BuffInfo(this, target, skill), true, false);
  1755. }
  1756. // Before start AI Cast Broadcast Fly Effect is Need
  1757. if (skill.getFlyType() != null)
  1758. {
  1759. ThreadPoolManager.getInstance().scheduleEffect(new FlyToLocationTask(this, target, skill), 50);
  1760. }
  1761. MagicUseTask mut = new MagicUseTask(this, targets, skill, skillTime, simultaneously);
  1762. // launch the magic in skillTime milliseconds
  1763. if (skillTime > 0)
  1764. {
  1765. // Send a Server->Client packet SetupGauge with the color of the gauge and the casting time
  1766. if (isPlayer() && !simultaneously)
  1767. {
  1768. sendPacket(new SetupGauge(SetupGauge.BLUE, skillTime));
  1769. }
  1770. if (skill.isChanneling() && (skill.getChannelingSkillId() > 0))
  1771. {
  1772. getSkillChannelizer().startChanneling(skill);
  1773. }
  1774. if (simultaneously)
  1775. {
  1776. Future<?> future = _skillCast2;
  1777. if (future != null)
  1778. {
  1779. future.cancel(true);
  1780. _skillCast2 = null;
  1781. }
  1782. // Create a task MagicUseTask to launch the MagicSkill at the end of the casting time (skillTime)
  1783. // For client animation reasons (party buffs especially) 400 ms before!
  1784. _skillCast2 = ThreadPoolManager.getInstance().scheduleEffect(mut, skillTime - 400);
  1785. }
  1786. else
  1787. {
  1788. Future<?> future = _skillCast;
  1789. if (future != null)
  1790. {
  1791. future.cancel(true);
  1792. _skillCast = null;
  1793. }
  1794. // Create a task MagicUseTask to launch the MagicSkill at the end of the casting time (skillTime)
  1795. // For client animation reasons (party buffs especially) 400 ms before!
  1796. _skillCast = ThreadPoolManager.getInstance().scheduleEffect(mut, skillTime - 400);
  1797. }
  1798. }
  1799. else
  1800. {
  1801. mut.setSkillTime(0);
  1802. onMagicLaunchedTimer(mut);
  1803. }
  1804. }
  1805. /**
  1806. * Check if casting of skill is possible
  1807. * @param skill
  1808. * @return True if casting is possible
  1809. */
  1810. public boolean checkDoCastConditions(Skill skill)
  1811. {
  1812. if ((skill == null) || isSkillDisabled(skill) || (((skill.getFlyRadius() > 0) || (skill.getFlyType() != null)) && isMovementDisabled()))
  1813. {
  1814. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1815. sendPacket(ActionFailed.STATIC_PACKET);
  1816. return false;
  1817. }
  1818. // Check if the caster has enough MP
  1819. if (getCurrentMp() < (getStat().getMpConsume(skill) + getStat().getMpInitialConsume(skill)))
  1820. {
  1821. // Send a System Message to the caster
  1822. sendPacket(SystemMessageId.NOT_ENOUGH_MP);
  1823. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1824. sendPacket(ActionFailed.STATIC_PACKET);
  1825. return false;
  1826. }
  1827. // Check if the caster has enough HP
  1828. if (getCurrentHp() <= skill.getHpConsume())
  1829. {
  1830. // Send a System Message to the caster
  1831. sendPacket(SystemMessageId.NOT_ENOUGH_HP);
  1832. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1833. sendPacket(ActionFailed.STATIC_PACKET);
  1834. return false;
  1835. }
  1836. // Skill mute checks.
  1837. if (!skill.isStatic())
  1838. {
  1839. // Check if the skill is a magic spell and if the L2Character is not muted
  1840. if (skill.isMagic())
  1841. {
  1842. if (isMuted())
  1843. {
  1844. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1845. sendPacket(ActionFailed.STATIC_PACKET);
  1846. return false;
  1847. }
  1848. }
  1849. else
  1850. {
  1851. // Check if the skill is physical and if the L2Character is not physical_muted
  1852. if (isPhysicalMuted())
  1853. {
  1854. // Send a Server->Client packet ActionFailed to the L2PcInstance
  1855. sendPacket(ActionFailed.STATIC_PACKET);
  1856. return false;
  1857. }
  1858. }
  1859. }
  1860. // prevent casting signets to peace zone
  1861. if (skill.isChanneling() && (skill.getChannelingSkillId() > 0))
  1862. {
  1863. L2WorldRegion region = getWorldRegion();
  1864. if (region == null)
  1865. {
  1866. return false;
  1867. }
  1868. boolean canCast = true;
  1869. if ((skill.getTargetType() == L2TargetType.GROUND) && isPlayer())
  1870. {
  1871. Location wp = getActingPlayer().getCurrentSkillWorldPosition();
  1872. if (!region.checkEffectRangeInsidePeaceZone(skill, wp.getX(), wp.getY(), wp.getZ()))
  1873. {
  1874. canCast = false;
  1875. }
  1876. }
  1877. else if (!region.checkEffectRangeInsidePeaceZone(skill, getX(), getY(), getZ()))
  1878. {
  1879. canCast = false;
  1880. }
  1881. if (!canCast)
  1882. {
  1883. SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED);
  1884. sm.addSkillName(skill);
  1885. sendPacket(sm);
  1886. return false;
  1887. }
  1888. }
  1889. // Check if the caster's weapon is limited to use only its own skills
  1890. if (getActiveWeaponItem() != null)
  1891. {
  1892. L2Weapon wep = getActiveWeaponItem();
  1893. if (wep.useWeaponSkillsOnly() && !isGM() && wep.hasSkills())
  1894. {
  1895. boolean found = false;
  1896. for (SkillHolder sh : wep.getSkills())
  1897. {
  1898. if (sh.getSkillId() == skill.getId())
  1899. {
  1900. found = true;
  1901. }
  1902. }
  1903. if (!found)
  1904. {
  1905. if (getActingPlayer() != null)
  1906. {
  1907. sendPacket(SystemMessageId.WEAPON_CAN_USE_ONLY_WEAPON_SKILL);
  1908. }
  1909. return false;
  1910. }
  1911. }
  1912. }
  1913. // Check if the spell consumes an Item
  1914. // TODO: combine check and consume
  1915. if ((skill.getItemConsumeId() > 0) && (getInventory() != null))
  1916. {
  1917. // Get the L2ItemInstance consumed by the spell
  1918. L2ItemInstance requiredItems = getInventory().getItemByItemId(skill.getItemConsumeId());
  1919. // Check if the caster owns enough consumed Item to cast
  1920. if ((requiredItems == null) || (requiredItems.getCount() < skill.getItemConsumeCount()))
  1921. {
  1922. // Checked: when a summon skill failed, server show required consume item count
  1923. if (skill.hasEffectType(L2EffectType.SUMMON))
  1924. {
  1925. SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.SUMMONING_SERVITOR_COSTS_S2_S1);
  1926. sm.addItemName(skill.getItemConsumeId());
  1927. sm.addInt(skill.getItemConsumeCount());
  1928. sendPacket(sm);
  1929. }
  1930. else
  1931. {
  1932. // Send a System Message to the caster
  1933. sendPacket(SystemMessageId.THERE_ARE_NOT_ENOUGH_NECESSARY_ITEMS_TO_USE_THE_SKILL);
  1934. }
  1935. return false;
  1936. }
  1937. }
  1938. return true;
  1939. }
  1940. /**
  1941. * Gets the item reuse time stamps map.
  1942. * @return the item reuse time stamps map
  1943. */
  1944. public final Map<Integer, TimeStamp> getItemReuseTimeStamps()
  1945. {
  1946. return _reuseTimeStampsItems;
  1947. }
  1948. /**
  1949. * Adds a item reuse time stamp.
  1950. * @param item the item
  1951. * @param reuse the reuse
  1952. */
  1953. public final void addTimeStampItem(L2ItemInstance item, long reuse)
  1954. {
  1955. addTimeStampItem(item, reuse, -1);
  1956. }
  1957. /**
  1958. * Adds a item reuse time stamp.<br>
  1959. * Used for restoring purposes.
  1960. * @param item the item
  1961. * @param reuse the reuse
  1962. * @param systime the system time
  1963. */
  1964. public final void addTimeStampItem(L2ItemInstance item, long reuse, long systime)
  1965. {
  1966. if (_reuseTimeStampsItems == null)
  1967. {
  1968. synchronized (this)
  1969. {
  1970. if (_reuseTimeStampsItems == null)
  1971. {
  1972. _reuseTimeStampsItems = new ConcurrentHashMap<>();
  1973. }
  1974. }
  1975. }
  1976. _reuseTimeStampsItems.put(item.getObjectId(), new TimeStamp(item, reuse, systime));
  1977. }
  1978. /**
  1979. * Gets the item remaining reuse time for a given item object ID.
  1980. * @param itemObjId the item object ID
  1981. * @return if the item has a reuse time stamp, the remaining time, otherwise -1
  1982. */
  1983. public synchronized final long getItemRemainingReuseTime(int itemObjId)
  1984. {
  1985. final TimeStamp reuseStamp = (_reuseTimeStampsItems != null) ? _reuseTimeStampsItems.get(itemObjId) : null;
  1986. return reuseStamp != null ? reuseStamp.getRemaining() : -1;
  1987. }
  1988. /**
  1989. * Gets the item remaining reuse time for a given shared reuse item group.
  1990. * @param group the shared reuse item group
  1991. * @return if the shared reuse item group has a reuse time stamp, the remaining time, otherwise -1
  1992. */
  1993. public final long getReuseDelayOnGroup(int group)
  1994. {
  1995. if ((group > 0) && (_reuseTimeStampsItems != null))
  1996. {
  1997. for (TimeStamp ts : _reuseTimeStampsItems.values())
  1998. {
  1999. if ((ts.getSharedReuseGroup() == group) && ts.hasNotPassed())
  2000. {
  2001. return ts.getRemaining();
  2002. }
  2003. }
  2004. }
  2005. return -1;
  2006. }
  2007. /**
  2008. * Gets the skill reuse time stamps map.
  2009. * @return the skill reuse time stamps map
  2010. */
  2011. public final Map<Integer, TimeStamp> getSkillReuseTimeStamps()
  2012. {
  2013. return _reuseTimeStampsSkills;
  2014. }
  2015. /**
  2016. * Adds the skill reuse time stamp.
  2017. * @param skill the skill
  2018. * @param reuse the delay
  2019. */
  2020. public final void addTimeStamp(Skill skill, long reuse)
  2021. {
  2022. addTimeStamp(skill, reuse, -1);
  2023. }
  2024. /**
  2025. * Adds the skill reuse time stamp.<br>
  2026. * Used for restoring purposes.
  2027. * @param skill the skill
  2028. * @param reuse the reuse
  2029. * @param systime the system time
  2030. */
  2031. public final void addTimeStamp(Skill skill, long reuse, long systime)
  2032. {
  2033. if (_reuseTimeStampsSkills == null)
  2034. {
  2035. synchronized (this)
  2036. {
  2037. if (_reuseTimeStampsSkills == null)
  2038. {
  2039. _reuseTimeStampsSkills = new ConcurrentHashMap<>();
  2040. }
  2041. }
  2042. }
  2043. _reuseTimeStampsSkills.put(skill.getReuseHashCode(), new TimeStamp(skill, reuse, systime));
  2044. }
  2045. /**
  2046. * Removes a skill reuse time stamp.
  2047. * @param skill the skill to remove
  2048. */
  2049. public synchronized final void removeTimeStamp(Skill skill)
  2050. {
  2051. if (_reuseTimeStampsSkills != null)
  2052. {
  2053. _reuseTimeStampsSkills.remove(skill.getReuseHashCode());
  2054. }
  2055. }
  2056. /**
  2057. * Removes all skill reuse time stamps.
  2058. */
  2059. public synchronized final void resetTimeStamps()
  2060. {
  2061. if (_reuseTimeStampsSkills != null)
  2062. {
  2063. _reuseTimeStampsSkills.clear();
  2064. }
  2065. }
  2066. /**
  2067. * Gets the skill remaining reuse time for a given skill hash code.
  2068. * @param hashCode the skill hash code
  2069. * @return if the skill has a reuse time stamp, the remaining time, otherwise -1
  2070. */
  2071. public synchronized final long getSkillRemainingReuseTime(int hashCode)
  2072. {
  2073. final TimeStamp reuseStamp = (_reuseTimeStampsSkills != null) ? _reuseTimeStampsSkills.get(hashCode) : null;
  2074. return reuseStamp != null ? reuseStamp.getRemaining() : -1;
  2075. }
  2076. /**
  2077. * Verifies if the skill is under reuse time.
  2078. * @param hashCode the skill hash code
  2079. * @return {@code true} if the skill is under reuse time, {@code false} otherwise
  2080. */
  2081. public synchronized final boolean hasSkillReuse(int hashCode)
  2082. {
  2083. final TimeStamp reuseStamp = (_reuseTimeStampsSkills != null) ? _reuseTimeStampsSkills.get(hashCode) : null;
  2084. return (reuseStamp != null) && reuseStamp.hasNotPassed();
  2085. }
  2086. /**
  2087. * Gets the skill reuse time stamp.
  2088. * @param hashCode the skill hash code
  2089. * @return if the skill has a reuse time stamp, the skill reuse time stamp, otherwise {@code null}
  2090. */
  2091. public synchronized final TimeStamp getSkillReuseTimeStamp(int hashCode)
  2092. {
  2093. return _reuseTimeStampsSkills != null ? _reuseTimeStampsSkills.get(hashCode) : null;
  2094. }
  2095. /**
  2096. * Gets the disabled skills map.
  2097. * @return the disabled skills map
  2098. */
  2099. public Map<Integer, Long> getDisabledSkills()
  2100. {
  2101. return _disabledSkills;
  2102. }
  2103. /**
  2104. * Enables a skill.
  2105. * @param skill the skill to enable
  2106. */
  2107. public void enableSkill(Skill skill)
  2108. {
  2109. if ((skill == null) || (_disabledSkills == null))
  2110. {
  2111. return;
  2112. }
  2113. _disabledSkills.remove(skill.getReuseHashCode());
  2114. }
  2115. /**
  2116. * Disables a skill for a given time.<br>
  2117. * If delay is lesser or equal than zero, skill will be disabled "forever".
  2118. * @param skill the skill to disable
  2119. * @param delay delay in milliseconds
  2120. */
  2121. public void disableSkill(Skill skill, long delay)
  2122. {
  2123. if (skill == null)
  2124. {
  2125. return;
  2126. }
  2127. if (_disabledSkills == null)
  2128. {
  2129. synchronized (this)
  2130. {
  2131. if (_disabledSkills == null)
  2132. {
  2133. _disabledSkills = new ConcurrentHashMap<>();
  2134. }
  2135. }
  2136. }
  2137. _disabledSkills.put(skill.getReuseHashCode(), delay > 0 ? System.currentTimeMillis() + delay : Long.MAX_VALUE);
  2138. }
  2139. /**
  2140. * Removes all the disabled skills.
  2141. */
  2142. public synchronized final void resetDisabledSkills()
  2143. {
  2144. if (_disabledSkills != null)
  2145. {
  2146. _disabledSkills.clear();
  2147. }
  2148. }
  2149. /**
  2150. * Verifies if the skill is disabled.
  2151. * @param skill the skill
  2152. * @return {@code true} if the skill is disabled, {@code false} otherwise
  2153. */
  2154. public boolean isSkillDisabled(Skill skill)
  2155. {
  2156. return (skill != null) && isSkillDisabled(skill.getReuseHashCode());
  2157. }
  2158. /**
  2159. * Verifies if the skill is disabled.
  2160. * @param hashCode the skill hash code
  2161. * @return {@code true} if the skill is disabled, {@code false} otherwise
  2162. */
  2163. public boolean isSkillDisabled(int hashCode)
  2164. {
  2165. if (isAllSkillsDisabled())
  2166. {
  2167. return true;
  2168. }
  2169. if (_disabledSkills == null)
  2170. {
  2171. return false;
  2172. }
  2173. final Long stamp = _disabledSkills.get(hashCode);
  2174. if (stamp == null)
  2175. {
  2176. return false;
  2177. }
  2178. if (stamp < System.currentTimeMillis())
  2179. {
  2180. _disabledSkills.remove(hashCode);
  2181. return false;
  2182. }
  2183. return true;
  2184. }
  2185. /**
  2186. * Disables all skills.
  2187. */
  2188. public void disableAllSkills()
  2189. {
  2190. _allSkillsDisabled = true;
  2191. }
  2192. /**
  2193. * Enables all skills, except those under reuse time or previously disabled.
  2194. */
  2195. public void enableAllSkills()
  2196. {
  2197. _allSkillsDisabled = false;
  2198. }
  2199. /**
  2200. * Kill the L2Character.<br>
  2201. * <B><U>Actions</U>:</B>
  2202. * <ul>
  2203. * <li>Set target to null and cancel Attack or Cast</li>
  2204. * <li>Stop movement</li>
  2205. * <li>Stop HP/MP/CP Regeneration task</li>
  2206. * <li>Stop all active skills effects in progress on the L2Character</li>
  2207. * <li>Send the Server->Client packet StatusUpdate with current HP and MP to all other L2PcInstance to inform</li>
  2208. * <li>Notify L2Character AI</li>
  2209. * </ul>
  2210. * @param killer The L2Character who killed it
  2211. * @return false if the player is already dead.
  2212. */
  2213. public boolean doDie(L2Character killer)
  2214. {
  2215. final TerminateReturn returnBack = EventDispatcher.getInstance().notifyEvent(new OnCreatureKill(killer, this), this, TerminateReturn.class);
  2216. if ((returnBack != null) && returnBack.terminate())
  2217. {
  2218. return false;
  2219. }
  2220. // killing is only possible one time
  2221. synchronized (this)
  2222. {
  2223. if (isDead())
  2224. {
  2225. return false;
  2226. }
  2227. // now reset currentHp to zero
  2228. setCurrentHp(0);
  2229. setIsDead(true);
  2230. }
  2231. // Set target to null and cancel Attack or Cast
  2232. setTarget(null);
  2233. // Stop movement
  2234. stopMove(null);
  2235. // Stop HP/MP/CP Regeneration task
  2236. getStatus().stopHpMpRegeneration();
  2237. stopAllEffectsExceptThoseThatLastThroughDeath();
  2238. if (isPlayer() && (getActingPlayer().getAgathionId() != 0))
  2239. {
  2240. getActingPlayer().setAgathionId(0);
  2241. }
  2242. calculateRewards(killer);
  2243. // Send the Server->Client packet StatusUpdate with current HP and MP to all other L2PcInstance to inform
  2244. broadcastStatusUpdate();
  2245. // Notify L2Character AI
  2246. if (hasAI())
  2247. {
  2248. getAI().notifyEvent(CtrlEvent.EVT_DEAD);
  2249. }
  2250. if (getWorldRegion() != null)
  2251. {
  2252. getWorldRegion().onDeath(this);
  2253. }
  2254. getAttackByList().clear();
  2255. if (isChannelized())
  2256. {
  2257. getSkillChannelized().abortChannelization();
  2258. }
  2259. return true;
  2260. }
  2261. @Override
  2262. public boolean deleteMe()
  2263. {
  2264. setDebug(null);
  2265. if (hasAI())
  2266. {
  2267. getAI().stopAITask();
  2268. }
  2269. return true;
  2270. }
  2271. protected void calculateRewards(L2Character killer)
  2272. {
  2273. }
  2274. /** Sets HP, MP and CP and revives the L2Character. */
  2275. public void doRevive()
  2276. {
  2277. if (!isDead())
  2278. {
  2279. return;
  2280. }
  2281. if (!isTeleporting())
  2282. {
  2283. setIsPendingRevive(false);
  2284. setIsDead(false);
  2285. if ((Config.RESPAWN_RESTORE_CP > 0) && (getCurrentCp() < (getMaxCp() * Config.RESPAWN_RESTORE_CP)))
  2286. {
  2287. _status.setCurrentCp(getMaxCp() * Config.RESPAWN_RESTORE_CP);
  2288. }
  2289. if ((Config.RESPAWN_RESTORE_HP > 0) && (getCurrentHp() < (getMaxHp() * Config.RESPAWN_RESTORE_HP)))
  2290. {
  2291. _status.setCurrentHp(getMaxHp() * Config.RESPAWN_RESTORE_HP);
  2292. }
  2293. if ((Config.RESPAWN_RESTORE_MP > 0) && (getCurrentMp() < (getMaxMp() * Config.RESPAWN_RESTORE_MP)))
  2294. {
  2295. _status.setCurrentMp(getMaxMp() * Config.RESPAWN_RESTORE_MP);
  2296. }
  2297. // Start broadcast status
  2298. broadcastPacket(new Revive(this));
  2299. if (getWorldRegion() != null)
  2300. {
  2301. getWorldRegion().onRevive(this);
  2302. }
  2303. }
  2304. else
  2305. {
  2306. setIsPendingRevive(true);
  2307. }
  2308. }
  2309. /**
  2310. * Revives the L2Character using skill.
  2311. * @param revivePower
  2312. */
  2313. public void doRevive(double revivePower)
  2314. {
  2315. doRevive();
  2316. }
  2317. /**
  2318. * Gets this creature's AI.
  2319. * @return the AI
  2320. */
  2321. public final L2CharacterAI getAI()
  2322. {
  2323. if (_ai == null)
  2324. {
  2325. synchronized (this)
  2326. {
  2327. if (_ai == null)
  2328. {
  2329. _ai = initAI();
  2330. }
  2331. }
  2332. }
  2333. return _ai;
  2334. }
  2335. /**
  2336. * Initialize this creature's AI.<br>
  2337. * OOP approach to be overridden in child classes.
  2338. * @return the new AI
  2339. */
  2340. protected L2CharacterAI initAI()
  2341. {
  2342. return new L2CharacterAI(new AIAccessor());
  2343. }
  2344. public void setAI(L2CharacterAI newAI)
  2345. {
  2346. L2CharacterAI oldAI = _ai;
  2347. if ((oldAI != null) && (oldAI != newAI) && (oldAI instanceof L2AttackableAI))
  2348. {
  2349. oldAI.stopAITask();
  2350. }
  2351. _ai = newAI;
  2352. }
  2353. /**
  2354. * Verifies if this creature has an AI,
  2355. * @return {@code true} if this creature has an AI, {@code false} otherwise
  2356. */
  2357. public boolean hasAI()
  2358. {
  2359. return _ai != null;
  2360. }
  2361. /**
  2362. * @return True if the L2Character is RaidBoss or his minion.
  2363. */
  2364. public boolean isRaid()
  2365. {
  2366. return false;
  2367. }
  2368. /**
  2369. * @return True if the L2Character is minion.
  2370. */
  2371. public boolean isMinion()
  2372. {
  2373. return false;
  2374. }
  2375. /**
  2376. * @return True if the L2Character is minion of RaidBoss.
  2377. */
  2378. public boolean isRaidMinion()
  2379. {
  2380. return false;
  2381. }
  2382. /**
  2383. * @return a list of L2Character that attacked.
  2384. */
  2385. public final Set<L2Character> getAttackByList()
  2386. {
  2387. if (_attackByList == null)
  2388. {
  2389. synchronized (this)
  2390. {
  2391. if (_attackByList == null)
  2392. {
  2393. _attackByList = new WeakFastSet<>(true);
  2394. }
  2395. }
  2396. }
  2397. return _attackByList;
  2398. }
  2399. public final Skill getLastSimultaneousSkillCast()
  2400. {
  2401. return _lastSimultaneousSkillCast;
  2402. }
  2403. public void setLastSimultaneousSkillCast(Skill skill)
  2404. {
  2405. _lastSimultaneousSkillCast = skill;
  2406. }
  2407. public final Skill getLastSkillCast()
  2408. {
  2409. return _lastSkillCast;
  2410. }
  2411. public void setLastSkillCast(Skill skill)
  2412. {
  2413. _lastSkillCast = skill;
  2414. }
  2415. public final boolean isNoRndWalk()
  2416. {
  2417. return _isNoRndWalk;
  2418. }
  2419. public final void setIsNoRndWalk(boolean value)
  2420. {
  2421. _isNoRndWalk = value;
  2422. }
  2423. public final boolean isAfraid()
  2424. {
  2425. return isAffected(EffectFlag.FEAR);
  2426. }
  2427. /**
  2428. * @return True if the L2Character can't use its skills (ex : stun, sleep...).
  2429. */
  2430. public final boolean isAllSkillsDisabled()
  2431. {
  2432. return _allSkillsDisabled || isStunned() || isSleeping() || isParalyzed();
  2433. }
  2434. /**
  2435. * @return True if the L2Character can't attack (stun, sleep, attackEndTime, fakeDeath, paralyze, attackMute).
  2436. */
  2437. public boolean isAttackingDisabled()
  2438. {
  2439. return isFlying() || isStunned() || isSleeping() || isAttackingNow() || isAlikeDead() || isParalyzed() || isPhysicalAttackMuted() || isCoreAIDisabled();
  2440. }
  2441. public final Calculator[] getCalculators()
  2442. {
  2443. return _calculators;
  2444. }
  2445. public final boolean isConfused()
  2446. {
  2447. return isAffected(EffectFlag.CONFUSED);
  2448. }
  2449. /**
  2450. * @return True if the L2Character is dead or use fake death.
  2451. */
  2452. public boolean isAlikeDead()
  2453. {
  2454. return _isDead;
  2455. }
  2456. /**
  2457. * @return True if the L2Character is dead.
  2458. */
  2459. public final boolean isDead()
  2460. {
  2461. return _isDead;
  2462. }
  2463. public final void setIsDead(boolean value)
  2464. {
  2465. _isDead = value;
  2466. }
  2467. public boolean isImmobilized()
  2468. {
  2469. return _isImmobilized;
  2470. }
  2471. public void setIsImmobilized(boolean value)
  2472. {
  2473. _isImmobilized = value;
  2474. }
  2475. public final boolean isMuted()
  2476. {
  2477. return isAffected(EffectFlag.MUTED);
  2478. }
  2479. public final boolean isPhysicalMuted()
  2480. {
  2481. return isAffected(EffectFlag.PSYCHICAL_MUTED);
  2482. }
  2483. public final boolean isPhysicalAttackMuted()
  2484. {
  2485. return isAffected(EffectFlag.PSYCHICAL_ATTACK_MUTED);
  2486. }
  2487. /**
  2488. * @return True if the L2Character can't move (stun, root, sleep, overload, paralyzed).
  2489. */
  2490. public boolean isMovementDisabled()
  2491. {
  2492. // check for isTeleporting to prevent teleport cheating (if appear packet not received)
  2493. return isStunned() || isRooted() || isSleeping() || isOverloaded() || isParalyzed() || isImmobilized() || isAlikeDead() || isTeleporting();
  2494. }
  2495. /**
  2496. * @return True if the L2Character can not be controlled by the player (confused, afraid).
  2497. */
  2498. public final boolean isOutOfControl()
  2499. {
  2500. return isConfused() || isAfraid();
  2501. }
  2502. public final boolean isOverloaded()
  2503. {
  2504. return _isOverloaded;
  2505. }
  2506. /**
  2507. * Set the overloaded status of the L2Character is overloaded (if True, the L2PcInstance can't take more item).
  2508. * @param value
  2509. */
  2510. public final void setIsOverloaded(boolean value)
  2511. {
  2512. _isOverloaded = value;
  2513. }
  2514. public final boolean isParalyzed()
  2515. {
  2516. return _isParalyzed || isAffected(EffectFlag.PARALYZED);
  2517. }
  2518. public final void setIsParalyzed(boolean value)
  2519. {
  2520. _isParalyzed = value;
  2521. }
  2522. public final boolean isPendingRevive()
  2523. {
  2524. return isDead() && _isPendingRevive;
  2525. }
  2526. public final void setIsPendingRevive(boolean value)
  2527. {
  2528. _isPendingRevive = value;
  2529. }
  2530. public final boolean isDisarmed()
  2531. {
  2532. return isAffected(EffectFlag.DISARMED);
  2533. }
  2534. /**
  2535. * @return the summon
  2536. */
  2537. public L2Summon getSummon()
  2538. {
  2539. return null;
  2540. }
  2541. /**
  2542. * @return {@code true} if the character has a summon, {@code false} otherwise
  2543. */
  2544. public final boolean hasSummon()
  2545. {
  2546. return getSummon() != null;
  2547. }
  2548. /**
  2549. * @return {@code true} if the character has a pet, {@code false} otherwise
  2550. */
  2551. public final boolean hasPet()
  2552. {
  2553. return hasSummon() && getSummon().isPet();
  2554. }
  2555. /**
  2556. * @return {@code true} if the character has a servitor, {@code false} otherwise
  2557. */
  2558. public final boolean hasServitor()
  2559. {
  2560. return hasSummon() && getSummon().isServitor();
  2561. }
  2562. public final boolean isRooted()
  2563. {
  2564. return isAffected(EffectFlag.ROOTED);
  2565. }
  2566. /**
  2567. * @return True if the L2Character is running.
  2568. */
  2569. public boolean isRunning()
  2570. {
  2571. return _isRunning;
  2572. }
  2573. public final void setIsRunning(boolean value)
  2574. {
  2575. if (_isRunning == value)
  2576. {
  2577. return;
  2578. }
  2579. _isRunning = value;
  2580. if (getRunSpeed() != 0)
  2581. {
  2582. broadcastPacket(new ChangeMoveType(this));
  2583. }
  2584. if (isPlayer())
  2585. {
  2586. getActingPlayer().broadcastUserInfo();
  2587. }
  2588. else if (isSummon())
  2589. {
  2590. broadcastStatusUpdate();
  2591. }
  2592. else if (isNpc())
  2593. {
  2594. Collection<L2PcInstance> plrs = getKnownList().getKnownPlayers().values();
  2595. for (L2PcInstance player : plrs)
  2596. {
  2597. if ((player == null) || !isVisibleFor(player))
  2598. {
  2599. continue;
  2600. }
  2601. else if (getRunSpeed() == 0)
  2602. {
  2603. player.sendPacket(new ServerObjectInfo((L2Npc) this, player));
  2604. }
  2605. else
  2606. {
  2607. player.sendPacket(new AbstractNpcInfo.NpcInfo((L2Npc) this, player));
  2608. }
  2609. }
  2610. }
  2611. }
  2612. /** Set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all others L2PcInstance. */
  2613. public final void setRunning()
  2614. {
  2615. if (!isRunning())
  2616. {
  2617. setIsRunning(true);
  2618. }
  2619. }
  2620. public final boolean isSleeping()
  2621. {
  2622. return isAffected(EffectFlag.SLEEP);
  2623. }
  2624. public final boolean isStunned()
  2625. {
  2626. return isAffected(EffectFlag.STUNNED);
  2627. }
  2628. public final boolean isBetrayed()
  2629. {
  2630. return isAffected(EffectFlag.BETRAYED);
  2631. }
  2632. public final boolean isTeleporting()
  2633. {
  2634. return _isTeleporting;
  2635. }
  2636. public void setIsTeleporting(boolean value)
  2637. {
  2638. _isTeleporting = value;
  2639. }
  2640. public void setIsInvul(boolean b)
  2641. {
  2642. _isInvul = b;
  2643. }
  2644. public boolean isInvul()
  2645. {
  2646. return _isInvul || _isTeleporting || isAffected(EffectFlag.INVUL);
  2647. }
  2648. public void setIsMortal(boolean b)
  2649. {
  2650. _isMortal = b;
  2651. }
  2652. public boolean isMortal()
  2653. {
  2654. return _isMortal;
  2655. }
  2656. public boolean isUndead()
  2657. {
  2658. return false;
  2659. }
  2660. public boolean isResurrectionBlocked()
  2661. {
  2662. return isAffected(EffectFlag.BLOCK_RESURRECTION);
  2663. }
  2664. public final boolean isFlying()
  2665. {
  2666. return _isFlying;
  2667. }
  2668. public final void setIsFlying(boolean mode)
  2669. {
  2670. _isFlying = mode;
  2671. }
  2672. @Override
  2673. public CharKnownList getKnownList()
  2674. {
  2675. return ((CharKnownList) super.getKnownList());
  2676. }
  2677. @Override
  2678. public void initKnownList()
  2679. {
  2680. setKnownList(new CharKnownList(this));
  2681. }
  2682. public CharStat getStat()
  2683. {
  2684. return _stat;
  2685. }
  2686. /**
  2687. * Initializes the CharStat class of the L2Object, is overwritten in classes that require a different CharStat Type.<br>
  2688. * Removes the need for instanceof checks.
  2689. */
  2690. public void initCharStat()
  2691. {
  2692. _stat = new CharStat(this);
  2693. }
  2694. public final void setStat(CharStat value)
  2695. {
  2696. _stat = value;
  2697. }
  2698. public CharStatus getStatus()
  2699. {
  2700. return _status;
  2701. }
  2702. /**
  2703. * Initializes the CharStatus class of the L2Object, is overwritten in classes that require a different CharStatus Type.<br>
  2704. * Removes the need for instanceof checks.
  2705. */
  2706. public void initCharStatus()
  2707. {
  2708. _status = new CharStatus(this);
  2709. }
  2710. public final void setStatus(CharStatus value)
  2711. {
  2712. _status = value;
  2713. }
  2714. public L2CharTemplate getTemplate()
  2715. {
  2716. return _template;
  2717. }
  2718. /**
  2719. * Set the template of the L2Character.<br>
  2720. * <B><U>Concept</U>:</B><br>
  2721. * Each L2Character owns generic and static properties (ex : all Keltir have the same number of HP...).<br>
  2722. * All of those properties are stored in a different template for each type of L2Character.<br>
  2723. * Each template is loaded once in the server cache memory (reduce memory use).<br>
  2724. * When a new instance of L2Character is spawned, server just create a link between the instance and the template This link is stored in <B>_template</B>.
  2725. * @param template
  2726. */
  2727. protected final void setTemplate(L2CharTemplate template)
  2728. {
  2729. _template = template;
  2730. }
  2731. /**
  2732. * @return the Title of the L2Character.
  2733. */
  2734. public final String getTitle()
  2735. {
  2736. return _title;
  2737. }
  2738. /**
  2739. * Set the Title of the L2Character.
  2740. * @param value
  2741. */
  2742. public final void setTitle(String value)
  2743. {
  2744. if (value == null)
  2745. {
  2746. _title = "";
  2747. }
  2748. else
  2749. {
  2750. _title = value.length() > 21 ? value.substring(0, 20) : value;
  2751. }
  2752. }
  2753. /**
  2754. * Set the L2Character movement type to walk and send Server->Client packet ChangeMoveType to all others L2PcInstance.
  2755. */
  2756. public final void setWalking()
  2757. {
  2758. if (isRunning())
  2759. {
  2760. setIsRunning(false);
  2761. }
  2762. }
  2763. /**
  2764. * Gets the abnormal visual effects affecting this character.
  2765. * @return a map of 32 bits containing all abnormal visual effects in progress for this character
  2766. */
  2767. public int getAbnormalVisualEffects()
  2768. {
  2769. return _abnormalVisualEffects;
  2770. }
  2771. /**
  2772. * Gets the special abnormal visual effects affecting this character.
  2773. * @return a map of 32 bits containing all special effect in progress for this character
  2774. */
  2775. public int getAbnormalVisualEffectSpecial()
  2776. {
  2777. return _abnormalVisualEffectsSpecial;
  2778. }
  2779. /**
  2780. * Gets the event abnormal visual effects affecting this character.
  2781. * @return a map of 32 bits containing all event abnormal visual effects in progress for this character
  2782. */
  2783. public int getAbnormalVisualEffectEvent()
  2784. {
  2785. return _abnormalVisualEffectsEvent;
  2786. }
  2787. /**
  2788. * Verify if this creature is affected by the given abnormal visual effect.
  2789. * @param ave the abnormal visual effect
  2790. * @return {@code true} if the creature is affected by the abnormal visual effect, {@code false} otherwise
  2791. */
  2792. public boolean hasAbnormalVisualEffect(AbnormalVisualEffect ave)
  2793. {
  2794. if (ave.isEvent())
  2795. {
  2796. return (getAbnormalVisualEffectEvent() & ave.getMask()) == ave.getMask();
  2797. }
  2798. if (ave.isSpecial())
  2799. {
  2800. return (getAbnormalVisualEffectSpecial() & ave.getMask()) == ave.getMask();
  2801. }
  2802. return (getAbnormalVisualEffects() & ave.getMask()) == ave.getMask();
  2803. }
  2804. /**
  2805. * Adds the abnormal visual effect flags in the binary mask and send Server->Client UserInfo/CharInfo packet.
  2806. * @param update if {@code true} update packets will be sent
  2807. * @param aves the abnormal visual effects
  2808. */
  2809. public final void startAbnormalVisualEffect(boolean update, AbnormalVisualEffect... aves)
  2810. {
  2811. for (AbnormalVisualEffect ave : aves)
  2812. {
  2813. if (ave.isEvent())
  2814. {
  2815. _abnormalVisualEffectsEvent |= ave.getMask();
  2816. }
  2817. else if (ave.isSpecial())
  2818. {
  2819. _abnormalVisualEffectsSpecial |= ave.getMask();
  2820. }
  2821. else
  2822. {
  2823. _abnormalVisualEffects |= ave.getMask();
  2824. }
  2825. }
  2826. if (update)
  2827. {
  2828. updateAbnormalEffect();
  2829. }
  2830. }
  2831. /**
  2832. * Removes the abnormal visual effect flags from the binary mask and send Server->Client UserInfo/CharInfo packet.
  2833. * @param update if {@code true} update packets will be sent
  2834. * @param aves the abnormal visual effects
  2835. */
  2836. public final void stopAbnormalVisualEffect(boolean update, AbnormalVisualEffect... aves)
  2837. {
  2838. for (AbnormalVisualEffect ave : aves)
  2839. {
  2840. if (ave.isEvent())
  2841. {
  2842. _abnormalVisualEffectsEvent &= ~ave.getMask();
  2843. }
  2844. else if (ave.isSpecial())
  2845. {
  2846. _abnormalVisualEffectsSpecial &= ~ave.getMask();
  2847. }
  2848. else
  2849. {
  2850. _abnormalVisualEffects &= ~ave.getMask();
  2851. }
  2852. }
  2853. if (update)
  2854. {
  2855. updateAbnormalEffect();
  2856. }
  2857. }
  2858. /**
  2859. * Active the abnormal effect Fake Death flag, notify the L2Character AI and send Server->Client UserInfo/CharInfo packet.
  2860. */
  2861. public final void startFakeDeath()
  2862. {
  2863. if (!isPlayer())
  2864. {
  2865. return;
  2866. }
  2867. getActingPlayer().setIsFakeDeath(true);
  2868. // Aborts any attacks/casts if fake dead
  2869. abortAttack();
  2870. abortCast();
  2871. stopMove(null);
  2872. getAI().notifyEvent(CtrlEvent.EVT_FAKE_DEATH);
  2873. broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_START_FAKEDEATH));
  2874. }
  2875. /**
  2876. * Launch a Stun Abnormal Effect on the L2Character.<br>
  2877. * <B><U>Actions</U>:</B>
  2878. * <ul>
  2879. * <li>Calculate the success rate of the Stun Abnormal Effect on this L2Character</li>
  2880. * <li>If Stun succeed, active the abnormal effect Stun flag, notify the L2Character AI and send Server->Client UserInfo/CharInfo packet</li>
  2881. * <li>If Stun NOT succeed, send a system message Failed to the L2PcInstance attacker</li>
  2882. * </ul>
  2883. */
  2884. public final void startStunning()
  2885. {
  2886. // Aborts any attacks/casts if stunned
  2887. abortAttack();
  2888. abortCast();
  2889. stopMove(null);
  2890. getAI().notifyEvent(CtrlEvent.EVT_STUNNED);
  2891. if (!isSummon())
  2892. {
  2893. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  2894. }
  2895. updateAbnormalEffect();
  2896. }
  2897. public final void startParalyze()
  2898. {
  2899. // Aborts any attacks/casts if paralyzed
  2900. abortAttack();
  2901. abortCast();
  2902. stopMove(null);
  2903. getAI().notifyEvent(CtrlEvent.EVT_PARALYZED);
  2904. }
  2905. /**
  2906. * Stop all active skills effects in progress on the L2Character.
  2907. */
  2908. public void stopAllEffects()
  2909. {
  2910. _effectList.stopAllEffects();
  2911. }
  2912. /**
  2913. * Stops all effects, except those that last through death.
  2914. */
  2915. public void stopAllEffectsExceptThoseThatLastThroughDeath()
  2916. {
  2917. _effectList.stopAllEffectsExceptThoseThatLastThroughDeath();
  2918. }
  2919. /**
  2920. * Stop and remove the effects corresponding to the skill ID.
  2921. * @param removed if {@code true} the effect will be set as removed, and a system message will be sent
  2922. * @param skillId the skill Id
  2923. */
  2924. public void stopSkillEffects(boolean removed, int skillId)
  2925. {
  2926. _effectList.stopSkillEffects(removed, skillId);
  2927. }
  2928. public final void stopEffects(L2EffectType type)
  2929. {
  2930. _effectList.stopEffects(type);
  2931. }
  2932. /**
  2933. * Exits all buffs effects of the skills with "removedOnAnyAction" set.<br>
  2934. * Called on any action except movement (attack, cast).
  2935. */
  2936. public final void stopEffectsOnAction()
  2937. {
  2938. _effectList.stopEffectsOnAction();
  2939. }
  2940. /**
  2941. * Exits all buffs effects of the skills with "removedOnDamage" set.<br>
  2942. * Called on decreasing HP and mana burn.
  2943. * @param awake
  2944. */
  2945. public final void stopEffectsOnDamage(boolean awake)
  2946. {
  2947. _effectList.stopEffectsOnDamage(awake);
  2948. }
  2949. /**
  2950. * Stop a specified/all Fake Death abnormal L2Effect.<br>
  2951. * <B><U>Actions</U>:</B>
  2952. * <ul>
  2953. * <li>Delete a specified/all (if effect=null) Fake Death abnormal L2Effect from L2Character and update client magic icon</li>
  2954. * <li>Set the abnormal effect flag _fake_death to False</li>
  2955. * <li>Notify the L2Character AI</li>
  2956. * </ul>
  2957. * @param removeEffects
  2958. */
  2959. public final void stopFakeDeath(boolean removeEffects)
  2960. {
  2961. if (removeEffects)
  2962. {
  2963. stopEffects(L2EffectType.FAKE_DEATH);
  2964. }
  2965. // if this is a player instance, start the grace period for this character (grace from mobs only)!
  2966. if (isPlayer())
  2967. {
  2968. getActingPlayer().setIsFakeDeath(false);
  2969. getActingPlayer().setRecentFakeDeath(true);
  2970. }
  2971. broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_STOP_FAKEDEATH));
  2972. // TODO: Temp hack: players see FD on ppl that are moving: Teleport to someone who uses FD - if he gets up he will fall down again for that client -
  2973. // even tho he is actually standing... Probably bad info in CharInfo packet?
  2974. broadcastPacket(new Revive(this));
  2975. }
  2976. /**
  2977. * Stop a specified/all Stun abnormal L2Effect.<br>
  2978. * <B><U>Actions</U>:</B>
  2979. * <ul>
  2980. * <li>Delete a specified/all (if effect=null) Stun abnormal L2Effect from L2Character and update client magic icon</li>
  2981. * <li>Set the abnormal effect flag _stuned to False</li>
  2982. * <li>Notify the L2Character AI</li>
  2983. * <li>Send Server->Client UserInfo/CharInfo packet</li>
  2984. * </ul>
  2985. * @param removeEffects
  2986. */
  2987. public final void stopStunning(boolean removeEffects)
  2988. {
  2989. if (removeEffects)
  2990. {
  2991. stopEffects(L2EffectType.STUN);
  2992. }
  2993. if (!isPlayer())
  2994. {
  2995. getAI().notifyEvent(CtrlEvent.EVT_THINK);
  2996. }
  2997. updateAbnormalEffect();
  2998. }
  2999. /**
  3000. * Stop L2Effect: Transformation.<br>
  3001. * <B><U>Actions</U>:</B>
  3002. * <ul>
  3003. * <li>Remove Transformation Effect</li>
  3004. * <li>Notify the L2Character AI</li>
  3005. * <li>Send Server->Client UserInfo/CharInfo packet</li>
  3006. * </ul>
  3007. * @param removeEffects
  3008. */
  3009. public final void stopTransformation(boolean removeEffects)
  3010. {
  3011. if (removeEffects)
  3012. {
  3013. getEffectList().stopSkillEffects(false, AbnormalType.TRANSFORM);
  3014. }
  3015. // if this is a player instance, then untransform, also set the transform_id column equal to 0 if not cursed.
  3016. if (isPlayer())
  3017. {
  3018. if (getActingPlayer().getTransformation() != null)
  3019. {
  3020. getActingPlayer().untransform();
  3021. }
  3022. }
  3023. if (!isPlayer())
  3024. {
  3025. getAI().notifyEvent(CtrlEvent.EVT_THINK);
  3026. }
  3027. updateAbnormalEffect();
  3028. }
  3029. public abstract void updateAbnormalEffect();
  3030. /**
  3031. * Update active skills in progress (In Use and Not In Use because stacked) icons on client.<br>
  3032. * <B><U>Concept</U>:</B><br>
  3033. * All active skills effects in progress (In Use and Not In Use because stacked) are represented by an icon on the client.<br>
  3034. * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method ONLY UPDATE the client of the player and not clients of all players in the party.</B></FONT>
  3035. */
  3036. public final void updateEffectIcons()
  3037. {
  3038. updateEffectIcons(false);
  3039. }
  3040. /**
  3041. * Updates Effect Icons for this character(player/summon) and his party if any.
  3042. * @param partyOnly
  3043. */
  3044. public void updateEffectIcons(boolean partyOnly)
  3045. {
  3046. // overridden
  3047. }
  3048. public boolean isAffectedBySkill(int skillId)
  3049. {
  3050. return _effectList.isAffectedBySkill(skillId);
  3051. }
  3052. // TODO: NEED TO ORGANIZE AND MOVE TO PROPER PLACE
  3053. /** This class permit to the L2Character AI to obtain informations and uses L2Character method */
  3054. public class AIAccessor
  3055. {
  3056. /**
  3057. * @return the L2Character managed by this Accessor AI.
  3058. */
  3059. public L2Character getActor()
  3060. {
  3061. return L2Character.this;
  3062. }
  3063. /**
  3064. * Accessor to L2Character moveToLocation() method with an interaction area.
  3065. * @param x
  3066. * @param y
  3067. * @param z
  3068. * @param offset
  3069. */
  3070. public void moveTo(int x, int y, int z, int offset)
  3071. {
  3072. moveToLocation(x, y, z, offset);
  3073. }
  3074. /**
  3075. * Accessor to L2Character moveToLocation() method without interaction area.
  3076. * @param x
  3077. * @param y
  3078. * @param z
  3079. */
  3080. public void moveTo(int x, int y, int z)
  3081. {
  3082. moveToLocation(x, y, z, 0);
  3083. }
  3084. /**
  3085. * Accessor to L2Character stopMove() method.
  3086. * @param loc
  3087. */
  3088. public void stopMove(Location loc)
  3089. {
  3090. L2Character.this.stopMove(loc);
  3091. }
  3092. /**
  3093. * Accessor to L2Character doAttack() method.
  3094. * @param target
  3095. */
  3096. public void doAttack(L2Character target)
  3097. {
  3098. L2Character.this.doAttack(target);
  3099. }
  3100. /**
  3101. * Accessor to L2Character doCast() method.
  3102. * @param skill
  3103. */
  3104. public void doCast(Skill skill)
  3105. {
  3106. L2Character.this.doCast(skill);
  3107. }
  3108. /**
  3109. * Create a NotifyAITask.
  3110. * @param evt
  3111. * @return
  3112. */
  3113. public NotifyAITask newNotifyTask(CtrlEvent evt)
  3114. {
  3115. return new NotifyAITask(getActor(), evt);
  3116. }
  3117. /**
  3118. * Cancel the AI.
  3119. */
  3120. public void detachAI()
  3121. {
  3122. // Skip character, if it is controlled by Walking Manager
  3123. if (isWalker())
  3124. {
  3125. return;
  3126. }
  3127. setAI(null);
  3128. }
  3129. }
  3130. /**
  3131. * This class group all movement data.<br>
  3132. * <B><U> Data</U> :</B>
  3133. * <ul>
  3134. * <li>_moveTimestamp : Last time position update</li>
  3135. * <li>_xDestination, _yDestination, _zDestination : Position of the destination</li>
  3136. * <li>_xMoveFrom, _yMoveFrom, _zMoveFrom : Position of the origin</li>
  3137. * <li>_moveStartTime : Start time of the movement</li>
  3138. * <li>_ticksToMove : Nb of ticks between the start and the destination</li>
  3139. * <li>_xSpeedTicks, _ySpeedTicks : Speed in unit/ticks</li>
  3140. * </ul>
  3141. */
  3142. public static class MoveData
  3143. {
  3144. // when we retrieve x/y/z we use GameTimeControl.getGameTicks()
  3145. // if we are moving, but move timestamp==gameticks, we don't need
  3146. // to recalculate position
  3147. public int _moveStartTime;
  3148. public int _moveTimestamp; // last update
  3149. public int _xDestination;
  3150. public int _yDestination;
  3151. public int _zDestination;
  3152. public double _xAccurate; // otherwise there would be rounding errors
  3153. public double _yAccurate;
  3154. public double _zAccurate;
  3155. public int _heading;
  3156. public boolean disregardingGeodata;
  3157. public int onGeodataPathIndex;
  3158. public List<AbstractNodeLoc> geoPath;
  3159. public int geoPathAccurateTx;
  3160. public int geoPathAccurateTy;
  3161. public int geoPathGtx;
  3162. public int geoPathGty;
  3163. }
  3164. /**
  3165. * Add a Func to the Calculator set of the L2Character.<br>
  3166. * <b><u>Concept</u>:</b> A L2Character owns a table of Calculators called <b>_calculators</b>.<br>
  3167. * Each Calculator (a calculator per state) own a table of Func object.<br>
  3168. * A Func object is a mathematical function that permit to calculate the modifier of a state (ex : REGENERATE_HP_RATE...).<br>
  3169. * To reduce cache memory use, L2NPCInstances who don't have skills share the same Calculator set called <b>NPC_STD_CALCULATOR</b>.<br>
  3170. * That's why, if a L2NPCInstance is under a skill/spell effect that modify one of its state, a copy of the NPC_STD_CALCULATOR must be create in its _calculators before adding new Func object.<br>
  3171. * <b><u>Actions</u>:</b>
  3172. * <ul>
  3173. * <li>If _calculators is linked to NPC_STD_CALCULATOR, create a copy of NPC_STD_CALCULATOR in _calculators</li>
  3174. * <li>Add the Func object to _calculators</li>
  3175. * </ul>
  3176. * @param function The Func object to add to the Calculator corresponding to the state affected
  3177. */
  3178. public final void addStatFunc(AbstractFunction function)
  3179. {
  3180. if (function == null)
  3181. {
  3182. return;
  3183. }
  3184. synchronized (this)
  3185. {
  3186. // Check if Calculator set is linked to the standard Calculator set of NPC
  3187. if (_calculators == NPC_STD_CALCULATOR)
  3188. {
  3189. // Create a copy of the standard NPC Calculator set
  3190. _calculators = new Calculator[Stats.NUM_STATS];
  3191. for (int i = 0; i < Stats.NUM_STATS; i++)
  3192. {
  3193. if (NPC_STD_CALCULATOR[i] != null)
  3194. {
  3195. _calculators[i] = new Calculator(NPC_STD_CALCULATOR[i]);
  3196. }
  3197. }
  3198. }
  3199. // Select the Calculator of the affected state in the Calculator set
  3200. int stat = function.getStat().ordinal();
  3201. if (_calculators[stat] == null)
  3202. {
  3203. _calculators[stat] = new Calculator();
  3204. }
  3205. // Add the Func to the calculator corresponding to the state
  3206. _calculators[stat].addFunc(function);
  3207. }
  3208. }
  3209. /**
  3210. * Add a list of Funcs to the Calculator set of the L2Character.<br>
  3211. * <B><U>Concept</U>:</B><br>
  3212. * A L2Character owns a table of Calculators called <B>_calculators</B>.<br>
  3213. * Each Calculator (a calculator per state) own a table of Func object.<br>
  3214. * A Func object is a mathematic function that permit to calculate the modifier of a state (ex : REGENERATE_HP_RATE...).<br>
  3215. * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method is ONLY for L2PcInstance</B></FONT><br>
  3216. * <B><U>Example of use</U>:</B>
  3217. * <ul>
  3218. * <li>Equip an item from inventory</li>
  3219. * <li>Learn a new passive skill</li>
  3220. * <li>Use an active skill</li>
  3221. * </ul>
  3222. * @param functions The list of Func objects to add to the Calculator corresponding to the state affected
  3223. */
  3224. public final void addStatFuncs(List<AbstractFunction> functions)
  3225. {
  3226. if (!isPlayer() && getKnownList().getKnownPlayers().isEmpty())
  3227. {
  3228. for (AbstractFunction f : functions)
  3229. {
  3230. addStatFunc(f);
  3231. }
  3232. }
  3233. else
  3234. {
  3235. final List<Stats> modifiedStats = new ArrayList<>();
  3236. for (AbstractFunction f : functions)
  3237. {
  3238. modifiedStats.add(f.getStat());
  3239. addStatFunc(f);
  3240. }
  3241. broadcastModifiedStats(modifiedStats);
  3242. }
  3243. }
  3244. /**
  3245. * Remove a Func from the Calculator set of the L2Character.<br>
  3246. * <B><U>Concept</U>:</B><br>
  3247. * A L2Character owns a table of Calculators called <B>_calculators</B>.<br>
  3248. * Each Calculator (a calculator per state) own a table of Func object.<br>
  3249. * A Func object is a mathematic function that permit to calculate the modifier of a state (ex : REGENERATE_HP_RATE...).<br>
  3250. * To reduce cache memory use, L2NPCInstances who don't have skills share the same Calculator set called <B>NPC_STD_CALCULATOR</B>.<br>
  3251. * That's why, if a L2NPCInstance is under a skill/spell effect that modify one of its state, a copy of the NPC_STD_CALCULATOR must be create in its _calculators before addind new Func object.<br>
  3252. * <B><U>Actions</U>:</B>
  3253. * <ul>
  3254. * <li>Remove the Func object from _calculators</li>
  3255. * <li>If L2Character is a L2NPCInstance and _calculators is equal to NPC_STD_CALCULATOR, free cache memory and just create a link on NPC_STD_CALCULATOR in _calculators</li>
  3256. * </ul>
  3257. * @param function The Func object to remove from the Calculator corresponding to the state affected
  3258. */
  3259. public final void removeStatFunc(AbstractFunction function)
  3260. {
  3261. if (function == null)
  3262. {
  3263. return;
  3264. }
  3265. // Select the Calculator of the affected state in the Calculator set
  3266. int stat = function.getStat().ordinal();
  3267. synchronized (this)
  3268. {
  3269. if (_calculators[stat] == null)
  3270. {
  3271. return;
  3272. }
  3273. // Remove the Func object from the Calculator
  3274. _calculators[stat].removeFunc(function);
  3275. if (_calculators[stat].size() == 0)
  3276. {
  3277. _calculators[stat] = null;
  3278. }
  3279. // If possible, free the memory and just create a link on NPC_STD_CALCULATOR
  3280. if (isNpc())
  3281. {
  3282. int i = 0;
  3283. for (; i < Stats.NUM_STATS; i++)
  3284. {
  3285. if (!Calculator.equalsCals(_calculators[i], NPC_STD_CALCULATOR[i]))
  3286. {
  3287. break;
  3288. }
  3289. }
  3290. if (i >= Stats.NUM_STATS)
  3291. {
  3292. _calculators = NPC_STD_CALCULATOR;
  3293. }
  3294. }
  3295. }
  3296. }
  3297. /**
  3298. * Remove a list of Funcs from the Calculator set of the L2PcInstance.<br>
  3299. * <B><U>Concept</U>:</B><br>
  3300. * A L2Character owns a table of Calculators called <B>_calculators</B>.<br>
  3301. * Each Calculator (a calculator per state) own a table of Func object.<br>
  3302. * A Func object is a mathematic function that permit to calculate the modifier of a state (ex : REGENERATE_HP_RATE...).<br>
  3303. * <FONT COLOR=#FF0000><B> <U>Caution</U> : This method is ONLY for L2PcInstance</B></FONT><br>
  3304. * <B><U>Example of use</U>:</B>
  3305. * <ul>
  3306. * <li>Unequip an item from inventory</li>
  3307. * <li>Stop an active skill</li>
  3308. * </ul>
  3309. * @param functions The list of Func objects to add to the Calculator corresponding to the state affected
  3310. */
  3311. public final void removeStatFuncs(AbstractFunction[] functions)
  3312. {
  3313. if (!isPlayer() && getKnownList().getKnownPlayers().isEmpty())
  3314. {
  3315. for (AbstractFunction f : functions)
  3316. {
  3317. removeStatFunc(f);
  3318. }
  3319. }
  3320. else
  3321. {
  3322. final List<Stats> modifiedStats = new ArrayList<>();
  3323. for (AbstractFunction f : functions)
  3324. {
  3325. modifiedStats.add(f.getStat());
  3326. removeStatFunc(f);
  3327. }
  3328. broadcastModifiedStats(modifiedStats);
  3329. }
  3330. }
  3331. /**
  3332. * Remove all Func objects with the selected owner from the Calculator set of the L2Character.<br>
  3333. * <B><U>Concept</U>:</B><br>
  3334. * A L2Character owns a table of Calculators called <B>_calculators</B>.<br>
  3335. * Each Calculator (a calculator per state) own a table of Func object.<br>
  3336. * A Func object is a mathematic function that permit to calculate the modifier of a state (ex : REGENERATE_HP_RATE...).<br>
  3337. * To reduce cache memory use, L2NPCInstances who don't have skills share the same Calculator set called <B>NPC_STD_CALCULATOR</B>.<br>
  3338. * That's why, if a L2NPCInstance is under a skill/spell effect that modify one of its state, a copy of the NPC_STD_CALCULATOR must be create in its _calculators before addind new Func object.<br>
  3339. * <B><U>Actions</U>:</B>
  3340. * <ul>
  3341. * <li>Remove all Func objects of the selected owner from _calculators</li>
  3342. * <li>If L2Character is a L2NPCInstance and _calculators is equal to NPC_STD_CALCULATOR, free cache memory and just create a link on NPC_STD_CALCULATOR in _calculators</li>
  3343. * </ul>
  3344. * <B><U>Example of use</U>:</B>
  3345. * <ul>
  3346. * <li>Unequip an item from inventory</li>
  3347. * <li>Stop an active skill</li>
  3348. * </ul>
  3349. * @param owner The Object(Skill, Item...) that has created the effect
  3350. */
  3351. public final void removeStatsOwner(Object owner)
  3352. {
  3353. List<Stats> modifiedStats = null;
  3354. int i = 0;
  3355. // Go through the Calculator set
  3356. synchronized (this)
  3357. {
  3358. for (Calculator calc : _calculators)
  3359. {
  3360. if (calc != null)
  3361. {
  3362. // Delete all Func objects of the selected owner
  3363. if (modifiedStats != null)
  3364. {
  3365. modifiedStats.addAll(calc.removeOwner(owner));
  3366. }
  3367. else
  3368. {
  3369. modifiedStats = calc.removeOwner(owner);
  3370. }
  3371. if (calc.size() == 0)
  3372. {
  3373. _calculators[i] = null;
  3374. }
  3375. }
  3376. i++;
  3377. }
  3378. // If possible, free the memory and just create a link on NPC_STD_CALCULATOR
  3379. if (isNpc())
  3380. {
  3381. i = 0;
  3382. for (; i < Stats.NUM_STATS; i++)
  3383. {
  3384. if (!Calculator.equalsCals(_calculators[i], NPC_STD_CALCULATOR[i]))
  3385. {
  3386. break;
  3387. }
  3388. }
  3389. if (i >= Stats.NUM_STATS)
  3390. {
  3391. _calculators = NPC_STD_CALCULATOR;
  3392. }
  3393. }
  3394. broadcastModifiedStats(modifiedStats);
  3395. }
  3396. }
  3397. protected void broadcastModifiedStats(List<Stats> stats)
  3398. {
  3399. if ((stats == null) || stats.isEmpty())
  3400. {
  3401. return;
  3402. }
  3403. if (isSummon())
  3404. {
  3405. L2Summon summon = (L2Summon) this;
  3406. if (summon.getOwner() != null)
  3407. {
  3408. summon.updateAndBroadcastStatus(1);
  3409. }
  3410. }
  3411. else
  3412. {
  3413. boolean broadcastFull = false;
  3414. StatusUpdate su = new StatusUpdate(this);
  3415. for (Stats stat : stats)
  3416. {
  3417. if (stat == Stats.POWER_ATTACK_SPEED)
  3418. {
  3419. su.addAttribute(StatusUpdate.ATK_SPD, getPAtkSpd());
  3420. }
  3421. else if (stat == Stats.MAGIC_ATTACK_SPEED)
  3422. {
  3423. su.addAttribute(StatusUpdate.CAST_SPD, getMAtkSpd());
  3424. }
  3425. else if (stat == Stats.MOVE_SPEED)
  3426. {
  3427. broadcastFull = true;
  3428. }
  3429. }
  3430. if (isPlayer())
  3431. {
  3432. if (broadcastFull)
  3433. {
  3434. getActingPlayer().updateAndBroadcastStatus(2);
  3435. }
  3436. else
  3437. {
  3438. getActingPlayer().updateAndBroadcastStatus(1);
  3439. if (su.hasAttributes())
  3440. {
  3441. broadcastPacket(su);
  3442. }
  3443. }
  3444. if ((getSummon() != null) && isAffected(EffectFlag.SERVITOR_SHARE))
  3445. {
  3446. getSummon().broadcastStatusUpdate();
  3447. }
  3448. }
  3449. else if (isNpc())
  3450. {
  3451. if (broadcastFull)
  3452. {
  3453. Collection<L2PcInstance> plrs = getKnownList().getKnownPlayers().values();
  3454. for (L2PcInstance player : plrs)
  3455. {
  3456. if ((player == null) || !isVisibleFor(player))
  3457. {
  3458. continue;
  3459. }
  3460. if (getRunSpeed() == 0)
  3461. {
  3462. player.sendPacket(new ServerObjectInfo((L2Npc) this, player));
  3463. }
  3464. else
  3465. {
  3466. player.sendPacket(new AbstractNpcInfo.NpcInfo((L2Npc) this, player));
  3467. }
  3468. }
  3469. }
  3470. else if (su.hasAttributes())
  3471. {
  3472. broadcastPacket(su);
  3473. }
  3474. }
  3475. else if (su.hasAttributes())
  3476. {
  3477. broadcastPacket(su);
  3478. }
  3479. }
  3480. }
  3481. public final int getXdestination()
  3482. {
  3483. MoveData m = _move;
  3484. if (m != null)
  3485. {
  3486. return m._xDestination;
  3487. }
  3488. return getX();
  3489. }
  3490. /**
  3491. * @return the Y destination of the L2Character or the Y position if not in movement.
  3492. */
  3493. public final int getYdestination()
  3494. {
  3495. MoveData m = _move;
  3496. if (m != null)
  3497. {
  3498. return m._yDestination;
  3499. }
  3500. return getY();
  3501. }
  3502. /**
  3503. * @return the Z destination of the L2Character or the Z position if not in movement.
  3504. */
  3505. public final int getZdestination()
  3506. {
  3507. MoveData m = _move;
  3508. if (m != null)
  3509. {
  3510. return m._zDestination;
  3511. }
  3512. return getZ();
  3513. }
  3514. /**
  3515. * @return True if the L2Character is in combat.
  3516. */
  3517. public boolean isInCombat()
  3518. {
  3519. return hasAI() && ((getAI().getAttackTarget() != null) || getAI().isAutoAttacking());
  3520. }
  3521. /**
  3522. * @return True if the L2Character is moving.
  3523. */
  3524. public final boolean isMoving()
  3525. {
  3526. return _move != null;
  3527. }
  3528. /**
  3529. * @return True if the L2Character is travelling a calculated path.
  3530. */
  3531. public final boolean isOnGeodataPath()
  3532. {
  3533. MoveData m = _move;
  3534. if (m == null)
  3535. {
  3536. return false;
  3537. }
  3538. if (m.onGeodataPathIndex == -1)
  3539. {
  3540. return false;
  3541. }
  3542. if (m.onGeodataPathIndex == (m.geoPath.size() - 1))
  3543. {
  3544. return false;
  3545. }
  3546. return true;
  3547. }
  3548. /**
  3549. * @return True if the L2Character is casting.
  3550. */
  3551. public final boolean isCastingNow()
  3552. {
  3553. return _isCastingNow;
  3554. }
  3555. public void setIsCastingNow(boolean value)
  3556. {
  3557. _isCastingNow = value;
  3558. }
  3559. public final boolean isCastingSimultaneouslyNow()
  3560. {
  3561. return _isCastingSimultaneouslyNow;
  3562. }
  3563. public void setIsCastingSimultaneouslyNow(boolean value)
  3564. {
  3565. _isCastingSimultaneouslyNow = value;
  3566. }
  3567. /**
  3568. * @return True if the cast of the L2Character can be aborted.
  3569. */
  3570. public final boolean canAbortCast()
  3571. {
  3572. return _castInterruptTime > GameTimeController.getInstance().getGameTicks();
  3573. }
  3574. public int getCastInterruptTime()
  3575. {
  3576. return _castInterruptTime;
  3577. }
  3578. /**
  3579. * @return True if the L2Character is attacking.
  3580. */
  3581. public final boolean isAttackingNow()
  3582. {
  3583. return _attackEndTime > System.currentTimeMillis();
  3584. }
  3585. /**
  3586. * Abort the attack of the L2Character and send Server->Client ActionFailed packet.
  3587. */
  3588. public final void abortAttack()
  3589. {
  3590. if (isAttackingNow())
  3591. {
  3592. sendPacket(ActionFailed.STATIC_PACKET);
  3593. }
  3594. }
  3595. /**
  3596. * Abort the cast of the L2Character and send Server->Client MagicSkillCanceld/ActionFailed packet.
  3597. */
  3598. public final void abortCast()
  3599. {
  3600. if (isCastingNow() || isCastingSimultaneouslyNow())
  3601. {
  3602. Future<?> future = _skillCast;
  3603. // cancels the skill hit scheduled task
  3604. if (future != null)
  3605. {
  3606. future.cancel(true);
  3607. _skillCast = null;
  3608. }
  3609. future = _skillCast2;
  3610. if (future != null)
  3611. {
  3612. future.cancel(true);
  3613. _skillCast2 = null;
  3614. }
  3615. // TODO: Handle removing spawned npc.
  3616. if (isChanneling())
  3617. {
  3618. getSkillChannelizer().stopChanneling();
  3619. }
  3620. if (_allSkillsDisabled)
  3621. {
  3622. enableAllSkills(); // this remains for forced skill use, e.g. scroll of escape
  3623. }
  3624. setIsCastingNow(false);
  3625. setIsCastingSimultaneouslyNow(false);
  3626. // safeguard for cannot be interrupt any more
  3627. _castInterruptTime = 0;
  3628. if (isPlayer())
  3629. {
  3630. getAI().notifyEvent(CtrlEvent.EVT_FINISH_CASTING); // setting back previous intention
  3631. }
  3632. broadcastPacket(new MagicSkillCanceld(getObjectId())); // broadcast packet to stop animations client-side
  3633. sendPacket(ActionFailed.STATIC_PACKET); // send an "action failed" packet to the caster
  3634. }
  3635. }
  3636. /**
  3637. * Update the position of the L2Character during a movement and return True if the movement is finished.<br>
  3638. * <B><U>Concept</U>:</B><br>
  3639. * At the beginning of the move action, all properties of the movement are stored in the MoveData object called <B>_move</B> of the L2Character.<br>
  3640. * The position of the start point and of the destination permit to estimated in function of the movement speed the time to achieve the destination.<br>
  3641. * When the movement is started (ex : by MovetoLocation), this method will be called each 0.1 sec to estimate and update the L2Character position on the server.<br>
  3642. * Note, that the current server position can differe from the current client position even if each movement is straight foward.<br>
  3643. * That's why, client send regularly a Client->Server ValidatePosition packet to eventually correct the gap on the server.<br>
  3644. * But, it's always the server position that is used in range calculation. At the end of the estimated movement time,<br>
  3645. * the L2Character position is automatically set to the destination position even if the movement is not finished.<br>
  3646. * <FONT COLOR=#FF0000><B><U>Caution</U>: The current Z position is obtained FROM THE CLIENT by the Client->Server ValidatePosition Packet.<br>
  3647. * But x and y positions must be calculated to avoid that players try to modify their movement speed.</B></FONT>
  3648. * @param gameTicks Nb of ticks since the server start
  3649. * @return True if the movement is finished
  3650. */
  3651. public boolean updatePosition(int gameTicks)
  3652. {
  3653. // Get movement data
  3654. MoveData m = _move;
  3655. if (m == null)
  3656. {
  3657. return true;
  3658. }
  3659. if (!isVisible())
  3660. {
  3661. _move = null;
  3662. return true;
  3663. }
  3664. // Check if this is the first update
  3665. if (m._moveTimestamp == 0)
  3666. {
  3667. m._moveTimestamp = m._moveStartTime;
  3668. m._xAccurate = getX();
  3669. m._yAccurate = getY();
  3670. }
  3671. // Check if the position has already been calculated
  3672. if (m._moveTimestamp == gameTicks)
  3673. {
  3674. return false;
  3675. }
  3676. int xPrev = getX();
  3677. int yPrev = getY();
  3678. int zPrev = getZ(); // the z coordinate may be modified by coordinate synchronizations
  3679. double dx, dy, dz;
  3680. if (Config.COORD_SYNCHRONIZE == 1)
  3681. // the only method that can modify x,y while moving (otherwise _move would/should be set null)
  3682. {
  3683. dx = m._xDestination - xPrev;
  3684. dy = m._yDestination - yPrev;
  3685. }
  3686. else
  3687. // otherwise we need saved temporary values to avoid rounding errors
  3688. {
  3689. dx = m._xDestination - m._xAccurate;
  3690. dy = m._yDestination - m._yAccurate;
  3691. }
  3692. final boolean isFloating = isFlying() || isInsideZone(ZoneId.WATER);
  3693. // Z coordinate will follow geodata or client values
  3694. if ((Config.GEODATA > 0) && (Config.COORD_SYNCHRONIZE == 2) && !isFloating && !m.disregardingGeodata && ((GameTimeController.getInstance().getGameTicks() % 10) == 0 // once a second to reduce possible cpu load
  3695. ) && GeoData.getInstance().hasGeo(xPrev, yPrev))
  3696. {
  3697. int geoHeight = GeoData.getInstance().getSpawnHeight(xPrev, yPrev, zPrev);
  3698. dz = m._zDestination - geoHeight;
  3699. // quite a big difference, compare to validatePosition packet
  3700. if (isPlayer() && (Math.abs(getActingPlayer().getClientZ() - geoHeight) > 200) && (Math.abs(getActingPlayer().getClientZ() - geoHeight) < 1500))
  3701. {
  3702. dz = m._zDestination - zPrev; // allow diff
  3703. }
  3704. else if (isInCombat() && (Math.abs(dz) > 200) && (((dx * dx) + (dy * dy)) < 40000)) // allow mob to climb up to pcinstance
  3705. {
  3706. dz = m._zDestination - zPrev; // climbing
  3707. }
  3708. else
  3709. {
  3710. zPrev = geoHeight;
  3711. }
  3712. }
  3713. else
  3714. {
  3715. dz = m._zDestination - zPrev;
  3716. }
  3717. double delta = (dx * dx) + (dy * dy);
  3718. if ((delta < 10000) && ((dz * dz) > 2500) // close enough, allows error between client and server geodata if it cannot be avoided
  3719. && !isFloating)
  3720. {
  3721. delta = Math.sqrt(delta);
  3722. }
  3723. else
  3724. {
  3725. delta = Math.sqrt(delta + (dz * dz));
  3726. }
  3727. double distFraction = Double.MAX_VALUE;
  3728. if (delta > 1)
  3729. {
  3730. final double distPassed = (getMoveSpeed() * (gameTicks - m._moveTimestamp)) / GameTimeController.TICKS_PER_SECOND;
  3731. distFraction = distPassed / delta;
  3732. }
  3733. // if (Config.DEVELOPER) _log.warning("Move Ticks:" + (gameTicks - m._moveTimestamp) + ", distPassed:" + distPassed + ", distFraction:" + distFraction);
  3734. if (distFraction > 1)
  3735. {
  3736. // Set the position of the L2Character to the destination
  3737. super.setXYZ(m._xDestination, m._yDestination, m._zDestination);
  3738. }
  3739. else
  3740. {
  3741. m._xAccurate += dx * distFraction;
  3742. m._yAccurate += dy * distFraction;
  3743. // Set the position of the L2Character to estimated after parcial move
  3744. super.setXYZ((int) (m._xAccurate), (int) (m._yAccurate), zPrev + (int) ((dz * distFraction) + 0.5));
  3745. }
  3746. revalidateZone(false);
  3747. // Set the timer of last position update to now
  3748. m._moveTimestamp = gameTicks;
  3749. return (distFraction > 1);
  3750. }
  3751. public void revalidateZone(boolean force)
  3752. {
  3753. if (getWorldRegion() == null)
  3754. {
  3755. return;
  3756. }
  3757. // This function is called too often from movement code
  3758. if (force)
  3759. {
  3760. _zoneValidateCounter = 4;
  3761. }
  3762. else
  3763. {
  3764. _zoneValidateCounter--;
  3765. if (_zoneValidateCounter < 0)
  3766. {
  3767. _zoneValidateCounter = 4;
  3768. }
  3769. else
  3770. {
  3771. return;
  3772. }
  3773. }
  3774. getWorldRegion().revalidateZones(this);
  3775. }
  3776. /**
  3777. * Stop movement of the L2Character (Called by AI Accessor only).<br>
  3778. * <B><U>Actions</U>:</B>
  3779. * <ul>
  3780. * <li>Delete movement data of the L2Character</li>
  3781. * <li>Set the current position (x,y,z), its current L2WorldRegion if necessary and its heading</li>
  3782. * <li>Remove the L2Object object from _gmList of GmListTable</li>
  3783. * <li>Remove object from _knownObjects and _knownPlayer of all surrounding L2WorldRegion L2Characters</li>
  3784. * </ul>
  3785. * <FONT COLOR=#FF0000><B><U>Caution</U>: This method DOESN'T send Server->Client packet StopMove/StopRotation</B></FONT>
  3786. * @param loc
  3787. */
  3788. public void stopMove(Location loc)
  3789. {
  3790. stopMove(loc, false);
  3791. }
  3792. public void stopMove(Location loc, boolean updateKnownObjects)
  3793. {
  3794. // Delete movement data of the L2Character
  3795. _move = null;
  3796. // if (getAI() != null)
  3797. // getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  3798. // Set the current position (x,y,z), its current L2WorldRegion if necessary and its heading
  3799. // All data are contained in a Location object
  3800. if (loc != null)
  3801. {
  3802. setXYZ(loc.getX(), loc.getY(), loc.getZ());
  3803. setHeading(loc.getHeading());
  3804. revalidateZone(true);
  3805. }
  3806. broadcastPacket(new StopMove(this));
  3807. if (Config.MOVE_BASED_KNOWNLIST && updateKnownObjects)
  3808. {
  3809. getKnownList().findObjects();
  3810. }
  3811. }
  3812. /**
  3813. * @return Returns the showSummonAnimation.
  3814. */
  3815. public boolean isShowSummonAnimation()
  3816. {
  3817. return _showSummonAnimation;
  3818. }
  3819. /**
  3820. * @param showSummonAnimation The showSummonAnimation to set.
  3821. */
  3822. public void setShowSummonAnimation(boolean showSummonAnimation)
  3823. {
  3824. _showSummonAnimation = showSummonAnimation;
  3825. }
  3826. /**
  3827. * Target a L2Object (add the target to the L2Character _target, _knownObject and L2Character to _KnownObject of the L2Object).<br>
  3828. * <B><U>Concept</U>:</B><br>
  3829. * The L2Object (including L2Character) targeted is identified in <B>_target</B> of the L2Character.<br>
  3830. * <B><U>Actions</U>:</B>
  3831. * <ul>
  3832. * <li>Set the _target of L2Character to L2Object</li>
  3833. * <li>If necessary, add L2Object to _knownObject of the L2Character</li>
  3834. * <li>If necessary, add L2Character to _KnownObject of the L2Object</li>
  3835. * <li>If object==null, cancel Attak or Cast</li>
  3836. * </ul>
  3837. * @param object L2object to target
  3838. */
  3839. public void setTarget(L2Object object)
  3840. {
  3841. if ((object != null) && !object.isVisible())
  3842. {
  3843. object = null;
  3844. }
  3845. if ((object != null) && (object != _target))
  3846. {
  3847. getKnownList().addKnownObject(object);
  3848. object.getKnownList().addKnownObject(this);
  3849. }
  3850. _target = object;
  3851. }
  3852. /**
  3853. * @return the identifier of the L2Object targeted or -1.
  3854. */
  3855. public final int getTargetId()
  3856. {
  3857. if (_target != null)
  3858. {
  3859. return _target.getObjectId();
  3860. }
  3861. return 0;
  3862. }
  3863. /**
  3864. * @return the L2Object targeted or null.
  3865. */
  3866. public final L2Object getTarget()
  3867. {
  3868. return _target;
  3869. }
  3870. // called from AIAccessor only
  3871. /**
  3872. * Calculate movement data for a move to location action and add the L2Character to movingObjects of GameTimeController (only called by AI Accessor).<br>
  3873. * <B><U>Concept</U>:</B><br>
  3874. * At the beginning of the move action, all properties of the movement are stored in the MoveData object called <B>_move</B> of the L2Character.<br>
  3875. * The position of the start point and of the destination permit to estimated in function of the movement speed the time to achieve the destination.<br>
  3876. * All L2Character in movement are identified in <B>movingObjects</B> of GameTimeController that will call the updatePosition method of those L2Character each 0.1s.<br>
  3877. * <B><U>Actions</U>:</B>
  3878. * <ul>
  3879. * <li>Get current position of the L2Character</li>
  3880. * <li>Calculate distance (dx,dy) between current position and destination including offset</li>
  3881. * <li>Create and Init a MoveData object</li>
  3882. * <li>Set the L2Character _move object to MoveData object</li>
  3883. * <li>Add the L2Character to movingObjects of the GameTimeController</li>
  3884. * <li>Create a task to notify the AI that L2Character arrives at a check point of the movement</li>
  3885. * </ul>
  3886. * <FONT COLOR=#FF0000><B><U>Caution</U>: This method DOESN'T send Server->Client packet MoveToPawn/CharMoveToLocation.</B></FONT><br>
  3887. * <B><U>Example of use</U>:</B>
  3888. * <ul>
  3889. * <li>AI : onIntentionMoveTo(Location), onIntentionPickUp(L2Object), onIntentionInteract(L2Object)</li>
  3890. * <li>FollowTask</li>
  3891. * </ul>
  3892. * @param x The X position of the destination
  3893. * @param y The Y position of the destination
  3894. * @param z The Y position of the destination
  3895. * @param offset The size of the interaction area of the L2Character targeted
  3896. */
  3897. protected void moveToLocation(int x, int y, int z, int offset)
  3898. {
  3899. // Get the Move Speed of the L2Charcater
  3900. double speed = getMoveSpeed();
  3901. if ((speed <= 0) || isMovementDisabled())
  3902. {
  3903. return;
  3904. }
  3905. // Get current position of the L2Character
  3906. final int curX = super.getX();
  3907. final int curY = super.getY();
  3908. final int curZ = super.getZ();
  3909. // Calculate distance (dx,dy) between current position and destination
  3910. // TODO: improve Z axis move/follow support when dx,dy are small compared to dz
  3911. double dx = (x - curX);
  3912. double dy = (y - curY);
  3913. double dz = (z - curZ);
  3914. double distance = Math.sqrt((dx * dx) + (dy * dy));
  3915. final boolean verticalMovementOnly = isFlying() && (distance == 0) && (dz != 0);
  3916. if (verticalMovementOnly)
  3917. {
  3918. distance = Math.abs(dz);
  3919. }
  3920. // make water move short and use no geodata checks for swimming chars
  3921. // distance in a click can easily be over 3000
  3922. if ((Config.GEODATA > 0) && isInsideZone(ZoneId.WATER) && (distance > 700))
  3923. {
  3924. double divider = 700 / distance;
  3925. x = curX + (int) (divider * dx);
  3926. y = curY + (int) (divider * dy);
  3927. z = curZ + (int) (divider * dz);
  3928. dx = (x - curX);
  3929. dy = (y - curY);
  3930. dz = (z - curZ);
  3931. distance = Math.sqrt((dx * dx) + (dy * dy));
  3932. }
  3933. // Define movement angles needed
  3934. // ^
  3935. // | X (x,y)
  3936. // | /
  3937. // | /distance
  3938. // | /
  3939. // |/ angle
  3940. // X ---------->
  3941. // (curx,cury)
  3942. double cos;
  3943. double sin;
  3944. // Check if a movement offset is defined or no distance to go through
  3945. if ((offset > 0) || (distance < 1))
  3946. {
  3947. // approximation for moving closer when z coordinates are different
  3948. // TODO: handle Z axis movement better
  3949. offset -= Math.abs(dz);
  3950. if (offset < 5)
  3951. {
  3952. offset = 5;
  3953. }
  3954. // If no distance to go through, the movement is canceled
  3955. if ((distance < 1) || ((distance - offset) <= 0))
  3956. {
  3957. // Notify the AI that the L2Character is arrived at destination
  3958. getAI().notifyEvent(CtrlEvent.EVT_ARRIVED);
  3959. return;
  3960. }
  3961. // Calculate movement angles needed
  3962. sin = dy / distance;
  3963. cos = dx / distance;
  3964. distance -= (offset - 5); // due to rounding error, we have to move a bit closer to be in range
  3965. // Calculate the new destination with offset included
  3966. x = curX + (int) (distance * cos);
  3967. y = curY + (int) (distance * sin);
  3968. }
  3969. else
  3970. {
  3971. // Calculate movement angles needed
  3972. sin = dy / distance;
  3973. cos = dx / distance;
  3974. }
  3975. // Create and Init a MoveData object
  3976. MoveData m = new MoveData();
  3977. // GEODATA MOVEMENT CHECKS AND PATHFINDING
  3978. m.onGeodataPathIndex = -1; // Initialize not on geodata path
  3979. m.disregardingGeodata = false;
  3980. if ((Config.GEODATA > 0) && !isFlying() // flying chars not checked - even canSeeTarget doesn't work yet
  3981. && (!isInsideZone(ZoneId.WATER) || isInsideZone(ZoneId.SIEGE))) // swimming also not checked unless in siege zone - but distance is limited
  3982. {
  3983. final boolean isInVehicle = isPlayer() && (getActingPlayer().getVehicle() != null);
  3984. if (isInVehicle)
  3985. {
  3986. m.disregardingGeodata = true;
  3987. }
  3988. double originalDistance = distance;
  3989. int originalX = x;
  3990. int originalY = y;
  3991. int originalZ = z;
  3992. int gtx = (originalX - L2World.MAP_MIN_X) >> 4;
  3993. int gty = (originalY - L2World.MAP_MIN_Y) >> 4;
  3994. // Movement checks:
  3995. // when geodata == 2, for all characters except mobs returning home (could be changed later to teleport if pathfinding fails)
  3996. // when geodata == 1, for L2Playable and L2RiftInvaderInstance only
  3997. if (((Config.GEODATA == 2) && !(isAttackable() && ((L2Attackable) this).isReturningToSpawnPoint())) || (isPlayer() && !(isInVehicle && (distance > 1500))) || (isSummon() && !(getAI().getIntention() == AI_INTENTION_FOLLOW)) // assuming intention_follow only when following owner
  3998. || isAfraid() || (this instanceof L2RiftInvaderInstance))
  3999. {
  4000. if (isOnGeodataPath())
  4001. {
  4002. try
  4003. {
  4004. if ((gtx == _move.geoPathGtx) && (gty == _move.geoPathGty))
  4005. {
  4006. return;
  4007. }
  4008. _move.onGeodataPathIndex = -1; // Set not on geodata path
  4009. }
  4010. catch (NullPointerException e)
  4011. {
  4012. // nothing
  4013. }
  4014. }
  4015. if ((curX < L2World.MAP_MIN_X) || (curX > L2World.MAP_MAX_X) || (curY < L2World.MAP_MIN_Y) || (curY > L2World.MAP_MAX_Y))
  4016. {
  4017. // Temporary fix for character outside world region errors
  4018. _log.warning("Character " + getName() + " outside world area, in coordinates x:" + curX + " y:" + curY);
  4019. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4020. if (isPlayer())
  4021. {
  4022. getActingPlayer().logout();
  4023. }
  4024. else if (isSummon())
  4025. {
  4026. return; // preventation when summon get out of world coords, player will not loose him, unsummon handled from pcinstance
  4027. }
  4028. else
  4029. {
  4030. onDecay();
  4031. }
  4032. return;
  4033. }
  4034. Location destiny = GeoData.getInstance().moveCheck(curX, curY, curZ, x, y, z, getInstanceId());
  4035. // location different if destination wasn't reached (or just z coord is different)
  4036. x = destiny.getX();
  4037. y = destiny.getY();
  4038. z = destiny.getZ();
  4039. dx = x - curX;
  4040. dy = y - curY;
  4041. dz = z - curZ;
  4042. distance = verticalMovementOnly ? Math.abs(dz * dz) : Math.sqrt((dx * dx) + (dy * dy));
  4043. }
  4044. // Pathfinding checks. Only when geodata setting is 2, the LoS check gives shorter result
  4045. // than the original movement was and the LoS gives a shorter distance than 2000
  4046. // This way of detecting need for pathfinding could be changed.
  4047. if ((Config.GEODATA == 2) && ((originalDistance - distance) > 30) && (distance < 2000) && !isAfraid())
  4048. {
  4049. // Path calculation
  4050. // Overrides previous movement check
  4051. if ((isPlayable() && !isInVehicle) || isMinion() || isInCombat())
  4052. {
  4053. m.geoPath = PathFinding.getInstance().findPath(curX, curY, curZ, originalX, originalY, originalZ, getInstanceId(), isPlayable());
  4054. if ((m.geoPath == null) || (m.geoPath.size() < 2)) // No path found
  4055. {
  4056. // * Even though there's no path found (remember geonodes aren't perfect),
  4057. // the mob is attacking and right now we set it so that the mob will go
  4058. // after target anyway, is dz is small enough.
  4059. // * With cellpathfinding this approach could be changed but would require taking
  4060. // off the geonodes and some more checks.
  4061. // * Summons will follow their masters no matter what.
  4062. // * Currently minions also must move freely since L2AttackableAI commands
  4063. // them to move along with their leader
  4064. if (isPlayer() || (!isPlayable() && !isMinion() && (Math.abs(z - curZ) > 140)) || (isSummon() && !((L2Summon) this).getFollowStatus()))
  4065. {
  4066. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4067. return;
  4068. }
  4069. m.disregardingGeodata = true;
  4070. x = originalX;
  4071. y = originalY;
  4072. z = originalZ;
  4073. distance = originalDistance;
  4074. }
  4075. else
  4076. {
  4077. m.onGeodataPathIndex = 0; // on first segment
  4078. m.geoPathGtx = gtx;
  4079. m.geoPathGty = gty;
  4080. m.geoPathAccurateTx = originalX;
  4081. m.geoPathAccurateTy = originalY;
  4082. x = m.geoPath.get(m.onGeodataPathIndex).getX();
  4083. y = m.geoPath.get(m.onGeodataPathIndex).getY();
  4084. z = m.geoPath.get(m.onGeodataPathIndex).getZ();
  4085. // check for doors in the route
  4086. if (DoorTable.getInstance().checkIfDoorsBetween(curX, curY, curZ, x, y, z, getInstanceId()))
  4087. {
  4088. m.geoPath = null;
  4089. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4090. return;
  4091. }
  4092. for (int i = 0; i < (m.geoPath.size() - 1); i++)
  4093. {
  4094. if (DoorTable.getInstance().checkIfDoorsBetween(m.geoPath.get(i), m.geoPath.get(i + 1), getInstanceId()))
  4095. {
  4096. m.geoPath = null;
  4097. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4098. return;
  4099. }
  4100. }
  4101. dx = x - curX;
  4102. dy = y - curY;
  4103. dz = z - curZ;
  4104. distance = verticalMovementOnly ? Math.abs(dz * dz) : Math.sqrt((dx * dx) + (dy * dy));
  4105. sin = dy / distance;
  4106. cos = dx / distance;
  4107. }
  4108. }
  4109. }
  4110. // If no distance to go through, the movement is canceled
  4111. if ((distance < 1) && ((Config.GEODATA == 2) || isPlayable() || (this instanceof L2RiftInvaderInstance) || isAfraid()))
  4112. {
  4113. if (isSummon())
  4114. {
  4115. ((L2Summon) this).setFollowStatus(false);
  4116. }
  4117. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4118. return;
  4119. }
  4120. }
  4121. // Apply Z distance for flying or swimming for correct timing calculations
  4122. if ((isFlying() || isInsideZone(ZoneId.WATER)) && !verticalMovementOnly)
  4123. {
  4124. distance = Math.sqrt((distance * distance) + (dz * dz));
  4125. }
  4126. // Caclulate the Nb of ticks between the current position and the destination
  4127. // One tick added for rounding reasons
  4128. int ticksToMove = 1 + (int) ((GameTimeController.TICKS_PER_SECOND * distance) / speed);
  4129. m._xDestination = x;
  4130. m._yDestination = y;
  4131. m._zDestination = z; // this is what was requested from client
  4132. // Calculate and set the heading of the L2Character
  4133. m._heading = 0; // initial value for coordinate sync
  4134. // Does not broke heading on vertical movements
  4135. if (!verticalMovementOnly)
  4136. {
  4137. setHeading(Util.calculateHeadingFrom(cos, sin));
  4138. }
  4139. m._moveStartTime = GameTimeController.getInstance().getGameTicks();
  4140. // Set the L2Character _move object to MoveData object
  4141. _move = m;
  4142. // Add the L2Character to movingObjects of the GameTimeController
  4143. // The GameTimeController manage objects movement
  4144. GameTimeController.getInstance().registerMovingObject(this);
  4145. // Create a task to notify the AI that L2Character arrives at a check point of the movement
  4146. if ((ticksToMove * GameTimeController.MILLIS_IN_TICK) > 3000)
  4147. {
  4148. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
  4149. }
  4150. // the CtrlEvent.EVT_ARRIVED will be sent when the character will actually arrive
  4151. // to destination by GameTimeController
  4152. }
  4153. public boolean moveToNextRoutePoint()
  4154. {
  4155. if (!isOnGeodataPath())
  4156. {
  4157. // Cancel the move action
  4158. _move = null;
  4159. return false;
  4160. }
  4161. // Get the Move Speed of the L2Charcater
  4162. double speed = getMoveSpeed();
  4163. if ((speed <= 0) || isMovementDisabled())
  4164. {
  4165. // Cancel the move action
  4166. _move = null;
  4167. return false;
  4168. }
  4169. MoveData md = _move;
  4170. if (md == null)
  4171. {
  4172. return false;
  4173. }
  4174. // Create and Init a MoveData object
  4175. MoveData m = new MoveData();
  4176. // Update MoveData object
  4177. m.onGeodataPathIndex = md.onGeodataPathIndex + 1; // next segment
  4178. m.geoPath = md.geoPath;
  4179. m.geoPathGtx = md.geoPathGtx;
  4180. m.geoPathGty = md.geoPathGty;
  4181. m.geoPathAccurateTx = md.geoPathAccurateTx;
  4182. m.geoPathAccurateTy = md.geoPathAccurateTy;
  4183. if (md.onGeodataPathIndex == (md.geoPath.size() - 2))
  4184. {
  4185. m._xDestination = md.geoPathAccurateTx;
  4186. m._yDestination = md.geoPathAccurateTy;
  4187. m._zDestination = md.geoPath.get(m.onGeodataPathIndex).getZ();
  4188. }
  4189. else
  4190. {
  4191. m._xDestination = md.geoPath.get(m.onGeodataPathIndex).getX();
  4192. m._yDestination = md.geoPath.get(m.onGeodataPathIndex).getY();
  4193. m._zDestination = md.geoPath.get(m.onGeodataPathIndex).getZ();
  4194. }
  4195. double dx = (m._xDestination - super.getX());
  4196. double dy = (m._yDestination - super.getY());
  4197. double distance = Math.sqrt((dx * dx) + (dy * dy));
  4198. // Calculate and set the heading of the L2Character
  4199. if (distance != 0)
  4200. {
  4201. setHeading(Util.calculateHeadingFrom(getX(), getY(), m._xDestination, m._yDestination));
  4202. }
  4203. // Caclulate the Nb of ticks between the current position and the destination
  4204. // One tick added for rounding reasons
  4205. int ticksToMove = 1 + (int) ((GameTimeController.TICKS_PER_SECOND * distance) / speed);
  4206. m._heading = 0; // initial value for coordinate sync
  4207. m._moveStartTime = GameTimeController.getInstance().getGameTicks();
  4208. // Set the L2Character _move object to MoveData object
  4209. _move = m;
  4210. // Add the L2Character to movingObjects of the GameTimeController
  4211. // The GameTimeController manage objects movement
  4212. GameTimeController.getInstance().registerMovingObject(this);
  4213. // Create a task to notify the AI that L2Character arrives at a check point of the movement
  4214. if ((ticksToMove * GameTimeController.MILLIS_IN_TICK) > 3000)
  4215. {
  4216. ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
  4217. }
  4218. // the CtrlEvent.EVT_ARRIVED will be sent when the character will actually arrive
  4219. // to destination by GameTimeController
  4220. // Send a Server->Client packet CharMoveToLocation to the actor and all L2PcInstance in its _knownPlayers
  4221. MoveToLocation msg = new MoveToLocation(this);
  4222. broadcastPacket(msg);
  4223. return true;
  4224. }
  4225. public boolean validateMovementHeading(int heading)
  4226. {
  4227. MoveData m = _move;
  4228. if (m == null)
  4229. {
  4230. return true;
  4231. }
  4232. boolean result = true;
  4233. if (m._heading != heading)
  4234. {
  4235. result = (m._heading == 0); // initial value or false
  4236. m._heading = heading;
  4237. }
  4238. return result;
  4239. }
  4240. /**
  4241. * Check if this object is inside the given radius around the given point.
  4242. * @param loc Location of the target
  4243. * @param radius the radius around the target
  4244. * @param checkZAxis should we check Z axis also
  4245. * @param strictCheck true if (distance < radius), false if (distance <= radius)
  4246. * @return true if the L2Character is inside the radius.
  4247. */
  4248. public final boolean isInsideRadius(ILocational loc, int radius, boolean checkZAxis, boolean strictCheck)
  4249. {
  4250. return isInsideRadius(loc.getX(), loc.getY(), loc.getZ(), radius, checkZAxis, strictCheck);
  4251. }
  4252. /**
  4253. * Check if this object is inside the given radius around the given point.
  4254. * @param x X position of the target
  4255. * @param y Y position of the target
  4256. * @param z Z position of the target
  4257. * @param radius the radius around the target
  4258. * @param checkZAxis should we check Z axis also
  4259. * @param strictCheck true if (distance < radius), false if (distance <= radius)
  4260. * @return true if the L2Character is inside the radius.
  4261. */
  4262. public final boolean isInsideRadius(int x, int y, int z, int radius, boolean checkZAxis, boolean strictCheck)
  4263. {
  4264. final double distance = calculateDistance(x, y, z, checkZAxis, true);
  4265. return (strictCheck) ? (distance < (radius * radius)) : (distance <= (radius * radius));
  4266. }
  4267. /**
  4268. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4269. * @return True if arrows are available.
  4270. */
  4271. protected boolean checkAndEquipArrows()
  4272. {
  4273. return true;
  4274. }
  4275. /**
  4276. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4277. * @return True if bolts are available.
  4278. */
  4279. protected boolean checkAndEquipBolts()
  4280. {
  4281. return true;
  4282. }
  4283. /**
  4284. * Add Exp and Sp to the L2Character.<br>
  4285. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li> <li>L2PetInstance</li>
  4286. * @param addToExp
  4287. * @param addToSp
  4288. */
  4289. public void addExpAndSp(long addToExp, int addToSp)
  4290. {
  4291. // Dummy method (overridden by players and pets)
  4292. }
  4293. /**
  4294. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4295. * @return the active weapon instance (always equiped in the right hand).
  4296. */
  4297. public abstract L2ItemInstance getActiveWeaponInstance();
  4298. /**
  4299. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4300. * @return the active weapon item (always equiped in the right hand).
  4301. */
  4302. public abstract L2Weapon getActiveWeaponItem();
  4303. /**
  4304. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4305. * @return the secondary weapon instance (always equiped in the left hand).
  4306. */
  4307. public abstract L2ItemInstance getSecondaryWeaponInstance();
  4308. /**
  4309. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4310. * @return the secondary {@link L2Item} item (always equiped in the left hand).
  4311. */
  4312. public abstract L2Item getSecondaryWeaponItem();
  4313. /**
  4314. * Manage hit process (called by Hit Task).<br>
  4315. * <B><U>Actions</U>:</B>
  4316. * <ul>
  4317. * <li>If the attacker/target is dead or use fake death, notify the AI with EVT_CANCEL and send a Server->Client packet ActionFailed (if attacker is a L2PcInstance)</li>
  4318. * <li>If attack isn't aborted, send a message system (critical hit, missed...) to attacker/target if they are L2PcInstance</li>
  4319. * <li>If attack isn't aborted and hit isn't missed, reduce HP of the target and calculate reflection damage to reduce HP of attacker if necessary</li>
  4320. * <li>if attack isn't aborted and hit isn't missed, manage attack or cast break of the target (calculating rate, sending message...)</li>
  4321. * </ul>
  4322. * @param target The L2Character targeted
  4323. * @param damage Nb of HP to reduce
  4324. * @param crit True if hit is critical
  4325. * @param miss True if hit is missed
  4326. * @param soulshot True if SoulShot are charged
  4327. * @param shld True if shield is efficient
  4328. */
  4329. public void onHitTimer(L2Character target, int damage, boolean crit, boolean miss, boolean soulshot, byte shld)
  4330. {
  4331. // If the attacker/target is dead or use fake death, notify the AI with EVT_CANCEL
  4332. // and send a Server->Client packet ActionFailed (if attacker is a L2PcInstance)
  4333. if ((target == null) || isAlikeDead() || (isNpc() && ((L2Npc) this).isEventMob()))
  4334. {
  4335. getAI().notifyEvent(CtrlEvent.EVT_CANCEL);
  4336. return;
  4337. }
  4338. if ((isNpc() && target.isAlikeDead()) || target.isDead() || (!getKnownList().knowsObject(target) && !isDoor()))
  4339. {
  4340. // getAI().setIntention(CtrlIntention.AI_INTENTION_ACTIVE, null);
  4341. getAI().notifyEvent(CtrlEvent.EVT_CANCEL);
  4342. sendPacket(ActionFailed.STATIC_PACKET);
  4343. return;
  4344. }
  4345. if (miss)
  4346. {
  4347. // Notify target AI
  4348. if (target.hasAI())
  4349. {
  4350. target.getAI().notifyEvent(CtrlEvent.EVT_EVADED, this);
  4351. }
  4352. notifyAttackAvoid(target, false);
  4353. }
  4354. // Send message about damage/crit or miss
  4355. sendDamageMessage(target, damage, false, crit, miss);
  4356. // Check Raidboss attack
  4357. // Character will be petrified if attacking a raid that's more
  4358. // than 8 levels lower
  4359. if (target.isRaid() && target.giveRaidCurse() && !Config.RAID_DISABLE_CURSE)
  4360. {
  4361. if (getLevel() > (target.getLevel() + 8))
  4362. {
  4363. Skill skill = CommonSkill.RAID_CURSE2.getSkill();
  4364. if (skill != null)
  4365. {
  4366. abortAttack();
  4367. abortCast();
  4368. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  4369. skill.applyEffects(target, this);
  4370. }
  4371. else
  4372. {
  4373. _log.warning("Skill 4515 at level 1 is missing in DP.");
  4374. }
  4375. damage = 0; // prevents messing up drop calculation
  4376. }
  4377. }
  4378. // If L2Character target is a L2PcInstance, send a system message
  4379. if (target.isPlayer())
  4380. {
  4381. L2PcInstance enemy = target.getActingPlayer();
  4382. enemy.getAI().clientStartAutoAttack();
  4383. }
  4384. if (!miss && (damage > 0))
  4385. {
  4386. L2Weapon weapon = getActiveWeaponItem();
  4387. boolean isBow = ((weapon != null) && ((weapon.getItemType() == WeaponType.BOW) || (weapon.getItemType() == WeaponType.CROSSBOW)));
  4388. int reflectedDamage = 0;
  4389. if (!isBow && !target.isInvul()) // Do not reflect if weapon is of type bow or target is invunlerable
  4390. {
  4391. // quick fix for no drop from raid if boss attack high-level char with damage reflection
  4392. if (!target.isRaid() || (getActingPlayer() == null) || (getActingPlayer().getLevel() <= (target.getLevel() + 8)))
  4393. {
  4394. // Reduce HP of the target and calculate reflection damage to reduce HP of attacker if necessary
  4395. double reflectPercent = target.getStat().calcStat(Stats.REFLECT_DAMAGE_PERCENT, 0, null, null);
  4396. if (reflectPercent > 0)
  4397. {
  4398. reflectedDamage = (int) ((reflectPercent / 100.) * damage);
  4399. if (reflectedDamage > target.getMaxHp())
  4400. {
  4401. reflectedDamage = target.getMaxHp();
  4402. }
  4403. }
  4404. }
  4405. }
  4406. // reduce targets HP
  4407. target.reduceCurrentHp(damage, this, null);
  4408. target.notifyDamageReceived(damage, this, null, crit, false);
  4409. if (reflectedDamage > 0)
  4410. {
  4411. reduceCurrentHp(reflectedDamage, target, true, false, null);
  4412. notifyDamageReceived(reflectedDamage, target, null, crit, false);
  4413. }
  4414. if (!isBow) // Do not absorb if weapon is of type bow
  4415. {
  4416. // Absorb HP from the damage inflicted
  4417. double absorbPercent = getStat().calcStat(Stats.ABSORB_DAMAGE_PERCENT, 0, null, null);
  4418. if (absorbPercent > 0)
  4419. {
  4420. int maxCanAbsorb = (int) (getMaxRecoverableHp() - getCurrentHp());
  4421. int absorbDamage = (int) ((absorbPercent / 100.) * damage);
  4422. if (absorbDamage > maxCanAbsorb)
  4423. {
  4424. absorbDamage = maxCanAbsorb; // Can't absord more than max hp
  4425. }
  4426. if (absorbDamage > 0)
  4427. {
  4428. setCurrentHp(getCurrentHp() + absorbDamage);
  4429. }
  4430. }
  4431. // Absorb MP from the damage inflicted
  4432. absorbPercent = getStat().calcStat(Stats.ABSORB_MANA_DAMAGE_PERCENT, 0, null, null);
  4433. if (absorbPercent > 0)
  4434. {
  4435. int maxCanAbsorb = (int) (getMaxRecoverableMp() - getCurrentMp());
  4436. int absorbDamage = (int) ((absorbPercent / 100.) * damage);
  4437. if (absorbDamage > maxCanAbsorb)
  4438. {
  4439. absorbDamage = maxCanAbsorb; // Can't absord more than max hp
  4440. }
  4441. if (absorbDamage > 0)
  4442. {
  4443. setCurrentMp(getCurrentMp() + absorbDamage);
  4444. }
  4445. }
  4446. }
  4447. // Notify AI with EVT_ATTACKED
  4448. if (target.hasAI())
  4449. {
  4450. target.getAI().notifyEvent(CtrlEvent.EVT_ATTACKED, this);
  4451. }
  4452. getAI().clientStartAutoAttack();
  4453. if (isSummon())
  4454. {
  4455. L2PcInstance owner = ((L2Summon) this).getOwner();
  4456. if (owner != null)
  4457. {
  4458. owner.getAI().clientStartAutoAttack();
  4459. }
  4460. }
  4461. // Manage attack or cast break of the target (calculating rate, sending message...)
  4462. if (!target.isRaid() && Formulas.calcAtkBreak(target, damage))
  4463. {
  4464. target.breakAttack();
  4465. target.breakCast();
  4466. }
  4467. if (_triggerSkills != null)
  4468. {
  4469. for (OptionsSkillHolder holder : _triggerSkills.values())
  4470. {
  4471. if ((!crit && (holder.getSkillType() == OptionsSkillType.ATTACK)) || ((holder.getSkillType() == OptionsSkillType.CRITICAL) && crit))
  4472. {
  4473. if (Rnd.get(100) < holder.getChance())
  4474. {
  4475. makeTriggerCast(holder.getSkill(), target);
  4476. }
  4477. }
  4478. }
  4479. }
  4480. }
  4481. // Launch weapon Special ability effect if available
  4482. L2Weapon activeWeapon = getActiveWeaponItem();
  4483. if (activeWeapon != null)
  4484. {
  4485. activeWeapon.castOnCriticalSkill(this, target);
  4486. }
  4487. // Recharge any active auto-soulshot tasks for current creature.
  4488. rechargeShots(true, false);
  4489. }
  4490. /**
  4491. * Break an attack and send Server->Client ActionFailed packet and a System Message to the L2Character.
  4492. */
  4493. public void breakAttack()
  4494. {
  4495. if (isAttackingNow())
  4496. {
  4497. // Abort the attack of the L2Character and send Server->Client ActionFailed packet
  4498. abortAttack();
  4499. if (isPlayer())
  4500. {
  4501. // Send a system message
  4502. sendPacket(SystemMessageId.ATTACK_FAILED);
  4503. }
  4504. }
  4505. }
  4506. /**
  4507. * Break a cast and send Server->Client ActionFailed packet and a System Message to the L2Character.
  4508. */
  4509. public void breakCast()
  4510. {
  4511. // damage can only cancel magical & static skills
  4512. if (isCastingNow() && canAbortCast() && (getLastSkillCast() != null) && (getLastSkillCast().isMagic() || getLastSkillCast().isStatic()))
  4513. {
  4514. // Abort the cast of the L2Character and send Server->Client MagicSkillCanceld/ActionFailed packet.
  4515. abortCast();
  4516. if (isPlayer())
  4517. {
  4518. // Send a system message
  4519. sendPacket(SystemMessageId.CASTING_INTERRUPTED);
  4520. }
  4521. }
  4522. }
  4523. /**
  4524. * Reduce the arrow number of the L2Character.<br>
  4525. * <B><U> Overridden in </U> :</B> <li>L2PcInstance</li>
  4526. * @param bolts
  4527. */
  4528. protected void reduceArrowCount(boolean bolts)
  4529. {
  4530. // default is to do nothing
  4531. }
  4532. /**
  4533. * Manage Forced attack (shift + select target).<br>
  4534. * <B><U>Actions</U>:</B>
  4535. * <ul>
  4536. * <li>If L2Character or target is in a town area, send a system message TARGET_IN_PEACEZONE a Server->Client packet ActionFailed</li>
  4537. * <li>If target is confused, send a Server->Client packet ActionFailed</li>
  4538. * <li>If L2Character is a L2ArtefactInstance, send a Server->Client packet ActionFailed</li>
  4539. * <li>Send a Server->Client packet MyTargetSelected to start attack and Notify AI with AI_INTENTION_ATTACK</li>
  4540. * </ul>
  4541. * @param player The L2PcInstance to attack
  4542. */
  4543. @Override
  4544. public void onForcedAttack(L2PcInstance player)
  4545. {
  4546. if (isInsidePeaceZone(player))
  4547. {
  4548. // If L2Character or target is in a peace zone, send a system message TARGET_IN_PEACEZONE a Server->Client packet ActionFailed
  4549. player.sendPacket(SystemMessageId.TARGET_IN_PEACEZONE);
  4550. player.sendPacket(ActionFailed.STATIC_PACKET);
  4551. return;
  4552. }
  4553. if (player.isInOlympiadMode() && (player.getTarget() != null) && player.getTarget().isPlayable())
  4554. {
  4555. L2PcInstance target = null;
  4556. L2Object object = player.getTarget();
  4557. if ((object != null) && object.isPlayable())
  4558. {
  4559. target = object.getActingPlayer();
  4560. }
  4561. if ((target == null) || (target.isInOlympiadMode() && (!player.isOlympiadStart() || (player.getOlympiadGameId() != target.getOlympiadGameId()))))
  4562. {
  4563. // if L2PcInstance is in Olympia and the match isn't already start, send a Server->Client packet ActionFailed
  4564. player.sendPacket(ActionFailed.STATIC_PACKET);
  4565. return;
  4566. }
  4567. }
  4568. if ((player.getTarget() != null) && !player.getTarget().canBeAttacked() && !player.getAccessLevel().allowPeaceAttack())
  4569. {
  4570. // If target is not attackable, send a Server->Client packet ActionFailed
  4571. player.sendPacket(ActionFailed.STATIC_PACKET);
  4572. return;
  4573. }
  4574. if (player.isConfused())
  4575. {
  4576. // If target is confused, send a Server->Client packet ActionFailed
  4577. player.sendPacket(ActionFailed.STATIC_PACKET);
  4578. return;
  4579. }
  4580. // GeoData Los Check or dz > 1000
  4581. if (!GeoData.getInstance().canSeeTarget(player, this))
  4582. {
  4583. player.sendPacket(SystemMessageId.CANT_SEE_TARGET);
  4584. player.sendPacket(ActionFailed.STATIC_PACKET);
  4585. return;
  4586. }
  4587. if (player.getBlockCheckerArena() != -1)
  4588. {
  4589. player.sendPacket(ActionFailed.STATIC_PACKET);
  4590. return;
  4591. }
  4592. // Notify AI with AI_INTENTION_ATTACK
  4593. player.getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, this);
  4594. }
  4595. /**
  4596. * @param attacker
  4597. * @return True if inside peace zone.
  4598. */
  4599. public boolean isInsidePeaceZone(L2PcInstance attacker)
  4600. {
  4601. return isInsidePeaceZone(attacker, this);
  4602. }
  4603. public boolean isInsidePeaceZone(L2PcInstance attacker, L2Object target)
  4604. {
  4605. return (!attacker.getAccessLevel().allowPeaceAttack() && isInsidePeaceZone((L2Object) attacker, target));
  4606. }
  4607. public boolean isInsidePeaceZone(L2Object attacker, L2Object target)
  4608. {
  4609. if (target == null)
  4610. {
  4611. return false;
  4612. }
  4613. if (!(target.isPlayable() && attacker.isPlayable()))
  4614. {
  4615. return false;
  4616. }
  4617. if (InstanceManager.getInstance().getInstance(getInstanceId()).isPvPInstance())
  4618. {
  4619. return false;
  4620. }
  4621. if (TerritoryWarManager.PLAYER_WITH_WARD_CAN_BE_KILLED_IN_PEACEZONE && TerritoryWarManager.getInstance().isTWInProgress())
  4622. {
  4623. if (target.isPlayer() && target.getActingPlayer().isCombatFlagEquipped())
  4624. {
  4625. return false;
  4626. }
  4627. }
  4628. if (Config.ALT_GAME_KARMA_PLAYER_CAN_BE_KILLED_IN_PEACEZONE)
  4629. {
  4630. // allows red to be attacked and red to attack flagged players
  4631. if ((target.getActingPlayer() != null) && (target.getActingPlayer().getKarma() > 0))
  4632. {
  4633. return false;
  4634. }
  4635. if ((attacker.getActingPlayer() != null) && (attacker.getActingPlayer().getKarma() > 0) && (target.getActingPlayer() != null) && (target.getActingPlayer().getPvpFlag() > 0))
  4636. {
  4637. return false;
  4638. }
  4639. }
  4640. return (target.isInsideZone(ZoneId.PEACE) || attacker.isInsideZone(ZoneId.PEACE));
  4641. }
  4642. /**
  4643. * @return true if this character is inside an active grid.
  4644. */
  4645. public boolean isInActiveRegion()
  4646. {
  4647. L2WorldRegion region = getWorldRegion();
  4648. return ((region != null) && (region.isActive()));
  4649. }
  4650. /**
  4651. * @return True if the L2Character has a Party in progress.
  4652. */
  4653. public boolean isInParty()
  4654. {
  4655. return false;
  4656. }
  4657. /**
  4658. * @return the L2Party object of the L2Character.
  4659. */
  4660. public L2Party getParty()
  4661. {
  4662. return null;
  4663. }
  4664. /**
  4665. * @param target
  4666. * @param weapon
  4667. * @return the Attack Speed of the L2Character (delay (in milliseconds) before next attack).
  4668. */
  4669. public int calculateTimeBetweenAttacks(L2Character target, L2Weapon weapon)
  4670. {
  4671. if ((weapon != null) && !isTransformed())
  4672. {
  4673. switch (weapon.getItemType())
  4674. {
  4675. case BOW:
  4676. return (1500 * 345) / getPAtkSpd();
  4677. case CROSSBOW:
  4678. return (1200 * 345) / getPAtkSpd();
  4679. case DAGGER:
  4680. // atkSpd /= 1.15;
  4681. break;
  4682. }
  4683. }
  4684. return Formulas.calcPAtkSpd(this, target, getPAtkSpd());
  4685. }
  4686. public int calculateReuseTime(L2Character target, L2Weapon weapon)
  4687. {
  4688. if ((weapon == null) || isTransformed())
  4689. {
  4690. return 0;
  4691. }
  4692. int reuse = weapon.getReuseDelay();
  4693. // only bows should continue for now
  4694. if (reuse == 0)
  4695. {
  4696. return 0;
  4697. }
  4698. reuse *= getStat().getWeaponReuseModifier(target);
  4699. double atkSpd = getStat().getPAtkSpd();
  4700. switch (weapon.getItemType())
  4701. {
  4702. case BOW:
  4703. case CROSSBOW:
  4704. return (int) ((reuse * 345) / atkSpd);
  4705. default:
  4706. return (int) ((reuse * 312) / atkSpd);
  4707. }
  4708. }
  4709. /**
  4710. * Add a skill to the L2Character _skills and its Func objects to the calculator set of the L2Character.<br>
  4711. * <B><U>Concept</U>:</B><br>
  4712. * All skills own by a L2Character are identified in <B>_skills</B><br>
  4713. * <B><U>Actions</U>:</B>
  4714. * <ul>
  4715. * <li>Replace oldSkill by newSkill or Add the newSkill</li>
  4716. * <li>If an old skill has been replaced, remove all its Func objects of L2Character calculator set</li>
  4717. * <li>Add Func objects of newSkill to the calculator set of the L2Character</li>
  4718. * </ul>
  4719. * <B><U>Overridden in</U>:</B>
  4720. * <ul>
  4721. * <li>L2PcInstance : Save update in the character_skills table of the database</li>
  4722. * </ul>
  4723. * @param newSkill The L2Skill to add to the L2Character
  4724. * @return The L2Skill replaced or null if just added a new L2Skill
  4725. */
  4726. @Override
  4727. public Skill addSkill(Skill newSkill)
  4728. {
  4729. Skill oldSkill = null;
  4730. if (newSkill != null)
  4731. {
  4732. // Replace oldSkill by newSkill or Add the newSkill
  4733. oldSkill = _skills.put(newSkill.getId(), newSkill);
  4734. // If an old skill has been replaced, remove all its Func objects
  4735. if (oldSkill != null)
  4736. {
  4737. removeStatsOwner(oldSkill);
  4738. }
  4739. // Add Func objects of newSkill to the calculator set of the L2Character
  4740. addStatFuncs(newSkill.getStatFuncs(null, this));
  4741. if (newSkill.isPassive())
  4742. {
  4743. newSkill.applyEffects(this, null, this, false, true, false, 0);
  4744. }
  4745. }
  4746. return oldSkill;
  4747. }
  4748. public Skill removeSkill(Skill skill, boolean cancelEffect)
  4749. {
  4750. return (skill != null) ? removeSkill(skill.getId(), cancelEffect) : null;
  4751. }
  4752. public Skill removeSkill(int skillId)
  4753. {
  4754. return removeSkill(skillId, true);
  4755. }
  4756. public Skill removeSkill(int skillId, boolean cancelEffect)
  4757. {
  4758. // Remove the skill from the L2Character _skills
  4759. Skill oldSkill = _skills.remove(skillId);
  4760. // Remove all its Func objects from the L2Character calculator set
  4761. if (oldSkill != null)
  4762. {
  4763. // Stop casting if this skill is used right now
  4764. if ((getLastSkillCast() != null) && isCastingNow())
  4765. {
  4766. if (oldSkill.getId() == getLastSkillCast().getId())
  4767. {
  4768. abortCast();
  4769. }
  4770. }
  4771. if ((getLastSimultaneousSkillCast() != null) && isCastingSimultaneouslyNow())
  4772. {
  4773. if (oldSkill.getId() == getLastSimultaneousSkillCast().getId())
  4774. {
  4775. abortCast();
  4776. }
  4777. }
  4778. // Stop effects.
  4779. if (cancelEffect || oldSkill.isToggle() || oldSkill.isPassive())
  4780. {
  4781. removeStatsOwner(oldSkill);
  4782. stopSkillEffects(true, oldSkill.getId());
  4783. }
  4784. }
  4785. return oldSkill;
  4786. }
  4787. /**
  4788. * <B><U>Concept</U>:</B><br>
  4789. * All skills own by a L2Character are identified in <B>_skills</B> the L2Character
  4790. * @return all skills own by the L2Character in a table of L2Skill.
  4791. */
  4792. public final Collection<Skill> getAllSkills()
  4793. {
  4794. return new ArrayList<>(_skills.values());
  4795. }
  4796. /**
  4797. * @return the map containing this character skills.
  4798. */
  4799. @Override
  4800. public Map<Integer, Skill> getSkills()
  4801. {
  4802. return _skills;
  4803. }
  4804. /**
  4805. * Return the level of a skill owned by the L2Character.
  4806. * @param skillId The identifier of the L2Skill whose level must be returned
  4807. * @return The level of the L2Skill identified by skillId
  4808. */
  4809. @Override
  4810. public int getSkillLevel(int skillId)
  4811. {
  4812. final Skill skill = getKnownSkill(skillId);
  4813. return (skill == null) ? -1 : skill.getLevel();
  4814. }
  4815. /**
  4816. * @param skillId The identifier of the L2Skill to check the knowledge
  4817. * @return the skill from the known skill.
  4818. */
  4819. @Override
  4820. public final Skill getKnownSkill(int skillId)
  4821. {
  4822. return _skills.get(skillId);
  4823. }
  4824. /**
  4825. * Return the number of buffs affecting this L2Character.
  4826. * @return The number of Buffs affecting this L2Character
  4827. */
  4828. public int getBuffCount()
  4829. {
  4830. return _effectList.getBuffCount();
  4831. }
  4832. public int getDanceCount()
  4833. {
  4834. return _effectList.getDanceCount();
  4835. }
  4836. /**
  4837. * Manage the magic skill launching task (MP, HP, Item consumation...) and display the magic skill animation on client.<br>
  4838. * <B><U>Actions</U>:</B>
  4839. * <ul>
  4840. * <li>Send a Server->Client packet MagicSkillLaunched (to display magic skill animation) to all L2PcInstance of L2Charcater _knownPlayers</li>
  4841. * <li>Consumme MP, HP and Item if necessary</li>
  4842. * <li>Send a Server->Client packet StatusUpdate with MP modification to the L2PcInstance</li>
  4843. * <li>Launch the magic skill in order to calculate its effects</li>
  4844. * <li>If the skill type is PDAM, notify the AI of the target with AI_INTENTION_ATTACK</li>
  4845. * <li>Notify the AI of the L2Character with EVT_FINISH_CASTING</li>
  4846. * </ul>
  4847. * <FONT COLOR=#FF0000><B><U>Caution</U>: A magic skill casting MUST BE in progress</B></FONT>
  4848. * @param mut
  4849. */
  4850. public void onMagicLaunchedTimer(MagicUseTask mut)
  4851. {
  4852. final Skill skill = mut.getSkill();
  4853. L2Object[] targets = mut.getTargets();
  4854. if ((skill == null) || (targets == null))
  4855. {
  4856. abortCast();
  4857. return;
  4858. }
  4859. if (targets.length == 0)
  4860. {
  4861. switch (skill.getTargetType())
  4862. {
  4863. // only AURA-type skills can be cast without target
  4864. case AURA:
  4865. case FRONT_AURA:
  4866. case BEHIND_AURA:
  4867. case AURA_CORPSE_MOB:
  4868. break;
  4869. default:
  4870. abortCast();
  4871. return;
  4872. }
  4873. }
  4874. // Escaping from under skill's radius and peace zone check. First version, not perfect in AoE skills.
  4875. int escapeRange = 0;
  4876. if (skill.getEffectRange() > escapeRange)
  4877. {
  4878. escapeRange = skill.getEffectRange();
  4879. }
  4880. else if ((skill.getCastRange() < 0) && (skill.getAffectRange() > 80))
  4881. {
  4882. escapeRange = skill.getAffectRange();
  4883. }
  4884. if ((targets.length > 0) && (escapeRange > 0))
  4885. {
  4886. int _skiprange = 0;
  4887. int _skipgeo = 0;
  4888. int _skippeace = 0;
  4889. List<L2Character> targetList = new FastList<>(targets.length);
  4890. for (L2Object target : targets)
  4891. {
  4892. if (target instanceof L2Character)
  4893. {
  4894. if (!isInsideRadius(target.getX(), target.getY(), target.getZ(), escapeRange + getTemplate().getCollisionRadius(), true, false))
  4895. {
  4896. _skiprange++;
  4897. continue;
  4898. }
  4899. if ((escapeRange > 0) && (Config.GEODATA > 0) && !GeoData.getInstance().canSeeTarget(this, target))
  4900. {
  4901. _skipgeo++;
  4902. continue;
  4903. }
  4904. if (skill.isBad())
  4905. {
  4906. if (isPlayer())
  4907. {
  4908. if (((L2Character) target).isInsidePeaceZone(getActingPlayer()))
  4909. {
  4910. _skippeace++;
  4911. continue;
  4912. }
  4913. }
  4914. else
  4915. {
  4916. if (((L2Character) target).isInsidePeaceZone(this, target))
  4917. {
  4918. _skippeace++;
  4919. continue;
  4920. }
  4921. }
  4922. }
  4923. targetList.add((L2Character) target);
  4924. }
  4925. }
  4926. if (targetList.isEmpty())
  4927. {
  4928. if (isPlayer())
  4929. {
  4930. if (_skiprange > 0)
  4931. {
  4932. sendPacket(SystemMessageId.DIST_TOO_FAR_CASTING_STOPPED);
  4933. }
  4934. else if (_skipgeo > 0)
  4935. {
  4936. sendPacket(SystemMessageId.CANT_SEE_TARGET);
  4937. }
  4938. else if (_skippeace > 0)
  4939. {
  4940. sendPacket(SystemMessageId.A_MALICIOUS_SKILL_CANNOT_BE_USED_IN_PEACE_ZONE);
  4941. }
  4942. }
  4943. abortCast();
  4944. return;
  4945. }
  4946. mut.setTargets(targetList.toArray(new L2Character[targetList.size()]));
  4947. }
  4948. // Ensure that a cast is in progress
  4949. // Check if player is using fake death.
  4950. // Static skills can be used while faking death.
  4951. if ((mut.isSimultaneous() && !isCastingSimultaneouslyNow()) || (!mut.isSimultaneous() && !isCastingNow()) || (isAlikeDead() && !skill.isStatic()))
  4952. {
  4953. // now cancels both, simultaneous and normal
  4954. getAI().notifyEvent(CtrlEvent.EVT_CANCEL);
  4955. return;
  4956. }
  4957. if (!skill.isToggle())
  4958. {
  4959. broadcastPacket(new MagicSkillLaunched(this, skill.getDisplayId(), skill.getDisplayLevel(), targets));
  4960. }
  4961. mut.setPhase(2);
  4962. if (mut.getSkillTime() == 0)
  4963. {
  4964. onMagicHitTimer(mut);
  4965. }
  4966. else
  4967. {
  4968. _skillCast = ThreadPoolManager.getInstance().scheduleEffect(mut, 400);
  4969. }
  4970. }
  4971. // Runs in the end of skill casting
  4972. public void onMagicHitTimer(MagicUseTask mut)
  4973. {
  4974. final Skill skill = mut.getSkill();
  4975. final L2Object[] targets = mut.getTargets();
  4976. if ((skill == null) || (targets == null))
  4977. {
  4978. abortCast();
  4979. return;
  4980. }
  4981. try
  4982. {
  4983. // Go through targets table
  4984. for (L2Object tgt : targets)
  4985. {
  4986. if (tgt.isPlayable())
  4987. {
  4988. if (isPlayer() && tgt.isSummon())
  4989. {
  4990. ((L2Summon) tgt).updateAndBroadcastStatus(1);
  4991. }
  4992. }
  4993. else if (isPlayable() && tgt.isAttackable())
  4994. {
  4995. L2Character target = (L2Character) tgt;
  4996. if (skill.getEffectPoint() > 0)
  4997. {
  4998. ((L2Attackable) target).reduceHate(this, skill.getEffectPoint());
  4999. }
  5000. else if (skill.getEffectPoint() < 0)
  5001. {
  5002. ((L2Attackable) target).addDamageHate(this, 0, -skill.getEffectPoint());
  5003. }
  5004. }
  5005. }
  5006. rechargeShots(skill.useSoulShot(), skill.useSpiritShot());
  5007. final StatusUpdate su = new StatusUpdate(this);
  5008. boolean isSendStatus = false;
  5009. // Consume MP of the L2Character and Send the Server->Client packet StatusUpdate with current HP and MP to all other L2PcInstance to inform
  5010. double mpConsume = getStat().getMpConsume(skill);
  5011. if (mpConsume > 0)
  5012. {
  5013. if (mpConsume > getCurrentMp())
  5014. {
  5015. sendPacket(SystemMessageId.NOT_ENOUGH_MP);
  5016. abortCast();
  5017. return;
  5018. }
  5019. getStatus().reduceMp(mpConsume);
  5020. su.addAttribute(StatusUpdate.CUR_MP, (int) getCurrentMp());
  5021. isSendStatus = true;
  5022. }
  5023. // Consume HP if necessary and Send the Server->Client packet StatusUpdate with current HP and MP to all other L2PcInstance to inform
  5024. if (skill.getHpConsume() > 0)
  5025. {
  5026. double consumeHp = skill.getHpConsume();
  5027. if (consumeHp >= getCurrentHp())
  5028. {
  5029. sendPacket(SystemMessageId.NOT_ENOUGH_HP);
  5030. abortCast();
  5031. return;
  5032. }
  5033. getStatus().reduceHp(consumeHp, this, true);
  5034. su.addAttribute(StatusUpdate.CUR_HP, (int) getCurrentHp());
  5035. isSendStatus = true;
  5036. }
  5037. // Send a Server->Client packet StatusUpdate with MP modification to the L2PcInstance
  5038. if (isSendStatus)
  5039. {
  5040. sendPacket(su);
  5041. }
  5042. if (isPlayer())
  5043. {
  5044. // Consume Charges
  5045. if (skill.getChargeConsume() > 0)
  5046. {
  5047. getActingPlayer().decreaseCharges(skill.getChargeConsume());
  5048. }
  5049. // Consume Souls if necessary
  5050. if (skill.getMaxSoulConsumeCount() > 0)
  5051. {
  5052. if (!getActingPlayer().decreaseSouls(skill.getMaxSoulConsumeCount(), skill))
  5053. {
  5054. abortCast();
  5055. return;
  5056. }
  5057. }
  5058. }
  5059. // Launch the magic skill in order to calculate its effects
  5060. callSkill(mut.getSkill(), mut.getTargets());
  5061. }
  5062. catch (NullPointerException e)
  5063. {
  5064. _log.log(Level.WARNING, "", e);
  5065. }
  5066. if (mut.getSkillTime() > 0)
  5067. {
  5068. mut.setCount(mut.getCount() + 1);
  5069. }
  5070. mut.setPhase(3);
  5071. if (mut.getSkillTime() == 0)
  5072. {
  5073. onMagicFinalizer(mut);
  5074. }
  5075. else
  5076. {
  5077. if (mut.isSimultaneous())
  5078. {
  5079. _skillCast2 = ThreadPoolManager.getInstance().scheduleEffect(mut, 0);
  5080. }
  5081. else
  5082. {
  5083. _skillCast = ThreadPoolManager.getInstance().scheduleEffect(mut, 0);
  5084. }
  5085. }
  5086. }
  5087. // Runs after skillTime
  5088. public void onMagicFinalizer(MagicUseTask mut)
  5089. {
  5090. if (mut.isSimultaneous())
  5091. {
  5092. _skillCast2 = null;
  5093. setIsCastingSimultaneouslyNow(false);
  5094. return;
  5095. }
  5096. // Cleanup
  5097. _skillCast = null;
  5098. _castInterruptTime = 0;
  5099. // Stop casting
  5100. setIsCastingNow(false);
  5101. final Skill skill = mut.getSkill();
  5102. final L2Object target = mut.getTargets().length > 0 ? mut.getTargets()[0] : null;
  5103. // On each repeat recharge shots before cast.
  5104. if (mut.getCount() > 0)
  5105. {
  5106. rechargeShots(mut.getSkill().useSoulShot(), mut.getSkill().useSpiritShot());
  5107. }
  5108. // Attack target after skill use
  5109. if ((skill.nextActionIsAttack()) && (getTarget() instanceof L2Character) && (getTarget() != this) && (target != null) && (getTarget() == target) && target.canBeAttacked())
  5110. {
  5111. if ((getAI().getNextIntention() == null) || (getAI().getNextIntention().getCtrlIntention() != CtrlIntention.AI_INTENTION_MOVE_TO))
  5112. {
  5113. getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
  5114. }
  5115. }
  5116. if (skill.isBad() && (skill.getTargetType() != L2TargetType.UNLOCKABLE))
  5117. {
  5118. getAI().clientStartAutoAttack();
  5119. }
  5120. // Notify the AI of the L2Character with EVT_FINISH_CASTING
  5121. getAI().notifyEvent(CtrlEvent.EVT_FINISH_CASTING);
  5122. // Notify DP Scripts
  5123. notifyQuestEventSkillFinished(skill, target);
  5124. // If character is a player, then wipe their current cast state and check if a skill is queued.
  5125. // If there is a queued skill, launch it and wipe the queue.
  5126. if (isPlayer())
  5127. {
  5128. L2PcInstance currPlayer = getActingPlayer();
  5129. SkillUseHolder queuedSkill = currPlayer.getQueuedSkill();
  5130. currPlayer.setCurrentSkill(null, false, false);
  5131. if (queuedSkill != null)
  5132. {
  5133. currPlayer.setQueuedSkill(null, false, false);
  5134. // DON'T USE : Recursive call to useMagic() method
  5135. // currPlayer.useMagic(queuedSkill.getSkill(), queuedSkill.isCtrlPressed(), queuedSkill.isShiftPressed());
  5136. ThreadPoolManager.getInstance().executeGeneral(new QueuedMagicUseTask(currPlayer, queuedSkill.getSkill(), queuedSkill.isCtrlPressed(), queuedSkill.isShiftPressed()));
  5137. }
  5138. }
  5139. if (isChanneling())
  5140. {
  5141. getSkillChannelizer().stopChanneling();
  5142. }
  5143. }
  5144. // Quest event ON_SPELL_FNISHED
  5145. protected void notifyQuestEventSkillFinished(Skill skill, L2Object target)
  5146. {
  5147. }
  5148. /**
  5149. * Launch the magic skill and calculate its effects on each target contained in the targets table.
  5150. * @param skill The L2Skill to use
  5151. * @param targets The table of L2Object targets
  5152. */
  5153. public void callSkill(Skill skill, L2Object[] targets)
  5154. {
  5155. try
  5156. {
  5157. L2Weapon activeWeapon = getActiveWeaponItem();
  5158. // Check if the toggle skill effects are already in progress on the L2Character
  5159. if (skill.isToggle() && isAffectedBySkill(skill.getId()))
  5160. {
  5161. return;
  5162. }
  5163. // Initial checks
  5164. for (L2Object obj : targets)
  5165. {
  5166. if ((obj == null) || !obj.isCharacter())
  5167. {
  5168. continue;
  5169. }
  5170. final L2Character target = (L2Character) obj;
  5171. // Check raid monster attack and check buffing characters who attack raid monsters.
  5172. L2Character targetsAttackTarget = null;
  5173. L2Character targetsCastTarget = null;
  5174. if (target.hasAI())
  5175. {
  5176. targetsAttackTarget = target.getAI().getAttackTarget();
  5177. targetsCastTarget = target.getAI().getCastTarget();
  5178. }
  5179. if (!Config.RAID_DISABLE_CURSE && ((target.isRaid() && target.giveRaidCurse() && (getLevel() > (target.getLevel() + 8))) || (!skill.isBad() && (targetsAttackTarget != null) && targetsAttackTarget.isRaid() && targetsAttackTarget.giveRaidCurse() && targetsAttackTarget.getAttackByList().contains(target) && (getLevel() > (targetsAttackTarget.getLevel() + 8))) || (!skill.isBad() && (targetsCastTarget != null) && targetsCastTarget.isRaid() && targetsCastTarget.giveRaidCurse() && targetsCastTarget.getAttackByList().contains(target) && (getLevel() > (targetsCastTarget.getLevel() + 8)))))
  5180. {
  5181. final CommonSkill curse = skill.isMagic() ? CommonSkill.RAID_CURSE : CommonSkill.RAID_CURSE2;
  5182. Skill curseSkill = curse.getSkill();
  5183. if (curseSkill != null)
  5184. {
  5185. abortAttack();
  5186. abortCast();
  5187. getAI().setIntention(CtrlIntention.AI_INTENTION_IDLE);
  5188. curseSkill.applyEffects(target, this);
  5189. }
  5190. else
  5191. {
  5192. _log.warning("Skill ID " + curse.getId() + " level " + curse.getLevel() + " is missing in DP!");
  5193. }
  5194. return;
  5195. }
  5196. // Check if over-hit is possible
  5197. if (skill.isOverhit())
  5198. {
  5199. if (target.isAttackable())
  5200. {
  5201. ((L2Attackable) target).overhitEnabled(true);
  5202. }
  5203. }
  5204. // Static skills not trigger any chance skills
  5205. if (!skill.isStatic())
  5206. {
  5207. // Launch weapon Special ability skill effect if available
  5208. if ((activeWeapon != null) && !target.isDead())
  5209. {
  5210. activeWeapon.castOnMagicSkill(this, target, skill);
  5211. }
  5212. if (_triggerSkills != null)
  5213. {
  5214. for (OptionsSkillHolder holder : _triggerSkills.values())
  5215. {
  5216. if ((skill.isMagic() && (holder.getSkillType() == OptionsSkillType.MAGIC)) || (skill.isPhysical() && (holder.getSkillType() == OptionsSkillType.ATTACK)))
  5217. {
  5218. if (Rnd.get(100) < holder.getChance())
  5219. {
  5220. makeTriggerCast(holder.getSkill(), target);
  5221. }
  5222. }
  5223. }
  5224. }
  5225. }
  5226. }
  5227. // Launch the magic skill and calculate its effects
  5228. skill.activateSkill(this, targets);
  5229. L2PcInstance player = getActingPlayer();
  5230. if (player != null)
  5231. {
  5232. for (L2Object target : targets)
  5233. {
  5234. // EVT_ATTACKED and PvPStatus
  5235. if (target instanceof L2Character)
  5236. {
  5237. if (skill.getEffectPoint() <= 0)
  5238. {
  5239. if ((target.isPlayable() || target.isTrap()) && skill.isBad())
  5240. {
  5241. // Casted on target_self but don't harm self
  5242. if (!target.equals(this))
  5243. {
  5244. // Combat-mode check
  5245. if (target.isPlayer())
  5246. {
  5247. target.getActingPlayer().getAI().clientStartAutoAttack();
  5248. }
  5249. else if (target.isSummon() && ((L2Character) target).hasAI())
  5250. {
  5251. L2PcInstance owner = ((L2Summon) target).getOwner();
  5252. if (owner != null)
  5253. {
  5254. owner.getAI().clientStartAutoAttack();
  5255. }
  5256. }
  5257. // attack of the own pet does not flag player
  5258. // triggering trap not flag trap owner
  5259. if ((player.getSummon() != target) && !isTrap() && !((skill.getEffectPoint() == 0) && (skill.getAffectRange() > 0)))
  5260. {
  5261. player.updatePvPStatus((L2Character) target);
  5262. }
  5263. }
  5264. }
  5265. else if (target.isAttackable())
  5266. {
  5267. switch (skill.getId())
  5268. {
  5269. case 51: // Lure
  5270. case 511: // Temptation
  5271. break;
  5272. default:
  5273. // add attacker into list
  5274. ((L2Character) target).addAttackerToAttackByList(this);
  5275. }
  5276. }
  5277. // notify target AI about the attack
  5278. if (((L2Character) target).hasAI() && !skill.hasEffectType(L2EffectType.HATE))
  5279. {
  5280. ((L2Character) target).getAI().notifyEvent(CtrlEvent.EVT_ATTACKED, this);
  5281. }
  5282. }
  5283. else
  5284. {
  5285. if (target.isPlayer())
  5286. {
  5287. // Casting non offensive skill on player with pvp flag set or with karma
  5288. if (!(target.equals(this) || target.equals(player)) && ((target.getActingPlayer().getPvpFlag() > 0) || (target.getActingPlayer().getKarma() > 0)))
  5289. {
  5290. player.updatePvPStatus();
  5291. }
  5292. }
  5293. else if (target.isAttackable())
  5294. {
  5295. player.updatePvPStatus();
  5296. }
  5297. }
  5298. }
  5299. }
  5300. // Mobs in range 1000 see spell
  5301. Collection<L2Object> objs = player.getKnownList().getKnownObjects().values();
  5302. for (L2Object spMob : objs)
  5303. {
  5304. if ((spMob != null) && spMob.isNpc())
  5305. {
  5306. final L2Npc npcMob = (L2Npc) spMob;
  5307. if ((npcMob.isInsideRadius(player, 1000, true, true)))
  5308. {
  5309. EventDispatcher.getInstance().notifyEventAsync(new OnNpcSkillSee(npcMob, player, skill, targets, isSummon()), npcMob);
  5310. // On Skill See logic
  5311. if (npcMob.isAttackable())
  5312. {
  5313. final L2Attackable attackable = (L2Attackable) npcMob;
  5314. int skillEffectPoint = skill.getEffectPoint();
  5315. if (player.hasSummon())
  5316. {
  5317. if ((targets.length == 1) && Util.contains(targets, player.getSummon()))
  5318. {
  5319. skillEffectPoint = 0;
  5320. }
  5321. }
  5322. if (skillEffectPoint > 0)
  5323. {
  5324. if (attackable.hasAI() && (attackable.getAI().getIntention() == AI_INTENTION_ATTACK))
  5325. {
  5326. L2Object npcTarget = attackable.getTarget();
  5327. for (L2Object skillTarget : targets)
  5328. {
  5329. if ((npcTarget == skillTarget) || (npcMob == skillTarget))
  5330. {
  5331. L2Character originalCaster = isSummon() ? getSummon() : player;
  5332. attackable.addDamageHate(originalCaster, 0, (skillEffectPoint * 150) / (attackable.getLevel() + 7));
  5333. }
  5334. }
  5335. }
  5336. }
  5337. }
  5338. }
  5339. }
  5340. }
  5341. }
  5342. // Notify AI
  5343. if (skill.isBad() && !skill.hasEffectType(L2EffectType.HATE))
  5344. {
  5345. for (L2Object target : targets)
  5346. {
  5347. if ((target instanceof L2Character) && ((L2Character) target).hasAI())
  5348. {
  5349. // notify target AI about the attack
  5350. ((L2Character) target).getAI().notifyEvent(CtrlEvent.EVT_ATTACKED, this);
  5351. }
  5352. }
  5353. }
  5354. }
  5355. catch (Exception e)
  5356. {
  5357. _log.log(Level.WARNING, getClass().getSimpleName() + ": callSkill() failed.", e);
  5358. }
  5359. }
  5360. /**
  5361. * @param target
  5362. * @return True if the L2Character is behind the target and can't be seen.
  5363. */
  5364. public boolean isBehind(L2Object target)
  5365. {
  5366. double angleChar, angleTarget, angleDiff, maxAngleDiff = 60;
  5367. if (target == null)
  5368. {
  5369. return false;
  5370. }
  5371. if (target instanceof L2Character)
  5372. {
  5373. L2Character target1 = (L2Character) target;
  5374. angleChar = Util.calculateAngleFrom(this, target1);
  5375. angleTarget = Util.convertHeadingToDegree(target1.getHeading());
  5376. angleDiff = angleChar - angleTarget;
  5377. if (angleDiff <= (-360 + maxAngleDiff))
  5378. {
  5379. angleDiff += 360;
  5380. }
  5381. if (angleDiff >= (360 - maxAngleDiff))
  5382. {
  5383. angleDiff -= 360;
  5384. }
  5385. if (Math.abs(angleDiff) <= maxAngleDiff)
  5386. {
  5387. return true;
  5388. }
  5389. }
  5390. return false;
  5391. }
  5392. public boolean isBehindTarget()
  5393. {
  5394. return isBehind(getTarget());
  5395. }
  5396. /**
  5397. * @param target
  5398. * @return True if the target is facing the L2Character.
  5399. */
  5400. public boolean isInFrontOf(L2Character target)
  5401. {
  5402. double angleChar, angleTarget, angleDiff, maxAngleDiff = 60;
  5403. if (target == null)
  5404. {
  5405. return false;
  5406. }
  5407. angleTarget = Util.calculateAngleFrom(target, this);
  5408. angleChar = Util.convertHeadingToDegree(target.getHeading());
  5409. angleDiff = angleChar - angleTarget;
  5410. if (angleDiff <= (-360 + maxAngleDiff))
  5411. {
  5412. angleDiff += 360;
  5413. }
  5414. if (angleDiff >= (360 - maxAngleDiff))
  5415. {
  5416. angleDiff -= 360;
  5417. }
  5418. return Math.abs(angleDiff) <= maxAngleDiff;
  5419. }
  5420. /**
  5421. * @param target
  5422. * @param maxAngle
  5423. * @return true if target is in front of L2Character (shield def etc)
  5424. */
  5425. public boolean isFacing(L2Object target, int maxAngle)
  5426. {
  5427. double angleChar, angleTarget, angleDiff, maxAngleDiff;
  5428. if (target == null)
  5429. {
  5430. return false;
  5431. }
  5432. maxAngleDiff = maxAngle / 2.;
  5433. angleTarget = Util.calculateAngleFrom(this, target);
  5434. angleChar = Util.convertHeadingToDegree(getHeading());
  5435. angleDiff = angleChar - angleTarget;
  5436. if (angleDiff <= (-360 + maxAngleDiff))
  5437. {
  5438. angleDiff += 360;
  5439. }
  5440. if (angleDiff >= (360 - maxAngleDiff))
  5441. {
  5442. angleDiff -= 360;
  5443. }
  5444. return Math.abs(angleDiff) <= maxAngleDiff;
  5445. }
  5446. public boolean isInFrontOfTarget()
  5447. {
  5448. L2Object target = getTarget();
  5449. if (target instanceof L2Character)
  5450. {
  5451. return isInFrontOf((L2Character) target);
  5452. }
  5453. return false;
  5454. }
  5455. /**
  5456. * @return the Level Modifier ((level + 89) / 100).
  5457. */
  5458. public double getLevelMod()
  5459. {
  5460. return ((getLevel() + 89) / 100d);
  5461. }
  5462. public final void setSkillCast(Future<?> newSkillCast)
  5463. {
  5464. _skillCast = newSkillCast;
  5465. }
  5466. /**
  5467. * Sets _isCastingNow to true and _castInterruptTime is calculated from end time (ticks)
  5468. * @param newSkillCastEndTick
  5469. */
  5470. public final void forceIsCasting(int newSkillCastEndTick)
  5471. {
  5472. setIsCastingNow(true);
  5473. // for interrupt -400 ms
  5474. _castInterruptTime = newSkillCastEndTick - 4;
  5475. }
  5476. private boolean _AIdisabled = false;
  5477. public void updatePvPFlag(int value)
  5478. {
  5479. // Overridden in L2PcInstance
  5480. }
  5481. /**
  5482. * @return a multiplier based on weapon random damage
  5483. */
  5484. public final double getRandomDamageMultiplier()
  5485. {
  5486. L2Weapon activeWeapon = getActiveWeaponItem();
  5487. int random;
  5488. if (activeWeapon != null)
  5489. {
  5490. random = activeWeapon.getRandomDamage();
  5491. }
  5492. else
  5493. {
  5494. random = 5 + (int) Math.sqrt(getLevel());
  5495. }
  5496. return (1 + ((double) Rnd.get(0 - random, random) / 100));
  5497. }
  5498. public final long getAttackEndTime()
  5499. {
  5500. return _attackEndTime;
  5501. }
  5502. public int getBowAttackEndTime()
  5503. {
  5504. return _disableBowAttackEndTime;
  5505. }
  5506. /**
  5507. * Not Implemented.
  5508. * @return
  5509. */
  5510. public abstract int getLevel();
  5511. // Stat - NEED TO REMOVE ONCE L2CHARSTAT IS COMPLETE
  5512. public final double calcStat(Stats stat, double init, L2Character target, Skill skill)
  5513. {
  5514. return getStat().calcStat(stat, init, target, skill);
  5515. }
  5516. public int getAccuracy()
  5517. {
  5518. return getStat().getAccuracy();
  5519. }
  5520. public final float getAttackSpeedMultiplier()
  5521. {
  5522. return getStat().getAttackSpeedMultiplier();
  5523. }
  5524. public final double getCriticalDmg(L2Character target, double init)
  5525. {
  5526. return getStat().getCriticalDmg(target, init);
  5527. }
  5528. public int getCriticalHit(L2Character target, Skill skill)
  5529. {
  5530. return getStat().getCriticalHit(target, skill);
  5531. }
  5532. public int getEvasionRate(L2Character target)
  5533. {
  5534. return getStat().getEvasionRate(target);
  5535. }
  5536. public final int getMagicalAttackRange(Skill skill)
  5537. {
  5538. return getStat().getMagicalAttackRange(skill);
  5539. }
  5540. public final int getMaxCp()
  5541. {
  5542. return getStat().getMaxCp();
  5543. }
  5544. public final int getMaxRecoverableCp()
  5545. {
  5546. return getStat().getMaxRecoverableCp();
  5547. }
  5548. public int getMAtk(L2Character target, Skill skill)
  5549. {
  5550. return getStat().getMAtk(target, skill);
  5551. }
  5552. public int getMAtkSpd()
  5553. {
  5554. return getStat().getMAtkSpd();
  5555. }
  5556. public int getMaxMp()
  5557. {
  5558. return getStat().getMaxMp();
  5559. }
  5560. public int getMaxRecoverableMp()
  5561. {
  5562. return getStat().getMaxRecoverableMp();
  5563. }
  5564. public int getMaxHp()
  5565. {
  5566. return getStat().getMaxHp();
  5567. }
  5568. public int getMaxRecoverableHp()
  5569. {
  5570. return getStat().getMaxRecoverableHp();
  5571. }
  5572. public final int getMCriticalHit(L2Character target, Skill skill)
  5573. {
  5574. return getStat().getMCriticalHit(target, skill);
  5575. }
  5576. public int getMDef(L2Character target, Skill skill)
  5577. {
  5578. return getStat().getMDef(target, skill);
  5579. }
  5580. public double getMReuseRate(Skill skill)
  5581. {
  5582. return getStat().getMReuseRate(skill);
  5583. }
  5584. public int getPAtk(L2Character target)
  5585. {
  5586. return getStat().getPAtk(target);
  5587. }
  5588. public int getPAtkSpd()
  5589. {
  5590. return getStat().getPAtkSpd();
  5591. }
  5592. public int getPDef(L2Character target)
  5593. {
  5594. return getStat().getPDef(target);
  5595. }
  5596. public final int getPhysicalAttackRange()
  5597. {
  5598. return getStat().getPhysicalAttackRange();
  5599. }
  5600. public double getMovementSpeedMultiplier()
  5601. {
  5602. return getStat().getMovementSpeedMultiplier();
  5603. }
  5604. public double getRunSpeed()
  5605. {
  5606. return getStat().getRunSpeed();
  5607. }
  5608. public double getWalkSpeed()
  5609. {
  5610. return getStat().getWalkSpeed();
  5611. }
  5612. public final double getSwimRunSpeed()
  5613. {
  5614. return getStat().getSwimRunSpeed();
  5615. }
  5616. public final double getSwimWalkSpeed()
  5617. {
  5618. return getStat().getSwimWalkSpeed();
  5619. }
  5620. public double getMoveSpeed()
  5621. {
  5622. return getStat().getMoveSpeed();
  5623. }
  5624. public final int getShldDef()
  5625. {
  5626. return getStat().getShldDef();
  5627. }
  5628. public int getSTR()
  5629. {
  5630. return getStat().getSTR();
  5631. }
  5632. public int getDEX()
  5633. {
  5634. return getStat().getDEX();
  5635. }
  5636. public int getCON()
  5637. {
  5638. return getStat().getCON();
  5639. }
  5640. public int getINT()
  5641. {
  5642. return getStat().getINT();
  5643. }
  5644. public int getWIT()
  5645. {
  5646. return getStat().getWIT();
  5647. }
  5648. public int getMEN()
  5649. {
  5650. return getStat().getMEN();
  5651. }
  5652. // Status - NEED TO REMOVE ONCE L2CHARTATUS IS COMPLETE
  5653. public void addStatusListener(L2Character object)
  5654. {
  5655. getStatus().addStatusListener(object);
  5656. }
  5657. public void reduceCurrentHp(double i, L2Character attacker, Skill skill)
  5658. {
  5659. reduceCurrentHp(i, attacker, true, false, skill);
  5660. }
  5661. public void reduceCurrentHpByDOT(double i, L2Character attacker, Skill skill)
  5662. {
  5663. reduceCurrentHp(i, attacker, !skill.isToggle(), true, skill);
  5664. }
  5665. public void reduceCurrentHp(double i, L2Character attacker, boolean awake, boolean isDOT, Skill skill)
  5666. {
  5667. if (Config.L2JMOD_CHAMPION_ENABLE && isChampion() && (Config.L2JMOD_CHAMPION_HP != 0))
  5668. {
  5669. getStatus().reduceHp(i / Config.L2JMOD_CHAMPION_HP, attacker, awake, isDOT, false);
  5670. }
  5671. else
  5672. {
  5673. getStatus().reduceHp(i, attacker, awake, isDOT, false);
  5674. }
  5675. }
  5676. public void reduceCurrentMp(double i)
  5677. {
  5678. getStatus().reduceMp(i);
  5679. }
  5680. @Override
  5681. public void removeStatusListener(L2Character object)
  5682. {
  5683. getStatus().removeStatusListener(object);
  5684. }
  5685. protected void stopHpMpRegeneration()
  5686. {
  5687. getStatus().stopHpMpRegeneration();
  5688. }
  5689. public final double getCurrentCp()
  5690. {
  5691. return getStatus().getCurrentCp();
  5692. }
  5693. public final void setCurrentCp(double newCp)
  5694. {
  5695. getStatus().setCurrentCp(newCp);
  5696. }
  5697. public final double getCurrentHp()
  5698. {
  5699. return getStatus().getCurrentHp();
  5700. }
  5701. public final void setCurrentHp(double newHp)
  5702. {
  5703. getStatus().setCurrentHp(newHp);
  5704. }
  5705. public final void setCurrentHpMp(double newHp, double newMp)
  5706. {
  5707. getStatus().setCurrentHpMp(newHp, newMp);
  5708. }
  5709. public final double getCurrentMp()
  5710. {
  5711. return getStatus().getCurrentMp();
  5712. }
  5713. public final void setCurrentMp(double newMp)
  5714. {
  5715. getStatus().setCurrentMp(newMp);
  5716. }
  5717. /**
  5718. * @return the max weight that the L2Character can load.
  5719. */
  5720. public int getMaxLoad()
  5721. {
  5722. if (isPlayer() || isPet())
  5723. {
  5724. // Weight Limit = (CON Modifier*69000) * Skills
  5725. // Source http://l2p.bravehost.com/weightlimit.html (May 2007)
  5726. double baseLoad = Math.floor(BaseStats.CON.calcBonus(this) * 69000 * Config.ALT_WEIGHT_LIMIT);
  5727. return (int) calcStat(Stats.WEIGHT_LIMIT, baseLoad, this, null);
  5728. }
  5729. return 0;
  5730. }
  5731. public int getBonusWeightPenalty()
  5732. {
  5733. if (isPlayer() || isPet())
  5734. {
  5735. return (int) calcStat(Stats.WEIGHT_PENALTY, 1, this, null);
  5736. }
  5737. return 0;
  5738. }
  5739. /**
  5740. * @return the current weight of the L2Character.
  5741. */
  5742. public int getCurrentLoad()
  5743. {
  5744. if (isPlayer() || isPet())
  5745. {
  5746. return getInventory().getTotalWeight();
  5747. }
  5748. return 0;
  5749. }
  5750. public boolean isChampion()
  5751. {
  5752. return false;
  5753. }
  5754. /**
  5755. * Send system message about damage.
  5756. * @param target
  5757. * @param damage
  5758. * @param mcrit
  5759. * @param pcrit
  5760. * @param miss
  5761. */
  5762. public void sendDamageMessage(L2Character target, int damage, boolean mcrit, boolean pcrit, boolean miss)
  5763. {
  5764. }
  5765. public byte getAttackElement()
  5766. {
  5767. return getStat().getAttackElement();
  5768. }
  5769. public int getAttackElementValue(byte attackAttribute)
  5770. {
  5771. return getStat().getAttackElementValue(attackAttribute);
  5772. }
  5773. public int getDefenseElementValue(byte defenseAttribute)
  5774. {
  5775. return getStat().getDefenseElementValue(defenseAttribute);
  5776. }
  5777. public final void startPhysicalAttackMuted()
  5778. {
  5779. abortAttack();
  5780. }
  5781. public void disableCoreAI(boolean val)
  5782. {
  5783. _AIdisabled = val;
  5784. }
  5785. public boolean isCoreAIDisabled()
  5786. {
  5787. return _AIdisabled;
  5788. }
  5789. /**
  5790. * @return true
  5791. */
  5792. public boolean giveRaidCurse()
  5793. {
  5794. return true;
  5795. }
  5796. /**
  5797. * Check if target is affected with special buff
  5798. * @see CharEffectList#isAffected(EffectFlag)
  5799. * @param flag int
  5800. * @return boolean
  5801. */
  5802. public boolean isAffected(EffectFlag flag)
  5803. {
  5804. return _effectList.isAffected(flag);
  5805. }
  5806. public void broadcastSocialAction(int id)
  5807. {
  5808. broadcastPacket(new SocialAction(getObjectId(), id));
  5809. }
  5810. public Team getTeam()
  5811. {
  5812. return _team;
  5813. }
  5814. public void setTeam(Team team)
  5815. {
  5816. _team = team;
  5817. }
  5818. public void addOverrideCond(PcCondOverride... excs)
  5819. {
  5820. for (PcCondOverride exc : excs)
  5821. {
  5822. _exceptions |= exc.getMask();
  5823. }
  5824. }
  5825. public void removeOverridedCond(PcCondOverride... excs)
  5826. {
  5827. for (PcCondOverride exc : excs)
  5828. {
  5829. _exceptions &= ~exc.getMask();
  5830. }
  5831. }
  5832. public boolean canOverrideCond(PcCondOverride excs)
  5833. {
  5834. return (_exceptions & excs.getMask()) == excs.getMask();
  5835. }
  5836. public void setOverrideCond(long masks)
  5837. {
  5838. _exceptions = masks;
  5839. }
  5840. public void setLethalable(boolean val)
  5841. {
  5842. _lethalable = val;
  5843. }
  5844. public boolean isLethalable()
  5845. {
  5846. return _lethalable;
  5847. }
  5848. public Map<Integer, OptionsSkillHolder> getTriggerSkills()
  5849. {
  5850. if (_triggerSkills == null)
  5851. {
  5852. synchronized (this)
  5853. {
  5854. if (_triggerSkills == null)
  5855. {
  5856. _triggerSkills = new ConcurrentHashMap<>();
  5857. }
  5858. }
  5859. }
  5860. return _triggerSkills;
  5861. }
  5862. public void addTriggerSkill(OptionsSkillHolder holder)
  5863. {
  5864. getTriggerSkills().put(holder.getSkillId(), holder);
  5865. }
  5866. public void removeTriggerSkill(OptionsSkillHolder holder)
  5867. {
  5868. getTriggerSkills().remove(holder.getSkillId());
  5869. }
  5870. public void makeTriggerCast(Skill skill, L2Character target, boolean ignoreTargetType)
  5871. {
  5872. try
  5873. {
  5874. if ((skill == null))
  5875. {
  5876. return;
  5877. }
  5878. if (skill.checkCondition(this, target, false))
  5879. {
  5880. if (isSkillDisabled(skill))
  5881. {
  5882. return;
  5883. }
  5884. if (skill.getReuseDelay() > 0)
  5885. {
  5886. disableSkill(skill, skill.getReuseDelay());
  5887. }
  5888. // @formatter:off
  5889. final L2Object[] targets = !ignoreTargetType ? skill.getTargetList(this, false, target) : new L2Character[]{ target };
  5890. // @formatter:on
  5891. if (targets.length == 0)
  5892. {
  5893. return;
  5894. }
  5895. for (L2Object obj : targets)
  5896. {
  5897. if ((obj != null) && obj.isCharacter())
  5898. {
  5899. target = (L2Character) obj;
  5900. break;
  5901. }
  5902. }
  5903. if (Config.ALT_VALIDATE_TRIGGER_SKILLS && isPlayable() && (target != null) && target.isPlayable())
  5904. {
  5905. final L2PcInstance player = getActingPlayer();
  5906. if (!player.checkPvpSkill(target, skill))
  5907. {
  5908. return;
  5909. }
  5910. }
  5911. broadcastPacket(new MagicSkillUse(this, target, skill.getDisplayId(), skill.getLevel(), 0, 0));
  5912. broadcastPacket(new MagicSkillLaunched(this, skill.getDisplayId(), skill.getLevel(), targets));
  5913. // Launch the magic skill and calculate its effects
  5914. skill.activateSkill(this, targets);
  5915. }
  5916. }
  5917. catch (Exception e)
  5918. {
  5919. _log.log(Level.WARNING, "", e);
  5920. }
  5921. }
  5922. public void makeTriggerCast(Skill skill, L2Character target)
  5923. {
  5924. makeTriggerCast(skill, target, false);
  5925. }
  5926. /**
  5927. * Dummy method overriden in {@link L2PcInstance}
  5928. * @return {@code true} if current player can revive and shows 'To Village' button upon death, {@code false} otherwise.
  5929. */
  5930. public boolean canRevive()
  5931. {
  5932. return true;
  5933. }
  5934. /**
  5935. * Dummy method overriden in {@link L2PcInstance}
  5936. * @param val
  5937. */
  5938. public void setCanRevive(boolean val)
  5939. {
  5940. }
  5941. /**
  5942. * Dummy method overriden in {@link L2Attackable}
  5943. * @return {@code true} if there is a loot to sweep, {@code false} otherwise.
  5944. */
  5945. public boolean isSweepActive()
  5946. {
  5947. return false;
  5948. }
  5949. /**
  5950. * Dummy method overriden in {@link L2PcInstance}
  5951. * @return {@code true} if player is on event, {@code false} otherwise.
  5952. */
  5953. public boolean isOnEvent()
  5954. {
  5955. return false;
  5956. }
  5957. /**
  5958. * Dummy method overriden in {@link L2PcInstance}
  5959. * @return the clan id of current character.
  5960. */
  5961. public int getClanId()
  5962. {
  5963. return 0;
  5964. }
  5965. /**
  5966. * Dummy method overriden in {@link L2PcInstance}
  5967. * @return the clan of current character.
  5968. */
  5969. public L2Clan getClan()
  5970. {
  5971. return null;
  5972. }
  5973. /**
  5974. * Dummy method overriden in {@link L2PcInstance}
  5975. * @return {@code true} if player is in academy, {@code false} otherwise.
  5976. */
  5977. public boolean isAcademyMember()
  5978. {
  5979. return false;
  5980. }
  5981. /**
  5982. * Dummy method overriden in {@link L2PcInstance}
  5983. * @return the pledge type of current character.
  5984. */
  5985. public int getPledgeType()
  5986. {
  5987. return 0;
  5988. }
  5989. /**
  5990. * Dummy method overriden in {@link L2PcInstance}
  5991. * @return the alliance id of current character.
  5992. */
  5993. public int getAllyId()
  5994. {
  5995. return 0;
  5996. }
  5997. /**
  5998. * Notifies to listeners that current character received damage.
  5999. * @param damage
  6000. * @param attacker
  6001. * @param skill
  6002. * @param critical
  6003. * @param damageOverTime
  6004. */
  6005. public void notifyDamageReceived(double damage, L2Character attacker, Skill skill, boolean critical, boolean damageOverTime)
  6006. {
  6007. EventDispatcher.getInstance().notifyEventAsync(new OnCreatureDamageReceived(attacker, this, damage, skill, critical, damageOverTime), this);
  6008. EventDispatcher.getInstance().notifyEventAsync(new OnCreatureDamageDealt(attacker, this, damage, skill, critical, damageOverTime), attacker);
  6009. }
  6010. /**
  6011. * Notifies to listeners that current character avoid attack.
  6012. * @param target
  6013. * @param isDot
  6014. */
  6015. public void notifyAttackAvoid(final L2Character target, final boolean isDot)
  6016. {
  6017. EventDispatcher.getInstance().notifyEventAsync(new OnCreatureAttackAvoid(this, target, isDot), target);
  6018. }
  6019. /**
  6020. * @return {@link WeaponType} of current character's weapon or basic weapon type.
  6021. */
  6022. public final WeaponType getAttackType()
  6023. {
  6024. final L2Weapon weapon = getActiveWeaponItem();
  6025. if (weapon != null)
  6026. {
  6027. return weapon.getItemType();
  6028. }
  6029. else if (isTransformed())
  6030. {
  6031. final TransformTemplate template = getTransformation().getTemplate(getActingPlayer());
  6032. if (template != null)
  6033. {
  6034. return template.getBaseAttackType();
  6035. }
  6036. }
  6037. return getTemplate().getBaseAttackType();
  6038. }
  6039. public final boolean isInCategory(CategoryType type)
  6040. {
  6041. return CategoryData.getInstance().isInCategory(type, getId());
  6042. }
  6043. /**
  6044. * @return the character that summoned this NPC.
  6045. */
  6046. public L2Character getSummoner()
  6047. {
  6048. return _summoner;
  6049. }
  6050. /**
  6051. * @param summoner the summoner of this NPC.
  6052. */
  6053. public void setSummoner(L2Character summoner)
  6054. {
  6055. _summoner = summoner;
  6056. }
  6057. @Override
  6058. public boolean isCharacter()
  6059. {
  6060. return true;
  6061. }
  6062. /**
  6063. * @return {@code true} if current character is casting channeling skill, {@code false} otherwise.
  6064. */
  6065. public final boolean isChanneling()
  6066. {
  6067. return (_channelizer != null) && _channelizer.isChanneling();
  6068. }
  6069. public final SkillChannelizer getSkillChannelizer()
  6070. {
  6071. if (_channelizer == null)
  6072. {
  6073. _channelizer = new SkillChannelizer(this);
  6074. }
  6075. return _channelizer;
  6076. }
  6077. /**
  6078. * @return {@code true} if current character is affected by channeling skill, {@code false} otherwise.
  6079. */
  6080. public final boolean isChannelized()
  6081. {
  6082. return (_channelized != null) && !_channelized.isChannelized();
  6083. }
  6084. public final SkillChannelized getSkillChannelized()
  6085. {
  6086. if (_channelized == null)
  6087. {
  6088. _channelized = new SkillChannelized();
  6089. }
  6090. return _channelized;
  6091. }
  6092. public void addInvulAgainst(SkillHolder holder)
  6093. {
  6094. final InvulSkillHolder invulHolder = getInvulAgainstSkills().get(holder.getSkillId());
  6095. if (invulHolder != null)
  6096. {
  6097. invulHolder.increaseInstances();
  6098. return;
  6099. }
  6100. getInvulAgainstSkills().put(holder.getSkillId(), new InvulSkillHolder(holder));
  6101. }
  6102. public void removeInvulAgainst(SkillHolder holder)
  6103. {
  6104. final InvulSkillHolder invulHolder = getInvulAgainstSkills().get(holder.getSkillId());
  6105. if ((invulHolder != null) && (invulHolder.decreaseInstances() < 1))
  6106. {
  6107. getInvulAgainstSkills().remove(holder.getSkillId());
  6108. }
  6109. }
  6110. public boolean isInvulAgainst(int skillId, int skillLvl)
  6111. {
  6112. if (_invulAgainst != null)
  6113. {
  6114. final SkillHolder holder = getInvulAgainstSkills().get(skillId);
  6115. return ((holder != null) && ((holder.getSkillLvl() < 1) || (holder.getSkillLvl() == skillLvl)));
  6116. }
  6117. return false;
  6118. }
  6119. private Map<Integer, InvulSkillHolder> getInvulAgainstSkills()
  6120. {
  6121. if (_invulAgainst == null)
  6122. {
  6123. synchronized (this)
  6124. {
  6125. if (_invulAgainst == null)
  6126. {
  6127. _invulAgainst = new ConcurrentHashMap<>();
  6128. }
  6129. }
  6130. }
  6131. return _invulAgainst;
  6132. }
  6133. @Override
  6134. public Queue<AbstractEventListener> getListeners(EventType type)
  6135. {
  6136. final Queue<AbstractEventListener> objectListenres = super.getListeners(type);
  6137. final Queue<AbstractEventListener> templateListeners = getTemplate().getListeners(type);
  6138. final Queue<AbstractEventListener> globalListeners = isNpc() && !isMonster() ? Containers.Npcs().getListeners(type) : isMonster() ? Containers.Monsters().getListeners(type) : isPlayer() ? Containers.Players().getListeners(type) : EmptyQueue.emptyQueue();
  6139. // Attempt to do not create collection
  6140. if (objectListenres.isEmpty() && templateListeners.isEmpty() && globalListeners.isEmpty())
  6141. {
  6142. return EmptyQueue.emptyQueue();
  6143. }
  6144. else if (!objectListenres.isEmpty() && templateListeners.isEmpty() && globalListeners.isEmpty())
  6145. {
  6146. return objectListenres;
  6147. }
  6148. else if (!templateListeners.isEmpty() && objectListenres.isEmpty() && globalListeners.isEmpty())
  6149. {
  6150. return templateListeners;
  6151. }
  6152. else if (!globalListeners.isEmpty() && objectListenres.isEmpty() && templateListeners.isEmpty())
  6153. {
  6154. return globalListeners;
  6155. }
  6156. final Queue<AbstractEventListener> both = new LinkedBlockingDeque<>(objectListenres.size() + templateListeners.size() + globalListeners.size());
  6157. both.addAll(objectListenres);
  6158. both.addAll(templateListeners);
  6159. both.addAll(globalListeners);
  6160. return both;
  6161. }
  6162. public Race getRace()
  6163. {
  6164. return getTemplate().getRace();
  6165. }
  6166. }