LCOV - code coverage report
Current view: top level - mapplanner - lib.go Coverage Total Hit
Test: coverage.lcov Lines: 86.0 % 186 160
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : // Package mapplanner はマップ生成機能を提供する
       2              : // 参考: https://bfnightly.bracketproductions.com
       3              : package mapplanner
       4              : 
       5              : import (
       6              :         "fmt"
       7              :         "math/rand/v2"
       8              :         "reflect"
       9              :         "slices"
      10              :         "time"
      11              : 
      12              :         gc "github.com/kijimaD/ruins/internal/components"
      13              :         "github.com/kijimaD/ruins/internal/consts"
      14              :         "github.com/kijimaD/ruins/internal/maptemplate"
      15              :         "github.com/kijimaD/ruins/internal/raw"
      16              :         "github.com/kijimaD/ruins/internal/rawschema"
      17              :         w "github.com/kijimaD/ruins/internal/world"
      18              : )
      19              : 
      20              : // PropsSpec はProps配置仕様を表す
      21              : type PropsSpec struct {
      22              :         consts.Coord[consts.Tile]
      23              :         Name string // Prop名
      24              : }
      25              : 
      26              : // DoorSpec はドア配置仕様を表す
      27              : type DoorSpec struct {
      28              :         consts.Coord[consts.Tile]
      29              :         Orientation gc.DoorOrientation
      30              : }
      31              : 
      32              : // MetaPlan は階層のタイルを作る元になる概念の集合体
      33              : type MetaPlan struct {
      34              :         // Danger はこのプランに適用する危険度。敵やアイテムの湧きフィルタに使う。1以上であること。
      35              :         // 呼び出し側が世界の現在地から確定して渡す。
      36              :         Danger consts.Danger
      37              :         // Ground は計画の下地のタイル。地上の計画は全面を埋め、森は孤立した壁を、絵は下地を残す地形のマスをこれで置く
      38              :         Ground string
      39              :         // NeedsGround は間取りのタイルが下地 ground を指すか。立っていて Ground が空なら計画できない
      40              :         NeedsGround bool
      41              :         // FixedPortals はポータルを手続きで置かないか。絵がポータルを持つ計画と、ポータルを持たない地上の計画で立てる
      42              :         FixedPortals bool
      43              :         // 階層情報
      44              :         Level gc.Level
      45              :         // 部屋群。部屋は長方形の移動可能な空間のことをいう。
      46              :         // 部屋はタイルの集合体である
      47              :         Rooms []gc.Rect
      48              :         // 廊下群。廊下は部屋と部屋をつなぐ移動可能な空間のことをいう。
      49              :         // 廊下はタイルの集合体である
      50              :         Corridors [][]gc.TileIdx
      51              :         // 乱数生成器
      52              :         RNG *rand.Rand
      53              :         // 階層を構成するタイル群。長さはステージの大きさで決まる
      54              :         // 通行可能かを判定するための情報を保持している必要がある
      55              :         Tiles []rawschema.Tile
      56              :         // Environments は Tiles と同じ並びのタイルの環境。EnvironmentPlanner が計算する。計算前は nil
      57              :         Environments []gc.TileEnvironment
      58              :         // NextPortals は次の階へ進むポータルリスト
      59              :         NextPortals []consts.Coord[consts.Tile]
      60              :         // NPCs は配置予定のNPCリスト
      61              :         NPCs []NPCSpec
      62              :         // Items は配置予定のアイテムリスト
      63              :         Items []ItemSpec
      64              :         // Props は配置予定のPropsリスト
      65              :         Props []PropsSpec
      66              :         // Doors は配置予定のドアリスト
      67              :         Doors []DoorSpec
      68              :         // SpawnPoints はプレイヤーのスポーン地点リスト
      69              :         SpawnPoints []maptemplate.SpawnPoint
      70              :         // RawMaster はタイル生成に使用するマスターデータ
      71              :         RawMaster *rawschema.Raws
      72              : }
      73              : 
      74              : // IsSpawnableTile は指定タイル座標がスポーン可能かを返す
      75              : func (bm MetaPlan) IsSpawnableTile(_ w.World, tx consts.Tile, ty consts.Tile) bool {
      76            1 :         pos := consts.Coord[consts.Tile]{X: tx, Y: ty}
      77            1 :         idx := bm.Level.CoordToIndex(pos)
      78            1 :         tile := bm.Tiles[idx]
      79            1 :         // 通行不可なのでスポーン不可
      80            1 :         if tile.BlockPass {
      81            1 :                 return false
      82            1 :         }
      83              : 
      84              :         // planning段階では、MetaPlan内の計画済みエンティティをチェック
      85            1 :         if bm.existPlannedEntityOnTile(pos) {
      86            0 :                 return false
      87            0 :         }
      88              : 
      89            1 :         return true
      90              : }
      91              : 
      92              : // existPlannedEntityOnTile は指定座標に計画済みエンティティがあるかをチェック
      93              : func (bm MetaPlan) existPlannedEntityOnTile(pos consts.Coord[consts.Tile]) bool {
      94            1 :         return slices.Contains(bm.NextPortals, pos) ||
      95            2 :                 slices.ContainsFunc(bm.NPCs, func(npc NPCSpec) bool { return npc.Coord == pos }) ||
      96            1 :                 slices.ContainsFunc(bm.Items, func(item ItemSpec) bool { return item.Coord == pos }) ||
      97            0 :                 slices.ContainsFunc(bm.Props, func(prop PropsSpec) bool { return prop.Coord == pos }) ||
      98            1 :                 slices.ContainsFunc(bm.Doors, func(door DoorSpec) bool { return door.Coord == pos })
      99              : }
     100              : 
     101              : // outsideTile は地図の外を表すタイル。id を持たず、通れない
     102              : var outsideTile = rawschema.Tile{BlockPass: true}
     103              : 
     104              : // UpTile は上にあるタイルを調べる。地図の外は outsideTile を返す
     105              : func (bm MetaPlan) UpTile(idx gc.TileIdx) rawschema.Tile {
     106            1 :         targetIdx := gc.TileIdx(int(idx) - int(bm.Level.TileWidth))
     107            1 :         if targetIdx < 0 {
     108            1 :                 return outsideTile
     109            1 :         }
     110              : 
     111            1 :         return bm.Tiles[targetIdx]
     112              : }
     113              : 
     114              : // DownTile は下にあるタイルを調べる。地図の外は outsideTile を返す
     115              : func (bm MetaPlan) DownTile(idx gc.TileIdx) rawschema.Tile {
     116            1 :         targetIdx := int(idx) + int(bm.Level.TileWidth)
     117            1 :         if targetIdx > len(bm.Tiles)-1 {
     118            1 :                 return outsideTile
     119            1 :         }
     120              : 
     121            1 :         return bm.Tiles[targetIdx]
     122              : }
     123              : 
     124              : // LeftTile は左にあるタイルを調べる。地図の外は outsideTile を返す
     125              : func (bm MetaPlan) LeftTile(idx gc.TileIdx) rawschema.Tile {
     126            1 :         pos := bm.Level.IndexToCoord(idx)
     127            1 :         if pos.X == 0 {
     128            1 :                 return outsideTile
     129            1 :         }
     130              : 
     131              :         // 左のタイルが同じ行であることを確認
     132            1 :         targetIdx := idx - 1
     133            1 :         if bm.Level.IndexToCoord(targetIdx).Y != pos.Y {
     134            0 :                 return outsideTile
     135            0 :         }
     136              : 
     137            1 :         return bm.Tiles[targetIdx]
     138              : }
     139              : 
     140              : // RightTile は右にあるタイルを調べる。地図の外は outsideTile を返す
     141              : func (bm MetaPlan) RightTile(idx gc.TileIdx) rawschema.Tile {
     142            1 :         pos := bm.Level.IndexToCoord(idx)
     143            1 :         if pos.X == bm.Level.TileWidth-1 {
     144            1 :                 return outsideTile
     145            1 :         }
     146              : 
     147              :         // 右のタイルが同じ行であることを確認
     148            1 :         targetIdx := idx + 1
     149            1 :         if bm.Level.IndexToCoord(targetIdx).Y != pos.Y {
     150            0 :                 return outsideTile
     151            0 :         }
     152              : 
     153            1 :         return bm.Tiles[targetIdx]
     154              : }
     155              : 
     156              : // AdjacentAnyFloor は直交・斜めを含む近傍8タイルに床があるか判定する
     157              : func (bm MetaPlan) AdjacentAnyFloor(idx gc.TileIdx) bool {
     158            1 :         pos := bm.Level.IndexToCoord(idx)
     159            1 :         width := int(bm.Level.TileWidth)
     160            1 :         height := int(bm.Level.TileHeight)
     161            1 : 
     162              :         // 8方向の隣接タイル座標をチェック
     163            1 :         directions := [][2]int{
     164            1 :                 {-1, -1}, {-1, 0}, {-1, 1}, // 上段
     165            1 :                 {0, -1}, {0, 1}, // 中段(中心を除く)
     166            1 :                 {1, -1}, {1, 0}, {1, 1}, // 下段
     167            1 :         }
     168              : 
     169            1 :         for _, dir := range directions {
     170            1 :                 nx, ny := int(pos.X)+dir[0], int(pos.Y)+dir[1]
     171            1 : 
     172              :                 // 境界チェック
     173            1 :                 if nx < 0 || nx >= width || ny < 0 || ny >= height {
     174            1 :                         continue
     175              :                 }
     176              : 
     177            1 :                 neighborIdx := bm.Level.CoordToIndex(consts.Coord[consts.Tile]{X: consts.Tile(nx), Y: consts.Tile(ny)})
     178            1 :                 tile := bm.Tiles[neighborIdx]
     179            1 : 
     180              :                 // 歩行可能
     181            1 :                 if !tile.BlockPass {
     182            1 :                         return true
     183            1 :                 }
     184              :         }
     185              : 
     186            1 :         return false
     187              : }
     188              : 
     189              : // PlannerChain は階層データMetaPlanに対して適用する生成ロジックを保持する構造体
     190              : type PlannerChain struct {
     191              :         Starter   *InitialMapPlanner
     192              :         Planners  []MetaMapPlanner
     193              :         PlanData  MetaPlan
     194              :         Snapshots []Snapshot // フェーズごとのスナップショット
     195              :         Recording bool       // trueの場合、各フェーズ完了時にスナップショットを記録する
     196              : }
     197              : 
     198              : // NewPlannerChain はシード値を指定してプランナーチェーンを作成する
     199              : // シードが0の場合はランダムなシードを生成する
     200              : func NewPlannerChain(width consts.Tile, height consts.Tile, seed uint64) *PlannerChain {
     201            1 :         tileCount := int(width) * int(height)
     202            1 :         tiles := make([]rawschema.Tile, tileCount)
     203            1 : 
     204              :         // シードが0の場合はランダムなシードを生成
     205            1 :         if seed == 0 {
     206            1 :                 seed = uint64(time.Now().UnixNano())
     207            1 :         }
     208              : 
     209            1 :         return &PlannerChain{
     210            1 :                 Starter:  nil,
     211            1 :                 Planners: []MetaMapPlanner{},
     212            1 :                 PlanData: MetaPlan{
     213            1 :                         Level: gc.Level{
     214            1 :                                 TileWidth:  width,
     215            1 :                                 TileHeight: height,
     216            1 :                         },
     217            1 :                         Tiles:       tiles,
     218            1 :                         Rooms:       []gc.Rect{},
     219            1 :                         Corridors:   [][]gc.TileIdx{},
     220            1 :                         RNG:         rand.New(rand.NewPCG(seed, seed+1)),
     221            1 :                         NextPortals: []consts.Coord[consts.Tile]{},
     222            1 :                         NPCs:        []NPCSpec{},
     223            1 :                         Items:       []ItemSpec{},
     224            1 :                         Props:       []PropsSpec{},
     225            1 :                         Doors:       []DoorSpec{},
     226            1 :                 },
     227            1 :         }
     228              : }
     229              : 
     230              : // StartWith は初期プランナーを設定する
     231              : func (b *PlannerChain) StartWith(initialMapPlanner InitialMapPlanner) {
     232            1 :         b.Starter = &initialMapPlanner
     233            1 : }
     234              : 
     235              : // With はメタプランナーを追加する
     236              : func (b *PlannerChain) With(metaMapPlanner MetaMapPlanner) {
     237            1 :         b.Planners = append(b.Planners, metaMapPlanner)
     238            1 : }
     239              : 
     240              : // Plan はプランナーチェーンを実行してマップを生成する
     241              : func (b *PlannerChain) Plan() error {
     242            1 :         if b.Starter == nil {
     243            0 :                 return fmt.Errorf("empty starter planner")
     244            0 :         }
     245            1 :         if b.PlanData.NeedsGround && b.PlanData.Ground == "" {
     246            1 :                 return ErrGroundNotSet
     247            1 :         }
     248            1 :         if err := (*b.Starter).PlanInitial(&b.PlanData); err != nil {
     249            0 :                 return fmt.Errorf("PlanInitial failed: %w", err)
     250            0 :         }
     251            1 :         b.takeSnapshot("Initial")
     252            1 : 
     253            1 :         for _, meta := range b.Planners {
     254            1 :                 if err := meta.PlanMeta(&b.PlanData); err != nil {
     255            1 :                         return fmt.Errorf("PlanMeta failed: %w", err)
     256            1 :                 }
     257            1 :                 b.takeSnapshot(plannerName(meta))
     258              :         }
     259            1 :         return nil
     260              : }
     261              : 
     262              : // plannerName はMetaMapPlannerの型名を返す
     263              : func plannerName(p MetaMapPlanner) string {
     264            1 :         t := reflect.TypeOf(p)
     265            1 :         if t.Kind() == reflect.Pointer {
     266            1 :                 t = t.Elem()
     267            1 :         }
     268            1 :         return t.Name()
     269              : }
     270              : 
     271              : // InitialMapPlanner は初期マップをプランするインターフェース
     272              : // タイルへの描画は行わず、構造体フィールドの値を初期化するだけ
     273              : type InitialMapPlanner interface {
     274              :         PlanInitial(*MetaPlan) error
     275              : }
     276              : 
     277              : // MetaMapPlanner はメタ情報をプランするインターフェース
     278              : type MetaMapPlanner interface {
     279              :         PlanMeta(*MetaPlan) error
     280              : }
     281              : 
     282              : // SpawnEntry はスポーン対象のエントリを表す。
     283              : type SpawnEntry struct {
     284              :         Name   string
     285              :         Weight float64
     286              :         Pack   consts.Dice // 1山あたりの個数
     287              : }
     288              : 
     289              : // PackSize はダイス表記からパックサイズを抽選する
     290              : func (e SpawnEntry) PackSize(rng *rand.Rand) int {
     291            1 :         return e.Pack.Roll(rng)
     292            1 : }
     293              : 
     294              : // PlannerType はマップ生成の設定を表す構造体
     295              : type PlannerType struct {
     296              :         // プランナー名
     297              :         Name string
     298              :         // 敵テーブル名。RawMasterから敵エントリを解決する際に使用する
     299              :         EnemyTableName string
     300              :         // アイテムテーブル名。RawMasterからアイテムエントリを解決する際に使用する
     301              :         ItemTableName string
     302              :         // フロアに置く敵の数
     303              :         EnemyCount rawschema.RandInt
     304              :         // フロアに置くアイテムの数
     305              :         ItemCount rawschema.RandInt
     306              :         // 危険度。敵やアイテムのフィルタリングに使用する。1以上であること。
     307              :         Danger consts.Danger
     308              :         // 地面を埋める下地のタイル。地上と森の間取りが使い、空ならエラーにする
     309              :         Ground string
     310              :         // プランナー関数。間取りの行は raws から引く
     311              :         PlannerFunc func(raws rawschema.Raws, width consts.Tile, height consts.Tile, seed uint64) (*PlannerChain, error)
     312              : }
     313              : 
     314              : var (
     315              :         // PlannerTypeRandom はランダム選択用のプランナータイプ
     316              :         PlannerTypeRandom = PlannerType{
     317              :                 Name:        "Random",
     318              :                 PlannerFunc: NewRandomPlanner,
     319              :         }
     320              : 
     321              :         // PlannerTypeOverworldField はシームレスワールドの開けた地形チャンクのプランナータイプ。
     322              :         // 通行可能がデフォルトで障壁は例外。チャンクを継いでも東西通行が保証される。
     323              :         // 下地は区分ごとに決まるので持たない。使う側が Ground を補わないと ErrGroundNotSet になる。
     324              :         PlannerTypeOverworldField = PlannerType{
     325              :                 Name: "Overworld Field",
     326              :                 PlannerFunc: func(_ rawschema.Raws, width, height consts.Tile, seed uint64) (*PlannerChain, error) {
     327            1 :                         return NewOverworldFieldPlanner(width, height, seed)
     328            1 :                 },
     329              :         }
     330              : )
     331              : 
     332              : // NewRandomPlanner は絵を使わない間取りの行からシード値で1つ選び、その間取りのチェーンを作成する
     333              : func NewRandomPlanner(raws rawschema.Raws, width consts.Tile, height consts.Tile, seed uint64) (*PlannerChain, error) {
     334              :         // シードが0の場合はランダムなシードを生成する。後続のビルダーに渡される
     335            1 :         if seed == 0 {
     336            0 :                 seed = uint64(time.Now().UnixNano())
     337            0 :         }
     338            1 :         candidates := proceduralLayoutIDs(raws)
     339            1 :         if len(candidates) == 0 {
     340            0 :                 return nil, fmt.Errorf("random planner selection error: %w", ErrNoLayout)
     341            0 :         }
     342            1 :         rng := rand.New(rand.NewPCG(seed, 0))
     343            1 :         chain, err := newLayoutChain(raws, candidates[rng.IntN(len(candidates))], width, height, seed)
     344            1 :         if err != nil {
     345            0 :                 return nil, fmt.Errorf("random planner selection error: %w", err)
     346            0 :         }
     347            1 :         return chain, nil
     348              : }
     349              : 
     350              : // selectSpawnEntry はSpawnEntryリストから重み付き抽選で1つ選択する
     351              : func selectSpawnEntry(entries []SpawnEntry, rng *rand.Rand) (SpawnEntry, bool) {
     352            2 :         i, ok := consts.Pick(rng, entries, func(e SpawnEntry) float64 { return e.Weight })
     353            1 :         if !ok {
     354            0 :                 return SpawnEntry{}, false
     355            0 :         }
     356            1 :         return entries[i], true
     357              : }
     358              : 
     359              : // selectRoom は部屋リストから面積で重み付けして1つ選択し、部屋とそのインデックスを返す
     360              : // 大きな部屋ほど選ばれやすくなり、配置可能タイル数に比例した自然な分布になる
     361              : func (bm *MetaPlan) selectRoom() (gc.Rect, int, bool) {
     362            1 :         i, ok := consts.Pick(bm.RNG, bm.Rooms, func(r gc.Rect) float64 {
     363            1 :                 w, h := int(r.Width()), int(r.Height())
     364            1 :                 if w <= 0 || h <= 0 {
     365            0 :                         return 0
     366            0 :                 }
     367            1 :                 return float64(w * h)
     368              :         })
     369            1 :         if !ok {
     370            0 :                 return gc.Rect{}, 0, false
     371            0 :         }
     372            1 :         return bm.Rooms[i], i, true
     373              : }
     374              : 
     375              : // randomPositionInRoom は指定した部屋内からスポーン可能なランダム座標を探す
     376              : // maxAttemptsを超えても見つからない場合はfalseを返す
     377              : func (bm *MetaPlan) randomPositionInRoom(room gc.Rect, world w.World, maxAttempts int) (consts.Tile, consts.Tile, bool) {
     378            1 :         rw, rh := int(room.Width()), int(room.Height())
     379            1 :         if rw <= 0 || rh <= 0 {
     380            0 :                 return 0, 0, false
     381            0 :         }
     382            1 :         for range maxAttempts {
     383            1 :                 tx := consts.Tile(int(room.Min.X) + bm.RNG.IntN(rw))
     384            1 :                 ty := consts.Tile(int(room.Min.Y) + bm.RNG.IntN(rh))
     385            1 :                 if bm.IsSpawnableTile(world, tx, ty) {
     386            1 :                         return tx, ty, true
     387            1 :                 }
     388              :         }
     389            0 :         return 0, 0, false
     390              : }
     391              : 
     392              : // randomPositionNear は指定座標の近く、かつ部屋内からスポーン可能なランダム座標を探す。
     393              : // 大部屋でクラスタメンバーを密集させるために使用する
     394              : func (bm *MetaPlan) randomPositionNear(centerX, centerY consts.Tile, radius int, room gc.Rect, world w.World, maxAttempts int) (consts.Tile, consts.Tile, bool) {
     395            1 :         for range maxAttempts {
     396            1 :                 dx := bm.RNG.IntN(radius*2+1) - radius
     397            1 :                 dy := bm.RNG.IntN(radius*2+1) - radius
     398            1 :                 tx := consts.Tile(int(centerX) + dx)
     399            1 :                 ty := consts.Tile(int(centerY) + dy)
     400            1 :                 if tx < room.Min.X || tx > room.Max.X || ty < room.Min.Y || ty > room.Max.Y {
     401            1 :                         continue
     402              :                 }
     403            1 :                 if bm.IsSpawnableTile(world, tx, ty) {
     404            1 :                         return tx, ty, true
     405            1 :                 }
     406              :         }
     407            1 :         return 0, 0, false
     408              : }
     409              : 
     410              : // GetTile はタイルを生成する
     411              : // TODO: エラーを潰しているだけなので直す
     412              : func (bm *MetaPlan) GetTile(name string) rawschema.Tile {
     413            1 :         if name == maptemplate.GroundTerrain {
     414            1 :                 name = bm.Ground
     415            1 :         }
     416            1 :         if bm.RawMaster == nil {
     417            1 :                 panic("RawMaster is not set; tile generation from TOML is required")
     418              :         }
     419            1 :         tile, err := raw.GetTile(*bm.RawMaster, name)
     420            1 :         if err != nil {
     421            1 :                 panic(fmt.Sprintf("tile generation error: %v", err))
     422              :         }
     423            1 :         return tile
     424              : }
     425              : 
     426              : // isInAnyRoom は指定座標がいずれかの部屋内に含まれるかを判定する
     427              : func (bm *MetaPlan) isInAnyRoom(x, y consts.Tile) bool {
     428            1 :         for _, room := range bm.Rooms {
     429            1 :                 if x >= room.Min.X && x <= room.Max.X && y >= room.Min.Y && y <= room.Max.Y {
     430            1 :                         return true
     431            1 :                 }
     432              :         }
     433            1 :         return false
     434              : }
     435              : 
     436              : // GetPlayerStartPosition はプレイヤーの開始位置を取得する
     437              : // ポータルへの到達性も確認し、到達可能な位置を返す
     438              : func (bm *MetaPlan) GetPlayerStartPosition() (consts.Coord[consts.Tile], error) {
     439            1 :         return NewPathFinder(bm).FindPlayerStartPosition()
     440            1 : }
        

Generated by: LCOV version 2.0-1