api.lua 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958
  1. -- File rewritten to be live-reloadable August 14, 2018 by MustTest.
  2. -- `mobs.registered' is checked throughout file, but only set `true' @ END!
  3. -- Localize functions.
  4. local pi = math.pi
  5. local square = math.sqrt
  6. local sin = math.sin
  7. local cos = math.cos
  8. local atan2 = math.atan2
  9. local abs = math.abs
  10. local min = math.min
  11. local max = math.max
  12. local ceil = math.ceil
  13. local floor = math.floor
  14. local random = math.random
  15. local v_round = vector.round
  16. local v_equals = vector.equals
  17. local v_distance = vector.distance
  18. local v_add = vector.add
  19. local rad = math.rad
  20. local deg = math.deg
  21. -- For debug reports.
  22. local function report(self, msg, range)
  23. if mobs.enable_reports then
  24. return
  25. end
  26. if self.name ~= mobs.report_name then
  27. return
  28. end
  29. local pname = gdac.name_of_admin
  30. if minetest.is_singleplayer() then
  31. pname = "singleplayer"
  32. end
  33. local player = minetest.get_player_by_name(pname)
  34. -- Range limit so I only get reports from mobs nearby.
  35. if player then
  36. local s = self.object:get_pos()
  37. local p = player:get_pos()
  38. if vector.distance(s, p) < (range or 50) then
  39. minetest.chat_send_player(pname, msg)
  40. end
  41. end
  42. end
  43. -- Export.
  44. mobs.report = report
  45. -- Function to tell mob which direction to turn to face target.
  46. -- Add pi to the returned yaw to face in the opposite direction.
  47. -- Fixed to use atan2 correctly by MustTest.
  48. local function yaw_to_pos(self, target, pos)
  49. local x = target.x - pos.x
  50. local z = target.z - pos.z
  51. local yaw = atan2(z, x) - self.rotate
  52. yaw = yaw - (pi / 2)
  53. return yaw
  54. end
  55. -- Function which takes a yaw value and "squares" it so it points in one of the
  56. -- 4 cardinal directions. Used to make mobs face along one of the horizontal
  57. -- axes, instead of diagonally, for some special situations.
  58. local function square_yaw(yaw)
  59. local pi2 = pi * 2
  60. if yaw < 0 then yaw = yaw + pi2 end
  61. if yaw > pi2 then yaw = yaw - pi2 end
  62. yaw = deg(yaw)
  63. if yaw <= 45 or yaw > 315 then
  64. yaw = 0 -- North.
  65. elseif yaw <= 315 and yaw > 225 then
  66. yaw = 270 -- East.
  67. elseif yaw <= 225 and yaw > 135 then
  68. yaw = 180 -- South.
  69. elseif yaw <= 135 and yaw > 45 then
  70. yaw = 90 -- West.
  71. end
  72. return rad(yaw)
  73. end
  74. -- Settings.
  75. local damage_enabled = true
  76. local peaceful_only = false
  77. local disable_blood = false
  78. local mobs_drop_items = minetest.settings:get_bool("mobs_drop_items") ~= false
  79. local mobs_griefing = true
  80. local creative = false
  81. local spawn_protected = minetest.settings:get_bool("mobs_spawn_protected") ~= false
  82. local remove_far = false
  83. local difficulty = 1.0
  84. local show_health = true
  85. local max_per_block = tonumber(minetest.settings:get("max_objects_per_block") or 99)
  86. local mob_chance_multiplier = tonumber(minetest.settings:get("mob_chance_multiplier") or 1)
  87. local default_knockback = 1
  88. -- Used by spawner function.
  89. mobs.spawn_protected = spawn_protected
  90. -- Legacy.
  91. if not mobs.invis then
  92. mobs.invis = {}
  93. end
  94. function mobs.is_invisible(self, pname)
  95. -- Administrative invisibility is paramount.
  96. if gdac_invis.is_invisible(pname) then
  97. return true
  98. end
  99. if self.ignore_invisibility then
  100. return
  101. end
  102. return cloaking.is_cloaked(pname)
  103. end
  104. -- Peaceful mode message so players will know there are no monsters.
  105. -- Perform registration only ONCE.
  106. if not mobs.registered and peaceful_only then
  107. minetest.register_on_joinplayer(function(player)
  108. minetest.chat_send_player(player:get_player_name(),
  109. "# Server: Peaceful mode active - no new monsters will spawn.")
  110. end)
  111. end
  112. -- calculate aoc range for mob count
  113. local aoc_range = tonumber(minetest.settings:get("active_block_range")) * 16
  114. -- Pathfinding settings.
  115. local enable_pathfinding = true
  116. local stuck_timeout = 3
  117. -- Note: stuck path timeout is determined based on the length of the path, and
  118. -- is a mob-internal property [MustTest].
  119. -- Default nodes:
  120. local node_fire = "fire:basic_flame"
  121. local node_permanent_flame = "fire:permanent_flame"
  122. local node_ice = "default:ice"
  123. local node_snowblock = "default:snowblock"
  124. local node_snow = "default:snow"
  125. local node_pathfinder_place = "default:cobble"
  126. mobs.fallback_node = "default:cobble"
  127. -- play sound
  128. local function mob_sound(self, sound)
  129. if sound then
  130. local dist = self.sounds.distance or 30
  131. ambiance.sound_play(sound, self.object:get_pos(), 1.0, dist)
  132. -- This isn't working!
  133. --minetest.sound_play(sound, {
  134. -- object = self.object,
  135. -- gain = 1.0,
  136. -- max_hear_distance = self.sounds.distance
  137. --})
  138. end
  139. end
  140. local function set_state(self, newstate)
  141. local oldstate = self.state or ""
  142. if newstate ~= oldstate then
  143. local sm = mobs.state_machine
  144. if sm[oldstate] and sm[oldstate].exit then
  145. sm[oldstate].exit(self)
  146. end
  147. self.state = newstate
  148. self.substate = ""
  149. if sm[newstate] and sm[newstate].enter then
  150. sm[newstate].enter(self)
  151. end
  152. report(self, "stack: " .. self.state .. " (" .. self.substate .. ") -> " ..
  153. table.concat(self.state_stack or {}, ","))
  154. end
  155. end
  156. -- State transition function [MustTest]. Do not set mob state designation
  157. -- manually, call this function instead. It handles state transitions, etc.
  158. local function transition_state(self, newstate)
  159. self.state_stack = {}
  160. set_state(self, newstate)
  161. end
  162. -- Export.
  163. mobs.transition_state = function(...)
  164. transition_state(...)
  165. end
  166. -- States can have "substates". This is basically just an alternate main()
  167. -- function, so states can swap between different main() functions as needed.
  168. -- There are no exit() or enter() calls here.
  169. local function transition_substate(self, newsub)
  170. if newsub ~= self.substate then
  171. self.substate = newsub
  172. report(self, "stack: " .. self.state .. " (" .. self.substate .. ") -> " ..
  173. table.concat(self.state_stack or {}, ","))
  174. end
  175. end
  176. -- Export.
  177. mobs.transition_substate = function(...)
  178. transition_substate(...)
  179. end
  180. local function push_state(self, newstate)
  181. if not self.state_stack then
  182. self.state_stack = {}
  183. end
  184. if self.state and self.state ~= "" then
  185. table.insert(self.state_stack, 1, self.state)
  186. end
  187. set_state(self, newstate)
  188. end
  189. local function pop_state(self)
  190. if not self.state_stack then
  191. self.state_stack = {}
  192. end
  193. local state = self.state_stack[1]
  194. if state then
  195. table.remove(self.state_stack, 1)
  196. set_state(self, state)
  197. return
  198. end
  199. set_state(self, "")
  200. end
  201. local function do_attack(self, target)
  202. if self.state == "attack" then
  203. return
  204. end
  205. if target and target:get_pos() then
  206. self.attack = target
  207. transition_state(self, "attack")
  208. return
  209. else
  210. transition_state(self, "")
  211. return
  212. end
  213. end
  214. -- Check if the node at a position has 'walkable = true'.
  215. local function pos_walkable(pos)
  216. local nn = minetest.get_node(pos).name
  217. local dd = minetest.registered_nodes[nn]
  218. return dd.walkable
  219. end
  220. local function set_velocity(self, v)
  221. local yaw = (self.object:get_yaw() or 0) + (self.rotate or 0)
  222. local vel = self.object:get_velocity()
  223. local y = 0
  224. if vel then
  225. y = vel.y or 0
  226. end
  227. -- Fix crash: 2020-09-12 14:26:15: ERROR[Main]: ServerError: AsyncErr:
  228. -- ServerThread::run Lua: Runtime error from mod 'griefer' in callback
  229. -- luaentity_Step(): Invalid float vector dimension range 'y' (expected
  230. -- -2.14748e+06 < y < 2.14748e+06 got -1.96364e+12).
  231. y = max(min(y, 200), -200)
  232. self.object:set_velocity({
  233. x = sin(yaw) * -v,
  234. y = y,
  235. z = cos(yaw) * v
  236. })
  237. -- Store the requested velocity.
  238. local o = self.wanted_velocity or 0
  239. self.wanted_velocity = v
  240. if v <= 0 and o > 0 then
  241. self.stand_timer = 0
  242. end
  243. if v <= 0 then
  244. self.stuck_timer = 0
  245. end
  246. end
  247. local function get_velocity(self)
  248. local v = self.object:get_velocity()
  249. return ((v.x * v.x) + (v.z * v.z)) ^ 0.5
  250. end
  251. -- set and return valid yaw
  252. local function set_yaw(self, yaw, delay)
  253. if not yaw or yaw ~= yaw then
  254. yaw = 0
  255. end
  256. delay = delay or 0
  257. if delay == 0 then
  258. self.object:set_yaw(yaw)
  259. return yaw
  260. end
  261. self.target_yaw = yaw
  262. self.delay = delay
  263. return self.target_yaw
  264. end
  265. -- global function to set mob yaw
  266. function mobs.yaw(self, yaw, delay)
  267. set_yaw(self, yaw, delay)
  268. end
  269. local function set_animation(self, anim, speed)
  270. if not self.animation or not anim then
  271. return
  272. end
  273. self.animation.current = self.animation.current or ""
  274. -- only set different animation for attacks when setting to same set
  275. if anim ~= "punch" and anim ~= "shoot"
  276. and string.find(self.animation.current, anim) then
  277. return
  278. end
  279. -- check for more than one animation
  280. local num = 0
  281. for n = 1, 4 do
  282. if self.animation[anim .. n .. "_start"]
  283. and self.animation[anim .. n .. "_end"] then
  284. num = n
  285. end
  286. end
  287. -- choose random animation from set
  288. if num > 0 then
  289. num = random(0, num)
  290. anim = anim .. (num ~= 0 and num or "")
  291. end
  292. if anim == self.animation.current
  293. or not self.animation[anim .. "_start"]
  294. or not self.animation[anim .. "_end"] then
  295. return
  296. end
  297. self.animation.current = anim
  298. local anim_speed = (speed or
  299. self.animation[anim .. "_speed"] or
  300. self.animation.speed_normal or 15)
  301. self.object:set_animation({
  302. x = self.animation[anim .. "_start"],
  303. y = self.animation[anim .. "_end"]},
  304. anim_speed,
  305. 0, self.animation[anim .. "_loop"] ~= false)
  306. end
  307. -- Above function exported for "mount.lua".
  308. function mobs.set_animation(self, anim)
  309. set_animation(self, anim)
  310. end
  311. -- Calculate distance.
  312. local function get_distance(a, b)
  313. local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
  314. return square(x * x + y * y + z * z)
  315. end
  316. -- Check line of sight using raycasting (thanks Astrobe).
  317. local function raycast_los(self, pos1, pos2)
  318. local ray = minetest.raycast(pos1, pos2, false, true)
  319. local thing = ray:next()
  320. while thing do
  321. if thing.type == "node" then
  322. local name = minetest.get_node(thing.under).name
  323. local ndef = minetest.registered_nodes[name]
  324. if ndef and ndef.walkable then
  325. return false
  326. end
  327. end
  328. thing = ray:next()
  329. end
  330. return true
  331. end
  332. -- Export.
  333. function mobs.line_of_sight(self, pos1, pos2)
  334. return raycast_los(self, pos1, pos2)
  335. end
  336. -- Are we flying in what we are suppose to? (taikedz)
  337. local function flight_check(self, pos_w)
  338. if type(self.fly_in) == "string" and self.standing_in == self.fly_in then
  339. return true
  340. elseif type(self.fly_in) == "table" then
  341. for _, fly_in in ipairs(self.fly_in) do
  342. if self.standing_in == fly_in then
  343. return true
  344. end
  345. end
  346. end
  347. local def = minetest.reg_ns_nodes[self.standing_in]
  348. if not def then return false end -- nil check
  349. -- stops mobs getting stuck inside stairs and plantlike nodes
  350. if def.drawtype ~= "airlike"
  351. and def.drawtype ~= "liquid"
  352. and def.drawtype ~= "flowingliquid" then
  353. return true
  354. end
  355. -- Enables mobs to fly in non-walkable stuff like thin "default:snow".
  356. if not def.walkable then
  357. return true
  358. end
  359. return false
  360. end
  361. -- custom particle effects
  362. local function effect(
  363. pos, amount, texture, min_size, max_size, radius, gravity, glow, fall)
  364. radius = radius or 2
  365. min_size = min_size or 0.5
  366. max_size = max_size or 1
  367. gravity = gravity or -10
  368. glow = glow or 0
  369. if fall == true then
  370. fall = 0
  371. elseif fall == false then
  372. fall = radius
  373. else
  374. fall = -radius
  375. end
  376. minetest.add_particlespawner({
  377. amount = amount,
  378. time = 0.25,
  379. minpos = pos,
  380. maxpos = pos,
  381. minvel = {x = -radius, y = fall, z = -radius},
  382. maxvel = {x = radius, y = radius, z = radius},
  383. minacc = {x = 0, y = gravity, z = 0},
  384. maxacc = {x = 0, y = gravity, z = 0},
  385. minexptime = 0.1,
  386. maxexptime = 1,
  387. minsize = min_size,
  388. maxsize = max_size,
  389. texture = texture,
  390. glow = glow,
  391. })
  392. end
  393. -- Update nametag colour.
  394. local function update_tag(self)
  395. local col = "#00FF00"
  396. local qua = self.hp_max / 4
  397. if self.health <= floor(qua * 3) then
  398. col = "#FFFF00"
  399. end
  400. if self.health <= floor(qua * 2) then
  401. col = "#FF6600"
  402. end
  403. if self.health <= floor(qua) then
  404. col = "#FF0000"
  405. end
  406. self.object:set_properties({
  407. nametag = self.nametag,
  408. nametag_color = col,
  409. })
  410. end
  411. -- drop items
  412. local function item_drop(self, cooked)
  413. -- check for nil or no drops
  414. if not self.drops or #self.drops == 0 then
  415. return
  416. end
  417. -- no drops if disabled by setting
  418. if not mobs_drop_items then return end
  419. -- no drops for child mobs
  420. if self.child then return end
  421. local obj, item, num
  422. local pos = self.object:get_pos()
  423. for n = 1, #self.drops do
  424. if random(1, self.drops[n].chance) == 1 then
  425. num = random(self.drops[n].min or 0, self.drops[n].max or 1)
  426. item = self.drops[n].name
  427. -- cook items when true
  428. if cooked then
  429. local output = minetest.get_craft_result({
  430. method = "cooking", width = 1, items = {item}})
  431. if output and output.item and not output.item:is_empty() then
  432. item = output.item:get_name()
  433. end
  434. end
  435. -- add item if it exists
  436. obj = minetest.add_item(pos, ItemStack(item .. " " .. num))
  437. if obj and obj:get_luaentity() then
  438. obj:set_velocity({
  439. x = random(-10, 10) / 9,
  440. y = 6,
  441. z = random(-10, 10) / 9,
  442. })
  443. elseif obj then
  444. obj:remove() -- item does not exist
  445. end
  446. end
  447. end
  448. self.drops = {}
  449. end
  450. -- check if mob is dead or only hurt
  451. local function check_for_death(self, cause, cmi_cause)
  452. -- has health actually changed?
  453. if self.health == self.old_health and self.health > 0 then
  454. return
  455. end
  456. self.old_health = self.health
  457. -- still got some health? play hurt sound
  458. if self.health > 0 then
  459. mob_sound(self, self.sounds.damage)
  460. -- make sure health isn't higher than max
  461. if self.health > self.hp_max then
  462. self.health = self.hp_max
  463. end
  464. -- backup nametag so we can show health stats
  465. if not self.nametag2 then
  466. self.nametag2 = self.nametag or ""
  467. end
  468. if show_health and self.show_health ~= false and
  469. (cmi_cause and cmi_cause.type == "punch") then
  470. local pc = floor((self.health / self.hp_max) * 100)
  471. self.htimer = 2
  472. self.nametag = "♥ " .. pc .. "%"
  473. update_tag(self)
  474. end
  475. return false
  476. end
  477. -- Mob will die, check if we were attacked.
  478. if cause == "hit" then
  479. if self.last_attacked_by and self.last_attacked_by ~= "" then
  480. local attacked_by = minetest.get_player_by_name(self.last_attacked_by)
  481. if attacked_by then
  482. mobs.player_killed_mob(self, attacked_by)
  483. end
  484. end
  485. end
  486. -- only drop items if weapon is of sufficient level to overcome mob's armor level
  487. local can_drop = true
  488. if cmi_cause and cmi_cause.tool_capabilities then
  489. local max_drop_level = (cmi_cause.tool_capabilities.max_drop_level or 0)
  490. -- Increase weapon's max drop level if rank is level 7.
  491. local tool_level = 1
  492. if cmi_cause.wielded then
  493. local tool_meta = cmi_cause.wielded:get_meta()
  494. tool_level = tonumber(tool_meta:get_string("tr_lastlevel")) or 1
  495. end
  496. if tool_level >= 7 then
  497. max_drop_level = max_drop_level + 1
  498. end
  499. if (max_drop_level) < (self.armor_level or 0) then
  500. can_drop = false
  501. end
  502. end
  503. -- mob doesn't drop anything if killed by sunlight
  504. -- this fixes the problem of drops being scattered around after sunrise
  505. -- caused by icemen and sandmen
  506. if cause == "light" then
  507. can_drop = false
  508. end
  509. if can_drop then
  510. -- dropped cooked item if mob died in lava
  511. if cause == "lava" or cause == "fire" then
  512. item_drop(self, true)
  513. else
  514. item_drop(self, nil)
  515. end
  516. end
  517. mob_sound(self, self.sounds.death)
  518. local pos = self.object:get_pos()
  519. -- execute custom death function
  520. if self.on_die then
  521. self.on_die(self, pos)
  522. -- Mark for removal as last action on mob_step().
  523. self.mkrm = true
  524. return true
  525. end
  526. -- default death function and die animation (if defined)
  527. if self.animation
  528. and self.animation.die_start
  529. and self.animation.die_end then
  530. local frames = self.animation.die_end - self.animation.die_start
  531. local speed = self.animation.die_speed or 15
  532. local length = max(frames / speed, 0)
  533. self.attack = nil
  534. self.v_start = false
  535. self.blinktimer = 0
  536. self.passive = true
  537. transition_state(self, "die")
  538. set_velocity(self, 0)
  539. set_animation(self, "die")
  540. minetest.after(length, function(self)
  541. -- Mark for removal as last action on mob_step().
  542. -- Note: this is deferred for a bit!
  543. self.mkrm = true
  544. end, self)
  545. else
  546. -- Mark for removal as last action on mob_step().
  547. self.mkrm = true
  548. end
  549. effect(pos, 20, "tnt_smoke.png")
  550. return true
  551. end
  552. -- Check if within physical map limits (-30911 to 30927).
  553. local function within_limits(pos, radius)
  554. if (pos.x - radius) > -30913
  555. and (pos.x + radius) < 30928
  556. and (pos.y - radius) > -30913
  557. and (pos.y + radius) < 30928
  558. and (pos.z - radius) > -30913
  559. and (pos.z + radius) < 30928 then
  560. return true -- Within limits.
  561. end
  562. return false -- Beyond limits.
  563. end
  564. -- Returns true if node can deal damage to self.
  565. local function is_node_dangerous(self, nodename, ndef)
  566. if nodename == "air" then
  567. return false
  568. end
  569. if not ndef then
  570. ndef = minetest.registered_nodes[nodename]
  571. end
  572. if not ndef then
  573. return true
  574. end
  575. local groups = ndef.groups
  576. local water = groups.water or 0
  577. local lava = groups.lava or 0
  578. local fire = groups.fire or 0
  579. if (self.water_damage or 0) > 0 and water ~= 0 then
  580. return true
  581. end
  582. if (self.lava_damage or 0) > 0 and lava ~= 0 then
  583. return true
  584. end
  585. if (self.fire_damage or 0) > 0 and fire ~= 0 then
  586. return true
  587. end
  588. if ndef.damage_per_second > 0 then
  589. return true
  590. end
  591. return false
  592. end
  593. -- Get node but use fallback for nil or unknown.
  594. local function node_ok(pos, fallback)
  595. fallback = fallback or mobs.fallback_node
  596. local node = minetest.get_node_or_nil(pos)
  597. if node and minetest.registered_nodes[node.name] then
  598. return node
  599. end
  600. return minetest.registered_nodes[fallback]
  601. end
  602. -- This function moves a mob to the center of the X,Z column.
  603. -- True is returned to indicate the mob is moving; otherwise false.
  604. -- Note: the point is to get the mob's collision box entirely inside the X,Z
  605. -- plain of the node it is standing on; if this can't be achieved, the
  606. -- pathfinder WILL exhibit bugs!
  607. local function keep_mob_centered(self, ss)
  608. local s = ss or self.object:get_pos()
  609. local c = vector.round(s)
  610. -- Have mob position himself nearer the center of the node.
  611. if abs(s.x - c.x) > 0.2 or abs(s.z - c.z) > 0.2 then
  612. set_yaw(self, yaw_to_pos(self, c, s))
  613. set_velocity(self, 0.2)
  614. set_animation(self, "walk", 5)
  615. return true
  616. end
  617. end
  618. -- This function causes a mob to walk slowly toward its facing direction until
  619. -- it detects an obstacle (of any kind). It returns true to indicate the mob is
  620. -- moving.
  621. local function walk_mob_forward(self)
  622. -- Function is not defined yet.
  623. if not mobs.facing_wall_or_pit(self) then
  624. set_velocity(self, 0.5)
  625. set_animation(self, "walk", 5)
  626. return true
  627. end
  628. end
  629. local function show_position(p)
  630. -- Keep this particle code for debugging purposes [MustTest].
  631. -- Spawn particle at actual computed position without rounding.
  632. local pname = "singleplayer"
  633. if not minetest.is_singleplayer() then
  634. pname = gdac.name_of_admin
  635. end
  636. utility.original_add_particle({
  637. playername = pname,
  638. pos = p,
  639. velocity = {x=0, y=0, z=0},
  640. acceleration = {x=0, y=0, z=0},
  641. expirationtime = 0.5,
  642. size = 1,
  643. collisiondetection = false,
  644. vertical = false,
  645. texture = "bubble.png",
  646. })
  647. end
  648. -- This function computes the rounded position of the node in front of the mob.
  649. -- The math must be such that the mob MUST be standing WITHIN the node's X,Z
  650. -- bounds, in order to get the position of the node ahead. If this is not the
  651. -- case, then the mob would detect obstacles either too soon or too late to
  652. -- correctly deal with them.
  653. local function get_ahead_pos(self, pos, yaw)
  654. -- Copy position argument so we do not modify it.
  655. local s = (pos and vector.copy(pos)) or self.object:get_pos()
  656. s.y = s.y + self.collisionbox[2] + 0.5
  657. local off = (pi / 2)
  658. local cir = (pi * 2)
  659. local dir = yaw or (self.object:get_yaw() + off)
  660. -- Adjustment factor to improve accuracy.
  661. local fac = 0.99
  662. local ang = dir - off
  663. if ang < 0 then ang = ang + cir end
  664. if ang > cir then ang = ang - cir end
  665. local dd = deg(ang)
  666. --report(self, "angle: " .. dd)
  667. -- Increase distance when facing corners.
  668. if dd > 30 and dd < 60 then
  669. fac = 1.3
  670. elseif dd > 120 and dd < 150 then
  671. fac = 1.3
  672. elseif dd > 210 and dd < 240 then
  673. fac = 1.3
  674. elseif dd > 300 and dd < 330 then
  675. fac = 1.3
  676. end
  677. local p = {
  678. x = s.x + (cos(dir) * fac),
  679. y = s.y,
  680. z = s.z + (sin(dir) * fac),
  681. }
  682. -- Keep this particle code for debugging purposes [MustTest].
  683. --[[
  684. -- Spawn particle at actual computed position without rounding.
  685. local pname = "singleplayer"
  686. if not minetest.is_singleplayer() then
  687. pname = gdac.name_of_admin
  688. end
  689. utility.original_add_particle({
  690. playername = pname,
  691. pos = p,
  692. velocity = {x=0, y=0, z=0},
  693. acceleration = {x=0, y=0, z=0},
  694. expirationtime = 0.5,
  695. size = 1,
  696. collisiondetection = false,
  697. vertical = false,
  698. texture = "bubble.png",
  699. })
  700. --]]
  701. p = v_round(p)
  702. --[[
  703. -- Spawn particle at rounded node position.
  704. utility.original_add_particle({
  705. playername = pname,
  706. pos = p,
  707. velocity = {x=0, y=0, z=0},
  708. acceleration = {x=0, y=0, z=0},
  709. expirationtime = 0.5,
  710. size = 4,
  711. collisiondetection = false,
  712. vertical = false,
  713. texture = "bubble.png",
  714. })
  715. --]]
  716. return p
  717. end
  718. -- This function returns a list of walkable surfaces which are level with the
  719. -- position. The returned list contains positions *above* the walkable surfaces.
  720. -- The center position is also included, for a max total of 9 locations.
  721. local function walkable_around(pos)
  722. local minp = v_add(pos, {x=-1, y=0, z=-1})
  723. local maxp = v_add(pos, {x=1, y=0, z=1})
  724. return hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  725. end
  726. -- Check if a position is a wall or pit. You should pass the rounded position of
  727. -- the node which the mob wants to move INTO. Always returns two values,
  728. -- true/false, and a reason string.
  729. local function is_wall_or_pit(self, wp)
  730. local drop = (self.fear_height or 0)
  731. local jump = (self.jump_height or 0)
  732. -- Note: we need to add 1 to the jump height in order to take care of the case
  733. -- that the wall has a hole in it near the top. The mob would not be able to
  734. -- jump through such a wall because of the block above (assuming the mob is 2
  735. -- blocks high).
  736. jump = jump + 1
  737. -- Start the raycast from the top and go down.
  738. -- Note: the raycast ignores air nodes. So we do not need to do air checks.
  739. -- Note: the raycast returns ALL nodes, not just those exposed to air.
  740. local p1 = v_add(wp, {x=0, y=jump, z=0})
  741. local p2 = v_add(wp, {x=0, y=-drop, z=0})
  742. local ray = minetest.raycast(p1, p2, false, true)
  743. local thing = ray:next()
  744. local head_solid = false
  745. while thing do
  746. if thing.type == "node" then
  747. local p = thing.under
  748. local n = minetest.get_node(p).name
  749. local d = minetest.registered_nodes[n]
  750. if not d then
  751. return true, "undef"
  752. end
  753. if is_node_dangerous(self, n, d) then
  754. if head_solid then
  755. return true, "wall"
  756. else
  757. return true, "danger"
  758. end
  759. end
  760. -- If the node is not walkable, skip these checks.
  761. if d.walkable then
  762. if p.y == p1.y then
  763. head_solid = true
  764. elseif p.y == (p1.y - 1) then
  765. return true, "wall"
  766. elseif p.y == (p1.y - 2) and head_solid then
  767. return true, "wall"
  768. else
  769. return false, "surface"
  770. end
  771. end
  772. end
  773. thing = ray:next()
  774. end
  775. -- If we reach here, the raycast did not intersect any nodes.
  776. if (self.fear_height or 0) == 0 then
  777. return false, "nofear"
  778. end
  779. return true, "pit"
  780. end
  781. -- Export function.
  782. mobs.is_wall_or_pit = is_wall_or_pit
  783. -- Is mob facing a wall or a pit/cliff. Always returns two values, true/false,
  784. -- and a reason string.
  785. local function facing_wall_or_pit(self)
  786. if self.driver then
  787. return false, "driver"
  788. end
  789. local ahead = get_ahead_pos(self)
  790. return is_wall_or_pit(self, ahead)
  791. end
  792. -- Export function.
  793. mobs.facing_wall_or_pit = facing_wall_or_pit
  794. -- This function is to be called by the pathfinder to determine if a waypoint
  795. -- would be dangerous for a mob to follow. Note that the pathfinder does not
  796. -- place waypoints over deep pits, cliffs, or walls, so we do not need to check
  797. -- for that kind of blockage. Note: pathfinder returns rounded positions.
  798. function waypoint_dangerous(self, waypoint)
  799. local bnode = node_ok(waypoint)
  800. -- Is waypoint inside a dangerous node?
  801. if is_node_dangerous(self, bnode.name) then
  802. return true
  803. end
  804. end
  805. -- Global function.
  806. function mobs.node_ok(pos, fallback)
  807. return node_ok(pos, fallback)
  808. end
  809. -- Get list of players and mobs in radius. Note: all "actor" (player, mob) type
  810. -- targets are returned, irrespective of invisibility. Self is never included.
  811. local function get_targets_in_radius(self, pos, radius)
  812. local list = {}
  813. local objs = minetest.get_objects_inside_radius(pos, radius)
  814. for k, v in ipairs(objs) do
  815. if v:is_player() then
  816. list[#list + 1] = v
  817. else
  818. local ent = v:get_luaentity()
  819. if ent and (ent.mob or ent._cmi_is_mob) then
  820. if ent.object ~= self.object then
  821. list[#list + 1] = v
  822. end
  823. end
  824. end
  825. end
  826. return list
  827. end
  828. -- Environmental damage (water, lava, fire, light).
  829. local function do_env_damage(self)
  830. -- feed/tame text timer (so mob 'full' messages dont spam chat)
  831. if self.htimer > 0 then
  832. self.htimer = self.htimer - 1
  833. end
  834. -- reset nametag after showing health stats
  835. if self.htimer < 1 and self.nametag2 then
  836. self.nametag = self.nametag2
  837. self.nametag2 = nil
  838. update_tag(self)
  839. end
  840. local pos = self.object:get_pos()
  841. self.time_of_day = minetest.get_timeofday()
  842. -- remove mob if beyond map limits
  843. if not within_limits(pos, 0) then
  844. -- Mark for removal as last action on mob_step().
  845. self.mkrm = true
  846. return
  847. end
  848. -- mob may simply despawn at daytime, without dropping anything
  849. if random(1, 10) == 1 then -- add some random delay chance
  850. if self.daytime_despawn and pos.y > -10
  851. and self.time_of_day > 0.2
  852. and self.time_of_day < 0.8
  853. and (minetest.get_node_light(pos) or 0) > 12 then
  854. if self.on_despawn then
  855. self.on_despawn(self)
  856. return
  857. else
  858. -- Mark for removal as last action on mob_step().
  859. self.mkrm = true
  860. return
  861. end
  862. end
  863. end
  864. -- bright light harms mob
  865. -- daylight above ground
  866. if self.light_damage ~= 0
  867. and pos.y > -10
  868. and self.time_of_day > 0.2
  869. and self.time_of_day < 0.8
  870. and (minetest.get_node_light(pos) or 0) > 12 then
  871. self.health = self.health - self.light_damage
  872. effect(pos, 5, "tnt_smoke.png")
  873. if check_for_death(self, "light", {type = "light"}) then return end
  874. end
  875. if self.despawns_in_dark_caves and pos.y < -12 then
  876. if (minetest.get_node_light(pos) or 0) == 0 then
  877. -- Mark for removal as last action on mob_step().
  878. self.mkrm = true
  879. return
  880. end
  881. end
  882. -- don't fall when on ignore, just stand still
  883. if self.standing_in == "ignore" then
  884. self.object:set_velocity({x = 0, y = 0, z = 0})
  885. end
  886. local nodef = minetest.reg_ns_nodes[self.standing_in]
  887. local nodef2 = minetest.reg_ns_nodes[self.standing_on]
  888. -- Stairs nodes don't do env damage.
  889. if not nodef or not nodef2 then
  890. return
  891. end
  892. pos.y = pos.y + 1 -- for particle effect position
  893. -- water
  894. if self.water_damage ~= 0 and nodef.groups.water then
  895. if self.water_damage ~= 0 then
  896. self.health = self.health - self.water_damage
  897. effect(pos, 5, "bubble.png", nil, nil, 1, nil)
  898. if check_for_death(self, "water", {type = "environment",
  899. pos = pos, node = self.standing_in}) then return end
  900. end
  901. -- lava damage
  902. elseif self.lava_damage ~= 0 and nodef.groups.lava then
  903. if self.lava_damage ~= 0 then
  904. self.health = self.health - self.lava_damage
  905. effect(pos, 5, "fire_basic_flame.png", nil, nil, 1, nil)
  906. if check_for_death(self, "lava", {type = "environment",
  907. pos = pos, node = self.standing_in}) then return end
  908. end
  909. -- fire damage
  910. elseif self.fire_damage ~= 0 and nodef.groups.fire then
  911. self.health = self.health - self.fire_damage
  912. effect(pos, 15, "fire_basic_flame.png", 1, 5, 1, 0.2, 15, true)
  913. if check_for_death(self, "fire", {type = "environment", pos = pos,
  914. node = self.standing_in, hot = true}) then return end
  915. -- damage_per_second node check
  916. elseif nodef.damage_per_second ~= 0
  917. and nodef.groups.lava == nil and nodef.groups.fire == nil then
  918. self.health = self.health - nodef.damage_per_second
  919. effect(pos, 5, "tnt_smoke.png")
  920. if check_for_death(self, "dps", {type = "environment",
  921. pos = pos, node = self.standing_in}) then return end
  922. end
  923. if nodef2.groups.lava and self.lava_annihilates and self.lava_annihilates == true then
  924. self.health = 0
  925. effect(pos, 5, "tnt_smoke.png")
  926. pos.y = pos.y - 1 -- erase effect of adjusting for particle position.
  927. local pb = v_round(pos) -- use rounded position
  928. local pa = {x=pb.x, y=pb.y+1, z=pb.z}
  929. if minetest.get_node(pb).name == "air" and minetest.get_node(pa).name == "air" then
  930. if self.makes_bones_in_lava and self.makes_bones_in_lava == true then
  931. minetest.add_node(pb, {name="bones:bones_type2"})
  932. local meta = minetest.get_meta(pb)
  933. meta:set_int("protection_cancel", 1)
  934. minetest.add_node(pa, {name="fire:basic_flame"})
  935. minetest.check_for_falling(pb)
  936. else
  937. minetest.add_node(pb, {name="fire:basic_flame"})
  938. end
  939. end
  940. if check_for_death(self, "lava", {type = "environment",
  941. pos = pos, node = self.standing_in}) then return end
  942. end
  943. check_for_death(self, "", {type = "unknown"})
  944. end
  945. -- Arrow shooting code extracted into its own function [MustTest].
  946. local function shoot_arrow(self, vec)
  947. -- Play shoot attack sound.
  948. mob_sound(self, self.sounds.shoot_attack)
  949. -- Spawn arrow comming from mid-height of mob.
  950. local p = self.object:get_pos()
  951. p.y = p.y + (self.collisionbox[2] + self.collisionbox[5]) / 2
  952. if minetest.registered_entities[self.arrow] then
  953. local obj = minetest.add_entity(p, self.arrow)
  954. if not obj then return end -- Sanity check.
  955. local ent = obj:get_luaentity()
  956. if not ent then
  957. obj:remove()
  958. return
  959. end -- Sanity check.
  960. local amount = (vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) ^ 0.5
  961. local v = ent.velocity or 1 -- or set to default
  962. ent.switch = 1
  963. ent.owner_obj = self.object -- Add unique owner object ref to arrow.
  964. -- Offset makes shoot aim accurate.
  965. vec.y = vec.y + self.shoot_offset
  966. vec.x = vec.x * (v / amount)
  967. vec.y = vec.y * (v / amount)
  968. vec.z = vec.z * (v / amount)
  969. obj:set_velocity(vec)
  970. end
  971. end
  972. -- Export.
  973. mobs.shoot_arrow = function(...)
  974. shoot_arrow(...)
  975. end
  976. -- Target punching code extracted into its own function [MustTest].
  977. local function punch_target(self, dtime)
  978. if not self.attack then return end
  979. if not self.attack:get_pos() then return end
  980. -- If the punch timer is still running since the last successful punch, then
  981. -- don't do anything.
  982. if (self.punch_timer or 0) > 0 then return end
  983. local s2 = self.object:get_pos()
  984. local p2 = self.attack:get_pos()
  985. p2.y = p2.y + 0.5
  986. s2.y = s2.y + 0.5
  987. if not raycast_los(self, p2, s2) then
  988. return
  989. end
  990. -- play attack sound
  991. mob_sound(self, self.sounds.attack)
  992. local targetname = (self.attack:is_player() and self.attack:get_player_name() or "")
  993. -- punch player (or what player is attached to)
  994. local attached = self.attack:get_attach()
  995. if attached or default.player_attached[targetname] then
  996. -- Mob has a chance of removing the player from whatever they're attached to.
  997. -- This chance only applies on the mob's first hit; if they fail to detach
  998. -- the player, the mob's target is set to the entity the player is attached to.
  999. if self.attack:is_player() and random(1, 5) == 1 then
  1000. utility.detach_player_with_message(self.attack)
  1001. elseif attached then
  1002. self.attack = attached
  1003. end
  1004. end
  1005. -- If attacking an entity that has no attached player, then stop attacking.
  1006. if targetname == "" then
  1007. local luaent = self.attack:get_luaentity()
  1008. if luaent and not luaent._cmi_is_mob then
  1009. local children = self.attack:get_children()
  1010. if not children or #children == 0 then
  1011. self.attack = nil
  1012. return
  1013. else
  1014. local has_player = false
  1015. for k, v in ipairs(children) do
  1016. if v:is_player() then
  1017. has_player = true
  1018. end
  1019. end
  1020. if not has_player then
  1021. self.attack = nil
  1022. return
  1023. end
  1024. end
  1025. end
  1026. end
  1027. -- Don't bother the admin.
  1028. if gdac.player_is_admin(targetname) then
  1029. return
  1030. end
  1031. if self.punch_target and self.punch_target(self, self.object, self.attack) == true then
  1032. -- If 'true', skip default punch action.
  1033. else
  1034. local damage = self.damage or 0
  1035. if self.damage_min and self.damage_max then
  1036. if self.damage_min > damage and self.damage_max >= self.damage_min then
  1037. damage = random(self.damage_min, self.damage_max)
  1038. end
  1039. end
  1040. local dgroup = self.damage_group or "fleshy"
  1041. if self.attack:is_player() then
  1042. armor.notify_punch_reason({reason=dgroup})
  1043. end
  1044. self.attack:punch(self.object, 1.0, {
  1045. full_punch_interval = 1.0,
  1046. damage_groups = {[dgroup] = damage}
  1047. }, nil)
  1048. -- Start punch timer; mob cannot punch again until timer reaches 0.
  1049. self.punch_timer = 1
  1050. ambiance.sound_play("default_punch", p2, 2.0, 30)
  1051. end
  1052. --minetest.log('hp post punch: ' .. self.attack:get_hp())
  1053. -- Tell everyone about the death [MustTest].
  1054. if self.attack:is_player() and self.attack:get_hp() <= 0 then
  1055. mobs.mob_killed_player(self, self.attack)
  1056. self.attack = nil
  1057. end
  1058. end
  1059. -- Remove block if possible [MustTest]. Note: this function does not necessarily
  1060. -- have to break a node if it is non-walkable, but even if so (i.e., air) it
  1061. -- MUST still return true in that case!
  1062. local function try_break_block(self, s)
  1063. -- Must round position ourselves, otherwise we'll expose rounding
  1064. -- inconsistencies in the engine and possibly break protection.
  1065. s = v_round(s)
  1066. local node1 = minetest.get_node(s).name
  1067. -- Shortcut.
  1068. if node1 == "air" then
  1069. return true
  1070. end
  1071. -- Checks must be performed in order of severity.
  1072. local ndef1 = minetest.registered_nodes[node1]
  1073. -- Don't destroy player's bones [MustTest]!
  1074. if (not ndef1) or node1 == "ignore" or node1 == "bones:bones" then
  1075. return false, "special"
  1076. end
  1077. if ndef1.groups.unbreakable or ndef1.groups.immovable then
  1078. return false, "unbreakable"
  1079. end
  1080. -- Some liquids (like lava sources) are walkable. The liquid check must
  1081. -- therefore come first. (Some fake liquids, like nether grit, are diggable.)
  1082. if ndef1.groups.liquid and not ndef1.diggable then
  1083. return false, "liquid"
  1084. end
  1085. -- Check node level against mob's max-dig-level.
  1086. if (ndef1.groups.level or 0) > (self.max_node_dig_level or 1) then
  1087. return false, "unbreakable"
  1088. end
  1089. if ndef1.walkable and minetest.test_protection(s, "") then
  1090. return false, "protected"
  1091. end
  1092. -- If a non-walkable node is also NOT dangerous, it does not block pathfinder.
  1093. if not ndef1.walkable and not is_node_dangerous(node1) then
  1094. return true
  1095. end
  1096. -- If we reach here, node ought to be either walkable, either/or dangerous.
  1097. local oldnode = minetest.get_node(s)
  1098. minetest.set_node(s, {name = "air"})
  1099. -- Run script hook
  1100. for _, callback in ipairs(minetest.registered_on_dignodes) do
  1101. -- Deepcopy pos, oldnode, because callback can modify them
  1102. callback(table.copy(s), table.copy(oldnode), self.object)
  1103. end
  1104. minetest.check_for_falling(s)
  1105. -- This function takes both nodetables and nodenames.
  1106. -- Pass node names, because passing a node table gives wrong results.
  1107. local drops = minetest.get_node_drops(oldnode.name, "")
  1108. for _, item in pairs(drops) do
  1109. local p = {
  1110. x = s.x + random() / 2 - 0.25,
  1111. y = s.y + random() / 2 - 0.25,
  1112. z = s.z + random() / 2 - 0.25,
  1113. }
  1114. minetest.add_item(p, item)
  1115. end
  1116. return true -- success!
  1117. end
  1118. local function force_jump_up(self, height)
  1119. height = height or self.jump_height or 0
  1120. local v = self.object:get_velocity()
  1121. if height == 1 then
  1122. v.y = 5 -- Jump a bit over one node.
  1123. elseif height == 2 then
  1124. v.y = 6.8 -- Jump slightly over two nodes.
  1125. elseif height == 3 then
  1126. v.y = 8.2 -- Jump over three nodes.
  1127. else
  1128. v.y = 5
  1129. end
  1130. v.y = v.y + (random(-50, 50) / 100)
  1131. self.object:set_velocity(v)
  1132. set_animation(self, "jump")
  1133. end
  1134. -- Jump if facing a solid node while moving forward (not fences or gates).
  1135. -- This function returns true if mob jumped; otherwise 'false' + "reason".
  1136. -- Notice: this func DOES NOT rotate the mob under any circumstances.
  1137. local function try_jump(self, dtime)
  1138. -- Abort if mob does not have the ability to jump.
  1139. if not self.jump or self.jump_height == 0 or self.fly then
  1140. return false, "disabled"
  1141. end
  1142. -- Limit jump attempts to once per second.
  1143. self.jump_timer = (self.jump_timer or 0) - dtime
  1144. if self.jump_timer > 0 then
  1145. return false, "jumping"
  1146. end
  1147. self.jump_timer = 0
  1148. -- If we've only been stuck for less than a moment, we are still moving.
  1149. if self.stuck_timer < 0.5 then
  1150. return false, "moving"
  1151. end
  1152. -- We can only jump if standing on solid node.
  1153. if not minetest.registered_nodes[self.standing_on].walkable then
  1154. return false, "unwalkable"
  1155. end
  1156. -- What is in front of the mob?
  1157. local nodebot = self.facing_node
  1158. local nodetop = node_ok(v_add(self.facing_pos, {x=0, y=1, z=0}))
  1159. -- Is the mob facing a fence?
  1160. if self.facing_fence then
  1161. return false, "fence"
  1162. end
  1163. -- Is the node in front of the mob's head (assuming 2 node high mob) walkable?
  1164. local blocked = minetest.registered_nodes[nodetop.name].walkable
  1165. if blocked then
  1166. -- Only considered blocked if the mob can't jump 2 nodes high.
  1167. if self.jump_height < 2 then
  1168. return false, "blocked"
  1169. end
  1170. end
  1171. -- Is the node ahead NOT walkable? Something else is probably blocking us.
  1172. if not minetest.registered_nodes[nodebot].walkable then
  1173. return false, "walkable"
  1174. end
  1175. force_jump_up(self)
  1176. -- When in air move forward.
  1177. minetest.after(0.3, function(self)
  1178. if self.object:get_luaentity() then
  1179. local v = self.object:get_velocity()
  1180. self.object:set_acceleration({
  1181. x = v.x * 2,
  1182. y = 0,
  1183. z = v.z * 2,
  1184. })
  1185. end
  1186. end, self)
  1187. if get_velocity(self) > 0 then
  1188. mob_sound(self, self.sounds.jump)
  1189. end
  1190. -- Cannot jump again for one second.
  1191. self.jump_timer = 1
  1192. return true
  1193. end
  1194. -- Env damage avoidance extracted into its own function [MustTest].
  1195. local env_damage_nodes = {
  1196. "group:soil",
  1197. "group:stone",
  1198. "group:sand",
  1199. "group:rackstone",
  1200. "group:netherack",
  1201. node_ice,
  1202. node_snowblock,
  1203. }
  1204. -- Executed when self.state == "avoid" [MustTest].
  1205. -- Function assumes entity object exists (entity methods shall not return nil).
  1206. local function avoid_env_damage(self, dtime)
  1207. -- Get rounded position of the node the mob is standing in.
  1208. local s = self.object:get_pos()
  1209. s.y = s.y + self.collisionbox[2] + 0.5
  1210. s = v_round(s)
  1211. self.avoid.timer = self.avoid.timer - dtime
  1212. if self.avoid.timer <= 0 then
  1213. self.avoid.timer = 0
  1214. self.avoid.target = nil
  1215. end
  1216. -- Current target's timeout has expired. Need to find a new safe spot.
  1217. if self.avoid.timer <= 0 then
  1218. -- Get list of nearby safe nodes under air.
  1219. local minp = {x=s.x - 1, y=s.y - 0, z=s.z - 1}
  1220. local maxp = {x=s.x + 1, y=s.y + 1, z=s.z + 1}
  1221. local targets = minetest.find_nodes_in_area_under_air(
  1222. minp, maxp, env_damage_nodes)
  1223. -- Didn't find anything? Expand search area.
  1224. if #targets == 0 then
  1225. minp.x = minp.x - 2
  1226. minp.y = minp.y - 0
  1227. minp.z = minp.z - 2
  1228. maxp.x = maxp.x + 2
  1229. maxp.y = maxp.y + 1
  1230. maxp.z = maxp.z + 2
  1231. targets = minetest.find_nodes_in_area_under_air(
  1232. minp, maxp, env_damage_nodes)
  1233. end
  1234. -- Still didn't find anything? Expand search area again.
  1235. if #targets == 0 then
  1236. minp.x = minp.x - 2
  1237. minp.y = minp.y - 1
  1238. minp.z = minp.z - 2
  1239. maxp.x = maxp.x + 2
  1240. maxp.y = maxp.y + 1
  1241. maxp.z = maxp.z + 2
  1242. targets = minetest.find_nodes_in_area_under_air(
  1243. minp, maxp, env_damage_nodes)
  1244. end
  1245. -- Select position of random block to climb onto.
  1246. if #targets > 0 then
  1247. self.avoid.target = targets[random(1, #targets)]
  1248. self.avoid.timer = 3
  1249. end
  1250. end
  1251. -- Do we have a safe position?
  1252. if self.avoid.target then
  1253. if (self.pathfinding or 0) >= 1 then
  1254. self.path.target = v_add(self.avoid.target, {x=0, y=1, z=0})
  1255. self.path.dangerous_paths = true
  1256. push_state(self, "pathfind")
  1257. return
  1258. else
  1259. -- Look towards land and jump/move in that direction.
  1260. local yaw = yaw_to_pos(self, self.avoid.target, s)
  1261. set_yaw(self, yaw, 4)
  1262. set_velocity(self, self.run_velocity or 0)
  1263. set_animation(self, "run")
  1264. self.avoid.timer = 3
  1265. end
  1266. else
  1267. -- Mob panics, turns in random direction.
  1268. if self.avoid.timer <= 0 then
  1269. local yaw = self.object:get_yaw()
  1270. yaw = yaw + random(-pi, pi)
  1271. set_yaw(self, yaw, 6)
  1272. self.avoid.timer = 3
  1273. end
  1274. set_velocity(self, self.run_velocity or 0)
  1275. set_animation(self, "run")
  1276. end
  1277. end
  1278. local function do_avoid_enter(self)
  1279. self.avoid.target = nil
  1280. self.avoid.timer = 0
  1281. end
  1282. -- Should mob follow what I'm holding?
  1283. local function follow_holding(self, clicker)
  1284. if not clicker:is_player() then
  1285. return false
  1286. end
  1287. local item = clicker:get_wielded_item()
  1288. local t = type(self.follow)
  1289. local name = item:get_name()
  1290. -- Single item.
  1291. if t == "string" and name == self.follow then
  1292. return true
  1293. -- Multiple items.
  1294. elseif t == "table" then
  1295. for i = 1, #self.follow, 1 do
  1296. if self.follow[i] == name then
  1297. return true
  1298. end
  1299. end
  1300. end
  1301. return false
  1302. end
  1303. -- Find two animals of same type and breed if nearby and horny.
  1304. -- Note: function is never called more than once per second. (No 'dtime' arg.)
  1305. local function attempt_breed(self)
  1306. -- Child takes 240 seconds before growing into adult.
  1307. if self.child == true then
  1308. self.hornytimer = self.hornytimer + 1
  1309. if self.hornytimer > 240 then
  1310. self.child = false
  1311. self.hornytimer = 0
  1312. self.object:set_properties({
  1313. textures = self.base_texture,
  1314. mesh = self.base_mesh,
  1315. visual_size = self.base_size,
  1316. collisionbox = self.base_colbox,
  1317. selectionbox = self.base_selbox,
  1318. })
  1319. -- custom function when child grows up
  1320. if self.on_grown then
  1321. self.on_grown(self)
  1322. else
  1323. -- jump when fully grown so as not to fall into ground
  1324. self.object:set_velocity({
  1325. x = 0,
  1326. y = 5,
  1327. z = 0
  1328. })
  1329. end
  1330. end
  1331. return
  1332. end
  1333. -- horny animal can mate for 40 seconds,
  1334. -- afterwards horny animal cannot mate again for 200 seconds
  1335. if self.horny == true
  1336. and self.hornytimer < 240 then
  1337. self.hornytimer = self.hornytimer + 1
  1338. if self.hornytimer >= 240 then
  1339. self.hornytimer = 0
  1340. self.horny = false
  1341. end
  1342. end
  1343. -- find another same animal who is also horny and mate if nearby
  1344. if self.horny == true
  1345. and self.hornytimer <= 40 then
  1346. local pos = self.object:get_pos()
  1347. effect({x = pos.x, y = pos.y + 1, z = pos.z}, 8, "heart.png", 3, 4, 1, 0.1)
  1348. local objs = minetest.get_objects_inside_radius(pos, 3)
  1349. local num = 0
  1350. local ent = nil
  1351. for n = 1, #objs do
  1352. ent = objs[n]:get_luaentity()
  1353. -- check for same animal with different colour
  1354. local canmate = false
  1355. if ent then
  1356. if ent.name == self.name then
  1357. canmate = true
  1358. else
  1359. local entname = string.split(ent.name,":")
  1360. local selfname = string.split(self.name,":")
  1361. if entname[1] == selfname[1] then
  1362. entname = string.split(entname[2],"_")
  1363. selfname = string.split(selfname[2],"_")
  1364. if entname[1] == selfname[1] then
  1365. canmate = true
  1366. end
  1367. end
  1368. end
  1369. end
  1370. if ent
  1371. and canmate == true
  1372. and ent.horny == true
  1373. and ent.hornytimer <= 40 then
  1374. num = num + 1
  1375. end
  1376. -- found your mate? then have a baby
  1377. if num > 1 then
  1378. self.hornytimer = 41
  1379. ent.hornytimer = 41
  1380. -- spawn baby
  1381. minetest.after(5, function(self, ent)
  1382. if not self.object:get_luaentity() then
  1383. return
  1384. end
  1385. -- custom breed function
  1386. if self.on_breed then
  1387. -- when false skip going any further
  1388. if self.on_breed(self, ent) == false then
  1389. return
  1390. end
  1391. else
  1392. effect(pos, 15, "tnt_smoke.png", 1, 2, 2, 15, 5)
  1393. end
  1394. local mob = minetest.add_entity(pos, self.name)
  1395. local ent2 = mob:get_luaentity()
  1396. local textures = self.base_texture
  1397. -- using specific child texture (if found)
  1398. if self.child_texture then
  1399. textures = self.child_texture[1]
  1400. end
  1401. -- and resize to half height
  1402. mob:set_properties({
  1403. textures = textures,
  1404. visual_size = {
  1405. x = self.base_size.x * .5,
  1406. y = self.base_size.y * .5,
  1407. },
  1408. collisionbox = {
  1409. self.base_colbox[1] * .5,
  1410. self.base_colbox[2] * .5,
  1411. self.base_colbox[3] * .5,
  1412. self.base_colbox[4] * .5,
  1413. self.base_colbox[5] * .5,
  1414. self.base_colbox[6] * .5,
  1415. },
  1416. selectionbox = {
  1417. self.base_selbox[1] * .5,
  1418. self.base_selbox[2] * .5,
  1419. self.base_selbox[3] * .5,
  1420. self.base_selbox[4] * .5,
  1421. self.base_selbox[5] * .5,
  1422. self.base_selbox[6] * .5,
  1423. },
  1424. })
  1425. -- tamed and owned by parents' owner
  1426. ent2.child = true
  1427. ent2.tamed = true
  1428. ent2.owner = self.owner
  1429. end, self, ent)
  1430. num = 0
  1431. break
  1432. end
  1433. end
  1434. end
  1435. end
  1436. -- Find and replace what mob is looking for (grass, wheat etc.).
  1437. local function replace(self, pos)
  1438. if not mobs_griefing
  1439. or not self.replace_rate
  1440. or not self.replace_what
  1441. or self.child == true
  1442. or self.object:get_velocity().y ~= 0
  1443. or random(1, self.replace_rate) > 1 then
  1444. return
  1445. end
  1446. local what, with, y_offset
  1447. if type(self.replace_what[1]) == "table" then
  1448. local num = random(#self.replace_what)
  1449. what = self.replace_what[num][1] or ""
  1450. with = self.replace_what[num][2] or ""
  1451. y_offset = self.replace_what[num][3] or 0
  1452. else
  1453. what = self.replace_what
  1454. with = self.replace_with or ""
  1455. y_offset = self.replace_offset or 0
  1456. end
  1457. pos.y = pos.y + y_offset
  1458. local range = self.replace_range or 1
  1459. local target = minetest.find_node_near(pos, range, what)
  1460. if target then
  1461. -- Do not disturb protected stuff.
  1462. if minetest.test_protection(target, "") then return end
  1463. -- print ("replace node = ".. minetest.get_node(pos).name, pos.y)
  1464. local oldnode = {name = what}
  1465. local newnode = {name = with}
  1466. local on_replace_return
  1467. if self.on_replace then
  1468. on_replace_return = self.on_replace(self, target, oldnode, newnode)
  1469. end
  1470. if on_replace_return ~= false then
  1471. minetest.add_node(target, {name = with})
  1472. -- when cow/sheep eats grass, replace wool and milk
  1473. if self.gotten == true then
  1474. self.gotten = false
  1475. self.object:set_properties(self)
  1476. end
  1477. end
  1478. end
  1479. end
  1480. -- Check if daytime and also if mob is docile during daylight hours.
  1481. local function day_docile(self)
  1482. if not self.docile_by_day then
  1483. return false
  1484. elseif self.time_of_day > 0.2 and self.time_of_day < 0.8 then
  1485. return true
  1486. end
  1487. end
  1488. -- Debug path display function.
  1489. local function highlight_path(self)
  1490. if not mobs.debug_paths then
  1491. return
  1492. end
  1493. if not self.path.following then
  1494. return
  1495. end
  1496. -- Show path using particles.
  1497. if self.path.way and #self.path.way > 0 then
  1498. local pname = "singleplayer"
  1499. if not minetest.is_singleplayer() then
  1500. pname = gdac.name_of_admin
  1501. end
  1502. for _, pos in ipairs(self.path.way) do
  1503. utility.original_add_particle({
  1504. playername = pname,
  1505. pos = pos,
  1506. velocity = {x=0, y=0, z=0},
  1507. acceleration = {x=0, y=0, z=0},
  1508. expirationtime = 1.5,
  1509. size = 4,
  1510. collisiondetection = false,
  1511. vertical = false,
  1512. texture = "heart.png",
  1513. })
  1514. end
  1515. end
  1516. end
  1517. -- Place node, excluding it from protection.
  1518. local function force_place_block(name, pos, bridge)
  1519. minetest.set_node(pos, {name=name})
  1520. local meta = minetest.get_meta(pos)
  1521. meta:set_int("protection_cancel", 1)
  1522. -- Drop node if the position underneath is not walkable and NOT bridging.
  1523. if not bridge then
  1524. if not pos_walkable(v_add(pos, {x=0, y=-1, z=0})) then
  1525. if not minetest.test_protection(pos, "") then
  1526. sfn.drop_node(pos)
  1527. end
  1528. else
  1529. minetest.check_for_falling(pos)
  1530. end
  1531. end
  1532. end
  1533. -- Function shall attempt to place a node, exluding it from protection.
  1534. local function try_place_block(self, target, bridge)
  1535. local pn = self.place_node or node_pathfinder_place
  1536. local nn = minetest.get_node(target).name
  1537. if nn == "air" or nn == "default:snow" then
  1538. force_place_block(pn, target, bridge)
  1539. return true
  1540. end
  1541. local ndef = minetest.registered_nodes[nn]
  1542. if not ndef or nn == "ignore" then
  1543. return false
  1544. end
  1545. if ndef.buildable_to and not minetest.test_protection(target, "") then
  1546. force_place_block(pn, target, bridge)
  1547. return true
  1548. end
  1549. end
  1550. -- Shall return true if blockage was fully removed [MustTest].
  1551. local function try_dig_doorway(self)
  1552. local p1 = get_ahead_pos(self)
  1553. -- First, try to break the block above.
  1554. -- If we can't do this, there's no point in trying to break the bottom block.
  1555. -- That would also interfere with us closing the bottom hole up.
  1556. p1.y = p1.y + 1
  1557. local b1
  1558. local b2 = try_break_block(self, p1)
  1559. p1.y = p1.y - 1
  1560. -- Sometimes, a mob is trying to path through a 1x1 hole, where the block
  1561. -- above is undiggable for some reason. I can do something clever here:
  1562. -- if the bottom hole is air, I can close it up. This way, the next time the
  1563. -- pathfinder runs, it will not try to go through this hole. [MustTest]
  1564. local hole_closed = false
  1565. if not b2 then
  1566. if try_place_block(self, p1) then
  1567. hole_closed = true
  1568. end
  1569. else
  1570. b1 = try_break_block(self, p1)
  1571. end
  1572. if b1 and b2 then
  1573. return true
  1574. elseif hole_closed then
  1575. return false, "changed"
  1576. else
  1577. return false, "failed"
  1578. end
  1579. end
  1580. -- Specific attack.
  1581. local function specific_attack(list, what)
  1582. -- No list so attack default (player, animals etc.)
  1583. if list == nil then
  1584. return true
  1585. end
  1586. -- is found entity on list to attack?
  1587. for no = 1, #list do
  1588. if list[no] == what then
  1589. return true
  1590. end
  1591. end
  1592. return false
  1593. end
  1594. -- Select nearest target entity from an array of entities.
  1595. local function select_nearest_entity(self, list)
  1596. local s = self.object:get_pos()
  1597. s.y = s.y + 1 -- Make easier to look up hills.
  1598. local closest_target
  1599. local current_distance = self.view_range + 1
  1600. -- Go through entities and select closest.
  1601. local size = #list -- Cache array length.
  1602. for n = 1, size, 1 do
  1603. local target = list[n]
  1604. local p = target:get_pos()
  1605. p.y = p.y + 1 -- Make easier to look up hills.
  1606. local dist = get_distance(p, s)
  1607. -- Choose closest target that is not self.
  1608. if dist > 0 then
  1609. if dist < current_distance and raycast_los(self, s, p) then
  1610. current_distance = dist
  1611. closest_target = target
  1612. end
  1613. end
  1614. end
  1615. return closest_target
  1616. end
  1617. -- Specific runaway.
  1618. local function specific_runaway(list, what)
  1619. -- No list.
  1620. if not list then return end
  1621. -- Found entity on list to run away from?
  1622. for no = 1, #list, 1 do
  1623. if list[no] == what then
  1624. return true
  1625. end
  1626. end
  1627. end
  1628. -- Get list of targets in area that should be run away from.
  1629. local function get_avoidable_targets(self)
  1630. local s = self.object:get_pos()
  1631. local objs = minetest.get_objects_inside_radius(s, self.view_range)
  1632. for n = 1, #objs, 1 do
  1633. local ent = objs[n]:get_luaentity()
  1634. -- Are we a player?
  1635. if objs[n]:is_player() then
  1636. local pname = objs[n]:get_player_name()
  1637. -- If player invisible them mob does not run away from them.
  1638. if mobs.is_invisible(self, pname) then
  1639. objs[n] = nil
  1640. goto continue
  1641. end
  1642. -- Ignore dead players.
  1643. if objs[n]:get_hp() <= 0 then
  1644. objs[n] = nil
  1645. goto continue
  1646. end
  1647. -- If player nametag is off, reduce range at which mob can see them.
  1648. if objs[n] and player_labels.query_nametag_onoff(pname) == false then
  1649. local r = self.view_range * 0.8
  1650. local p = objs[n]:get_pos()
  1651. if v_distance(p, s) > r then
  1652. objs[n] = nil
  1653. goto continue
  1654. end
  1655. end
  1656. -- Don't run from ignored players.
  1657. if minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1658. objs[n] = nil
  1659. goto continue
  1660. end
  1661. -- Or are we a mob?
  1662. elseif ent and ent._cmi_is_mob then
  1663. -- Don't run away from mobs of our own type, or unknown type.
  1664. if ent.name == "" or self.name == ent.name then
  1665. objs[n] = nil
  1666. goto continue
  1667. end
  1668. -- Ignore mobs we don't care about.
  1669. if not specific_runaway(self.runaway_from, ent.name) then
  1670. objs[n] = nil
  1671. goto continue
  1672. end
  1673. -- Remove all other entities.
  1674. else
  1675. objs[n] = nil
  1676. goto continue
  1677. end
  1678. ::continue::
  1679. end
  1680. -- Compact targets into an array.
  1681. local targets = {}
  1682. local index = 1
  1683. for k, v in pairs(objs) do
  1684. targets[index] = v
  1685. index = index + 1
  1686. end
  1687. return targets
  1688. end
  1689. -- Get list of targets in area that can be attacked.
  1690. local function get_attackable_targets(self)
  1691. local s = self.object:get_pos()
  1692. local objs = minetest.get_objects_inside_radius(s, self.view_range)
  1693. -- Scan found entities and remove entities we aren't interested in.
  1694. for n = 1, #objs, 1 do
  1695. local ent = objs[n]:get_luaentity()
  1696. -- Are we a player?
  1697. if objs[n]:is_player() then
  1698. local pname = objs[n]:get_player_name()
  1699. -- If mob does not attack players.
  1700. if not self.attack_players then
  1701. objs[n] = nil
  1702. goto continue
  1703. end
  1704. -- If player is invisible (some mobs can ignore invisibility).
  1705. if mobs.is_invisible(self, pname) then
  1706. objs[n] = nil
  1707. goto continue
  1708. end
  1709. if not specific_attack(self.specific_attack, "player") then
  1710. objs[n] = nil
  1711. goto continue
  1712. end
  1713. -- Ignore dead players.
  1714. if objs[n]:get_hp() <= 0 then
  1715. objs[n] = nil
  1716. goto continue
  1717. end
  1718. -- If player nametag is off, reduce range at which mob can see them.
  1719. if player_labels.query_nametag_onoff(pname) == false then
  1720. local r = self.view_range * 0.8
  1721. local p = objs[n]:get_pos()
  1722. if v_distance(p, s) > r then
  1723. objs[n] = nil
  1724. goto continue
  1725. end
  1726. end
  1727. -- Don't attack ignored players.
  1728. if minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1729. objs[n] = nil
  1730. goto continue
  1731. end
  1732. -- Or are we a mob?
  1733. elseif ent and ent._cmi_is_mob then
  1734. -- Remove mobs not to attack.
  1735. if self.name == ent.name
  1736. or (not self.attack_animals and ent.type == "animal")
  1737. or (not self.attack_monsters and ent.type == "monster")
  1738. or (not self.attack_npcs and ent.type == "npc")
  1739. or not specific_attack(self.specific_attack, ent.name) then
  1740. objs[n] = nil
  1741. goto continue
  1742. end
  1743. -- Ignore allies.
  1744. if self.specific_allies and self.specific_allies[ent.name] then
  1745. objs[n] = nil
  1746. goto continue
  1747. end
  1748. -- Remove all other entities.
  1749. else
  1750. objs[n] = nil
  1751. goto continue
  1752. end
  1753. ::continue::
  1754. end
  1755. -- Compact targets into an array.
  1756. local targets = {}
  1757. local index = 1
  1758. for k, v in pairs(objs) do
  1759. targets[index] = v
  1760. index = index + 1
  1761. end
  1762. return targets
  1763. end
  1764. -- General attack function for all mobs. Scan for targets and attack them.
  1765. -- This function (usually) only executes once per second (per mob) [MustTest].
  1766. local function general_attack(self)
  1767. -- Skip because mob is passive.
  1768. if self.passive then return end
  1769. -- Skip because already attacking something, or running away.
  1770. if self.state == "attack" then return end
  1771. if self.state == "runaway" then return end
  1772. if self.state == "pathfind" then return end
  1773. if self.state == "avoid" then return end
  1774. if self.state == "digbuild" then return end
  1775. -- Skip if mob is docile during day.
  1776. if day_docile(self) then return end
  1777. -- Get array list of targets to attack.
  1778. local objs = get_attackable_targets(self)
  1779. local target = select_nearest_entity(self, objs)
  1780. -- Attack closest target.
  1781. if target and random(1, 100) < (self.attack_chance or 95) then
  1782. do_attack(self, target)
  1783. return
  1784. end
  1785. -- Hunt random nearby target. (Allows targets outside of LOS.)
  1786. if #objs > 0 then
  1787. if not target and random(1, 100) < (self.hunt_chance or 5) then
  1788. local tarhunt = objs[random(1, #objs)]
  1789. do_attack(self, tarhunt)
  1790. return
  1791. end
  1792. end
  1793. end
  1794. -- Find someone to runaway from.
  1795. local function runaway_from(self)
  1796. -- Abort if mob doesn't fear any particular enemies.
  1797. if not self.runaway_from then return end
  1798. -- If non-passive mob is attacking, then it will not run away right now.
  1799. if self.state == "attack" and not self.passive then return end
  1800. if self.state == "runaway" then return end
  1801. if self.state == "pathfind" then return end
  1802. if self.state == "avoid" then return end
  1803. -- Get array list of targets to run away from.
  1804. local objs = get_avoidable_targets(self)
  1805. local target = select_nearest_entity(self, objs)
  1806. if target then
  1807. local s = self.object:get_pos()
  1808. local p = target:get_pos()
  1809. local yaw = yaw_to_pos(self, p, s)
  1810. yaw = yaw + pi -- Face opposite.
  1811. set_yaw(self, yaw, 4)
  1812. transition_state(self, "runaway")
  1813. end
  1814. end
  1815. -- Get an object ref to the mob's owner if in view range.
  1816. local function get_owner_in_range(self)
  1817. if not self.owner or self.owner == "" then
  1818. return
  1819. end
  1820. -- Only players can be mob owners.
  1821. local players = minetest.get_connected_players()
  1822. for i = 1, #players, 1 do
  1823. local pref = players[i]
  1824. local pname = pref:get_player_name()
  1825. if pname == self.owner then
  1826. local s = self.object:get_pos()
  1827. local p = pref:get_pos()
  1828. if v_distance(s, p) < self.view_range then
  1829. s.y = s.y + 1
  1830. p.y = p.y + 1
  1831. if raycast_los(self, s, p) then
  1832. -- Do not return player ref if player is ignored.
  1833. if not minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1834. return pref
  1835. end
  1836. end
  1837. end
  1838. end
  1839. end
  1840. end
  1841. local function get_follow_holding_in_range(self)
  1842. if not self.follow or self.follow == "" then
  1843. return
  1844. end
  1845. -- Only players can hold items that mob might follow.
  1846. local players = minetest.get_connected_players()
  1847. for i = 1, #players, 1 do
  1848. local pref = players[i]
  1849. local s = self.object:get_pos()
  1850. local p = pref:get_pos()
  1851. if v_distance(s, p) < self.view_range then
  1852. if follow_holding(self, pref) then
  1853. s.y = s.y + 1
  1854. p.y = p.y + 1
  1855. if raycast_los(self, s, p) then
  1856. local pname = pref:get_player_name()
  1857. if not minetest.check_player_privs(pname, {mobs_ignore=true}) then
  1858. return pref
  1859. end
  1860. end
  1861. end
  1862. end
  1863. end
  1864. end
  1865. -- Check nearby players and follow them if conditions are right.
  1866. -- Shall follow player if player is mob's owner, or if holding item.
  1867. local function follow_something(self)
  1868. -- Skip if attacking or running away.
  1869. if self.state == "attack" then return end
  1870. if self.state == "runaway" then return end
  1871. if self.state == "avoid" then return end
  1872. if self.state == "pathfind" then return end
  1873. -- Skip if already following.
  1874. if self.following and self.following:get_pos() then return end
  1875. -- Skip if horny (who comes up with these terms? Geez).
  1876. if self.horny then return end
  1877. -- Skip if mob is child.
  1878. if self.child then return end
  1879. -- If the mob has an owner nearby, follow him!
  1880. local owner = get_owner_in_range(self)
  1881. if owner then
  1882. local pname = owner:get_player_name()
  1883. if not mobs.is_invisible(self, pname) then
  1884. self.following = owner
  1885. transition_state(self, "follow")
  1886. return
  1887. end
  1888. end
  1889. local holding = get_follow_holding_in_range(self)
  1890. if holding then
  1891. local pname = holding:get_player_name()
  1892. if not mobs.is_invisible(self, pname) then
  1893. self.following = holding
  1894. transition_state(self, "follow")
  1895. return
  1896. end
  1897. end
  1898. end
  1899. -- If the mob has a target, and LOS to target for time, then refocus attack!
  1900. -- This function expects to run once per second.
  1901. local function refocus_attack(self)
  1902. if not self.attack then
  1903. self.refocus_timer = 0
  1904. return
  1905. end
  1906. local s = self.object:get_pos()
  1907. local p = self.attack:get_pos()
  1908. if not p then
  1909. self.refocus_timer = 0
  1910. return
  1911. end
  1912. -- Make looking up hills easier.
  1913. s.y = s.y + 1
  1914. p.y = p.y + 1
  1915. local los = raycast_los(self, s, p)
  1916. -- Count consecutive seconds in which mob has LOS to active target.
  1917. if los then
  1918. self.refocus_timer = (self.refocus_timer or 0) + 1
  1919. else
  1920. self.refocus_timer = 0
  1921. return
  1922. end
  1923. -- The counter limit is arbitrary.
  1924. if self.refocus_timer >= 8 then
  1925. transition_state(self, "attack")
  1926. return
  1927. end
  1928. end
  1929. -- Dogshoot attack switch and counter function.
  1930. local function dogswitch(self, dtime)
  1931. -- Switch mode not activated.
  1932. if not self.dogshoot_switch or not dtime then
  1933. return 0
  1934. end
  1935. -- Run timer.
  1936. self.dogshoot_count = self.dogshoot_count + dtime
  1937. local expired
  1938. if self.dogshoot_switch == 1 and self.dogshoot_count > self.dogshoot_count_max then
  1939. expired = true
  1940. elseif self.dogshoot_switch == 2 and self.dogshoot_count > self.dogshoot_count2_max then
  1941. expired = true
  1942. end
  1943. if expired then
  1944. -- Reset timer.
  1945. self.dogshoot_count = 0
  1946. -- Toggle.
  1947. if self.dogshoot_switch == 1 then
  1948. self.dogshoot_switch = 2
  1949. else
  1950. self.dogshoot_switch = 1
  1951. end
  1952. end
  1953. return self.dogshoot_switch
  1954. end
  1955. local function do_stand_enter(self)
  1956. set_velocity(self, 0)
  1957. set_animation(self, "stand")
  1958. end
  1959. -- State self.state == "stand" moved to its own function [MustTest].
  1960. local function do_stand_state(self, dtime)
  1961. -- Avoid dangerous nodes.
  1962. if is_node_dangerous(self, self.standing_in) then
  1963. push_state(self, "avoid")
  1964. return
  1965. end
  1966. local s = self.object:get_pos()
  1967. if keep_mob_centered(self, s) then
  1968. return
  1969. end
  1970. -- NPCs look at any players nearby, otherwise turn randomly.
  1971. if random(1, 4) == 1 then
  1972. local lp = nil
  1973. if self.type == "npc" then
  1974. local objs = minetest.get_objects_inside_radius(s, 10)
  1975. for n = 1, #objs, 1 do
  1976. if objs[n]:is_player() then
  1977. lp = objs[n]:get_pos()
  1978. break
  1979. end
  1980. end
  1981. -- Small chance that player gets ignored.
  1982. if random(1, 4) == 1 then
  1983. lp = nil
  1984. end
  1985. end
  1986. local yaw = self.object:get_yaw()
  1987. if lp then
  1988. yaw = yaw_to_pos(self, lp, s)
  1989. else
  1990. yaw = yaw + random(-0.5, 0.5)
  1991. end
  1992. set_yaw(self, yaw, 8)
  1993. end
  1994. set_velocity(self, 0)
  1995. set_animation(self, "stand")
  1996. -- Mobs ordered to stand stay standing.
  1997. if self.order == "stand" then return end
  1998. -- Am I facing something dangerous?
  1999. local result, reason = facing_wall_or_pit(self)
  2000. if result then return end
  2001. -- Animals are restricted by fences.
  2002. if self.type == "animal" and self.facing_fence then
  2003. return
  2004. end
  2005. if random(1, 100) > (self.walk_chance or 0) then
  2006. return
  2007. end
  2008. transition_state(self, "walk")
  2009. --[[ fly up/down randomly for flying mobs
  2010. if self.fly and random(1, 100) <= self.walk_chance then
  2011. local v = self.object:get_velocity()
  2012. local ud = random(-1, 2) / 9
  2013. self.object:set_velocity({x = v.x, y = ud, z = v.z})
  2014. end--]]
  2015. end
  2016. local function do_walk_enter(self)
  2017. set_velocity(self, self.walk_velocity or 0)
  2018. set_animation(self, "walk")
  2019. end
  2020. -- State self.state == "walk" moved to its own function [MustTest].
  2021. local function do_walk_state(self, dtime)
  2022. -- Avoid dangerous nodes.
  2023. if is_node_dangerous(self, self.standing_in) then
  2024. push_state(self, "avoid")
  2025. return
  2026. end
  2027. -- Am I facing something dangerous?
  2028. local result, reason = facing_wall_or_pit(self)
  2029. if result then
  2030. transition_state(self, "stand")
  2031. return
  2032. end
  2033. if self.type == "animal" and self.facing_fence then
  2034. transition_state(self, "stand")
  2035. return
  2036. end
  2037. -- Chance to stop walking.
  2038. if random(1, 100) <= 30 then
  2039. transition_state(self, "stand")
  2040. return
  2041. end
  2042. -- Randomly turn.
  2043. if random(1, 100) <= 30 then
  2044. local yaw = self.object:get_yaw()
  2045. yaw = yaw + random(-0.5, 0.5)
  2046. set_yaw(self, yaw, 8)
  2047. end
  2048. set_velocity(self, self.walk_velocity or 0)
  2049. if flight_check(self)
  2050. and self.animation
  2051. and self.animation.fly_start
  2052. and self.animation.fly_end then
  2053. set_animation(self, "fly")
  2054. else
  2055. set_animation(self, "walk")
  2056. end
  2057. end
  2058. local function do_runaway_enter(self)
  2059. self.runaway_timer = 5
  2060. end
  2061. -- Runaway (self.state == "runaway") moved to its own function [MustTest].
  2062. -- Note: this function executes once per frame ('continuous is true').
  2063. local function do_runaway_state(self, dtime)
  2064. self.runaway_timer = (self.runaway_timer or 0) - dtime
  2065. if self.runaway_timer <= 0 then
  2066. -- Timer has expired. Should we keep running, or stop?
  2067. local objs = get_avoidable_targets(self)
  2068. local target = select_nearest_entity(self, objs)
  2069. if target then
  2070. self.runaway_timer = 5
  2071. else
  2072. pop_state(self)
  2073. return
  2074. end
  2075. end
  2076. -- Do evasion if inside dangerous node.
  2077. if is_node_dangerous(self, self.standing_in) then
  2078. push_state(self, "avoid")
  2079. return
  2080. end
  2081. -- Stop fleeing if heading into obstacle.
  2082. local result, reason = facing_wall_or_pit(self)
  2083. if result then
  2084. pop_state(self)
  2085. return
  2086. end
  2087. try_jump(self, dtime)
  2088. set_velocity(self, self.sprint_velocity or 0)
  2089. set_animation(self, "run")
  2090. end
  2091. local function do_avoid_state(self, dtime)
  2092. if is_node_dangerous(self, self.standing_in) then
  2093. avoid_env_damage(self, dtime)
  2094. else
  2095. pop_state(self)
  2096. end
  2097. end
  2098. -- Mob has caught up with target.
  2099. local function do_caught_attack(self, dtime)
  2100. -- Target might not be valid anymore.
  2101. if not self.attack or not self.attack:get_pos() then
  2102. pop_state(self)
  2103. return
  2104. end
  2105. local s = self.object:get_pos()
  2106. local p = self.attack:get_pos()
  2107. local dist = get_distance(p, s)
  2108. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2109. -- Stop attacking if target invisible, dead, or out of range.
  2110. if dist > self.view_range or self.attack:get_hp() <= 0
  2111. or mobs.is_invisible(self, targetname) then
  2112. pop_state(self)
  2113. return
  2114. end
  2115. -- Start chasing again if target moved beyond reach.
  2116. if dist > self.reach then
  2117. transition_substate(self, "chase")
  2118. return
  2119. end
  2120. -- Stop and face target.
  2121. do
  2122. set_velocity(self, 0)
  2123. local yaw = yaw_to_pos(self, p, s)
  2124. set_yaw(self, yaw)
  2125. end
  2126. -- If mob does not have a custom attack, or that function returns true, then
  2127. -- execute the default punch-attack code.
  2128. if not self.custom_attack or self.custom_attack(self, p) == true then
  2129. set_animation(self, "punch")
  2130. punch_target(self, dtime)
  2131. end
  2132. end
  2133. -- Mob is blocked from reaching target by environment, etc.
  2134. local function do_blocked_attack(self, dtime)
  2135. -- Target might not be valid anymore.
  2136. if not self.attack or not self.attack:get_pos() then
  2137. pop_state(self)
  2138. return
  2139. end
  2140. -- Avoid dangerous nodes.
  2141. if is_node_dangerous(self, self.standing_in) then
  2142. push_state(self, "avoid")
  2143. return
  2144. end
  2145. local s = self.object:get_pos()
  2146. local p = self.attack:get_pos()
  2147. local dist = get_distance(p, s)
  2148. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2149. -- Stop attacking if target invisible, dead, or out of range.
  2150. if dist > self.view_range or self.attack:get_hp() <= 0
  2151. or mobs.is_invisible(self, targetname) then
  2152. pop_state(self)
  2153. return
  2154. end
  2155. -- Turn to face target. If the target moves around we may eventually become
  2156. -- unblocked.
  2157. do
  2158. set_velocity(self, 0)
  2159. set_animation(self, "stand")
  2160. local yaw = yaw_to_pos(self, p, s)
  2161. set_yaw(self, yaw)
  2162. end
  2163. -- Punch target if within punching range even while stuck [MustTest].
  2164. if dist <= (self.punch_reach or self.reach or 0) then
  2165. punch_target(self, dtime)
  2166. end
  2167. -- If dogshooter, transition to shoot once dogshoot timer expires.
  2168. -- This attack works even while mob is stuck.
  2169. if self.attack_type == "dogshoot" then
  2170. local switch = dogswitch(self, dtime)
  2171. if switch == 1 then
  2172. transition_substate(self, "shoot")
  2173. return
  2174. end
  2175. end
  2176. -- Flag set if mob is directly over or under player. If that is the case, but
  2177. -- we're still beyond the mob's reach, then we have to try something else ....
  2178. local overunder = false
  2179. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  2180. overunder = true
  2181. end
  2182. if dist < self.reach then
  2183. transition_substate(self, "chase")
  2184. return
  2185. end
  2186. -- If mob facing obstacle, or directly over/under target, then we're stuck.
  2187. if overunder or facing_wall_or_pit(self) then
  2188. -- Mob is stuck and has been standing for 3 seconds.
  2189. if (self.pathfinding or 0) >= 1 and self.stand_timer > 3 then
  2190. self.path.dangerous_paths = false
  2191. self.path.target = v_round(self.attack:get_pos())
  2192. push_state(self, "pathfind")
  2193. return
  2194. end
  2195. else
  2196. -- Otherwise, not facing obstacle and NOT over/under target. Chase!
  2197. transition_substate(self, "chase")
  2198. return
  2199. end
  2200. end
  2201. local function do_chase_attack(self, dtime)
  2202. -- Target might not be valid anymore.
  2203. if not self.attack or not self.attack:get_pos() then
  2204. pop_state(self)
  2205. return
  2206. end
  2207. local s = self.object:get_pos()
  2208. local p = self.attack:get_pos()
  2209. local dist = get_distance(p, s)
  2210. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2211. -- Stop attacking if target invisible, dead, or out of range.
  2212. if dist > self.view_range or self.attack:get_hp() <= 0
  2213. or mobs.is_invisible(self, targetname) then
  2214. pop_state(self)
  2215. return
  2216. end
  2217. -- If dogshooter, transition to shoot once dogshoot timer expires.
  2218. if self.attack_type == "dogshoot" then
  2219. local switch = dogswitch(self, dtime)
  2220. if switch == 1 then
  2221. transition_substate(self, "shoot")
  2222. return
  2223. end
  2224. end
  2225. local dist = get_distance(p, s)
  2226. -- TODO: must use set_velocity (for fliers) here, not directly!
  2227. if self.fly and dist > self.reach then
  2228. local me_y = floor(s.y + 1)
  2229. local p_y = floor(p.y + 1)
  2230. local v = self.object:get_velocity()
  2231. if flight_check(self, s) then
  2232. if me_y < p_y then
  2233. -- Fly up.
  2234. self.object:set_velocity({
  2235. x = v.x,
  2236. y = 1 * self.walk_velocity,
  2237. z = v.z
  2238. })
  2239. elseif me_y > p_y then
  2240. -- Fly down.
  2241. self.object:set_velocity({
  2242. x = v.x,
  2243. y = -1 * self.walk_velocity,
  2244. z = v.z
  2245. })
  2246. end
  2247. else
  2248. if me_y < p_y then
  2249. -- Fly up slowly.
  2250. self.object:set_velocity({
  2251. x = v.x,
  2252. y = 0.01,
  2253. z = v.z
  2254. })
  2255. elseif me_y > p_y then
  2256. -- Fly down slowly.
  2257. self.object:set_velocity({
  2258. x = v.x,
  2259. y = -0.01,
  2260. z = v.z
  2261. })
  2262. end
  2263. end
  2264. end
  2265. -- Face target.
  2266. do
  2267. local yaw = yaw_to_pos(self, p, s)
  2268. set_yaw(self, yaw)
  2269. end
  2270. -- Flag set if mob is directly over or under player. If that is the case, but
  2271. -- we're still beyond the mob's reach, then we have to try something else ....
  2272. local overunder = false
  2273. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  2274. overunder = true
  2275. end
  2276. -- Move towards enemy if beyond mob reach.
  2277. if dist > self.reach then
  2278. -- Note: the 'facing_wall_or_pit' function also checks for dangerous nodes.
  2279. -- But some dangerous nodes are non-walkable, which means the pathfinder
  2280. -- would path through them.
  2281. if facing_wall_or_pit(self) or overunder or self.stuck_timer > 1 then
  2282. -- Chase blocked, NOT pathfind blocked.
  2283. transition_substate(self, "blocked")
  2284. else
  2285. try_jump(self, dtime)
  2286. if dist > self.punch_reach then
  2287. set_velocity(self, self.sprint_velocity or 0)
  2288. set_animation(self, "run")
  2289. else
  2290. set_velocity(self, self.run_velocity or 0)
  2291. set_animation(self, "run")
  2292. end
  2293. end
  2294. -- Punch target if within punching range even while moving [MustTest].
  2295. if dist <= (self.punch_reach or self.reach or 0) then
  2296. punch_target(self, dtime)
  2297. end
  2298. else
  2299. -- Inside 'self.reach' range.
  2300. transition_substate(self, "caught")
  2301. end
  2302. end
  2303. local function do_shoot_attack(self, dtime)
  2304. -- Target might not be valid anymore.
  2305. if not self.attack or not self.attack:get_pos() then
  2306. pop_state(self)
  2307. return
  2308. end
  2309. local s = self.object:get_pos()
  2310. local p = self.attack:get_pos()
  2311. local dist = get_distance(p, s)
  2312. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2313. -- Stop attacking if target invisible, dead, or out of range.
  2314. if dist > self.view_range or self.attack:get_hp() <= 0
  2315. or mobs.is_invisible(self, targetname) then
  2316. pop_state(self)
  2317. return
  2318. end
  2319. p.y = p.y - 0.5
  2320. s.y = s.y + 0.5
  2321. -- If dogshooter, transition to chase once dogshoot timer expires.
  2322. if self.attack_type == "dogshoot" then
  2323. local switch = dogswitch(self, dtime)
  2324. if switch ~= 1 then
  2325. transition_substate(self, "chase")
  2326. return
  2327. end
  2328. end
  2329. -- Face target and stand.
  2330. local yaw = yaw_to_pos(self, p, s)
  2331. set_yaw(self, yaw)
  2332. set_velocity(self, 0)
  2333. set_animation(self, "shoot")
  2334. self.shoot_timer = (self.shoot_timer or 0) + dtime
  2335. if self.shoot_timer > (self.shoot_interval or 1) then
  2336. self.shoot_timer = 0
  2337. -- Shoot in this direction.
  2338. local vec = {
  2339. x = p.x - s.x,
  2340. y = p.y - s.y,
  2341. z = p.z - s.z,
  2342. }
  2343. shoot_arrow(self, vec)
  2344. end
  2345. end
  2346. local function do_attack_enter(self)
  2347. if random(0, 100) < 90 and self.sounds.war_cry then
  2348. mob_sound(self, self.sounds.war_cry)
  2349. end
  2350. end
  2351. local function do_attack_exit(self)
  2352. end
  2353. -- State self.state == "attack" extracted to its own function [MustTest].
  2354. -- The attack routines (explode, dogfight, shoot, dogshoot, etc.). This function
  2355. -- runs once per frame, while the "attack" state is active.
  2356. local function do_attack_state(self, dtime)
  2357. -- Abort if we have no target!
  2358. if not self.attack or not self.attack:get_pos() then
  2359. pop_state(self)
  2360. return
  2361. end
  2362. -- Calculate distance from mob and enemy.
  2363. local s = self.object:get_pos()
  2364. local p = self.attack:get_pos()
  2365. -- Abort if target entity does not exist.
  2366. if not p then
  2367. pop_state(self)
  2368. return
  2369. end
  2370. local dist = get_distance(p, s)
  2371. local targetname = (self.attack:is_player() and self.attack:get_player_name()) or ""
  2372. -- Stop attacking if target invisible, dead, or out of range.
  2373. if dist > self.view_range or self.attack:get_hp() <= 0
  2374. or mobs.is_invisible(self, targetname) then
  2375. pop_state(self)
  2376. return
  2377. end
  2378. local attack_type = self.attack_type
  2379. -- The special "dogshoot" attack type basically just swaps between "dogfight"
  2380. -- and "shoot" based on timers.
  2381. if attack_type == "dogshoot" then
  2382. local switch = dogswitch(self, dtime)
  2383. if switch == 1 then
  2384. attack_type = "shoot"
  2385. else
  2386. -- If 'dogswitch' returns 0 or 2, mob shall dogfight.
  2387. attack_type = "dogfight"
  2388. end
  2389. end
  2390. if attack_type == "dogfight" then
  2391. transition_substate(self, "chase")
  2392. elseif attack_type == "shoot" then
  2393. transition_substate(self, "shoot")
  2394. end
  2395. end
  2396. -- Code to handle mob's lifetimer extracted to own function [MustTest].
  2397. local function do_lifetimer(self, pos)
  2398. if self.tamed then return end
  2399. if self.type == "npc" then return end
  2400. if self.state == "attack" then return end
  2401. if self.lifetimer > 20000 then return end
  2402. if not remove_far then return end
  2403. self.lifetimer = self.lifetimer - dtime
  2404. if self.lifetimer > 0 then return end
  2405. -- Only despawn away from player
  2406. local objs = minetest.get_objects_inside_radius(pos, 15)
  2407. for n = 1, #objs, 1 do
  2408. if objs[n]:is_player() then
  2409. self.lifetimer = 20
  2410. return
  2411. end
  2412. end
  2413. effect(pos, 15, "tnt_smoke.png", 2, 4, 2, 0)
  2414. -- Mark for removal as last action on mob_step().
  2415. self.mkrm = true
  2416. end
  2417. -- This function gets the position of the node the mob is standing IN.
  2418. -- The node position around its feet, basically.
  2419. local function get_standing_pos(self, pos)
  2420. -- Copy position argument so we do not modify it.
  2421. local p = (pos and vector.copy(pos)) or self.object:get_pos()
  2422. local y = self.collisionbox[2]
  2423. if self.child then
  2424. y = self.collisionbox[2] * 0.5
  2425. end
  2426. p.y = p.y + y + 0.25
  2427. p = v_round(p)
  2428. return p
  2429. end
  2430. -- Code to get what mob is standing in/on extracted to own function [MustTest].
  2431. local function update_foot_nodes(self, pos, dtime)
  2432. -- Get node at foot level every quarter second.
  2433. self.node_timer = (self.node_timer or 0) + dtime
  2434. if self.node_timer > 0.25 then
  2435. self.node_timer = 0
  2436. -- What is mob standing in and on?
  2437. local spos = get_standing_pos(self, pos)
  2438. self.standing_in = node_ok(spos, "air").name
  2439. spos.y = spos.y - 1
  2440. self.standing_on = node_ok(spos, "air").name
  2441. -- What is mob facing?
  2442. self.facing_pos = get_ahead_pos(self, pos)
  2443. self.facing_node = node_ok(self.facing_pos, "air").name
  2444. -- Are we facing a fence or wall?
  2445. local fn = self.facing_node
  2446. if fn:find("fence") or fn:find("gate") or fn:find("wall") then
  2447. self.facing_fence = true
  2448. else
  2449. self.facing_fence = false
  2450. end
  2451. end
  2452. end
  2453. -- Get the absolute delta angle between two yaw angles, in radians.
  2454. function yaw_delta(y1, y2)
  2455. local y
  2456. -- First, get the difference between the two yaws.
  2457. if y1 > y2 then
  2458. y = y1 - y2
  2459. else
  2460. y = y2 - y1
  2461. end
  2462. -- Subtract PI if needed to get the smaller delta.
  2463. if y > pi then
  2464. y = y - (pi * 2)
  2465. end
  2466. return abs(y)
  2467. end
  2468. -- Detect whether a waypoint path contains sharp turns. This function checks the
  2469. -- mob's current yaw against the next 3 waypoints. If its yaw to each waypoint
  2470. -- is within a small tolerance, the path is straight; otherwise it is not.
  2471. local function path_is_straight(self, pos)
  2472. local path = self.path.way
  2473. if not path then return end
  2474. local w1 = path[1]
  2475. local w2 = path[2]
  2476. local w3 = path[3]
  2477. if not w1 or not w2 or not w3 then
  2478. return
  2479. end
  2480. local y1 = self.object:get_yaw()
  2481. local y2 = yaw_to_pos(self, w1, pos)
  2482. local y3 = yaw_to_pos(self, w2, pos)
  2483. local y4 = yaw_to_pos(self, w3, pos)
  2484. local d1 = deg(yaw_delta(y1, y2))
  2485. local d2 = deg(yaw_delta(y1, y3))
  2486. local d3 = deg(yaw_delta(y1, y4))
  2487. return (d1 < 15 and d2 < 10 and d3 < 5)
  2488. end
  2489. local function do_pathfind_enter(self)
  2490. -- The pathfinder requires a target. I assume the target is a rounded vector.
  2491. -- It should be inside an air node, or non-walkable, and walkable node under.
  2492. if not self.path.target then
  2493. pop_state(self)
  2494. return
  2495. end
  2496. transition_substate(self, "newpath")
  2497. end
  2498. local function do_pathfind_newpath(self, dtime)
  2499. -- Make sure to round positions, because the pathfinder is very sensitive.
  2500. local start = self.object:get_pos()
  2501. start.y = start.y + self.collisionbox[2] + 0.5
  2502. start = v_round(start)
  2503. -- The mob might be clipped inside a node. Find a start position nearby.
  2504. if pos_walkable(start) then
  2505. local minp = v_add(start, {x=-1, y=0, z=-1})
  2506. local maxp = v_add(start, {x=1, y=0, z=1})
  2507. local positions = hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  2508. if #positions == 0 then
  2509. transition_state(self, "")
  2510. return
  2511. else
  2512. start = positions[random(1, #positions)]
  2513. end
  2514. end
  2515. local target = v_round(self.path.target)
  2516. local radius = self.pathing_radius or 16
  2517. -- The target might not always be reachable (e.g., the target is a player who
  2518. -- has sneak-moved off the edge of a node, and thus are "standing" in air). So
  2519. -- we choose a random valid position near the target instead of the target
  2520. -- itself. We also check if the player is slightly clipped inside walkable.
  2521. if pos_walkable(target) or not pos_walkable(v_add(target, {x=0, y=-1, z=0})) then
  2522. local minp = v_add(target, {x=-2, y=-1, z=-2})
  2523. local maxp = v_add(target, {x=2, y=1, z=2})
  2524. local positions = hb4.find_walkable_in_area_under_unwalkable(minp, maxp)
  2525. if #positions == 0 then
  2526. if (self.pathfinding or 0) >= 3 then
  2527. -- Replace pathfinder with dig/build code.
  2528. -- The dig/build code should swap back to the pathfinder when ready.
  2529. self.digbuild.target = self.path.target
  2530. pop_state(self)
  2531. push_state(self, "digbuild")
  2532. return
  2533. end
  2534. transition_state(self, "")
  2535. return
  2536. else
  2537. target = positions[random(1, #positions)]
  2538. end
  2539. end
  2540. local dh = 6
  2541. local jh = 0
  2542. if self.fear_height ~= 0 then dh = (self.fear_height - 1) end
  2543. if self.stepheight > 1 then jh = 1 end
  2544. -- Do not generate paths with a jump-height above 3 nodes.
  2545. if self.jump then
  2546. if self.jump_height >= 3 then
  2547. jh = 3
  2548. elseif self.jump_height >= 2 then
  2549. jh = 2
  2550. elseif self.jump_height >= 1 then
  2551. jh = 1
  2552. end
  2553. end
  2554. -- Note: pathfinder is very sensitive to start and finish positions.
  2555. local path = minetest.find_path(start, target, radius, jh, dh, "A*")
  2556. if path then
  2557. -- Yay, I found path.
  2558. if self.attack and self.attack:get_pos() then
  2559. mob_sound(self, self.sounds.war_cry)
  2560. else
  2561. mob_sound(self, self.sounds.random)
  2562. end
  2563. self.path.way = path
  2564. self.path.following = true
  2565. self.path.blocked_count = 0
  2566. self.path.waypoints_gotten = 0
  2567. transition_substate(self, "")
  2568. return
  2569. else
  2570. if (self.pathfinding or 0) >= 3 then
  2571. -- Replace pathfinder with dig/build code.
  2572. -- The dig/build code should swap back to the pathfinder when ready.
  2573. self.digbuild.target = self.path.target
  2574. pop_state(self)
  2575. push_state(self, "digbuild")
  2576. return
  2577. end
  2578. transition_state(self, "")
  2579. return
  2580. end
  2581. end
  2582. -- In order to correctly follow a path, this function requires to be called once
  2583. -- per frame. This property is specified in the state machine table.
  2584. local function do_pathfind_state(self, dtime)
  2585. if not self.path.following or not self.path.way then
  2586. transition_state(self, "")
  2587. return
  2588. end
  2589. -- No very long paths [MustTest]. Note that the engine is now a lot better at
  2590. -- pathfinding, so bad paths aren't often generated anymore. I can leave the
  2591. -- limit fairly high.
  2592. local max_len = (self.pathing_radius or 16) * 4
  2593. if #self.path.way > max_len then
  2594. transition_state(self, "")
  2595. return
  2596. end
  2597. local wp = self.path.way[1]
  2598. if not wp then
  2599. transition_state(self, "")
  2600. return
  2601. end
  2602. -- Debug path display.
  2603. highlight_path(self)
  2604. local s = self.object:get_pos()
  2605. local dist = get_distance(wp, s)
  2606. -- Note: waypoint may be vertical from us (above or below).
  2607. if dist < 0.6 then
  2608. -- Reached waypoint, remove it from queue.
  2609. table.remove(self.path.way, 1)
  2610. self.path.waypoints_gotten = (self.path.waypoints_gotten or 0) + 1
  2611. -- Are we done following the path?
  2612. if #self.path.way == 0 then
  2613. pop_state(self)
  2614. return
  2615. end
  2616. -- Take shortcuts only if we've gotten a few waypoints successfully already.
  2617. -- The requirement that we must first traverse at least 4 waypoints prevents
  2618. -- rapid switching between the "main", "newpath", and "rondev" states.
  2619. -- Overall, taking shortcuts makes mob movement look a bit better, at the
  2620. -- cost that sometimes the mob walks into a trap and has to path out of it.
  2621. -- A 50/50 random number helps to break up circular traps.
  2622. local count = random(4, 8)
  2623. local fw = self.path.way[count]
  2624. if random(1, 2) == 1 and fw and abs(wp.y - fw.y) <= 2 and self.path.waypoints_gotten > 4 then
  2625. local y1 = self.object:get_yaw()
  2626. local y2 = yaw_to_pos(self, fw, s)
  2627. local d = yaw_delta(y1, y2)
  2628. if d > rad(20) then
  2629. -- Move raycast up a bit to improve behavior over rough terrain.
  2630. local a = {x=0, y=1, z=0}
  2631. if raycast_los(self, v_add(s, a), v_add(fw, a)) then
  2632. for i = 1, (count - 1), 1 do
  2633. table.remove(self.path.way, 1)
  2634. end
  2635. self.path.rondev_timeout = 5
  2636. transition_substate(self, "rondev")
  2637. end
  2638. end
  2639. end
  2640. elseif dist > 3 then -- Dist factor is a bit arbitrary right now.
  2641. -- We are some distance to the waypoint. Transition to the "rondev" state,
  2642. -- which tries to walk the mob to the target in a direct line.
  2643. self.path.rondev_timeout = 5
  2644. transition_substate(self, "rondev")
  2645. return
  2646. end
  2647. -- Is mob directly over or under the target?
  2648. -- If so, mob should move more slowly so we don't miss the waypoint.
  2649. local on_target = false
  2650. if abs(wp.x - s.x) < 0.2 and abs(wp.z - s.z) < 0.2 then
  2651. on_target = true
  2652. end
  2653. -- Note: the 'facing_wall_or_pit' function also checks for dangerous nodes.
  2654. -- But some dangerous nodes are non-walkable, which means the pathfinder
  2655. -- would path through them.
  2656. local path_careful = false
  2657. if not self.path.dangerous_paths then
  2658. if waypoint_dangerous(self, wp) then
  2659. -- Usually happens due to paths through deadly liquid.
  2660. transition_substate(self, "blocked")
  2661. return
  2662. elseif is_wall_or_pit(self, wp) then
  2663. -- This can happen if the environment changed (player dug pit or wall?).
  2664. self.path.blocked_count = self.path.blocked_count + 1
  2665. transition_substate(self, "blocked")
  2666. return
  2667. else
  2668. -- Soft "slowdown" check has to be performed last.
  2669. local result, reason = facing_wall_or_pit(self)
  2670. if result and (reason == "pit" or reason == "danger") then
  2671. -- Path goes in the direction of something dangerous, like a cliff.
  2672. -- But we don't care if the path is next to a wall.
  2673. path_careful = true
  2674. end
  2675. end
  2676. end
  2677. -- Query whether path is straight. Note: do this BEFORE rotating mob.
  2678. -- The mob's initial yaw is taken into account.
  2679. local sharp_turn = (not path_is_straight(self, s))
  2680. -- Get the mob facing in the right direction.
  2681. local yaw = yaw_to_pos(self, wp, s)
  2682. set_yaw(self, yaw)
  2683. -- Start moving to next waypoint.
  2684. if on_target then
  2685. -- Slow down so we don't overshoot waypoint.
  2686. set_velocity(self, 0.1)
  2687. set_animation(self, "walk", 5)
  2688. elseif path_careful then
  2689. -- Slow down when near dangerous terrain.
  2690. local half_run = ((self.walk_velocity or 0) + (self.run_velocity or 0)) / 2
  2691. set_velocity(self, half_run)
  2692. set_animation(self, "walk")
  2693. elseif sharp_turn then
  2694. -- Slow down to execute turns.
  2695. set_velocity(self, self.run_velocity or 0)
  2696. set_animation(self, "run")
  2697. else
  2698. set_velocity(self, self.sprint_velocity or 0)
  2699. set_animation(self, "run")
  2700. end
  2701. -- Jump only if next waypoint is higher than us.
  2702. if wp.y > s.y then
  2703. try_jump(self, dtime)
  2704. end
  2705. -- Is mob becoming stuck? (Haven't removed next waypoint in timely manner.)
  2706. -- Note that this can trigger if the mob just moves too slowly, so we should
  2707. -- avoid very-slow-moving behaviors when possible.
  2708. if self.stuck_timer > 3 then
  2709. self.path.blocked_count = self.path.blocked_count + 1
  2710. transition_substate(self, "blocked")
  2711. return
  2712. end
  2713. end
  2714. -- In this state, the mob is some distance from the first waypoint in the path,
  2715. -- and must move toward it in a direct line.
  2716. local function do_pathfind_rondev(self, dtime)
  2717. if not self.path.following or not self.path.way then
  2718. pop_state(self)
  2719. return
  2720. end
  2721. local wp = self.path.way[1]
  2722. if not wp then
  2723. pop_state(self)
  2724. return
  2725. end
  2726. -- If we've exceeded the time budget for this action, we must be blocked.
  2727. self.path.rondev_timeout = (self.path.rondev_timeout or 0) - dtime
  2728. if self.path.rondev_timeout < 0 then
  2729. self.path.blocked_count = self.path.blocked_count + 1
  2730. transition_substate(self, "blocked")
  2731. return
  2732. end
  2733. local s = self.object:get_pos()
  2734. -- Get the mob facing in the right direction.
  2735. local yaw = yaw_to_pos(self, wp, s)
  2736. set_yaw(self, yaw)
  2737. if facing_wall_or_pit(self) then
  2738. set_velocity(self, 0)
  2739. transition_substate(self, "newpath")
  2740. return
  2741. end
  2742. -- Slow down (half-run) to execute shortcuts.
  2743. set_velocity(self, self.run_velocity)
  2744. set_animation(self, "run")
  2745. try_jump(self, dtime)
  2746. if get_distance(wp, s) < 1.0 then
  2747. transition_substate(self, "")
  2748. return
  2749. end
  2750. end
  2751. local function try_unblock_path(self)
  2752. --report(self, "try unblock path")
  2753. local s = get_standing_pos(self)
  2754. local p = get_ahead_pos(self)
  2755. local w1 = self.path.way[1]
  2756. local w2 = self.path.way[2]
  2757. -- First, check if the waypoint is inside a walkable or dangerous node. This
  2758. -- would happen if the player (or another mob) modified the environment
  2759. -- through which the path traveled, by placing a block on it.
  2760. if w1 then
  2761. local nn = minetest.get_node(w1).name
  2762. local ndef = minetest.registered_nodes[nn]
  2763. if ndef.walkable or is_node_dangerous(self, nn, ndef) then
  2764. --report(self, "floating in: " .. nn)
  2765. if try_break_block(self, w1) then
  2766. return "continue"
  2767. elseif try_place_block(self, v_add(w1, {x=0, y=1, z=0})) then
  2768. -- Jump up to avoid getting stuck in placed node.
  2769. if w1.y + 1 >= p.y then
  2770. force_jump_up(self, 1)
  2771. end
  2772. -- Move waypoint 2 nodes up and try to continue the same path.
  2773. w1.y = w1.y + 2
  2774. return "continue"
  2775. else
  2776. return ""
  2777. end
  2778. end
  2779. end
  2780. -- Check if the waypoint floating OVER non-walkable (like air). For example,
  2781. -- player might have dug a pit in the mob's path.
  2782. do
  2783. local p2 = v_add(w1, {x=0, y=-1, z=0})
  2784. local nn = minetest.get_node(p2).name
  2785. local ndef = minetest.registered_nodes[nn]
  2786. if not ndef.walkable or is_node_dangerous(self, nn, ndef) then
  2787. report(self, "floating over")
  2788. if try_place_block(self, p2) then
  2789. -- Waypoint goes over placed block; path not modified.
  2790. return "continue"
  2791. elseif try_place_block(self, w1) then
  2792. return "newpath"
  2793. else
  2794. return ""
  2795. end
  2796. end
  2797. end
  2798. -- Is path obstructed by a mob or player?
  2799. if w1 then
  2800. -- Note: w1 is the obstructed waypoint, w2 is the waypoint beyond.
  2801. local obstructed = false
  2802. local can_move = false
  2803. -- Check both the next waypoint AND the mob's "ahead" pos. They might be
  2804. -- separated by some distance, and thus one might be blocked while the other
  2805. -- is not.
  2806. local objs = get_targets_in_radius(self, w1, 1.5)
  2807. if #objs > 0 then
  2808. obstructed = true
  2809. else
  2810. objs = get_targets_in_radius(self, p, 1.5)
  2811. if #objs > 0 then obstructed = true end
  2812. end
  2813. -- Make sure nothing is obstructing the mob (assuming 2-node high mob).
  2814. if obstructed then
  2815. local p2 = v_add(w1, {x=0, y=1, z=0})
  2816. if try_break_block(self, p2) then
  2817. can_move = true
  2818. end
  2819. end
  2820. if obstructed and can_move then
  2821. -- If obstructed, I can deal with this by simply moving the mob by fiat.
  2822. -- Note: cannot use move_to(), it simply collides.
  2823. local t = vector.copy(w1)
  2824. t.y = (t.y - 0.5) + abs(self.collisionbox[2])
  2825. self.object:set_pos(t) -- Place mob exactly on ground.
  2826. -- Remove waypoint.
  2827. table.remove(self.path.way, 1)
  2828. return "continue"
  2829. end
  2830. end
  2831. -- Path goes over a hump while ceiling prevents jumping.
  2832. -- (This function doesn't check for a ceiling, but we assume there is one,
  2833. -- otherwise the movement code would have just jumped over the hump.)
  2834. if w1 and w1.y == p.y + 1 then
  2835. if w2 and w2.y <= w1.y then
  2836. local result, reason = try_break_block(self, p)
  2837. if result then
  2838. -- Modify path slightly.
  2839. w1.y = w1.y - 1
  2840. return "continue"
  2841. else
  2842. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2843. -- Try something else.
  2844. if try_place_block(self, w1) then
  2845. return "newpath"
  2846. end
  2847. end
  2848. end
  2849. end
  2850. -- Path's next waypoint is 2 nodes or higher from mob's ahead position.
  2851. -- Most mobs can't jump this high (neither can the player, usually).
  2852. if w1 and w1.y > p.y + 1 then
  2853. local p2 = v_add(w1, {x=0, y=-1, z=0})
  2854. local result, reason = try_break_block(self, p2)
  2855. if result then
  2856. -- Modify path slightly.
  2857. w1.y = w1.y - 1
  2858. return "continue"
  2859. else
  2860. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2861. -- Try something else.
  2862. if try_place_block(self, w1) then
  2863. return "newpath"
  2864. end
  2865. end
  2866. end
  2867. -- Path goes straight ahead flat (or down). Mob is probably blocked by
  2868. -- blockage over a 1x1 hole or other space too low to fit its head through.
  2869. if w1 and w1.y <= p.y then
  2870. local p2 = v_add(p, {x=0, y=1, z=0})
  2871. local result, reason = try_break_block(self, p2)
  2872. if result then
  2873. -- Keep following path unmodified.
  2874. return "continue"
  2875. else
  2876. -- Couldn't remove blockage (protected, unbreakable, etc.).
  2877. -- Try something else.
  2878. if try_place_block(self, w1) then
  2879. return "newpath"
  2880. end
  2881. end
  2882. end
  2883. -- Path goes up stairs. In this case, we DON'T want to dig the stair node.
  2884. -- We have to dig the ceiling instead.
  2885. if w1 and w2 and w1.y > p.y and w2.y > w1.y then
  2886. local p2 = get_standing_pos(self)
  2887. p2.y = p2.y + 2
  2888. local result, reason = try_break_block(self, p2)
  2889. if result then
  2890. -- Keep following path.
  2891. return "continue"
  2892. else
  2893. -- Couldn't remove ceiling blockage (protected, unbreakable, etc.).
  2894. -- Try something else.
  2895. if try_place_block(self, w1) then
  2896. return "newpath"
  2897. end
  2898. end
  2899. end
  2900. return ""
  2901. end
  2902. -- This pathfinding state attempts to remove (or place) blocks in order to get
  2903. -- around blockages. It should only be entered if the mob's pathfinding value is
  2904. -- 2 or greater.
  2905. local function do_pathfind_blocked(self, dtime)
  2906. -- Usually, mob should be facing whatever is blocking us. Generally, only
  2907. -- other entities (like mobs) and physical terrain are responsible for this.
  2908. if not self.path.following or not self.path.way then
  2909. transition_state(self, "")
  2910. return
  2911. end
  2912. -- Blocked too many times without successful unblocking? Give up.
  2913. if self.path.blocked_count > 3 then
  2914. transition_state(self, "")
  2915. return
  2916. end
  2917. -- Mob does not support this level of pathfinding?
  2918. if (self.pathfinding or 0) < 2 then
  2919. transition_state(self, "")
  2920. return
  2921. end
  2922. local wp = self.path.way[1]
  2923. if not wp then
  2924. transition_state(self, "")
  2925. return
  2926. end
  2927. -- Halt mob's movement while we try to unblock the path.
  2928. set_velocity(self, 0)
  2929. set_animation(self, "stand")
  2930. -- Get mob facing the next waypoint (and the blockage, presumably).
  2931. local yaw = yaw_to_pos(self, wp, self.object:get_pos())
  2932. set_yaw(self, yaw)
  2933. -- Limit the rate at which blockage is removed.
  2934. self.path.blocked_timer = (self.path.blocked_timer or 0) + dtime
  2935. if self.path.blocked_timer > 1 then
  2936. self.path.blocked_timer = 0
  2937. local result = try_unblock_path(self)
  2938. if result == "continue" then
  2939. -- Continue original path. (Note: path might have been modified slightly.)
  2940. self.path.blocked_count = 0
  2941. transition_substate(self, "")
  2942. return
  2943. elseif result == "newpath" then
  2944. -- The attempt resulted in the environment being changed; retry pathfinder.
  2945. self.path.blocked_count = 0
  2946. transition_substate(self, "newpath")
  2947. return
  2948. else
  2949. -- Couldn't remove blockage.
  2950. pop_state(self)
  2951. return
  2952. end
  2953. end
  2954. end
  2955. local function do_pathfind_exit(self)
  2956. self.path.following = false
  2957. self.path.way = nil
  2958. self.path.dangerous_paths = false
  2959. end
  2960. -- Pillar and tunnel to get to the target.
  2961. local function do_digbuild_state(self, dtime)
  2962. -- Pathfinder does not have a target?
  2963. if not self.digbuild.target then
  2964. transition_state(self, "")
  2965. return
  2966. end
  2967. -- Mob does not support this level of pathfinding?
  2968. if (self.pathfinding or 0) < 3 then
  2969. transition_state(self, "")
  2970. return
  2971. end
  2972. -- Has mob reached its objective?
  2973. if v_distance(self.object:get_pos(), self.digbuild.target) < 1 then
  2974. pop_state(self)
  2975. return
  2976. end
  2977. local s = self.object:get_pos()
  2978. local p = self.digbuild.target
  2979. local yaw = yaw_to_pos(self, p, s)
  2980. set_yaw(self, yaw)
  2981. -- Start moving! The goal is to get as close to the target as possible in the
  2982. -- X,Z plane before we go up or down.
  2983. local face_result, face_reason = facing_wall_or_pit(self)
  2984. -- If the mob is over or under the target, slow down.
  2985. local overunder = false
  2986. if abs(s.x - p.x) < 0.5 and abs(s.z - p.z) < 0.5 then
  2987. velocity = self.walk_velocity or 0
  2988. overunder = true
  2989. elseif abs(s.x - p.x) < 0.2 and abs(s.z - p.z) < 0.2 then
  2990. overunder = true
  2991. velocity = 0.1
  2992. end
  2993. if face_result or overunder then
  2994. set_velocity(self, 0)
  2995. set_animation(self, "stand")
  2996. else
  2997. -- Get mob moving in the right direction.
  2998. local velocity = self.run_velocity or 0
  2999. set_velocity(self, velocity)
  3000. set_animation(self, "run")
  3001. try_jump(self, dtime)
  3002. return
  3003. end
  3004. -- Another function handles the obstacle we (hopefully) just ran into.
  3005. if face_reason == "wall" or face_reason == "pit" or overunder then
  3006. transition_substate(self, "obstacle")
  3007. return
  3008. end
  3009. if self.stand_timer > 1 then
  3010. transition_substate(self, "obstacle")
  3011. return
  3012. end
  3013. end
  3014. -- Dig up until we reach the top of a wall.
  3015. local function do_digbuild_pillar(self, dtime)
  3016. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3017. if keep_mob_centered(self) then
  3018. return
  3019. end
  3020. local s = self.object:get_pos()
  3021. local p = self.digbuild.target
  3022. local v = self.object:get_velocity()
  3023. -- Get mob facing in the right direction.
  3024. local yaw = yaw_to_pos(self, p, s)
  3025. set_yaw(self, yaw)
  3026. set_velocity(self, 0)
  3027. -- Limit upward building to once per second.
  3028. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3029. if self.digbuild.node_timer > 0.5 then
  3030. set_animation(self, "stand")
  3031. end
  3032. if self.digbuild.node_timer < 1 then return end
  3033. self.digbuild.node_timer = 0
  3034. -- Obviosly we can't pillar if the mob is currently falling. We check this
  3035. -- only after checking the dig/build timer, otherwise it would run every frame
  3036. -- and we would immediately exit the pillaring function on every upward jump.
  3037. if v.y < 0 then
  3038. transition_state(self, "")
  3039. return
  3040. end
  3041. -- Ceiling position. Assume mob is 2 blocks high, so it digs above its
  3042. -- head. Position is rounded, so we use a fixed integer.
  3043. local sps = get_standing_pos(self)
  3044. local cps = v_add(sps, {x=0, y=2, z=0})
  3045. -- Cancel pillaring if we're above or near the target's X,Z level.
  3046. if sps.y >= self.digbuild.target.y then
  3047. transition_substate(self, "")
  3048. return
  3049. end
  3050. -- Try to dig ceiling first, then place floor block. There is no point in
  3051. -- placing the floor block unless we can dig the ceiling. Otherwise mob would
  3052. -- just get stuck.
  3053. if try_break_block(self, cps) then
  3054. if try_place_block(self, sps) then
  3055. set_animation(self, "punch")
  3056. force_jump_up(self, 1)
  3057. -- If we reach a plateau, we might be able to path from here.
  3058. local decks = walkable_around(sps)
  3059. if #decks > 1 then -- Always at least 1 due to self.
  3060. -- Try swapping back to the pathfinder.
  3061. -- Note: we assume that if the pathfinder cannot find a path, that it
  3062. -- does NOT move the mob!
  3063. self.path.target = self.digbuild.target
  3064. pop_state(self)
  3065. push_state(self, "pathfind")
  3066. return
  3067. end
  3068. -- If we are above our target, we should switch to bridge/tunnel.
  3069. if sps.y >= self.digbuild.target.y then
  3070. transition_substate(self, "tunnel")
  3071. return
  3072. end
  3073. else
  3074. -- Cannot build, stop trying to get target.
  3075. transition_state(self, "")
  3076. return
  3077. end
  3078. else
  3079. -- Cannot dig, stop trying to get target.
  3080. transition_state(self, "")
  3081. return
  3082. end
  3083. end
  3084. local function do_digbuild_dig(self, dtime)
  3085. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3086. if keep_mob_centered(self) then
  3087. return
  3088. end
  3089. local s = self.object:get_pos()
  3090. local p = self.digbuild.target
  3091. -- Get mob facing in the right direction.
  3092. local yaw = yaw_to_pos(self, p, s)
  3093. set_yaw(self, yaw)
  3094. set_velocity(self, 0)
  3095. -- Limit downward building to once per second.
  3096. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3097. if self.digbuild.node_timer > 0.5 then
  3098. set_animation(self, "stand")
  3099. end
  3100. if self.digbuild.node_timer < 1 then return end
  3101. self.digbuild.node_timer = 0
  3102. -- Ground position.
  3103. local sps = get_standing_pos(self)
  3104. local fps = v_add(sps, {x=0, y=-1, z=0})
  3105. local ups = v_add(sps, {x=0, y=-2, z=0})
  3106. -- Cancel digging if we're below or near the target's X,Z level.
  3107. if sps.y <= self.digbuild.target.y then
  3108. transition_substate(self, "")
  3109. return
  3110. end
  3111. -- Don't dig block below if mob would fall.
  3112. if not pos_walkable(ups) then
  3113. transition_state(self, "")
  3114. return
  3115. end
  3116. if try_break_block(self, fps) then
  3117. set_animation(self, "punch")
  3118. -- If we reach a plateau, we might be able to path from here.
  3119. local decks = walkable_around(v_add(fps, {x=0, y=-1, z=0}))
  3120. if #decks > 1 then -- Always at least 1 due to self.
  3121. -- Try swapping back to the pathfinder.
  3122. -- Note: we assume that if the pathfinder cannot find a path, that it
  3123. -- does NOT move the mob!
  3124. self.path.target = self.digbuild.target
  3125. pop_state(self)
  3126. push_state(self, "pathfind")
  3127. return
  3128. end
  3129. -- If we are below our target, we should switch to bridge/tunnel.
  3130. if sps.y <= self.digbuild.target.y then
  3131. transition_substate(self, "tunnel")
  3132. return
  3133. end
  3134. else
  3135. -- Cannot dig, stop trying to get target.
  3136. transition_state(self, "")
  3137. return
  3138. end
  3139. end
  3140. local function do_digbuild_tunnel(self, dtime)
  3141. -- Do nothing until mob is centered in column. Otherwise might get stuck!
  3142. if keep_mob_centered(self) then
  3143. return
  3144. end
  3145. -- Exit if falling.
  3146. local v = self.object:get_velocity()
  3147. if v.y < 0 then
  3148. transition_state(self, "")
  3149. return
  3150. end
  3151. local s = self.object:get_pos()
  3152. local p = self.digbuild.target
  3153. -- Get mob facing in the right direction.
  3154. local yaw = yaw_to_pos(self, p, s)
  3155. set_yaw(self, yaw)
  3156. set_velocity(self, 0)
  3157. --local face_result, face_reason = facing_wall_or_pit(self)
  3158. -- If we're no longer facing a wall or other obstacle, we can stop
  3159. -- tunneling/bridging operations (for now).
  3160. --if face_reason == "surface" then
  3161. -- transition_substate(self, "")
  3162. -- return
  3163. --end
  3164. -- Face one of the cardinal directions, and if that direction is a surface,
  3165. -- move to it.
  3166. set_yaw(self, square_yaw(yaw))
  3167. local face_result, face_reason = facing_wall_or_pit(self)
  3168. if face_reason == "surface" then
  3169. self.digbuild.move_to = get_ahead_pos(self)
  3170. transition_substate(self, "move")
  3171. return
  3172. end
  3173. -- Limit digging/building to once per second.
  3174. self.digbuild.node_timer = self.digbuild.node_timer + dtime
  3175. if self.digbuild.node_timer > 0.5 then
  3176. set_animation(self, "stand")
  3177. end
  3178. if self.digbuild.node_timer < 1 then return end
  3179. self.digbuild.node_timer = 0
  3180. -- Tunnel/bridge position. Assume mob is 2 blocks high, so it digs blocks for
  3181. -- its head. Position is rounded, so we use a fixed integer.
  3182. local p1 = get_ahead_pos(self)
  3183. local p2 = v_add(p1, {x=0, y=1, z=0})
  3184. local p0 = v_add(p1, {x=0, y=-1, z=0})
  3185. -- Place bridge block if needed.
  3186. if not pos_walkable(p0) then
  3187. try_place_block(self, p0, true)
  3188. end
  3189. -- Try digging the doorway.
  3190. if try_break_block(self, p1) then
  3191. if try_break_block(self, p2) then
  3192. -- Both blocks facing forwards are successfully dug (or didn't exist).
  3193. -- If we reach an opening, we might be able to path from here.
  3194. -- Start with at least 2 due to self + path behind us.
  3195. local amount = 2
  3196. local decks = walkable_around(p0)
  3197. if #decks <= 2 then
  3198. -- In this case there shouldn't be more than 1 if there is no opening.
  3199. decks = walkable_around(p1)
  3200. amount = 1
  3201. end
  3202. if #decks > amount then
  3203. -- Try swapping back to the pathfinder.
  3204. -- Note: we assume that if the pathfinder cannot find a path, that it
  3205. -- does NOT move the mob!
  3206. self.path.target = self.digbuild.target
  3207. pop_state(self)
  3208. push_state(self, "pathfind")
  3209. return
  3210. end
  3211. -- Move to the section we just built/dug.
  3212. self.digbuild.move_to = p1
  3213. self.digbuild.node_timer = 1
  3214. transition_substate(self, "move")
  3215. else
  3216. -- Cannot dig, stop trying to get target.
  3217. transition_state(self, "")
  3218. return
  3219. end
  3220. else
  3221. -- Cannot dig, stop trying to get target.
  3222. transition_state(self, "")
  3223. return
  3224. end
  3225. end
  3226. -- Move the mob to the target location. We assume the distance to this location
  3227. -- is no more than 1.5 nodes, more or less, and that there are NO obstacles.
  3228. -- Once we've reached the target, we transition to the primary state.
  3229. local function do_digbuild_move(self, dtime)
  3230. if not self.digbuild.move_to then
  3231. transition_state(self, "")
  3232. return
  3233. end
  3234. local s = self.object:get_pos()
  3235. local c = self.digbuild.move_to
  3236. -- Abort if stuck.
  3237. if self.stuck_timer > 5 then
  3238. transition_state(self, "")
  3239. return
  3240. end
  3241. -- Walk to target.
  3242. if abs(s.x - c.x) > 0.4 or abs(s.z - c.z) > 0.4 then
  3243. set_yaw(self, yaw_to_pos(self, c, s))
  3244. set_velocity(self, self.walk_velocity or 0)
  3245. try_jump(self, dtime)
  3246. set_animation(self, "walk")
  3247. return
  3248. end
  3249. transition_substate(self, "")
  3250. end
  3251. -- This function expects that the mob is currently facing an obstacle, and NOT
  3252. -- currently moving.
  3253. local function do_digbuild_obstacle(self, dtime)
  3254. if keep_mob_centered(self) then
  3255. return
  3256. end
  3257. -- First, square the mob's yaw so we can accurately get the obstacle type.
  3258. set_velocity(self, 0)
  3259. set_yaw(self, square_yaw(self.object:get_yaw()))
  3260. -- Wait a moment. (Note: timer only increments when mob is standing still!)
  3261. --if self.stand_timer < 1 then
  3262. -- report(self, "waiting ...")
  3263. -- return
  3264. --end
  3265. local face_result, face_reason = facing_wall_or_pit(self)
  3266. local s = self.object:get_pos()
  3267. local p = self.digbuild.target
  3268. -- Is target directly over or under us?
  3269. if abs(p.x - s.x) < 0.3 and abs(p.z - s.z) < 0.3 then
  3270. if s.y < (p.y - 0.9) then
  3271. transition_substate(self, "pillar")
  3272. return
  3273. elseif s.y > (p.y + 0.9) then
  3274. transition_substate(self, "dig")
  3275. return
  3276. else
  3277. -- We have reached the target.
  3278. pop_state(self)
  3279. return
  3280. end
  3281. -- Is target more than 1 block higher, and we are facing a wall or pit?
  3282. elseif p.y >= (s.y + 0.9) then
  3283. if face_reason == "wall" then
  3284. transition_substate(self, "pillar")
  3285. return
  3286. elseif face_reason == "pit" then
  3287. transition_substate(self, "tunnel")
  3288. return
  3289. elseif face_reason == "surface" then
  3290. self.digbuild.move_to = get_ahead_pos(self)
  3291. transition_substate(self, "move")
  3292. return
  3293. else
  3294. transition_state(self, "")
  3295. return
  3296. end
  3297. -- Otherwise, is target more than 1 block lower than us?
  3298. elseif p.y < (s.y - 0.9) then
  3299. if face_reason == "pit" then
  3300. transition_substate(self, "dig")
  3301. return
  3302. elseif face_reason == "wall" then
  3303. transition_substate(self, "tunnel")
  3304. return
  3305. elseif face_reason == "surface" then
  3306. self.digbuild.move_to = get_ahead_pos(self)
  3307. transition_substate(self, "move")
  3308. return
  3309. else
  3310. transition_state(self, "")
  3311. return
  3312. end
  3313. -- Otherwise, we are (nearly) on the same level as the target.
  3314. else
  3315. -- Dig tunnel through rock, or build bridge through air.
  3316. if face_reason == "pit" or face_reason == "wall" then
  3317. transition_substate(self, "tunnel")
  3318. return
  3319. elseif face_reason == "surface" then
  3320. self.digbuild.move_to = get_ahead_pos(self)
  3321. transition_substate(self, "move")
  3322. return
  3323. end
  3324. end
  3325. -- Encountered a situation we don't know how to deal with. Cancel.
  3326. transition_state(self, "")
  3327. end
  3328. local function do_follow_state(self, dtime)
  3329. if not self.following then
  3330. transition_state(self, "")
  3331. return
  3332. end
  3333. local s = self.object:get_pos()
  3334. local p = self.following:get_pos()
  3335. -- Stop following if target doesn't exist anymore.
  3336. if not p then
  3337. transition_state(self, "")
  3338. return
  3339. end
  3340. -- Stop following when (...) (who comes up with these terms? Geez).
  3341. if self.horny then
  3342. transition_state(self, "")
  3343. return
  3344. end
  3345. -- Avoid dangerous nodes.
  3346. if is_node_dangerous(self, self.standing_in) then
  3347. push_state(self, "avoid")
  3348. return
  3349. end
  3350. -- Stop following if no longer holding item the (non-NPC) mob wants. Does not
  3351. -- apply to NPCs.
  3352. if self.type ~= "npc" then
  3353. if not follow_holding(self, self.following) then
  3354. transition_state(self, "")
  3355. return
  3356. end
  3357. end
  3358. -- Follow that thing!
  3359. local yaw = yaw_to_pos(self, p, s)
  3360. set_yaw(self, yaw, 6)
  3361. if v_distance(s, p) > self.reach then
  3362. set_velocity(self, self.walk_velocity or 0)
  3363. set_animation(self, "walk")
  3364. try_jump(self, dtime)
  3365. else
  3366. set_velocity(self, 0)
  3367. set_animation(self, "stand")
  3368. end
  3369. -- If stuck, maybe we can pathfind to target.
  3370. if self.stuck_timer > 5 then
  3371. if (self.pathfinding or 0) >= 1 then
  3372. self.path.target = v_round(p)
  3373. push_state(self, "pathfind")
  3374. return
  3375. else
  3376. transition_state(self, "")
  3377. return
  3378. end
  3379. end
  3380. end
  3381. local function do_follow_exit(self)
  3382. self.following = nil
  3383. end
  3384. -- This table contains all the individual state functions and their transitions.
  3385. local state_machine = {
  3386. -- State with no name.
  3387. [""] = {
  3388. enter = do_stand_enter,
  3389. main = do_stand_state,
  3390. },
  3391. stand = {
  3392. enter = do_stand_enter,
  3393. main = do_stand_state,
  3394. },
  3395. walk = {
  3396. enter = do_walk_enter,
  3397. main = do_walk_state,
  3398. },
  3399. avoid = {
  3400. enter = do_avoid_enter,
  3401. main = do_avoid_state,
  3402. },
  3403. runaway = {
  3404. enter = do_runaway_enter,
  3405. main = do_runaway_state,
  3406. continuous = true,
  3407. },
  3408. attack = {
  3409. enter = do_attack_enter,
  3410. exit = do_attack_exit,
  3411. main = do_attack_state,
  3412. chase = do_chase_attack,
  3413. shoot = do_shoot_attack,
  3414. caught = do_caught_attack,
  3415. blocked = do_blocked_attack,
  3416. continuous = true,
  3417. },
  3418. pathfind = {
  3419. enter = do_pathfind_enter,
  3420. main = do_pathfind_state,
  3421. blocked = do_pathfind_blocked,
  3422. newpath = do_pathfind_newpath,
  3423. rondev = do_pathfind_rondev,
  3424. exit = do_pathfind_exit,
  3425. continuous = true,
  3426. },
  3427. digbuild = {
  3428. main = do_digbuild_state,
  3429. pillar = do_digbuild_pillar,
  3430. dig = do_digbuild_dig,
  3431. tunnel = do_digbuild_tunnel,
  3432. move = do_digbuild_move,
  3433. obstacle = do_digbuild_obstacle,
  3434. continuous = true,
  3435. },
  3436. follow = {
  3437. main = do_follow_state,
  3438. exit = do_follow_exit,
  3439. },
  3440. }
  3441. -- Export.
  3442. mobs.state_machine = state_machine
  3443. -- Execute current state (stand, walk, run, attacks). This function is rate
  3444. -- limited to reduce server load; thus 'dtime' may be large, but should usually
  3445. -- be within 1 second. [MustTest]
  3446. local function do_states(self, dtime)
  3447. -- Stupid spurious bugs [MustTest]. Implies our object no longer exists.
  3448. local yaw = self.object:get_yaw()
  3449. if not yaw then return end
  3450. -- Deal with invalid states. Note: unknown state types (non-empty string) are
  3451. -- valid and we don't do anything with them; they can be used by some mobs.
  3452. if not self.state or self.state == "" then
  3453. transition_state(self, "stand")
  3454. end
  3455. --report(self, "current state: " .. self.state .. " (" .. self.substate .. ")", 2)
  3456. -- Execute current state's main function.
  3457. local sm = mobs.state_machine
  3458. local state = sm[self.state]
  3459. if state[self.substate] then
  3460. state[self.substate](self, dtime)
  3461. elseif state.main then
  3462. state.main(self, dtime)
  3463. end
  3464. end
  3465. -- Export.
  3466. mobs.do_states = function(...)
  3467. do_states(...)
  3468. end
  3469. -- falling and fall damage
  3470. local function falling(self, pos)
  3471. if self.fly then
  3472. return
  3473. end
  3474. -- floating in water (or falling)
  3475. local v = self.object:get_velocity()
  3476. if v.y > 0 then
  3477. -- apply gravity when moving up
  3478. self.object:set_acceleration({
  3479. x = 0,
  3480. y = -10,
  3481. z = 0
  3482. })
  3483. elseif v.y <= 0 and v.y > self.fall_speed then
  3484. -- fall downwards at set speed
  3485. self.object:set_acceleration({
  3486. x = 0,
  3487. y = self.fall_speed,
  3488. z = 0
  3489. })
  3490. else
  3491. -- stop accelerating once max fall speed hit
  3492. self.object:set_acceleration({x = 0, y = 0, z = 0})
  3493. end
  3494. -- If in water then float up. Nil check.
  3495. local ndef = self.standing_in and minetest.reg_ns_nodes[self.standing_in]
  3496. if ndef and ndef.groups.water then
  3497. if self.floats == 1 then
  3498. self.object:set_acceleration({
  3499. x = 0,
  3500. y = -self.fall_speed / (max(1, v.y) ^ 8), -- 8 was 2
  3501. z = 0
  3502. })
  3503. end
  3504. else
  3505. -- fall damage onto solid ground
  3506. if self.fall_damage == 1
  3507. and self.object:get_velocity().y == 0 then
  3508. local d = (self.old_y or 0) - self.object:get_pos().y
  3509. if d > 5 then
  3510. self.health = self.health - floor(d - 5)
  3511. effect(pos, 5, "tnt_smoke.png", 1, 2, 2, nil)
  3512. if check_for_death(self, "fall", {type = "fall"}) then
  3513. return
  3514. end
  3515. end
  3516. self.old_y = self.object:get_pos().y
  3517. end
  3518. end
  3519. end
  3520. -- is Took Ranks mod active?
  3521. local tr = minetest.get_modpath("toolranks")
  3522. -- Deal damage and effects when mob punched.
  3523. local function mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3524. -- Mob health check.
  3525. if self.health <= 0 then return end
  3526. -- Sanity check.
  3527. if not tool_capabilities then return end
  3528. -- Custom punch function.
  3529. if self.do_punch then
  3530. -- When false skip going any further.
  3531. if self.do_punch(self, hitter, tflp, tool_capabilities, dir) == false then
  3532. return
  3533. end
  3534. end
  3535. -- Record name of last attacker.
  3536. self.last_attacked_by = (hitter and hitter:is_player() and hitter:get_player_name()) or ""
  3537. if hitter then
  3538. if hitter:is_player() then
  3539. cloaking.disable_if_enabled(hitter:get_player_name(), true)
  3540. end
  3541. end
  3542. -- Is mob protected?
  3543. if self.protected and hitter:is_player()
  3544. and minetest.test_protection(v_round(self.object:get_pos()), hitter:get_player_name()) then
  3545. minetest.chat_send_player(hitter:get_player_name(), "# Server: Mob has been protected!")
  3546. return
  3547. end
  3548. -- weapon wear
  3549. local weapon = hitter:get_wielded_item()
  3550. --minetest.log("weapon: <" .. weapon:get_name() .. ">")
  3551. local punch_interval = 1.4
  3552. -- calculate mob damage
  3553. local damage = 0
  3554. local armor = self.object:get_armor_groups() or {}
  3555. local tmp
  3556. -- quick error check incase it ends up 0 (serialize.h check test)
  3557. if tflp <= 0 then
  3558. -- This used to be 0.2
  3559. -- Pretty sure that doesn't make sense.
  3560. tflp = 0
  3561. end
  3562. do
  3563. for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do
  3564. tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)
  3565. if tmp < 0 then
  3566. tmp = 0.0
  3567. elseif tmp > 1 then
  3568. tmp = 1.0
  3569. end
  3570. damage = damage + (tool_capabilities.damage_groups[group] or 0)
  3571. * tmp * ((armor[group] or 0) / 100.0)
  3572. end
  3573. end
  3574. -- check for tool immunity or special damage
  3575. for n = 1, #self.immune_to do
  3576. if self.immune_to[n][1] == weapon:get_name() then
  3577. damage = self.immune_to[n][2] or 0
  3578. break
  3579. -- if "all" then no tool does damage unless it's specified in list
  3580. elseif self.immune_to[n][1] == "all" then
  3581. damage = self.immune_to[n][2] or 0
  3582. end
  3583. end
  3584. -- healing
  3585. if damage <= -1 then
  3586. self.health = self.health - floor(damage)
  3587. return
  3588. end
  3589. -- add weapon wear
  3590. if tool_capabilities then
  3591. punch_interval = tool_capabilities.full_punch_interval or 1.4
  3592. end
  3593. if weapon:get_definition()
  3594. and weapon:get_definition().tool_capabilities then
  3595. -- toolrank support
  3596. local wear = floor((punch_interval / 75) * 9000)
  3597. if tr then
  3598. if weapon:get_definition()
  3599. and weapon:get_definition().original_description then
  3600. weapon:add_wear(toolranks.new_afteruse(weapon, hitter, nil, {wear = wear}))
  3601. end
  3602. else
  3603. weapon:add_wear(wear)
  3604. end
  3605. hitter:set_wielded_item(weapon)
  3606. end
  3607. -- only play hit sound and show blood effects if damage is 1 or over
  3608. if damage >= 1 then
  3609. local weapon_def_sounds = weapon:get_definition().sounds
  3610. -- weapon sounds
  3611. if weapon_def_sounds ~= nil then
  3612. -- Names beginning with a '_' should never be clobbered by engine.
  3613. if weapon_def_sounds._punch_mob then
  3614. minetest.sound_play(weapon_def_sounds._punch_mob, {
  3615. object = self.object, --hitter,
  3616. max_hear_distance = 20
  3617. }, true)
  3618. else
  3619. minetest.sound_play("default_punch", {
  3620. object = self.object, --hitter,
  3621. max_hear_distance = 20
  3622. }, true)
  3623. end
  3624. else
  3625. minetest.sound_play("default_punch", {
  3626. object = self.object, --hitter,
  3627. max_hear_distance = 20
  3628. }, true)
  3629. end
  3630. -- blood_particles
  3631. if self.blood_amount > 0 and not disable_blood then
  3632. local pos = self.object:get_pos()
  3633. pos.y = pos.y + (-self.collisionbox[2] + self.collisionbox[5]) * .5
  3634. -- do we have a single blood texture or multiple?
  3635. if type(self.blood_texture) == "table" then
  3636. local blood = self.blood_texture[random(1, #self.blood_texture)]
  3637. effect(pos, self.blood_amount, blood, nil, nil, 1, nil)
  3638. else
  3639. effect(pos, self.blood_amount, self.blood_texture, nil, nil, 1, nil)
  3640. end
  3641. end
  3642. -- do damage
  3643. self.health = self.health - floor(damage)
  3644. -- exit here if dead, special item check
  3645. if weapon:get_name() == "mobs:pick_lava" then
  3646. if check_for_death(self, "lava", {
  3647. type = "punch",
  3648. puncher = hitter,
  3649. tool_capabilities = tool_capabilities,
  3650. wielded = weapon,
  3651. }) then
  3652. return
  3653. end
  3654. else
  3655. if check_for_death(self, "hit", {
  3656. type = "punch",
  3657. puncher = hitter,
  3658. tool_capabilities = tool_capabilities,
  3659. wielded = weapon,
  3660. }) then
  3661. return
  3662. end
  3663. end
  3664. --[[ add healthy afterglow when hit (can cause hit lag with larger textures)
  3665. minetest.after(0.1, function()
  3666. if not self.object:get_luaentity() then return end
  3667. self.object:settexturemod("^[colorize:#c9900070")
  3668. core.after(0.3, function()
  3669. self.object:settexturemod("")
  3670. end)
  3671. end) ]]
  3672. -- knock back effect (only on full punch)
  3673. if self.knock_back and tflp >= punch_interval then
  3674. local v = self.object:get_velocity()
  3675. local r = 1.4 - min(punch_interval, 1.4)
  3676. local kb = r * 5
  3677. local up = 2
  3678. -- if already in air then dont go up anymore when hit
  3679. if v.y > 0
  3680. or self.fly then
  3681. up = 0
  3682. end
  3683. -- direction error check
  3684. dir = dir or {x = 0, y = 0, z = 0}
  3685. -- Knockback multiplier.
  3686. kb = kb * default_knockback
  3687. self.object:set_velocity({
  3688. x = dir.x * kb,
  3689. y = up,
  3690. z = dir.z * kb
  3691. })
  3692. self.pause_timer = 0.25
  3693. end
  3694. end -- END if damage
  3695. -- If skittish then run away.
  3696. if self.runaway == true then
  3697. local lp = hitter:get_pos()
  3698. local s = self.object:get_pos()
  3699. local yaw = yaw_to_pos(self, lp, s)
  3700. yaw = yaw + pi -- go in reverse
  3701. yaw = set_yaw(self, yaw, 6)
  3702. transition_state(self, "runaway")
  3703. return
  3704. end
  3705. -- Ignore punches from self.
  3706. if self.object == hitter then return end
  3707. -- Ignore punches if mob is passive.
  3708. if self.passive then return end
  3709. if self.child then return end
  3710. -- Ignore punches from owner.
  3711. local name = (hitter:is_player() and hitter:get_player_name()) or ""
  3712. if name ~= "" and name == self.owner then
  3713. return
  3714. end
  3715. -- Note: mob can defend itself if punched by invisible players, so no
  3716. -- invisibility check here.
  3717. -- Attack whoever punched mob (if not already attacking that player/mob).
  3718. if self.state ~= "attack" or self.attack ~= hitter then
  3719. transition_state(self, "")
  3720. do_attack(self, hitter)
  3721. end
  3722. if not self.group_attack then return end
  3723. -- Alert others to the attack.
  3724. local objs = minetest.get_objects_inside_radius(hitter:get_pos(), self.view_range)
  3725. for n = 1, #objs, 1 do
  3726. local obj = objs[n]:get_luaentity()
  3727. if obj and obj._cmi_is_mob then
  3728. -- Alert members of same mob if have 'group_attack'.
  3729. if obj.state ~= "attack" and obj.name == self.name then
  3730. -- But owned mobs will not attack their owners.
  3731. if not (obj.owner == name) then
  3732. do_attack(obj, hitter)
  3733. end
  3734. end
  3735. -- have owned mobs attack player threat
  3736. if name ~= "" and obj.owner == name and obj.owner_loyal then
  3737. do_attack(obj, self.object)
  3738. end
  3739. end
  3740. end
  3741. end
  3742. -- export!
  3743. function mobs.mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3744. return mob_punch(self, hitter, tflp, tool_capabilities, dir)
  3745. end
  3746. -- get entity staticdata
  3747. local function mob_staticdata(self)
  3748. -- remove mob when out of range unless tamed
  3749. if remove_far
  3750. and self.remove_ok
  3751. and self.type ~= "npc"
  3752. and self.state ~= "attack"
  3753. and not self.tamed
  3754. and self.lifetimer < 20000 then
  3755. --print ("REMOVED " .. self.name)
  3756. -- Mark for removal as last action on mob_step().
  3757. self.mkrm = true
  3758. return ""-- nil
  3759. end
  3760. self.remove_ok = true
  3761. self.attack = nil
  3762. self.following = nil
  3763. self.state = "stand"
  3764. self.substate = ""
  3765. -- used to rotate older mobs
  3766. if self.drawtype and self.drawtype == "side" then
  3767. self.rotate = rad(90)
  3768. end
  3769. local tmp = {}
  3770. for _,stat in pairs(self) do
  3771. local t = type(stat)
  3772. if t ~= "function" and t ~= "nil" and t ~= "userdata" and _ ~= "_cmi_components" then
  3773. tmp[_] = self[_]
  3774. end
  3775. end
  3776. --print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
  3777. return minetest.serialize(tmp)
  3778. end
  3779. -- export!
  3780. function mobs.mob_staticdata(self)
  3781. return mob_staticdata(self)
  3782. end
  3783. -- Activate mob and reload settings.
  3784. local function mob_activate(self, staticdata, def, dtime)
  3785. --minetest.chat_send_all('activating mob')
  3786. -- Remove mob if activated during daytime and has 'daytime_despawn'.
  3787. if def.daytime_despawn then
  3788. local tod = (minetest.get_timeofday() or 0) * 24000
  3789. if tod > 4500 and tod < 19500 then
  3790. -- Daylight, but mob despawns at daytime.
  3791. -- Mark for removal as last action on mob_step().
  3792. self.mkrm = true
  3793. return
  3794. end
  3795. end
  3796. -- Remove mob if outside realm dimensions.
  3797. if not rc.is_valid_realm_pos(self.object:get_pos()) then
  3798. -- Mark for removal as last action on mob_step().
  3799. self.mkrm = true
  3800. return
  3801. end
  3802. -- load entity variables
  3803. local tmp = minetest.deserialize(staticdata)
  3804. if tmp then
  3805. for _, stat in pairs(tmp) do
  3806. self[_] = stat
  3807. end
  3808. end
  3809. -- Do select random texture, set model and size.
  3810. if not self.base_texture then
  3811. -- Do compatiblity with old simple mobs textures.
  3812. if def.textures and type(def.textures[1]) == "string" then
  3813. def.textures = {def.textures}
  3814. end
  3815. self.base_texture = def.textures and def.textures[random(1, #def.textures)]
  3816. self.base_mesh = def.mesh
  3817. self.base_size = self.visual_size
  3818. self.base_colbox = self.collisionbox
  3819. self.base_selbox = self.selectionbox
  3820. end
  3821. -- for current mobs that dont have this set
  3822. if not self.base_selbox then
  3823. self.base_selbox = self.selectionbox or self.base_colbox
  3824. end
  3825. -- set texture, model and size
  3826. local textures = self.base_texture
  3827. local mesh = self.base_mesh
  3828. local vis_size = self.base_size
  3829. local colbox = self.base_colbox
  3830. local selbox = self.base_selbox
  3831. -- specific texture if gotten
  3832. if self.gotten == true and def.gotten_texture then
  3833. textures = def.gotten_texture
  3834. end
  3835. -- specific mesh if gotten
  3836. if self.gotten == true and def.gotten_mesh then
  3837. mesh = def.gotten_mesh
  3838. end
  3839. -- set child objects to half size
  3840. if self.child == true then
  3841. vis_size = {
  3842. x = self.base_size.x * .5,
  3843. y = self.base_size.y * .5,
  3844. }
  3845. if def.child_texture then
  3846. textures = def.child_texture[1]
  3847. end
  3848. colbox = {
  3849. self.base_colbox[1] * .5,
  3850. self.base_colbox[2] * .5,
  3851. self.base_colbox[3] * .5,
  3852. self.base_colbox[4] * .5,
  3853. self.base_colbox[5] * .5,
  3854. self.base_colbox[6] * .5
  3855. }
  3856. selbox = {
  3857. self.base_selbox[1] * .5,
  3858. self.base_selbox[2] * .5,
  3859. self.base_selbox[3] * .5,
  3860. self.base_selbox[4] * .5,
  3861. self.base_selbox[5] * .5,
  3862. self.base_selbox[6] * .5
  3863. }
  3864. end
  3865. if self.health == 0 then
  3866. -- Choose full health from min/max HP.
  3867. -- Then, set max HP to chosen value.
  3868. self.health = random (self.hp_min, self.hp_max)
  3869. self.hp_max = self.health
  3870. end
  3871. -- Pathfinding init.
  3872. self.path = {}
  3873. self.path.way = {} -- path to follow, table of positions
  3874. self.path.lastpos = {x = 0, y = 0, z = 0}
  3875. self.path.following = false -- currently following path?
  3876. self.path.pos_rec_timer = 0
  3877. self.path.find_path_timer = 0
  3878. self.path.putnode_timer = 0
  3879. self.path.los_counter = 0
  3880. self.path.los_check = 0
  3881. self.path.target = nil
  3882. -- Avoidance "avoid" state init.
  3883. self.avoid = {}
  3884. self.avoid.target = nil
  3885. self.avoid.timer = 0
  3886. -- Dig/build state init.
  3887. self.digbuild = {}
  3888. self.digbuild.target = nil
  3889. self.digbuild.node_timer = 0
  3890. -- Adjust the chance to use pathfinding on a per-entity basis.
  3891. if self.pathfinding and self.pathfinding ~= 0 then
  3892. -- If pathfinding is enabled, by default chance is 100%.
  3893. local chance = self.pathfinding_chance or 100
  3894. local res = random(1, 100)
  3895. if res > chance then
  3896. self.pathfinding = 0
  3897. end
  3898. end
  3899. -- mob defaults
  3900. -- Hmmm ... setting 'immortal' prevents Minetest's default damage calculation.
  3901. self.object:set_armor_groups(utility.builtin_armor_groups({immortal = 1, fleshy = self.armor}))
  3902. self.old_y = self.object:get_pos().y
  3903. self.old_health = self.health
  3904. self.sounds.distance = self.sounds.distance or 10
  3905. self.textures = textures
  3906. self.mesh = mesh
  3907. self.collisionbox = colbox
  3908. self.selectionbox = selbox
  3909. self.visual_size = vis_size
  3910. self.standing_in = "air"
  3911. self.standing_on = "air"
  3912. -- check existing nametag
  3913. if not self.nametag then
  3914. self.nametag = def.nametag
  3915. end
  3916. -- set anything changed above
  3917. self.object:set_properties(self)
  3918. set_yaw(self, (random(0, 360) - 180) / 180 * pi, 6)
  3919. update_tag(self)
  3920. set_animation(self, "stand")
  3921. -- run on_spawn function if found
  3922. if self.on_spawn and not self.on_spawn_run then
  3923. if self.on_spawn(self) then
  3924. self.on_spawn_run = true -- if true, set flag to run once only
  3925. end
  3926. end
  3927. -- run after_activate
  3928. if def.after_activate then
  3929. def.after_activate(self, staticdata, def, dtime)
  3930. end
  3931. end
  3932. -- export!
  3933. function mobs.mob_activate(self, staticdata, def, dtime)
  3934. return mob_activate(self, staticdata, def, dtime)
  3935. end
  3936. local function smooth_rotate(self)
  3937. -- smooth rotation by ThomasMonroe314
  3938. if self.delay and self.delay > 0 then
  3939. local yaw = self.object:get_yaw()
  3940. if self.delay == 1 then
  3941. yaw = self.target_yaw
  3942. else
  3943. local dif = abs(yaw - self.target_yaw)
  3944. if yaw > self.target_yaw then
  3945. if dif > pi then
  3946. dif = 2 * pi - dif -- need to add
  3947. yaw = yaw + dif / self.delay
  3948. else
  3949. yaw = yaw - dif / self.delay -- need to subtract
  3950. end
  3951. elseif yaw < self.target_yaw then
  3952. if dif > pi then
  3953. dif = 2 * pi - dif
  3954. yaw = yaw - dif / self.delay -- need to subtract
  3955. else
  3956. yaw = yaw + dif / self.delay -- need to add
  3957. end
  3958. end
  3959. if yaw > (pi * 2) then yaw = yaw - (pi * 2) end
  3960. if yaw < 0 then yaw = yaw + (pi * 2) end
  3961. end
  3962. self.delay = self.delay - 1
  3963. self.object:set_yaw(yaw)
  3964. end
  3965. -- end rotation
  3966. end
  3967. local function stuck_timer(self, dtime, pos)
  3968. -- Set up 'is_stuck' state flag/timer. This is a timer which clocks how long
  3969. -- the mob has not moved for. It is clamped whenever it exceeds 100 seconds,
  3970. -- and reset when the mob's position changes.
  3971. if (self.wanted_velocity or 0) > 0 then
  3972. self.stuck_timer = (self.stuck_timer or 0) + dtime
  3973. if self.stuck_timer > 100 then self.stuck_timer = 100 end
  3974. if v_distance(self.last_pos or pos, pos) > 0.001 then
  3975. self.stuck_timer = 0
  3976. end
  3977. self.last_pos = pos
  3978. self.stand_timer = 0
  3979. else
  3980. -- If the wanted velocity is zero, the stuck-timer does not run.
  3981. -- We are obviously not stuck in such a case!
  3982. self.last_pos = pos
  3983. self.stuck_timer = 0
  3984. self.stand_timer = (self.stand_timer or 0) + dtime
  3985. if self.stand_timer > 100 then self.stand_timer = 100 end
  3986. end
  3987. end
  3988. local function do_punch_timer(self, dtime)
  3989. self.punch_timer = (self.punch_timer or 0) - dtime
  3990. if self.punch_timer < 0 then
  3991. self.punch_timer = 0
  3992. end
  3993. end
  3994. -- Here is the main mob function.
  3995. local function mob_step(self, dtime)
  3996. -- The final (actually first) action of mob_step().
  3997. -- If the mob was marked for removal, we call self.object:remove() here.
  3998. -- This: self.object:remove(), should not be called anywhere else!
  3999. if self.mkrm then self.object:remove(); return end
  4000. -- Stupid spurious errors [MustTest]. Implies our object does not exist.
  4001. local pos = self.object:get_pos()
  4002. if not pos then return end
  4003. -- Manage stuck-timer.
  4004. stuck_timer(self, dtime, pos)
  4005. -- When lifetimer expires, remove mob.
  4006. do_lifetimer(self, pos)
  4007. -- Get what nodes the mob is standing in/on.
  4008. update_foot_nodes(self, pos, dtime)
  4009. -- Check if falling, flying, floating.
  4010. falling(self, pos)
  4011. -- Do smooth rotation.
  4012. smooth_rotate(self)
  4013. -- Manage punch timer.
  4014. do_punch_timer(self, dtime)
  4015. -- Knockback timer. If set, the mob will do nothing until it expires!
  4016. -- Typically this would be set for something like a knockback effect.
  4017. if self.pause_timer > 0 then
  4018. self.pause_timer = self.pause_timer - dtime
  4019. return
  4020. end
  4021. -- Run custom function (defined in mob's script file).
  4022. if self.do_custom then
  4023. -- when false skip going any further
  4024. if self.do_custom(self, dtime) == false then
  4025. return
  4026. end
  4027. end
  4028. -- Environmental damage timer (every 1 second).
  4029. self.env_damage_timer = self.env_damage_timer + dtime
  4030. if self.env_damage_timer >= 1 then
  4031. self.env_damage_timer = 0
  4032. -- Check for environmental damage (water, fire, lava, etc.).
  4033. do_env_damage(self)
  4034. -- Node replace check (cow eats grass, etc.).
  4035. replace(self, pos)
  4036. -- Debug path display.
  4037. highlight_path(self)
  4038. end
  4039. -- Mob plays random sound at times.
  4040. self.sound_timer = (self.sound_timer or 0) + dtime
  4041. if self.sound_timer >= 1 then
  4042. if random(1, 100) == 1 then
  4043. mob_sound(self, self.sounds.random)
  4044. end
  4045. self.sound_timer = 0
  4046. end
  4047. -- This code forces state logic to only run once per second, unless the
  4048. -- current state is flagged to execute continuously. This reduces load on the
  4049. -- server.
  4050. local sm = state_machine
  4051. if not sm[self.state].continuous then
  4052. self.logic_timer = (self.logic_timer or 0) + dtime
  4053. if self.logic_timer < 1 then return end
  4054. self.logic_timer = 0
  4055. -- Since we return early if time is less than 1 second, once timer fires,
  4056. -- we need to pass a 'dtime' of 1 to the logic that follows.
  4057. dtime = 1
  4058. end
  4059. -- Limit the general scanning functions to once per second.
  4060. self.scan_timer = (self.scan_timer or 0) + dtime
  4061. if self.scan_timer >= 1 then
  4062. self.scan_timer = 0
  4063. -- For belligerent mobs, scan for victims to attack.
  4064. general_attack(self)
  4065. -- For skittish mobs, scan for things to run away from.
  4066. runaway_from(self)
  4067. -- Mob reproduction.
  4068. attempt_breed(self)
  4069. -- Periodically refocus attacking mobs.
  4070. refocus_attack(self)
  4071. -- Scan for things to follow around.
  4072. follow_something(self)
  4073. end
  4074. do_states(self, dtime)
  4075. end
  4076. -- export!
  4077. function mobs.mob_step(self, dtime)
  4078. return mob_step(self, dtime)
  4079. end
  4080. -- Default function when mobs are blown up with TNT.
  4081. local function do_tnt(obj, damage)
  4082. obj.object:punch(obj.object, 1.0, {
  4083. full_punch_interval = 1.0,
  4084. damage_groups = {boom = damage},
  4085. }, nil)
  4086. return false, true, {}
  4087. end
  4088. -- export!
  4089. function mobs.do_tnt(obj, damage)
  4090. return do_tnt(obj, damage)
  4091. end
  4092. local function first_or_second(arg1, arg2)
  4093. if type(arg1) ~= "nil" then
  4094. return arg1
  4095. else
  4096. return arg2
  4097. end
  4098. end
  4099. -- register mob entity function
  4100. if not mobs.registered then
  4101. mobs.spawning_mobs = {}
  4102. -- Register mob function.
  4103. mobs.register_mob = function(name, def)
  4104. mobs.spawning_mobs[name] = true
  4105. minetest.register_entity(name, {
  4106. -- Warning: this parameter is set by the engine anway!
  4107. name = name,
  4108. _name = name,
  4109. mob = true,
  4110. type = def.type,
  4111. armor_level = def.armor_level or 0,
  4112. description = def.description,
  4113. stepheight = def.stepheight or 1.1,
  4114. attack_type = def.attack_type,
  4115. fly = def.fly,
  4116. fly_in = def.fly_in or "air",
  4117. owner = def.owner or "",
  4118. order = def.order or "",
  4119. on_die = def.on_die,
  4120. do_custom = def.do_custom,
  4121. -- The number of nodes a mob can jump over. Actual jump velocity is
  4122. -- calculated from this. Supported values are 1, 2, 3.
  4123. jump_height = def.jump_height or 1,
  4124. drawtype = def.drawtype, -- DEPRECATED, use rotate instead
  4125. rotate = rad(def.rotate or 0), -- 0=front, 90=side, 180=back, 270=side2
  4126. lifetimer = def.lifetimer or 180, -- 3 minutes
  4127. hp_min = (def.hp_min or (5*500)) * difficulty,
  4128. hp_max = (def.hp_max or (10*500)) * difficulty,
  4129. physical = true,
  4130. collisionbox = def.collisionbox or {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
  4131. selectionbox = def.selectionbox or def.collisionbox,
  4132. visual = def.visual,
  4133. visual_size = def.visual_size or {x = 1, y = 1},
  4134. mesh = def.mesh,
  4135. makes_footstep_sound = def.makes_footstep_sound or false,
  4136. view_range = def.view_range or 5,
  4137. walk_velocity = def.walk_velocity or 1,
  4138. run_velocity = def.run_velocity or 2,
  4139. sprint_velocity = def.sprint_velocity or def.run_velocity or 2,
  4140. -- Mob may do an exact amount of damage.
  4141. -- But if min/max damage values are set (non-nil, non-0), those are used
  4142. -- instead.
  4143. damage = (def.damage or 0) * difficulty,
  4144. damage_min = (def.damage_min or 0) * difficulty,
  4145. damage_max = (def.damage_max or 0) * difficulty,
  4146. damage_group = def.damage_group,
  4147. daytime_despawn = def.daytime_despawn,
  4148. on_despawn = def.on_despawn,
  4149. light_damage = def.light_damage or 0,
  4150. water_damage = def.water_damage or 0,
  4151. lava_damage = def.lava_damage or 0,
  4152. fire_damage = def.fire_damage or 0,
  4153. suffocation = def.suffocation or 2,
  4154. lava_annihilates = first_or_second(def.lava_annihilates, true),
  4155. makes_bones_in_lava = first_or_second(def.makes_bones_in_lava, true),
  4156. fall_damage = def.fall_damage or (1*500),
  4157. fall_speed = def.fall_speed or -10, -- must be lower than -2 (default: -10)
  4158. drops = def.drops or {},
  4159. armor = def.armor or 100,
  4160. on_rightclick = def.on_rightclick,
  4161. arrow = def.arrow,
  4162. shoot_interval = def.shoot_interval,
  4163. sounds = def.sounds or {},
  4164. animation = def.animation,
  4165. follow = def.follow,
  4166. jump = def.jump ~= false,
  4167. walk_chance = def.walk_chance or 50,
  4168. --fov = def.fov or 120,
  4169. passive = def.passive or false,
  4170. knock_back = def.knock_back ~= false,
  4171. blood_amount = def.blood_amount or 5,
  4172. blood_texture = def.blood_texture or "mobs_blood.png",
  4173. shoot_offset = def.shoot_offset or 0,
  4174. floats = def.floats or 1, -- floats in water by default
  4175. replace_rate = def.replace_rate,
  4176. replace_what = def.replace_what,
  4177. replace_with = def.replace_with,
  4178. replace_offset = def.replace_offset or 0,
  4179. on_replace = def.on_replace,
  4180. -- Feature added by MustTest.
  4181. replace_range = def.replace_range or 1,
  4182. despawns_in_dark_caves = def.despawns_in_dark_caves or false,
  4183. timer = 0,
  4184. env_damage_timer = 0, -- only used when state = "attack"
  4185. tamed = false,
  4186. pause_timer = 0,
  4187. horny = false,
  4188. hornytimer = 0,
  4189. child = false,
  4190. gotten = false,
  4191. health = 0,
  4192. reach = def.reach or 3,
  4193. punch_reach = def.punch_reach or def.reach or 3,
  4194. htimer = 0,
  4195. texture_list = def.textures,
  4196. child_texture = def.child_texture,
  4197. docile_by_day = def.docile_by_day or false,
  4198. time_of_day = 0.5,
  4199. fear_height = def.fear_height or 0,
  4200. runaway = def.runaway,
  4201. runaway_timer = 0,
  4202. pathfinding = def.pathfinding or 0,
  4203. pathfinding_chance = def.pathfinding_chance,
  4204. place_node = def.place_node,
  4205. immune_to = def.immune_to or {},
  4206. explosion_radius = def.explosion_radius,
  4207. explosion_damage_radius = def.explosion_damage_radius,
  4208. explosion_timer = def.explosion_timer or 3,
  4209. allow_fuse_reset = def.allow_fuse_reset ~= false,
  4210. stop_to_explode = def.stop_to_explode ~= false,
  4211. custom_attack = def.custom_attack,
  4212. double_melee_attack = def.double_melee_attack,
  4213. dogshoot_switch = def.dogshoot_switch,
  4214. dogshoot_count = 0,
  4215. dogshoot_count_max = def.dogshoot_count_max or 5,
  4216. dogshoot_count2_max = def.dogshoot_count2_max or (def.dogshoot_count_max or 5),
  4217. group_attack = def.group_attack or false,
  4218. attack_monsters = def.attack_monsters or false,
  4219. attack_animals = def.attack_animals or false,
  4220. attack_players = def.attack_players ~= false,
  4221. attack_npcs = def.attack_npcs ~= false,
  4222. specific_attack = def.specific_attack,
  4223. specific_allies = def.specific_allies,
  4224. runaway_from = def.runaway_from,
  4225. owner_loyal = def.owner_loyal,
  4226. facing_fence = false,
  4227. ignore_invisibility = def.ignore_invisibility,
  4228. pathing_radius = def.pathing_radius,
  4229. max_node_dig_level = def.max_node_dig_level,
  4230. --hunt_players = def.hunt_players,
  4231. hunt_chance = def.hunt_chance or 0,
  4232. -- The meaning of 'attack_chance' is inverted in order to make more sense [MustTest].
  4233. attack_chance = def.attack_chance or 95,
  4234. show_health = def.show_health,
  4235. _cmi_is_mob = true,
  4236. glow = def.glow,
  4237. punch_target = def.punch_target,
  4238. on_spawn = def.on_spawn,
  4239. on_blast = def.on_blast or function(...) return mobs.do_tnt(...) end,
  4240. on_step = function(...) return mobs.mob_step(...) end,
  4241. do_punch = def.do_punch,
  4242. on_punch = function(...) return mobs.mob_punch(...) end,
  4243. on_breed = def.on_breed,
  4244. on_grown = def.on_grown,
  4245. on_activate = function(self, staticdata, dtime)
  4246. return mobs.mob_activate(self, staticdata, def, dtime)
  4247. end,
  4248. get_staticdata = function(self)
  4249. return mobs.mob_staticdata(self)
  4250. end,
  4251. })
  4252. end -- END mobs:register_mob function
  4253. end
  4254. local function arrow_step(self, dtime, def)
  4255. self.timer = self.timer + 1
  4256. local pos = self.object:get_pos()
  4257. if not pos then
  4258. return
  4259. end
  4260. -- Remove expired arrows.
  4261. if self.switch == 0
  4262. or self.timer > 150
  4263. or not within_limits(pos, 0) then
  4264. self.object:remove()
  4265. return
  4266. end
  4267. -- does arrow have a tail (fireball)
  4268. if def.tail
  4269. and def.tail == 1
  4270. and def.tail_texture then
  4271. minetest.add_particle({
  4272. pos = pos,
  4273. velocity = {x = 0, y = 0, z = 0},
  4274. acceleration = {x = 0, y = 0, z = 0},
  4275. expirationtime = def.expire or 0.25,
  4276. collisiondetection = false,
  4277. texture = def.tail_texture,
  4278. size = def.tail_size or 5,
  4279. glow = def.glow or 0,
  4280. })
  4281. end
  4282. if self.hit_node then
  4283. -- Always round node position before passing it to code that probably
  4284. -- assumes that position is an integer (failure to do this can result in
  4285. -- coordinate problems in the engine)!
  4286. local rpos = v_round(pos)
  4287. local node = node_ok(rpos).name
  4288. local ndef = minetest.reg_ns_nodes[node]
  4289. if not ndef or ndef.walkable then
  4290. self.hit_node(self, rpos, node)
  4291. if self.drop == true then
  4292. pos.y = pos.y + 1
  4293. self.lastpos = (self.lastpos or pos)
  4294. minetest.add_item(self.lastpos, self.object:get_luaentity().name)
  4295. end
  4296. self.object:remove() ; -- print ("hit node")
  4297. return
  4298. end
  4299. end
  4300. if self.hit_player or self.hit_mob then
  4301. -- Find target that we hit.
  4302. for _, target in pairs(minetest.get_objects_inside_radius(pos, 1.5)) do
  4303. if self.hit_player and target:is_player() then
  4304. self.hit_player(self, target)
  4305. self.object:remove()
  4306. return
  4307. end
  4308. local entity = target:get_luaentity()
  4309. if entity and self.hit_mob and entity._cmi_is_mob == true
  4310. and target ~= self.owner_obj
  4311. and entity.name ~= self.name then
  4312. -- Check that target actually exists.
  4313. if target:get_pos() then
  4314. self.hit_mob(self, target)
  4315. self.object:remove()
  4316. return
  4317. end
  4318. end
  4319. end
  4320. end
  4321. self.lastpos = pos
  4322. end
  4323. -- export!
  4324. function mobs.arrow_step(self, dtime, def)
  4325. return arrow_step(self, dtime, def)
  4326. end
  4327. -- register mob arrow entity function
  4328. if not mobs.registered then
  4329. -- register arrow for shoot attack
  4330. function mobs.register_arrow(name, def)
  4331. if not name or not def then return end -- errorcheck
  4332. minetest.register_entity(name, {
  4333. physical = false,
  4334. visual = def.visual,
  4335. visual_size = def.visual_size,
  4336. textures = def.textures,
  4337. velocity = def.velocity,
  4338. hit_player = def.hit_player,
  4339. hit_node = def.hit_node,
  4340. hit_mob = def.hit_mob,
  4341. drop = def.drop or false, -- drops arrow as registered item when true
  4342. collisionbox = {0, 0, 0, 0, 0, 0}, -- remove box around arrows
  4343. timer = 0,
  4344. switch = 0,
  4345. rotate = def.rotate,
  4346. automatic_face_movement_dir = def.rotate
  4347. and (def.rotate - (pi / 180)) or false,
  4348. on_activate = def.on_activate,
  4349. on_step = def.on_step or function(self, dtime)
  4350. return mobs.arrow_step(self, dtime, def)
  4351. end,
  4352. })
  4353. end
  4354. end
  4355. -- Spawner item.
  4356. -- Note: This also introduces the “spawn_egg” group:
  4357. -- * spawn_egg=1: Spawn egg (generic mob, no metadata)
  4358. -- * spawn_egg=2: Spawn egg (captured/tamed mob, metadata)
  4359. if not mobs.registered then
  4360. mobs.register_egg = function(mob, desc, background, addegg, no_creative)
  4361. local invimg = background
  4362. if addegg == 1 then
  4363. invimg = "mobs_egg.png^(" .. background .. "^[mask:mobs_egg_overlay.png)"
  4364. elseif addegg == 0 then
  4365. invimg = background
  4366. end
  4367. -- Register new spawn egg containing mob information
  4368. minetest.register_craftitem(mob .. "_set", {
  4369. description = desc .. " Spawn Egg (Tamed)",
  4370. inventory_image = invimg,
  4371. groups = {
  4372. not_in_creative_inventory = 1,
  4373. not_in_craft_guide = 1,
  4374. spawn_egg = 2,
  4375. },
  4376. stack_max = 1,
  4377. on_place = function(itemstack, placer, pointed_thing)
  4378. local pos = pointed_thing.above
  4379. -- Am I clicking on something with existing on_rightclick function?
  4380. local under = minetest.get_node(pointed_thing.under)
  4381. local def = minetest.registered_nodes[under.name]
  4382. if def and def.on_rightclick then
  4383. return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
  4384. end
  4385. if pos and within_limits(pos, 0) then
  4386. if not minetest.registered_entities[mob] then
  4387. minetest.chat_send_player(name, "# Server: Creature type not defined!")
  4388. return
  4389. end
  4390. pos.y = pos.y + 1
  4391. local data = itemstack:get_metadata()
  4392. local mob = minetest.add_entity(pos, mob, data)
  4393. local ent = mob:get_luaentity()
  4394. if not ent then mob:remove()
  4395. minetest.chat_send_player(name, "# Server: Failed to revive creature!")
  4396. return
  4397. end
  4398. -- Set owner if not a monster or NPC.
  4399. if ent.type ~= "monster" and ent.type ~= "npc" then
  4400. ent.owner = placer:get_player_name()
  4401. ent.tamed = true
  4402. end
  4403. -- Since mob is unique we remove egg once spawned.
  4404. itemstack:take_item()
  4405. end
  4406. return itemstack
  4407. end,
  4408. })
  4409. -- Register old stackable mob egg.
  4410. minetest.register_craftitem(mob, {
  4411. description = desc .. " Spawn Egg",
  4412. inventory_image = invimg,
  4413. groups = {
  4414. not_in_creative_inventory = 1,
  4415. not_in_craft_guide = 1,
  4416. spawn_egg = 1,
  4417. },
  4418. on_place = function(itemstack, placer, pointed_thing)
  4419. local pos = pointed_thing.above
  4420. local name = placer:get_player_name()
  4421. if pos and within_limits(pos, 0) then
  4422. if not minetest.registered_entities[mob] then
  4423. minetest.chat_send_player(name, "# Server: Creature type not defined!")
  4424. return
  4425. end
  4426. pos.y = pos.y + 1
  4427. local mob = minetest.add_entity(pos, mob)
  4428. local ent = mob:get_luaentity()
  4429. if not ent then mob:remove()
  4430. minetest.chat_send_player(name, "# Server: Failed to summon creature!")
  4431. return
  4432. end
  4433. -- Don't set owner if monster or NPC or sneak pressed.
  4434. if ent.type ~= "monster" and ent.type ~= "npc" then
  4435. if not placer:get_player_control().sneak then
  4436. ent.owner = placer:get_player_name()
  4437. ent.tamed = true
  4438. end
  4439. end
  4440. end
  4441. itemstack:take_item()
  4442. return itemstack
  4443. end,
  4444. })
  4445. end
  4446. end
  4447. -- Capture critter (thanks to blert2112 for idea).
  4448. function mobs.capture_mob(self, clicker, chance_hand, chance_net, chance_lasso, force_take, replacewith)
  4449. if self.child
  4450. or not clicker:is_player()
  4451. or not clicker:get_inventory() then
  4452. return false
  4453. end
  4454. -- get name of clicked mob
  4455. local mobname = self.name
  4456. -- if not nil change what will be added to inventory
  4457. if replacewith then
  4458. mobname = replacewith
  4459. end
  4460. local name = clicker:get_player_name()
  4461. local tool = clicker:get_wielded_item()
  4462. -- are we using hand, net or lasso to pick up mob?
  4463. if tool:get_name() ~= ""
  4464. and tool:get_name() ~= "mobs:net"
  4465. and tool:get_name() ~= "mobs:lasso" then
  4466. return false
  4467. end
  4468. -- Is mob tamed?
  4469. if self.tamed == false and force_take == false then
  4470. minetest.chat_send_player(name, "# Server: Animal not tamed!")
  4471. return true -- false
  4472. end
  4473. -- Cannot pick up if not owner.
  4474. if self.owner ~= name and force_take == false then
  4475. minetest.chat_send_player(name, "# Server: Player <" .. rename.gpn(self.owner) .. "> is owner!")
  4476. return true -- false
  4477. end
  4478. if clicker:get_inventory():room_for_item("main", mobname) then
  4479. -- Was mob clicked with hand, net, or lasso?
  4480. local chance = 0
  4481. local tool = clicker:get_wielded_item()
  4482. if tool:get_name() == "" then
  4483. chance = chance_hand
  4484. elseif tool:get_name() == "mobs:net" then
  4485. chance = chance_net
  4486. tool:add_wear(4000) -- 17 uses
  4487. clicker:set_wielded_item(tool)
  4488. elseif tool:get_name() == "mobs:lasso" then
  4489. chance = chance_lasso
  4490. tool:add_wear(650) -- 100 uses
  4491. clicker:set_wielded_item(tool)
  4492. end
  4493. -- calculate chance.. add to inventory if successful?
  4494. if chance > 0 and random(1, 100) <= chance then
  4495. -- default mob egg
  4496. local new_stack = ItemStack(mobname)
  4497. -- add special mob egg with all mob information
  4498. -- unless 'replacewith' contains new item to use
  4499. if not replacewith then
  4500. new_stack = ItemStack(mobname .. "_set")
  4501. local tmp = {}
  4502. for _,stat in pairs(self) do
  4503. local t = type(stat)
  4504. if t ~= "function"
  4505. and t ~= "nil"
  4506. and t ~= "userdata" then
  4507. tmp[_] = self[_]
  4508. end
  4509. end
  4510. local data_str = minetest.serialize(tmp)
  4511. new_stack:set_metadata(data_str)
  4512. end
  4513. local inv = clicker:get_inventory()
  4514. if inv:room_for_item("main", new_stack) then
  4515. inv:add_item("main", new_stack)
  4516. else
  4517. minetest.add_item(clicker:get_pos(), new_stack)
  4518. end
  4519. -- Mark for removal as last action on mob_step().
  4520. self.mkrm = true
  4521. mob_sound(self, "default_place_node_hard")
  4522. elseif chance ~= 0 then
  4523. minetest.chat_send_player(name, "# Server: Missed!")
  4524. mob_sound(self, "mobs_swing")
  4525. end
  4526. end
  4527. end
  4528. -- Make tables persistent even when file reloaded.
  4529. if not mobs.registered then
  4530. mobs.nametagdata = {}
  4531. mobs.nametagdata.mob_obj = {}
  4532. mobs.nametagdata.mob_sta = {}
  4533. end
  4534. local mob_obj = mobs.nametagdata.mob_obj
  4535. local mob_sta = mobs.nametagdata.mob_sta
  4536. -- Feeding, taming and breeding (thanks blert2112).
  4537. function mobs.feed_tame(self, clicker, feed_count, breed, tame)
  4538. if not self.follow then
  4539. return false
  4540. end
  4541. -- can eat/tame with item in hand
  4542. if follow_holding(self, clicker) then
  4543. -- if not in creative then take item
  4544. if not creative then
  4545. local item = clicker:get_wielded_item()
  4546. item:take_item()
  4547. clicker:set_wielded_item(item)
  4548. end
  4549. -- increase health
  4550. self.health = self.health + 4
  4551. if self.health >= self.hp_max then
  4552. self.health = self.hp_max
  4553. if self.htimer < 1 then
  4554. minetest.chat_send_player(clicker:get_player_name(), "# Server: Mob has full health!")
  4555. self.htimer = 5
  4556. end
  4557. end
  4558. self.object:set_hp(self.health)
  4559. update_tag(self)
  4560. -- make children grow quicker
  4561. if self.child == true then
  4562. self.hornytimer = self.hornytimer + 20
  4563. return true
  4564. end
  4565. -- feed and tame
  4566. self.food = (self.food or 0) + 1
  4567. if self.food >= feed_count then
  4568. self.food = 0
  4569. if breed and self.hornytimer == 0 then
  4570. self.horny = true
  4571. end
  4572. self.gotten = false
  4573. if tame then
  4574. if self.tamed == false then
  4575. minetest.chat_send_player(clicker:get_player_name(), "# Server: Mob has been tamed!")
  4576. end
  4577. self.tamed = true
  4578. if not self.owner or self.owner == "" then
  4579. self.owner = clicker:get_player_name()
  4580. end
  4581. end
  4582. -- make sound when fed so many times
  4583. mob_sound(self, self.sounds.random)
  4584. end
  4585. return true
  4586. end
  4587. local item = clicker:get_wielded_item()
  4588. -- if mob has been tamed you can name it with a nametag
  4589. if item:get_name() == "mobs:nametag"
  4590. and clicker:get_player_name() == self.owner then
  4591. local name = clicker:get_player_name()
  4592. -- store mob and nametag stack in external variables
  4593. mob_obj[name] = self
  4594. mob_sta[name] = item
  4595. local tag = self.nametag or ""
  4596. minetest.show_formspec(name, "mobs_nametag", "size[8,4]"
  4597. .. default.gui_bg
  4598. .. default.gui_bg_img
  4599. .. "field[0.5,1;7.5,0;name;" .. minetest.formspec_escape("Enter name:") .. ";" .. tag .. "]"
  4600. .. "button_exit[2.5,3.5;3,1;mob_rename;" .. minetest.formspec_escape("Rename") .. "]")
  4601. end
  4602. return false
  4603. end
  4604. function mobs.nametag_receive_fields(player, formname, fields)
  4605. -- right-clicked with nametag and name entered?
  4606. if formname == "mobs_nametag"
  4607. and fields.name
  4608. and fields.name ~= "" then
  4609. local name = player:get_player_name()
  4610. if not mob_obj[name]
  4611. or not mob_obj[name].object then
  4612. return
  4613. end
  4614. -- make sure nametag is being used to name mob
  4615. local item = player:get_wielded_item()
  4616. if item:get_name() ~= "mobs:nametag" then
  4617. return
  4618. end
  4619. -- limit name entered to 64 characters long
  4620. if string.len(fields.name) > 64 then
  4621. fields.name = string.sub(fields.name, 1, 64)
  4622. end
  4623. -- update nametag
  4624. mob_obj[name].nametag = fields.name
  4625. update_tag(mob_obj[name])
  4626. -- take item
  4627. mob_sta[name]:take_item()
  4628. player:set_wielded_item(mob_sta[name])
  4629. -- reset external variables
  4630. mob_obj[name] = nil
  4631. mob_sta[name] = nil
  4632. end
  4633. end
  4634. -- inspired by blockmen's nametag mod
  4635. if not mobs.registered then
  4636. minetest.register_on_player_receive_fields(function(...)
  4637. return mobs.nametag_receive_fields(...)
  4638. end)
  4639. end
  4640. -- compatibility function for old entities to new modpack entities
  4641. if not mobs.registered then
  4642. function mobs.alias_mob(old_name, new_name)
  4643. -- spawn egg
  4644. minetest.register_alias(old_name, new_name)
  4645. -- entity
  4646. minetest.register_entity(":" .. old_name, {
  4647. physical = false,
  4648. on_activate = function(self)
  4649. if minetest.registered_entities[new_name] then
  4650. minetest.add_entity(self.object:get_pos(), new_name)
  4651. end
  4652. -- Remove mob immediately, as last step of this function.
  4653. -- Control returns to engine.
  4654. self.object:remove()
  4655. self.mkrm = true
  4656. end
  4657. })
  4658. end
  4659. end
  4660. -- Register as a reloadable file.
  4661. if not mobs.registered then
  4662. local c = "mobs:api"
  4663. local f = mobs.modpath .. "/api.lua"
  4664. reload.register_file(c, f, false)
  4665. mobs.registered = true
  4666. end