battle_ui.lua 339 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525
  1. if UiContainer == nil then UiContainer = {} end
  2. --- Animation settings used in battle.
  3. --
  4. -- Battle models have animations named XX_NN (XX are the first two letters of the model name, NN a
  5. -- two digit number). A model also has numbered animation scripts (generated in
  6. -- game/battle/scripts/) that chain animations, mark the moment an attack hits and so on. Attacks,
  7. -- hurt reactions and deaths play one of those scripts.
  8. --
  9. -- Enemies attacks use the script number set in the enemy data. The scripts for the other
  10. -- reactions are set here. Player models share the layout of their scripts, and can be overridden
  11. -- by model name (like "rt_cloud") in `models`. Use the animation viewer in battle (keys V, N and
  12. -- B) to see what each animation looks like.
  13. BattleAnimations = {
  14. enemy = {hurt_script = 1},
  15. -- Script 12 is the victory pose, 5 and 6 are hurt reactions, 7 is the fall to the floor (animation
  16. -- 18, the root height goes from 673 to 58), 13 and 14 are the run away.
  17. player = {attack_script = 20, hurt_script = 5, death_script = 7, victory_script = 12, escape_script = 13,
  18. -- Script 29 (17 and 30 are the same): ready the weapon, incantation and release.
  19. magic_script = 29,
  20. -- Script 44 (45 is the same): ready, hit mark and the throwing animation 21, shared by all the party.
  21. throw_script = 44,
  22. -- Script 32 (33 is the same with animation 10 instead of 9): the pose of the commands that don't hit
  23. -- (Manipulate). The hit lands when it ends.
  24. manip_script = 32,
  25. -- Script 30 is the same as 29 with the pink aura of the enemy skills.
  26. eskill_script = 30},
  27. models = {},
  28. }
  29. --- Music of the battles, by the names of the music index.
  30. --
  31. -- `battle` is the music of normal battles and `victory` the fanfare played once when a battle is won.
  32. -- The music of the battles of a field can be changed by its scripts, with the BMUSC opcode.
  33. -- Setting `next` makes the next battle use that track only.
  34. BattleMusic = {
  35. battle = "bat",
  36. boss = "chu",
  37. victory = "fanfare",
  38. next = nil,
  39. }
  40. --- Status effects.
  41. --
  42. -- Status IDs are the bit positions of the original game, as stored in the attack and enemy data.
  43. BattleStatus = {
  44. DEATH = 0, NEAR_DEATH = 1, SLEEP = 2, POISON = 3, SADNESS = 4, FURY = 5, CONFUSION = 6,
  45. SILENCE = 7, HASTE = 8, SLOW = 9, STOP = 10, FROG = 11, SMALL = 12, SLOW_NUMB = 13,
  46. PETRIFY = 14, REGEN = 15, BARRIER = 16, M_BARRIER = 17, REFLECT = 18, DUAL = 19, SHIELD = 20,
  47. D_SENTENCE = 21, MANIPULATE = 22, BERSERK = 23, PEERLESS = 24, PARALYSIS = 25, DARKNESS = 26,
  48. }
  49. BattleStatus.NAME = {
  50. [0] = "Death", "Near-death", "Sleep", "Poison", "Sadness", "Fury", "Confusion", "Silence",
  51. "Haste", "Slow", "Stop", "Frog", "Small", "Slow-numb", "Petrify", "Regen", "Barrier",
  52. "M.Barrier", "Reflect", "Dual", "Shield", "D.Sentence", "Manipulate", "Berserk", "Peerless",
  53. "Paralysis", "Darkness",
  54. }
  55. --- Time units each timed status lasts (the table of ff7.exe at 0x7ad3e0). The other statuses last until they
  56. -- are cured, the character is KO'd or the battle ends. How long a unit is depends on the battle speed and on
  57. -- haste and slow, see {@see get_status_speed}.
  58. BattleStatus.UNITS = {
  59. [BattleStatus.STOP] = 30, [BattleStatus.PARALYSIS] = 20, [BattleStatus.D_SENTENCE] = 60,
  60. [BattleStatus.SLOW_NUMB] = 30, [BattleStatus.BARRIER] = 127, [BattleStatus.M_BARRIER] = 127,
  61. [BattleStatus.SLEEP] = 100, [BattleStatus.REGEN] = 127, [BattleStatus.SHIELD] = 64, [BattleStatus.PEERLESS] = 64,
  62. }
  63. --- Statuses that stop the ATB, so the combatant can't act.
  64. BattleStatus.FROZEN = {
  65. [BattleStatus.SLEEP] = true, [BattleStatus.STOP] = true, [BattleStatus.PETRIFY] = true,
  66. [BattleStatus.PARALYSIS] = true,
  67. }
  68. --- Statuses that each status removes when it is inflicted (ff7.exe: the pair of the table at 0x7ad628 for Haste
  69. -- and Slow, and the gain of Petrify at 0x433fe0). Fury and Sadness are handled with their items.
  70. BattleStatus.REMOVES = {
  71. [BattleStatus.HASTE] = {BattleStatus.SLOW}, [BattleStatus.SLOW] = {BattleStatus.HASTE},
  72. [BattleStatus.PETRIFY] = {BattleStatus.SLEEP, BattleStatus.POISON, BattleStatus.CONFUSION, BattleStatus.REGEN},
  73. }
  74. --- Seconds between the damage or healing of poison and regen.
  75. BattleStatus.TICK = 3
  76. --- Fraction of the maximum HP lost by poison and recovered by regen on each tick.
  77. BattleStatus.POISON_FRACTION = 1 / 32
  78. BattleStatus.REGEN_FRACTION = 1 / 16
  79. --- Playback speed of battle animations.
  80. --
  81. -- Animations are converted at 30 frames per second, but battle animations were designed to be
  82. -- slower. 1 is the converted speed, 0.5 is half of it. It can be changed during a battle with
  83. -- the keys Z (slower) and X (faster).
  84. BattleAnimations.SPEED = 0.4
  85. --- Seconds an action lasts when the animation to play is unknown.
  86. BattleAnimations.DEFAULT_ACTION_TIME = 0.6
  87. --- Distance, in battle units, party members run when escaping from a battle.
  88. BattleAnimations.ESCAPE_DISTANCE = 40
  89. --- Seconds an enemy takes to disappear after dying.
  90. BattleAnimations.ENEMY_DEATH_TIME = 0.5
  91. --- Shortest time, in seconds, a single frame animation is shown.
  92. BattleAnimations.MIN_FRAME_TIME = 0.1
  93. --- Speed, in battle units per second, at which combatants run to their targets and back.
  94. BattleAnimations.RUN_SPEED = 12
  95. --- Distances in the scripts are in original game units. This is the divisor to turn them into
  96. -- battle units (the same one the installer uses for model coordinates).
  97. BattleAnimations.DISTANCE_DIVISOR = 255
  98. --- Cache of the animation scripts read from the files, by model name.
  99. BattleAnimations.script_cache = {}
  100. --- Reads the animation scripts of a model.
  101. --
  102. -- The generated files can't be run (some have jumps to missing labels), so they are read as text.
  103. -- @param model Model name, without extension (like "aq_mp").
  104. -- @return A table indexed by script number, each a list of steps: {type = "anim", number = N} for
  105. -- animations to play, {type = "hit"} where the attack lands. Empty if the file can't be read.
  106. BattleAnimations.get_scripts = function(model)
  107. if BattleAnimations.script_cache[model] ~= nil then return BattleAnimations.script_cache[model] end
  108. local scripts = {}
  109. local file = io.open("./game/battle/scripts/" .. model .. ".lua", "r")
  110. if file == nil then
  111. print("No animation scripts found for model " .. model)
  112. else
  113. local text = file:read("*a")
  114. file:close()
  115. for number, body in text:gmatch("%.script(%d+) = function%(%)(.-)\nend") do
  116. local steps = {}
  117. for fn, args in body:gmatch("([%w_]+)%(([^)]*)%)") do
  118. if fn == "play_animation" and tonumber(args) ~= nil then
  119. table.insert(steps, {type = "anim", number = tonumber(args)})
  120. elseif fn == "execute_attack" then
  121. table.insert(steps, {type = "hit"})
  122. elseif fn == "move_to_target" then
  123. -- Arguments: distance to stop from the target, unknown, unknown.
  124. table.insert(steps, {type = "move", distance = tonumber(args:match("^%s*(-?%d+)")) or 0})
  125. elseif fn == "return_position" then
  126. table.insert(steps, {type = "return"})
  127. elseif (fn == "set_camera" or fn == "set_formation_camera") and tonumber(args) ~= nil
  128. -- Some models have scripts that are not real ones (they don't end).
  129. and body:find("return 0", 1, true) then
  130. table.insert(steps, {type = fn == "set_camera" and "camera" or "view", number = tonumber(args)})
  131. end
  132. -- TODO: set_direction, effects, sounds...
  133. end
  134. scripts[tonumber(number)] = steps
  135. end
  136. end
  137. BattleAnimations.script_cache[model] = scripts
  138. return scripts
  139. end
  140. --- The battle UI
  141. --
  142. -- Controls the battle UI and the battle flow
  143. -- TODO: Merge this code into Battle
  144. UiContainer.BattleUi = {
  145. --- Party members
  146. --
  147. --
  148. party = {},
  149. --- Enemies
  150. enemies = {},
  151. --- Battle action queue.
  152. --
  153. -- Every battle action gets added to the end of this queue, and the actions are executed in
  154. -- order. ff7.exe does not sort the queue (its ring buffer at 0x99c420 is only appended to), so
  155. -- there are no priorities. The exception is the counterattacks of enemies, which go to the
  156. -- front: see {@see ai_action}. Actions for enemies and allies are stored here.
  157. action_queue = {},
  158. --- Indexes in {@see enemies} of the living enemies shown in the target window.
  159. --
  160. -- Dead enemies can't be targeted. Refreshed every time the target window opens.
  161. target_enemies = {},
  162. --- Refreshes the list of enemies that can be targeted.
  163. refresh_target_enemies = function(self)
  164. self.target_enemies = {}
  165. for i = 1, #self.enemies do
  166. if self.enemies[i].dead == false then table.insert(self.target_enemies, i) end
  167. end
  168. end,
  169. --- Result pages shown after a victory (EXP, gil, items), as strings.
  170. result_pages = {},
  171. --- Index of the result page being shown.
  172. result_page = 0,
  173. --- Battle to start after the results, if any.
  174. pending_next_battle = -1,
  175. --- Animation scripts being played, by combatant.
  176. animation_queues = {},
  177. --- The action being executed. Nil if none.
  178. current_action = nil,
  179. --- Entities to hide when their death animation ends: {entity name, side, index, time}.
  180. pending_hides = {},
  181. --- Animation viewer: combatant and animation being shown.
  182. viewer = {combatant = 1, animation = 0},
  183. --- Attack data already read, by attack ID.
  184. attack_cache = {},
  185. --- Rows of the list window, see {@see build_list_rows}: {entries = {...}, tag = text}.
  186. list_entries = {},
  187. --- Item, spell or summon selected to be used.
  188. selected_item = nil,
  189. selected_summon = nil,
  190. selected_links = nil,
  191. selected_limit = nil,
  192. selected_throw = nil,
  193. selected_coin = nil,
  194. --- Data of the basic physical attack ("Attack" command).
  195. --
  196. -- Party members use {@see get_weapon_attack} instead.
  197. basic_attack = {
  198. id = -1, name = "Attack", mp = 0,
  199. damage = {formula = 1, modifier = 1, power = 16, accuracy = 1},
  200. target = {}, effects = {}, elements = {}, animation = {},
  201. },
  202. --- Determines if an action is being executed.
  203. action_executing = false,
  204. --- Last time (game time) L1 and R1 were pressed, to detect that both are being held.
  205. escape_seen = {},
  206. --- Party members that have turned their back to the enemies while trying to escape, by
  207. -- party index: {rotation = original rotation, animation = run animation, next_time = ...}.
  208. escape_pose = {},
  209. --- Time (in seconds) L1 and R1 have been held together.
  210. escape_progress = 0,
  211. --- Game time of the last tick, to calculate the time delta.
  212. last_tick_time = 0,
  213. --- Party ATBs are not filling (back attacks).
  214. party_hold = false,
  215. --- Enemy ATBs are not filling (preemptive attacks).
  216. enemy_hold = false,
  217. --- Game time at which the ATB hold started.
  218. hold_start = 0,
  219. --- Seconds before a held ATB starts to fill again if nobody has acted.
  220. HOLD_TIME = 15,
  221. --- Party command selection queue.
  222. --
  223. -- When a party member ATB is filled, the character is added to this queue. Command selection
  224. -- windows are show in this order. If a character is dismissed (triangle in PSX), the character
  225. -- gets moved to the end of the queue.
  226. command_queue = {},
  227. --- Run when the menu is creaded.
  228. --
  229. -- It does nothing.
  230. on_start = function(self)
  231. return 0
  232. end,
  233. --- Indicates what the current cursor is for.
  234. --
  235. -- Possible values are "wait" (no cursor), "command" (for command selection), "list" (for
  236. -- magic, item, summon... selection), and "target" for target selection.
  237. window_state = "wait", -- wait, command, list, target
  238. --- Current position for the cursor in the command window.
  239. cursor_command = 1,
  240. --- Last command chosen by each party member (position in the command window), by party slot.
  241. -- Used when the cursor memory is on.
  242. memory_command = {},
  243. --- Last position chosen by each party member in the lists (magic, summon, item), by party slot
  244. -- and list kind: {first = first visible entry, cursor = row of the cursor}.
  245. memory_list = {},
  246. --- Current position for the cursor in the list window.
  247. cursor_list = 1,
  248. --- Column of the cursor in the magic list, which has several spells in each row.
  249. cursor_col = 1,
  250. --- First visible item in the list window
  251. first_list = 1,
  252. --- Current horizontal position for the cursor in the target window.
  253. cursor_target_h = 1,
  254. --- Current vertical position for the cursor in the target window.
  255. cursor_target_v = 1,
  256. --- First visible enemy in the target window
  257. first_target = 1,
  258. --- ID of the character the cursor is for.
  259. current_character_window = -1,
  260. --- Indicates the currently opened menu
  261. --
  262. -- Possible values are none, magic, wmagic1, wmagic2, summon, wsummon1, wsummon2, item, witem1,
  263. -- witem2, eskill, throw, limit, coin.
  264. current_list = "none",
  265. --- Target options of the currently selected attack
  266. target_options = {},
  267. --- Target mode.
  268. target_type = Battle.TargetType.SINGLE,
  269. --- The targeted group.
  270. target_group = Battle.TargetGroup.ENEMIES,
  271. --- The targeted unit index in the targeted group.
  272. target_index = 1,
  273. --- Handles button events.
  274. --
  275. -- For the current submenu, handles directional keys, enter and escape events.
  276. -- @param button Game event (the directions, OK, cancel...) or, for the debug keys, the name of
  277. -- the key.
  278. -- @param event Trigger event. Normally, "Press".
  279. on_button = function(self, button, event)
  280. if self.active == false then do return 0 end end
  281. if self.window_state == "gameover" then do return 0 end end
  282. if self.window_state == "result" then
  283. if button == Config.ACTIONS.CONFIRM then
  284. audio_manager:play_sound("Cursor")
  285. self:show_next_result()
  286. end
  287. return 0
  288. end
  289. if button == "K" then Battle.finish() end
  290. if button == "V" or button == "N" or button == "B" then self:viewer_input(button) end
  291. if button == "Z" or button == "X" then self:change_animation_speed(button) end
  292. if button == "F" then self:viewer_rotate() end
  293. if button == "C" then
  294. -- Debug: cycle the cameras of the formation.
  295. local count = battle_manager:set_camera(0)
  296. if count > 0 then
  297. self.camera_index = ((self.camera_index or 0) + 1) % count
  298. battle_manager:set_camera(self.camera_index)
  299. self:show_message("Camera " .. tostring(self.camera_index + 1) .. "/" .. tostring(count))
  300. end
  301. end
  302. -- Escape: L1 and R1 must be held together. Release events are not received, so
  303. -- the key repeat events are used to know if they are still held.
  304. if button == Config.ACTIONS.L1 or button == Config.ACTIONS.R1 then
  305. self.escape_seen[button] = timer:get_game_time_total()
  306. end
  307. -- Handle command cursors
  308. if self.window_state == "command" then
  309. local command_count = #self:get_command_list(self.current_character_window)
  310. local cursor = ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cursor")
  311. if button == Config.CONTROLS.DOWN then
  312. if self.cursor_command < 4 then
  313. -- If on the first three ones, always alow to go down to reach "Item"
  314. self.cursor_command = self.cursor_command + 1
  315. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  316. audio_manager:play_sound("Cursor")
  317. elseif self.cursor_command % 4 == 0 then
  318. -- If on a multiple of 4, go to the top of the column
  319. self.cursor_command = self.cursor_command - 3
  320. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  321. audio_manager:play_sound("Cursor")
  322. elseif command_count > self.cursor_command then
  323. -- If there is a command below, allow one position down.
  324. self.cursor_command = self.cursor_command + 1
  325. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  326. audio_manager:play_sound("Cursor")
  327. else
  328. -- Back to the first row
  329. self.cursor_command = 4 * math.floor(self.cursor_command / 4) + 1
  330. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  331. audio_manager:play_sound("Cursor")
  332. end
  333. elseif button == Config.CONTROLS.UP then
  334. if self.cursor_command == 1 then
  335. -- If on "Attack, always go to item
  336. self.cursor_command = 4
  337. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  338. audio_manager:play_sound("Cursor")
  339. elseif self.cursor_command > 1 and self.cursor_command < 5 then
  340. -- If on the second, third, or fourth, always alwow to go down to
  341. -- reach "Attack" from "Item"
  342. self.cursor_command = self.cursor_command - 1
  343. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  344. audio_manager:play_sound("Cursor")
  345. elseif self.cursor_command % 4 == 1 and command_count > self.cursor_command then
  346. -- If on the first row, go to the last where there is a command
  347. self.cursor_command = self.cursor_command + 3
  348. while self.cursor_command > command_count do self.cursor_command = self.cursor_command - 1 end
  349. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  350. audio_manager:play_sound("Cursor")
  351. else
  352. -- Else, always allow to go one up.
  353. self.cursor_command = self.cursor_command - 1
  354. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  355. audio_manager:play_sound("Cursor")
  356. end
  357. elseif button == Config.CONTROLS.LEFT then
  358. if self.cursor_command > 4 then
  359. self.cursor_command = self.cursor_command - 4
  360. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  361. audio_manager:play_sound("Cursor")
  362. else
  363. -- Left of the first column is the Change window.
  364. self:open_side_window("change")
  365. end
  366. elseif button == Config.CONTROLS.RIGHT then
  367. if self.cursor_command + 4 <= command_count then
  368. self.cursor_command = self.cursor_command + 4
  369. cursor:set_default_animation("Position" .. tostring(self.cursor_command))
  370. audio_manager:play_sound("Cursor")
  371. else
  372. -- Right of the last column is the Defend window.
  373. self:open_side_window("defend")
  374. end
  375. elseif button == Config.ACTIONS.CANCEL then
  376. -- Push the current character to the end of the command queue, and show the first.
  377. local new_queue = {}
  378. for i = 1, #self.command_queue do
  379. if self.command_queue[i + 1] ~= nil then table.insert(new_queue, self.command_queue[i + 1]) end
  380. end
  381. table.insert(new_queue, self.command_queue[1])
  382. self.command_queue = new_queue
  383. audio_manager:play_sound("Cursor")
  384. self:show_commands(self.command_queue[1])
  385. elseif button == Config.ACTIONS.CONFIRM and self.party[self.current_character_window].manip_commands ~= nil
  386. and self:has_status(Battle.TargetGroup.PARTY, self.current_character_window, BattleStatus.FROG) then
  387. audio_manager:play_sound("Error")
  388. elseif button == Config.ACTIONS.CONFIRM and self.party[self.current_character_window].manip_commands ~= nil then
  389. -- The commands are the attacks of the manipulated enemy.
  390. self:select_manip_attack(self.cursor_command)
  391. elseif button == Config.ACTIONS.CONFIRM then
  392. self.memory_command[self.current_character_window] = self.cursor_command
  393. -- Check if a menu must be shown
  394. local cmd = Game.Commands[self.party[self.current_character_window].command[self.cursor_command]]
  395. if cmd == nil then
  396. print("DEBUG: no command at the cursor " .. tostring(self.cursor_command) .. " of " .. tostring(self.current_character_window))
  397. return 0
  398. end
  399. local command_id = self.party[self.current_character_window].command[self.cursor_command]
  400. if self:is_frog_blocked(self.current_character_window, command_id) then
  401. audio_manager:play_sound("Error")
  402. return 0
  403. end
  404. if command_id == self.MANIP_COMMAND and self.party[self.current_character_window].manipulating ~= nil then
  405. -- Nobody can manipulate an enemy while manipulating another one.
  406. audio_manager:play_sound("Error")
  407. return 0
  408. end
  409. if cmd.menu == Battle.Menu.NONE and not self.ENEMY_COMMANDS[command_id] then
  410. if not self:queue_direct_command(self.party[self.current_character_window].command[self.cursor_command]) then
  411. print("DIRECT COMMAND")
  412. end
  413. elseif cmd.menu == Battle.Menu.COIN then
  414. self:open_coin_window()
  415. elseif cmd.menu == Battle.Menu.TARGET or self.ENEMY_COMMANDS[command_id] then
  416. audio_manager:play_sound("Cursor")
  417. self:select_command_target(self.party[self.current_character_window].command[self.cursor_command])
  418. elseif self.SILENCED_COMMANDS[command_id] and self:has_status(Battle.TargetGroup.PARTY, self.current_character_window, BattleStatus.SILENCE) then
  419. -- Silenced characters can't cast, summon nor use enemy skills.
  420. audio_manager:play_sound("Error")
  421. else
  422. self.selected_command = self.party[self.current_character_window].command[self.cursor_command]
  423. self.w_first = nil
  424. self:show_list(cmd.menu)
  425. end
  426. end
  427. -- Coin: the amount of gil is chosen with the directions.
  428. elseif self.window_state == "coin" then
  429. self:handle_coin_button(button)
  430. -- Change (on the left of the commands) and Defend (on the right) have a window with one option.
  431. elseif self.window_state == "change" or self.window_state == "defend" then
  432. local kind = self.window_state
  433. if button == Config.ACTIONS.CANCEL or (kind == "change" and button == Config.CONTROLS.RIGHT)
  434. or (kind == "defend" and button == Config.CONTROLS.LEFT) then
  435. audio_manager:play_sound("Cursor")
  436. self:close_side_window()
  437. elseif button == Config.ACTIONS.CONFIRM then
  438. audio_manager:play_sound("Cursor")
  439. self:queue_side_command(kind == "change" and 18 or 19)
  440. end
  441. -- Handle menu list cursor
  442. elseif self.window_state == "list" then
  443. local total = #self.list_entries
  444. local cursor = ui_manager:get_widget("BattleUi.Container.Bottom.List.Cursor")
  445. if button == Config.ACTIONS.CANCEL then
  446. audio_manager:play_sound("Cursor")
  447. self:close_list()
  448. elseif button == Config.CONTROLS.DOWN then
  449. if total <= self.cursor_list + self.first_list - 1 then do return 0 end end
  450. if self.cursor_list < 4 then
  451. -- Move cursor down
  452. audio_manager:play_sound("Cursor")
  453. self.cursor_list = self.cursor_list + 1
  454. else
  455. -- Scroll down
  456. audio_manager:play_sound("Cursor")
  457. self.first_list = self.first_list + 1
  458. self:repopulate_list()
  459. end
  460. self:update_list_cursor()
  461. elseif button == Config.CONTROLS.UP then
  462. if self.cursor_list == 1 and self.first_list == 1 then do return 0 end end
  463. if self.cursor_list > 1 then
  464. -- Move cursor up
  465. audio_manager:play_sound("Cursor")
  466. self.cursor_list = self.cursor_list - 1
  467. else
  468. -- Scroll up
  469. audio_manager:play_sound("Cursor")
  470. self.first_list = self.first_list - 1
  471. self:repopulate_list()
  472. end
  473. self:update_list_cursor()
  474. elseif button == Config.CONTROLS.LEFT or button == Config.CONTROLS.RIGHT then
  475. -- The rows of the magic list have several spells.
  476. local row = self.list_entries[self.cursor_list + self.first_list - 1]
  477. local column = self.cursor_col + (button == Config.CONTROLS.LEFT and -1 or 1)
  478. if row ~= nil and column >= 1 and column <= #row.entries then
  479. audio_manager:play_sound("Cursor")
  480. self.cursor_col = column
  481. self:update_list_cursor()
  482. end
  483. elseif button == Config.ACTIONS.CONFIRM then
  484. audio_manager:play_sound("Cursor")
  485. self:select_target()
  486. end
  487. elseif self.window_state == "target" then
  488. if button == Config.ACTIONS.CANCEL then
  489. audio_manager:play_sound("Cursor")
  490. self:close_target()
  491. elseif button == Config.CONTROLS.UP then
  492. if self.cursor_target_h == 2 then
  493. -- Allies cursor, never scroll. Go un up or to the bottom
  494. self.cursor_target_v = self.cursor_target_v - 1
  495. if self.cursor_target_v == 0 then self.cursor_target_v = #self.party end
  496. audio_manager:play_sound("Cursor")
  497. self:populate_target_list()
  498. else
  499. -- Cursor on the left. Can be enemies or allies, depends on the options.
  500. if self.target_options.fixed_row == 1 and self.target_options.default_enemy == 0 then
  501. -- Allies
  502. self.cursor_target_v = self.cursor_target_v - 1
  503. if self.cursor_target_v == 0 then self.cursor_target_v = #self.party end
  504. audio_manager:play_sound("Cursor")
  505. self:populate_target_list()
  506. else
  507. -- Enemies
  508. if #self.target_enemies > 4 then
  509. if self.cursor_target_v == 1 then
  510. if self.first_target == 1 then
  511. -- Scroll to the bottom, set cursor in last
  512. self.first_target = #self.target_enemies - 4
  513. self.cursor_target_v = 4
  514. audio_manager:play_sound("Cursor")
  515. self:populate_target_list()
  516. else
  517. self.first_target = self.first_target - 1
  518. audio_manager:play_sound("Cursor")
  519. self:populate_target_list()
  520. end
  521. else
  522. self.cursor_target_v = self.cursor_target_v - 1
  523. audio_manager:play_sound("Cursor")
  524. self:populate_target_list()
  525. end
  526. else
  527. self.cursor_target_v = self.cursor_target_v - 1
  528. if self.cursor_target_v == 0 then self.cursor_target_v = #self.target_enemies end
  529. audio_manager:play_sound("Cursor")
  530. self:populate_target_list()
  531. end
  532. end
  533. end
  534. elseif button == Config.CONTROLS.DOWN then
  535. if self.cursor_target_h == 2 then
  536. -- Allies cursor, never scroll. Go un up or to the bottom
  537. self.cursor_target_v = self.cursor_target_v + 1
  538. if self.cursor_target_v > #self.party then self.cursor_target_v = 1 end
  539. audio_manager:play_sound("Cursor")
  540. self:populate_target_list()
  541. else
  542. -- Cursor on the left. Can be enemies or allies, depends on the options.
  543. if self.target_options.fixed_row == 1 and self.target_options.default_enemy == 0 then
  544. -- Allies
  545. self.cursor_target_v = self.cursor_target_v + 1
  546. if self.cursor_target_v > #self.party then self.cursor_target_v = 1 end
  547. audio_manager:play_sound("Cursor")
  548. self:populate_target_list()
  549. else
  550. -- Enemies
  551. if #self.target_enemies > 4 then
  552. if self.cursor_target_v == 4 then
  553. if self.first_target + 4 == #self.target_enemies then
  554. -- Scroll to the top, set cursor in first
  555. self.first_target = 1
  556. self.cursor_target_v = 1
  557. audio_manager:play_sound("Cursor")
  558. self:populate_target_list()
  559. else
  560. self.first_target = self.first_target + 1
  561. audio_manager:play_sound("Cursor")
  562. self:populate_target_list()
  563. end
  564. else
  565. self.cursor_target_v = self.cursor_target_v + 1
  566. audio_manager:play_sound("Cursor")
  567. self:populate_target_list()
  568. end
  569. else
  570. self.cursor_target_v = self.cursor_target_v + 1
  571. if self.cursor_target_v > #self.target_enemies then self.cursor_target_v = 1 end
  572. audio_manager:play_sound("Cursor")
  573. self:populate_target_list()
  574. end
  575. end
  576. end
  577. elseif button == Config.CONTROLS.LEFT then
  578. if self.target_options.fixed_row == 0 and self.target_options.toggle_multiple == 0 then
  579. -- If both rows are present and multiple toggling is not available...
  580. if self.cursor_target_h == 2 then
  581. -- and the cursor is in the second column, go to the fisrt. Also, move the
  582. --cursor up until a valid enemy is pointed.
  583. self.cursor_target_h = 1
  584. while self.cursor_target_v + self.first_target - 1 > #self.target_enemies do self.cursor_target_v = self.cursor_target_v - 1 end
  585. audio_manager:play_sound("Cursor")
  586. self:populate_target_list()
  587. end
  588. elseif self.target_options.fixed_row == 0 and self.target_options.toggle_multiple == 1 then
  589. -- If both rows are present, and multiple targets can be toggled...
  590. if self.cursor_target_h == 2 and self.target_type == Battle.TargetType.GROUP then
  591. -- ... and the cursor is on the rigth, with multiple targets, set to single
  592. -- target
  593. self.target_type = Battle.TargetType.SINGLE
  594. audio_manager:play_sound("Cursor")
  595. self:populate_target_list()
  596. elseif self.cursor_target_h == 2 and self.target_type == Battle.TargetType.SINGLE then
  597. -- ... and the cursor is on the rigth, with single targets, go to the left
  598. -- target. Also, move the cursor up until a valid enemy is pointed.
  599. self.cursor_target_h = 1
  600. while self.cursor_target_v + self.first_target - 1 > #self.target_enemies do self.cursor_target_v = self.cursor_target_v - 1 end
  601. audio_manager:play_sound("Cursor")
  602. self:populate_target_list()
  603. elseif self.cursor_target_h == 1 and self.target_type == Battle.TargetType.SINGLE then
  604. -- ... and the cursor is on the left, with single targets, set to multiple
  605. -- targets
  606. self.target_type = Battle.TargetType.GROUP
  607. audio_manager:play_sound("Cursor")
  608. self:populate_target_list()
  609. end
  610. elseif self.target_options.fixed_row == 1 and self.target_options.toggle_multiple == 1 then
  611. -- If only one row is present and multiple can be toggled, toggle it
  612. local prev_mode = self.target_type
  613. if prev_mode == Battle.TargetType.GROUP then self.target_type = Battle.TargetType.SINGLE
  614. elseif prev_mode == Battle.TargetType.SINGLE then self.target_type = Battle.TargetType.GROUP
  615. end
  616. end
  617. elseif button == Config.CONTROLS.RIGHT then
  618. if self.target_options.fixed_row == 0 and self.target_options.toggle_multiple == 0 then
  619. -- If both rows are present and multiple toggling is not available...
  620. if self.cursor_target_h == 1 then
  621. -- and the cursor is in the left column, go to the right. Also, move the
  622. --cursor up until a valid party member is pointed.
  623. self.cursor_target_h = 2
  624. while self.cursor_target_v + self.first_target - 1 > #self.party do self.cursor_target_v = self.cursor_target_v - 1 end
  625. audio_manager:play_sound("Cursor")
  626. self:populate_target_list()
  627. end
  628. elseif self.target_options.fixed_row == 0 and self.target_options.toggle_multiple == 1 then
  629. -- If both rows are present, and multiple targets can be toggled...
  630. if self.cursor_target_h == 1 and self.target_type == Battle.TargetType.GROUP then
  631. -- ... and the cursor is on the left, on multiple target mode, set to
  632. -- single target mode.
  633. self.target_type = Battle.TargetType.SINGLE
  634. audio_manager:play_sound("Cursor")
  635. self:populate_target_list()
  636. elseif self.cursor_target_h == 1 and self.target_type == Battle.TargetType.SINGLE then
  637. -- ... and the cursor is on the left, on single target mode, go to the
  638. -- right. Also, move the cursor up until a valid party member is pointed.
  639. self.cursor_target_h = 2
  640. while self.cursor_target_v + self.first_target - 1 > #self.party do self.cursor_target_v = self.cursor_target_v - 1 end
  641. audio_manager:play_sound("Cursor")
  642. self:populate_target_list()
  643. elseif self.cursor_target_h == 2 and self.target_type == Battle.TargetType.SINGLE then
  644. -- ... and the cursor is on the right, on single target mode, set to
  645. -- multiple target mode.
  646. self.target_type = Battle.TargetType.GROUP
  647. audio_manager:play_sound("Cursor")
  648. self:populate_target_list()
  649. end
  650. elseif self.target_options.fixed_row == 1 and self.target_options.toggle_multiple == 1 then
  651. -- If only one row is present and multiple can be toggled, toggle it
  652. local prev_mode = self.target_type
  653. if prev_mode == Battle.TargetType.GROUP then self.target_type = Battle.TargetType.SINGLE
  654. elseif prev_mode == Battle.TargetType.SINGLE then self.target_type = Battle.TargetType.GROUP
  655. end
  656. end
  657. elseif button == Config.ACTIONS.CONFIRM then
  658. -- Determine target type and target index
  659. if self.target_options.fixed_row == 1 then
  660. if self.target_options.default_enemy == 1 then
  661. self.target_group = Battle.TargetGroup.ENEMIES
  662. if self.target_type == Battle.TargetType.SINGLE then self.target_index = self.target_enemies[self.cursor_target_v + self.first_target - 1]
  663. else self.target_index = nil
  664. end
  665. else
  666. self.target_group = Battle.TargetGroup.PARTY
  667. if self.target_type == Battle.TargetType.SINGLE then self.target_index = self.cursor_target_v
  668. else self.target_index = nil
  669. end
  670. end
  671. else
  672. if self.cursor_target_h == 1 then
  673. self.target_group = Battle.TargetGroup.ENEMIES
  674. if self.target_type == Battle.TargetType.SINGLE then self.target_index = self.target_enemies[self.cursor_target_v + self.first_target - 1]
  675. else self.target_index = nil
  676. end
  677. else
  678. self.target_group = Battle.TargetGroup.PARTY
  679. if self.target_type == Battle.TargetType.SINGLE then self.target_index = self.cursor_target_v
  680. else self.target_index = nil
  681. end
  682. end
  683. end
  684. -- Add the action to the queue.
  685. self:queue_character_action()
  686. end
  687. end
  688. return 0
  689. end,
  690. --- Repopulates a list
  691. --
  692. -- Repopulates the currently shown list with the current cursor and scroll positions.
  693. repopulate_list = function(self)
  694. self:populate_list()
  695. end,
  696. --- Distance a character moves to change the row, in world units (about the size of the character).
  697. -- TODO: Estimated, tune it here.
  698. ROW_STEP = 3.0,
  699. --- Seconds a row change lasts.
  700. ROW_MOVE_TIME = 0.4,
  701. --- Distance in front of the covered character where the one that covers stands, and seconds it takes
  702. -- to get there and back.
  703. COVER_DISTANCE = 2.5,
  704. COVER_MOVE_TIME = 0.25,
  705. --- Slides a party member to a position, replacing the slide it was doing.
  706. --
  707. -- @param index Index in the party.
  708. -- @param to Destination, {x, y, z}.
  709. -- @param duration Seconds it takes.
  710. slide_party = function(self, index, to, duration)
  711. local entity = self:get_entity(Battle.TargetGroup.PARTY, index)
  712. if entity == nil then return end
  713. for i = #self.row_moves, 1, -1 do
  714. if self.row_moves[i].index == index then table.remove(self.row_moves, i) end
  715. end
  716. local x, y, z = entity:get_position()
  717. local now = timer:get_game_time_total()
  718. table.insert(self.row_moves, {index = index, from = {x = x, y = y, z = z}, to = to, start = now, finish = now + duration})
  719. end,
  720. --- Slides a party member back to its place once its animations are over (the end of an animation puts
  721. -- the character where the animation started, which would undo the slide).
  722. --
  723. -- @param index Index in the party.
  724. -- @param home Place to go back to, {x, y, z}.
  725. return_to_place = function(self, index, home, since)
  726. local now = timer:get_game_time_total()
  727. since = since or now
  728. local key = tostring(Battle.TargetGroup.PARTY) .. "_" .. tostring(index)
  729. -- It doesn't wait more than two seconds.
  730. if self.animation_queues[key] ~= nil and now - since < 2 then
  731. table.insert(self.delayed_calls, {
  732. time = now + 0.05, call = function() self:return_to_place(index, home, since) end,
  733. })
  734. return
  735. end
  736. self:slide_party(index, home, self.COVER_MOVE_TIME)
  737. end,
  738. --- Animation of the defensive stance of the party. TODO: Unverified: check it in the animation viewer.
  739. DEFEND_ANIMATION = 3,
  740. --- Opens the window of the Change command (on the left of the commands) or of the Defend command
  741. -- (on the right).
  742. --
  743. -- @param kind "change" or "defend".
  744. open_side_window = function(self, kind)
  745. local name = kind == "change" and "Change" or "Defend"
  746. local window = ui_manager:get_widget("BattleUi.Container.Bottom." .. name)
  747. ui_manager:get_widget("BattleUi.Container.Bottom." .. name .. ".Text"):set_text(Game.Commands[kind == "change" and 18 or 19].name)
  748. -- Defend goes right after the commands.
  749. if kind == "defend" then window:set_x(22, self.commands_width or 120) end
  750. window:set_visible(true)
  751. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cursor"):set_visible(false)
  752. audio_manager:play_sound("Cursor")
  753. self.window_state = kind
  754. end,
  755. --- Closes the window of Change or Defend, and goes back to the commands.
  756. close_side_window = function(self)
  757. ui_manager:get_widget("BattleUi.Container.Bottom.Change"):set_visible(false)
  758. ui_manager:get_widget("BattleUi.Container.Bottom.Defend"):set_visible(false)
  759. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cursor"):set_visible(true)
  760. self.window_state = "command"
  761. end,
  762. --- Queues Change or Defend for the character that is choosing.
  763. --
  764. -- @param command_id 18 for Change, 19 for Defend.
  765. queue_side_command = function(self, command_id)
  766. if self:is_frog_blocked(self.current_character_window, command_id) then
  767. audio_manager:play_sound("Error")
  768. return
  769. end
  770. self.selected_command = command_id
  771. self.current_list = "none"
  772. self.selected_attack = nil
  773. self.selected_item = nil
  774. self.selected_summon = nil
  775. self.selected_limit = nil
  776. self.selected_throw = nil
  777. self.selected_coin = nil
  778. self.selected_links = nil
  779. self.target_type = Battle.TargetType.SINGLE
  780. self.target_group = Battle.TargetGroup.PARTY
  781. self.target_index = self.current_character_window
  782. self:queue_character_action()
  783. end,
  784. --- Gets the direction a party member faces to look at the enemies, as a unit vector in the ground.
  785. get_row_direction = function(self, x, y)
  786. local cx, cy, count = 0, 0, 0
  787. for e = 0, battle_manager:get_enemy_count() - 1 do
  788. local ex, ey = battle_manager:get_enemy(e):get_position()
  789. cx, cy, count = cx + ex, cy + ey, count + 1
  790. end
  791. if count > 0 then
  792. local dx, dy = cx / count - x, cy / count - y
  793. local length = math.sqrt(dx * dx + dy * dy)
  794. if length > 0.001 then return dx / length, dy / length end
  795. end
  796. -- The party is on the positive side of the ground, facing the negative one.
  797. return 0, y > 0 and -1 or 1
  798. end,
  799. --- Moves a party member forward or back, as the rows do.
  800. --
  801. -- @param index Index in the party.
  802. -- @param back True to move away from the enemies (back row), false to go towards them.
  803. -- @param instant True to move at once, otherwise it slides (see {@see update_row_moves}).
  804. -- @param on_done Function to call at the end of a slide, or nil.
  805. move_row = function(self, index, back, instant, on_done)
  806. local entity = self:get_entity(Battle.TargetGroup.PARTY, index)
  807. if entity == nil then
  808. if on_done ~= nil then on_done() end
  809. return
  810. end
  811. local x, y, z = entity:get_position()
  812. local dx, dy = self:get_row_direction(x, y)
  813. local sign = back and -1 or 1
  814. local to = {x = x + dx * self.ROW_STEP * sign, y = y + dy * self.ROW_STEP * sign, z = z}
  815. -- The new row is the place of the character.
  816. if self.party[index] ~= nil then self.party[index].home = {x = to.x, y = to.y, z = to.z} end
  817. if instant then
  818. entity:set_position(to.x, to.y, to.z)
  819. if on_done ~= nil then on_done() end
  820. else
  821. local now = timer:get_game_time_total()
  822. table.insert(self.row_moves, {
  823. index = index, from = {x = x, y = y, z = z}, to = to, start = now, finish = now + self.ROW_MOVE_TIME, on_done = on_done,
  824. })
  825. end
  826. end,
  827. --- Advances the slides of the row changes.
  828. update_row_moves = function(self, now)
  829. for i = #self.row_moves, 1, -1 do
  830. local move = self.row_moves[i]
  831. local entity = self:get_entity(Battle.TargetGroup.PARTY, move.index)
  832. local t = math.min(1, (now - move.start) / (move.finish - move.start))
  833. if entity ~= nil then
  834. entity:set_position(
  835. move.from.x + (move.to.x - move.from.x) * t, move.from.y + (move.to.y - move.from.y) * t,
  836. move.from.z + (move.to.z - move.from.z) * t
  837. )
  838. end
  839. if t >= 1 then
  840. table.remove(self.row_moves, i)
  841. if move.on_done ~= nil then move.on_done() end
  842. end
  843. end
  844. end,
  845. --- Slides that are in progress, see {@see update_row_moves}.
  846. row_moves = {},
  847. --- Checks if a combatant is in a defensive stance.
  848. is_defending = function(self, side, index)
  849. return side == Battle.TargetGroup.PARTY and self.party[index] ~= nil and self.party[index].defending == true
  850. end,
  851. --- Puts a party member in the defensive stance or takes it out of it.
  852. set_defending = function(self, index, defending)
  853. self.party[index].defending = defending
  854. local entity = self:get_entity(Battle.TargetGroup.PARTY, index)
  855. local name = self:get_animation_name(Battle.TargetGroup.PARTY, index, defending and self.DEFEND_ANIMATION or 0)
  856. if entity ~= nil and name ~= nil and entity:get_animation_count() > 0 then
  857. if defending then entity:play_animation_stop(name) else entity:play_animation(name) end
  858. end
  859. end,
  860. --- Goes back to the defensive stance after an animation that interrupted it (a hit).
  861. restore_stance = function(self, side, index)
  862. if self:is_defending(side, index) and not self.party[index].dead then self:set_defending(index, true) end
  863. end,
  864. --- Runs Change or Defend for the party member that chose it.
  865. --
  866. -- Change moves the character to the other row for good (it stays after the battle), and Defend puts it
  867. -- in a defensive stance until its ATB is full again: the physical damage it takes is halved.
  868. run_side_command = function(self, current, action)
  869. local index = action.actor
  870. local member = self.party[index]
  871. local char = Characters[member.character]
  872. self:show_message(Game.Commands[action.command].name)
  873. current.hit_done = true
  874. current.pending = 0
  875. if action.command == 18 then
  876. char.back_row = not (char.back_row == true)
  877. if member.defending then self:set_defending(index, false) end
  878. current.pending = 1
  879. self:move_row(index, char.back_row, false, function()
  880. current.pending = current.pending - 1
  881. end)
  882. else
  883. self:set_defending(index, true)
  884. end
  885. self:update_action(timer:get_game_time_total())
  886. end,
  887. --- Opens the target window for a command that goes straight to target selection.
  888. --
  889. -- Used by commands with {@see Battle.Menu.TARGET}, like "Attack".
  890. -- @param command_id ID of the command in Game.Commands.
  891. select_command_target = function(self, command_id)
  892. self.selected_command = command_id
  893. self.current_list = "none"
  894. self.selected_attack = nil
  895. self.selected_item = nil
  896. self.selected_summon = nil
  897. self.selected_limit = nil
  898. self.selected_throw = nil
  899. self.selected_coin = nil
  900. self.selected_links = nil
  901. self.target_options = {
  902. fixed_row = 0, default_enemy = 1, default_multiple = 0, toggle_multiple = 0,
  903. all_rows = 0, random = 0, selectable = 1
  904. }
  905. -- Mega All lets the attack hit all the enemies.
  906. if self:mega_all_left(self.party[self.current_character_window]) > 0 then self.target_options.toggle_multiple = 1 end
  907. self.target_type = Battle.TargetType.SINGLE
  908. self.cursor_target_h = 1
  909. self.cursor_target_v = 1
  910. self.first_target = 1
  911. self:refresh_target_enemies()
  912. self:populate_target_list()
  913. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(true)
  914. self.window_state = "target"
  915. end,
  916. --- Attack commands that are done: the number of attacks they make (the others make one), and the ones
  917. -- that aim each attack at a random enemy.
  918. COMMAND_STRIKES = {[25] = 2, [27] = 4},
  919. COMMAND_RANDOM = {[27] = true},
  920. --- Chance of the instant death of Flash on an enemy that is hit (and not immune to it).
  921. FLASH_CHANCE = 1,
  922. --- Queues a command that has no target window: Slash-All and Flash hit all the enemies, and 4x-Cut
  923. -- picks a random enemy for each hit.
  924. --
  925. -- @param command_id ID of the command in Game.Commands.
  926. -- @return True if the command is one of them and was queued.
  927. --- Gets the attacks of an enemy that a party member can use while it manipulates it.
  928. --
  929. -- Builds the commands of the window (virtual commands that have the names of the attacks), or removes them
  930. -- if the member is not manipulating an enemy.
  931. update_manip_commands = function(self, index)
  932. local member = self.party[index]
  933. member.manip_commands = nil
  934. self.manip_attack = nil
  935. local enemy = member.manipulating
  936. if enemy == nil then return end
  937. local source = battle_manager:get_enemy(enemy - 1)
  938. member.manip_commands = {}
  939. member.manip_attacks = {}
  940. for slot = 0, math.min(11, source:get_manip_count() - 1) do
  941. local id = source:get_manip_attack(slot)
  942. local data = self:get_attack_data(id)
  943. Game.Commands[1000 + slot] = {name = data ~= nil and data.name or "?", menu = Battle.Menu.NONE, camera = {single = 65535, multiple = 65535}}
  944. table.insert(member.manip_commands, 1000 + slot)
  945. table.insert(member.manip_attacks, id)
  946. end
  947. end,
  948. --- Picks an attack of the manipulated enemy and asks for its targets.
  949. select_manip_attack = function(self, cursor)
  950. local member = self.party[self.current_character_window]
  951. local id = member.manip_attacks[cursor]
  952. if id == nil then return end
  953. audio_manager:play_sound("Cursor")
  954. local data = self:get_attack_data(id)
  955. local target = data.target or {}
  956. self.manip_attack = id
  957. self.selected_command = nil
  958. self.current_list = "none"
  959. self.selected_attack = nil
  960. self.selected_item = nil
  961. self.selected_summon = nil
  962. self.selected_limit = nil
  963. self.selected_throw = nil
  964. self.selected_coin = nil
  965. self.selected_links = nil
  966. -- The attacks of an enemy that aim at "enemies" are aimed at the party, so the sides are the other way round.
  967. self.target_options = {
  968. selectable = 1, default_enemy = target.default_enemy == 1 and 0 or 1, default_multiple = target.default_multiple or 0,
  969. toggle_multiple = target.toggle_multiple or 0, fixed_row = target.fixed_row or 0, all_rows = target.all_rows or 0,
  970. random = target.random or 0, short_range = target.short_range or 0,
  971. }
  972. self.target_type = self.target_options.default_multiple == 1 and Battle.TargetType.GROUP or Battle.TargetType.SINGLE
  973. self.cursor_target_h = self.target_options.default_enemy == 1 and 1 or 2
  974. self.cursor_target_v = 1
  975. self.first_target = 1
  976. self:refresh_target_enemies()
  977. self:populate_target_list()
  978. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(true)
  979. self.window_state = "target"
  980. end,
  981. --- Queues the attack of the manipulated enemy chosen by its controller. It takes the turn of the controller.
  982. queue_manip_action = function(self)
  983. local controller = self.current_character_window
  984. local member = self.party[controller]
  985. local enemy = member.manipulating
  986. local id = self.manip_attack
  987. local script = nil
  988. local source = battle_manager:get_enemy(enemy - 1)
  989. for slot = 0, source:get_attack_count() - 1 do
  990. if source:get_attack(slot) == id then
  991. script = source:get_attack_animation(slot)
  992. break
  993. end
  994. end
  995. if script ~= nil and script < 0 then script = nil end
  996. table.insert(self.action_queue, {
  997. actor = enemy, actor_side = Battle.TargetGroup.ENEMIES, type = Battle.ActionType.COMMAND, command = 1,
  998. attack_id = id, script = script, controller = controller,
  999. target_type = self.target_type, target_group = self.target_group, target_index = self.target_index,
  1000. })
  1001. member.acting = true
  1002. member.manip_commands = nil
  1003. self.manip_attack = nil
  1004. for i = #self.command_queue, 1, -1 do
  1005. if self.command_queue[i] == controller then table.remove(self.command_queue, i) end
  1006. end
  1007. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  1008. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  1009. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  1010. ui_manager:get_widget("BattleUi.Container.Bottom.Change"):set_visible(false)
  1011. ui_manager:get_widget("BattleUi.Container.Bottom.Defend"):set_visible(false)
  1012. self.current_list = "none"
  1013. self.window_state = "wait"
  1014. end,
  1015. --- Builds the action that a Mime command does: a copy of the last action of the party, done by the member that mimes.
  1016. --
  1017. -- Limits can only be mimed by their owner. The copy uses no MP, summon or All counters; items, thrown things
  1018. -- and gil are paid again.
  1019. --
  1020. -- @return The action, or nil and the message of why it can't be done.
  1021. build_mime_action = function(self, action)
  1022. local last = self.last_party_action
  1023. if last == nil then return nil, "Nothing to mime" end
  1024. if last.limit ~= nil and last.actor ~= action.actor then return nil, "Can't mime that" end
  1025. local copy = {}
  1026. for key, value in pairs(last) do copy[key] = value end
  1027. copy.actor = action.actor
  1028. copy.actor_side = Battle.TargetGroup.PARTY
  1029. copy.mimed = true
  1030. copy.no_atb = nil
  1031. return copy
  1032. end,
  1033. --- Makes an enemy a puppet of a party member (Manipulate). It fails with a message if the enemy has no attacks
  1034. -- to be manipulated with, is immune, or the member is already controlling one.
  1035. manipulate = function(self, actor, target)
  1036. local member = self.party[actor]
  1037. local enemy = self.enemies[target]
  1038. local source = battle_manager:get_enemy(target - 1)
  1039. if member.manipulating ~= nil or enemy == nil or enemy.manipulated_by ~= nil or source:get_manip_count() == 0 then
  1040. self:show_message("Can't be manipulated")
  1041. return
  1042. end
  1043. self:apply_attack_effects({effects = {{id = BattleStatus.MANIPULATE, chance = 1, mode = "inflict"}}}, Battle.TargetGroup.ENEMIES, target)
  1044. if self:has_status(Battle.TargetGroup.ENEMIES, target, BattleStatus.MANIPULATE) then
  1045. member.manipulating = target
  1046. enemy.manipulated_by = actor
  1047. -- The puppet turns around while it is controlled.
  1048. local entity = self:get_entity(Battle.TargetGroup.ENEMIES, target)
  1049. if entity ~= nil then
  1050. enemy.manip_rotation = entity:get_rotation()
  1051. entity:set_rotation((enemy.manip_rotation + 180) % 360)
  1052. end
  1053. else
  1054. self:show_message("Can't be manipulated")
  1055. end
  1056. end,
  1057. --- Frees an enemy that was manipulated: its controller dies, it dies, or it takes physical damage.
  1058. release_manipulation = function(self, target)
  1059. local enemy = self.enemies[target]
  1060. if enemy == nil or enemy.manipulated_by == nil then return end
  1061. local controller = enemy.manipulated_by
  1062. enemy.manipulated_by = nil
  1063. local entity = self:get_entity(Battle.TargetGroup.ENEMIES, target)
  1064. if entity ~= nil and enemy.manip_rotation ~= nil then entity:set_rotation(enemy.manip_rotation) end
  1065. enemy.manip_rotation = nil
  1066. self.party[controller].manipulating = nil
  1067. self:clear_status(Battle.TargetGroup.ENEMIES, target, BattleStatus.MANIPULATE)
  1068. -- If its controller was choosing, it chooses its own commands again.
  1069. if self.party[controller].manip_commands ~= nil and not self.party[controller].acting then
  1070. self.manip_attack = nil
  1071. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  1072. if self.current_character_window == controller and (self.window_state == "command" or self.window_state == "target") then
  1073. self:show_commands(controller)
  1074. else
  1075. self.party[controller].manip_commands = nil
  1076. end
  1077. end
  1078. end,
  1079. --- Gets the commands a member shows: its own, or the attacks of the enemy it manipulates.
  1080. get_command_list = function(self, index)
  1081. local member = self.party[index]
  1082. return member.manip_commands or member.command
  1083. end,
  1084. queue_direct_command = function(self, command_id)
  1085. -- Mime copies the last action when its turn comes, so it has no choices.
  1086. if command_id == self.MIME_COMMAND then
  1087. audio_manager:play_sound("Cursor")
  1088. self.selected_command = command_id
  1089. self.current_list = "none"
  1090. self.selected_attack = nil
  1091. self.selected_item = nil
  1092. self.selected_summon = nil
  1093. self.selected_limit = nil
  1094. self.selected_throw = nil
  1095. self.selected_coin = nil
  1096. self.selected_links = nil
  1097. self.target_group = Battle.TargetGroup.ENEMIES
  1098. self.target_type = Battle.TargetType.GROUP
  1099. self.target_index = nil
  1100. self:queue_character_action()
  1101. return true
  1102. end
  1103. if command_id ~= 24 and command_id ~= 26 and command_id ~= 27 then return false end
  1104. local target = nil
  1105. local all = command_id == 24 or command_id == 26
  1106. if not all then
  1107. target = self:random_living(Battle.TargetGroup.ENEMIES)
  1108. if target == nil then return true end
  1109. end
  1110. audio_manager:play_sound("Cursor")
  1111. self.selected_command = command_id
  1112. self.current_list = "none"
  1113. self.selected_attack = nil
  1114. self.selected_item = nil
  1115. self.selected_summon = nil
  1116. self.selected_limit = nil
  1117. self.selected_throw = nil
  1118. self.selected_coin = nil
  1119. self.selected_links = nil
  1120. self.target_group = Battle.TargetGroup.ENEMIES
  1121. self.target_type = all and Battle.TargetType.GROUP or Battle.TargetType.SINGLE
  1122. self.target_index = target
  1123. self:queue_character_action()
  1124. return true
  1125. end,
  1126. --- Double commands, with the menu of each one.
  1127. W_COMMANDS = {[21] = Battle.Menu.W_MAGIC, [22] = Battle.Menu.W_SUMMON, [23] = Battle.Menu.W_ITEM},
  1128. --- Gets the name of what an action uses (the spell, summon or item).
  1129. get_w_name = function(self, action)
  1130. if action.item_id ~= nil then return Game.Items[action.item_id].name end
  1131. if action.attack_id ~= nil then return Game.Attacks[action.attack_id].name end
  1132. return ""
  1133. end,
  1134. --- Gets the MP that the first choice of a double command will use.
  1135. get_w_reserved_mp = function(self)
  1136. local first = self.w_first
  1137. if first == nil or first.attack_id == nil then return 0 end
  1138. return self:get_spell_cost(Game.Attacks[first.attack_id].mp, first.links)
  1139. end,
  1140. --- Adds a party character action to the queue
  1141. --
  1142. -- Closes the selection windows and removes the character from the command queue.
  1143. queue_character_action = function(self)
  1144. if self.manip_attack ~= nil then
  1145. self:queue_manip_action()
  1146. return
  1147. end
  1148. local action = {}
  1149. action.actor = self.current_character_window
  1150. action.actor_side = Battle.TargetGroup.PARTY
  1151. action.command = self.selected_command
  1152. if self.current_list == "none" then action.type = Battle.ActionType.COMMAND
  1153. else action.type = Battle.ActionType.ATTACK
  1154. end
  1155. -- Spells, summons and items carry the attack to use. The basic attack has none.
  1156. if self.current_list ~= "none" then
  1157. action.attack_id = self.selected_attack
  1158. action.item_id = self.selected_item
  1159. action.summon = self.selected_summon
  1160. action.limit = self.selected_limit
  1161. action.links = self.selected_links
  1162. action.throw_item = self.selected_throw
  1163. elseif self.selected_command == self.party[action.actor].command[1] then
  1164. -- The Attack command carries the links of its materia. A frog that lost a replacement of the command
  1165. -- loses its links too.
  1166. local member = self.party[action.actor]
  1167. if member.command[1] == member.attack_command or member.command[1] == 20 then action.links = member.attack_links end
  1168. end
  1169. if self.selected_command == self.COIN_COMMAND then action.coin_gil = self.selected_coin end
  1170. action.target_type = self.target_type
  1171. action.target_group = self.target_group
  1172. action.target_index = self.target_index
  1173. -- W-Magic, W-Summon and W-Item: the first choice waits, and the list opens again for the second one. Both
  1174. -- are queued together, the first without resetting the ATB (that happens after the second).
  1175. if self.W_COMMANDS[self.selected_command] ~= nil then
  1176. if self.w_first == nil then
  1177. action.no_atb = true
  1178. self.w_first = action
  1179. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  1180. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  1181. self.current_list = "none"
  1182. self.window_state = "command"
  1183. self:show_message(self:get_w_name(action), false)
  1184. self.message_until = nil
  1185. self:show_list(self.W_COMMANDS[self.selected_command])
  1186. return
  1187. end
  1188. table.insert(self.action_queue, self.w_first)
  1189. self.w_first = nil
  1190. self:show_message("")
  1191. end
  1192. table.insert(self.action_queue, action)
  1193. -- The member has chosen: it doesn't choose again until the action is executed.
  1194. self.party[action.actor].acting = true
  1195. -- The character has chosen: remove it from the command queue and close the windows.
  1196. for i = #self.command_queue, 1, -1 do
  1197. if self.command_queue[i] == action.actor then table.remove(self.command_queue, i) end
  1198. end
  1199. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  1200. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  1201. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  1202. ui_manager:get_widget("BattleUi.Container.Bottom.Change"):set_visible(false)
  1203. ui_manager:get_widget("BattleUi.Container.Bottom.Defend"):set_visible(false)
  1204. self.current_list = "none"
  1205. self.window_state = "wait"
  1206. end,
  1207. --- Handles a time tick.
  1208. --
  1209. -- Increases the ATBs of party and enemies. If one of them gets filled, it shows tha command
  1210. -- window
  1211. tick = function(self)
  1212. if System:is_paused() == true then do return end end
  1213. local now = timer:get_game_time_total()
  1214. if self.ending == true then
  1215. -- Nothing else advances once the battle is over, but animations (victory poses) go on.
  1216. self:update_animations(now)
  1217. UiContainer.BattleFx:update(now)
  1218. local ok, err = pcall(BattleCameraController.update, BattleCameraController, now - self.last_tick_time)
  1219. if not ok then print("Battle camera: " .. tostring(err)) BattleCameraController:reset() end
  1220. self.last_tick_time = now
  1221. do return end
  1222. end
  1223. if self.intro == true then
  1224. -- The battle waits for the camera of its start. The first tick can be late (loading), so
  1225. -- the camera doesn't skip ahead.
  1226. self:update_animations(now)
  1227. UiContainer.BattleFx:update(now)
  1228. local elapsed = math.min(now - self.last_tick_time, 0.2)
  1229. self.last_tick_time = now
  1230. local ok, going = pcall(BattleCameraController.update_intro, BattleCameraController, elapsed)
  1231. if not ok then
  1232. print("Battle camera: " .. tostring(going))
  1233. BattleCameraController:reset()
  1234. battle_manager:set_camera(0)
  1235. end
  1236. self.intro = ok and going
  1237. -- The time that the ATBs are held for starts when the camera ends.
  1238. if self.intro ~= true then self.hold_start = now end
  1239. do return end
  1240. end
  1241. local delta = now - self.last_tick_time
  1242. self.last_tick_time = now
  1243. if self:update_escape(now, delta) then return end
  1244. self:update_animations(now)
  1245. UiContainer.BattleFx:update(now)
  1246. self:update_hides(now)
  1247. self:update_delayed_calls(now)
  1248. self:update_row_moves(now)
  1249. self:update_limit_flash(now)
  1250. if self.message_until ~= nil and now >= self.message_until then self:show_message("") end
  1251. self:update_action(now)
  1252. -- The camera of the attacks.
  1253. if self.action_executing ~= true and not BattleCameraController:is_script_running() then
  1254. BattleCameraController:stop()
  1255. end
  1256. local ok, err = pcall(BattleCameraController.update, BattleCameraController, delta)
  1257. if not ok then print("Battle camera: " .. tostring(err)) BattleCameraController:stop(false) end
  1258. -- Held ATBs start to fill after some time.
  1259. if (self.party_hold or self.enemy_hold) and now - self.hold_start > self.HOLD_TIME then
  1260. self:release_hold()
  1261. end
  1262. self:update_statuses(now)
  1263. -- A manipulated enemy is freed when it dies or its controller does.
  1264. for i = 1, #self.enemies do
  1265. local enemy = self.enemies[i]
  1266. if enemy.manipulated_by ~= nil and (enemy.dead or self.party[enemy.manipulated_by].dead) then self:release_manipulation(i) end
  1267. end
  1268. -- Advance party ATBs
  1269. for i = 1, #self.party do
  1270. local member = self.party[i]
  1271. if member.dead == false and self.party_hold == false then
  1272. -- 0 if a status stops the ATB.
  1273. local rate = self:get_atb_rate(Battle.TargetGroup.PARTY, i)
  1274. if member.atb < 255 and rate > 0 then
  1275. member.atb = member.atb + self:get_atb_speed(Battle.TargetGroup.PARTY, i) * delta
  1276. -- Fill ATB UI bar
  1277. -- 0 -> 0%
  1278. -- 255 -> 18%-6
  1279. local width_percent = math.min(18, 18 * member.atb / 255)
  1280. local width_fixed = math.max(-6, -6 * width_percent / 18)
  1281. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.AtbFill"):set_width(width_percent, width_fixed)
  1282. end
  1283. -- The defensive stance lasts until the ATB is full again.
  1284. if member.defending and member.atb >= 255 then self:set_defending(i, false) end
  1285. -- A full ATB can choose a command, unless a status stops it or it already has one.
  1286. local queued = false
  1287. for _, q in ipairs(self.command_queue) do if q == i then queued = true end end
  1288. if member.atb >= 255 and rate > 0 and not member.acting and self:acts_by_itself(Battle.TargetGroup.PARTY, i) then
  1289. -- Berserk and confused characters don't choose.
  1290. self:queue_auto_action(Battle.TargetGroup.PARTY, i)
  1291. elseif member.atb >= 255 and rate > 0 and not member.acting then
  1292. if not queued then
  1293. print(Characters[member.character].name .. " ATB full")
  1294. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.AtbFill"):set_colour(0, 1, 0)
  1295. table.insert(self.command_queue, i)
  1296. end
  1297. elseif queued then
  1298. self:remove_from_command_queue(i)
  1299. end
  1300. end
  1301. end
  1302. -- Advance enemy ATBs
  1303. for i = 1, #self.enemies do
  1304. if self.enemies[i].dead == false and self.enemy_hold == false then
  1305. local rate = self:get_atb_rate(Battle.TargetGroup.ENEMIES, i)
  1306. if rate > 0 then
  1307. if self.enemies[i].atb < 255 and self.enemies[i].waiting ~= true then
  1308. self.enemies[i].atb = self.enemies[i].atb + self:get_atb_speed(Battle.TargetGroup.ENEMIES, i) * delta
  1309. end
  1310. if self.enemies[i].atb >= 255 and self.enemies[i].waiting ~= true then
  1311. print("Enemy " .. self.enemies[i].name .. " ATB full")
  1312. self:queue_enemy_action(i)
  1313. end
  1314. end
  1315. end
  1316. end
  1317. -- Show a command window if required
  1318. if self.window_state == "wait" and #self.command_queue > 0 then self:show_commands(self.command_queue[1]) end
  1319. -- Execute an action if none is being executed
  1320. if self.action_executing == false and #self.action_queue > 0 then
  1321. self:execute_action()
  1322. end
  1323. end,
  1324. --- Sets the initial ATBs, depending on the battle layout.
  1325. --
  1326. -- Layouts as in BattleManager::LAYOUT: 0 normal, 1 preemptive, 2 back attack, 3 side attack,
  1327. -- 4 pincer attack, 5 solo, 8 locked. ATBs start random, except:
  1328. -- preemptive: party full, enemies empty and held; back attack: party empty and held, enemies
  1329. -- full; side attack: party full; pincer attack: enemies full.
  1330. init_atb = function(self)
  1331. local layout = battle_manager:get_layout()
  1332. -- Pre-Emptive materia can make a normal battle a pre-emptive one. TODO: The chance is a guess
  1333. -- (its percent points).
  1334. if layout == 0 then
  1335. local points = 0
  1336. for i = 1, #self.party do points = points + (self.party[i].independent ~= nil and self.party[i].independent.preemptive or 0) end
  1337. if points > 0 and math.random() * 100 < points then
  1338. print("Pre-Emptive materia: pre-emptive attack")
  1339. layout = 1
  1340. end
  1341. end
  1342. self.party_hold = false
  1343. self.enemy_hold = false
  1344. self.hold_start = timer:get_game_time_total()
  1345. self.last_tick_time = self.hold_start
  1346. self.escape_seen = {}
  1347. self.escape_progress = 0
  1348. self.escape_pose = {}
  1349. -- Average dex of the enemies (rounded up) plus 50, the divisor of the ATB speeds.
  1350. local sum = 0
  1351. for i = 1, #self.enemies do sum = sum + (self.enemies[i].stats.dex or 0) end
  1352. local count = math.max(1, #self.enemies)
  1353. self.enemy_dex_average = math.floor((sum + count - 1) / count) + 50
  1354. local party_atb, enemy_atb = nil, nil
  1355. if layout == 1 then
  1356. party_atb, enemy_atb = 255, 0
  1357. self.enemy_hold = true
  1358. elseif layout == 2 then
  1359. party_atb, enemy_atb = 0, 255
  1360. self.party_hold = true
  1361. elseif layout == 3 then party_atb = 255
  1362. elseif layout == 4 then enemy_atb = 255
  1363. end
  1364. for i = 1, #self.party do
  1365. if party_atb ~= nil then self.party[i].atb = party_atb end
  1366. if self.party[i].atb >= 255 then
  1367. table.insert(self.command_queue, i)
  1368. local bar = ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.AtbFill")
  1369. bar:set_width(18, -6)
  1370. bar:set_colour(0, 1, 0)
  1371. end
  1372. end
  1373. for i = 1, #self.enemies do
  1374. if enemy_atb ~= nil then self.enemies[i].atb = enemy_atb end
  1375. end
  1376. end,
  1377. --- Lets held ATBs start to fill.
  1378. release_hold = function(self)
  1379. self.party_hold = false
  1380. self.enemy_hold = false
  1381. end,
  1382. --- Handles escaping.
  1383. --
  1384. -- While L1 and R1 are held, the party turns its back to the enemies and runs in place. If they
  1385. -- are held long enough, and the formation allows it, the party runs away and the battle ends.
  1386. -- Releasing them makes the party turn back to the enemies. The time depends on the escape
  1387. -- difficulty of the formation.
  1388. -- @param now Current game time.
  1389. -- @param delta Seconds since the last tick.
  1390. -- @return True if the battle was escaped.
  1391. update_escape = function(self, now, delta)
  1392. local l1 = self.escape_seen[Config.ACTIONS.L1]
  1393. local r1 = self.escape_seen[Config.ACTIONS.R1]
  1394. -- Key repeat is not instant, so both keys are considered held for a while after the
  1395. -- last event.
  1396. local window = 0.8
  1397. local held = l1 ~= nil and r1 ~= nil and now - l1 <= window and now - r1 <= window
  1398. local difficulty = battle_manager:get_escape_difficulty()
  1399. if not held then
  1400. self.escape_progress = 0
  1401. if next(self.escape_pose) ~= nil then
  1402. print("Escape: keys released, turning back.")
  1403. self:end_escape_pose()
  1404. end
  1405. return false
  1406. end
  1407. if difficulty < 0 or Battle.has_mode(Battle.Mode.NO_ESCAPE) then
  1408. if self.escape_progress == 0 then print("This battle can't be escaped.") end
  1409. self.escape_progress = delta
  1410. return false
  1411. end
  1412. if self.escape_progress == 0 and next(self.escape_pose) == nil then
  1413. print("Escape: keys held, turning around.")
  1414. self:begin_escape_pose()
  1415. end
  1416. self.escape_progress = self.escape_progress + delta
  1417. self:update_escape_pose(now)
  1418. if self.escape_progress >= 1 + 4 * difficulty then
  1419. print("Escaped from the battle.")
  1420. self:start_escape()
  1421. return true
  1422. end
  1423. return false
  1424. end,
  1425. --- Gets the data of an attack.
  1426. --
  1427. -- @param id Attack ID. Nil for the basic attack.
  1428. -- @return The attack data as in the attack files, nil if it doesn't exist.
  1429. get_attack_data = function(self, id)
  1430. if id == nil or id < 0 then return self.basic_attack end
  1431. if self.attack_cache[id] == nil then
  1432. local data = nil
  1433. -- Attacks of the scenes have a file. The other ones (summons) come from the kernel.
  1434. if battle_manager:has_attack(id) then data = battle_manager:get_attack(id)
  1435. else data = self:kernel_attack_to_data(id)
  1436. end
  1437. self.attack_cache[id] = data or false
  1438. end
  1439. return self.attack_cache[id] or nil
  1440. end,
  1441. --- Converts the status effects of the kernel data (items, kernel attacks) to the format of
  1442. -- the attack files.
  1443. convert_kernel_effects = function(self, status)
  1444. local effects = {}
  1445. for _, st in ipairs(status or {}) do
  1446. local mode = "inflict"
  1447. if st.mode == 1 then mode = "cure" elseif st.mode == 2 then mode = "toggle" end
  1448. table.insert(effects, {id = st.status, chance = st.chance / 63, mode = mode})
  1449. end
  1450. return effects
  1451. end,
  1452. --- Converts the target data of the kernel data to the format of the attack files.
  1453. convert_kernel_target = function(self, target)
  1454. local result = {}
  1455. for key, value in pairs(target or {}) do result[key == "selectable" and "selection_enabled" or key] = value end
  1456. return result
  1457. end,
  1458. --- Builds the attack data of a kernel attack, with the format of the attack files.
  1459. --
  1460. -- @return The attack data, nil if there is no such attack.
  1461. kernel_attack_to_data = function(self, id)
  1462. local k = Game.Attacks[id]
  1463. if k == nil then return nil end
  1464. return {
  1465. id = id, name = k.name, mp = k.mp or 0, reflectable = false,
  1466. -- Limits with the additional effect 0 hit as many times as the modifier says (Omnislash 15, from the
  1467. -- attack data of ff7.exe; not verified for the other attacks).
  1468. hits = (k.additional ~= nil and k.additional.effect == 0 and k.additional.modifier > 1 and id >= 128) and k.additional.modifier or nil,
  1469. damage = {
  1470. formula = k.dmg_formula, modifier = k.dmg_modifier, power = k.power,
  1471. accuracy = (k.accuracy or 255) / 255, restore = k.restore,
  1472. },
  1473. target = self:convert_kernel_target(k.target), animation = {},
  1474. effects = self:convert_kernel_effects(k.status), elements = k.elements or {},
  1475. }
  1476. end,
  1477. --- Builds attack data from an item, so it can be used as any attack.
  1478. --
  1479. -- Item formulas: (2, 6) restores power * 20 HP or MP, (2, 4) restores power / 32 of the
  1480. -- maximum HP or MP, (0, 8) restores everything, (3, 7) is fixed damage of power * 20, and (2, 3)
  1481. -- is a fraction of the current HP. Items without damage only apply statuses.
  1482. item_to_attack = function(self, item_id)
  1483. local item = Game.Items[item_id]
  1484. if item == nil then return nil end
  1485. return {
  1486. id = -2, item = true, name = item.name, mp = 0, reflectable = false,
  1487. damage = {
  1488. formula = item.dmg_formula, modifier = item.dmg_modifier, power = item.power,
  1489. accuracy = 1, restore = item.restore,
  1490. },
  1491. target = self:convert_kernel_target(item.target), animation = {},
  1492. effects = self:convert_kernel_effects(item.status), elements = item.elements or {},
  1493. }
  1494. end,
  1495. --- Attack of the kernel with the data of Throw.
  1496. THROW_ATTACK = 122,
  1497. --- Gets the attack data of an action: an item, a spell or summon, or the basic attack.
  1498. get_action_attack = function(self, action)
  1499. if action.item_id ~= nil then return self:item_to_attack(action.item_id) or self.basic_attack end
  1500. -- Coin: a tenth of the gil thrown as fixed damage, divided among the enemies that are alive (rounded up).
  1501. if action.coin_gil ~= nil then
  1502. if action.coin_damage == nil then
  1503. local alive = 0
  1504. for _, enemy in ipairs(self.enemies) do if not enemy.dead then alive = alive + 1 end end
  1505. action.coin_damage = math.ceil(action.coin_gil / 10 / math.max(1, alive))
  1506. end
  1507. return {
  1508. id = -3, name = "Coin", mp = 0, reflectable = false,
  1509. damage = {formula = 1, modifier = 1, power = 0, accuracy = 1, fixed_damage = action.coin_damage},
  1510. -- It always affects all the enemies, so it doesn't need All.
  1511. target = {short_range = 0, default_multiple = 1}, effects = {}, elements = {}, animation = {},
  1512. }
  1513. end
  1514. -- Throw: a physical attack of power 16 (attack 122 of the kernel) that never misses, with the attack of the
  1515. -- thrown weapon added to the one of the thrower (0x5c8fbd in ff7.exe).
  1516. if action.throw_item ~= nil then
  1517. local item = Game.Items[action.throw_item]
  1518. local data = self:get_attack_data(self.THROW_ATTACK)
  1519. if item ~= nil and data ~= nil then
  1520. local copy, damage = {}, {}
  1521. for key, value in pairs(data) do copy[key] = value end
  1522. for key, value in pairs(data.damage) do damage[key] = value end
  1523. damage.attack_bonus = item.type == Inventory.ITEM_TYPE.WEAPON and (item.power or 0) or 0
  1524. copy.damage = damage
  1525. copy.name = item.name
  1526. copy.elements = {}
  1527. copy.target = {short_range = 0}
  1528. return copy
  1529. end
  1530. end
  1531. -- The data of the limit techniques (ids 128 to 183) comes from a table of ff7.exe that the installer
  1532. -- adds to the kernel attacks. The physical ones (formulas 1 and 11) are used as they are. The other
  1533. -- ones are not done in SPECIAL_LIMITS yet (statuses, MP damage, slots, transformations...) and are
  1534. -- a strong normal attack. TODO: Those ones.
  1535. if action.limit ~= nil and action.attack_id ~= nil and action.actor_side == Battle.TargetGroup.PARTY then
  1536. local kernel = Game.Attacks[action.attack_id]
  1537. -- Mindblow (formula 2) goes through the data too, and does its damage to MP.
  1538. if kernel ~= nil and (kernel.dmg_formula == 1 or kernel.dmg_formula == 11
  1539. or (kernel.dmg_formula == 2 and self.LIMIT_DATA_ATTACKS[action.attack_id])) then
  1540. local data = self:get_attack_data(action.attack_id)
  1541. if data ~= nil then
  1542. if self.LIMIT_MP_DAMAGE[action.attack_id] then data.damage.mp_damage = true end
  1543. return data
  1544. end
  1545. end
  1546. if kernel ~= nil then
  1547. local limit = self:get_weapon_attack(action.actor)
  1548. local damage = {}
  1549. for key, value in pairs(limit.damage) do damage[key] = value end
  1550. damage.power = self.LIMIT_FALLBACK_POWER
  1551. limit.damage = damage
  1552. limit.name = kernel.name
  1553. return limit
  1554. end
  1555. end
  1556. if (action.attack_id == nil or action.attack_id < 0) and action.actor_side == Battle.TargetGroup.PARTY then
  1557. if action.command == 26 then
  1558. -- Flash: it can miss like a normal attack, with half of the accuracy of the weapon (ff7.exe,
  1559. -- 0x5ca5c1), does no damage, and kills the enemies it hits unless they are immune to death.
  1560. local flash = self:get_weapon_attack(action.actor)
  1561. local damage = {}
  1562. for key, value in pairs(flash.damage) do damage[key] = value end
  1563. damage.power = 0
  1564. damage.no_damage = true
  1565. damage.critical = 0
  1566. damage.accuracy = math.floor(math.floor((damage.accuracy or 1) * 255 + 0.5) / 2) / 255
  1567. flash.damage = damage
  1568. flash.name = "Flash"
  1569. flash.elements = {}
  1570. flash.effects = {{id = BattleStatus.DEATH, chance = self.FLASH_CHANCE, mode = "inflict"}}
  1571. return flash
  1572. end
  1573. -- D.blow: an attack that is always a critical hit, or misses.
  1574. if action.command == self.DBLOW_COMMAND then
  1575. local attack = self:get_weapon_attack(action.actor)
  1576. local damage = {}
  1577. for key, value in pairs(attack.damage) do damage[key] = value end
  1578. damage.always_critical = 1
  1579. -- A third of the accuracy of the weapon (ff7.exe, 0x5ca610).
  1580. damage.accuracy = math.floor(math.floor((damage.accuracy or 1) * 255 + 0.5) / 3) / 255
  1581. attack.damage = damage
  1582. attack.name = "D.blow"
  1583. return attack
  1584. end
  1585. return self:get_weapon_attack(action.actor)
  1586. end
  1587. return self:get_attack_data(action.attack_id) or self.basic_attack
  1588. end,
  1589. --- Builds the basic attack of a party member from the weapon equipped: its accuracy, critical
  1590. -- rate, elements and range.
  1591. --
  1592. -- @param index Index in the party (1 based).
  1593. get_weapon_attack = function(self, index)
  1594. local member = self.party[index]
  1595. local char = member ~= nil and Characters[member.character] or nil
  1596. local weapon = (char ~= nil and char.weapon ~= nil) and Game.Items[char.weapon.id] or nil
  1597. if weapon == nil then return self.basic_attack end
  1598. local elements = {}
  1599. for element, _ in pairs(member.effects.elements.attack) do table.insert(elements, element) end
  1600. table.sort(elements)
  1601. -- The added statuses have the chance 5 of 63 (ff7.exe, 0x5c9c5f).
  1602. local effects = {}
  1603. for status, _ in pairs(member.effects.status.attack) do
  1604. table.insert(effects, {id = status, chance = self.ADDED_EFFECT_CHANCE, mode = "inflict"})
  1605. end
  1606. return {
  1607. id = -1, name = "Attack", mp = 0, weapon = true,
  1608. -- The accuracy of weapons is a percentage.
  1609. damage = {formula = 1, modifier = 1, power = 16, accuracy = (weapon.accuracy or 100) / 255, critical = weapon.critical or 0},
  1610. target = {short_range = weapon.target ~= nil and weapon.target.short_range or 0},
  1611. -- Elemental materia linked in the weapon adds elements, and Added Effect adds statuses.
  1612. effects = effects, elements = elements, animation = {},
  1613. }
  1614. end,
  1615. --- Checks if an attack brings back the dead (it cures death), like Life or Phoenix Down.
  1616. attack_revives = function(self, attack)
  1617. for _, effect in ipairs(attack.effects or {}) do
  1618. if effect.id == BattleStatus.DEATH and effect.mode == "cure" then return true end
  1619. end
  1620. return false
  1621. end,
  1622. --- Checks if a combatant acts on its own because of its statuses (berserk or confusion).
  1623. acts_by_itself = function(self, side, index)
  1624. return self:has_status(side, index, BattleStatus.BERSERK) or self:has_status(side, index, BattleStatus.CONFUSION)
  1625. end,
  1626. --- Picks the random target of a confused combatant in a side: a living one (a dead one for attacks that revive),
  1627. -- and not itself while there is another one.
  1628. --
  1629. -- @return The index, nil if there is nobody to target.
  1630. get_confused_target = function(self, group, side, index, revives)
  1631. local list = group == Battle.TargetGroup.PARTY and self.party or self.enemies
  1632. local candidates = {}
  1633. for i = 1, #list do
  1634. if list[i].dead == revives and not (group == side and i == index) then table.insert(candidates, i) end
  1635. end
  1636. if #candidates == 0 then
  1637. if group == side and list[index] ~= nil and list[index].dead == revives then return index end
  1638. return nil
  1639. end
  1640. return candidates[math.random(1, #candidates)]
  1641. end,
  1642. --- Aims an action of a confused combatant: at the side opposite to the usual one of what it uses (an ally for what
  1643. -- is meant for enemies, and the other way round), at one random combatant or at the whole side.
  1644. --
  1645. -- @param multiple True to aim at the whole side.
  1646. -- @return False if there is nobody to target.
  1647. aim_confused = function(self, action, group, multiple, revives)
  1648. action.target_group = group
  1649. action.target_list = nil
  1650. action.target_index = nil
  1651. if multiple then
  1652. action.target_type = Battle.TargetType.GROUP
  1653. return true
  1654. end
  1655. action.target_type = Battle.TargetType.SINGLE
  1656. action.target_index = self:get_confused_target(group, action.actor_side or Battle.TargetGroup.PARTY, action.actor, revives)
  1657. return action.target_index ~= nil
  1658. end,
  1659. --- Turns around the targets of an action that was chosen before its actor got confused.
  1660. --
  1661. -- @param attack Attack data of the action.
  1662. -- @return False if there is nobody to target.
  1663. apply_confusion = function(self, action, attack)
  1664. local side = action.actor_side or Battle.TargetGroup.PARTY
  1665. if action.automatic or action.target_group == nil or not self:has_status(side, action.actor, BattleStatus.CONFUSION) then
  1666. return true
  1667. end
  1668. local group = action.target_group == Battle.TargetGroup.PARTY and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  1669. local multiple = action.target_index == nil and (action.target_list == nil or #action.target_list > 1)
  1670. return self:aim_confused(action, group, multiple, self:attack_revives(attack))
  1671. end,
  1672. --- Gets the spells that a confused combatant can cast: the ones it can pay and isn't stopped from casting. For an
  1673. -- enemy, its attacks that cost MP.
  1674. --
  1675. -- @return A list of actions (attack_id, command and script).
  1676. get_confused_spells = function(self, side, index)
  1677. local spells = {}
  1678. if self:has_status(side, index, BattleStatus.SILENCE) then return spells end
  1679. local frog = self:has_status(side, index, BattleStatus.FROG)
  1680. if side == Battle.TargetGroup.PARTY then
  1681. local member = self.party[index]
  1682. local mp = Characters[member.character].stats.mp.current
  1683. for _, spell in ipairs(member.magic or {}) do
  1684. if self:get_spell_cost(Game.Attacks[spell.id].mp, nil) <= mp and (not frog or spell.id == self.FROG_SPELL) then
  1685. table.insert(spells, {attack_id = spell.id, command = 2})
  1686. end
  1687. end
  1688. elseif not frog then
  1689. local source = battle_manager:get_enemy(index - 1)
  1690. for slot = 0, source:get_attack_count() - 1 do
  1691. local id = source:get_attack(slot)
  1692. local data = self:get_attack_data(id)
  1693. if data ~= nil and (data.mp or 0) > 0 and data.mp <= self.enemies[index].stats.mp then
  1694. local script = source:get_attack_animation(slot)
  1695. table.insert(spells, {attack_id = id, command = 1, script = script >= 0 and script or nil})
  1696. end
  1697. end
  1698. end
  1699. return spells
  1700. end,
  1701. --- Queues the action of a combatant that doesn't choose what to do. A berserk one attacks a random enemy. A
  1702. -- confused one attacks or casts a random spell (half of the times each, if it can cast any), at the side opposite
  1703. -- to the usual one. Berserk goes first.
  1704. queue_auto_action = function(self, side, index)
  1705. local other = side == Battle.TargetGroup.PARTY and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  1706. local berserk = self:has_status(side, index, BattleStatus.BERSERK)
  1707. local action = {
  1708. actor = index, actor_side = side, type = Battle.ActionType.COMMAND, command = 1, automatic = true,
  1709. }
  1710. -- The attack of an enemy is the first of the ones it has when manipulated (ff7.exe, 0x435a32 for Berserk).
  1711. if side == Battle.TargetGroup.ENEMIES then
  1712. local source = battle_manager:get_enemy(index - 1)
  1713. if source:get_manip_count() > 0 then
  1714. action.attack_id = source:get_manip_attack(0)
  1715. for slot = 0, source:get_attack_count() - 1 do
  1716. if source:get_attack(slot) == action.attack_id and source:get_attack_animation(slot) >= 0 then
  1717. action.script = source:get_attack_animation(slot)
  1718. break
  1719. end
  1720. end
  1721. end
  1722. end
  1723. local aimed = false
  1724. if not berserk then
  1725. local spells = self:get_confused_spells(side, index)
  1726. if #spells > 0 and math.random() < 0.5 then
  1727. local spell = spells[math.random(1, #spells)]
  1728. local cast = {
  1729. actor = index, actor_side = side, automatic = true, command = spell.command,
  1730. attack_id = spell.attack_id, script = spell.script,
  1731. type = side == Battle.TargetGroup.PARTY and Battle.ActionType.ATTACK or Battle.ActionType.COMMAND,
  1732. }
  1733. -- A spell without anybody to target (like Life with everybody alive) is left for an attack.
  1734. if self:aim_confused_default(cast) then action, aimed = cast, true end
  1735. end
  1736. if not aimed then aimed = self:aim_confused_default(action) end
  1737. else
  1738. action.target_type = Battle.TargetType.SINGLE
  1739. action.target_group = other
  1740. action.target_index = self:random_living(other)
  1741. aimed = action.target_index ~= nil
  1742. end
  1743. if not aimed then return end
  1744. table.insert(self.action_queue, action)
  1745. local combatant = self:get_combatant(side, index)
  1746. if side == Battle.TargetGroup.PARTY then combatant.acting = true
  1747. else
  1748. combatant.atb = 0
  1749. combatant.waiting = true
  1750. end
  1751. end,
  1752. --- Aims an action that a confused combatant chooses itself, from the usual targets of what it uses.
  1753. aim_confused_default = function(self, action)
  1754. local side = action.actor_side
  1755. local attack = self:get_action_attack(action)
  1756. local target = attack.target or {}
  1757. local other = side == Battle.TargetGroup.PARTY and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  1758. local group = target.default_enemy ~= 0 and side or other
  1759. -- Spells that All materia can widen have both flags, and start with one target.
  1760. local multiple = target.default_multiple == 1 and target.toggle_multiple ~= 1
  1761. return self:aim_confused(action, group, multiple, self:attack_revives(attack))
  1762. end,
  1763. -- ================================================================================
  1764. -- Enemy AI scripts (see battle_ai_vm.lua)
  1765. -- ================================================================================
  1766. --- Registers of the actor fields the scripts can read: field address (in bits) of each.
  1767. AI_REGISTERS = {
  1768. 0x00, 0x20, 0x40, 0x48, 0x58, 0x60, 0x68, 0x70, 0x78, 0x80, 0x88, 0x90, 0x98, 0xA0, 0xA8,
  1769. 0xB0, 0xB8, 0xC0, 0xD0, 0xE0, 0xF0, 0x100, 0x110, 0x120, 0x130, 0x140, 0x150, 0x160, 0x180,
  1770. 0x268, 0x270, 0x2B0, 0x2C0, 0x2E0,
  1771. },
  1772. --- Gets the actor number a combatant has in the scripts: 0 to 2 are the party, 4 to 9 enemies.
  1773. ai_actor_of = function(self, side, index)
  1774. if side == Battle.TargetGroup.PARTY then return index - 1 end
  1775. return index + 3
  1776. end,
  1777. --- Gets the combatant of an actor number.
  1778. -- @return side and index, nil if there is no such actor.
  1779. ai_combatant_of = function(self, actor)
  1780. if actor >= 0 and actor <= 2 and self.party[actor + 1] ~= nil then return Battle.TargetGroup.PARTY, actor + 1 end
  1781. if actor >= 4 and actor <= 9 and self.enemies[actor - 3] ~= nil then return Battle.TargetGroup.ENEMIES, actor - 3 end
  1782. return nil
  1783. end,
  1784. --- Gets the mask of the actors of a side.
  1785. -- @param alive_only True to only include the ones that are not dead.
  1786. ai_mask = function(self, side, alive_only)
  1787. local list = side == Battle.TargetGroup.PARTY and self.party or self.enemies
  1788. local mask = 0
  1789. for i = 1, #list do
  1790. if not alive_only or list[i].dead == false then mask = mask + 2 ^ self:ai_actor_of(side, i) end
  1791. end
  1792. return mask
  1793. end,
  1794. --- Gets the side of an actor number.
  1795. ai_side_of = function(self, actor)
  1796. if actor <= 2 then return Battle.TargetGroup.PARTY end
  1797. return Battle.TargetGroup.ENEMIES
  1798. end,
  1799. --- Reads a global value of the scripts.
  1800. ai_read_global = function(self, owner, address)
  1801. local own = self:ai_side_of(owner)
  1802. local other = own == Battle.TargetGroup.PARTY and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  1803. if address == 0x2060 then return 2 ^ owner
  1804. elseif address == 0x2050 then return self:ai_mask(Battle.TargetGroup.PARTY, true) + self:ai_mask(Battle.TargetGroup.ENEMIES, true)
  1805. elseif address == 0x2070 then return self.ai_targets or 0
  1806. elseif address == 0x2080 then return self:ai_mask(own, false)
  1807. elseif address == 0x2090 then return self:ai_mask(own, true)
  1808. elseif address == 0x20A0 then return self:ai_mask(other, false)
  1809. elseif address == 0x20B0 then return self:ai_mask(other, true)
  1810. elseif address == 0x20C0 then return self:ai_mask(Battle.TargetGroup.PARTY, true)
  1811. elseif address == 0x20E0 then return self:ai_mask(Battle.TargetGroup.PARTY, false) + self:ai_mask(Battle.TargetGroup.ENEMIES, false)
  1812. elseif address == 0x2020 then return battle_manager:get_layout()
  1813. elseif address == 0x2140 then return battle_manager:get_formation_id()
  1814. elseif address == 0x2000 then return 0
  1815. elseif address == 0x2008 or address == 0x2150 then return self.ai_last_action or 0
  1816. elseif address == 0x2120 then return self.ai_last_elements or 0
  1817. elseif address == 0x2010 then return self.ai_membank or 0
  1818. elseif address >= 0x2110 and address < 0x2120 then return self.ai_end_flags or 0
  1819. end
  1820. return 0
  1821. end,
  1822. --- Writes a global value of the scripts.
  1823. ai_write_global = function(self, owner, address, size, value)
  1824. if address == 0x2070 then self.ai_targets = value
  1825. elseif address == 0x2010 then self.ai_membank = value
  1826. elseif address >= 0x2110 and address < 0x2120 then
  1827. -- Flags of the end of the battle, one bit each: 0x2114 ends the battle.
  1828. local bit = address - 0x2110
  1829. if size == 0 and bit == 4 and value ~= 0 then self.ai_end_battle = true end
  1830. end
  1831. end,
  1832. --- Gets the value of one of the registers of an actor (see AI_REGISTERS).
  1833. ai_read_register = function(self, actor, base)
  1834. local side, index = self:ai_combatant_of(actor)
  1835. if side == nil then return 0 end
  1836. local c = self:get_combatant(side, index)
  1837. local stats = self:get_combat_stats(side, index)
  1838. if base == 0x00 then
  1839. local mask = 0
  1840. for id, _ in pairs(c.status or {}) do mask = mask + 2 ^ id end
  1841. if c.dead and math.floor(mask) % 2 == 0 then mask = mask + 1 end
  1842. return mask
  1843. elseif base == 0x20 then
  1844. local back = false
  1845. if side == Battle.TargetGroup.PARTY then back = Characters[c.character].back_row == true
  1846. else back = not battle_manager:get_enemy(index - 1):is_front() end
  1847. local flags = 0
  1848. if back then flags = flags + 2 ^ 6 end
  1849. if c.dead then flags = flags + 2 ^ 13 end
  1850. if side == Battle.TargetGroup.ENEMIES and c.hidden then flags = flags + 2 ^ 14 end
  1851. return flags
  1852. elseif base == 0x40 or base == 0x120 then return actor
  1853. elseif base == 0x48 then return stats.level
  1854. elseif base == 0x60 then return side == Battle.TargetGroup.PARTY and (c.character + 16) or index
  1855. elseif base == 0x68 then return stats.str
  1856. elseif base == 0x70 then return stats.mag
  1857. elseif base == 0xA0 then
  1858. if side == Battle.TargetGroup.PARTY then return Characters[c.character].stats.dex.total end
  1859. return c.stats.dex
  1860. elseif base == 0xA8 then
  1861. if side == Battle.TargetGroup.PARTY then return Characters[c.character].stats.lck.total end
  1862. return c.stats.lck
  1863. elseif base == 0x100 then return stats.def
  1864. elseif base == 0x110 then return stats.mdef
  1865. elseif base == 0x140 then return stats.mp
  1866. elseif base == 0x150 then return stats.mp_max
  1867. elseif base == 0x160 then return stats.hp
  1868. elseif base == 0x180 then return stats.hp_max
  1869. elseif base == 0x270 then
  1870. if side == Battle.TargetGroup.PARTY then return Characters[c.character].back_row and 1 or 0 end
  1871. return battle_manager:get_enemy(index - 1):is_front() and 0 or 1
  1872. elseif base == 0x2B0 then return c.ap or 0
  1873. elseif base == 0x2C0 then return c.money or 0
  1874. elseif base == 0x2E0 then return c.exp or 0
  1875. elseif base == 0xC0 then return c.ai_last_targets or 0
  1876. elseif base == 0xD0 then return c.ai_prev_attacker or 0
  1877. elseif base == 0xE0 then return c.ai_prev_physical or 0
  1878. elseif base == 0xF0 then return c.ai_prev_magical or 0
  1879. end
  1880. return 0
  1881. end,
  1882. --- Reads an actor field of the scripts.
  1883. -- @param field Field address, in bits (the address minus 0x4000).
  1884. ai_read_actor = function(self, actor, field, size)
  1885. local base = nil
  1886. for _, register in ipairs(self.AI_REGISTERS) do
  1887. if register <= field then base = register end
  1888. end
  1889. if base == nil then return 0 end
  1890. local value = math.floor(self:ai_read_register(actor, base))
  1891. local offset = field - base
  1892. if size == 0 then return math.floor(value / 2 ^ offset) % 2 end
  1893. return math.floor(value / 2 ^ offset) % 2 ^ (8 * BattleAI.SIZE_BYTES[size])
  1894. end,
  1895. --- Writes an actor field of the scripts. Only some fields do something.
  1896. ai_write_actor = function(self, actor, field, size, value)
  1897. local side, index = self:ai_combatant_of(actor)
  1898. if side == nil then do return end end
  1899. local c = self:get_combatant(side, index)
  1900. if field < 0x20 then
  1901. -- Statuses. A bit sets or cures one, a whole value changes all of them.
  1902. local function change(id, on)
  1903. if id == BattleStatus.DEATH then
  1904. if on and not c.dead then
  1905. local stats = self:get_combat_stats(side, index)
  1906. if stats.hp > 0 then self:apply_damage(side, index, stats.hp, false) end
  1907. end
  1908. elseif on then self:set_status(side, index, id)
  1909. else self:clear_status(side, index, id)
  1910. end
  1911. end
  1912. if size == 0 then change(field, value ~= 0)
  1913. else
  1914. for id = 0, 31 do
  1915. local on = math.floor(value / 2 ^ id) % 2 == 1
  1916. if on ~= (c.status[id] ~= nil) then change(id, on) end
  1917. end
  1918. end
  1919. elseif field >= 0x20 and field < 0x40 then
  1920. local bit = field - 0x20
  1921. if size == 0 and bit == 14 and side == Battle.TargetGroup.ENEMIES then
  1922. -- Invisible: the model is hidden, and it can't be targeted.
  1923. c.hidden = value ~= 0
  1924. battle_manager:set_enemy_visible(index - 1, value == 0)
  1925. end
  1926. elseif field >= 0x160 and field < 0x180 and size == 3 then
  1927. -- HP.
  1928. local stats = self:get_combat_stats(side, index)
  1929. local difference = stats.hp - math.floor(value)
  1930. if difference ~= 0 then self:apply_damage(side, index, difference, false) end
  1931. elseif field >= 0x140 and field < 0x150 and size == 2 then
  1932. -- MP.
  1933. local stats = self:get_combat_stats(side, index)
  1934. local difference = stats.mp - math.floor(value)
  1935. if difference ~= 0 then self:apply_damage(side, index, difference, true) end
  1936. end
  1937. end,
  1938. --- Decodes a text of the FF7 encoding.
  1939. ai_decode_text = function(self, bytes)
  1940. local text = {}
  1941. for i = 1, #bytes do
  1942. local code = bytes:byte(i)
  1943. -- Characters are the ASCII ones minus 0x20. The other codes are control codes.
  1944. if code <= 0x5F then table.insert(text, string.char(code + 0x20))
  1945. elseif code == 0xE0 or code == 0xE1 then table.insert(text, " ")
  1946. end
  1947. end
  1948. return table.concat(text)
  1949. end,
  1950. --- The interface the AI scripts use to talk to the battle.
  1951. ai_host = nil,
  1952. --- Creates the interface of the AI interpreter, once.
  1953. get_ai_host = function(self)
  1954. if self.ai_host ~= nil then return self.ai_host end
  1955. local ui = self
  1956. local host = {}
  1957. function host:read_global(address, size) return ui:ai_read_global(self.owner, address) end
  1958. function host:write_global(address, size, value) ui:ai_write_global(self.owner, address, size, value) end
  1959. function host:read_actor(actor, field, size) return ui:ai_read_actor(actor, field, size) end
  1960. function host:write_actor(actor, field, size, value) ui:ai_write_actor(actor, field, size, value) end
  1961. function host:random(n) return math.random(0, n - 1) end
  1962. function host:mp_cost(id)
  1963. local attack = ui:get_attack_data(id)
  1964. return attack ~= nil and attack.mp or 0
  1965. end
  1966. function host:text(owner, bytes)
  1967. local text = ui:ai_decode_text(bytes)
  1968. print("AI text: " .. text)
  1969. ui:show_message(text)
  1970. end
  1971. function host:memory_bank(write, offset)
  1972. -- Access to the game memory banks: the value at 0x2010 is stored there, or read from
  1973. -- there. TODO: Map the offsets to the variables of the game.
  1974. end
  1975. function host:action(owner, kind, id) ui:ai_action(owner, kind, id) end
  1976. self.ai_host = host
  1977. return host
  1978. end,
  1979. --- Handles an action requested by a script.
  1980. ai_action = function(self, owner, kind, id)
  1981. local side, index = self:ai_combatant_of(owner)
  1982. if side == nil then do return end end
  1983. if kind == BattleAI.ACTION.RUN_SCRIPT then
  1984. self:ai_run(owner, id)
  1985. do return end
  1986. end
  1987. if kind ~= BattleAI.ACTION.ENEMY_ATTACK then do return end end
  1988. -- Targets: the actors of the mask, all of the side of the first one.
  1989. local mask = math.floor(self.ai_targets or 0)
  1990. local group, list = nil, {}
  1991. for actor = 0, 31 do
  1992. if math.floor(mask / 2 ^ actor) % 2 == 1 then
  1993. local target_side, target_index = self:ai_combatant_of(actor)
  1994. if target_side ~= nil and (group == nil or group == target_side) then
  1995. group = target_side
  1996. table.insert(list, target_index)
  1997. end
  1998. end
  1999. end
  2000. if group == nil then do return end end
  2001. -- The animation of the attack is the one of the enemy slot that has it.
  2002. local script = nil
  2003. if side == Battle.TargetGroup.ENEMIES then
  2004. local source = battle_manager:get_enemy(index - 1)
  2005. for slot = 0, source:get_attack_count() - 1 do
  2006. if source:get_attack(slot) == id then
  2007. script = source:get_attack_animation(slot)
  2008. break
  2009. end
  2010. end
  2011. if script ~= nil and script < 0 then script = nil end
  2012. end
  2013. local action = {
  2014. actor = index, actor_side = side, type = Battle.ActionType.COMMAND, command = 1,
  2015. attack_id = id, script = script,
  2016. target_type = #list == 1 and Battle.TargetType.SINGLE or Battle.TargetType.GROUP,
  2017. target_group = group, target_list = list, target_index = #list == 1 and list[1] or nil,
  2018. allow_dead = self.ai_counter == true, is_counter = self.ai_counter == true,
  2019. }
  2020. if self.ai_counter then
  2021. -- Counterattacks go before the other actions, but keep the order they were requested in.
  2022. local position = self.ai_counter_count + 1
  2023. table.insert(self.action_queue, math.min(position, #self.action_queue + 1), action)
  2024. self.ai_counter_count = position
  2025. else table.insert(self.action_queue, action)
  2026. end
  2027. self.ai_queued = (self.ai_queued or 0) + 1
  2028. end,
  2029. --- Runs one of the AI scripts of an actor.
  2030. --
  2031. -- @param slot 0 init, 1 main, 2 general counter, 3 death counter, 4 physical counter, 5 magic
  2032. -- counter, 6 battle end, 7 pre-turn, 8 to 15 events.
  2033. -- @return True if the actor has a script in that slot.
  2034. ai_run = function(self, owner, slot)
  2035. local side, index = self:ai_combatant_of(owner)
  2036. if side ~= Battle.TargetGroup.ENEMIES then return false end
  2037. local code = battle_manager:get_enemy(index - 1):get_ai_script(slot)
  2038. if code == nil or code == "" then return false end
  2039. -- Scripts set the targets before an action; they start from nothing.
  2040. local previous_targets = self.ai_targets
  2041. self.ai_targets = 0
  2042. BattleAI.run_safe(code, owner, self:get_ai_host())
  2043. self.ai_targets = previous_targets
  2044. return true
  2045. end,
  2046. --- Prepares the AI of the battle: clears the variables and runs the initialization scripts.
  2047. ai_setup = function(self)
  2048. BattleAI.reset()
  2049. self.ai_targets = 0
  2050. self.ai_queued = 0
  2051. self.ai_counter = false
  2052. self.ai_counter_count = 0
  2053. self.ai_end_battle = false
  2054. self.ai_end_flags = 0
  2055. self.ai_last_action = 0
  2056. self.ai_last_elements = 0
  2057. for i = 1, #self.enemies do self:ai_run(self:ai_actor_of(Battle.TargetGroup.ENEMIES, i), BattleAI.SLOT.INIT) end
  2058. end,
  2059. --- Lets the AI scripts of an enemy decide its turn.
  2060. --
  2061. -- @return True if the enemy has AI scripts and they were used, false to use a random attack.
  2062. ai_take_turn = function(self, index)
  2063. local owner = self:ai_actor_of(Battle.TargetGroup.ENEMIES, index)
  2064. local source = battle_manager:get_enemy(index - 1)
  2065. if source:get_ai_script(BattleAI.SLOT.MAIN) == "" then return false end
  2066. self.ai_counter = false
  2067. self.ai_queued = 0
  2068. self:ai_run(owner, BattleAI.SLOT.PRE_TURN)
  2069. self:ai_run(owner, BattleAI.SLOT.MAIN)
  2070. self.enemies[index].atb = 0
  2071. -- Without actions, the enemy skips the turn. Otherwise it waits for them to be executed.
  2072. if self.ai_queued > 0 then self.enemies[index].waiting = true end
  2073. return true
  2074. end,
  2075. --- Runs the counter scripts of an enemy after it's attacked.
  2076. --
  2077. -- @param attacker_side Side of the attacker, and attacker_index its index.
  2078. -- @param kind The formula of the attack: 1 physical, 2 magical.
  2079. ai_after_hit = function(self, attack, attacker_side, attacker_index, target_index, dead)
  2080. local enemy = self.enemies[target_index]
  2081. local owner = self:ai_actor_of(Battle.TargetGroup.ENEMIES, target_index)
  2082. local attacker = 2 ^ self:ai_actor_of(attacker_side, attacker_index)
  2083. local formula = math.floor(attack.damage.formula or 0)
  2084. enemy.ai_prev_attacker = attacker
  2085. if formula == 1 then enemy.ai_prev_physical = attacker else enemy.ai_prev_magical = attacker end
  2086. self.ai_last_action = attack.id >= 0 and attack.id or 0
  2087. local elements = 0
  2088. for _, element in ipairs(attack.elements or {}) do elements = elements + 2 ^ element end
  2089. self.ai_last_elements = elements
  2090. -- Counterattacks go before everything else in the queue.
  2091. self.ai_counter = true
  2092. if not dead then
  2093. self:ai_run(owner, BattleAI.SLOT.COUNTER_GENERAL)
  2094. if formula == 1 then self:ai_run(owner, BattleAI.SLOT.COUNTER_PHYSICAL)
  2095. else self:ai_run(owner, BattleAI.SLOT.COUNTER_MAGIC)
  2096. end
  2097. else
  2098. self:ai_run(owner, BattleAI.SLOT.COUNTER_DEATH)
  2099. end
  2100. self.ai_counter = false
  2101. end,
  2102. --- Queues an attack for an enemy whose ATB is full.
  2103. --
  2104. -- The attack is picked at random between the ones of the enemy.
  2105. -- TODO: Use the enemy AI scripts.
  2106. -- @param index Enemy index in {@see enemies}.
  2107. queue_enemy_action = function(self, index)
  2108. if self:acts_by_itself(Battle.TargetGroup.ENEMIES, index) then
  2109. self:queue_auto_action(Battle.TargetGroup.ENEMIES, index)
  2110. do return end
  2111. end
  2112. -- The AI scripts of the enemy decide, if it has any.
  2113. if self:ai_take_turn(index) then do return end end
  2114. local source = battle_manager:get_enemy(index - 1)
  2115. local attack_id, script = nil, nil
  2116. local count = source:get_attack_count()
  2117. if count > 0 then
  2118. local slot = math.random(0, count - 1)
  2119. attack_id = source:get_attack(slot)
  2120. script = source:get_attack_animation(slot)
  2121. if script < 0 then script = nil end
  2122. end
  2123. local attack = self:get_attack_data(attack_id) or self.basic_attack
  2124. -- Enemy attacks aimed at "enemies" are aimed at the party, the other ones at the enemies
  2125. -- (restoring, buffs...).
  2126. local target_group = Battle.TargetGroup.PARTY
  2127. if attack.target.default_enemy == 0 then target_group = Battle.TargetGroup.ENEMIES end
  2128. local list = target_group == Battle.TargetGroup.PARTY and self.party or self.enemies
  2129. local candidates = {}
  2130. for i = 1, #list do
  2131. if list[i].dead == false then table.insert(candidates, i) end
  2132. end
  2133. if #candidates == 0 then do return end end
  2134. local target_index = nil
  2135. if attack.target.default_multiple ~= 1 then target_index = candidates[math.random(1, #candidates)] end
  2136. table.insert(self.action_queue, {
  2137. actor = index,
  2138. actor_side = Battle.TargetGroup.ENEMIES,
  2139. type = Battle.ActionType.COMMAND,
  2140. command = 1,
  2141. attack_id = attack_id,
  2142. script = script,
  2143. target_type = target_index == nil and Battle.TargetType.GROUP or Battle.TargetType.SINGLE,
  2144. target_group = target_group,
  2145. target_index = target_index,
  2146. })
  2147. -- Stop the enemy ATB from refilling until its action is done.
  2148. self.enemies[index].atb = 0
  2149. self.enemies[index].waiting = true
  2150. end,
  2151. --- Statuses that make a target be hit by the physical attacks (0x2404445 in ff7.exe), and by the magical ones
  2152. -- (0x2004445, without Manipulate).
  2153. PHYSICAL_AUTO_HIT = {BattleStatus.DEATH, BattleStatus.SLEEP, BattleStatus.CONFUSION, BattleStatus.STOP,
  2154. BattleStatus.PETRIFY, BattleStatus.MANIPULATE, BattleStatus.PARALYSIS},
  2155. MAGICAL_AUTO_HIT = {BattleStatus.DEATH, BattleStatus.SLEEP, BattleStatus.CONFUSION, BattleStatus.STOP,
  2156. BattleStatus.PETRIFY, BattleStatus.PARALYSIS},
  2157. --- Rolls if an attack hits, with the formulas of ff7.exe (0x5ddb20 physical, 0x5dddce magical).
  2158. --
  2159. -- Physical: the chance is the accuracy of the attack + dexterity / 4 of the attacker + the evade of the attacker
  2160. -- - the evade of the target (see get_evade), minus 30% if the attacker has Fury, and it is rolled from 1 to
  2161. -- 100 (it hits if the roll is lower). Darkness halves the accuracy of the attack. Luck lets attackers always
  2162. -- hit (luck / 4 percent) and, for the attacks of enemies, lets party members always evade. Sleep, Stop,
  2163. -- Confusion, Petrify, Paralysis, Manipulate and Death are always hit (before the luck rolls).
  2164. -- Magical: the chance is the accuracy (minus 30% with Fury) + level of the attacker - level of the target / 2,
  2165. -- after a roll against the magic evasion of the target (a percent). Reflect, and the statuses of
  2166. -- the physical ones except Manipulate, make the target be hit. 255 or more of accuracy always hits.
  2167. -- Elements: a target that nullifies or absorbs the attack, or dies by its element, is hit like the ones with
  2168. -- those statuses. For attacks without power (the ones that only add statuses), a weakness doubles the
  2169. -- accuracy and a resistance halves it.
  2170. --
  2171. -- @param formula Formula of the attack.
  2172. -- @param accuracy Accuracy byte of the attack.
  2173. -- @param element Element factor of the target against the attack (see get_element_factor), 1 if nil.
  2174. -- @param power Power of the attack.
  2175. -- @return True if the attack hits.
  2176. roll_hit = function(self, formula, accuracy, attacker_side, attacker_index, target_side, target_index, element, power)
  2177. local physical = formula == 1 or formula == 6 or formula == 10
  2178. local magical = formula == 2 or formula == 7
  2179. if not physical and not magical then return true end
  2180. local a = self:get_combat_stats(attacker_side, attacker_index)
  2181. local t = self:get_combat_stats(target_side, target_index)
  2182. local fury = self:has_status(attacker_side, attacker_index, BattleStatus.FURY)
  2183. local function any(list)
  2184. for _, id in ipairs(list) do
  2185. if self:has_status(target_side, target_index, id) then return true end
  2186. end
  2187. return false
  2188. end
  2189. element = element or 1
  2190. local element_hit = element >= 10 or element == 0 or (element < 0 and element > -10)
  2191. if physical and self:has_status(attacker_side, attacker_index, BattleStatus.DARKNESS) then
  2192. accuracy = math.floor(accuracy / 2)
  2193. end
  2194. if power == 0 then
  2195. if element == 2 then accuracy = accuracy * 2
  2196. elseif element == 0.5 then accuracy = math.floor(accuracy / 2)
  2197. end
  2198. end
  2199. if magical then
  2200. if accuracy >= 255 or element_hit then return true end
  2201. if self:has_status(target_side, target_index, BattleStatus.REFLECT) or any(self.MAGICAL_AUTO_HIT) then return true end
  2202. if fury then accuracy = accuracy - math.floor(accuracy * 3 / 10) end
  2203. if math.floor(math.random() * 100) < t.meva then return false end
  2204. return math.random(1, 100) < accuracy + a.level - math.floor(t.level / 2)
  2205. end
  2206. local chance
  2207. if element_hit or any(self.PHYSICAL_AUTO_HIT) then chance = 255
  2208. else
  2209. chance = accuracy + math.floor(a.dex / 4) + self:get_evade(attacker_side, attacker_index)
  2210. - self:get_evade(target_side, target_index)
  2211. if chance < 255 and fury then chance = chance - math.floor(chance * 3 / 10) end
  2212. if chance <= 0 then chance = 1 end
  2213. end
  2214. local roll = math.floor(math.random() * 100)
  2215. if roll < math.floor(self:get_luck(attacker_side, attacker_index) / 4) then chance = 255
  2216. elseif attacker_side == Battle.TargetGroup.ENEMIES and target_side == Battle.TargetGroup.PARTY
  2217. and roll < math.floor(self:get_luck(target_side, target_index) / 4) then chance = 0
  2218. end
  2219. return math.random(1, 100) < chance
  2220. end,
  2221. --- Gets the physical evade of a combatant: dexterity / 4 plus the evasion of the armor for a party member,
  2222. -- its evade for an enemy. The evade modifier applies to the whole sum, the dexterity one doesn't count.
  2223. get_evade = function(self, side, index)
  2224. local stats = self:get_base_combat_stats(side, index)
  2225. local evade = stats.eva
  2226. if side == Battle.TargetGroup.PARTY then evade = evade + math.floor(stats.dex / 4) end
  2227. local mods = self:get_combatant(side, index).stat_mods
  2228. if mods ~= nil and mods.eva ~= nil then evade = evade + math.floor(evade * mods.eva / 100) end
  2229. return evade
  2230. end,
  2231. --- Gets the stats a damage formula needs from a combatant.
  2232. --
  2233. -- @param side {@see Battle.TargetGroup.PARTY} or {@see Battle.TargetGroup.ENEMIES}.
  2234. -- @param index Index in the party or enemy list.
  2235. -- @return A table with level, str (attack), def, mag, mdef, hp, hp_max, mp.
  2236. get_combat_stats = function(self, side, index)
  2237. local stats = self:get_base_combat_stats(side, index)
  2238. local mods = self:get_combatant(side, index).stat_mods
  2239. if mods ~= nil then
  2240. for kind, percent in pairs(mods) do
  2241. if stats[kind] ~= nil then stats[kind] = stats[kind] + math.floor(stats[kind] * percent / 100) end
  2242. end
  2243. end
  2244. return stats
  2245. end,
  2246. --- Changes a stat modifier of a combatant, a percentage (-100 to 100) of its stat as in ff7.exe (0x5c7e55).
  2247. -- The modifiers last until the end of the battle.
  2248. --
  2249. -- @param kind Stat: str, mag, def, mdef, eva or dex.
  2250. -- @param delta Percentage added to the modifier.
  2251. change_stat_mod = function(self, side, index, kind, delta)
  2252. local combatant = self:get_combatant(side, index)
  2253. combatant.stat_mods = combatant.stat_mods or {}
  2254. combatant.stat_mods[kind] = math.max(-100, math.min(100, (combatant.stat_mods[kind] or 0) + delta))
  2255. end,
  2256. --- Gets the stats of a combatant without the modifiers of the limits. See {@see get_combat_stats}.
  2257. get_base_combat_stats = function(self, side, index)
  2258. if side == Battle.TargetGroup.PARTY then
  2259. local char = Characters[self.party[index].character]
  2260. local stats = char.stats
  2261. local str = stats.str.total or stats.str.base or 1
  2262. if char.weapon ~= nil and char.weapon.attack ~= nil then str = str + char.weapon.attack end
  2263. -- Defense, magic defense and the evasions include the armor (Characters.recalculate_stats).
  2264. return {
  2265. level = char.level or 1, str = str,
  2266. def = stats.def or stats.vit.total or stats.vit.base or 0,
  2267. mag = stats.mag.total or stats.mag.base or 1,
  2268. mdef = stats.mdef or stats.spr.total or stats.spr.base or 0,
  2269. dex = stats.dex.total or stats.dex.base or 0, eva = stats.eva or 0, meva = stats.meva or 0,
  2270. hp = stats.hp.current, hp_max = self:get_stat_max(stats.hp),
  2271. mp = stats.mp.current, mp_max = self:get_stat_max(stats.mp),
  2272. }
  2273. end
  2274. local enemy = self.enemies[index]
  2275. return {
  2276. level = enemy.level, str = enemy.stats.str, def = enemy.stats.def, mag = enemy.stats.mag,
  2277. mdef = enemy.stats.spr, hp = enemy.stats.hp, hp_max = enemy.stats.hp_max, mp = enemy.stats.mp,
  2278. mp_max = enemy.stats.mp_max, dex = enemy.stats.dex or 0, eva = enemy.stats.eva or 0, meva = enemy.stats.meva or 0,
  2279. }
  2280. end,
  2281. --- Gets the luck of a combatant.
  2282. get_luck = function(self, side, index)
  2283. if side == Battle.TargetGroup.PARTY then
  2284. local stats = Characters[self.party[index].character].stats
  2285. return stats.lck.total or stats.lck.base or 0
  2286. end
  2287. return self.enemies[index].stats.lck or 0
  2288. end,
  2289. --- Checks if a combatant has Long Range materia: its attacks don't lose power from the rows.
  2290. has_long_range = function(self, side, index)
  2291. return side == Battle.TargetGroup.PARTY and self.party[index].independent ~= nil and self.party[index].independent.long_range
  2292. end,
  2293. --- Takes the use of All or Mega All of an action that was widened to all the targets.
  2294. --
  2295. -- @return False if it can't be paid anymore.
  2296. spend_all = function(self, action, attack)
  2297. if action.target_type ~= Battle.TargetType.GROUP or action.is_counter or action.sneak_attack then return true end
  2298. -- Actions that already hit all the targets.
  2299. if attack.target.default_multiple == 1 or (action.attack_id == nil and (action.command == 24 or action.command == 26)) then return true end
  2300. local member = self.party[action.actor]
  2301. if action.links ~= nil and (action.links.all or 0) > 0 and attack.target.toggle_multiple == 1 then
  2302. local used = member.all_used[action.attack_id] or 0
  2303. if used < action.links.all then
  2304. member.all_used[action.attack_id] = used + 1
  2305. return true
  2306. end
  2307. end
  2308. if self:mega_all_left(member) > 0 then
  2309. member.mega_all_used = member.mega_all_used + 1
  2310. return true
  2311. end
  2312. return false
  2313. end,
  2314. --- Gets the times a character can still use Mega All (All on every action) in this battle.
  2315. mega_all_left = function(self, member)
  2316. if member == nil or member.independent == nil then return 0 end
  2317. return member.independent.mega_all - (member.mega_all_used or 0)
  2318. end,
  2319. --- Looks for a party member that covers another one that was attacked: an ally with Cover materia
  2320. -- takes the attack, by chance, for a member with critical HP (a quarter of the maximum or less).
  2321. --
  2322. -- @return The index of the member that covers it, nil if nobody does.
  2323. find_cover = function(self, target)
  2324. local stats = self:get_combat_stats(Battle.TargetGroup.PARTY, target)
  2325. if self.party[target].dead or stats.hp > stats.hp_max / 4 then return nil end
  2326. for index = 1, #self.party do
  2327. local member = self.party[index]
  2328. if index ~= target and not member.dead and member.independent ~= nil and member.independent.cover > 0
  2329. and not self:is_frozen(Battle.TargetGroup.PARTY, index) and math.random() * 100 < member.independent.cover then
  2330. return index
  2331. end
  2332. end
  2333. return nil
  2334. end,
  2335. --- Checks if a combatant is in the back row.
  2336. is_back_row = function(self, side, index)
  2337. if side == Battle.TargetGroup.PARTY then return Characters[self.party[index].character].back_row == true end
  2338. return not battle_manager:get_enemy(index - 1):is_front()
  2339. end,
  2340. --- Gets how an enemy reacts to the elements of an attack.
  2341. --
  2342. -- @return The damage factor: 1 normal, 2 double, 0.5 half, 0 nullified, negative absorbed (it
  2343. -- heals), 10 or more kills, -10 or less heals everything. Party members react as their armor,
  2344. -- accessory and Elemental materia say (half, nullified or absorbed).
  2345. get_element_factor = function(self, attack, side, index)
  2346. if side == Battle.TargetGroup.PARTY then
  2347. local defense = self.party[index].effects.elements.defense
  2348. local factor = 1
  2349. for _, element in ipairs(attack.elements or {}) do
  2350. local mode = defense[element]
  2351. if mode == Characters.ELEMENT_MODE.ABSORB then factor = factor * -1
  2352. elseif mode == Characters.ELEMENT_MODE.NULLIFY then factor = 0
  2353. elseif mode == Characters.ELEMENT_MODE.HALF then factor = factor * 0.5
  2354. end
  2355. end
  2356. return factor
  2357. end
  2358. local source = battle_manager:get_enemy(index - 1)
  2359. local factor = 1
  2360. for _, element in ipairs(attack.elements or {}) do
  2361. for e = 0, source:get_element_count() - 1 do
  2362. if source:get_element(e) == element then factor = factor * source:get_element_factor(e) end
  2363. end
  2364. end
  2365. return factor
  2366. end,
  2367. --- Calculates the result of an attack on a target.
  2368. --
  2369. -- Formulas as in the original game: 1 is physical, 2 is magical (modifier 5 heals, 3 takes a
  2370. -- fraction of the current HP). Level attacks (8) only apply their effects, and some of formula 6 are done. The rest do no damage.
  2371. -- Hit chance, criticals, rows and defending are handled.
  2372. -- @param attack Attack data, as in {@see get_attack_data}.
  2373. -- @param target_count Number of targets of the action (several of them reduce the damage).
  2374. -- @return A table: hit (false if the attack misses), amount (positive damages, negative heals),
  2375. -- mp (true if the amount is for MP).
  2376. calculate_attack = function(self, attack, attacker_side, attacker_index, target_side, target_index, target_count)
  2377. local data = attack.damage
  2378. local formula, modifier, power = math.floor(data.formula or 0), math.floor(data.modifier or 0), data.power or 0
  2379. local result = {hit = true, amount = 0, mp = (data.damage_mp or 0) == 1, extra_mp = 0}
  2380. -- Fixed damage (Coin): it always hits and nothing changes it.
  2381. if data.fixed_damage ~= nil then
  2382. result.amount = data.fixed_damage
  2383. return result
  2384. end
  2385. local is_item = attack.item == true
  2386. -- Limit breaks (11) are physical attacks that check the hit chance but never are critical.
  2387. local no_critical = false
  2388. if formula == 11 then formula = 1; no_critical = true end
  2389. -- Level attacks (L4 Suicide, L5 Death...): the accuracy holds the divisor, and they only affect
  2390. -- the targets whose level is a multiple of it (a divisor of 0 affects all). Then they do the
  2391. -- damage of their modifier (L4 Suicide: 31/32 of the current HP) and apply their effects.
  2392. local level_attack = formula == 8
  2393. if level_attack then
  2394. local divisor = math.floor((data.accuracy or 0) * 255 + 0.5)
  2395. local level = self:get_combat_stats(target_side, target_index).level
  2396. if divisor > 0 and level % divisor ~= 0 then
  2397. result.hit = false
  2398. return result
  2399. end
  2400. formula = 2
  2401. data = {formula = 2, modifier = modifier, power = power, accuracy = 1}
  2402. end
  2403. -- Accuracy is stored as the original byte divided by 255 (older installs stored 0 or 1, so 0 is treated
  2404. -- as 1). Only the physical (1, 6, 10) and the magical (2, 7) formulas roll to hit, as in ff7.exe.
  2405. local byte = (data.accuracy or 1) <= 0 and 255 or math.floor((data.accuracy or 1) * 255 + 0.5)
  2406. local element = self:get_element_factor(attack, target_side, target_index)
  2407. if not self:roll_hit(formula, byte, attacker_side, attacker_index, target_side, target_index, element, data.no_damage and 1 or power) then
  2408. result.hit = false
  2409. return result
  2410. end
  2411. local a = self:get_combat_stats(attacker_side, attacker_index)
  2412. local t = self:get_combat_stats(target_side, target_index)
  2413. local amount = 0
  2414. local revives = self:attack_revives(attack)
  2415. if is_item then
  2416. local restores_mp = (data.restore or 0) == 1
  2417. if formula == 2 and modifier == 6 then
  2418. amount = -power * 20
  2419. result.mp = restores_mp
  2420. elseif formula == 2 and modifier == 4 then
  2421. result.mp = restores_mp
  2422. amount = -((restores_mp and t.mp_max or t.hp_max) * power / 32)
  2423. elseif formula == 0 and modifier == 8 then
  2424. -- Elixirs restore all HP and MP.
  2425. amount = -(t.hp_max - t.hp)
  2426. result.extra_mp = -(t.mp_max - t.mp)
  2427. elseif formula == 3 and modifier == 7 then
  2428. -- Original: power * (512 - defense) / 32.
  2429. amount = power * (512 - math.min(t.def, 511)) / 32
  2430. elseif formula == 2 and modifier == 3 then
  2431. amount = t.hp * power / 32
  2432. end
  2433. elseif formula == 1 then
  2434. local str = a.str + (data.attack_bonus or 0)
  2435. local base = str + ((a.level + str) / 32) * ((a.level * str) / 32)
  2436. amount = base * (512 - math.min(t.def, 511)) * power / (16 * 512)
  2437. -- Small characters hit for almost nothing.
  2438. -- Original: Berserk x1.5, Frog /4, Small 0 (so 1).
  2439. if self:has_status(attacker_side, attacker_index, BattleStatus.SMALL) then amount = 1
  2440. elseif self:has_status(attacker_side, attacker_index, BattleStatus.FROG) then amount = amount / 4
  2441. end
  2442. if self:has_status(attacker_side, attacker_index, BattleStatus.BERSERK) then amount = amount * 1.5 end
  2443. elseif formula == 6 then
  2444. -- Special attacks, as in the original game. TODO: Chocobuckle (6, 9) and Time Damage
  2445. -- (6, 11) read counters of the savegame (escapes and play time), and do no damage yet.
  2446. local target_char = target_side == Battle.TargetGroup.PARTY and Characters[self.party[target_index].character] or nil
  2447. if modifier == 0 then amount = -a.hp -- White Wind: the HP of the caster.
  2448. elseif modifier == 1 then amount = a.hp_max - a.hp -- ????: the HP the caster is missing.
  2449. elseif modifier == 10 then amount = t.hp - 1 -- Heartless Angel: leaves 1 HP.
  2450. elseif modifier == 12 then -- Everyone's Grudge: 10 per kill of a party member.
  2451. amount = target_char ~= nil and (target_char.kills or 0) * 10 or 0
  2452. elseif modifier == 13 then -- Aire Tam Storm: 1111 per materia the target has equipped.
  2453. local count = 0
  2454. if target_char ~= nil then
  2455. for _, equip in ipairs({target_char.weapon, target_char.armor}) do
  2456. for m = 0, 7 do
  2457. if equip ~= nil and equip.materia ~= nil and equip.materia[m] ~= nil then count = count + 1 end
  2458. end
  2459. end
  2460. end
  2461. amount = count * 1111
  2462. end
  2463. elseif formula == 2 then
  2464. -- Magical attack stat (mag + level) * 6, not the physical one.
  2465. if data.mp_damage then result.mp = true end
  2466. local sum = (a.mag + a.level) * 6
  2467. local restores = (data.restore or 0) == 1
  2468. if revives then
  2469. -- Life and Life2: a fraction of the maximum HP, a quarter if the power is unknown.
  2470. amount = -t.hp_max * (power > 0 and power or 8) / 32
  2471. elseif modifier == 5 then amount = -(sum + power * 22) -- Cure: (mag + level) * 6 + power * 22.
  2472. elseif modifier == 3 then amount = (result.mp and t.mp or t.hp) * power / 32
  2473. elseif modifier == 4 then
  2474. amount = (result.mp and t.mp_max or t.hp_max) * power / 32
  2475. if restores then amount = -amount end
  2476. elseif modifier == 6 then
  2477. amount = power * 20
  2478. if restores then amount = -amount end
  2479. elseif modifier == 7 then amount = power * (512 - math.min(t.def, 511)) / 32
  2480. else amount = sum * (512 - math.min(t.mdef, 511)) * power / (16 * 512)
  2481. end
  2482. end
  2483. -- MP Turbo adds a percent of power to the damage and the healing.
  2484. if amount ~= 0 and (data.power_bonus or 0) > 0 then amount = amount * (100 + data.power_bonus) / 100 end
  2485. -- Spread: attacks that hit several targets (but not the ones that always do) do 2/3 of the
  2486. -- damage. Original: physical, Cure and magic (unless it can only be aimed at all).
  2487. if amount ~= 0 and (target_count or 1) >= 2 and (formula == 1 or (formula == 2 and (modifier == 1 or modifier == 2 or modifier == 5)))
  2488. and (attack.target.random or 0) ~= 1
  2489. and not (formula == 2 and modifier ~= 5 and (attack.target.default_multiple or 0) == 1 and (attack.target.toggle_multiple or 0) == 0) then
  2490. amount = amount * 2 / 3
  2491. end
  2492. if amount ~= 0 and formula ~= 6 and (modifier == 1 or modifier == 2 or modifier == 5 or modifier == 7 or modifier == 9) and not (is_item and formula ~= 3) then amount = amount * (15 + math.random()) / 16 end
  2493. if amount > 0 and formula == 1 and not is_item then
  2494. -- Criticals double the damage. The chance is (luck + level - target level) / 4 percent,
  2495. -- plus the one of the weapon.
  2496. local chance = math.max(0, (self:get_luck(attacker_side, attacker_index) + a.level - t.level) / 4) + (data.critical or 0)
  2497. if not no_critical and ((data.always_critical or 0) == 1 or math.random() * 100 < chance) then
  2498. amount = amount * 2
  2499. result.critical = true
  2500. end
  2501. -- A defending target takes half of the physical damage (the exe halves only the physical one).
  2502. if self:is_defending(target_side, target_index) then amount = amount / 2 end
  2503. -- Short range attacks do half the damage from or to the back row.
  2504. if (attack.target.short_range or 0) == 1 and not self:has_long_range(attacker_side, attacker_index)
  2505. and (self:is_back_row(attacker_side, attacker_index) or self:is_back_row(target_side, target_index)) then
  2506. amount = amount / 2
  2507. end
  2508. end
  2509. -- Barriers halve the damage of physical attacks, and magic barriers the one of magic.
  2510. if amount > 0 then
  2511. if formula == 1 and self:has_status(target_side, target_index, BattleStatus.BARRIER) then amount = amount / 2 end
  2512. if formula == 2 and self:has_status(target_side, target_index, BattleStatus.M_BARRIER) then amount = amount / 2 end
  2513. if self:has_status(target_side, target_index, BattleStatus.SADNESS) then amount = amount * 0.7 end
  2514. -- Peerless can't be hurt.
  2515. if self:has_status(target_side, target_index, BattleStatus.PEERLESS) then amount = 0 end
  2516. end
  2517. local factor = self:get_element_factor(attack, target_side, target_index)
  2518. if factor >= 10 then amount = t.hp_max
  2519. elseif factor <= -10 then amount = -t.hp_max
  2520. elseif amount > 0 or factor < 0 then
  2521. -- Absorbed attacks heal, whatever they were doing.
  2522. amount = (amount == 0 and 0 or math.abs(amount)) * factor
  2523. end
  2524. if amount > 0 then result.amount = math.min(9999, math.max(1, math.floor(amount)))
  2525. elseif amount < 0 then result.amount = math.min(-1, math.ceil(amount))
  2526. end
  2527. if result.extra_mp < 0 then result.extra_mp = math.ceil(result.extra_mp) end
  2528. return result
  2529. end,
  2530. --- Checks if a party slot has a character with data, so it can fight.
  2531. --
  2532. -- @param id Character ID in the party slot, nil if empty.
  2533. -- @return True if the character can be loaded into the battle.
  2534. has_character_data = function(self, id)
  2535. if id == nil then return false end
  2536. if Characters[id] == nil or Characters[id].stats == nil then
  2537. print("Battle: no data for the party character " .. tostring(id) .. ", it won't fight.")
  2538. return false
  2539. end
  2540. return true
  2541. end,
  2542. --- Gets a combatant from its side and index.
  2543. get_combatant = function(self, side, index)
  2544. if side == Battle.TargetGroup.PARTY then return self.party[index] end
  2545. return self.enemies[index]
  2546. end,
  2547. --- Checks if a combatant has a status.
  2548. has_status = function(self, side, index, id)
  2549. local combatant = self:get_combatant(side, index)
  2550. return combatant ~= nil and combatant.status ~= nil and combatant.status[id] ~= nil
  2551. end,
  2552. --- Checks if a status stops the ATB of a combatant.
  2553. is_frozen = function(self, side, index)
  2554. for id, _ in pairs(BattleStatus.FROZEN) do
  2555. if self:has_status(side, index, id) then return true end
  2556. end
  2557. return false
  2558. end,
  2559. --- Gets how fast the ATB of a combatant fills: 1 is normal, 0 is stopped.
  2560. get_atb_rate = function(self, side, index)
  2561. if self:is_frozen(side, index) then return 0 end
  2562. -- A manipulated enemy only acts on the turns of its controller.
  2563. if side == Battle.TargetGroup.ENEMIES and self.enemies[index] ~= nil and self.enemies[index].manipulated_by ~= nil then return 0 end
  2564. local rate = 1
  2565. if self:has_status(side, index, BattleStatus.HASTE) then rate = rate * 2 end
  2566. if self:has_status(side, index, BattleStatus.SLOW) then rate = rate * 0.5 end
  2567. return rate
  2568. end,
  2569. --- Gets the base step of the battle clock, from the battle speed of the configuration (0 fast to 10 slow).
  2570. -- It is the B of {@see get_atb_speed}.
  2571. get_battle_base = function(self)
  2572. local speed = 5
  2573. if MenuSettings ~= nil and MenuSettings.config ~= nil then speed = MenuSettings.config.battle_speed or 5 end
  2574. return 65536 / (2 * (120 + (speed * 255 / 10) * 480 / 256))
  2575. end,
  2576. --- Gets how many time units per second a timed status of a combatant counts down.
  2577. --
  2578. -- As in ff7.exe (0x4351da and 0x433932): Stop uses the base step B, Paralysis, Barrier, Sleep, Regen,
  2579. -- Shield and the others the step of the combatant (B x 2, x 4 with haste, x 1 with slow or stop), and
  2580. -- Slow-numb and Death Sentence use 34 x the same factor, with units of 4096 instead of 8192.
  2581. get_status_speed = function(self, side, index, id)
  2582. local base = self:get_battle_base()
  2583. local factor = 2
  2584. if self:has_status(side, index, BattleStatus.SLOW) then factor = 1
  2585. elseif self:has_status(side, index, BattleStatus.HASTE) then factor = 4
  2586. end
  2587. if self:has_status(side, index, BattleStatus.STOP) then factor = 1 end
  2588. local steps = self.ATB_STEPS_PER_SECOND
  2589. if id == BattleStatus.STOP then return steps * base / 8192 end
  2590. if id == BattleStatus.D_SENTENCE or id == BattleStatus.SLOW_NUMB then return steps * (34 * factor) / 4096 end
  2591. return steps * (base * factor) / 8192
  2592. end,
  2593. --- ATB steps per second (the speed formula of the original game is per step). Tuned by feel, not
  2594. -- read from the exe: the old battle.lua used 30, which was too slow in game, and 72 (30 * 2.4)
  2595. -- was confirmed as the right speed on 2026-11-17.
  2596. ATB_STEPS_PER_SECOND = 72,
  2597. --- Gets how much the ATB of a combatant fills per second, in the scale used here (0 to 255).
  2598. --
  2599. -- As in the original game (ff7.exe 0x433932 and 0x43853c). The ATB has 65535 steps, and each
  2600. -- step adds (dex + 50 for the party, dex for enemies) * 2 * rate * base / average, where base is
  2601. -- 65536 / (2 * (120 + battle speed * 480 / 256)) and the average is the average dex of the
  2602. -- enemies plus 50 (so strong enemies slow the party down). The rate is 1 normally, 2 with haste
  2603. -- and 0.5 with slow.
  2604. get_atb_speed = function(self, side, index)
  2605. local rate = self:get_atb_rate(side, index)
  2606. if rate <= 0 then return 0 end
  2607. local base = self:get_battle_base()
  2608. local dex
  2609. if side == Battle.TargetGroup.PARTY then
  2610. dex = Characters[self.party[index].character].stats.dex.total + 50
  2611. else
  2612. dex = self.enemies[index].stats.dex
  2613. end
  2614. local average = self.enemy_dex_average or 50
  2615. local per_step = dex * 2 * rate * base / average
  2616. return per_step * self.ATB_STEPS_PER_SECOND / 257
  2617. end,
  2618. --- Gets the name of a combatant, for messages.
  2619. get_combatant_name = function(self, side, index)
  2620. if side == Battle.TargetGroup.PARTY then return Characters[self.party[index].character].name end
  2621. return self.enemies[index].name
  2622. end,
  2623. --- Gives a status to a combatant, or renews it if it already has it.
  2624. set_status = function(self, side, index, id)
  2625. local combatant = self:get_combatant(side, index)
  2626. local now = timer:get_game_time_total()
  2627. local units = BattleStatus.UNITS[id]
  2628. if combatant.status[id] == nil then
  2629. print(self:get_combatant_name(side, index) .. " gets " .. (BattleStatus.NAME[id] or tostring(id)))
  2630. -- Good statuses are shown in a different colour than bad ones.
  2631. local good = id == BattleStatus.HASTE or id == BattleStatus.REGEN or id == BattleStatus.BARRIER
  2632. or id == BattleStatus.M_BARRIER or id == BattleStatus.REFLECT or id == BattleStatus.SHIELD
  2633. or id == BattleStatus.DUAL or id == BattleStatus.PEERLESS
  2634. UiContainer.BattleFx:text(side, index, BattleStatus.NAME[id] or tostring(id), good and {0.5, 1, 0.8} or {0.9, 0.5, 1})
  2635. end
  2636. combatant.status[id] = {remaining = units, last = now, next_tick = now + BattleStatus.TICK}
  2637. self:save_lasting_status(side, index, id, true)
  2638. for _, other in ipairs(BattleStatus.REMOVES[id] or {}) do self:clear_status(side, index, other) end
  2639. -- Those that can't act lose the control of who manipulates them.
  2640. if side == Battle.TargetGroup.ENEMIES and BattleStatus.FROZEN[id] then self:release_manipulation(index) end
  2641. self:status_changed(side, index)
  2642. end,
  2643. --- Keeps Fury and Sadness in the status list of the character, as they remain after the battle.
  2644. save_lasting_status = function(self, side, index, id, present)
  2645. if side ~= Battle.TargetGroup.PARTY or (id ~= BattleStatus.FURY and id ~= BattleStatus.SADNESS) then do return end end
  2646. local char = Characters[self.party[index].character]
  2647. if char.status == nil then char.status = {} end
  2648. for key = #char.status, 1, -1 do
  2649. if char.status[key] == id then table.remove(char.status, key) end
  2650. end
  2651. if present then table.insert(char.status, id) end
  2652. end,
  2653. --- Kernel attacks that hold the data of limits, by the technique that the character refers to. Tifa's
  2654. -- limits (149 to 155) are the attacks 98 to 104 of the kernel. TODO: The other characters' limit data
  2655. -- is not in the kernel (ff7.exe loads it from somewhere else when the battle starts).
  2656. LIMIT_ATTACK_DATA = {[149] = 98, [150] = 99, [151] = 100, [152] = 101, [153] = 102, [154] = 103, [155] = 104},
  2657. --- Animations of the party models that are empty in battle.lgp (the limit ones come from magic.lgp).
  2658. LIMIT_MISSING_FIRST = 42,
  2659. LIMIT_MISSING_LAST = 51,
  2660. --- Files of magic.lgp with the animations of the limits, by the prefix of the model and the position of the
  2661. -- technique. The installer converts them into the animations "<prefix>_<file>_00" to "_07", that the scripts
  2662. -- of the limits refer to as the animations 44 to 51. Same table as LimitAnimationFiles in BattleDataInstaller.cpp.
  2663. LIMIT_ANIMATION_FILES = (function()
  2664. local cloud = {"blaver", "kyou", "limcl2", "limcl6", "limcl3", "limcl7", "limcl4"}
  2665. local barret = {"hvshot", "limbr5", "limbr2", "limbr6", "limbr3", "limbr7", "limbr4"}
  2666. return {
  2667. rt = cloud, si = cloud,
  2668. ru = {"limfast"},
  2669. rv = {"iyash", "limea5", "limea2", "limea6", "limea3", "kodo", "limea4"},
  2670. rw = {"limsled", "limrd5", "limsled", "limrd6", "limrd3", "limrd7", "limrd4"},
  2671. rx = {"limyf1", "limyf5", "limyf2", "limyf6", "limyf3", "limyf7", "limyf4"},
  2672. ry = {"dice"},
  2673. rz = {"limcd1", "limcd5", "limcd2", "limcd6", "limcd3", "limcd7", "limcd4"},
  2674. sb = barret, sc = barret, sd = barret, se = barret,
  2675. }
  2676. end)(),
  2677. --- Number of the first animation script of the limits in the models of the party (60 in ff7.exe).
  2678. LIMIT_FIRST_SCRIPT = 60,
  2679. --- Gets the animation script of a limit technique.
  2680. --
  2681. -- As in ff7.exe (0x5c9524), it is 60 plus the position of the technique among the ones of its character,
  2682. -- in the order of the limit levels. The scripts only exist in the models installed with the fixed
  2683. -- installer (before, the characters had 32 scripts and the limits are in 60 and up).
  2684. --
  2685. -- @param index Index in the party.
  2686. -- @param attack_id ID of the limit technique.
  2687. -- @return The script number, nil if the model has no script for it.
  2688. get_limit_script = function(self, index, attack_id)
  2689. local definition = Game.Characters[self.party[index].character]
  2690. if definition == nil then return nil end
  2691. local position = 0
  2692. for level = 1, 4 do
  2693. local limit = definition.limits[level]
  2694. for _, technique in ipairs(limit ~= nil and limit.techniques or {}) do
  2695. if technique.command == attack_id then
  2696. local number = self.LIMIT_FIRST_SCRIPT + position
  2697. local scripts = BattleAnimations.get_scripts(self:get_model_name(Battle.TargetGroup.PARTY, index))
  2698. local steps = scripts ~= nil and scripts[number] or nil
  2699. if steps == nil or #steps == 0 then return nil end
  2700. local prefix = battle_manager:get_party_animation_prefix(index - 1)
  2701. local files = self.LIMIT_ANIMATION_FILES[prefix]
  2702. local tag = files ~= nil and files[position + 1] or nil
  2703. if tag ~= nil then return number, tag end
  2704. -- The animations 42 to 51 of the models are empty: the limits of most characters keep theirs in
  2705. -- files of magic.lgp (limcl2.a00...) that are not installed yet, so those limits use the normal
  2706. -- attack animation (the missing animations would only print errors).
  2707. -- TODO: Install the limit animation files (see the memory notes).
  2708. for _, step in ipairs(steps) do
  2709. if step.type == "anim" and step.number >= self.LIMIT_MISSING_FIRST and step.number <= self.LIMIT_MISSING_LAST then
  2710. return nil
  2711. end
  2712. end
  2713. return number
  2714. end
  2715. position = position + 1
  2716. end
  2717. end
  2718. return nil
  2719. end,
  2720. --- Limits of formula 2 that are attacks, and use their data.
  2721. LIMIT_DATA_ATTACKS = {[137] = true}, -- Mindblow (Grenade Bomb, 136, is physical)
  2722. --- Limits whose damage goes to the MP of the targets (Mindblow).
  2723. LIMIT_MP_DAMAGE = {[137] = true},
  2724. --- Power of the limits that have no data and are not in SPECIAL_LIMITS (a normal attack of that power).
  2725. LIMIT_FALLBACK_POWER = 40,
  2726. --- Limits that are not attacks and are not in the kernel data, by the ID of the technique (the Aerith
  2727. -- ones). They always affect a whole side. TODO: The amounts are estimates, and they have no visual effects.
  2728. -- * target: "allies" or "enemies".
  2729. -- * heal: power of the healing, (magic + level) * 6 + power * 22 HP for each ally.
  2730. -- * full: HP and MP of the allies are filled.
  2731. -- * cure: statuses of the allies that are cured.
  2732. -- * statuses: statuses given to the targets (the enemies can be immune).
  2733. -- * limit_bar: the limit bars of the allies, except the user, are filled.
  2734. SPECIAL_LIMITS = {
  2735. [145] = {target = "allies", limit_bar = true}, -- Fury Brand
  2736. },
  2737. --- Gets the special limit (one that is not an attack) of a technique, nil if it is an attack.
  2738. --
  2739. -- The limits of the kernel data that only heal, restore, or give and cure statuses are built from their
  2740. -- data (ff7.exe, ids 128 to 183): formula 2 with modifier 2 is statuses only, 2 with modifier 4 heals a
  2741. -- fraction (power / 32) of the maximum HP, and 0 with modifier 8 restores everything. The ones in
  2742. -- SPECIAL_LIMITS are done by hand. Additional effects 22 and 23 (Red XIII) change stat modifiers of the user.
  2743. --
  2744. -- @param id Attack ID of the technique.
  2745. get_special_limit = function(self, id)
  2746. if self.SPECIAL_LIMITS[id] ~= nil then return self.SPECIAL_LIMITS[id] end
  2747. local k = id ~= nil and id >= 128 and Game.Attacks[id] or nil
  2748. if k == nil then return nil end
  2749. local f, m = k.dmg_formula, k.dmg_modifier
  2750. if not ((f == 2 and (m == 2 or m == 4)) or (f == 0 and m == 8)) then return nil end
  2751. if k.target == nil then return nil end
  2752. local special = {
  2753. target = k.target.default_enemy == 1 and "enemies" or "allies",
  2754. self_only = k.target.selectable == 0, statuses = {}, cures = {},
  2755. }
  2756. if f == 2 and m == 4 then special.heal_fraction = k.power end
  2757. if f == 0 and m == 8 then special.full = true end
  2758. -- Additional effects 22 (evade) and 23 (strength) change a stat modifier of the user by (modifier - 100) percent.
  2759. local additional = k.additional
  2760. if additional ~= nil and additional.modifier ~= nil then
  2761. local kinds = {[22] = "eva", [23] = "str"}
  2762. if kinds[additional.effect] ~= nil then
  2763. special.user_mods = {{kind = kinds[additional.effect], delta = additional.modifier - 100}}
  2764. end
  2765. end
  2766. for _, entry in ipairs(k.status or {}) do
  2767. if entry.mode == 1 then table.insert(special.cures, entry.status)
  2768. else table.insert(special.statuses, entry.status) end
  2769. end
  2770. return special
  2771. end,
  2772. --- Statuses that Breath of the Earth and Pulse of Life don't cure (the good ones, death and Near Death).
  2773. KEPT_STATUSES = {
  2774. [BattleStatus.DEATH] = true, [BattleStatus.NEAR_DEATH] = true, [BattleStatus.HASTE] = true,
  2775. [BattleStatus.REGEN] = true, [BattleStatus.BARRIER] = true, [BattleStatus.M_BARRIER] = true,
  2776. [BattleStatus.REFLECT] = true, [BattleStatus.DUAL] = true, [BattleStatus.SHIELD] = true,
  2777. [BattleStatus.PEERLESS] = true,
  2778. },
  2779. --- Runs one of the limits of SPECIAL_LIMITS: the character casts, and the effect lands at the end.
  2780. run_special_limit = function(self, current, action)
  2781. local special = self:get_special_limit(action.attack_id)
  2782. local index = action.actor
  2783. self:use_limit(action)
  2784. self:show_message(Game.Attacks[action.attack_id].name, true)
  2785. -- The effect is not a normal hit.
  2786. current.hit_done = true
  2787. current.pending = 1
  2788. local applied = false
  2789. local function apply()
  2790. if applied then return end
  2791. applied = true
  2792. -- The side of the limit, or the opposite one if the caster is confused.
  2793. local group = action.target_group
  2794. -- Curing Death (Pulse of Life) reaches the dead allies too.
  2795. for _, mod in ipairs(special.user_mods or {}) do
  2796. self:change_stat_mod(Battle.TargetGroup.PARTY, index, mod.kind, mod.delta)
  2797. end
  2798. local targets = current.targets
  2799. for _, id in ipairs(special.cures or {}) do
  2800. if id == BattleStatus.DEATH and group == Battle.TargetGroup.PARTY then
  2801. targets = {}
  2802. for i = 1, #self.party do table.insert(targets, i) end
  2803. end
  2804. end
  2805. for _, t in ipairs(targets) do
  2806. if special.heal ~= nil then
  2807. local stats = self:get_combat_stats(Battle.TargetGroup.PARTY, index)
  2808. local amount = (stats.mag + stats.level) * 6 + special.heal * 22
  2809. self:apply_damage(group, t, -amount, false)
  2810. end
  2811. if special.heal_fraction ~= nil then
  2812. local stats = self:get_combat_stats(group, t)
  2813. self:apply_damage(group, t, -math.floor(stats.hp_max * special.heal_fraction / 32), false)
  2814. end
  2815. -- Curing Death (Pulse of Life) brings the dead back.
  2816. for _, id in ipairs(special.cures or {}) do
  2817. if id == BattleStatus.DEATH and self:get_combatant(group, t).dead then self:revive(group, t) end
  2818. end
  2819. if special.full then
  2820. local stats = self:get_combat_stats(group, t)
  2821. self:apply_damage(group, t, -(stats.hp_max - stats.hp), false)
  2822. self:apply_damage(group, t, -(stats.mp_max - stats.mp), true)
  2823. end
  2824. for _, id in ipairs(special.cures or {}) do
  2825. if id ~= BattleStatus.DEATH then self:clear_status(group, t, id) end
  2826. end
  2827. if special.cure then
  2828. local ids = {}
  2829. for id, _ in pairs(self:get_combatant(group, t).status) do table.insert(ids, id) end
  2830. for _, id in ipairs(ids) do
  2831. if not self.KEPT_STATUSES[id] then self:clear_status(group, t, id) end
  2832. end
  2833. end
  2834. if special.statuses ~= nil and #special.statuses > 0 then
  2835. local effects = {}
  2836. for _, id in ipairs(special.statuses) do table.insert(effects, {id = id, chance = 1, mode = "inflict"}) end
  2837. self:apply_attack_effects({effects = effects}, group, t)
  2838. end
  2839. if special.limit_bar and t ~= index then
  2840. local char = Characters[self.party[t].character]
  2841. if char.limit ~= nil and not self.party[t].dead then
  2842. char.limit.bar = 255
  2843. self:update_limit(t)
  2844. end
  2845. end
  2846. end
  2847. end
  2848. local played = self:play_script(
  2849. Battle.TargetGroup.PARTY, index, self:get_script_number(Battle.TargetGroup.PARTY, index, "magic"), false,
  2850. apply, function() apply() current.pending = current.pending - 1 end, nil
  2851. )
  2852. if not played then
  2853. apply()
  2854. current.pending = 0
  2855. end
  2856. self:update_action(timer:get_game_time_total())
  2857. end,
  2858. --- Colours of the pink windows of the limits (top-left, top-right, bottom-right and bottom-left corner).
  2859. LIMIT_WINDOW_COLOURS = {{1, 0.55, 0.8}, {1, 0.4, 0.7}, {0.6, 0.12, 0.4}, {0.8, 0.25, 0.55}},
  2860. --- Sets the colours of a window of the battle: the pink ones of the limits, or the normal ones of the
  2861. -- configuration.
  2862. --
  2863. -- @param path Path of the window widget.
  2864. -- @param pink True for the limit colours.
  2865. set_window_pink = function(self, path, pink)
  2866. local colours = {}
  2867. if pink then
  2868. for _, corner in ipairs(self.LIMIT_WINDOW_COLOURS) do
  2869. for channel = 1, 3 do colours[#colours + 1] = corner[channel] end
  2870. end
  2871. else
  2872. local config = MenuSettings ~= nil and MenuSettings.config ~= nil and MenuSettings.config.window_colours or nil
  2873. config = config or {{0, 0, 178}, {0, 0, 127}, {0, 0, 32}, {0, 0, 79}}
  2874. for _, corner in ipairs(config) do
  2875. for channel = 1, 3 do colours[#colours + 1] = corner[channel] / 255 end
  2876. end
  2877. end
  2878. ui_manager:get_widget(path .. ".Center"):set_colours(
  2879. colours[1], colours[2], colours[3], colours[4], colours[5], colours[6],
  2880. colours[7], colours[8], colours[9], colours[10], colours[11], colours[12]
  2881. )
  2882. end,
  2883. --- Shows a text in the message window of the top of the screen.
  2884. --
  2885. -- @param text The message.
  2886. -- @param pink True for the pink window of the limits.
  2887. show_message = function(self, text, pink)
  2888. self:set_window_pink("BattleUi.Container.Message", pink == true)
  2889. ui_manager:get_widget("BattleUi.Container.Message.Name"):set_text(text)
  2890. -- The pink messages of the limit bars go away by themselves.
  2891. self.message_until = (pink == true and self.message_timed) and timer:get_game_time_total() + 2.5 or nil
  2892. self.message_timed = false
  2893. end,
  2894. --- Gets the statuses that a hit of an attack would cure on a target: the physical formulas wake up, cure
  2895. -- Confusion and end the manipulation (ff7.exe, 0x5ddb20). Magic doesn't.
  2896. --
  2897. -- @return A list of status IDs, empty if the attack isn't physical.
  2898. get_physical_cures = function(self, attack, side, index)
  2899. local formula = attack.damage.formula
  2900. local cures = {}
  2901. if formula == 1 or formula == 6 or formula == 10 or formula == 11 then
  2902. for _, id in ipairs({BattleStatus.SLEEP, BattleStatus.CONFUSION, BattleStatus.MANIPULATE}) do
  2903. if self:has_status(side, index, id) then table.insert(cures, id) end
  2904. end
  2905. end
  2906. return cures
  2907. end,
  2908. --- Cures the statuses that {@see get_physical_cures} gave.
  2909. apply_physical_cures = function(self, cures, side, index)
  2910. for _, id in ipairs(cures) do
  2911. if id == BattleStatus.MANIPULATE and side == Battle.TargetGroup.ENEMIES then self:release_manipulation(index) end
  2912. self:clear_status(side, index, id)
  2913. end
  2914. end,
  2915. --- Queues again the actions that a combatant kept while it couldn't act, if it can now.
  2916. release_held_actions = function(self, side, index)
  2917. local combatant = self:get_combatant(side, index)
  2918. if combatant == nil or combatant.held == nil or self:is_frozen(side, index) then return end
  2919. for _, action in ipairs(combatant.held) do table.insert(self.action_queue, action) end
  2920. combatant.held = nil
  2921. end,
  2922. --- Applies Berserk to the action of a party member when its turn comes: anything but a plain attack becomes
  2923. -- one, on a random enemy.
  2924. --
  2925. -- @param action The action, that is changed if needed.
  2926. -- @return False if the action is dropped (the first one of a double command).
  2927. apply_berserk = function(self, action)
  2928. if not self:has_status(Battle.TargetGroup.PARTY, action.actor, BattleStatus.BERSERK) then return true end
  2929. if action.command == 1 and action.attack_id == nil and action.item_id == nil then
  2930. action.automatic, action.links = true, nil
  2931. return true
  2932. end
  2933. if action.no_atb then return false end
  2934. action.target_index = self:random_living(Battle.TargetGroup.ENEMIES)
  2935. if action.target_index == nil then return false end
  2936. action.target_group = Battle.TargetGroup.ENEMIES
  2937. action.target_type = Battle.TargetType.SINGLE
  2938. action.type = Battle.ActionType.COMMAND
  2939. action.command = 1
  2940. action.automatic = true
  2941. action.limit, action.attack_id, action.item_id, action.target_list, action.links = nil, nil, nil, nil, nil
  2942. action.summon, action.throw_item, action.coin_gil = nil, nil, nil
  2943. return true
  2944. end,
  2945. --- Commands that a silenced character can't use (ff7.exe, 0x5dbde0): Magic, Summon, E.Skill, W-Magic and
  2946. -- W-Summon.
  2947. SILENCED_COMMANDS = {[2] = true, [3] = true, [13] = true, [21] = true, [22] = true},
  2948. --- Checks if Silence makes an action fail, as in ff7.exe: the commands of {@see SILENCED_COMMANDS} for a party
  2949. -- member, and the attacks that cost MP for an enemy.
  2950. --
  2951. -- @param action The action, with actor, actor_side (the party if nil) and command.
  2952. -- @param attack Attack data, as in {@see get_attack_data}.
  2953. is_silenced_action = function(self, action, attack)
  2954. local side = action.actor_side or Battle.TargetGroup.PARTY
  2955. if not self:has_status(side, action.actor, BattleStatus.SILENCE) then return false end
  2956. if side == Battle.TargetGroup.PARTY then return self.SILENCED_COMMANDS[action.command] == true end
  2957. return attack ~= nil and (attack.mp or 0) > 0
  2958. end,
  2959. --- Commands that a frog can use: Attack and Item. Their replacements (Slash-All, 2x-Cut, Flash, 4x-Cut,
  2960. -- Limit and W-Item) go back to them.
  2961. FROG_COMMANDS = {[1] = true, [4] = true},
  2962. --- The only spell a frog can cast (Toad, that cures it), and the commands to cast it with: Magic and
  2963. -- W-Magic (ff7.exe, 0x5dbde0).
  2964. FROG_SPELL = 10,
  2965. FROG_MAGIC_COMMANDS = {[2] = true, [21] = true},
  2966. --- Checks if a command can't be chosen because the character is a frog. Magic and W-Magic can if the
  2967. -- character has the Toad spell.
  2968. is_frog_blocked = function(self, index, command_id)
  2969. if self.FROG_COMMANDS[command_id] == true or not self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.FROG) then
  2970. return false
  2971. end
  2972. if self.FROG_MAGIC_COMMANDS[command_id] == true then
  2973. for _, spell in ipairs(self.party[index].magic or {}) do
  2974. if spell.id == self.FROG_SPELL then return false end
  2975. end
  2976. end
  2977. return true
  2978. end,
  2979. --- Applies Frog to the action of a party member when its turn comes: attacks with a replacement of the Attack
  2980. -- command and limits become plain attacks on one enemy (the limit bar is kept), W-Item uses only the second
  2981. -- item, and any other command but Attack, Item and the casts of Toad fails.
  2982. --
  2983. -- @param action The action, that is changed if needed.
  2984. -- @return False if the action fails.
  2985. apply_frog = function(self, action)
  2986. if not self:has_status(Battle.TargetGroup.PARTY, action.actor, BattleStatus.FROG) then return true end
  2987. local command = action.command
  2988. if command == 23 then
  2989. -- The first of the two doesn't end the turn, so it is the one that is lost.
  2990. if action.no_atb then return false end
  2991. action.command = 4
  2992. return true
  2993. end
  2994. if action.limit ~= nil or command == 20 or (command ~= nil and command >= 24 and command <= 27) then
  2995. if action.target_group ~= Battle.TargetGroup.ENEMIES or action.target_index == nil then
  2996. action.target_index = self:random_living(Battle.TargetGroup.ENEMIES)
  2997. if action.target_index == nil then return false end
  2998. end
  2999. action.target_group = Battle.TargetGroup.ENEMIES
  3000. action.target_type = Battle.TargetType.SINGLE
  3001. action.type = Battle.ActionType.COMMAND
  3002. action.command = 1
  3003. action.limit, action.attack_id, action.target_list, action.links = nil, nil, nil, nil
  3004. return true
  3005. end
  3006. if self.FROG_MAGIC_COMMANDS[command] == true then return action.attack_id == self.FROG_SPELL end
  3007. return self.FROG_COMMANDS[command] == true
  3008. end,
  3009. --- Changes the commands of a party member that depend on its state: Limit takes the place of Attack when the
  3010. -- limit bar is full, and a frog only has the plain Attack and Item ones.
  3011. update_commands = function(self, index)
  3012. local member = self.party[index]
  3013. if member.attack_command == nil then return end
  3014. local frog = self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.FROG)
  3015. local limit = Characters[member.character].limit
  3016. local first = member.attack_command
  3017. if frog then first = 1
  3018. elseif limit ~= nil and (limit.bar or 0) >= 255 and self:has_limit_techniques(index) then first = 20
  3019. end
  3020. member.command[1] = first
  3021. if member.item_slot ~= nil then member.command[member.item_slot] = frog and 4 or member.item_command end
  3022. -- If the commands of this character are on the screen, they change on the spot.
  3023. if self.current_character_window == index and member.manip_commands == nil
  3024. and (self.window_state == "command" or self.window_state == "change" or self.window_state == "defend") then
  3025. for c = 1, 12 do
  3026. if member.command[c] ~= nil then self:set_command_widget(index, c, member.command[c]) end
  3027. end
  3028. end
  3029. end,
  3030. --- Writes a command in its place of the command window, grey if it can't be used.
  3031. set_command_widget = function(self, index, position, command_id)
  3032. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(position))
  3033. -- The colour goes before the text. Manipulate is not available while controlling an enemy.
  3034. if self:is_frog_blocked(index, command_id)
  3035. or (command_id == self.MANIP_COMMAND and self.party[index].manipulating ~= nil) then
  3036. widget:set_colour(0.5, 0.5, 0.5)
  3037. else
  3038. widget:set_colour(1, 1, 1)
  3039. end
  3040. widget:set_text(Game.Commands[command_id].name)
  3041. end,
  3042. --- Message of ff7.exe (battle text 91) for a character that can't pay a spell.
  3043. NOT_ENOUGH_MP = "Not enough MP!!",
  3044. --- Shows a message that goes away by itself after a moment.
  3045. show_timed_message = function(self, text)
  3046. self:show_message(text)
  3047. self.message_until = timer:get_game_time_total() + 2
  3048. end,
  3049. --- Takes from an enemy the MP of an attack, as ff7.exe does for every combatant (0x5dbde0).
  3050. --
  3051. -- @param index Index of the enemy.
  3052. -- @param attack Attack data, as in {@see get_attack_data}.
  3053. -- @return False if the enemy doesn't have enough MP: nothing is taken, and the attack fails.
  3054. pay_enemy_mp = function(self, index, attack)
  3055. local cost = attack.mp or 0
  3056. if cost <= 0 then return true end
  3057. local stats = self.enemies[index].stats
  3058. if stats.mp < cost then return false end
  3059. stats.mp = stats.mp - cost
  3060. return true
  3061. end,
  3062. --- Damage divisor of the limit bar by limit level, only for installs without the ones of the characters
  3063. -- (Game.Characters[id].limit_divisors). As in ff7.exe (0x5df1b0) the bar gets damage * 300 / maximum HP * 256 /
  3064. -- divisor (x2 with Fury, half with Sadness).
  3065. LIMIT_DIVISOR = {150, 200, 250, 300},
  3066. --- Checks if a party member has a limit technique that it can use: one that was learned in its limit level.
  3067. has_limit_techniques = function(self, index)
  3068. local char = Characters[self.party[index].character]
  3069. local learned = char.limit ~= nil and char.limit.learned ~= nil and char.limit.learned[char.limit.current] or nil
  3070. if learned == nil then return false end
  3071. for _, value in pairs(learned) do if value == true then return true end end
  3072. return false
  3073. end,
  3074. --- Fills the limit bar of a party member with the damage it takes from the enemies.
  3075. --
  3076. -- @param index Index in the party.
  3077. -- @param damage HP lost.
  3078. add_limit = function(self, index, damage)
  3079. local member = self.party[index]
  3080. local char = Characters[member.character]
  3081. if member.dead or char.limit == nil or damage <= 0 then return end
  3082. local stats = self:get_combat_stats(Battle.TargetGroup.PARTY, index)
  3083. local gain = math.floor(damage * 300 / math.max(1, stats.hp_max))
  3084. local factor = 1
  3085. if self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.FURY) then factor = 2
  3086. elseif self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.SADNESS) then factor = 0.5
  3087. end
  3088. local definition = Game.Characters[member.character]
  3089. local divisors = definition ~= nil and definition.limit_divisors or self.LIMIT_DIVISOR
  3090. local divisor = divisors[char.limit.current] or divisors[1]
  3091. char.limit.bar = math.min(255, (char.limit.bar or 0) + math.floor(gain * 256 * factor / divisor))
  3092. self:update_limit(index)
  3093. end,
  3094. --- Shows the limit bar of a party member (blue with Sadness, red with Fury), and puts the Limit command
  3095. -- in place of the Attack one when the bar is full and the character has a limit to use.
  3096. update_limit = function(self, index)
  3097. local member = self.party[index]
  3098. local char = Characters[member.character]
  3099. if char.limit == nil then
  3100. self:update_commands(index)
  3101. return
  3102. end
  3103. local bar = char.limit.bar or 0
  3104. -- The message of a limit bar that has just got full (not at the start of the battle).
  3105. local full = bar >= 255
  3106. if member.limit_full == false and full then
  3107. self.message_timed = true
  3108. self:show_message(self:get_combatant_name(Battle.TargetGroup.PARTY, index) .. " limit break!", true)
  3109. end
  3110. member.limit_full = full
  3111. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(index) .. ".Right.LimitFill")
  3112. local width_percent = math.min(18, 18 * bar / 255)
  3113. widget:set_width(width_percent, math.max(-6, -6 * width_percent / 18))
  3114. if self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.SADNESS) then widget:set_colour(0.4, 0.6, 1)
  3115. elseif self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.FURY) then widget:set_colour(1, 0.3, 0.3)
  3116. else widget:set_colour(1, 0, 1)
  3117. end
  3118. self:update_commands(index)
  3119. end,
  3120. --- Colours of the full limit bar, that flashes between them.
  3121. LIMIT_FLASH_COLOURS = {{1, 0, 1}, {0.4, 0.6, 1}, {1, 0.3, 0.3}},
  3122. --- Makes the full limit bars flash, and the "Limit" command change colours.
  3123. --
  3124. -- A full bar goes through its regular colour, blue and red (whatever status the character has). The
  3125. -- "Limit" command goes through the colours of the rainbow.
  3126. -- TODO: The fields have a rainbow with a colour for each letter in their dialogs (the installer writes it
  3127. -- from the original text codes), but the engine can't draw it yet: here all the word has the same colour.
  3128. update_limit_flash = function(self, now)
  3129. local step = math.floor(now * 15)
  3130. if step == self.limit_flash_step then return end
  3131. self.limit_flash_step = step
  3132. local phase = math.floor(now * 4) % 3 + 1
  3133. for index = 1, #self.party do
  3134. local char = Characters[self.party[index].character]
  3135. if char.limit ~= nil and (char.limit.bar or 0) >= 255 and not self.party[index].dead then
  3136. local colour = self.LIMIT_FLASH_COLOURS[phase]
  3137. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(index) .. ".Right.LimitFill"):set_colour(colour[1], colour[2], colour[3])
  3138. end
  3139. end
  3140. -- The command Limit of the character that is choosing.
  3141. local current = self.current_character_window
  3142. if (self.window_state == "command" or self.window_state == "change" or self.window_state == "defend") and current ~= nil
  3143. and self.party[current] ~= nil and self.party[current].manip_commands == nil then
  3144. for c = 1, 12 do
  3145. if self.party[current].command[c] == 20 then
  3146. local hue = (now * 1.5) % 1
  3147. local r = math.max(0, math.min(1, math.abs(hue * 6 - 3) - 1))
  3148. local g = math.max(0, math.min(1, 2 - math.abs(hue * 6 - 2)))
  3149. local b = math.max(0, math.min(1, 2 - math.abs(hue * 6 - 4)))
  3150. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(c))
  3151. widget:set_colour(r, g, b)
  3152. widget:set_text(Game.Commands[20].name)
  3153. end
  3154. end
  3155. end
  3156. end,
  3157. --- Uses the limit bar: it is emptied, and the uses of the first technique of the level unlock the second one.
  3158. use_limit = function(self, action)
  3159. local member = self.party[action.actor]
  3160. local char = Characters[member.character]
  3161. local level, technique = action.limit.level, action.limit.index
  3162. char.limit.bar = 0
  3163. if technique == 1 then
  3164. char.limit.uses[level] = (char.limit.uses[level] or 0) + 1
  3165. local definition = Game.Characters[member.character]
  3166. local second = definition ~= nil and definition.limits[level] ~= nil and definition.limits[level].techniques[2] or nil
  3167. if second ~= nil and second.uses ~= nil and second.uses > 0 and char.limit.uses[level] >= second.uses
  3168. and not char.limit.learned[level][2] then
  3169. char.limit.learned[level][2] = true
  3170. print(char.name .. " learns the second limit of level " .. tostring(level))
  3171. self:announce_limit(member.character, second.command)
  3172. end
  3173. end
  3174. self:update_limit(action.actor)
  3175. end,
  3176. --- Sets or clears Near Death in a combatant, depending on its HP: it has it with a quarter of the
  3177. -- maximum HP or less (and some HP left), as in ff7.exe (0x5c7d37). It isn't announced, and it ends by
  3178. -- itself when the HP is back. The HP of the party is shown in yellow while it lasts.
  3179. update_near_death = function(self, side, index)
  3180. local combatant = self:get_combatant(side, index)
  3181. if combatant == nil or combatant.dead or combatant.status == nil then return end
  3182. local stats = self:get_combat_stats(side, index)
  3183. local critical = stats.hp > 0 and stats.hp <= stats.hp_max / 4
  3184. local has = combatant.status[BattleStatus.NEAR_DEATH] ~= nil
  3185. if critical and not has then
  3186. combatant.status[BattleStatus.NEAR_DEATH] = {next_tick = timer:get_game_time_total() + BattleStatus.TICK}
  3187. self:status_changed(side, index)
  3188. elseif not critical and has then
  3189. combatant.status[BattleStatus.NEAR_DEATH] = nil
  3190. self:status_changed(side, index)
  3191. end
  3192. end,
  3193. --- Cures a status of a combatant.
  3194. clear_status = function(self, side, index, id)
  3195. local combatant = self:get_combatant(side, index)
  3196. if combatant.status[id] == nil then do return end end
  3197. combatant.status[id] = nil
  3198. self:save_lasting_status(side, index, id, false)
  3199. print(self:get_combatant_name(side, index) .. " is cured of " .. (BattleStatus.NAME[id] or tostring(id)))
  3200. self:status_changed(side, index)
  3201. end,
  3202. --- Updates what depends on the statuses of a combatant after they change.
  3203. status_changed = function(self, side, index)
  3204. self:release_held_actions(side, index)
  3205. if side == Battle.TargetGroup.PARTY then
  3206. -- Someone that can't act, or that acts by itself, can't choose a command.
  3207. if self:is_frozen(side, index) or self:acts_by_itself(side, index) then self:remove_from_command_queue(index) end
  3208. self:update_name_colours()
  3209. self:update_limit(index)
  3210. end
  3211. end,
  3212. --- Removes a party member from the queue of members that have to choose a command.
  3213. --
  3214. -- If the member was choosing, the command windows are closed.
  3215. remove_from_command_queue = function(self, index)
  3216. for i = #self.command_queue, 1, -1 do
  3217. if self.command_queue[i] == index then table.remove(self.command_queue, i) end
  3218. end
  3219. if self.current_character_window == index and self.window_state ~= "wait" and self.window_state ~= "result" and self.window_state ~= "gameover" then
  3220. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  3221. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  3222. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  3223. ui_manager:get_widget("BattleUi.Container.Bottom.Change"):set_visible(false)
  3224. ui_manager:get_widget("BattleUi.Container.Bottom.Defend"):set_visible(false)
  3225. self.current_list = "none"
  3226. self.window_state = "wait"
  3227. end
  3228. end,
  3229. --- Checks if a combatant is immune to a status. Party members are protected by their
  3230. -- accessory and by Added Effect materia linked in the armor.
  3231. is_immune = function(self, side, index, id)
  3232. if side == Battle.TargetGroup.PARTY then return self.party[index].effects.status.defense[id] == true end
  3233. local source = battle_manager:get_enemy(index - 1)
  3234. for i = 0, source:get_immunity_count() - 1 do
  3235. if source:get_immunity(i) == id and math.random() < source:get_immunity_rate(i) then return true end
  3236. end
  3237. return false
  3238. end,
  3239. --- Rolls if the statuses of an attack work on a target, as in ff7.exe (0x5dc099). The chance of the data is
  3240. -- a byte from 0 to 63 and it is worth 4 percent points each: 63 always works. MP Turbo raises it, and attacks
  3241. -- split between several targets lose a third of it. Removing Frog or Small from who has it always works, and so
  3242. -- do Haste, Shield and Berserk on party members.
  3243. --
  3244. -- @param attack Attack data, as in {@see get_attack_data}, with at least one effect.
  3245. -- @param target_count Number of targets of the action, one if nil.
  3246. -- @return True if the statuses work.
  3247. roll_status = function(self, attack, side, index, target_count)
  3248. local effects = attack.effects
  3249. local points = math.floor(math.abs(effects[1].chance) * 63 + 0.5) * 4
  3250. if #effects == 1 and (effects[1].id == BattleStatus.FROG or effects[1].id == BattleStatus.SMALL)
  3251. and self:has_status(side, index, effects[1].id) then
  3252. return true
  3253. end
  3254. if side == Battle.TargetGroup.PARTY then
  3255. for _, effect in ipairs(effects) do
  3256. if effect.id == BattleStatus.HASTE or effect.id == BattleStatus.SHIELD or effect.id == BattleStatus.BERSERK then
  3257. return true
  3258. end
  3259. end
  3260. end
  3261. if points >= 252 then return true end
  3262. local bonus = attack.damage ~= nil and attack.damage.power_bonus or 0
  3263. points = points + math.floor(points * bonus / 100)
  3264. local target = attack.target or {}
  3265. if (target_count or 1) >= 2 and target.random ~= 1
  3266. and not (target.default_multiple == 1 and target.toggle_multiple == 0) then
  3267. points = math.floor(points * 2 / 3)
  3268. end
  3269. return math.random(1, 100) < points
  3270. end,
  3271. --- Applies the status effects of an attack to a target.
  3272. --
  3273. -- Effects have a mode (inflict, cure or toggle), and a chance between 0 and 1.
  3274. apply_attack_effects = function(self, attack, side, index, target_count)
  3275. -- The original rolls once for all the statuses of an attack.
  3276. local roll = nil
  3277. for _, effect in ipairs(attack.effects) do
  3278. if roll == nil then roll = self:roll_status(attack, side, index, target_count) end
  3279. local has = self:has_status(side, index, effect.id)
  3280. local opposite = effect.id == BattleStatus.FURY and BattleStatus.SADNESS
  3281. or (effect.id == BattleStatus.SADNESS and BattleStatus.FURY or nil)
  3282. if opposite ~= nil and effect.mode ~= "cure" then
  3283. -- Hyper and Tranquilizer: they cure the opposite status if the target has it, and
  3284. -- otherwise induce their own (nothing happens if the target already has it).
  3285. if roll and not has then
  3286. if self:has_status(side, index, opposite) then self:clear_status(side, index, opposite)
  3287. else self:set_status(side, index, effect.id)
  3288. end
  3289. end
  3290. elseif effect.mode == "cure" or (effect.mode == "toggle" and has) then
  3291. if has and roll then self:clear_status(side, index, effect.id) end
  3292. elseif not self:is_immune(side, index, effect.id) and roll then
  3293. if effect.id == BattleStatus.DEATH then
  3294. -- Death takes all the HP.
  3295. local stats = self:get_combat_stats(side, index)
  3296. if stats.hp > 0 then self:apply_damage(side, index, stats.hp, false) end
  3297. elseif effect.id == BattleStatus.NEAR_DEATH then
  3298. -- Near Death follows the HP, see update_near_death.
  3299. else
  3300. self:set_status(side, index, effect.id)
  3301. end
  3302. end
  3303. end
  3304. end,
  3305. --- Updates the timed statuses: expiration, and the damage of poison and the healing of regen.
  3306. update_statuses = function(self, now)
  3307. -- Final Attacks of the characters that die of a status go at the front of the queue.
  3308. self.ai_counter_count = 0
  3309. for _, side in ipairs({Battle.TargetGroup.PARTY, Battle.TargetGroup.ENEMIES}) do
  3310. local list = side == Battle.TargetGroup.PARTY and self.party or self.enemies
  3311. for index = 1, #list do
  3312. local combatant = list[index]
  3313. if combatant.dead == false and combatant.status ~= nil then
  3314. local ids = {}
  3315. for id, _ in pairs(combatant.status) do table.insert(ids, id) end
  3316. for _, id in ipairs(ids) do
  3317. local status = combatant.status[id]
  3318. if status ~= nil then
  3319. -- Timed statuses count down their units, faster with haste and slower with slow.
  3320. local expired = false
  3321. if status.remaining ~= nil then
  3322. status.remaining = status.remaining - math.min(0.5, now - (status.last or now)) * self:get_status_speed(side, index, id)
  3323. status.last = now
  3324. expired = status.remaining <= 0
  3325. end
  3326. if expired then
  3327. self:clear_status(side, index, id)
  3328. -- Some statuses end with something worse.
  3329. if id == BattleStatus.D_SENTENCE then
  3330. local stats = self:get_combat_stats(side, index)
  3331. if stats.hp > 0 then self:apply_damage(side, index, stats.hp, false) end
  3332. elseif id == BattleStatus.SLOW_NUMB then
  3333. self:set_status(side, index, BattleStatus.PETRIFY)
  3334. end
  3335. elseif (id == BattleStatus.POISON or id == BattleStatus.REGEN) and now >= status.next_tick then
  3336. status.next_tick = now + BattleStatus.TICK
  3337. local stats = self:get_combat_stats(side, index)
  3338. if id == BattleStatus.POISON then
  3339. -- Poison can't kill.
  3340. local damage = math.min(math.max(1, math.floor(stats.hp_max * BattleStatus.POISON_FRACTION)), stats.hp - 1)
  3341. if damage > 0 then self:apply_damage(side, index, damage, false) end
  3342. else
  3343. self:apply_damage(side, index, -math.max(1, math.floor(stats.hp_max * BattleStatus.REGEN_FRACTION)), false)
  3344. end
  3345. end
  3346. end
  3347. end
  3348. end
  3349. end
  3350. end
  3351. end,
  3352. --- Gets the colour of the name of a party member in the battle window.
  3353. --
  3354. -- Yellow for the one choosing a command, red if it's dead, purple if poisoned, grey if it
  3355. -- can't act.
  3356. -- @return r, g, b.
  3357. get_name_colour = function(self, index, active)
  3358. if self.party[index].dead then return 1, 0, 0 end
  3359. if active then return 1, 1, 0 end
  3360. if self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.POISON) then return 0.75, 0.4, 1 end
  3361. if self:is_frozen(Battle.TargetGroup.PARTY, index) then return 0.6, 0.6, 0.6 end
  3362. -- Near death: less than a quarter of the HP.
  3363. local stats = Characters[self.party[index].character].stats
  3364. if stats.hp.current < self:get_stat_max(stats.hp) / 4 then return 1, 0.7, 0.2 end
  3365. return 1, 1, 1
  3366. end,
  3367. --- Updates the colours of the party names. The colour has to be set before the text.
  3368. update_name_colours = function(self)
  3369. for c = 1, #self.party do
  3370. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Left.Name")
  3371. local active = c == self.current_character_window and self.window_state ~= "wait"
  3372. widget:set_colour(self:get_name_colour(c, active))
  3373. widget:set_text(Characters[Party[c]].name)
  3374. end
  3375. end,
  3376. --- Gets the maximum of a character HP or MP.
  3377. --
  3378. -- Characters start with a max of 65535 until their stats are recalculated, so the base value is
  3379. -- used in that case.
  3380. -- @param stat A character stat with base and max, like stats.hp.
  3381. get_stat_max = function(self, stat)
  3382. if stat.max == nil or stat.max >= 65535 then return stat.base end
  3383. return stat.max
  3384. end,
  3385. --- Updates the HP and MP numbers and lines of a party member.
  3386. --
  3387. -- @param index Index of the party member.
  3388. update_party_bars = function(self, index)
  3389. local stats = Characters[self.party[index].character].stats
  3390. local base = "BattleUi.Container.Bottom.Character" .. tostring(index) .. ".Right."
  3391. -- The HP are yellow with Near Death (the colour has to be set before the text).
  3392. local hp_widget = ui_manager:get_widget(base .. "Hp.HpCurrent")
  3393. if self:has_status(Battle.TargetGroup.PARTY, index, BattleStatus.NEAR_DEATH) then hp_widget:set_colour(1, 1, 0)
  3394. else hp_widget:set_colour(1, 1, 1)
  3395. end
  3396. hp_widget:set_text(string.format("%5d", stats.hp.current))
  3397. ui_manager:get_widget(base .. "Mp.MpCurrent"):set_text(string.format("%5d", stats.mp.current))
  3398. local hp_max = self:get_stat_max(stats.hp)
  3399. local mp_max = self:get_stat_max(stats.mp)
  3400. -- The lines under the numbers show the proportion of HP and MP left.
  3401. ui_manager:get_widget(base .. "Hp.HpLineCurrent"):set_width(hp_max > 0 and 100 * math.min(1, stats.hp.current / hp_max) or 0, 0)
  3402. ui_manager:get_widget(base .. "Mp.MpLineCurrent"):set_width(mp_max > 0 and 100 * math.min(1, stats.mp.current / mp_max) or 0, 0)
  3403. -- The name changes colour when the HP is low.
  3404. self:update_name_colours()
  3405. end,
  3406. --- Applies damage or healing to a combatant, and handles its death.
  3407. --
  3408. -- @param amount Positive to damage, negative to heal.
  3409. -- @param mp True to change MP instead of HP.
  3410. apply_damage = function(self, side, index, amount, mp)
  3411. UiContainer.BattleFx:number(side, index, amount, mp)
  3412. if side == Battle.TargetGroup.PARTY then
  3413. local char = Characters[self.party[index].character]
  3414. if mp then
  3415. char.stats.mp.current = math.max(0, math.min(self:get_stat_max(char.stats.mp), char.stats.mp.current - amount))
  3416. self:update_party_bars(index)
  3417. print(char.name .. (amount >= 0 and " loses " or " restores ") .. tostring(math.abs(amount)) .. " MP. MP: " .. tostring(char.stats.mp.current))
  3418. return
  3419. end
  3420. char.stats.hp.current = math.max(0, math.min(self:get_stat_max(char.stats.hp), char.stats.hp.current - amount))
  3421. print(char.name .. (amount >= 0 and " takes " .. tostring(amount) .. " damage." or " recovers " .. tostring(-amount) .. " HP.") .. " HP: " .. tostring(char.stats.hp.current))
  3422. if char.stats.hp.current > 0 then self:update_near_death(side, index) end
  3423. self:update_party_bars(index)
  3424. if char.stats.hp.current == 0 then
  3425. self.party[index].dead = true
  3426. self.party[index].atb = 0
  3427. self.party[index].status = {}
  3428. self.party[index].held = nil
  3429. -- A character that dies loses its limit bar.
  3430. if char.limit ~= nil then char.limit.bar = 0 end
  3431. self:update_limit(index)
  3432. self:update_name_colours()
  3433. for i = #self.command_queue, 1, -1 do
  3434. if self.command_queue[i] == index then table.remove(self.command_queue, i) end
  3435. end
  3436. self:queue_final_attack(index)
  3437. end
  3438. else
  3439. local enemy = self.enemies[index]
  3440. if mp then
  3441. enemy.stats.mp = math.max(0, math.min(enemy.stats.mp_max, enemy.stats.mp - amount))
  3442. print(enemy.name .. (amount >= 0 and " loses " or " restores ") .. tostring(math.abs(amount)) .. " MP.")
  3443. return
  3444. end
  3445. enemy.stats.hp = math.max(0, math.min(enemy.stats.hp_max, enemy.stats.hp - amount))
  3446. print(enemy.name .. (amount >= 0 and " takes " .. tostring(amount) .. " damage." or " recovers " .. tostring(-amount) .. " HP.") .. " HP: " .. tostring(enemy.stats.hp))
  3447. if enemy.stats.hp > 0 then self:update_near_death(side, index) end
  3448. if enemy.stats.hp == 0 then
  3449. enemy.dead = true
  3450. enemy.status = {}
  3451. enemy.held = nil
  3452. -- The model is hidden once the death animation ends, see update_action.
  3453. end
  3454. end
  3455. end,
  3456. --- Notes that a character learned a limit technique, to show it with the results of the battle.
  3457. announce_limit = function(self, char_id, attack_id)
  3458. local attack = Game.Attacks[attack_id]
  3459. if attack == nil then return end
  3460. self.limit_learned = self.limit_learned or {}
  3461. local name = string.gsub(attack.name or "", "^[^%w]+", "")
  3462. table.insert(self.limit_learned, Characters[char_id].name .. " learned " .. name .. "!")
  3463. end,
  3464. --- Gives the first limit technique of the next levels to the characters that have enough kills.
  3465. --
  3466. -- The levels need the kills of the kernel data (Game.Characters[].limits[level].kills, 0 for the ones that
  3467. -- are not got with kills). The level that is being used does not change.
  3468. update_limit_levels = function(self)
  3469. for i = 1, #self.party do
  3470. local char_id = self.party[i].character
  3471. local char = Characters[char_id]
  3472. local definition = Game.Characters[char_id]
  3473. if char.limit ~= nil and definition ~= nil and definition.limits ~= nil then
  3474. for level = 2, #definition.limits do
  3475. local limit = definition.limits[level]
  3476. local learned = char.limit.learned[level]
  3477. if limit ~= nil and (limit.kills or 0) > 0 and (char.kills or 0) >= limit.kills
  3478. and not (learned ~= nil and learned[1] == true) then
  3479. char.limit.learned[level] = learned or {}
  3480. char.limit.learned[level][1] = true
  3481. if limit.techniques[1] ~= nil then self:announce_limit(char_id, limit.techniques[1].command) end
  3482. print(char.name .. " learns the limit level " .. tostring(level))
  3483. end
  3484. end
  3485. end
  3486. end
  3487. end,
  3488. --- Checks if an enemy was defeated: it is dead or petrified.
  3489. is_defeated = function(self, index)
  3490. return self.enemies[index].dead == true
  3491. or self:has_status(Battle.TargetGroup.ENEMIES, index, BattleStatus.PETRIFY)
  3492. end,
  3493. --- Rolls the item an enemy drops, as in ff7.exe (0x5c7c1e): its items are tried in order, each with its chance
  3494. -- out of 64, and the first one that passes is the drop.
  3495. --
  3496. -- @param source Enemy data.
  3497. -- @return The item ID, nil if it drops nothing.
  3498. roll_drop = function(self, source)
  3499. for d = 0, source:get_drop_count() - 1 do
  3500. local id = source:get_drop_id(d)
  3501. if id >= 0 and math.random(0, 63) <= math.floor(source:get_drop_rate(d) * 63 + 0.5) then return id end
  3502. end
  3503. return nil
  3504. end,
  3505. --- Calculates the rewards for winning the battle and gives them to the party.
  3506. --
  3507. -- As in ff7.exe, each party member that isn't dead or petrified gets all the EXP and AP, and the
  3508. -- available characters that aren't in the party get half of the EXP.
  3509. -- Only the defeated enemies (dead or petrified) give gil, EXP, AP and items, one item at most each.
  3510. -- @return A list of strings with the results, one per result page.
  3511. apply_rewards = function(self)
  3512. local gil, exp, ap = 0, 0, 0
  3513. local items = {}
  3514. for i = 1, #self.enemies do
  3515. if self:is_defeated(i) then
  3516. gil = gil + self.enemies[i].money
  3517. exp = exp + self.enemies[i].exp
  3518. ap = ap + self.enemies[i].ap
  3519. local source = battle_manager:get_enemy(i - 1)
  3520. -- A morphed enemy gives its morph item right away (Morph), and no drops.
  3521. if source ~= nil and not self.enemies[i].morphed then
  3522. local id = self:roll_drop(source)
  3523. if id ~= nil then table.insert(items, id) end
  3524. end
  3525. end
  3526. end
  3527. local alive = {}
  3528. for i = 1, #self.party do
  3529. if self.party[i].dead == false and not self:has_status(Battle.TargetGroup.PARTY, i, BattleStatus.PETRIFY) then
  3530. table.insert(alive, i)
  3531. end
  3532. end
  3533. local level_ups = {}
  3534. local function give_exp(char_id, amount)
  3535. if Characters.add_exp(char_id, amount) > 0 then
  3536. local text = Characters[char_id].name .. " Lv " .. tostring(Characters[char_id].level)
  3537. table.insert(level_ups, text)
  3538. print(text)
  3539. end
  3540. end
  3541. -- Gil Plus (the best one of the party) gives more gil.
  3542. local gil_plus = 1
  3543. for i = 1, #self.party do
  3544. if self.party[i].independent ~= nil then gil_plus = math.max(gil_plus, self.party[i].independent.gil_plus) end
  3545. end
  3546. gil = math.floor(gil * gil_plus)
  3547. for _, i in ipairs(alive) do
  3548. local char = Characters[self.party[i].character]
  3549. -- EXP Plus gives more EXP to the character that has it.
  3550. give_exp(self.party[i].character, math.floor(exp * ((self.party[i].independent or {}).exp_plus or 1)))
  3551. -- AP goes to the materia equipped in the weapon and armor.
  3552. for _, equip in ipairs({char.weapon, char.armor}) do
  3553. if equip ~= nil and equip.materia ~= nil then
  3554. for m = 0, 7 do
  3555. local materia = equip.materia[m]
  3556. if materia ~= nil and Game.Materia[materia.id] ~= nil then
  3557. local levels = Game.Materia[materia.id].levels_ap
  3558. local max_ap = levels ~= nil and levels[#levels] or nil
  3559. materia.ap = (materia.ap or 0) + ap
  3560. -- Mastered materia stops gaining AP.
  3561. if max_ap ~= nil and materia.ap > max_ap then materia.ap = max_ap end
  3562. end
  3563. end
  3564. end
  3565. end
  3566. end
  3567. -- The materia may have gained a level, and the ones that change the stats do it by level.
  3568. for _, i in ipairs(alive) do Characters.recalculate_stats(self.party[i].character) end
  3569. -- The reserve: everybody available that didn't fight.
  3570. local fought = {}
  3571. for i = 1, #self.party do fought[self.party[i].character] = true end
  3572. for char_id = 0, 8 do
  3573. local char = Characters[char_id]
  3574. if not fought[char_id] and IFMEMBQ(char_id) then
  3575. local hp_base, mp_base = char.stats.hp.base, char.stats.mp.base
  3576. give_exp(char_id, math.floor(exp / 2))
  3577. -- Unlike the ones that fought, they get the new HP and MP right away, if alive.
  3578. if char.stats.hp.current > 0 then
  3579. char.stats.hp.current = char.stats.hp.current + math.max(0, char.stats.hp.base - hp_base)
  3580. char.stats.mp.current = char.stats.mp.current + math.max(0, char.stats.mp.base - mp_base)
  3581. end
  3582. end
  3583. end
  3584. Inventory.add_money(gil)
  3585. local pages = {}
  3586. table.insert(pages, "EXP " .. tostring(exp) .. " AP " .. tostring(ap))
  3587. for _, text in ipairs(level_ups) do table.insert(pages, text) end
  3588. table.insert(pages, tostring(gil) .. " Gil")
  3589. for _, id in ipairs(items) do
  3590. if Game.Items[id] ~= nil then
  3591. Inventory.add_item(id, 1)
  3592. table.insert(pages, "Got " .. Game.Items[id].name)
  3593. end
  3594. end
  3595. -- The limit techniques learned (kills and uses).
  3596. self:update_limit_levels()
  3597. for _, text in ipairs(self.limit_learned or {}) do table.insert(pages, text) end
  3598. self.limit_learned = nil
  3599. print("Battle rewards: " .. tostring(exp) .. " EXP, " .. tostring(ap) .. " AP, " .. tostring(gil) .. " gil, " .. tostring(#items) .. " items.")
  3600. return pages
  3601. end,
  3602. --- Shows the next result page, or leaves the battle after the last one.
  3603. show_next_result = function(self)
  3604. self.result_page = self.result_page + 1
  3605. if self.result_pages[self.result_page] == nil then
  3606. self.window_state = "wait"
  3607. self:finish_battle()
  3608. return
  3609. end
  3610. self:show_message(self.result_pages[self.result_page])
  3611. end,
  3612. --- Leaves the battle, and starts the next one if the formation has any.
  3613. finish_battle = function(self)
  3614. local next_battle = self.pending_next_battle
  3615. self.pending_next_battle = -1
  3616. -- The camera of the victory stays until here: it must not go on in the next battle.
  3617. BattleCameraController:reset()
  3618. Battle.finish()
  3619. if next_battle >= 0 then
  3620. print("Next battle: " .. tostring(next_battle))
  3621. Battle.chain(next_battle)
  3622. end
  3623. end,
  3624. --- Checks if the battle is over, and finishes it.
  3625. --
  3626. -- @return True if the battle ended.
  3627. check_battle_end = function(self)
  3628. -- Timed battles end without results when the field timer runs out.
  3629. if Battle.has_mode(Battle.Mode.TIMED) then
  3630. if self.timed_started == nil then self.timed_started = timer:get_timer() > 0 end
  3631. if self.timed_started and timer:get_timer() <= 0 then
  3632. print("Battle timer expired.")
  3633. self.ending = true
  3634. self.action_queue = {}
  3635. self.command_queue = {}
  3636. self.pending_next_battle = -1
  3637. self:finish_battle()
  3638. return true
  3639. end
  3640. end
  3641. local enemies_alive = false
  3642. for i = 1, #self.enemies do if not self:is_defeated(i) then enemies_alive = true end end
  3643. -- Some scripts end the battle (a boss that leaves, for example).
  3644. if self.ai_end_battle == true then enemies_alive = false end
  3645. local party_alive = false
  3646. -- Petrified members can't fight, so they count as down.
  3647. for i = 1, #self.party do
  3648. if self.party[i].dead == false and not self:has_status(Battle.TargetGroup.PARTY, i, BattleStatus.PETRIFY) then party_alive = true end
  3649. end
  3650. if enemies_alive and party_alive then return false end
  3651. self.ending = true
  3652. self.action_queue = {}
  3653. self.command_queue = {}
  3654. if not enemies_alive and party_alive then
  3655. print("Battle won.")
  3656. if not Battle.has_mode(Battle.Mode.NO_VICTORY_MUSIC) then
  3657. audio_manager:play_music_once(BattleMusic.victory)
  3658. end
  3659. -- Some battles are followed by another one instead of returning to the field.
  3660. self.pending_next_battle = battle_manager:get_next_formation_id()
  3661. local pages = self:apply_rewards()
  3662. if battle_manager:show_victory_pose() then
  3663. local ok, err = pcall(BattleCameraController.start_victory, BattleCameraController)
  3664. if not ok then print("Battle camera: " .. tostring(err)) BattleCameraController:reset() end
  3665. for i = 1, #self.party do
  3666. if self.party[i].dead == false then
  3667. self:play_script(Battle.TargetGroup.PARTY, i, self:get_script_number(Battle.TargetGroup.PARTY, i, "victory"), true)
  3668. end
  3669. end
  3670. end
  3671. if battle_manager:show_spoils() and not Battle.has_mode(Battle.Mode.NO_RESULTS) then
  3672. self.result_pages = pages
  3673. self.result_page = 0
  3674. self.window_state = "result"
  3675. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  3676. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  3677. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  3678. self:show_next_result()
  3679. return true
  3680. end
  3681. else
  3682. print("Battle lost.")
  3683. if Battle.has_mode(Battle.Mode.NO_GAME_OVER) then
  3684. self.pending_next_battle = -1
  3685. self:finish_battle()
  3686. return true
  3687. end
  3688. -- The game over screen leaves the battle when it's dismissed.
  3689. self.window_state = "gameover"
  3690. script:request(Script.UI, "GameOver", "show", 0)
  3691. return true
  3692. end
  3693. self:finish_battle()
  3694. return true
  3695. end,
  3696. --- Gets the entity of a combatant.
  3697. --
  3698. -- @param side {@see Battle.TargetGroup.PARTY} or {@see Battle.TargetGroup.ENEMIES}.
  3699. -- @param index Index in the party or enemy list (1 based).
  3700. -- @return The entity, nil if it can't be found.
  3701. get_entity = function(self, side, index)
  3702. local name
  3703. if side == Battle.TargetGroup.PARTY then name = battle_manager:get_party_entity_name(index - 1)
  3704. else name = battle_manager:get_enemy_entity_name(index - 1)
  3705. end
  3706. if name == nil or name == "" then return nil end
  3707. return entity_manager:get_entity(name)
  3708. end,
  3709. --- Gets the animation name for a number in a combatant model.
  3710. get_animation_name = function(self, side, index, number)
  3711. local prefix
  3712. if side == Battle.TargetGroup.PARTY then prefix = battle_manager:get_party_animation_prefix(index - 1)
  3713. else prefix = battle_manager:get_enemy(index - 1):get_model_prefix()
  3714. end
  3715. if prefix == nil or prefix == "" then return nil end
  3716. return string.format("%s_%02d", prefix, number)
  3717. end,
  3718. --- Gets the name of the model of a combatant, as in "aq_mp".
  3719. get_model_name = function(self, side, index)
  3720. if side == Battle.TargetGroup.PARTY then return battle_manager:get_party_model_name(index - 1) end
  3721. return battle_manager:get_enemy(index - 1):get_model()
  3722. end,
  3723. --- Gets the animation script number for a reaction or attack of a combatant.
  3724. --
  3725. -- @param type "attack", "hurt" or "death".
  3726. -- @return The script number, nil if there is none.
  3727. get_script_number = function(self, side, index, type)
  3728. if side == Battle.TargetGroup.ENEMIES then
  3729. if type == "attack" then
  3730. local source = battle_manager:get_enemy(index - 1)
  3731. -- TODO: Use the animation of the attack actually used.
  3732. local count = source:get_animation_count()
  3733. if count > 0 then return source:get_animation(math.random(0, count - 1)) end
  3734. return nil
  3735. end
  3736. return BattleAnimations.enemy[type .. "_script"]
  3737. end
  3738. local mapped = BattleAnimations.models[self:get_model_name(side, index)]
  3739. if mapped ~= nil and mapped[type .. "_script"] ~= nil then return mapped[type .. "_script"] end
  3740. return BattleAnimations.player[type .. "_script"]
  3741. end,
  3742. --- Starts playing an animation script on a combatant.
  3743. --
  3744. -- Animations are played one after the other. If the script marks the moment an attack hits,
  3745. -- on_hit is called then. The queue is advanced by {@see update_animations}.
  3746. -- @param side {@see Battle.TargetGroup.PARTY} or {@see Battle.TargetGroup.ENEMIES}.
  3747. -- @param index Index of the combatant.
  3748. -- @param script Script number.
  3749. -- @param stay True to keep the last frame when finished (deaths).
  3750. -- @param on_hit Function to call when the attack hits, or nil.
  3751. -- @param on_done Function to call when the script is over, or nil.
  3752. -- @param target Combatant to run to, as {side = ..., index = ...}, or nil.
  3753. -- @return True if there was something to play.
  3754. play_script = function(self, side, index, script, stay, on_hit, on_done, target)
  3755. if script == nil then return false end
  3756. -- Scripts can be given as a list of steps too, for animations that are not in the files.
  3757. local steps = script
  3758. if type(script) ~= "table" then steps = BattleAnimations.get_scripts(self:get_model_name(side, index))[script] end
  3759. if steps == nil or #steps == 0 then return false end
  3760. -- A new script replaces the previous one of the combatant.
  3761. local key = tostring(side) .. "_" .. tostring(index)
  3762. local previous = self.animation_queues[key]
  3763. if previous ~= nil and previous.on_done ~= nil then previous.on_done() end
  3764. local tag = self.next_animation_tag
  3765. self.next_animation_tag = nil
  3766. local entity = self:get_entity(side, index)
  3767. local home = nil
  3768. if entity ~= nil then
  3769. local x, y, z = entity:get_position()
  3770. home = {x = x, y = y, z = z}
  3771. -- If a previous script left the combatant away, its home is the one to go back to.
  3772. if previous ~= nil and previous.home ~= nil then home = previous.home end
  3773. -- A party member always goes back to its place, even if it was covering someone.
  3774. if side == Battle.TargetGroup.PARTY and self.party[index] ~= nil and self.party[index].home ~= nil then
  3775. home = self.party[index].home
  3776. end
  3777. end
  3778. self.animation_queues[key] = {
  3779. side = side, index = index, steps = steps, step = 1, time = timer:get_game_time_total(),
  3780. stay = stay, on_hit = on_hit, on_done = on_done, target = target, home = home, tag = tag,
  3781. }
  3782. return true
  3783. end,
  3784. --- Moves a combatant in a straight line, for the movement steps of a script.
  3785. --
  3786. -- @param q The animation queue of the combatant.
  3787. -- @param to Destination, {x, y, z}.
  3788. start_move = function(self, q, to)
  3789. local entity = self:get_entity(q.side, q.index)
  3790. if entity == nil then do return end end
  3791. local x, y, z = entity:get_position()
  3792. local distance = math.sqrt((to.x - x) ^ 2 + (to.y - y) ^ 2 + (to.z - z) ^ 2)
  3793. local duration = math.max(0.2, distance / BattleAnimations.RUN_SPEED)
  3794. q.move = {from = {x = x, y = y, z = z}, to = to, start = q.time, finish = q.time + duration}
  3795. q.time = q.time + duration
  3796. end,
  3797. --- Advances the animation scripts being played.
  3798. update_animations = function(self, now)
  3799. -- Callbacks can start other scripts, so iterate over a copy of the keys.
  3800. local keys = {}
  3801. for key, _ in pairs(self.animation_queues) do table.insert(keys, key) end
  3802. for _, key in ipairs(keys) do
  3803. local q = self.animation_queues[key]
  3804. if q ~= nil then
  3805. local entity = self:get_entity(q.side, q.index)
  3806. -- A step ends when the time it was scheduled to end arrives.
  3807. while q.step <= #q.steps and now >= q.time do
  3808. -- A movement that just ended leaves the combatant exactly at its destination.
  3809. if q.move ~= nil and entity ~= nil then
  3810. entity:set_position(q.move.to.x, q.move.to.y, q.move.to.z)
  3811. q.move = nil
  3812. end
  3813. local step = q.steps[q.step]
  3814. if step.type == "anim" then
  3815. local name = self:get_animation_name(q.side, q.index, step.number)
  3816. -- The animations 44 to 51 of a limit are the ones of its own file.
  3817. if q.tag ~= nil and step.number >= 44 and step.number <= 51 and name ~= nil then
  3818. name = string.format("%s_%s_%02d", battle_manager:get_party_animation_prefix(q.index - 1), q.tag, step.number - 44)
  3819. end
  3820. local length = 0
  3821. if entity ~= nil and name ~= nil then length = entity:get_animation_length(name) end
  3822. local last = true
  3823. for i = q.step + 1, #q.steps do if q.steps[i].type == "anim" then last = false end end
  3824. if entity ~= nil and entity:get_animation_count() > 0 then
  3825. if q.stay and last then entity:play_animation_stop(name)
  3826. else entity:play_animation(name)
  3827. end
  3828. end
  3829. -- Real duration, considering the playback speed. Single frame poses last no time.
  3830. local duration = math.max(length / BattleAnimations.SPEED, BattleAnimations.MIN_FRAME_TIME)
  3831. q.last_name = name
  3832. q.last_duration = duration
  3833. q.time = q.time + duration
  3834. elseif step.type == "hit" then
  3835. if q.on_hit ~= nil then q.on_hit() end
  3836. elseif step.type == "camera" or step.type == "view" then
  3837. -- Nothing replaces the camera of the victory.
  3838. if self.ending ~= true then
  3839. local start = step.type == "camera" and BattleCameraController.start_script
  3840. or BattleCameraController.set_view
  3841. local ok, err = pcall(start, BattleCameraController, step.number)
  3842. if not ok then print("Battle camera: " .. tostring(err)) BattleCameraController:reset() end
  3843. if step.type == "camera" then print("Battle camera: animation, script " .. tostring(step.number)) end
  3844. end
  3845. elseif step.type == "move" then
  3846. -- Run to a point in front of the target, stopping some distance before it.
  3847. local target_entity = q.target ~= nil and self:get_entity(q.target.side, q.target.index) or nil
  3848. if entity ~= nil and target_entity ~= nil then
  3849. local x, y, z = entity:get_position()
  3850. local tx, ty, tz = target_entity:get_position()
  3851. local dx, dy = x - tx, y - ty
  3852. local length = math.sqrt(dx * dx + dy * dy)
  3853. if length > 0 then
  3854. local stop = step.distance / BattleAnimations.DISTANCE_DIVISOR
  3855. self:start_move(q, {x = tx + dx / length * stop, y = ty + dy / length * stop, z = z})
  3856. end
  3857. end
  3858. elseif step.type == "return" then
  3859. if q.home ~= nil then self:start_move(q, q.home) end
  3860. elseif step.type == "face_away" then
  3861. -- Face away from the enemies.
  3862. if entity ~= nil then self:face_away(q.index, entity) end
  3863. elseif step.type == "run_away" then
  3864. -- Run in a straight line away from the enemies.
  3865. if entity ~= nil then
  3866. local x, y, z = entity:get_position()
  3867. local cx, cy = self:get_enemy_center()
  3868. local dx, dy = x - cx, y - cy
  3869. local length = math.sqrt(dx * dx + dy * dy)
  3870. if length == 0 then dx, dy, length = 0, 1, 1 end
  3871. self:start_move(q, {x = x + dx / length * step.distance, y = y + dy / length * step.distance, z = z})
  3872. -- Running away is a one way trip.
  3873. q.home = nil
  3874. end
  3875. end
  3876. q.step = q.step + 1
  3877. end
  3878. -- While running, move the combatant and keep the run animation going.
  3879. if q.move ~= nil and entity ~= nil and now < q.move.finish then
  3880. local t = (now - q.move.start) / (q.move.finish - q.move.start)
  3881. t = math.max(0, math.min(1, t))
  3882. entity:set_position(
  3883. q.move.from.x + (q.move.to.x - q.move.from.x) * t,
  3884. q.move.from.y + (q.move.to.y - q.move.from.y) * t,
  3885. q.move.from.z + (q.move.to.z - q.move.from.z) * t
  3886. )
  3887. if q.last_name ~= nil and (q.loop_next == nil or now >= q.loop_next) then
  3888. entity:play_animation(q.last_name)
  3889. q.loop_next = now + math.max(q.last_duration or 0, 0.1)
  3890. end
  3891. end
  3892. if q.step > #q.steps and now >= q.time and self.animation_queues[key] == q then
  3893. -- Make sure the combatant ends up where it started.
  3894. if q.move ~= nil and entity ~= nil then
  3895. entity:set_position(q.move.to.x, q.move.to.y, q.move.to.z)
  3896. q.move = nil
  3897. end
  3898. if entity ~= nil and q.home ~= nil and not q.stay then
  3899. entity:set_position(q.home.x, q.home.y, q.home.z)
  3900. end
  3901. self.animation_queues[key] = nil
  3902. if q.on_done ~= nil then q.on_done() end
  3903. end
  3904. end
  3905. end
  3906. end,
  3907. --- Turns an entity to face a direction.
  3908. --
  3909. -- Rotation 0 faces towards -Y, 180 towards +Y and 90 towards +X.
  3910. -- @param dx X component of the direction.
  3911. -- @param dy Y component of the direction.
  3912. face_direction = function(self, entity, dx, dy)
  3913. if dx == 0 and dy == 0 then do return end end
  3914. entity:set_rotation(math.deg(math.atan2(dx, -dy)) % 360)
  3915. end,
  3916. --- Sets the rotation of a party member for the escape run.
  3917. --
  3918. -- The run animation already includes a half turn (the hips are rotated 180 degrees around the
  3919. -- vertical axis), so a character that faces the enemies must not be rotated: the animation
  3920. -- makes it face away. One that already faces away (back attacks) has to be turned around first,
  3921. -- or the animation would make it face the enemies.
  3922. -- @param index Index of the party member.
  3923. -- @param entity Entity of the party member.
  3924. -- @return The rotation set.
  3925. face_away = function(self, index, entity)
  3926. local pose = self.escape_pose[index]
  3927. local original = pose ~= nil and pose.rotation or entity:get_rotation()
  3928. local x, y = entity:get_position()
  3929. local cx, cy = self:get_enemy_center()
  3930. local rotation = original
  3931. if x ~= cx or y ~= cy then
  3932. -- Direction away from the enemies, and how far the original facing is from it.
  3933. local away = math.deg(math.atan2(x - cx, -(y - cy))) % 360
  3934. local difference = ((original - away + 540) % 360) - 180
  3935. if math.abs(difference) <= 90 then rotation = (original + 180) % 360 end
  3936. end
  3937. entity:set_rotation(rotation)
  3938. return rotation
  3939. end,
  3940. --- Makes the party turn their back to the enemies and run in place, while L1 and R1 are held.
  3941. begin_escape_pose = function(self)
  3942. self.escape_pose = {}
  3943. for i = 1, #self.party do
  3944. local key = tostring(Battle.TargetGroup.PARTY) .. "_" .. tostring(i)
  3945. -- Members acting or reacting keep doing it.
  3946. if self.party[i].dead == false and self.animation_queues[key] == nil
  3947. and not (self.current_action ~= nil and self.current_action.side == Battle.TargetGroup.PARTY and self.current_action.action.actor == i)
  3948. then
  3949. local entity = self:get_entity(Battle.TargetGroup.PARTY, i)
  3950. local script = self:get_script_number(Battle.TargetGroup.PARTY, i, "escape")
  3951. local steps = type(script) == "number" and BattleAnimations.get_scripts(self:get_model_name(Battle.TargetGroup.PARTY, i))[script] or nil
  3952. local run = nil
  3953. if steps ~= nil then
  3954. for _, step in ipairs(steps) do if step.type == "anim" then run = step.number break end end
  3955. end
  3956. if entity ~= nil and run ~= nil then
  3957. local name = self:get_animation_name(Battle.TargetGroup.PARTY, i, run)
  3958. self.escape_pose[i] = {rotation = entity:get_rotation(), animation = name, next_time = 0}
  3959. local facing = self:face_away(i, entity)
  3960. print(string.format("Escape: %s turns from %d to %d", entity:get_name(), self.escape_pose[i].rotation, facing))
  3961. end
  3962. end
  3963. end
  3964. end,
  3965. --- Keeps the party running in place while the escape pose lasts.
  3966. update_escape_pose = function(self, now)
  3967. for i, pose in pairs(self.escape_pose) do
  3968. local entity = self:get_entity(Battle.TargetGroup.PARTY, i)
  3969. local key = tostring(Battle.TargetGroup.PARTY) .. "_" .. tostring(i)
  3970. -- A member that is acting or reacting at the moment is left alone.
  3971. if self.animation_queues[key] ~= nil then entity = nil end
  3972. if entity ~= nil then self:face_away(i, entity) end
  3973. if entity ~= nil and now >= pose.next_time then
  3974. entity:play_animation(pose.animation)
  3975. pose.next_time = now + math.max(entity:get_animation_length(pose.animation) / BattleAnimations.SPEED, 0.1)
  3976. end
  3977. end
  3978. end,
  3979. --- Makes the party go back to their original position after trying to escape.
  3980. end_escape_pose = function(self)
  3981. for i, pose in pairs(self.escape_pose) do
  3982. local entity = self:get_entity(Battle.TargetGroup.PARTY, i)
  3983. if entity ~= nil then
  3984. entity:set_rotation(pose.rotation)
  3985. -- Back to the idle animation (the first one of the model).
  3986. local idle = self:get_animation_name(Battle.TargetGroup.PARTY, i, 0)
  3987. if idle ~= nil then entity:play_animation(idle) end
  3988. end
  3989. end
  3990. self.escape_pose = {}
  3991. end,
  3992. --- Gets the center of the enemies (X and Y), living or not.
  3993. --
  3994. -- @return X, Y. 0, 0 if there are no enemies.
  3995. get_enemy_center = function(self)
  3996. local sx, sy, count = 0, 0, 0
  3997. for i = 1, #self.enemies do
  3998. local entity = self:get_entity(Battle.TargetGroup.ENEMIES, i)
  3999. if entity ~= nil then
  4000. local x, y, z = entity:get_position()
  4001. sx, sy, count = sx + x, sy + y, count + 1
  4002. end
  4003. end
  4004. if count == 0 then return 0, 0 end
  4005. return sx / count, sy / count
  4006. end,
  4007. --- Escapes from the battle.
  4008. --
  4009. -- Living party members turn around and run away, then the battle ends without rewards.
  4010. start_escape = function(self)
  4011. self.ending = true
  4012. self.action_queue = {}
  4013. self.command_queue = {}
  4014. self.current_action = nil
  4015. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  4016. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  4017. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  4018. self.window_state = "wait"
  4019. local running = 0
  4020. for i = 1, #self.party do
  4021. if self.party[i].dead == false then
  4022. local script = self:get_script_number(Battle.TargetGroup.PARTY, i, "escape")
  4023. local model_steps = type(script) == "number" and BattleAnimations.get_scripts(self:get_model_name(Battle.TargetGroup.PARTY, i))[script] or nil
  4024. if model_steps ~= nil then
  4025. local steps = {{type = "face_away"}}
  4026. for _, step in ipairs(model_steps) do table.insert(steps, step) end
  4027. table.insert(steps, {type = "run_away", distance = BattleAnimations.ESCAPE_DISTANCE})
  4028. running = running + 1
  4029. self:play_script(Battle.TargetGroup.PARTY, i, steps, true, nil, function()
  4030. running = running - 1
  4031. if running <= 0 then self:finish_battle() end
  4032. end)
  4033. end
  4034. end
  4035. end
  4036. -- Nobody has an escape animation: leave right away.
  4037. if running == 0 then self:finish_battle() end
  4038. end,
  4039. --- Applies the animation playback speed to every combatant.
  4040. apply_animation_speed = function(self)
  4041. for i = 1, #self.party do
  4042. local entity = self:get_entity(Battle.TargetGroup.PARTY, i)
  4043. if entity ~= nil then entity:set_animation_speed(BattleAnimations.SPEED) end
  4044. end
  4045. for i = 1, #self.enemies do
  4046. local entity = self:get_entity(Battle.TargetGroup.ENEMIES, i)
  4047. if entity ~= nil then entity:set_animation_speed(BattleAnimations.SPEED) end
  4048. end
  4049. end,
  4050. --- Changes the animation speed, for tuning.
  4051. --
  4052. -- @param key "Z" to slow down, "X" to speed up.
  4053. change_animation_speed = function(self, key)
  4054. local speed = BattleAnimations.SPEED + (key == "X" and 0.1 or -0.1)
  4055. BattleAnimations.SPEED = math.max(0.1, math.min(3, speed))
  4056. self:apply_animation_speed()
  4057. self:show_message(string.format("Animation speed: x%.2f", BattleAnimations.SPEED))
  4058. print("Animation speed: " .. tostring(BattleAnimations.SPEED))
  4059. end,
  4060. --- Gets the camera IDs of an action: the ones of the item, of the limit, or of the attack, and for an enemy
  4061. -- the one it has for that attack.
  4062. --
  4063. -- @return The ID for one target and the one for several, nil if the action has no camera.
  4064. get_action_camera = function(self, side, action, attack)
  4065. if action.item_id ~= nil then
  4066. local item = Game.Items[action.item_id]
  4067. if item == nil then return nil end
  4068. return item.camera, item.camera
  4069. end
  4070. if action.attack_id == nil then return nil end
  4071. -- A limit has its own, even if it takes its data from another attack of the kernel.
  4072. local single, multiple
  4073. local own = action.limit ~= nil and Game.Attacks[action.attack_id] or nil
  4074. if own ~= nil and own.camera ~= nil then single, multiple = own.camera.single, own.camera.multiple
  4075. else
  4076. if attack.animation ~= nil then single, multiple = attack.animation.camera_single, attack.animation.camera_multiple end
  4077. local kernel = attack.id ~= nil and Game.Attacks[attack.id] or nil
  4078. if single == nil and kernel ~= nil and kernel.camera ~= nil then single, multiple = kernel.camera.single, kernel.camera.multiple end
  4079. end
  4080. -- The camera of the attack of an enemy overrides the one of the attack.
  4081. if side == Battle.TargetGroup.ENEMIES then
  4082. local source = battle_manager:get_enemy(action.actor - 1)
  4083. for slot = 0, source:get_attack_count() - 1 do
  4084. if source:get_attack(slot) == action.attack_id then
  4085. local camera = source:get_camera_for_attack(slot)
  4086. if camera ~= nil and camera >= 0 and camera < 0xffff then single, multiple = camera, camera end
  4087. break
  4088. end
  4089. end
  4090. end
  4091. return single, multiple
  4092. end,
  4093. --- Starts the camera of an action, if it has one.
  4094. start_action_camera = function(self, side, action, attack, targets)
  4095. local ok, err = pcall(function()
  4096. local single, multiple = self:get_action_camera(side, action, attack)
  4097. if single == nil and multiple == nil then return end
  4098. BattleCameraController:start(side, action.actor, action.target_group, targets, single, multiple)
  4099. end)
  4100. if not ok then print("Battle camera: " .. tostring(err)) end
  4101. end,
  4102. --- Starts executing the first action in the queue.
  4103. --
  4104. -- The attacker plays its attack script. The damage is applied when the script marks the hit,
  4105. -- (or at the end, if it doesn't) and the action is over when every animation is done.
  4106. execute_action = function(self)
  4107. if self.action_executing == true or #self.action_queue == 0 then do return 0 end end
  4108. local action = table.remove(self.action_queue, 1)
  4109. self.action_executing = true
  4110. self.ai_counter_count = 0
  4111. -- Once someone acts, held ATBs start to fill.
  4112. self:release_hold()
  4113. local actor_side = action.actor_side or Battle.TargetGroup.PARTY
  4114. local actors = actor_side == Battle.TargetGroup.PARTY and self.party or self.enemies
  4115. local actor = actors[action.actor]
  4116. local current = {action = action, side = actor_side, hit_done = false, targets = {}, pending = 0}
  4117. self.current_action = current
  4118. -- The actor may have died while waiting.
  4119. if actor == nil or (actor.dead == true and not action.allow_dead) then
  4120. current.hit_done = true
  4121. self:update_action(timer:get_game_time_total())
  4122. return
  4123. end
  4124. -- Those that can't act keep their actions for later. Counterattacks and the orders to manipulated enemies
  4125. -- are lost.
  4126. if self:is_frozen(actor_side, action.actor) and not action.final_attack then
  4127. if not action.is_counter and action.controller == nil then
  4128. actor.held = actor.held or {}
  4129. table.insert(actor.held, action)
  4130. self.current_action = nil
  4131. self.action_executing = false
  4132. return
  4133. end
  4134. current.hit_done = true
  4135. current.targets = {}
  4136. self:update_action(timer:get_game_time_total())
  4137. return
  4138. end
  4139. -- A berserk member attacks, whatever it chose before.
  4140. if actor_side == Battle.TargetGroup.PARTY and not self:apply_berserk(action) then
  4141. current.hit_done = true
  4142. current.targets = {}
  4143. self:update_action(timer:get_game_time_total())
  4144. return
  4145. end
  4146. -- A frog changes or loses the actions that it chose before.
  4147. if actor_side == Battle.TargetGroup.PARTY and not self:apply_frog(action) then
  4148. print(self:get_combatant_name(actor_side, action.actor) .. " can't do that as a frog")
  4149. current.hit_done = true
  4150. current.targets = {}
  4151. self:update_action(timer:get_game_time_total())
  4152. return
  4153. end
  4154. -- Mime repeats the last action of the party, as a copy that doesn't use MP (items are used up again).
  4155. if actor_side == Battle.TargetGroup.PARTY and action.command == self.MIME_COMMAND and action.attack_id == nil then
  4156. local copy, reason = self:build_mime_action(action)
  4157. if copy == nil then
  4158. self:show_message(reason)
  4159. current.hit_done = true
  4160. self:update_action(timer:get_game_time_total())
  4161. return
  4162. end
  4163. action = copy
  4164. current.action = copy
  4165. end
  4166. -- Change and Defend.
  4167. if actor_side == Battle.TargetGroup.PARTY and (action.command == 18 or action.command == 19) then
  4168. self:run_side_command(current, action)
  4169. return
  4170. end
  4171. -- The last action of the party, for Mime. A mimed action leaves the one that was copied, so it can be mimed again.
  4172. if actor_side == Battle.TargetGroup.PARTY and not action.mimed and not action.is_counter and not action.final_attack
  4173. and not action.sneak_attack and action.controller == nil and not action.automatic then
  4174. local last = {}
  4175. for key, value in pairs(action) do last[key] = value end
  4176. self.last_party_action = last
  4177. end
  4178. local attack = self:get_action_attack(action)
  4179. local revives = self:attack_revives(attack)
  4180. if not self:apply_confusion(action, attack) then
  4181. current.hit_done = true
  4182. self:update_action(timer:get_game_time_total())
  4183. return
  4184. end
  4185. -- Attacks that revive are for the dead, the other ones for the living.
  4186. local function valid(combatant) return combatant ~= nil and (combatant.dead == revives) end
  4187. local target_list = action.target_group == Battle.TargetGroup.PARTY and self.party or self.enemies
  4188. if action.target_list ~= nil then
  4189. -- Targets chosen by an AI script.
  4190. for _, target in ipairs(action.target_list) do
  4191. if valid(target_list[target]) then table.insert(current.targets, target) end
  4192. end
  4193. elseif action.target_index ~= nil then
  4194. if valid(target_list[action.target_index]) then
  4195. table.insert(current.targets, action.target_index)
  4196. elseif not revives and not action.no_retarget then
  4197. -- The target died: retarget to the first living one of the same group.
  4198. for i = 1, #target_list do
  4199. if valid(target_list[i]) then table.insert(current.targets, i) break end
  4200. end
  4201. end
  4202. else
  4203. for i = 1, #target_list do
  4204. if valid(target_list[i]) then table.insert(current.targets, i) end
  4205. end
  4206. end
  4207. -- Allies with Cover materia run in front of a member with critical HP that is the target of an
  4208. -- attack of an enemy, and take it. They go back when the action is over.
  4209. if actor_side == Battle.TargetGroup.ENEMIES and not action.is_counter and action.target_group == Battle.TargetGroup.PARTY
  4210. and #current.targets == 1 and (attack.damage.formula == 1 or attack.damage.formula == 2) then
  4211. local covered = current.targets[1]
  4212. local cover = self:find_cover(covered)
  4213. if cover ~= nil then
  4214. local cover_entity = self:get_entity(Battle.TargetGroup.PARTY, cover)
  4215. local covered_entity = self:get_entity(Battle.TargetGroup.PARTY, covered)
  4216. if cover_entity ~= nil and covered_entity ~= nil then
  4217. local home = self.party[cover].home
  4218. if home == nil then
  4219. local hx, hy, hz = cover_entity:get_position()
  4220. home = {x = hx, y = hy, z = hz}
  4221. end
  4222. local x, y, z = covered_entity:get_position()
  4223. local dx, dy = self:get_row_direction(x, y)
  4224. current.cover = {covered = covered, index = cover, home = home}
  4225. self:slide_party(cover, {x = x + dx * self.COVER_DISTANCE, y = y + dy * self.COVER_DISTANCE, z = z}, self.COVER_MOVE_TIME)
  4226. else
  4227. current.cover = {covered = covered, index = cover}
  4228. end
  4229. end
  4230. end
  4231. -- Counterattacks that lost their target (it died before they happened) are cancelled.
  4232. if action.no_retarget and #current.targets == 0 then
  4233. print("The counterattack has no target anymore.")
  4234. current.hit_done = true
  4235. self:update_action(timer:get_game_time_total())
  4236. return
  4237. end
  4238. -- Limits that are not attacks.
  4239. if actor_side == Battle.TargetGroup.PARTY and action.limit ~= nil and self:get_special_limit(action.attack_id) ~= nil then
  4240. self:start_action_camera(actor_side, action, attack, current.targets)
  4241. self:run_special_limit(current, action)
  4242. return
  4243. end
  4244. local script = action.script
  4245. if script == nil and actor_side == Battle.TargetGroup.PARTY then
  4246. local script_type = (action.attack_id ~= nil or action.item_id ~= nil or action.coin_gil ~= nil) and "magic" or "attack"
  4247. if action.throw_item ~= nil or action.coin_gil ~= nil then script_type = "throw" end
  4248. if action.command == self.MANIP_COMMAND and action.attack_id == nil then script_type = "manip" end
  4249. -- The physical limits use the animation of the attack.
  4250. if action.limit ~= nil and (attack.damage.formula == 1 or attack.damage.formula == 11) then script_type = "attack" end
  4251. -- The animation of the limit itself, if the model has it.
  4252. local limit_script, limit_tag = nil, nil
  4253. if action.limit ~= nil then limit_script, limit_tag = self:get_limit_script(action.actor, action.attack_id) end
  4254. self.next_animation_tag = limit_tag
  4255. -- A limit that hits several times has no hit marks in its script: the hits start with the animations of
  4256. -- the limit itself (44 to 51) and are spread over their duration.
  4257. if limit_script ~= nil and limit_tag ~= nil and attack.hits ~= nil then
  4258. local steps = BattleAnimations.get_scripts(self:get_model_name(Battle.TargetGroup.PARTY, action.actor))[limit_script]
  4259. local entity = self:get_entity(Battle.TargetGroup.PARTY, action.actor)
  4260. local prefix = battle_manager:get_party_animation_prefix(action.actor - 1)
  4261. local marked, span = {}, 0
  4262. for _, step in ipairs(steps) do
  4263. if step.type == "anim" and step.number >= 44 and step.number <= 51 then
  4264. if span == 0 then table.insert(marked, {type = "hit"}) end
  4265. local name = string.format("%s_%s_%02d", prefix, limit_tag, step.number - 44)
  4266. local length = entity ~= nil and entity:get_animation_length(name) or 0
  4267. span = span + math.max(length / BattleAnimations.SPEED, BattleAnimations.MIN_FRAME_TIME)
  4268. end
  4269. table.insert(marked, step)
  4270. end
  4271. current.limit_span = span
  4272. limit_script = marked
  4273. end
  4274. if action.command == Characters.E_SKILL_COMMAND and action.attack_id ~= nil then script_type = "eskill" end
  4275. script = limit_script or self:get_script_number(actor_side, action.actor, script_type)
  4276. end
  4277. -- Using things costs something. If it can't be paid anymore, the action fizzles.
  4278. local function fizzle(message)
  4279. print(message)
  4280. current.hit_done = true
  4281. current.targets = {}
  4282. current.pending = 0
  4283. self:update_action(timer:get_game_time_total())
  4284. end
  4285. -- Silence stops the actions that were chosen before it, too. Nothing is paid.
  4286. if self:is_silenced_action(action, attack) then
  4287. fizzle(self:get_combatant_name(actor_side, action.actor) .. " is silenced")
  4288. return
  4289. end
  4290. if actor_side == Battle.TargetGroup.PARTY then
  4291. local stats = Characters[self.party[action.actor].character].stats
  4292. if action.item_id ~= nil then
  4293. -- Items are used up.
  4294. local owned = 0
  4295. for slot = 0, MAX_INVENTORY_SLOTS do
  4296. if Inventory[slot] ~= nil and Inventory[slot].item == action.item_id then owned = owned + Inventory[slot].quantity end
  4297. end
  4298. if owned < 1 then fizzle("No more " .. attack.name) return end
  4299. Inventory.remove_item(action.item_id, 1)
  4300. elseif action.coin_gil ~= nil then
  4301. -- The gil is spent.
  4302. if (Inventory.money or 0) < action.coin_gil then fizzle("Not enough gil") return end
  4303. Inventory.money = Inventory.money - action.coin_gil
  4304. elseif action.throw_item ~= nil then
  4305. -- The thrown thing is gone.
  4306. local owned = 0
  4307. for slot = 0, MAX_INVENTORY_SLOTS do
  4308. if Inventory[slot] ~= nil and Inventory[slot].item == action.throw_item then owned = owned + Inventory[slot].quantity end
  4309. end
  4310. if owned < 1 then fizzle("No more " .. attack.name) return end
  4311. Inventory.remove_item(action.throw_item, 1)
  4312. elseif action.attack_id ~= nil and not action.mimed then
  4313. local cost = self:get_spell_cost(attack.mp, action.links)
  4314. local can_pay = stats.mp.current >= cost
  4315. -- Quadra Magic casts the spell four times with half of its power, for the MP of one cast, a
  4316. -- number of times per battle. TODO: Unverified: the targets of each cast.
  4317. if action.links ~= nil and (action.links.quadra or 0) > 0 and can_pay then
  4318. local used = self.party[action.actor].quadra_used[action.attack_id] or 0
  4319. if used < action.links.quadra then
  4320. self.party[action.actor].quadra_used[action.attack_id] = used + 1
  4321. current.quadra = true
  4322. end
  4323. end
  4324. if cost > 0 then
  4325. if not can_pay then
  4326. self:show_timed_message(self.NOT_ENOUGH_MP)
  4327. fizzle("Not enough MP for " .. attack.name)
  4328. return
  4329. end
  4330. self:apply_damage(actor_side, action.actor, cost, true)
  4331. end
  4332. if action.summon ~= nil then
  4333. local used = self.party[action.actor].summon_used[action.attack_id] or 0
  4334. if (action.summon.times or 1) < 255 then
  4335. if used >= (action.summon.times or 1) then fizzle("No summons left of " .. attack.name) return end
  4336. self.party[action.actor].summon_used[action.attack_id] = used + 1
  4337. end
  4338. end
  4339. end
  4340. end
  4341. -- Enemy frogs can't use the attacks that cost MP.
  4342. if actor_side == Battle.TargetGroup.ENEMIES and (attack.mp or 0) > 0
  4343. and self:has_status(actor_side, action.actor, BattleStatus.FROG) then
  4344. fizzle(self:get_combatant_name(actor_side, action.actor) .. " can't use " .. attack.name .. " as a frog")
  4345. return
  4346. end
  4347. if actor_side == Battle.TargetGroup.ENEMIES and not self:pay_enemy_mp(action.actor, attack) then
  4348. -- The window only shows the name of the attack, and nothing happens.
  4349. self:show_timed_message(attack.name)
  4350. fizzle(self:get_combatant_name(actor_side, action.actor) .. " doesn't have enough MP for " .. attack.name)
  4351. return
  4352. end
  4353. -- Limits empty the bar.
  4354. if actor_side == Battle.TargetGroup.PARTY and action.limit ~= nil then self:use_limit(action) end
  4355. -- Widening an action that has one target takes a use of All (spells with the materia linked) or of
  4356. -- Mega All.
  4357. if actor_side == Battle.TargetGroup.PARTY and not action.mimed and not self:spend_all(action, attack) then
  4358. fizzle("No more All left for " .. attack.name)
  4359. return
  4360. end
  4361. -- Spells, summons, items and enemy attacks show their names.
  4362. if action.attack_id ~= nil or action.item_id ~= nil then
  4363. self:show_message(attack.name, action.limit ~= nil)
  4364. end
  4365. -- Summons play their own sequence after the cast pose, and the hit lands during it.
  4366. local summon = action.attack_id ~= nil and UiContainer.BattleFx:has_summon(attack.id)
  4367. local summon_started = false
  4368. local function start_summon()
  4369. if summon_started then do return end end
  4370. summon_started = true
  4371. UiContainer.BattleFx:play_summon(
  4372. attack, actor_side, action.actor, action.target_group, current.targets,
  4373. function() self:apply_action_hit() end,
  4374. function() current.pending = current.pending - 1 end
  4375. )
  4376. end
  4377. -- Thrown things fly to the target, and the hit lands when they arrive.
  4378. local throw = (action.throw_item ~= nil or action.coin_gil ~= nil) and actor_side == Battle.TargetGroup.PARTY
  4379. local throw_started = false
  4380. local function start_throw()
  4381. if throw_started then do return end end
  4382. throw_started = true
  4383. -- The thing leaves the hand halfway through the throwing animation (21), which comes after the hit mark.
  4384. local delay = 0
  4385. local thrower = self:get_entity(actor_side, action.actor)
  4386. local anim = self:get_animation_name(actor_side, action.actor, 21)
  4387. if thrower ~= nil and anim ~= nil then
  4388. delay = thrower:get_animation_length(anim) / BattleAnimations.SPEED / 2
  4389. end
  4390. local ok = pcall(function()
  4391. UiContainer.BattleFx:play_throw(
  4392. actor_side, action.actor, action.target_group, current.targets, action.coin_gil ~= nil and "common_zeni" or self:get_throw_mesh(action.throw_item), delay,
  4393. function() self:apply_action_hit() end,
  4394. function() current.pending = current.pending - 1 end
  4395. )
  4396. end)
  4397. if not ok then
  4398. self:apply_action_hit()
  4399. current.pending = current.pending - 1
  4400. end
  4401. end
  4402. current.pending = (summon or throw) and 2 or 1
  4403. -- The aura of the caster.
  4404. if action.attack_id ~= nil and actor_side == Battle.TargetGroup.PARTY then
  4405. local ok, err = pcall(function()
  4406. local kind = action.limit ~= nil and 1 or UiContainer.BattleFx:aura_kind(action, summon)
  4407. UiContainer.BattleFx:start_aura(kind, actor_side, action.actor)
  4408. end)
  4409. if not ok then print("Battle aura: " .. tostring(err)) end
  4410. end
  4411. -- The camera of what is used (summons have their own).
  4412. if not summon then self:start_action_camera(actor_side, action, attack, current.targets) end
  4413. local played = self:play_script(
  4414. actor_side, action.actor, script, false,
  4415. function()
  4416. if summon then start_summon() elseif throw then start_throw() else self:apply_action_hit() end
  4417. end,
  4418. function()
  4419. current.pending = current.pending - 1
  4420. -- A script without a hit mark still ends with the summon.
  4421. if summon then start_summon() end
  4422. if throw then start_throw() end
  4423. end,
  4424. current.targets[1] ~= nil and {side = action.target_group, index = current.targets[1]} or nil
  4425. )
  4426. if not played then
  4427. if summon then
  4428. -- Nothing to play for the attacker: the summon starts right away.
  4429. current.pending = 1
  4430. start_summon()
  4431. elseif throw then
  4432. current.pending = 1
  4433. start_throw()
  4434. else
  4435. -- Nothing to play for the attacker: the hit lands right away.
  4436. current.pending = 0
  4437. end
  4438. end
  4439. self:update_action(timer:get_game_time_total())
  4440. end,
  4441. --- Applies the damage of the current action, and starts the reactions of the targets.
  4442. --- Brings a dead combatant back to life.
  4443. --
  4444. -- It comes back with 1 HP at least, the attack heals it afterwards.
  4445. revive = function(self, side, index)
  4446. local combatant = self:get_combatant(side, index)
  4447. if combatant == nil or combatant.dead == false then do return end end
  4448. combatant.dead = false
  4449. combatant.atb = 0
  4450. combatant.status = {}
  4451. combatant.held = nil
  4452. combatant.waiting = false
  4453. combatant.acting = false
  4454. if side == Battle.TargetGroup.PARTY then
  4455. Characters[combatant.character].stats.hp.current = 1
  4456. self:update_party_bars(index)
  4457. self:update_name_colours()
  4458. else
  4459. combatant.stats.hp = 1
  4460. battle_manager:set_enemy_visible(index - 1, true)
  4461. end
  4462. self:update_near_death(side, index)
  4463. -- Back to idle, it was lying on the floor.
  4464. local entity = self:get_entity(side, index)
  4465. local name = self:get_animation_name(side, index, 0)
  4466. if entity ~= nil and name ~= nil then entity:play_animation(name) end
  4467. print(self:get_combatant_name(side, index) .. " is back")
  4468. end,
  4469. --- Picks a random living combatant of a side, nil if there is none.
  4470. random_living = function(self, side)
  4471. local list = side == Battle.TargetGroup.PARTY and self.party or self.enemies
  4472. local alive = {}
  4473. for i = 1, #list do if list[i].dead == false then table.insert(alive, i) end end
  4474. if #alive == 0 then return nil end
  4475. return alive[math.random(1, #alive)]
  4476. end,
  4477. --- Applies the hit of the action being executed. Quadra Magic repeats it three more times.
  4478. apply_action_hit = function(self)
  4479. local current = self.current_action
  4480. if current == nil or current.hit_done == true then do return end end
  4481. current.hit_done = true
  4482. local action = current.action
  4483. local attack = self:apply_links(self:get_action_attack(action), action.links)
  4484. if current.quadra then attack = self:apply_quadra(attack) end
  4485. -- Steal and Sense do no damage.
  4486. if current.side == Battle.TargetGroup.PARTY and action.attack_id == nil and action.item_id == nil and action.limit == nil
  4487. and action.target_group == Battle.TargetGroup.ENEMIES and current.targets[1] ~= nil then
  4488. if action.command == self.STEAL_COMMAND then
  4489. self:try_steal(action.actor, current.targets[1], false)
  4490. return
  4491. elseif action.command == self.SENSE_COMMAND then
  4492. self:sense(action.actor, current.targets[1])
  4493. return
  4494. elseif action.command == self.MANIP_COMMAND then
  4495. self:manipulate(action.actor, current.targets[1])
  4496. return
  4497. end
  4498. end
  4499. -- The counterattacks of this hit go in front of the queue, in order.
  4500. self.ai_counter_count = 0
  4501. local hits = (action.limit ~= nil and current.side == Battle.TargetGroup.PARTY and attack.hits ~= nil) and attack.hits or 1
  4502. if hits > 1 then
  4503. -- A limit that hits several times (Omnislash...): the attack data tells if each hit goes to a random
  4504. -- enemy, or all of them go to the targets.
  4505. local random = (attack.target.random or 0) == 1 and action.target_group == Battle.TargetGroup.ENEMIES
  4506. local number = 0
  4507. -- Spread over the animation of the limit, if it is known.
  4508. local delay = (current.limit_span or 0) > 0 and current.limit_span / hits or self.LIMIT_HIT_DELAY
  4509. current.pending = current.pending + 1
  4510. local function one()
  4511. number = number + 1
  4512. local target = nil
  4513. if random then target = self:random_living(Battle.TargetGroup.ENEMIES) end
  4514. if number > hits or (random and target == nil) then
  4515. current.pending = current.pending - 1
  4516. return
  4517. end
  4518. local saved = current.targets
  4519. if random then current.targets = {target} end
  4520. self.ai_counter_count = 0
  4521. self:apply_hit_pass(current, action, attack, number)
  4522. current.targets = saved
  4523. table.insert(self.delayed_calls, {time = timer:get_game_time_total() + delay, call = one})
  4524. end
  4525. one()
  4526. else
  4527. self:apply_hit_pass(current, action, attack, 1)
  4528. end
  4529. -- Morph: an enemy that is defeated by it turns into its morph item.
  4530. if current.side == Battle.TargetGroup.PARTY and action.command == self.MORPH_COMMAND and action.attack_id == nil
  4531. and action.limit == nil and current.targets[1] ~= nil and action.target_group == Battle.TargetGroup.ENEMIES then
  4532. local target = current.targets[1]
  4533. local enemy = self.enemies[target]
  4534. local source = battle_manager:get_enemy(target - 1)
  4535. if enemy ~= nil and enemy.dead and source ~= nil and source:get_morph() >= 0 then
  4536. -- The item goes to the inventory right away, and the enemy drops nothing else.
  4537. enemy.morphed = true
  4538. local item_id = source:get_morph()
  4539. Inventory.add_item(item_id, 1)
  4540. local item = Game.Items[item_id]
  4541. self:show_message("Morphed into " .. (item ~= nil and item.name or "an item"))
  4542. end
  4543. end
  4544. -- Mug steals while it attacks (even if the attack kills the enemy).
  4545. if current.side == Battle.TargetGroup.PARTY and action.command == self.MUG_COMMAND and action.attack_id == nil
  4546. and action.limit == nil and current.targets[1] ~= nil and action.target_group == Battle.TargetGroup.ENEMIES then
  4547. self:try_steal(action.actor, current.targets[1], true, true)
  4548. end
  4549. -- Added Cut (Cloud attacks with his weapon after the spell) and Steal as well (a steal attempt) go
  4550. -- after the spell, and after all the casts of Quadra Magic.
  4551. local links = action.links
  4552. local added_cut = links ~= nil and (links.added_cut or 0) > 0 and action.attack_id ~= nil and current.side == Battle.TargetGroup.PARTY
  4553. local steal = links ~= nil and (links.steal_as_well or 0) > 0 and current.side == Battle.TargetGroup.PARTY
  4554. and action.target_group == Battle.TargetGroup.ENEMIES
  4555. -- Steal as well happens with the spell, even if it kills the enemy.
  4556. if steal and current.targets[1] ~= nil then
  4557. self:try_steal(action.actor, current.targets[1], true)
  4558. end
  4559. if added_cut then
  4560. current.pending = current.pending + 1
  4561. -- The first target that is still alive.
  4562. local function first_target()
  4563. for _, t in ipairs(current.targets) do
  4564. if self.enemies[t] ~= nil and not self.enemies[t].dead then return t end
  4565. end
  4566. return nil
  4567. end
  4568. local function finish() current.pending = current.pending - 1 end
  4569. -- The attack of Added Cut waits for the animation of the spell to end, as a new animation of
  4570. -- the character would cut it.
  4571. local added_cut_attack
  4572. added_cut_attack = function()
  4573. local key = tostring(Battle.TargetGroup.PARTY) .. "_" .. tostring(action.actor)
  4574. if self.animation_queues[key] ~= nil then
  4575. table.insert(self.delayed_calls, {time = timer:get_game_time_total() + 0.1, call = added_cut_attack})
  4576. return
  4577. end
  4578. local target = first_target()
  4579. local hit_done = false
  4580. local function hit()
  4581. if hit_done then return end
  4582. hit_done = true
  4583. self.ai_counter_count = 0
  4584. self:apply_hit_pass(current, action, self:get_weapon_attack(action.actor), 2)
  4585. end
  4586. local played = target ~= nil and self:play_script(
  4587. Battle.TargetGroup.PARTY, action.actor, self:get_script_number(Battle.TargetGroup.PARTY, action.actor, "attack"), false,
  4588. hit, function() hit() finish() end, {side = Battle.TargetGroup.ENEMIES, index = target}
  4589. )
  4590. if not played then
  4591. hit()
  4592. finish()
  4593. end
  4594. end
  4595. table.insert(self.delayed_calls, {
  4596. time = timer:get_game_time_total() + (current.quadra and 4 or 1) * self.QUADRA_DELAY,
  4597. call = added_cut_attack,
  4598. })
  4599. end
  4600. -- 2x-Cut and 4x-Cut hit again and again, with the animation of the attack each time.
  4601. local strikes = (action.attack_id == nil and current.side == Battle.TargetGroup.PARTY) and self.COMMAND_STRIKES[action.command] or nil
  4602. if strikes ~= nil and strikes > 1 then
  4603. current.pending = current.pending + 1
  4604. local list = self.enemies
  4605. local last_target = current.targets[1]
  4606. local function finish() current.pending = current.pending - 1 end
  4607. local strike
  4608. strike = function(number)
  4609. if number > strikes then finish() return end
  4610. local key = tostring(Battle.TargetGroup.PARTY) .. "_" .. tostring(action.actor)
  4611. if self.animation_queues[key] ~= nil then
  4612. table.insert(self.delayed_calls, {time = timer:get_game_time_total() + 0.1, call = function() strike(number) end})
  4613. return
  4614. end
  4615. -- The target of each hit: a random enemy for 4x-Cut, the same one for 2x-Cut (or another if it
  4616. -- died, unless it is a counterattack, which only hits the one that attacked).
  4617. local target = nil
  4618. if self.COMMAND_RANDOM[action.command] and not action.no_retarget then target = self:random_living(Battle.TargetGroup.ENEMIES)
  4619. elseif last_target ~= nil and list[last_target] ~= nil and not list[last_target].dead then target = last_target
  4620. elseif not action.no_retarget then target = self:random_living(Battle.TargetGroup.ENEMIES)
  4621. end
  4622. if target == nil or current.side ~= Battle.TargetGroup.PARTY or self.party[action.actor] == nil then finish() return end
  4623. last_target = target
  4624. local done = false
  4625. local function hit()
  4626. if done then return end
  4627. done = true
  4628. local targets = current.targets
  4629. current.targets = {target}
  4630. self.ai_counter_count = 0
  4631. self:apply_hit_pass(current, action, self:get_weapon_attack(action.actor), 2)
  4632. current.targets = targets
  4633. end
  4634. local played = self:play_script(
  4635. Battle.TargetGroup.PARTY, action.actor, self:get_script_number(Battle.TargetGroup.PARTY, action.actor, "attack"), false,
  4636. hit, function() hit() strike(number + 1) end, {side = Battle.TargetGroup.ENEMIES, index = target}
  4637. )
  4638. if not played then
  4639. hit()
  4640. strike(number + 1)
  4641. end
  4642. end
  4643. table.insert(self.delayed_calls, {time = timer:get_game_time_total() + 0.1, call = function() strike(2) end})
  4644. end
  4645. if current.quadra then
  4646. for pass = 2, 4 do
  4647. current.pending = current.pending + 1
  4648. table.insert(self.delayed_calls, {
  4649. time = timer:get_game_time_total() + (pass - 1) * self.QUADRA_DELAY,
  4650. call = function()
  4651. self.ai_counter_count = 0
  4652. self:apply_hit_pass(current, action, attack, pass)
  4653. current.pending = current.pending - 1
  4654. end,
  4655. })
  4656. end
  4657. end
  4658. end,
  4659. --- Seconds between the hits of the limits that hit several times.
  4660. LIMIT_HIT_DELAY = 0.15,
  4661. --- Seconds between the casts of Quadra Magic.
  4662. QUADRA_DELAY = 0.45,
  4663. --- Calls waiting for their time, {time = game time, call = function}.
  4664. delayed_calls = {},
  4665. --- Runs the delayed calls that are due.
  4666. update_delayed_calls = function(self, now)
  4667. for i = #self.delayed_calls, 1, -1 do
  4668. local delayed = self.delayed_calls[i]
  4669. if now >= delayed.time then
  4670. table.remove(self.delayed_calls, i)
  4671. local ok, err = pcall(delayed.call)
  4672. if not ok then print("Delayed call failed: " .. tostring(err)) end
  4673. end
  4674. end
  4675. end,
  4676. --- Applies an attack to the targets of the action once.
  4677. --
  4678. -- @param pass 1 for the first time, more for the repetitions of Quadra Magic, which skip the
  4679. -- targets that died (or go to the first one alive if all of them did).
  4680. apply_hit_pass = function(self, current, action, attack, pass)
  4681. local revives = self:attack_revives(attack)
  4682. local targets = current.targets
  4683. if pass > 1 and not revives then
  4684. local list = action.target_group == Battle.TargetGroup.PARTY and self.party or self.enemies
  4685. targets = {}
  4686. for _, t in ipairs(current.targets) do
  4687. if list[t] ~= nil and not list[t].dead then table.insert(targets, t) end
  4688. end
  4689. if #targets == 0 then
  4690. for i = 1, #list do
  4691. if not list[i].dead then table.insert(targets, i) break end
  4692. end
  4693. end
  4694. end
  4695. for _, t0 in ipairs(targets) do
  4696. local target_group = action.target_group
  4697. local t = t0
  4698. -- The ally that covers the target takes the attack (decided when the action started).
  4699. if current.cover ~= nil and target_group == Battle.TargetGroup.PARTY and t == current.cover.covered
  4700. and not self.party[current.cover.index].dead then
  4701. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, current.cover.index, "Cover", {1, 1, 0.6})
  4702. t = current.cover.index
  4703. end
  4704. -- Reflect bounces spells to the other side.
  4705. if attack.reflectable and self:has_status(target_group, t, BattleStatus.REFLECT) then
  4706. local other = target_group == Battle.TargetGroup.PARTY and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  4707. local bounce = self:random_living(other)
  4708. if bounce ~= nil then
  4709. print(attack.name .. " is reflected")
  4710. UiContainer.BattleFx:text(target_group, t, "Reflect", {0.7, 0.9, 1})
  4711. target_group, t = other, bounce
  4712. end
  4713. end
  4714. if revives then self:revive(target_group, t) end
  4715. local was_dead = target_group == Battle.TargetGroup.ENEMIES and self.enemies[t].dead
  4716. local result = self:calculate_attack(attack, current.side, action.actor, target_group, t, #targets)
  4717. -- What a physical hit cures is decided before the effects of the attack.
  4718. local physical_cures = self:get_physical_cures(attack, target_group, t)
  4719. if not result.hit then
  4720. print("Miss")
  4721. UiContainer.BattleFx:text(target_group, t, "Miss", UiContainer.BattleFx.COLOUR_MISS)
  4722. else
  4723. UiContainer.BattleFx:hit(attack, target_group, t, result)
  4724. -- Status effects of the attack.
  4725. self:apply_attack_effects(attack, target_group, t, #targets)
  4726. end
  4727. -- Physical hits wake up, cure Confusion and free manipulated enemies.
  4728. if result.hit then self:apply_physical_cures(physical_cures, target_group, t) end
  4729. if result.hit and result.amount ~= 0 then
  4730. -- What the target has left limits what can be absorbed.
  4731. local hp_before = self:get_combat_stats(target_group, t).hp
  4732. self:apply_damage(target_group, t, result.amount, result.mp)
  4733. local data = attack.damage
  4734. if result.amount > 0 and not result.mp then
  4735. local absorbed = math.min(result.amount, hp_before)
  4736. if (data.drain_hp or 0) == 1 then self:apply_damage(current.side, action.actor, -absorbed, false) end
  4737. if (data.drain_mp or 0) == 1 then self:apply_damage(current.side, action.actor, -absorbed, true) end
  4738. end
  4739. end
  4740. -- Elixirs restore MP too.
  4741. if result.hit and (result.extra_mp or 0) ~= 0 then self:apply_damage(target_group, t, result.extra_mp, true) end
  4742. local dead = (target_group == Battle.TargetGroup.PARTY and self.party[t].dead)
  4743. or (target_group == Battle.TargetGroup.ENEMIES and self.enemies[t].dead)
  4744. -- The character whose action defeats an enemy gets the kill, that counts for the limit levels.
  4745. if dead and not was_dead and target_group == Battle.TargetGroup.ENEMIES and current.side == Battle.TargetGroup.PARTY
  4746. and self.party[action.actor] ~= nil then
  4747. local killer = Characters[self.party[action.actor].character]
  4748. killer.kills = (killer.kills or 0) + 1
  4749. end
  4750. -- The limit bar fills with the damage that the enemies do.
  4751. if target_group == Battle.TargetGroup.PARTY and current.side == Battle.TargetGroup.ENEMIES and result.hit
  4752. and result.amount > 0 and not result.mp then
  4753. self:add_limit(t, result.amount)
  4754. end
  4755. -- Party members with counter materia attack back, but a counterattack never triggers another one.
  4756. if target_group == Battle.TargetGroup.PARTY and result.hit and result.amount > 0 and not result.mp and not dead
  4757. and current.side == Battle.TargetGroup.ENEMIES and not action.is_counter then
  4758. local formula = attack.damage.formula
  4759. self:party_counter(t, current.side, action.actor, formula == 1 or formula == 11)
  4760. end
  4761. -- The AI of enemies can counterattack, but a counterattack never triggers another one.
  4762. if target_group == Battle.TargetGroup.ENEMIES and result.hit and attack.id ~= nil and not action.is_counter then
  4763. self:ai_after_hit(attack, current.side, action.actor, t, dead)
  4764. end
  4765. -- Only damage makes the target react.
  4766. local reaction = nil
  4767. if dead then reaction = "death"
  4768. elseif result.hit and result.amount > 0 and not result.mp then reaction = "hurt"
  4769. end
  4770. if reaction ~= nil then
  4771. current.pending = current.pending + 1
  4772. local played = false
  4773. if not (dead and target_group == Battle.TargetGroup.ENEMIES) then
  4774. played = self:play_script(
  4775. target_group, t, self:get_script_number(target_group, t, reaction), dead, nil,
  4776. function()
  4777. current.pending = current.pending - 1
  4778. self:restore_stance(target_group, t)
  4779. end
  4780. )
  4781. end
  4782. if not played then current.pending = current.pending - 1 end
  4783. end
  4784. if dead and target_group == Battle.TargetGroup.ENEMIES then
  4785. -- Enemies have no death animation: they disappear a moment after dying.
  4786. table.insert(self.pending_hides, {side = target_group, index = t, time = timer:get_game_time_total() + BattleAnimations.ENEMY_DEATH_TIME})
  4787. current.pending = current.pending + 1
  4788. self.pending_hides[#self.pending_hides].on_done = function() current.pending = current.pending - 1 end
  4789. end
  4790. end
  4791. end,
  4792. --- Finishes the action being executed once all its animations are over.
  4793. update_action = function(self, now)
  4794. local current = self.current_action
  4795. if current == nil then do return end end
  4796. -- If the script didn't mark a hit, it lands when the attacker finishes.
  4797. if current.hit_done == false and current.pending <= 0 then self:apply_action_hit() end
  4798. if current.hit_done == false or current.pending > 0 then do return end end
  4799. local action = current.action
  4800. -- Reset the actor ATB so it starts filling again.
  4801. local actors = current.side == Battle.TargetGroup.PARTY and self.party or self.enemies
  4802. local actor = actors[action.actor]
  4803. -- Counterattacks happen outside the turn of the enemy, so they don't change its ATB.
  4804. if actor ~= nil and not action.is_counter and not action.no_atb then
  4805. actor.atb = 0
  4806. actor.waiting = false
  4807. actor.acting = false
  4808. if current.side == Battle.TargetGroup.PARTY then
  4809. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(action.actor) .. ".Right.AtbFill"):set_width(0, 0)
  4810. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(action.actor) .. ".Right.AtbFill"):set_colour(1, 1, 0)
  4811. end
  4812. end
  4813. -- The turn of a manipulated enemy is the one of its controller.
  4814. if action.controller ~= nil and self.party[action.controller] ~= nil then
  4815. local controller = self.party[action.controller]
  4816. controller.atb = 0
  4817. controller.acting = false
  4818. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(action.controller) .. ".Right.AtbFill"):set_width(0, 0)
  4819. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(action.controller) .. ".Right.AtbFill"):set_colour(1, 1, 0)
  4820. end
  4821. -- The one that covered goes back to its place.
  4822. if current.cover ~= nil and current.cover.home ~= nil then
  4823. self:return_to_place(current.cover.index, current.cover.home)
  4824. end
  4825. -- A dead character that attacked with Final Attack goes back to lying on the floor.
  4826. if action.final_attack and current.side == Battle.TargetGroup.PARTY then
  4827. self:play_script(current.side, action.actor, self:get_script_number(current.side, action.actor, "death"), true, nil, nil)
  4828. end
  4829. self.current_action = nil
  4830. self.action_executing = false
  4831. self:check_battle_end()
  4832. end,
  4833. --- Hides the enemies whose death time is over.
  4834. update_hides = function(self, now)
  4835. for i = #self.pending_hides, 1, -1 do
  4836. local hide = self.pending_hides[i]
  4837. if now >= hide.time then
  4838. battle_manager:set_enemy_visible(hide.index - 1, false)
  4839. table.remove(self.pending_hides, i)
  4840. if hide.on_done ~= nil then hide.on_done() end
  4841. end
  4842. end
  4843. end,
  4844. --- Rotates the combatant selected in the animation viewer 45 degrees, to find out which
  4845. -- angle faces which direction. Shows the new angle and position.
  4846. viewer_rotate = function(self)
  4847. local list = {}
  4848. for i = 1, #self.party do table.insert(list, {side = Battle.TargetGroup.PARTY, index = i}) end
  4849. for i = 1, #self.enemies do table.insert(list, {side = Battle.TargetGroup.ENEMIES, index = i}) end
  4850. if #list == 0 then do return end end
  4851. if self.viewer.combatant > #list then self.viewer.combatant = 1 end
  4852. local view = list[self.viewer.combatant]
  4853. local entity = self:get_entity(view.side, view.index)
  4854. if entity == nil then do return end end
  4855. self.viewer.rotation = ((self.viewer.rotation or entity:get_rotation()) + 45) % 360
  4856. entity:set_rotation(self.viewer.rotation)
  4857. local x, y, z = entity:get_position()
  4858. local text = string.format("%s rotation %d at (%.1f, %.1f)", entity:get_name(), self.viewer.rotation, x, y)
  4859. self:show_message(text)
  4860. print("Rotation viewer: " .. text)
  4861. end,
  4862. --- Animation viewer, to find out what each animation of a model is.
  4863. --
  4864. -- V selects the next combatant (party, then enemies), N and B play the next and previous
  4865. -- animations. The animation name and number are shown in the top window.
  4866. -- @param key "V", "N" or "B".
  4867. viewer_input = function(self, key)
  4868. local list = {}
  4869. for i = 1, #self.party do table.insert(list, {side = Battle.TargetGroup.PARTY, index = i}) end
  4870. for i = 1, #self.enemies do table.insert(list, {side = Battle.TargetGroup.ENEMIES, index = i}) end
  4871. if #list == 0 then do return end end
  4872. if self.viewer.combatant > #list then self.viewer.combatant = 1 end
  4873. local view = list[self.viewer.combatant]
  4874. if key == "V" then
  4875. self.viewer.combatant = self.viewer.combatant % #list + 1
  4876. view = list[self.viewer.combatant]
  4877. self.viewer.animation = 0
  4878. self.viewer.rotation = nil
  4879. end
  4880. local entity = self:get_entity(view.side, view.index)
  4881. if entity == nil then do return end end
  4882. local total = entity:get_animation_count()
  4883. if total == 0 then do return end end
  4884. if key == "N" then self.viewer.animation = (self.viewer.animation + 1) % total
  4885. elseif key == "B" then self.viewer.animation = (self.viewer.animation - 1) % total
  4886. end
  4887. local name = self:get_animation_name(view.side, view.index, self.viewer.animation)
  4888. local length = entity:get_animation_length(name)
  4889. entity:play_animation(name)
  4890. self:show_message(
  4891. name .. " " .. tostring(self.viewer.animation + 1) .. "/" .. tostring(total) .. string.format(" %.1fs x%.2f", length / BattleAnimations.SPEED, BattleAnimations.SPEED)
  4892. )
  4893. print("Animation viewer: " .. name .. " (" .. tostring(self.viewer.animation) .. " of " .. tostring(total) .. "), " .. tostring(length) .. "s")
  4894. end,
  4895. --- Shows a list of actions.
  4896. --
  4897. -- Can be used for the windows of magic, summons, items...
  4898. -- @param list The list to open, as in {@see Battle.Menu}
  4899. show_list = function(self, list)
  4900. local cursor = ui_manager:get_widget("BattleUi.Container.Bottom.List.Cursor")
  4901. local kind = nil
  4902. if list == Battle.Menu.MAGIC then kind = "magic"
  4903. elseif list == Battle.Menu.SUMMON then kind = "summon"
  4904. elseif list == Battle.Menu.E_SKILL then kind = "eskill"
  4905. elseif list == Battle.Menu.ITEM then kind = "item"
  4906. elseif list == Battle.Menu.LIMIT then kind = "limit"
  4907. elseif list == Battle.Menu.THROW then kind = "throw"
  4908. -- The double commands use the lists of magic, summons and items (twice).
  4909. elseif list == Battle.Menu.W_MAGIC then kind = "magic"
  4910. elseif list == Battle.Menu.W_SUMMON then kind = "summon"
  4911. elseif list == Battle.Menu.W_ITEM then kind = "item"
  4912. end
  4913. if kind ~= nil then
  4914. audio_manager:play_sound("Cursor")
  4915. self.cursor_list = 1
  4916. self.first_list = 1
  4917. self.cursor_col = 1
  4918. self.current_list = kind
  4919. -- The window of the limits is pink.
  4920. self:set_window_pink("BattleUi.Container.Bottom.List", kind == "limit")
  4921. self.list_entries = self:build_list_entries(kind)
  4922. -- The magic list is wider, with a row for each materia.
  4923. local window = ui_manager:get_widget("BattleUi.Container.Bottom.List")
  4924. if kind == "magic" then
  4925. window:set_x(20, 0)
  4926. window:set_width(0, self.MAGIC_LIST_WIDTH)
  4927. else
  4928. window:set_x(32, 0)
  4929. window:set_width(0, self.LIST_WIDTH)
  4930. end
  4931. -- Start where the list was left, if the cursor memory is on.
  4932. if UiContainer.cursor_memory() then
  4933. local remembered = (self.memory_list[self.current_character_window] or {})[kind]
  4934. if remembered ~= nil and remembered.first + remembered.cursor - 1 <= #self.list_entries then
  4935. self.first_list = remembered.first
  4936. self.cursor_list = remembered.cursor
  4937. self.cursor_col = remembered.col or 1
  4938. end
  4939. local row = self.list_entries[self.first_list + self.cursor_list - 1]
  4940. if row ~= nil and self.cursor_col > #row.entries then self.cursor_col = #row.entries end
  4941. end
  4942. self:populate_list()
  4943. self.window_state = "list"
  4944. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(true)
  4945. self:update_list_cursor()
  4946. cursor:set_visible(true)
  4947. elseif (list == Battle.Menu.COIN) then
  4948. print("Show coin list: Not implemented")
  4949. end
  4950. end,
  4951. --- Remembers the position of the cursor in the current list, for the cursor memory.
  4952. remember_list = function(self)
  4953. local slot = self.current_character_window
  4954. if self.current_list == "none" or slot == nil then return end
  4955. self.memory_list[slot] = self.memory_list[slot] or {}
  4956. self.memory_list[slot][self.current_list] = { first = self.first_list, cursor = self.cursor_list, col = self.cursor_col }
  4957. end,
  4958. --- Closes the currently opened list
  4959. close_list = function(self)
  4960. self:remember_list()
  4961. self.current_list = "none"
  4962. self.window_state = "command"
  4963. ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(false)
  4964. -- Cancelling the second choice of a double command goes back to the first one.
  4965. if self.w_first ~= nil then
  4966. local menu = self.W_COMMANDS[self.selected_command]
  4967. self.w_first = nil
  4968. self:show_message("")
  4969. if menu ~= nil then self:show_list(menu) end
  4970. end
  4971. end,
  4972. --- Shows the target selection window.
  4973. --
  4974. -- The elements displayed in the window and the navegability will depend on what is set in
  4975. -- {@see target_options}.
  4976. select_target = function(self)
  4977. local entry = nil
  4978. if self.window_state == "list" then entry = self:get_list_entry() end
  4979. if entry == nil then do return end end
  4980. self:remember_list()
  4981. -- Spells, summons and items that can't be used (not enough MP, no summons left...).
  4982. if not entry.enabled then
  4983. audio_manager:play_sound("Error")
  4984. do return end
  4985. end
  4986. local action = nil
  4987. if entry.item_id ~= nil then action = Game.Items[entry.item_id]
  4988. elseif entry.throw_item ~= nil then action = Game.Attacks[self.THROW_ATTACK]
  4989. else action = Game.Attacks[entry.attack_id]
  4990. end
  4991. self.selected_throw = entry.throw_item
  4992. self.selected_attack = entry.attack_id
  4993. self.selected_item = entry.item_id
  4994. self.selected_summon = entry.summon
  4995. self.selected_limit = entry.limit
  4996. self.selected_links = entry.links
  4997. -- The special limits always affect a whole side, so there is nothing to choose.
  4998. local special = entry.limit ~= nil and self:get_special_limit(entry.attack_id) or nil
  4999. if special ~= nil then
  5000. self.target_group = special.target == "enemies" and Battle.TargetGroup.ENEMIES or Battle.TargetGroup.PARTY
  5001. if special.self_only then
  5002. self.target_type = Battle.TargetType.SINGLE
  5003. self.target_index = self.current_character_window
  5004. else
  5005. self.target_type = Battle.TargetType.GROUP
  5006. self.target_index = nil
  5007. end
  5008. self:queue_character_action()
  5009. return
  5010. end
  5011. -- Some attacks (the limits that are not done) have no target data: one enemy.
  5012. local target_data = action.target or {
  5013. selectable = 1, default_enemy = 1, default_multiple = 0, toggle_multiple = 0, fixed_row = 0, short_range = 0,
  5014. all_rows = 0, random = 0,
  5015. }
  5016. if entry.throw_item ~= nil then
  5017. target_data = {
  5018. selectable = 1, default_enemy = 1, default_multiple = 0, toggle_multiple = 0, fixed_row = 0, short_range = 0,
  5019. all_rows = 0, random = 0,
  5020. }
  5021. end
  5022. self.target_options = target_data
  5023. -- In the kernel data, spells that All materia can turn into multiple target ones have both
  5024. -- "default multiple" and "toggle multiple" set, and the game clears both if the spell has no All
  5025. -- linked (items and the other attacks don't have them). With All (and uses left) the spell starts
  5026. -- with one target and can toggle to all of them, a number of times per battle.
  5027. if entry.item_id == nil and target_data.toggle_multiple == 1 then
  5028. local member = self.party[self.current_character_window]
  5029. local all = entry.links ~= nil and (entry.links.all or 0) > 0
  5030. and (member.all_used[entry.attack_id] or 0) < entry.links.all
  5031. local options = {}
  5032. for key, value in pairs(target_data) do options[key] = value end
  5033. options.default_multiple = 0
  5034. options.toggle_multiple = all and 1 or 0
  5035. self.target_options = options
  5036. end
  5037. -- Mega All lets any action that aims at one target hit all of them, a number of times per battle.
  5038. if self:mega_all_left(self.party[self.current_character_window]) > 0 and self.target_options.default_multiple ~= 1
  5039. and self.target_options.toggle_multiple ~= 1 then
  5040. local options = {}
  5041. for key, value in pairs(self.target_options) do options[key] = value end
  5042. options.toggle_multiple = 1
  5043. self.target_options = options
  5044. end
  5045. if self.target_options.default_multiple == 1 then self.target_type = Battle.TargetType.GROUP
  5046. else self.target_type = Battle.TargetType.SINGLE
  5047. end
  5048. self.cursor_target_h = 1
  5049. self.cursor_target_v = 1
  5050. self.first_target = 1
  5051. if self.target_options.default_enemy == 1 then self.cursor_target_h = 1
  5052. else self.cursor_target_h = 2
  5053. end
  5054. -- TODO: if self.target_options.selectable == 0, skip this and directly queue the action.
  5055. -- TODO: Populate options, hide and show right column and separator, and resize window
  5056. -- according to self.target_options
  5057. self:refresh_target_enemies()
  5058. self:populate_target_list()
  5059. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(true)
  5060. self.window_state = "target"
  5061. end,
  5062. --- Closes the target window and activates the previous cursor.
  5063. close_target = function(self)
  5064. if self.current_list == "none" then self.window_state = "command"
  5065. else self.window_state = "list"
  5066. end
  5067. ui_manager:get_widget("BattleUi.Container.Bottom.Target"):set_visible(false)
  5068. end,
  5069. --- Populates the target selection window.
  5070. --
  5071. -- The elements displayed in the window and the navegability will depend on what is set in
  5072. -- {@see target_options}.
  5073. populate_target_list = function(self)
  5074. self:populate_target_list_base()
  5075. self:update_all_cursors()
  5076. end,
  5077. --- Shows one hand cursor for each target when all the targets of a side are selected.
  5078. --
  5079. -- The target window has four of them for each side, but there can be fewer targets.
  5080. update_all_cursors = function(self)
  5081. if self.target_options == nil then do return end end
  5082. local left = #self.party
  5083. -- The left column has the enemies, unless the attack is only for the party.
  5084. if not (self.target_options.fixed_row == 1 and self.target_options.default_enemy == 0) then
  5085. left = math.max(0, #self.target_enemies - self.first_target + 1)
  5086. end
  5087. local right = #self.party
  5088. for i = 1, 4 do
  5089. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft.CursorAllLeft" .. tostring(i)):set_visible(i <= left)
  5090. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight.CursorAllRight" .. tostring(i)):set_visible(i <= right)
  5091. end
  5092. end,
  5093. --- Populates the target selection window (see {@see populate_target_list}).
  5094. populate_target_list_base = function(self)
  5095. print("POPULATE TARGET LIST: H: " .. tostring(self.cursor_target_h) .. " V: " .. tostring(self.cursor_target_v) .. " MODE: " .. tostring(self.target_type))
  5096. if self.target_options == nil then do return end end
  5097. if self.target_options.fixed_row == 1 then
  5098. if self.target_options.default_enemy == 1 then
  5099. -- Show only enemies
  5100. print("Enemies only")
  5101. else
  5102. -- Show only allies
  5103. print("Enemies only")
  5104. end
  5105. if self.target_type == Battle.TargetType.GROUP then
  5106. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(false)
  5107. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(false)
  5108. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(true)
  5109. else
  5110. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_default_animation("Position" .. tostring(self.cursor_target_h) .. "_" .. tostring(self.cursor_target_v))
  5111. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(true)
  5112. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(false)
  5113. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(false)
  5114. end
  5115. else
  5116. -- Enemies and allies
  5117. for e = 1, 4 do
  5118. if self.target_enemies[e + self.first_target - 1] ~= nil then
  5119. ui_manager:get_widget("BattleUi.Container.Bottom.Target.L" .. tostring(e)):set_text(self.enemies[self.target_enemies[e + self.first_target - 1]].name)
  5120. ui_manager:get_widget("BattleUi.Container.Bottom.Target.L" .. tostring(e)):set_visible(true)
  5121. else
  5122. ui_manager:get_widget("BattleUi.Container.Bottom.Target.L" .. tostring(e)):set_visible(false)
  5123. end
  5124. end
  5125. for a = 1, 4 do
  5126. if self.party[a] ~= nil then
  5127. ui_manager:get_widget("BattleUi.Container.Bottom.Target.R" .. tostring(a)):set_text(Characters[self.party[a].character].name)
  5128. ui_manager:get_widget("BattleUi.Container.Bottom.Target.R" .. tostring(a)):set_visible(true)
  5129. else
  5130. ui_manager:get_widget("BattleUi.Container.Bottom.Target.R" .. tostring(a)):set_visible(false)
  5131. end
  5132. end
  5133. if self.target_options.all_rows == 1 or self.target_options.random == 1 then
  5134. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(false)
  5135. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(true)
  5136. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(true)
  5137. elseif self.target_type == Battle.TargetType.GROUP then
  5138. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(false)
  5139. if self.cursor_target_h == 1 then
  5140. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(true)
  5141. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(false)
  5142. else
  5143. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(false)
  5144. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(true)
  5145. end
  5146. else
  5147. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllLeft"):set_visible(false)
  5148. ui_manager:get_widget("BattleUi.Container.Bottom.Target.CursorAllRight"):set_visible(false)
  5149. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(true)
  5150. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_default_animation("Position" .. tostring(self.cursor_target_h) .. "_" .. tostring(self.cursor_target_v))
  5151. ui_manager:get_widget("BattleUi.Container.Bottom.Target.Cursor"):set_visible(true)
  5152. end
  5153. end
  5154. end,
  5155. --- Populates the magic selction window.
  5156. --
  5157. -- It uses the magics the current character can use.
  5158. populate_magic_list = function(self)
  5159. self:populate_list()
  5160. end,
  5161. --- Builds the entries of the list window: spells, summons or items.
  5162. --
  5163. -- Each entry has a name, if it can be used (enabled), and what it refers to: attack_id for
  5164. -- spells and summons (and summon, with its data), item_id and quantity for items.
  5165. -- @param kind "magic", "summon" or "item".
  5166. build_list_entries = function(self, kind)
  5167. local entries = {}
  5168. local member = self.party[self.current_character_window]
  5169. local stats = Characters[member.character].stats
  5170. if kind == "magic" then
  5171. local frog = self:has_status(Battle.TargetGroup.PARTY, self.current_character_window, BattleStatus.FROG)
  5172. for _, spell in ipairs(member.magic) do
  5173. local data = Game.Attacks[spell.id]
  5174. table.insert(entries, {
  5175. name = data.name, attack_id = spell.id, links = spell, group = spell.group,
  5176. enabled = self:get_spell_cost(data.mp, spell) <= stats.mp.current - self:get_w_reserved_mp()
  5177. and (not frog or spell.id == self.FROG_SPELL),
  5178. })
  5179. end
  5180. elseif kind == "eskill" then
  5181. -- The enemy skills learned with the equipped materia.
  5182. local learned = Characters.get_abilities(member.character).e_skill
  5183. for _, id in ipairs(learned) do
  5184. local data = Game.Attacks[id]
  5185. if data ~= nil then
  5186. table.insert(entries, {name = data.name, attack_id = id, enabled = data.mp <= stats.mp.current})
  5187. end
  5188. end
  5189. elseif kind == "summon" then
  5190. for _, summon in ipairs(member.summon) do
  5191. local data = Game.Attacks[summon.id]
  5192. -- Summons can be used a number of times per battle. 255 times is no limit.
  5193. local used = member.summon_used[summon.id] or 0
  5194. local left = (summon.times or 1) - used
  5195. table.insert(entries, {
  5196. name = data.name, attack_id = summon.id, summon = summon, links = summon,
  5197. enabled = self:get_spell_cost(data.mp, summon) <= stats.mp.current - self:get_w_reserved_mp()
  5198. and (left - ((self.w_first ~= nil and self.w_first.attack_id == summon.id) and 1 or 0) > 0 or (summon.times or 0) >= 255),
  5199. })
  5200. end
  5201. elseif kind == "limit" then
  5202. -- The limits learned in the limit level of the character.
  5203. local char = Characters[member.character]
  5204. local level = char.limit.current
  5205. local definition = Game.Characters[member.character]
  5206. local techniques = definition ~= nil and definition.limits[level] ~= nil and definition.limits[level].techniques or {}
  5207. for k, technique in ipairs(techniques) do
  5208. local attack = Game.Attacks[technique.command]
  5209. if attack ~= nil and char.limit.learned[level] ~= nil and char.limit.learned[level][k] == true then
  5210. -- Some names have bytes that are not letters at the start.
  5211. local name = string.gsub(attack.name, "^[^%w]+", "")
  5212. table.insert(entries, {name = name, attack_id = technique.command, enabled = true, limit = {level = level, index = k}})
  5213. end
  5214. end
  5215. elseif kind == "throw" then
  5216. -- Everything that can be thrown: items, weapons, armor and accessories.
  5217. for slot = 0, MAX_INVENTORY_SLOTS do
  5218. local entry = Inventory[slot]
  5219. if entry ~= nil and entry.quantity > 0 then
  5220. local item = Game.Items[entry.item]
  5221. if item ~= nil and item.throw == 1 then
  5222. table.insert(entries, {name = item.name .. " " .. tostring(entry.quantity), throw_item = entry.item, enabled = true})
  5223. end
  5224. end
  5225. end
  5226. elseif kind == "item" then
  5227. for slot = 0, MAX_INVENTORY_SLOTS do
  5228. local entry = Inventory[slot]
  5229. if entry ~= nil and entry.quantity > 0 then
  5230. local item = Game.Items[entry.item]
  5231. -- Only the items that can be used in battle (weapons and armor can't).
  5232. if item ~= nil and item.battle == 1 then
  5233. -- The item of the first choice of a double command can't be used again if there is no more.
  5234. local left = entry.quantity - ((self.w_first ~= nil and self.w_first.item_id == entry.item) and 1 or 0)
  5235. table.insert(entries, {name = item.name .. " " .. tostring(entry.quantity), item_id = entry.item, enabled = left > 0})
  5236. end
  5237. end
  5238. end
  5239. end
  5240. return self:build_list_rows(kind, entries)
  5241. end,
  5242. --- Widths of the list window: the magic list has several spells in each row.
  5243. LIST_WIDTH = 120,
  5244. MAGIC_LIST_WIDTH = 302,
  5245. --- Longest name shown in the magic list (the columns fit 10 characters).
  5246. MAGIC_NAME_LENGTH = 10,
  5247. --- Colour of the modifiers of the magic list.
  5248. LIST_TAG_COLOUR = {0.8, 0.5, 1},
  5249. --- Gets the entry under the cursor of the list window.
  5250. get_list_entry = function(self)
  5251. local row = self.list_entries[self.cursor_list + self.first_list - 1]
  5252. if row == nil then return nil end
  5253. return row.entries[math.min(self.cursor_col, #row.entries)]
  5254. end,
  5255. --- Moves the cursor of the list window to its row and column.
  5256. update_list_cursor = function(self)
  5257. local row = self.list_entries[self.cursor_list + self.first_list - 1]
  5258. if row ~= nil and self.cursor_col > #row.entries then self.cursor_col = #row.entries end
  5259. local name = "Position" .. tostring(self.cursor_list)
  5260. if self.current_list == "magic" then name = name .. "_" .. tostring(self.cursor_col) end
  5261. ui_manager:get_widget("BattleUi.Container.Bottom.List.Cursor"):set_default_animation(name)
  5262. end,
  5263. --- Gets the modifiers of the materia linked to a spell, as the three letter strings of the list.
  5264. get_spell_tags = function(self, links)
  5265. local tags = {}
  5266. if links == nil then return tags end
  5267. if (links.all or 0) > 0 then table.insert(tags, "ALL") end
  5268. if (links.mp_turbo or 0) > 0 then table.insert(tags, "MPT") end
  5269. if (links.hp_absorb or 0) > 0 then table.insert(tags, "HPA") end
  5270. if (links.mp_absorb or 0) > 0 then table.insert(tags, "MPA") end
  5271. if (links.quadra or 0) > 0 then table.insert(tags, " x4") end
  5272. return tags
  5273. end,
  5274. --- Groups the entries of a list in rows. The spells of the same materia go in the same row, four
  5275. -- at most (a materia with more, like Master Magic, continues in the next row), with the first modifier of the materia.
  5276. -- The rows of the other lists have one entry.
  5277. --
  5278. -- @return Rows: {entries = {...}, tag = text of the modifiers}.
  5279. build_list_rows = function(self, kind, entries)
  5280. local rows = {}
  5281. for _, entry in ipairs(entries) do
  5282. local row = rows[#rows]
  5283. if kind == "magic" and row ~= nil and row.group == entry.group and #row.entries < 4 then
  5284. table.insert(row.entries, entry)
  5285. else
  5286. row = {entries = {entry}, group = entry.group}
  5287. -- The first column only fits one modifier.
  5288. row.tag = self:get_spell_tags(entry.links)[1] or ""
  5289. table.insert(rows, row)
  5290. end
  5291. end
  5292. return rows
  5293. end,
  5294. --- Populates the list window.
  5295. --
  5296. -- Uses the rows in {@see list_entries}, starting at {@see first_list}.
  5297. populate_list = function(self)
  5298. local magic = self.current_list == "magic"
  5299. local columns = {"A", "B", "C", "D"}
  5300. for pos = 1, 4 do
  5301. local single = ui_manager:get_widget("BattleUi.Container.Bottom.List.List" .. tostring(pos))
  5302. local tag = ui_manager:get_widget("BattleUi.Container.Bottom.List.ListTag" .. tostring(pos))
  5303. local row = self.list_entries[pos + self.first_list - 1]
  5304. -- The magic list uses the tag and spell widgets, the other ones the single widget.
  5305. single:set_visible(false)
  5306. tag:set_visible(false)
  5307. for _, letter in ipairs(columns) do
  5308. ui_manager:get_widget("BattleUi.Container.Bottom.List.List" .. letter .. tostring(pos)):set_visible(false)
  5309. end
  5310. if row ~= nil then
  5311. -- Entries that can't be used are greyed out. The colour has to be set before the
  5312. -- text, as it's applied to it when it's set.
  5313. if magic then
  5314. if row.tag ~= "" then
  5315. tag:set_colour(self.LIST_TAG_COLOUR[1], self.LIST_TAG_COLOUR[2], self.LIST_TAG_COLOUR[3])
  5316. tag:set_text(row.tag)
  5317. tag:set_visible(true)
  5318. end
  5319. for index, entry in ipairs(row.entries) do
  5320. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.List.List" .. columns[index] .. tostring(pos))
  5321. if entry.enabled then widget:set_colour(1, 1, 1) else widget:set_colour(0.5, 0.5, 0.5) end
  5322. widget:set_text(string.sub(entry.name, 1, self.MAGIC_NAME_LENGTH))
  5323. widget:set_visible(true)
  5324. end
  5325. else
  5326. local entry = row.entries[1]
  5327. if entry.enabled then single:set_colour(1, 1, 1) else single:set_colour(0.5, 0.5, 0.5) end
  5328. single:set_text(entry.name)
  5329. single:set_visible(true)
  5330. end
  5331. end
  5332. end
  5333. end,
  5334. --- Populates the summon selction window.
  5335. --
  5336. -- It uses the summons the current character can use.
  5337. populate_summon_list = function(self)
  5338. self:populate_list()
  5339. end,
  5340. --- Load enemies
  5341. load_enemies = function(self)
  5342. local total = battle_manager:get_enemy_count()
  5343. for e = 0, total - 1 do
  5344. local enemy_src = battle_manager:get_enemy(e)
  5345. enemy = {}
  5346. enemy.dead = false
  5347. enemy.status = {}
  5348. enemy.atb = math.random(0, 255)
  5349. enemy.id = enemy_src:get_id()
  5350. enemy.level = enemy_src:get_level()
  5351. enemy.name = enemy_src:get_name()
  5352. enemy.exp = enemy_src:get_exp()
  5353. enemy.ap = enemy_src:get_ap()
  5354. enemy.money = enemy_src:get_money()
  5355. enemy.stats = {}
  5356. enemy.stats.str = enemy_src:get_str();
  5357. enemy.stats.def = enemy_src:get_def();
  5358. enemy.stats.mag = enemy_src:get_mag();
  5359. enemy.stats.spr = enemy_src:get_spr();
  5360. enemy.stats.dex = enemy_src:get_dex();
  5361. enemy.stats.lck = enemy_src:get_lck();
  5362. enemy.stats.eva = enemy_src:get_eva();
  5363. enemy.stats.meva = enemy_src:get_meva();
  5364. enemy.stats.hp = enemy_src:get_hp();
  5365. enemy.stats.hp_max = enemy_src:get_hp_max();
  5366. enemy.stats.mp = enemy_src:get_mp();
  5367. enemy.stats.mp_max = enemy_src:get_mp_max();
  5368. -- Debug: Battle.debug_enemy_hp (set by the test menu) gives all the enemies that HP.
  5369. if Battle.debug_enemy_hp ~= nil then
  5370. enemy.stats.hp = Battle.debug_enemy_hp
  5371. enemy.stats.hp_max = Battle.debug_enemy_hp
  5372. end
  5373. -- TODO: Get more data
  5374. table.insert(self.enemies, enemy)
  5375. end
  5376. end,
  5377. --- Bone of the skeleton that holds the weapon, by the two letter prefix of the battle model.
  5378. --
  5379. -- Derived from the skeleton of each model: the arm chains hang from the spine, the chains from the
  5380. -- root are the legs. The hand of the second arm chain was chosen (the right one is a guess for all
  5381. -- but Barret, whose gun arm is the right one). If a weapon is in the wrong hand, use the hand of the
  5382. -- first arm chain instead: rt 7, ru 15, rv 12, rx 10, ry 19, rz 8, sb-se 7, sf-sh 41.
  5383. WEAPON_BONES = {
  5384. rt = 12, si = 12, ru = 22, rv = 17, rx = 18, ry = 24, rz = 16,
  5385. sb = 11, sc = 11, sd = 11, se = 11, sf = 46, sg = 46, sh = 46,
  5386. },
  5387. --- Extra rotation {x, y, z} in degrees of the weapon of each battle model, around the axes of the
  5388. -- weapon model itself, by the two letter prefix. Tune it here (no reinstall needed) until the weapons
  5389. -- look right; models not listed use no rotation.
  5390. WEAPON_ROTATIONS = {
  5391. rt = {90, 0, 0},
  5392. },
  5393. --- Battle model of the owner of each character of the kernel, to find the model of a thrown weapon.
  5394. THROW_MODELS = {
  5395. [0] = "rt_cloud", [1] = "sb_barret", [2] = "ru_tifa", [3] = "rv_aeris", [5] = "rx_yuffie",
  5396. [6] = "ry_cait_sith", [7] = "sf_vincent", [8] = "rz_cid",
  5397. },
  5398. --- Gets the mesh of a thrown thing: the model of the weapon, of the character that can use it.
  5399. --
  5400. -- @return Name of the mesh without extension, nil if it isn't a weapon with a model.
  5401. get_throw_mesh = function(self, item_id)
  5402. local item = Game.Items[item_id]
  5403. if item == nil or item.type ~= Inventory.ITEM_TYPE.WEAPON or item.model == nil then return nil end
  5404. for _, user in ipairs(item.users or {}) do
  5405. local model = self.THROW_MODELS[user]
  5406. if model ~= nil then return string.format("characters/%s_weapon_%02d", model, item.model) end
  5407. end
  5408. return nil
  5409. end,
  5410. --- Puts the weapon a party member has equipped in the hand of its battle model.
  5411. --
  5412. -- Weapon models are installed as <model>_weapon_NN.mesh, where NN is the model number of the weapon
  5413. -- (see the `model` field of the weapons). Red XIII has none.
  5414. --
  5415. -- @param index Index in the party (1 based).
  5416. attach_weapon = function(self, index)
  5417. local entity = self:get_entity(Battle.TargetGroup.PARTY, index)
  5418. local model = self:get_model_name(Battle.TargetGroup.PARTY, index)
  5419. if entity == nil or model == nil or model == "" then return end
  5420. local bone = self.WEAPON_BONES[string.sub(model, 1, 2)]
  5421. if bone == nil then return end
  5422. local character = Characters[self.party[index].character]
  5423. local weapon = (character ~= nil and character.weapon ~= nil) and Game.Items[character.weapon.id] or nil
  5424. if weapon == nil or weapon.model == nil then return end
  5425. local rot = self.WEAPON_ROTATIONS[string.sub(model, 1, 2)] or {0, 0, 0}
  5426. entity:attach_model(
  5427. string.format("characters/%s_weapon_%02d.mesh", model, weapon.model), bone, rot[1], rot[2], rot[3]
  5428. )
  5429. end,
  5430. --- Loads party character data
  5431. --
  5432. --- Gets the effects of the support materia linked to the materia of a slot.
  5433. --
  5434. -- @param equip The weapon or armor of the character ({@see Characters}).
  5435. -- @param slot Slot of the materia (1-8).
  5436. -- @return A table: all (times it can be used on all the targets, per battle), mp_turbo (percent
  5437. -- of extra power), hp_absorb, mp_absorb, quadra (times per battle), added_cut and steal_as_well (0 or 1).
  5438. get_materia_links = function(self, equip, slot)
  5439. local links = {all = 0, mp_turbo = 0, hp_absorb = 0, mp_absorb = 0, quadra = 0, added_cut = 0, steal_as_well = 0}
  5440. local item = Game.Items[equip.id]
  5441. if item == nil or item.slots == nil then return links end
  5442. for _, partner_slot in ipairs(Characters.get_linked_slots(item, slot)) do
  5443. local partner = equip.materia[partner_slot - 1]
  5444. local definition = partner ~= nil and Game.Materia[partner.id] or nil
  5445. if definition ~= nil and definition.link ~= nil then
  5446. local id = definition.link.id
  5447. local level = Characters.get_materia_level(definition, partner.ap or 0)
  5448. local param = definition.link.param[level] or definition.link.param[1] or 0
  5449. if id == Materia.LINK.ALL then links.all = math.max(links.all, param)
  5450. elseif id == Materia.LINK.MP_TURBO then links.mp_turbo = math.max(links.mp_turbo, param)
  5451. elseif id == Materia.LINK.HP_ABSORB then links.hp_absorb = 1
  5452. elseif id == Materia.LINK.MP_ABSORB then links.mp_absorb = 1
  5453. elseif id == Materia.LINK.QUADRA_MAGIC then links.quadra = math.max(links.quadra, param)
  5454. elseif id == Materia.LINK.ADDED_CUT then links.added_cut = 1
  5455. elseif id == Materia.LINK.STEAL_AS_WELL then links.steal_as_well = 1
  5456. end
  5457. end
  5458. end
  5459. return links
  5460. end,
  5461. --- Gets the counterattacks of a character: Counter materia paired with a command materia, and
  5462. -- Magic Counter materia paired with a magic materia.
  5463. --
  5464. -- Final Attack materia are in the list too, with final = true and the times they can be used per
  5465. -- battle in uses, and Sneak Attack ones with sneak = true.
  5466. --
  5467. -- @return A list of {chance = 0 to 1, command = command ID} or {chance, spells = {attack IDs, from the
  5468. -- lowest level to the highest}}.
  5469. get_counters = function(self, char)
  5470. local counters = {}
  5471. for _, equip in ipairs({char.weapon, char.armor}) do
  5472. local item = Game.Items[equip.id]
  5473. if item ~= nil and item.slots ~= nil then
  5474. for slot = 1, #item.slots do
  5475. local equipped = equip.materia[slot - 1]
  5476. local definition = equipped ~= nil and Game.Materia[equipped.id] or nil
  5477. local link = definition ~= nil and definition.link or nil
  5478. if link ~= nil and (link.id == Materia.LINK.COMMAND_COUNTER or link.id == Materia.LINK.MAGIC_COUNTER
  5479. or link.id == Materia.LINK.FINAL_ATTACK or link.id == Materia.LINK.SNEAK_ATTACK) then
  5480. local level = Characters.get_materia_level(definition, equipped.ap or 0)
  5481. local param = link.param[level] or link.param[1] or 0
  5482. local chance = param / 100
  5483. -- Final Attack: the level is the times it can be used per battle.
  5484. local final = link.id == Materia.LINK.FINAL_ATTACK
  5485. -- Sneak Attack: the level is the chance of using the paired materia at the start.
  5486. local sneak = link.id == Materia.LINK.SNEAK_ATTACK
  5487. for _, partner_slot in ipairs(Characters.get_linked_slots(item, slot)) do
  5488. local partner = equip.materia[partner_slot - 1]
  5489. local partner_def = partner ~= nil and Game.Materia[partner.id] or nil
  5490. if partner_def ~= nil then
  5491. local partner_level = Characters.get_materia_level(partner_def, partner.ap or 0)
  5492. if (link.id == Materia.LINK.COMMAND_COUNTER or final or sneak) and partner_def.type == 3 then
  5493. -- The highest command of the materia.
  5494. local command = nil
  5495. for lv, id in ipairs(partner_def.command or {}) do
  5496. if partner_level >= lv then command = id end
  5497. end
  5498. if command ~= nil then table.insert(counters, {chance = chance, command = command, final = final, sneak = sneak, uses = param}) end
  5499. elseif (link.id == Materia.LINK.MAGIC_COUNTER or final or sneak) and partner_def.type == 1 then
  5500. local spells = {}
  5501. for lv, id in ipairs(partner_def.magic or {}) do
  5502. if partner_level >= lv then table.insert(spells, id) end
  5503. end
  5504. if #spells > 0 then table.insert(counters, {chance = chance, spells = spells, final = final, sneak = sneak, uses = param}) end
  5505. end
  5506. end
  5507. end
  5508. end
  5509. end
  5510. end
  5511. end
  5512. return counters
  5513. end,
  5514. --- Queues the counterattacks of a party member that was hurt by an enemy.
  5515. --
  5516. -- Counter materia attack back with the command they are paired with (the commands that change the
  5517. -- attack, like Slash-All, aren't done and count as a normal attack), and Magic Counter materia cast
  5518. -- the highest spell of the paired magic materia (nothing if the MP doesn't allow it). Counter Attack
  5519. -- materia only counter physical attacks. They only
  5520. -- counter the enemy that attacked, and are cancelled if it died. They go in front of the queue.
  5521. -- TODO: Summons (Magic Counter with a summon materia) aren't done.
  5522. party_counter = function(self, index, attacker_side, attacker_index, physical)
  5523. local member = self.party[index]
  5524. if member == nil or member.dead or self:is_frozen(Battle.TargetGroup.PARTY, index) or self:acts_by_itself(Battle.TargetGroup.PARTY, index) then
  5525. do return end
  5526. end
  5527. -- Only the enemy that attacked is countered. If it's gone, there is no counterattack.
  5528. local enemy = attacker_index
  5529. if self.enemies[enemy] == nil or self.enemies[enemy].dead then do return end end
  5530. for _, counter in ipairs(member.counters or {}) do
  5531. if not counter.final and not counter.sneak and (not counter.physical or physical) and math.random() < counter.chance then
  5532. local action = {
  5533. actor = index, actor_side = Battle.TargetGroup.PARTY, is_counter = true, no_retarget = true,
  5534. target_type = Battle.TargetType.SINGLE, target_group = Battle.TargetGroup.ENEMIES, target_index = enemy,
  5535. }
  5536. if counter.command ~= nil then
  5537. action.type = Battle.ActionType.COMMAND
  5538. -- The commands that change the attack are done, the other ones count as an attack.
  5539. action.command = (counter.command >= 24 and counter.command <= 27) and counter.command or 1
  5540. -- Slash-All counters hit all the enemies, the other ones only the attacker.
  5541. if counter.command == 24 or counter.command == 26 then
  5542. action.target_type = Battle.TargetType.GROUP
  5543. action.target_index = nil
  5544. action.no_retarget = nil
  5545. end
  5546. else
  5547. -- Always the highest spell of the materia. Without the MP for it, there is no counterattack.
  5548. local mp = Characters[member.character].stats.mp.current
  5549. local spell = counter.spells[#counter.spells]
  5550. local cost = Game.Attacks[spell] ~= nil and Game.Attacks[spell].mp or nil
  5551. if cost ~= nil and cost > mp then
  5552. print("Magic Counter of " .. self:get_combatant_name(Battle.TargetGroup.PARTY, index) .. ": no MP for " .. Game.Attacks[spell].name)
  5553. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, index, "No MP", {1, 0.6, 0.6})
  5554. spell = nil
  5555. end
  5556. if spell ~= nil then
  5557. local data = Game.Attacks[spell]
  5558. action.type = Battle.ActionType.ATTACK
  5559. action.command = 2
  5560. action.attack_id = spell
  5561. if data.target.default_enemy == 0 then
  5562. -- Restoring spells go to the one that casts them.
  5563. action.target_group = Battle.TargetGroup.PARTY
  5564. action.target_index = index
  5565. elseif data.target.default_multiple == 1 and data.target.toggle_multiple ~= 1 then
  5566. action.target_type = Battle.TargetType.GROUP
  5567. action.target_index = nil
  5568. end
  5569. else
  5570. action = nil
  5571. end
  5572. end
  5573. if action ~= nil then
  5574. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, index, "Counter", {1, 1, 0.6})
  5575. local position = math.min((self.ai_counter_count or 0) + 1, #self.action_queue + 1)
  5576. table.insert(self.action_queue, position, action)
  5577. self.ai_counter_count = position
  5578. end
  5579. end
  5580. end
  5581. end,
  5582. --- Queues the Sneak Attacks at the start of the battle: each Sneak Attack materia has a chance (its
  5583. -- level) of making the character use the paired command (an Attack replacement) or the highest spell
  5584. -- of the paired magic materia before anyone else acts, on a random enemy. They don't use the turn of
  5585. -- the character. Nothing happens if the MP doesn't allow the spell.
  5586. -- TODO: Summons aren't done, and it is unknown if the original also does it in back attacks.
  5587. queue_sneak_attacks = function(self)
  5588. local position = 0
  5589. for index = 1, #self.party do
  5590. local member = self.party[index]
  5591. for _, counter in ipairs(member.counters or {}) do
  5592. if counter.sneak and math.random() < counter.chance then
  5593. local target = self:random_living(Battle.TargetGroup.ENEMIES)
  5594. if target == nil then do return end end
  5595. local action = {
  5596. actor = index, actor_side = Battle.TargetGroup.PARTY, no_atb = true, sneak_attack = true,
  5597. target_type = Battle.TargetType.SINGLE, target_group = Battle.TargetGroup.ENEMIES, target_index = target,
  5598. }
  5599. if counter.command ~= nil then
  5600. action.type = Battle.ActionType.COMMAND
  5601. action.command = (counter.command >= 24 and counter.command <= 27) and counter.command or 1
  5602. if counter.command == 24 or counter.command == 26 then
  5603. action.target_type = Battle.TargetType.GROUP
  5604. action.target_index = nil
  5605. end
  5606. else
  5607. local mp = Characters[member.character].stats.mp.current
  5608. local spell = counter.spells[#counter.spells]
  5609. local data = Game.Attacks[spell]
  5610. if data == nil or data.mp > mp then
  5611. if data ~= nil then
  5612. print("Sneak Attack of " .. self:get_combatant_name(Battle.TargetGroup.PARTY, index) .. ": no MP for " .. data.name)
  5613. end
  5614. action = nil
  5615. else
  5616. action.type = Battle.ActionType.ATTACK
  5617. action.command = 2
  5618. action.attack_id = spell
  5619. if data.target.default_enemy == 0 then
  5620. -- Restoring spells go to a random ally.
  5621. action.target_group = Battle.TargetGroup.PARTY
  5622. action.target_index = self:random_living(Battle.TargetGroup.PARTY)
  5623. elseif data.target.default_multiple == 1 and data.target.toggle_multiple ~= 1 then
  5624. action.target_type = Battle.TargetType.GROUP
  5625. action.target_index = nil
  5626. end
  5627. end
  5628. end
  5629. if action ~= nil then
  5630. position = position + 1
  5631. table.insert(self.action_queue, math.min(position, #self.action_queue + 1), action)
  5632. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, index, "Sneak Attack", {1, 1, 0.6})
  5633. end
  5634. end
  5635. end
  5636. end
  5637. end,
  5638. --- Queues the Final Attack of a party member that just died: it uses the paired command (a normal
  5639. -- attack) or the highest spell of the paired magic materia once, on a random enemy, a number of times
  5640. -- per battle. It does nothing if the MP doesn't allow the spell.
  5641. -- TODO: Summons aren't done.
  5642. queue_final_attack = function(self, index)
  5643. local member = self.party[index]
  5644. if member == nil or self.ending == true then do return end end
  5645. member.final_used = member.final_used or {}
  5646. for key, counter in ipairs(member.counters or {}) do
  5647. if counter.final and (member.final_used[key] or 0) < counter.uses then
  5648. local target = self:random_living(Battle.TargetGroup.ENEMIES)
  5649. if target == nil then do return end end
  5650. local action = {
  5651. actor = index, actor_side = Battle.TargetGroup.PARTY, is_counter = true, allow_dead = true, final_attack = true,
  5652. target_type = Battle.TargetType.SINGLE, target_group = Battle.TargetGroup.ENEMIES, target_index = target,
  5653. }
  5654. if counter.command ~= nil then
  5655. action.type = Battle.ActionType.COMMAND
  5656. action.command = (counter.command >= 24 and counter.command <= 27) and counter.command or 1
  5657. if counter.command == 24 or counter.command == 26 then
  5658. action.target_type = Battle.TargetType.GROUP
  5659. action.target_index = nil
  5660. end
  5661. else
  5662. local mp = Characters[member.character].stats.mp.current
  5663. local spell = counter.spells[#counter.spells]
  5664. local data = Game.Attacks[spell]
  5665. if data ~= nil and data.mp > mp then
  5666. print("Final Attack of " .. self:get_combatant_name(Battle.TargetGroup.PARTY, index) .. ": no MP for " .. data.name)
  5667. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, index, "No MP", {1, 0.6, 0.6})
  5668. action = nil
  5669. elseif data ~= nil then
  5670. action.type = Battle.ActionType.ATTACK
  5671. action.command = 2
  5672. action.attack_id = spell
  5673. if data.target.default_enemy == 0 then
  5674. -- Restoring spells go to a random ally that is alive.
  5675. local ally = self:random_living(Battle.TargetGroup.PARTY)
  5676. if ally == nil then action = nil
  5677. else
  5678. action.target_group = Battle.TargetGroup.PARTY
  5679. action.target_index = ally
  5680. end
  5681. elseif data.target.default_multiple == 1 and data.target.toggle_multiple ~= 1 then
  5682. action.target_type = Battle.TargetType.GROUP
  5683. action.target_index = nil
  5684. end
  5685. else
  5686. action = nil
  5687. end
  5688. end
  5689. if action ~= nil then
  5690. member.final_used[key] = (member.final_used[key] or 0) + 1
  5691. UiContainer.BattleFx:text(Battle.TargetGroup.PARTY, index, "Final Attack", {1, 1, 0.6})
  5692. local position = math.min((self.ai_counter_count or 0) + 1, #self.action_queue + 1)
  5693. table.insert(self.action_queue, position, action)
  5694. self.ai_counter_count = position
  5695. end
  5696. end
  5697. end
  5698. end,
  5699. --- Maximum gil that can be thrown with Coin: all the gil of the party, in tens.
  5700. coin_limit = function(self) return math.floor((Inventory.money or 0) / 10) * 10 end,
  5701. --- Opens the gil selection of Coin, in the message window.
  5702. open_coin_window = function(self)
  5703. if self:coin_limit() < 10 then
  5704. audio_manager:play_sound("Error")
  5705. do return end
  5706. end
  5707. audio_manager:play_sound("Cursor")
  5708. self.coin = {amount = math.min(self:coin_limit(), 100), step = 10}
  5709. self.window_state = "coin"
  5710. self:show_coin_amount()
  5711. end,
  5712. --- Shows the gil chosen for Coin in its window.
  5713. show_coin_amount = function(self)
  5714. local base = "BattleUi.Container.Bottom.Coin."
  5715. ui_manager:get_widget(base .. "Title"):set_text(Game.Commands[self.COIN_COMMAND].name)
  5716. ui_manager:get_widget(base .. "Amount"):set_text(string.format("%d Gil", self.coin.amount))
  5717. ui_manager:get_widget(base .. "Step"):set_text(string.format("+-%d", self.coin.step))
  5718. ui_manager:get_widget("BattleUi.Container.Bottom.Coin"):set_visible(true)
  5719. end,
  5720. --- Closes the window of Coin.
  5721. close_coin_window = function(self)
  5722. ui_manager:get_widget("BattleUi.Container.Bottom.Coin"):set_visible(false)
  5723. end,
  5724. --- Handles a button in the gil selection of Coin: up and down change the amount by the step, left and right
  5725. -- the step (10 to 100000). Confirm throws the gil at all the enemies.
  5726. handle_coin_button = function(self, button)
  5727. local coin = self.coin
  5728. local limit = self:coin_limit()
  5729. if button == Config.ACTIONS.CANCEL then
  5730. audio_manager:play_sound("Cursor")
  5731. self:close_coin_window()
  5732. self.window_state = "command"
  5733. elseif button == Config.ACTIONS.CONFIRM then
  5734. audio_manager:play_sound("Cursor")
  5735. self:close_coin_window()
  5736. self.selected_command = self.COIN_COMMAND
  5737. self.current_list = "none"
  5738. self.selected_attack = nil
  5739. self.selected_item = nil
  5740. self.selected_summon = nil
  5741. self.selected_limit = nil
  5742. self.selected_links = nil
  5743. self.selected_throw = nil
  5744. self.selected_coin = math.min(coin.amount, limit)
  5745. self.target_group = Battle.TargetGroup.ENEMIES
  5746. self.target_type = Battle.TargetType.GROUP
  5747. self.target_index = nil
  5748. self:queue_character_action()
  5749. return
  5750. elseif button == Config.CONTROLS.UP then coin.amount = math.min(limit, coin.amount + coin.step)
  5751. elseif button == Config.CONTROLS.DOWN then coin.amount = math.max(10, coin.amount - coin.step)
  5752. elseif button == Config.CONTROLS.RIGHT then coin.step = math.min(100000, coin.step * 10)
  5753. elseif button == Config.CONTROLS.LEFT then coin.step = math.max(10, coin.step / 10)
  5754. else return end
  5755. audio_manager:play_sound("Cursor")
  5756. self:show_coin_amount()
  5757. end,
  5758. COIN_COMMAND = 7,
  5759. --- IDs of the commands in Game.Commands.
  5760. STEAL_COMMAND = 5,
  5761. SENSE_COMMAND = 6,
  5762. MUG_COMMAND = 17,
  5763. MORPH_COMMAND = 9,
  5764. --- Commands that the kernel marks as having no menu, but choose an enemy (Sense, Morph and D.blow).
  5765. ENEMY_COMMANDS = {[6] = true, [9] = true, [10] = true, [11] = true},
  5766. MANIP_COMMAND = 11,
  5767. MIME_COMMAND = 12,
  5768. DBLOW_COMMAND = 10,
  5769. --- Chance of the statuses that Added Effect materia gives to the attacks, out of 1 (5 of 63).
  5770. ADDED_EFFECT_CHANCE = 5 / 63,
  5771. --- Names of the elements, by element id.
  5772. ELEMENT_NAMES = {[0] = "Fire", "Ice", "Bolt", "Earth", "Poison", "Gravity", "Water", "Wind", "Holy",
  5773. "Restorative", "Cut", "Hit", "Punch", "Shoot", "Shout"},
  5774. --- Shows the information of an enemy (Sense): name, level, HP, MP, how it reacts to the elements
  5775. -- (weak, half, nullified or absorbed) and the statuses it has now.
  5776. sense = function(self, actor, target)
  5777. local enemy = self.enemies[target]
  5778. if enemy == nil then do return end end
  5779. local source = battle_manager:get_enemy(target - 1)
  5780. local text = string.format("%s Lv%d HP %d/%d MP %d/%d", enemy.name, source:get_level(), enemy.stats.hp,
  5781. enemy.stats.hp_max, enemy.stats.mp, enemy.stats.mp_max)
  5782. local groups = {weak = {}, half = {}, none = {}, absorb = {}}
  5783. for e = 0, source:get_element_count() - 1 do
  5784. local name = self.ELEMENT_NAMES[source:get_element(e)]
  5785. local factor = source:get_element_factor(e)
  5786. if name ~= nil then
  5787. if factor < 0 then table.insert(groups.absorb, name)
  5788. elseif factor == 0 then table.insert(groups.none, name)
  5789. elseif factor < 1 then table.insert(groups.half, name)
  5790. elseif factor > 1 then table.insert(groups.weak, name) end
  5791. end
  5792. end
  5793. for _, entry in ipairs({{"weak", "Weak"}, {"half", "Resists"}, {"none", "Immune"}, {"absorb", "Absorbs"}}) do
  5794. if #groups[entry[1]] > 0 then text = text .. " | " .. entry[2] .. ": " .. table.concat(groups[entry[1]], ", ") end
  5795. end
  5796. local statuses = {}
  5797. for id = 0, 26 do
  5798. if self:has_status(Battle.TargetGroup.ENEMIES, target, id) then table.insert(statuses, BattleStatus.NAME[id]) end
  5799. end
  5800. if #statuses > 0 then text = text .. " | Status: " .. table.concat(statuses, ", ") end
  5801. self:show_message(text, false)
  5802. self.message_until = timer:get_game_time_total() + 4
  5803. end,
  5804. --- Tries to steal an item from an enemy.
  5805. --
  5806. -- As in ff7.exe (0x5ca7d0 and the item roll 0x5c7c1e): each steal item (in order) has a rate of 0..63 that is
  5807. -- scaled by (thief level + 40 - enemy level) percent (Mug never goes below 100%); the item is the first
  5808. -- one with a roll of 0..63 that is less than or equal to the scaled rate. Only one item can be stolen from
  5809. -- each enemy. With allow_dead, it can be stolen from an enemy that was just killed (Steal as well and Mug).
  5810. try_steal = function(self, actor, target, allow_dead, mug)
  5811. local enemy = self.enemies[target]
  5812. if enemy == nil or (enemy.dead and not allow_dead) then do return end end
  5813. local colour = {1, 1, 0.6}
  5814. if enemy.stolen then
  5815. UiContainer.BattleFx:text(Battle.TargetGroup.ENEMIES, target, "Nothing left", colour)
  5816. do return end
  5817. end
  5818. local source = battle_manager:get_enemy(target - 1)
  5819. local percent = self:get_combat_stats(Battle.TargetGroup.PARTY, actor).level + 40 - source:get_level()
  5820. if mug and percent < 100 then percent = 100 end
  5821. for i = 0, source:get_steal_count() - 1 do
  5822. local rate = math.floor(source:get_steal_rate(i) * 63 + 0.5)
  5823. local scaled = math.floor(rate * math.floor(percent * 512 / 100) / 256)
  5824. if math.random(0, 63) <= scaled then
  5825. local id = source:get_steal_id(i)
  5826. local item = Game.Items[id]
  5827. Inventory.add_item(id, 1)
  5828. enemy.stolen = true
  5829. print(self:get_combatant_name(Battle.TargetGroup.PARTY, actor) .. " steals " .. (item ~= nil and item.name or tostring(id)))
  5830. UiContainer.BattleFx:text(Battle.TargetGroup.ENEMIES, target, "Stole " .. (item ~= nil and item.name or tostring(id)), colour)
  5831. do return end
  5832. end
  5833. end
  5834. UiContainer.BattleFx:text(Battle.TargetGroup.ENEMIES, target, "Couldn't steal", colour)
  5835. end,
  5836. --- Adds a spell or summon to a list, merging the links if it is already there.
  5837. add_spell = function(self, list, spell)
  5838. for _, other in ipairs(list) do
  5839. if other.id == spell.id then
  5840. for _, key in ipairs({"all", "mp_turbo", "hp_absorb", "mp_absorb", "quadra", "added_cut", "steal_as_well"}) do
  5841. other[key] = math.max(other[key] or 0, spell[key] or 0)
  5842. end
  5843. return
  5844. end
  5845. end
  5846. table.insert(list, spell)
  5847. end,
  5848. --- Gets the MP an attack costs with the materia linked to it (MP Turbo adds its percent).
  5849. get_spell_cost = function(self, mp, links)
  5850. if links == nil or (links.mp_turbo or 0) == 0 then return mp end
  5851. return math.ceil(mp * (100 + links.mp_turbo) / 100)
  5852. end,
  5853. --- Gets a copy of an attack changed by the materia linked to it: MP Turbo adds power, HP Absorb
  5854. -- makes it heal the caster as much as it damages, and MP Absorb gives the caster that much MP.
  5855. apply_links = function(self, attack, links)
  5856. if links == nil then return attack end
  5857. local damage = {}
  5858. for key, value in pairs(attack.damage) do damage[key] = value end
  5859. damage.power_bonus = links.mp_turbo or 0
  5860. if (links.hp_absorb or 0) > 0 then damage.drain_hp = 1 end
  5861. if (links.mp_absorb or 0) > 0 then damage.drain_mp = 1 end
  5862. local copy = {}
  5863. for key, value in pairs(attack) do copy[key] = value end
  5864. copy.damage = damage
  5865. return copy
  5866. end,
  5867. --- Gets a copy of an attack with half of its power, the one of each of the casts of Quadra Magic.
  5868. apply_quadra = function(self, attack)
  5869. local damage = {}
  5870. for key, value in pairs(attack.damage) do damage[key] = value end
  5871. damage.power = (damage.power or 0) / 2
  5872. local copy = {}
  5873. for key, value in pairs(attack) do copy[key] = value end
  5874. copy.damage = damage
  5875. return copy
  5876. end,
  5877. -- Reads materia, calculates stats, computes attacks...
  5878. -- TODO: Move most of this code to Characters.recalculate_stats()
  5879. load_party_members = function(self)
  5880. for i = 1, Party.MAX do
  5881. if self:has_character_data(Party[i]) then
  5882. -- The stats depend on the equipment and the materia (HP<->MP swaps the HP and the MP).
  5883. Characters.recalculate_stats(Party[i])
  5884. self.party[i] = {}
  5885. self.party[i].character = Party[i]
  5886. self:attach_weapon(i)
  5887. --math.randomseed(('' .. os.time()):reverse())
  5888. -- TODO: Consider battle layouts.
  5889. -- TODO: Check random seed
  5890. self.party[i].dead = false
  5891. self.party[i].status = {}
  5892. -- Fury and Sadness remain after the battles.
  5893. for _, id in ipairs(Characters[Party[i]].status or {}) do
  5894. if id == BattleStatus.FURY or id == BattleStatus.SADNESS then
  5895. self.party[i].status[id] = {next_tick = timer:get_game_time_total() + BattleStatus.TICK}
  5896. end
  5897. end
  5898. -- Elements and statuses from the equipment and the linked materia.
  5899. self.party[i].effects = Characters.get_effects(Party[i])
  5900. self.party[i].acting = false
  5901. self.party[i].summon_used = {}
  5902. self.party[i].all_used = {}
  5903. self.party[i].quadra_used = {}
  5904. self.party[i].atb = math.random(0, 255)
  5905. self.party[i].command = {}
  5906. -- Set default "Attack" command.
  5907. self.party[i].command[1] = 1
  5908. self.party[i].magic = {}
  5909. self.party[i].summon = {}
  5910. -- What the independent materia do: Long Range, Mega All, Counter Attack, Cover, Pre-Emptive,
  5911. -- EXP Plus and Gil Plus.
  5912. self.party[i].independent = Characters.get_independent(Party[i])
  5913. self.party[i].defending = false
  5914. -- Characters in the back row start a bit behind.
  5915. local entity = self:get_entity(Battle.TargetGroup.PARTY, i)
  5916. if entity ~= nil then
  5917. local hx, hy, hz = entity:get_position()
  5918. self.party[i].home = {x = hx, y = hy, z = hz}
  5919. end
  5920. if Characters[Party[i]].back_row == true then self:move_row(i, true, true) end
  5921. self.party[i].mega_all_used = 0
  5922. -- Fill Limit UI bar
  5923. -- 0 -> 0%
  5924. -- 255 -> 18%-6
  5925. local width_percent = math.min(18, 18 * Characters[self.party[i].character].limit.bar / 255)
  5926. local width_fixed = math.max(-6, -6 * width_percent / 18)
  5927. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.LimitFill"):set_width(width_percent, width_fixed)
  5928. -- Counter materia paired with a command or a magic materia.
  5929. self.party[i].counters = self:get_counters(Characters[Party[i]])
  5930. -- Counter Attack counters the physical attacks with a normal attack.
  5931. if self.party[i].independent.counter_attack > 0 then
  5932. table.insert(self.party[i].counters, {chance = self.party[i].independent.counter_attack / 100, command = 1, physical = true})
  5933. end
  5934. -- Read materia
  5935. local w_magic = false
  5936. local w_item = false
  5937. local w_summon = false
  5938. for e = 1, 2 do -- Loop for weapon, armor
  5939. local equip = nil
  5940. if e == 1 then equip = Characters[Party[i]].weapon
  5941. else equip = Characters[Party[i]].armor
  5942. end
  5943. for m = 1, 8 do -- lop for materia in weapon/armor
  5944. if equip.materia[m - 1] ~= nil then
  5945. local materia = Game.Materia[equip.materia[m - 1].id]
  5946. local ap = equip.materia[m - 1].ap
  5947. local level = 0
  5948. for l = 1, #materia.levels_ap do if materia.levels_ap[l] <= ap then level = l end end
  5949. local links = self:get_materia_links(equip, m)
  5950. if materia.type == 5 then -- Summon
  5951. local summon = {
  5952. id = materia.summon,
  5953. times = materia.times[level],
  5954. all = links.all,
  5955. quadra = links.quadra,
  5956. mp_turbo = links.mp_turbo,
  5957. mp_absorb = links.mp_absorb,
  5958. hp_absorb = links.hp_absorb,
  5959. sneak_attack = 0,
  5960. final_attack = 0,
  5961. added_cut = links.added_cut,
  5962. steal_as_well = links.steal_as_well
  5963. }
  5964. self:add_spell(self.party[i].summon, summon)
  5965. elseif materia.type == 1 then -- Magic
  5966. for lv, spell in ipairs(materia.magic) do
  5967. if level >= lv then
  5968. local magic = {
  5969. id = spell,
  5970. group = (e - 1) * 10 + m,
  5971. all = links.all,
  5972. quadra = links.quadra,
  5973. mp_turbo = links.mp_turbo,
  5974. mp_absorb = links.mp_absorb,
  5975. hp_absorb = links.hp_absorb,
  5976. sneak_attack = 0,
  5977. final_attack = 0,
  5978. added_cut = links.added_cut,
  5979. steal_as_well = links.steal_as_well
  5980. }
  5981. self:add_spell(self.party[i].magic, magic)
  5982. end
  5983. end
  5984. elseif materia.type == 3 then -- Command
  5985. -- Pick only the highest level command available
  5986. local command_id = nil
  5987. for lv, cmd in ipairs(materia.command) do if level >= lv then command_id = cmd end end
  5988. if command_id ~= nil then
  5989. -- The links of the materia that gives the Attack command (Steal as well).
  5990. if command_id ~= 20 and (command_id == 1 or command_id == 24 or command_id == 25 or command_id == 26 or command_id == 27) then
  5991. self.party[i].attack_links = links
  5992. end
  5993. if command_id == 1 or command_id == 20 or command_id == 24 or command_id == 25 or command_id == 26 or command_id == 27 then
  5994. -- Attack substitutes, index 1
  5995. -- TODO: Handle priorities
  5996. -- 1: Attack, 20: Limit, 24: Slash-all,
  5997. -- 25: 2x-Cut, 26: Flash, 27: 4x-Cut
  5998. self.party[i].command[1] = command_id
  5999. else
  6000. self.party[i].command[#self.party[i].command + 1] = command_id
  6001. end
  6002. if command_id == 21 then w_magic = true end
  6003. if command_id == 22 then w_summon = true end
  6004. if command_id == 23 then w_item = true end
  6005. end
  6006. end
  6007. -- TODO: Independent materia
  6008. -- TODO: Linked materia
  6009. end
  6010. end
  6011. end
  6012. -- Enable Item command if W-Item is disabled
  6013. if w_item == false then self.party[i].command[#self.party[i].command + 1] = 4 end
  6014. -- Enable Magic command if any magic is available and W-Magic is disabled.
  6015. if #self.party[i].magic > 0 and w_magic == false then self.party[i].command[#self.party[i].command + 1] = 2 end
  6016. -- Enable Summon command if any magic is available and W-Summon is disabled.
  6017. if #self.party[i].summon > 0 and w_summon == false then self.party[i].command[#self.party[i].command + 1] = 3 end
  6018. -- TODO: Sort commands/magic/summons
  6019. table.sort(
  6020. self.party[i].command,
  6021. function(l, r)
  6022. -- Attack substitutes always go first. The order has to be strict (an element is
  6023. -- never before itself, and two substitutes don't go before each other), or the
  6024. -- sort fails with "invalid order function".
  6025. local function substitute(id) return id == 1 or id == 20 or (id >= 24 and id <= 27) end
  6026. if substitute(l) ~= substitute(r) then return substitute(l) end
  6027. return l < r
  6028. end
  6029. )
  6030. -- The spells of a materia go together, in the order of the materia (weapon first).
  6031. if #self.party[i].magic > 1 then
  6032. table.sort(self.party[i].magic, function(l, r)
  6033. if l.group ~= r.group then return l.group < r.group end
  6034. return l.id < r.id
  6035. end)
  6036. end
  6037. if #self.party[i].summon > 1 then table.sort(self.party[i].summon, function(l, r) return l.id < r.id end) end
  6038. -- The first command is the Attack one (or its replacement), and the Limit one takes its place when
  6039. -- the limit bar is full.
  6040. self.party[i].attack_command = self.party[i].command[1]
  6041. -- The Item command, or W-Item, that a frog turns back into Item.
  6042. for slot, command_id in ipairs(self.party[i].command) do
  6043. if command_id == 4 or command_id == 23 then
  6044. self.party[i].item_slot, self.party[i].item_command = slot, command_id
  6045. end
  6046. end
  6047. end
  6048. end
  6049. end,
  6050. --- Shows the battle UI.
  6051. --
  6052. -- Populates and updates displayed data.
  6053. show = function(self)
  6054. -- Reset the state of the previous battle.
  6055. self.party = {}
  6056. self.enemies = {}
  6057. self.action_queue = {}
  6058. self.command_queue = {}
  6059. self.action_executing = false
  6060. self.window_state = "wait"
  6061. self.current_list = "none"
  6062. self.ending = false
  6063. self.timed_started = nil
  6064. self.result_pages = {}
  6065. self.result_page = 0
  6066. self.pending_next_battle = -1
  6067. self.current_action = nil
  6068. self.animation_queues = {}
  6069. self.pending_hides = {}
  6070. self.delayed_calls = {}
  6071. self.row_moves = {}
  6072. self.attack_cache = {}
  6073. self.viewer = {combatant = 1, animation = 0}
  6074. self:populate()
  6075. ui_manager:get_widget("BattleUi"):set_visible(true)
  6076. self.active = true;
  6077. -- Lopad combatant data
  6078. self:load_party_members()
  6079. self:load_enemies()
  6080. self.last_party_action = nil
  6081. self.limit_learned = nil
  6082. self:ai_setup()
  6083. self:init_atb()
  6084. -- Near Death and the limit bars at the start of the battle.
  6085. for i = 1, #self.party do
  6086. self:update_near_death(Battle.TargetGroup.PARTY, i)
  6087. self:update_party_bars(i)
  6088. self:update_limit(i)
  6089. end
  6090. for i = 1, #self.enemies do self:update_near_death(Battle.TargetGroup.ENEMIES, i) end
  6091. self:queue_sneak_attacks()
  6092. self:apply_animation_speed()
  6093. UiContainer.BattleFx:show()
  6094. local ok, intro = pcall(BattleCameraController.start_intro, BattleCameraController)
  6095. if not ok then print("Battle camera: " .. tostring(intro)) end
  6096. self.intro = ok and intro
  6097. -- The transition from the field ends in white.
  6098. UiContainer.BattleFx:flash({1, 1, 1}, 1.0, 0.7)
  6099. -- Battle music. The music of the field continues when the battle ends.
  6100. -- The scripts of the field choose one of the music tracks of the field for the battles
  6101. -- (the BMUSC opcode of the original game). Without one, the default battle music plays.
  6102. local track = BattleMusic.next
  6103. if track == nil then
  6104. local field_track = audio_manager:get_battle_track_id()
  6105. if field_track >= 0 then
  6106. local music = audio_manager:get_track_id(field_track)
  6107. if music ~= -1 then track = tostring(music) end
  6108. end
  6109. end
  6110. BattleMusic.next = nil
  6111. audio_manager:play_music(track or BattleMusic.battle)
  6112. for i = 1, #self.party do self:update_party_bars(i) end
  6113. self:show_message("V: target N/B: anim F: rotate C: camera Z/X: speed K: end")
  6114. -- Set various transparencies
  6115. ui_manager:get_widget("BattleUi.Container.Help.Center"):set_alpha(0.5)
  6116. ui_manager:get_widget("BattleUi.Container.Message.Center"):set_alpha(0.5)
  6117. ui_manager:get_widget("BattleUi.Container.Message.Center"):set_alpha(0.5)
  6118. for i = 1, #self.party do
  6119. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.AtbFill"):set_alpha(0.45)
  6120. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(i) .. ".Right.LimitFill"):set_alpha(0.45)
  6121. end
  6122. -- DEBUG:
  6123. --ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Center"):set_alpha(0.5)
  6124. --self:show_commands(1)
  6125. return 0;
  6126. end,
  6127. --- Shows the command window for a character
  6128. --
  6129. -- @param party_id The ID of the party member whose commands to show
  6130. show_commands = function(self, party_id)
  6131. self.current_character_window = party_id
  6132. -- A member that manipulates an enemy chooses among the attacks of the enemy.
  6133. self:update_manip_commands(party_id)
  6134. local command_list = self:get_command_list(party_id)
  6135. self.cursor_command = 1
  6136. self.window_state = "command"
  6137. -- Colour the character name
  6138. for c = 1, #self.party do
  6139. local widget = ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Left.Name")
  6140. widget:set_colour(self:get_name_colour(c, c == party_id))
  6141. widget:set_text(Characters[Party[c]].name)
  6142. end
  6143. -- Show command names
  6144. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  6145. local total_commands = 0
  6146. for c = 1, 12 do
  6147. if command_list[c] == nil then ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(c)):set_visible(false)
  6148. else
  6149. -- The colour of the Limit command changes, so it is set again.
  6150. if self.party[party_id].manip_commands == nil then
  6151. self:set_command_widget(party_id, c, command_list[c])
  6152. else
  6153. -- The attacks of a manipulated enemy.
  6154. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(c)):set_colour(1, 1, 1)
  6155. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(c)):set_text(Game.Commands[command_list[c]].name)
  6156. end
  6157. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cmd" .. tostring(c)):set_visible(true)
  6158. total_commands = total_commands + 1
  6159. end
  6160. end
  6161. -- Resize the window
  6162. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(false)
  6163. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_width(60 * (1 + math.floor(total_commands / 4)))
  6164. self.commands_width = 60 * (1 + math.floor(total_commands / 4))
  6165. ui_manager:get_widget("BattleUi.Container.Bottom.Change"):set_visible(false)
  6166. ui_manager:get_widget("BattleUi.Container.Bottom.Defend"):set_visible(false)
  6167. ui_manager:get_widget("BattleUi.Container.Bottom.Commands"):set_visible(true)
  6168. -- Start at the command chosen last time, if the cursor memory is on.
  6169. if UiContainer.cursor_memory() then
  6170. local remembered = self.memory_command[party_id]
  6171. if remembered ~= nil and remembered <= total_commands then self.cursor_command = remembered end
  6172. end
  6173. -- Set and show cursor
  6174. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cursor"):set_default_animation("Position" .. tostring(self.cursor_command))
  6175. ui_manager:get_widget("BattleUi.Container.Bottom.Commands.Cursor"):set_visible(true)
  6176. self.window_state = "command"
  6177. end,
  6178. --- Hides the battle UI.
  6179. --
  6180. -- It also sets this widget to inactive.
  6181. hide = function(self)
  6182. UiContainer.BattleFx:hide()
  6183. ui_manager:get_widget("BattleUi"):set_visible(false)
  6184. self.active = false
  6185. return 0;
  6186. end,
  6187. --- Populates the battle bottom left and right pannels
  6188. populate = function(self)
  6189. space_pad = function(val, length)
  6190. str = tostring(val)
  6191. while #(str) < length do str = " " .. str end
  6192. return str
  6193. end
  6194. for c = 1, 3 do
  6195. if self:has_character_data(Party[c]) then
  6196. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c)):set_visible(true)
  6197. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Left.Name"):set_text(Characters[Party[c]].name)
  6198. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Right.Hp.HpCurrent"):set_text(space_pad(Characters[Party[c]].stats.hp.current, 5))
  6199. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Right.Hp.HpMax"):set_text(space_pad(Characters[Party[c]].stats.hp.base, 5))
  6200. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c) .. ".Right.Mp.MpCurrent"):set_text(space_pad(Characters[Party[c]].stats.mp.current, 5))
  6201. else
  6202. ui_manager:get_widget("BattleUi.Container.Bottom.Character" .. tostring(c)):set_visible(false)
  6203. end
  6204. end
  6205. return 0
  6206. end
  6207. }