Line data Source code
1 : package overworld
2 :
3 : import (
4 : "fmt"
5 : "math/rand/v2"
6 : "slices"
7 :
8 : gc "github.com/kijimaD/ruins/internal/components"
9 : "github.com/kijimaD/ruins/internal/consts"
10 : "github.com/kijimaD/ruins/internal/maptemplate"
11 : "github.com/kijimaD/ruins/internal/raw"
12 : "github.com/kijimaD/ruins/internal/rawschema"
13 : w "github.com/kijimaD/ruins/internal/world"
14 : "github.com/kijimaD/ruins/internal/world/lifecycle"
15 : "github.com/kijimaD/ruins/internal/world/query"
16 : "github.com/mlange-42/ark/ecs"
17 : )
18 :
19 : // 区域の各チャンクは、自分の建物を区域の seed と区域の中の座標から独立に決める。
20 : // 街路は各チャンクの北辺・西辺に敷き、隣接チャンクと連続して格子状の街並みになる。
21 : const urbanStreetW consts.Tile = 4 // チャンクの北辺・西辺の街路の幅。2車線+歩道ぶん
22 :
23 : // urbanFeature は市街地の feature 実装。
24 : type urbanFeature struct{}
25 :
26 : // urbanEnemyTableFor は施設行の enemyTable が指す敵テーブルを返す。
27 : func urbanEnemyTableFor(raws rawschema.Raws, fac string) (rawschema.EnemyTable, error) {
28 1 : f, ok := raw.GetFacility(raws, fac)
29 1 : if !ok {
30 1 : return rawschema.EnemyTable{}, fmt.Errorf("urban enemy table: facility %q not found", fac)
31 1 : }
32 1 : et, err := raw.GetEnemyTable(raws, f.EnemyTable)
33 1 : if err != nil {
34 1 : return rawschema.EnemyTable{}, fmt.Errorf("urban enemy table for facility %q: %w", fac, err)
35 1 : }
36 1 : return et, nil
37 : }
38 :
39 : // facilityWeight は施設の抽選重みと、規模と深さの足切り
40 : type facilityWeight struct {
41 : kind string
42 : weight int
43 : minSpan consts.Chunk
44 : minDanger consts.Danger
45 : }
46 :
47 : // zoneCatalog は地区ごとの施設抽選重み。
48 : type zoneCatalog map[rawschema.Zone][]facilityWeight
49 :
50 : // zoneCatalogFrom は facilities 行から地区ごとの施設抽選重みを導出する。
51 : func zoneCatalogFrom(raws rawschema.Raws) zoneCatalog {
52 1 : cat := make(zoneCatalog)
53 1 : for _, f := range raw.PtrSlice(raws.Facilities) {
54 1 : for _, z := range f.Zones {
55 1 : minDanger := consts.MinDanger
56 1 : if z.MinDanger != nil {
57 1 : minDanger = consts.Danger(*z.MinDanger)
58 1 : }
59 1 : cat[z.Zone] = append(cat[z.Zone], facilityWeight{kind: f.Id, weight: int(z.Weight), minSpan: consts.Chunk(z.MinSpan), minDanger: minDanger})
60 : }
61 : }
62 1 : return cat
63 : }
64 :
65 : // zoneChoiceShift は層の候補から地区を選ぶ、区域の seed のビットの位置
66 : const zoneChoiceShift = 32
67 :
68 : // zoneAt は区域の中の座標 l の地区を返す。並べ方で層を決め、層の候補から区域の seed で1つ選ぶ
69 : func (r districtRegion) zoneAt(l consts.Coord[consts.Chunk]) rawschema.Zone {
70 1 : zones := r.kind.Layers[r.layerAt(l)].Zones
71 1 : return zones[(r.seed>>zoneChoiceShift)%uint64(len(zones))]
72 1 : }
73 :
74 : // layerAt は区域の中の座標 l が属する層の添字を、区域の並べ方に従って返す
75 : func (r districtRegion) layerAt(l consts.Coord[consts.Chunk]) int {
76 1 : switch r.kind.Pattern {
77 : case rawschema.DistrictPatternRings:
78 1 : if inCore(l.X, l.Y, r.w, r.h) {
79 1 : return 1
80 1 : }
81 1 : return 0
82 : case rawschema.DistrictPatternRows:
83 1 : return rowsLayer(r.kind.Layers, l.Y, r.h)
84 : }
85 0 : return 0
86 : }
87 :
88 : // inCore は区域の中の座標が中心の層に入るかを返す。中心からの2倍座標のチェビシェフ距離が、短い辺から3を引いた値以下なら中心
89 : func inCore(lx, ly, cw, ch consts.Chunk) bool {
90 1 : dx := int(lx)*2 - int(cw-1)
91 1 : dy := int(ly)*2 - int(ch-1)
92 1 : if dx < 0 {
93 1 : dx = -dx
94 1 : }
95 1 : if dy < 0 {
96 1 : dy = -dy
97 1 : }
98 1 : return max(dx, dy) <= int(min(cw, ch))-3
99 : }
100 :
101 : // rowsLayer は高さ ch の区域の行 ly が属する層の添字を返す。行の数を省いた層より前の層は南の端から、
102 : // 後ろの層は北の端から順に行を占め、残りの行を行の数を省いた層が占める
103 : func rowsLayer(layers []rawschema.DistrictLayer, ly, ch consts.Chunk) int {
104 2 : rest := slices.IndexFunc(layers, func(l rawschema.DistrictLayer) bool { return l.Rows == nil })
105 1 : fromSouth := int(ch - 1 - ly)
106 1 : for i := range rest {
107 1 : if fromSouth < *layers[i].Rows {
108 1 : return i
109 1 : }
110 1 : fromSouth -= *layers[i].Rows
111 : }
112 1 : fromNorth := int(ly)
113 1 : for i := len(layers) - 1; i > rest; i-- {
114 1 : if fromNorth < *layers[i].Rows {
115 1 : return i
116 1 : }
117 1 : fromNorth -= *layers[i].Rows
118 : }
119 1 : return rest
120 : }
121 :
122 : // rollFacilityInZone は地区の重み表から、規模 span と危険度 danger の足切りを通った施設 id を重みで抽選する。exclude の施設は引かない
123 : func rollFacilityInZone(rng *rand.Rand, cat zoneCatalog, z rawschema.Zone, span consts.Chunk, danger consts.Danger, exclude string) string {
124 1 : zc := cat[z]
125 1 : i, ok := consts.Pick(rng, zc, func(f facilityWeight) float64 {
126 1 : if span < f.minSpan || danger < f.minDanger || f.kind == exclude {
127 1 : return 0
128 1 : }
129 1 : return float64(f.weight)
130 : })
131 1 : if !ok {
132 : // 一番小さく浅い区域でも各地区に建てられる基本施設があることを raw の検証が保証する
133 0 : panic("rollFacilityInZone: zone has no facility within span and danger")
134 : }
135 1 : return zc[i].kind
136 : }
137 :
138 : // urbanFacilityAt は区域 r の中のチャンク c に建つ施設 id を返す。地図表示と生成の両方が使う。
139 : func urbanFacilityAt(raws rawschema.Raws, cat zoneCatalog, r districtRegion, c consts.Coord[consts.Chunk], spawnRow consts.Chunk) string {
140 1 : return lotAt(lotsOf(raws, cat, r, spawnRow), r.local(c)).facility
141 1 : }
142 :
143 : // place は c が市街地の建物チャンクなら自分の建物を描く。各チャンクは自己完結するので
144 : // 生成順に依存しない。
145 : func (urbanFeature) place(world w.World, runSeed uint64, c consts.Coord[consts.Chunk], cols consts.Chunk, g chunkGeom) error {
146 1 : raws := world.Resources.RawMaster
147 1 : r, ok := districtAt(raws, runSeed, c, cols, spawnRowOf(world))
148 1 : if !ok {
149 1 : return nil
150 1 : }
151 1 : l := r.local(c)
152 1 : lots := lotsOf(raws, zoneCatalogFrom(raws), r, spawnRowOf(world))
153 1 : lot := lotAt(lots, l)
154 1 : var fence []consts.Coord[consts.Tile]
155 1 : fenceProp := ""
156 1 : if r.kind.Fence != nil {
157 1 : north, south := gateColumns(r, lots)
158 1 : fence = districtFence(r, l, g.chunkW, g.chunkH, north-r.anchor.X, south-r.anchor.X)
159 1 : fenceProp = *r.kind.Fence
160 1 : }
161 1 : enemies, err := consts.ParseDice(r.kind.StreetEnemies)
162 1 : if err != nil {
163 0 : return fmt.Errorf("district %q street enemies: %w", r.kind.Id, err)
164 0 : }
165 1 : return renderUrbanChunk(world, g, ChunkSeed2D(r.seed, l.X, l.Y), enemies, lot, l.Sub(lot.anchor), urbanDangerAt(world, c), fence, fenceProp, streetTilesOf(r.kind))
166 : }
167 :
168 : // gateColumns は塀を巡らせる区域 r の、北と南の門を開ける絶対チャンク列を、区域を埋めた区画 lots から返す。
169 : // 真ん中の列を覆う区画の西の端の列で、区画の西の帯は街路なので、門から区域の中の街路へ入れる
170 : func gateColumns(r districtRegion, lots []buildingLot) (north, south consts.Chunk) {
171 1 : north = lotAt(lots, consts.Coord[consts.Chunk]{X: r.w / 2, Y: 0}).anchor.X
172 1 : south = lotAt(lots, consts.Coord[consts.Chunk]{X: r.w / 2, Y: r.h - 1}).anchor.X
173 1 : return r.anchor.X + north, r.anchor.X + south
174 1 : }
175 :
176 : // districtFence は区域の中のチャンク l に置く塀のマスを、チャンク内の座標で返す。塀は区域の外周を巡り、
177 : // 区域の中の列 northGate と southGate の北と南の端に、街路の幅だけ門を開ける。東と南の辺には街路が無いので、
178 : // 建物の区画の外側の1列に置く
179 : func districtFence(r districtRegion, l consts.Coord[consts.Chunk], chunkW, chunkH consts.Tile, northGate, southGate consts.Chunk) []consts.Coord[consts.Tile] {
180 1 : northOpen := l.X == northGate && l.Y == 0
181 1 : southOpen := l.X == southGate && l.Y == r.h-1
182 1 : var out []consts.Coord[consts.Tile]
183 1 : add := func(x, y consts.Tile) {
184 1 : if ((northOpen && y == 0) || (southOpen && y == chunkH-1)) && x < urbanStreetW {
185 1 : return
186 1 : }
187 1 : out = append(out, consts.Coord[consts.Tile]{X: x, Y: y})
188 : }
189 1 : for y := range chunkH {
190 1 : for x := range chunkW {
191 1 : west := x == 0 && l.X == 0
192 1 : east := x == chunkW-1 && l.X == r.w-1
193 1 : north := y == 0 && l.Y == 0
194 1 : south := y == chunkH-1 && l.Y == r.h-1
195 1 : if west || east || north || south {
196 1 : add(x, y)
197 1 : }
198 : }
199 : }
200 1 : return out
201 : }
202 :
203 : // urbanDangerAt はチャンクの敵抽選に使う危険度を返す。北進度(空間)と日数(時間)の高い方。
204 : // c.Y は絶対チャンク行なので consts.NorthDepth へそのまま渡せ、生成の再訪一致を壊さない。
205 : func urbanDangerAt(world w.World, c consts.Coord[consts.Chunk]) consts.Danger {
206 1 : danger := query.DangerLevelAt(world)
207 1 : if sb := query.GetSeamlessBand(world); sb != nil {
208 1 : if d := query.DangerLevelForDepth(consts.NorthDepth(sb.SpawnChunkY(), c.Y)); d > danger {
209 1 : danger = d
210 1 : }
211 : }
212 1 : return danger
213 : }
214 :
215 : // renderUrbanChunk は1チャンクに街路と施設の絵と塀を置き、街路に enemies 体の敵を湧かせる。塀はチャンク内の座標と家具 fenceProp で受ける
216 : func renderUrbanChunk(world w.World, g chunkGeom, seed uint64, enemies consts.Dice, lot buildingLot, l consts.Coord[consts.Chunk], danger consts.Danger, fence []consts.Coord[consts.Tile], fenceProp string, streets streetTiles) error {
217 : // ストリーム識別子 0x2 は建物幾何と敵配置。施設抽選の 0x1、施設の絵の 0x3 と分けて相互干渉を避ける
218 1 : rng := rand.New(rand.NewPCG(seed, 0x2))
219 1 : loader, err := maptemplate.FacilityTemplates()
220 1 : if err != nil {
221 0 : return fmt.Errorf("failed to load facility templates: %w", err)
222 0 : }
223 1 : cells, origin, err := planUrbanChunk(world.Resources.RawMaster, loader, lot, l, g.chunkW, g.chunkH, seed, rng, streets)
224 1 : if err != nil {
225 0 : return err
226 0 : }
227 1 : if origin != 0 {
228 1 : if err := drawUrbanStreets(world, g, streets); err != nil {
229 0 : return err
230 0 : }
231 : }
232 1 : isWall, occupied, err := spawnFacility(world, g, cells, origin, origin, lot.facility, danger, seed)
233 1 : if err != nil {
234 0 : return err
235 0 : }
236 1 : fac := lot.facility
237 1 : for _, p := range fence {
238 1 : pos := consts.Coord[consts.Tile]{X: g.offsetX + p.X, Y: g.offsetY + p.Y}
239 1 : occupied[pos] = true
240 1 : // 建物の外壁が敷地の外周に来れば、外壁を塀の代わりにする
241 1 : if isWall(p.X, p.Y) || slices.ContainsFunc(query.GetEntitiesAt(world, pos.X, pos.Y), world.Components.Prop.Has) {
242 1 : continue
243 : }
244 1 : if _, err := lifecycle.SpawnProp(world, fenceProp, pos.X, pos.Y); err != nil {
245 0 : return fmt.Errorf("failed to place district fence at %d,%d: %w", pos.X, pos.Y, err)
246 0 : }
247 : }
248 1 : return spawnUrbanEnemies(world, g, rng, enemies, fac, danger, isWall, occupied)
249 : }
250 :
251 : // planUrbanChunk は区画 lot の中の座標 l のチャンクに置くマスと、マスを置くチャンク内の原点を返す。部屋の絵を持つ施設は
252 : // 部屋と帯でチャンク全体を組み、それ以外は街路の帯の内側に1棟の絵を置く。厚い壁の塊の内側は虚空にする
253 : func planUrbanChunk(raws rawschema.Raws, loader *maptemplate.TemplateLoader, lot buildingLot, l consts.Coord[consts.Chunk], chunkW, chunkH consts.Tile, seed uint64, rng *rand.Rand, streets streetTiles) ([][]maptemplate.MapCell, consts.Tile, error) {
254 1 : isTall, blocks := tileIsTall(raws), tileBlocksPass(raws)
255 1 : if loader.HasRooms(lot.facility) {
256 1 : cells, err := roomChunkCells(loader, lot, l, chunkW, chunkH, streets, isTall)
257 1 : if err != nil {
258 0 : return nil, 0, fmt.Errorf("failed to plan facility %q room: %w", lot.facility, err)
259 0 : }
260 : // 区画の東と南の外だけが隣の区画の街路で、ほかの外は隣の部屋の壁か帯
261 1 : w, h := int(chunkW), int(chunkH)
262 1 : voidEnclosedTall(cells, blocks, isTall, func(x, y int) bool {
263 1 : return x >= w && l.X == lot.w-1 || y >= h && l.Y == lot.h-1
264 1 : })
265 1 : return cells, 0, nil
266 : }
267 1 : cells, err := planFacility(loader, lot.facility, rand.New(rand.NewPCG(seed, 0x3)).Uint64(), rng)
268 1 : if err != nil {
269 0 : return nil, 0, fmt.Errorf("failed to plan facility %q: %w", lot.facility, err)
270 0 : }
271 : // 1棟の絵は街路の帯に囲まれるので、絵の外は通れるものとして数える
272 1 : voidEnclosedTall(cells, blocks, isTall, func(int, int) bool { return true })
273 1 : return cells, urbanStreetW, nil
274 : }
275 :
276 : // drawUrbanStreets はチャンクの北辺と西辺に街路を描く。建物区画のタイルは建物の生成が描くので触らない
277 : func drawUrbanStreets(world w.World, g chunkGeom, streets streetTiles) error {
278 1 : tiles := g.tiles.get()
279 1 : for ly := range g.chunkH {
280 1 : for lx := range g.chunkW {
281 1 : if lx >= urbanStreetW && ly >= urbanStreetW {
282 1 : continue
283 : }
284 1 : if _, err := replaceTile(world, tiles, consts.Coord[consts.Tile]{X: g.offsetX + lx, Y: g.offsetY + ly}, streetTerrain(lx, ly, streets)); err != nil {
285 0 : return fmt.Errorf("failed to place urban street (x=%d, y=%d): %w", g.offsetX+lx, g.offsetY+ly, err)
286 0 : }
287 : }
288 : }
289 1 : return nil
290 : }
291 :
292 : // streetTiles は区域の街路に置くタイル。verge が空なら植え込みを置かない
293 : type streetTiles struct {
294 : street string
295 : verge string
296 : }
297 :
298 : // streetTilesOf は区域の行から街路に置くタイルを組む
299 : func streetTilesOf(d *rawschema.District) streetTiles {
300 1 : s := streetTiles{street: d.Street}
301 1 : if d.Verge != nil {
302 1 : s.verge = *d.Verge
303 1 : }
304 1 : return s
305 : }
306 :
307 : // streetTerrain は街路の帯のマス (x, y) に置くタイルを返す。植え込みがあれば帯の両端の1マスを植え込みにして、
308 : // 建物と道の間を空ける。北と西の帯が交わる角は全て街路にする
309 : func streetTerrain(x, y consts.Tile, s streetTiles) string {
310 2 : edge := func(v consts.Tile) bool { return v == 0 || v == urbanStreetW-1 }
311 1 : switch {
312 : case s.verge == "" || x < urbanStreetW && y < urbanStreetW:
313 1 : return s.street
314 : case y < urbanStreetW && edge(y), x < urbanStreetW && edge(x):
315 1 : return s.verge
316 : }
317 1 : return s.street
318 : }
319 :
320 : // spawnUrbanEnemies はチャンクに敵を enemies 体湧かせる。種類は敵テーブルから危険度で重み抽選する。
321 : // 壁マスに埋まる位置は避ける。危険度は呼び出し側が北進度と日数から決める。
322 : func spawnUrbanEnemies(world w.World, g chunkGeom, rng *rand.Rand, enemies consts.Dice, fac string, danger consts.Danger, isWall func(lx, ly consts.Tile) bool, occupied map[consts.Coord[consts.Tile]]bool) error {
323 1 : enemyTable, err := urbanEnemyTableFor(world.Resources.RawMaster, fac)
324 1 : if err != nil {
325 0 : return fmt.Errorf("failed to get urban enemy table: %w", err)
326 0 : }
327 : // 敵種別は危険度でフィルタし、北へ進むほど・日が進むほど強敵が出る。
328 1 : count := enemies.Roll(rng)
329 1 : for range count {
330 1 : enemyName, err := raw.SelectEnemyByWeight(enemyTable, rng, int(danger))
331 1 : if err != nil {
332 0 : return fmt.Errorf("failed to select urban enemy: %w", err)
333 0 : }
334 1 : if enemyName == "" {
335 0 : continue // 危険度帯に該当する敵がいなければこの1体は諦める
336 : }
337 : // 敵は街路に湧かせ、建物の footprint と壁の上は避ける。占有は footprint 全域に及ぶので、一度引いて
338 : // 塞がっていたら目標数を満たすよう空きが出るまで位置を引き直す。試行を尽くしても空かなければその
339 : // 1体は諦める。抽選順は固定なので同じ seed なら同じ結果になる
340 1 : for range urbanSpawnTries {
341 1 : lx := consts.Tile(rng.IntN(int(g.chunkW)))
342 1 : ly := consts.Tile(rng.IntN(int(g.chunkH)))
343 1 : pos := consts.Coord[consts.Tile]{X: g.offsetX + lx, Y: g.offsetY + ly}
344 1 : if isWall(lx, ly) || occupied[pos] {
345 1 : continue
346 : }
347 1 : if _, err := lifecycle.SpawnEnemy(world, pos, enemyName); err != nil {
348 0 : return fmt.Errorf("failed to place urban enemy: %w", err)
349 0 : }
350 1 : break
351 : }
352 : }
353 1 : return nil
354 : }
355 :
356 : // urbanSpawnTries は敵1体あたり街路の空きタイルを探す最大試行数。建物が footprint 全域を占有し有効タイルが
357 : // 減るので、数回の引き直しで目標数をほぼ満たせるだけの余裕を持たせる。
358 : const urbanSpawnTries = 24
359 :
360 : // tileIndex はチャンク生成中に地物が共有するタイルの座標引き索引。地物が壁や道を置換する
361 : // とき使う。最初に必要とした地物が全域スキャンで構築し、以降の地物は再利用する。壁を置かない
362 : // 荒れ地では一度も構築されず、全域スキャンの無駄を避ける。replaceTile が置換後の実体を書き
363 : // 戻すので、地物をまたいでも索引は実状態を映し続け、二重残留を防ぐ。
364 : type tileIndex struct {
365 : world w.World
366 : loX, hiX consts.Tile
367 : tiles map[gc.GridElement]ecs.Entity
368 : }
369 :
370 : // get は索引を返す。未構築なら遅延構築する。壁を置く地物が現れて初めてスキャンが走る。
371 : func (ix *tileIndex) get() map[gc.GridElement]ecs.Entity {
372 1 : if ix.tiles == nil {
373 1 : ix.tiles = tileEntitiesInRange(ix.world, ix.loX, ix.hiX)
374 1 : }
375 1 : return ix.tiles
376 : }
377 :
378 : // tileEntitiesInRange は X 範囲 [loX, hiX) のタイルエンティティを座標引きできるよう集める。
379 : func tileEntitiesInRange(world w.World, loX, hiX consts.Tile) map[gc.GridElement]ecs.Entity {
380 1 : tiles := make(map[gc.GridElement]ecs.Entity)
381 1 : q := query.ActiveFilter2[gc.GridElement, gc.Tile](world).Query()
382 1 : for q.Next() {
383 1 : e := q.Entity()
384 1 : g := *world.Components.GridElement.Get(e)
385 1 : if g.X >= loX && g.X < hiX {
386 1 : tiles[g] = e
387 1 : }
388 : }
389 1 : return tiles
390 : }
391 :
392 : // replaceTile は座標のタイルを取り除き、tileName のタイルへ置き換える。
393 : // オートタイル添字は仮の 0 で置き、後段の RecalcAutotileInXRange が実状態から揃える。
394 : func replaceTile(world w.World, tiles map[gc.GridElement]ecs.Entity, pos consts.Coord[consts.Tile], tileName string) (ecs.Entity, error) {
395 1 : return replaceTileIndexed(world, tiles, pos, tileName, new(0))
396 1 : }
397 :
398 : // replaceTileIndexed は replaceTile と同じく置き換え、オートタイル添字 index を渡す。オートタイルしないタイルは nil を渡す
399 : func replaceTileIndexed(world w.World, tiles map[gc.GridElement]ecs.Entity, pos consts.Coord[consts.Tile], tileName string, index *int) (ecs.Entity, error) {
400 1 : g := gc.GridElement{Coord: pos}
401 1 : if e, ok := tiles[g]; ok && world.ECS.Alive(e) {
402 1 : world.ECS.RemoveEntity(e)
403 1 : }
404 1 : e, err := lifecycle.SpawnTile(world, tileName, pos.X, pos.Y, index)
405 1 : if err != nil {
406 0 : return ecs.Entity{}, err
407 0 : }
408 : // 置換後の実体を索引へ書き戻す。索引を地物間で共有するため、後続の地物が同じ座標を
409 : // 正しく再置換でき、旧タイルの二重残留を防ぐ。呼び出し側が実体へ属性を足せるよう返す
410 1 : tiles[g] = e
411 1 : return e, nil
412 : }
|