api.lua 145 KB

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