Line data Source code
1 : package mapspawner
2 :
3 : import (
4 : "errors"
5 : "fmt"
6 :
7 : gc "github.com/kijimaD/ruins/internal/components"
8 : "github.com/kijimaD/ruins/internal/consts"
9 : mapplanner "github.com/kijimaD/ruins/internal/mapplanner"
10 : "github.com/kijimaD/ruins/internal/raw"
11 : "github.com/kijimaD/ruins/internal/rawschema"
12 : w "github.com/kijimaD/ruins/internal/world"
13 :
14 : "github.com/kijimaD/ruins/internal/world/lifecycle"
15 : "github.com/mlange-42/ark/ecs"
16 : )
17 :
18 : var (
19 : // errUnsupportedTile は生成の仕様 spawn を持たないタイルを生成しようとしたときに返す
20 : errUnsupportedTile = errors.New("unsupported tile id")
21 : // errInvalidItemCount はアイテムの個数が0以下のときに返す
22 : errInvalidItemCount = errors.New("invalid item count")
23 : // errInvalidLootCount は収納propのルート数の表記が不正なときに返す
24 : errInvalidLootCount = errors.New("invalid lootCount notation")
25 : // errDrawLoot はルートテーブルからの抽選に失敗したときに返す
26 : errDrawLoot = errors.New("failed to draw item")
27 : )
28 :
29 : // Spawn はMetaPlanからレベルを生成する
30 : // タイル、NPC、Props、ワープポータル情報から効率的にエンティティを生成する
31 : func Spawn(world w.World, metaPlan *mapplanner.MetaPlan) (gc.Level, error) {
32 1 : return SpawnAt(world, metaPlan, 0, 0)
33 1 : }
34 :
35 : // SpawnAt は MetaPlan を offsetX, offsetY タイルずらして生成する。
36 : // オーバーワールドで、チャンクを帯の東スラブなど任意位置へ配置するために使う。
37 : // オフセットはエンティティ座標にのみ加算し、オートタイルや扉向きの判定は
38 : // プラン内ローカル座標、すなわち metaPlan.Tiles のインデックスで行うため影響しない。
39 : // 現状 offsetY は常に 0 で南北ストリーミングしない帯だが、将来の 2D 配置・対称性のため引数に残す。
40 : func SpawnAt(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) (gc.Level, error) {
41 1 : level := gc.Level{
42 1 : TileWidth: metaPlan.Level.TileWidth,
43 1 : TileHeight: metaPlan.Level.TileHeight,
44 1 : }
45 :
46 1 : if err := spawnTiles(world, metaPlan, offsetX, offsetY); err != nil {
47 1 : return gc.Level{}, err
48 1 : }
49 1 : if err := spawnNPCs(world, metaPlan, offsetX, offsetY); err != nil {
50 1 : return gc.Level{}, err
51 1 : }
52 1 : if err := spawnItems(world, metaPlan, offsetX, offsetY); err != nil {
53 1 : return gc.Level{}, err
54 1 : }
55 1 : if err := spawnProps(world, metaPlan, offsetX, offsetY); err != nil {
56 1 : return gc.Level{}, err
57 1 : }
58 1 : if err := spawnDoors(world, metaPlan, offsetX, offsetY); err != nil {
59 0 : return gc.Level{}, err
60 0 : }
61 1 : if err := spawnPortals(world, metaPlan, offsetX, offsetY); err != nil {
62 0 : return gc.Level{}, err
63 0 : }
64 :
65 1 : return level, nil
66 : }
67 :
68 : // spawnTiles はタイルからエンティティを生成する
69 : func spawnTiles(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
70 1 : for _i := range metaPlan.Tiles {
71 1 : tile := &metaPlan.Tiles[_i]
72 1 : i := gc.TileIdx(_i)
73 1 : pos := metaPlan.Level.IndexToCoord(i)
74 1 : tileX, tileY := pos.X+offsetX, pos.Y+offsetY
75 1 :
76 1 : tileEntity, err := spawnTile(world, metaPlan, *tile, i, tileX, tileY)
77 1 : if err != nil {
78 1 : return fmt.Errorf("failed to spawn tile entity (%d, %d): %w", int(pos.X), int(pos.Y), err)
79 1 : }
80 :
81 1 : if metaPlan.Environments != nil && world.Components.TileEnvironment.Has(tileEntity) {
82 1 : *world.Components.TileEnvironment.Get(tileEntity) = metaPlan.Environments[i]
83 1 : }
84 : }
85 1 : return nil
86 : }
87 :
88 : // spawnTile は1タイルを生成する。タイルの行の spawn が生成するタイルとオートタイルの有無を持ち、
89 : // spawn を持たないタイルは計画に置けないので error にする。
90 : func spawnTile(world w.World, metaPlan *mapplanner.MetaPlan, tile rawschema.Tile, i gc.TileIdx, tileX, tileY consts.Tile) (ecs.Entity, error) {
91 1 : if tile.Spawn == nil {
92 1 : category := "walkable"
93 1 : if tile.BlockPass {
94 0 : category = "impassable"
95 0 : }
96 1 : return gc.InvalidEntity, fmt.Errorf("%w: %s %s (%d, %d)", errUnsupportedTile, category, tile.Id, int(tileX), int(tileY))
97 : }
98 1 : spawnName := tile.Id
99 1 : if tile.Spawn.Tile != nil {
100 1 : spawnName = *tile.Spawn.Tile
101 1 : }
102 :
103 : // オートタイル添字は tile.Id で計算する。生成するタイル spawnName とは別物。
104 1 : var indexPtr *int
105 1 : if tile.Spawn.Autotile {
106 1 : index := int(metaPlan.CalculateAutoTileIndex(i, tile.Id))
107 1 : indexPtr = &index
108 1 : }
109 1 : return lifecycle.SpawnTile(world, spawnName, tileX, tileY, indexPtr)
110 : }
111 :
112 : // spawnNPCs はNPCを生成する
113 : func spawnNPCs(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
114 1 : for _, npc := range metaPlan.NPCs {
115 1 : member, err := raw.FindMember(world.Resources.RawMaster, npc.Name)
116 1 : if err != nil {
117 1 : return fmt.Errorf("NPC %q: %w", npc.Name, err)
118 1 : }
119 :
120 1 : x, y := int(npc.X)+int(offsetX), int(npc.Y)+int(offsetY)
121 1 : if member.FactionType != nil && *member.FactionType == rawschema.FactionNeutral {
122 1 : _, err := lifecycle.SpawnNeutralNPC(world, consts.Coord[consts.Tile]{X: consts.Tile(x), Y: consts.Tile(y)}, npc.Name)
123 1 : if err != nil {
124 0 : return fmt.Errorf("failed to spawn neutral NPC (%d, %d): %w", x, y, err)
125 0 : }
126 : } else {
127 1 : _, err := lifecycle.SpawnEnemy(world, consts.Coord[consts.Tile]{X: consts.Tile(x), Y: consts.Tile(y)}, npc.Name)
128 1 : if err != nil {
129 0 : return fmt.Errorf("failed to spawn enemy NPC (%d, %d): %w", x, y, err)
130 0 : }
131 : }
132 : }
133 1 : return nil
134 : }
135 :
136 : // spawnItems はアイテムを生成する
137 : func spawnItems(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
138 1 : for _, item := range metaPlan.Items {
139 1 : tileX, tileY := item.X+offsetX, item.Y+offsetY
140 1 : if item.Count <= 0 {
141 1 : return fmt.Errorf("%w (%d, %d): count=%d", errInvalidItemCount, item.X, item.Y, item.Count)
142 1 : }
143 1 : _, err := lifecycle.SpawnFieldItem(world, item.Name, tileX, tileY, item.Count)
144 1 : if err != nil {
145 1 : return fmt.Errorf("failed to spawn item (%d, %d): %w", item.X, item.Y, err)
146 1 : }
147 : }
148 1 : return nil
149 : }
150 :
151 : // spawnProps はPropsを生成する
152 : func spawnProps(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
153 1 : poses, err := planPoses(metaPlan)
154 1 : if err != nil {
155 1 : return err
156 1 : }
157 1 : for _, prop := range metaPlan.Props {
158 1 : tileX, tileY := prop.X+offsetX, prop.Y+offsetY
159 1 :
160 1 : propRaw, err := raw.GetProp(*metaPlan.RawMaster, prop.Name)
161 1 : if err != nil {
162 0 : return fmt.Errorf("failed to get props (%s): %w", prop.Name, err)
163 0 : }
164 :
165 1 : propEntity, err := lifecycle.SpawnProp(world, prop.Name, tileX, tileY)
166 1 : if err != nil {
167 0 : return fmt.Errorf("failed to spawn props (%d, %d): %w", prop.X, prop.Y, err)
168 0 : }
169 :
170 1 : if f, ok := poses[consts.Coord[consts.Tile]{X: prop.X, Y: prop.Y}]; ok && propRaw.SpriteRender.HasShape(rawschema.Facing) {
171 1 : world.Components.Pose.Add(propEntity, &f)
172 1 : }
173 :
174 : // Door componentがあれば向きを設定して閉じた状態で初期化
175 1 : if propRaw.Door != nil {
176 1 : doorComp := world.Components.Door.Get(propEntity)
177 1 : doorComp.Orientation = detectPropDoorOrientation(metaPlan, int(prop.X), int(prop.Y))
178 1 : if err := lifecycle.CloseDoor(world, propEntity); err != nil {
179 0 : return fmt.Errorf("failed to initialize door (%d, %d): %w", prop.X, prop.Y, err)
180 0 : }
181 : }
182 :
183 : // Storage propにルートアイテムを格納する
184 1 : if propRaw.Storage != nil && propRaw.Storage.LootTableId != nil && *propRaw.Storage.LootTableId != "" {
185 1 : if err := populateStorageLoot(world, metaPlan, propEntity, propRaw); err != nil {
186 0 : return fmt.Errorf("failed to spawn container item (%d, %d): %w", prop.X, prop.Y, err)
187 0 : }
188 : }
189 : }
190 1 : return nil
191 : }
192 :
193 : // spawnDoors はドアを生成する
194 : func spawnDoors(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
195 1 : for _, door := range metaPlan.Doors {
196 1 : tileX, tileY := door.X+offsetX, door.Y+offsetY
197 1 : _, err := lifecycle.SpawnDoor(world, consts.Coord[consts.Tile]{X: tileX, Y: tileY}, door.Orientation)
198 1 : if err != nil {
199 0 : return fmt.Errorf("failed to spawn door (%d, %d): %w", door.X, door.Y, err)
200 0 : }
201 : }
202 1 : return nil
203 : }
204 :
205 : // spawnPortals はポータルを生成する
206 : func spawnPortals(world w.World, metaPlan *mapplanner.MetaPlan, offsetX, offsetY consts.Tile) error {
207 1 : for _, portal := range metaPlan.NextPortals {
208 1 : tileX, tileY := portal.X+offsetX, portal.Y+offsetY
209 1 : _, err := lifecycle.SpawnProp(world, "warp_next", tileX, tileY)
210 1 : if err != nil {
211 0 : return fmt.Errorf("failed to spawn NextPortal (%d, %d): %w", portal.X, portal.Y, err)
212 0 : }
213 : }
214 :
215 1 : return nil
216 : }
217 :
218 : // planPoses は計画の facing の置物ごとの置き方を返す
219 : func planPoses(metaPlan *mapplanner.MetaPlan) (map[consts.Coord[consts.Tile]]gc.Pose, error) {
220 1 : facers := map[consts.Coord[consts.Tile]]bool{}
221 1 : blockers := map[consts.Coord[consts.Tile]]bool{}
222 1 : for _, prop := range metaPlan.Props {
223 1 : propRaw, err := raw.GetProp(*metaPlan.RawMaster, prop.Name)
224 1 : if err != nil {
225 1 : return nil, fmt.Errorf("failed to get props (%s): %w", prop.Name, err)
226 1 : }
227 1 : c := consts.Coord[consts.Tile]{X: prop.X, Y: prop.Y}
228 1 : isFacing := propRaw.SpriteRender.HasShape(rawschema.Facing)
229 1 : if isFacing {
230 1 : facers[c] = true
231 1 : }
232 1 : blockers[c] = blockers[c] || isFacing || propRaw.BlockPass
233 : }
234 1 : width, height := metaPlan.Level.TileWidth, metaPlan.Level.TileHeight
235 1 : wall := func(c consts.Coord[consts.Tile]) bool {
236 1 : return c.X >= 0 && c.Y >= 0 && c.X < width && c.Y < height && metaPlan.Tiles[int(c.Y*width+c.X)].BlockPass
237 1 : }
238 1 : return mapplanner.RowPoses(facers, blockers, wall), nil
239 : }
240 :
241 : // detectPropDoorOrientation はpropsの扉の向きを隣接タイルから判定する。
242 : // DoorSpecを持たないprops扉専用で、左右が壁なら縦向き、それ以外は横向きを返す
243 : func detectPropDoorOrientation(metaPlan *mapplanner.MetaPlan, x, y int) gc.DoorOrientation {
244 1 : width := int(metaPlan.Level.TileWidth)
245 1 : height := int(metaPlan.Level.TileHeight)
246 1 :
247 1 : if x <= 0 || x >= width-1 || y <= 0 || y >= height-1 {
248 1 : return gc.DoorOrientationHorizontal
249 1 : }
250 :
251 1 : idx := y*width + x
252 1 : if metaPlan.Tiles[idx-1].BlockPass && metaPlan.Tiles[idx+1].BlockPass {
253 1 : return gc.DoorOrientationVertical
254 1 : }
255 :
256 1 : return gc.DoorOrientationHorizontal
257 : }
258 :
259 : // populateStorageLoot は収納propにルートテーブルからアイテムを格納する
260 : func populateStorageLoot(world w.World, metaPlan *mapplanner.MetaPlan, storageEntity ecs.Entity, propRaw rawschema.Prop) error {
261 1 : tableName := *propRaw.Storage.LootTableId
262 1 : itemTable, err := raw.GetItemTable(*metaPlan.RawMaster, tableName)
263 1 : if err != nil {
264 1 : return fmt.Errorf("failed to get ItemTable '%s': %w", tableName, err)
265 1 : }
266 :
267 : // ルート数はダイス表記で決める。省略時は1個
268 1 : lootDice := consts.Dice{Base: 1, Sides: 1}
269 1 : if propRaw.Storage.LootCount != nil {
270 1 : d, err := consts.ParseDice(*propRaw.Storage.LootCount)
271 1 : if err != nil {
272 1 : return fmt.Errorf("%w for container %q: %w", errInvalidLootCount, propRaw.Name, err)
273 1 : }
274 1 : lootDice = d
275 : }
276 1 : lootCount := lootDice.Roll(metaPlan.RNG)
277 1 :
278 : // 危険度は生成中フロアのプランから取る。
279 1 : danger := metaPlan.Danger
280 1 :
281 1 : for range lootCount {
282 1 : draws, err := raw.DrawFromItemTable(*metaPlan.RawMaster, itemTable, metaPlan.RNG, int(danger))
283 1 : if err != nil {
284 1 : return fmt.Errorf("%w: %w", errDrawLoot, err)
285 1 : }
286 1 : for _, d := range draws {
287 1 : if _, err := lifecycle.SpawnStorageItem(world, d.Name, d.Count, storageEntity); err != nil {
288 1 : return fmt.Errorf("failed to spawn item '%s': %w", d.Name, err)
289 1 : }
290 : }
291 : }
292 :
293 1 : return nil
294 : }
|