LCOV - code coverage report
Current view: top level - world/lifecycle - spawn.go Coverage Total Hit
Test: coverage.lcov Lines: 77.9 % 244 190
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package lifecycle
       2              : 
       3              : import (
       4              :         "errors"
       5              :         "fmt"
       6              :         "math/rand/v2"
       7              : 
       8              :         "github.com/hajimehoshi/ebiten/v2/text/v2"
       9              :         gc "github.com/kijimaD/ruins/internal/components"
      10              :         "github.com/kijimaD/ruins/internal/consts"
      11              :         "github.com/kijimaD/ruins/internal/formula"
      12              :         "github.com/kijimaD/ruins/internal/raw"
      13              :         w "github.com/kijimaD/ruins/internal/world"
      14              :         "github.com/kijimaD/ruins/internal/world/query"
      15              :         "github.com/mlange-42/ark/ecs"
      16              : )
      17              : 
      18              : // エラー定義
      19              : var (
      20              :         ErrItemGeneration   = errors.New("failed to generate item")
      21              :         ErrMemberGeneration = errors.New("failed to generate member")
      22              :         ErrEnemyGeneration  = errors.New("failed to generate enemy")
      23              :         ErrEffectGeneration = errors.New("failed to generate effect")
      24              : 
      25              :         // errNotNeutralNPC は中立でないメンバーを中立NPCとして生成しようとしたときに返す
      26              :         errNotNeutralNPC = errors.New("not a neutral NPC")
      27              :         // errNonPositiveCount は生成個数が正でないときに返す
      28              :         errNonPositiveCount = errors.New("count must be positive")
      29              :         // errMissingStatsComponents はHPかAbilitiesを持たないエンティティの最大HPを設定しようとしたときに返す
      30              :         errMissingStatsComponents = errors.New("entity does not have required components HP or Abilities")
      31              : )
      32              : 
      33              : // initialPatrolDir はPatrol移動の初期方向をランダムに決定する。X軸方向で+1か-1を返す
      34              : func initialPatrolDir() consts.Tile {
      35            1 :         if rand.IntN(2) == 0 {
      36            1 :                 return 1
      37            1 :         }
      38            1 :         return -1
      39              : }
      40              : 
      41              : // SpawnTile はタイルを生成する
      42              : // autoTileIndexが指定された場合、spriteKeyを動的に生成する(例: "wall_5")
      43              : func SpawnTile(world w.World, tileName string, x consts.Tile, y consts.Tile, autoTileIndex *int) (ecs.Entity, error) {
      44            1 :         rawMaster := world.Resources.RawMaster
      45            1 :         entitySpec, err := raw.NewTileSpec(rawMaster, tileName, x, y, autoTileIndex)
      46            1 :         if err != nil {
      47            1 :                 return gc.InvalidEntity, err
      48            1 :         }
      49              : 
      50            1 :         entity := world.Components.AddEntity(world.ECS, &entitySpec)
      51            1 :         return entity, nil
      52              : }
      53              : 
      54              : // SpawnPlayer はプレイヤーキャラクターを生成する
      55              : func SpawnPlayer(world w.World, pos consts.Coord[consts.Tile], name string) (ecs.Entity, error) {
      56            1 :         entitySpec, err := raw.NewPlayerSpec(world.Resources.RawMaster, name)
      57            1 :         if err != nil {
      58            0 :                 return gc.InvalidEntity, fmt.Errorf("%w: %w", ErrMemberGeneration, err)
      59            0 :         }
      60              : 
      61            1 :         entitySpec.GridElement = &gc.GridElement{Coord: pos}
      62            1 :         center := consts.TileCenterToWorld(pos)
      63            1 :         entitySpec.Camera = &gc.Camera{
      64            1 :                 Scale:   gc.CameraMinScale,
      65            1 :                 ScaleTo: gc.CameraMinScale,
      66            1 :                 Pos:     center,
      67            1 :                 Target:  center,
      68            1 :                 Pitch:   gc.CameraDefaultPitch,
      69            1 :                 Dist:    gc.CameraDefaultDist,
      70            1 :         }
      71            1 :         entitySpec.Wallet = &gc.Wallet{Currency: 10000}
      72            1 :         playerEntity := world.Components.AddEntity(world.ECS, &entitySpec)
      73            1 : 
      74            1 :         if err := FullRecover(world, playerEntity); err != nil {
      75            0 :                 return gc.InvalidEntity, fmt.Errorf("player recovery failed: %w", err)
      76            0 :         }
      77            1 :         world.Components.WeightDirty.Add(playerEntity, &gc.WeightDirty{})
      78            1 : 
      79            1 :         if err := giveStartingGear(world, playerEntity, name); err != nil {
      80            0 :                 return gc.InvalidEntity, err
      81            0 :         }
      82              : 
      83            1 :         query.InvalidateSpatialIndex(world)
      84            1 :         return playerEntity, nil
      85              : }
      86              : 
      87              : // giveStartingGear は member の行の初期装備を装備させ、初期アイテムをバックパックへ持たせる。
      88              : // 所有者は生成中の member と確定しているので、世界からの検索を挟まず直接持たせる
      89              : func giveStartingGear(world w.World, owner ecs.Entity, name string) error {
      90            1 :         member, err := raw.FindMember(world.Resources.RawMaster, name)
      91            1 :         if err != nil {
      92            0 :                 return err
      93            0 :         }
      94            1 :         for _, equip := range raw.PtrSlice(member.StartingEquips) {
      95            1 :                 item, err := spawnItemBase(world, equip.Name)
      96            1 :                 if err != nil {
      97            0 :                         return fmt.Errorf("failed to spawn starting %s: %w", equip.Name, err)
      98            0 :                 }
      99            1 :                 if err := MoveToBackpack(world, item, owner); err != nil {
     100            0 :                         return fmt.Errorf("failed to give starting %s: %w", equip.Name, err)
     101            0 :                 }
     102            1 :                 slot, ok := gc.ParseEquipmentSlot(equip.Slot)
     103            1 :                 if !ok {
     104            0 :                         return fmt.Errorf("invalid equipment slot %q for %s", equip.Slot, equip.Name)
     105            0 :                 }
     106            1 :                 MoveToEquip(world, item, owner, slot)
     107              :         }
     108            1 :         for _, it := range raw.PtrSlice(member.StartingItems) {
     109            1 :                 for range it.Count {
     110            1 :                         item, err := spawnItemBase(world, it.Name)
     111            1 :                         if err != nil {
     112            0 :                                 return fmt.Errorf("failed to spawn starting %s: %w", it.Name, err)
     113            0 :                         }
     114            1 :                         if err := MoveToBackpack(world, item, owner); err != nil {
     115            0 :                                 return fmt.Errorf("failed to give starting %s: %w", it.Name, err)
     116            0 :                         }
     117              :                 }
     118              :         }
     119            1 :         return nil
     120              : }
     121              : 
     122              : // SpawnNeutralNPC はフィールド上に中立NPCを生成する(会話可能なNPC用)
     123              : func SpawnNeutralNPC(world w.World, pos consts.Coord[consts.Tile], name string) (ecs.Entity, error) {
     124            1 :         entitySpec, err := raw.NewMemberSpec(world.Resources.RawMaster, name)
     125            1 :         if err != nil {
     126            1 :                 return gc.InvalidEntity, fmt.Errorf("failed to generate neutral NPC: %w", err)
     127            1 :         }
     128              : 
     129            1 :         if entitySpec.FactionNeutral == nil {
     130            1 :                 return gc.InvalidEntity, fmt.Errorf("%w: %s", errNotNeutralNPC, name)
     131            1 :         }
     132            1 :         if entitySpec.Dialog == nil {
     133            0 :                 return gc.InvalidEntity, fmt.Errorf("'%s' has no dialog data", name)
     134            0 :         }
     135              : 
     136            1 :         entitySpec.GridElement = &gc.GridElement{Coord: pos}
     137            1 : 
     138            1 :         if entitySpec.SoloAI != nil {
     139            1 :                 solo := entitySpec.SoloAI
     140            1 :                 solo.SubState = gc.AIStateWaiting
     141            1 :                 solo.StartSubStateTurn = 1
     142            1 :                 solo.DurationSubStateTurns = consts.Turn(2 + rand.IntN(3))
     143            1 :                 solo.Origin = pos
     144            1 :                 solo.PatrolDir.X = initialPatrolDir()
     145            1 :                 solo.ViewDistance = consts.AIVisionDistance
     146            1 :         }
     147              : 
     148            1 :         npcEntity := world.Components.AddEntity(world.ECS, &entitySpec)
     149            1 :         if err := FullRecover(world, npcEntity); err != nil {
     150            0 :                 return gc.InvalidEntity, fmt.Errorf("NPC recovery failed: %w", err)
     151            0 :         }
     152              : 
     153              :         // 在庫を持つ member は店を開く。生成経路に依らずここで積むことで、集落でも街マップの
     154              :         // マッププランナ経由でも同じ在庫を持たせる。売買と雇用はこの在庫を出し入れする
     155            1 :         if err := PopulateStock(world, npcEntity, name); err != nil {
     156            0 :                 return gc.InvalidEntity, err
     157            0 :         }
     158              : 
     159            1 :         query.InvalidateSpatialIndex(world)
     160            1 :         return npcEntity, nil
     161              : }
     162              : 
     163              : // SpawnEnemy はフィールド上に敵キャラクターを生成する
     164              : func SpawnEnemy(world w.World, pos consts.Coord[consts.Tile], name string) (ecs.Entity, error) {
     165            1 :         entitySpec, err := raw.NewEnemySpec(world.Resources.RawMaster, name)
     166            1 :         if err != nil {
     167            0 :                 return gc.InvalidEntity, fmt.Errorf("%w: %w", ErrEnemyGeneration, err)
     168            0 :         }
     169              : 
     170            1 :         entitySpec.GridElement = &gc.GridElement{Coord: pos}
     171            1 :         if entitySpec.SoloAI == nil {
     172            0 :                 return gc.InvalidEntity, fmt.Errorf("enemy entity has no AI specified: %s", entitySpec.Name)
     173            0 :         }
     174            1 :         solo := entitySpec.SoloAI
     175            1 :         solo.SubState = gc.AIStateWaiting
     176            1 :         solo.StartSubStateTurn = 1
     177            1 :         solo.DurationSubStateTurns = consts.Turn(2 + rand.IntN(3))
     178            1 :         solo.Origin = pos
     179            1 :         solo.PatrolDir.X = initialPatrolDir()
     180            1 :         solo.ViewDistance = consts.AIVisionDistance
     181            1 :         entitySpec.Interactable = &gc.Interactable{
     182            1 :                 Interactions: []gc.InteractionKind{gc.InteractionMelee},
     183            1 :         }
     184              : 
     185            1 :         npcEntity := world.Components.AddEntity(world.ECS, &entitySpec)
     186            1 :         if err := FullRecover(world, npcEntity); err != nil {
     187            0 :                 return gc.InvalidEntity, fmt.Errorf("enemy recovery failed: %w", err)
     188            0 :         }
     189              : 
     190            1 :         if world.Components.TurnBased.Has(npcEntity) {
     191            1 :                 actionPoints := world.Components.TurnBased.Get(npcEntity)
     192            1 :                 maxAP := query.CalculateMaxActionPoints(world, npcEntity)
     193            1 :                 actionPoints.AP.Current = maxAP
     194            1 :                 actionPoints.AP.Max = maxAP
     195            1 :         }
     196              : 
     197            1 :         query.InvalidateSpatialIndex(world)
     198            1 :         return npcEntity, nil
     199              : }
     200              : 
     201              : // SpawnBackpackItem はバックパック内にアイテムを count 個生成する。
     202              : // 1個1エンティティなので count 回生成する。戻り値はスタック代表としての1個で、
     203              : // 同一スタックの個体はどれも等価。個数や全個体は代表から query 側で導出する。
     204              : func SpawnBackpackItem(world w.World, name string, count int) (ecs.Entity, error) {
     205            1 :         if count <= 0 {
     206            1 :                 return gc.InvalidEntity, fmt.Errorf("%w: %d", errNonPositiveCount, count)
     207            1 :         }
     208              : 
     209              :         // バックパックはプレイヤーの所有物なので、プレイヤー不在での生成は不変条件違反として返す。
     210              :         // 所有者なしのバックパック品は束ねの所有者一致に掛からず、silent な迷子になる
     211            1 :         playerEntity, err := query.GetPlayerEntity(world)
     212            1 :         if err != nil {
     213            1 :                 return gc.InvalidEntity, fmt.Errorf("failed to spawn backpack item: %w", err)
     214            1 :         }
     215              : 
     216            1 :         last := gc.InvalidEntity
     217            1 :         for range count {
     218            1 :                 item, err := spawnItemBase(world, name)
     219            1 :                 if err != nil {
     220            1 :                         return gc.InvalidEntity, err
     221            1 :                 }
     222            1 :                 if err := MoveToBackpack(world, item, playerEntity); err != nil {
     223            0 :                         return item, fmt.Errorf("failed to move to backpack: %w", err)
     224            0 :                 }
     225            1 :                 last = item
     226              :         }
     227            1 :         return last, nil
     228              : }
     229              : 
     230              : // spawnItemBase はLocationなしでアイテムエンティティを1個生成する内部関数。
     231              : // 1個1エンティティなので個数は扱わない。N個はラッパがN回呼んで作る。
     232              : func spawnItemBase(world w.World, name string) (ecs.Entity, error) {
     233            1 :         entitySpec, err := raw.NewItemSpec(world.Resources.RawMaster, name)
     234            1 :         if err != nil {
     235            1 :                 return gc.InvalidEntity, fmt.Errorf("%w: %w", ErrItemGeneration, err)
     236            1 :         }
     237              : 
     238            1 :         entity := world.Components.AddEntity(world.ECS, &entitySpec)
     239            1 :         // 腐敗の起点を今の総ターン数で刻む。GameTime は world 生成時から常在する
     240            1 :         if world.Components.Perishable.Has(entity) {
     241            1 :                 world.Components.Perishable.Get(entity).RotUpdatedTurn = query.GetGameTime(world).TotalTurns
     242            1 :         }
     243            1 :         return entity, nil
     244              : }
     245              : 
     246              : // FullRecover はエンティティのHP/APを全回復する
     247              : func FullRecover(world w.World, entity ecs.Entity) error {
     248            1 :         if err := setMaxStats(world, entity); err != nil {
     249            0 :                 return fmt.Errorf("failed to set max HP: %w", err)
     250            0 :         }
     251              : 
     252            1 :         hp := world.Components.HP.Get(entity)
     253            1 :         if hp == nil {
     254            0 :                 return fmt.Errorf("HP component is missing")
     255            0 :         }
     256            1 :         hp.Current = hp.Max
     257            1 : 
     258            1 :         if world.Components.TurnBased.Has(entity) {
     259            1 :                 maxAP := query.CalculateMaxActionPoints(world, entity)
     260            1 :                 turnBased := world.Components.TurnBased.Get(entity)
     261            1 :                 turnBased.AP.Current = maxAP
     262            1 :                 turnBased.AP.Max = maxAP
     263            1 :         }
     264              : 
     265            1 :         return nil
     266              : }
     267              : 
     268              : // setMaxStats はエンティティの最大HPを設定する
     269              : func setMaxStats(world w.World, entity ecs.Entity) error {
     270            1 :         if !world.Components.HP.Has(entity) || !world.Components.Abilities.Has(entity) {
     271            1 :                 return fmt.Errorf("%w: %v", errMissingStatsComponents, entity)
     272            1 :         }
     273              : 
     274            1 :         hp := world.Components.HP.Get(entity)
     275            1 :         abils := world.Components.Abilities.Get(entity)
     276            1 : 
     277            1 :         if abils.Vitality.Total == 0 {
     278            1 :                 abils.Vitality.Total = abils.Vitality.Base
     279            1 :         }
     280            1 :         if abils.Strength.Total == 0 {
     281            1 :                 abils.Strength.Total = abils.Strength.Base
     282            1 :         }
     283            1 :         if abils.Sensation.Total == 0 {
     284            1 :                 abils.Sensation.Total = abils.Sensation.Base
     285            1 :         }
     286            1 :         if abils.Dexterity.Total == 0 {
     287            1 :                 abils.Dexterity.Total = abils.Dexterity.Base
     288            1 :         }
     289            1 :         if abils.Agility.Total == 0 {
     290            1 :                 abils.Agility.Total = abils.Agility.Base
     291            1 :         }
     292            1 :         if abils.Defense.Total == 0 {
     293            1 :                 abils.Defense.Total = abils.Defense.Base
     294            1 :         }
     295              : 
     296            1 :         hp.Max = formula.CalcHP(abils.Vitality.Total, abils.Strength.Total, abils.Sensation.Total)
     297            1 :         hp.Current = hp.Max
     298            1 : 
     299            1 :         return nil
     300              : }
     301              : 
     302              : // SpawnStorageItem は収納内にアイテムを count 個生成する。戻り値はスタック代表としての1個。
     303              : func SpawnStorageItem(world w.World, itemName string, count int, storage ecs.Entity) (ecs.Entity, error) {
     304            1 :         if count <= 0 {
     305            0 :                 return gc.InvalidEntity, fmt.Errorf("%w: %d", errNonPositiveCount, count)
     306            0 :         }
     307            1 :         last := gc.InvalidEntity
     308            1 :         for range count {
     309            1 :                 item, err := spawnItemBase(world, itemName)
     310            1 :                 if err != nil {
     311            0 :                         return gc.InvalidEntity, err
     312            0 :                 }
     313            1 :                 if err := MoveToStorage(world, item, storage); err != nil {
     314            0 :                         return item, fmt.Errorf("failed to move to storage: %w", err)
     315            0 :                 }
     316            1 :                 last = item
     317              :         }
     318            1 :         return last, nil
     319              : }
     320              : 
     321              : // SpawnFieldItem はフィールド上に同じ位置へアイテムを count 個生成する。戻り値はスタック代表としての1個。
     322              : func SpawnFieldItem(world w.World, itemName string, x consts.Tile, y consts.Tile, count int) (ecs.Entity, error) {
     323            1 :         if count <= 0 {
     324            0 :                 return gc.InvalidEntity, fmt.Errorf("%w: %d", errNonPositiveCount, count)
     325            0 :         }
     326            1 :         last := gc.InvalidEntity
     327            1 :         for range count {
     328            1 :                 item, err := spawnItemBase(world, itemName)
     329            1 :                 if err != nil {
     330            1 :                         return gc.InvalidEntity, err
     331            1 :                 }
     332            1 :                 MoveToField(world, item, nil)
     333            1 :                 world.Components.GridElement.Add(item, &gc.GridElement{Coord: consts.Coord[consts.Tile]{X: x, Y: y}})
     334            1 :                 last = item
     335              :         }
     336            1 :         return last, nil
     337              : }
     338              : 
     339              : // SpawnVisualEffect はエンティティの位置にエフェクト専用エンティティを生成する
     340              : func SpawnVisualEffect(target ecs.Entity, effect gc.VisualEffect, world w.World) {
     341            1 :         if !world.Components.GridElement.Has(target) {
     342            1 :                 return
     343            1 :         }
     344              : 
     345            1 :         gridElement := world.Components.GridElement.Get(target)
     346            1 : 
     347            1 :         effectEntity := world.ECS.NewEntity()
     348            1 :         world.Components.GridElement.Add(effectEntity, &gc.GridElement{Coord: gridElement.Coord})
     349            1 :         world.Components.VisualEffects.Add(effectEntity, &gc.VisualEffects{
     350            1 :                 Effects: []gc.VisualEffect{effect},
     351            1 :         })
     352              : }
     353              : 
     354              : // SpawnSplashText は画面中央にテキストをスプラッシュ表示するエフェクト専用エンティティを生成する。
     355              : // 場面の節目を大書きで知らせる演出に使う。face はフォント未ロードの環境では nil のまま作り、
     356              : // 描画しない環境でも生成できるようにする
     357              : func SpawnSplashText(world w.World, textStr string) {
     358            0 :         screenW, screenH := world.Resources.GetScreenDimensions()
     359            0 :         var face text.Face
     360            0 :         if tr := world.Resources.UIResources.Text; tr != nil {
     361            0 :                 face = tr.SplashFontFace
     362            0 :         }
     363            0 :         effect := gc.NewSplashTextEffect(textStr, face, screenW, screenH)
     364            0 :         effectEntity := world.ECS.NewEntity()
     365            0 :         world.Components.VisualEffects.Add(effectEntity, &gc.VisualEffects{
     366            0 :                 Effects: []gc.VisualEffect{effect},
     367            0 :         })
     368              : }
        

Generated by: LCOV version 2.0-1