Line data Source code
1 : package lifecycle
2 :
3 : import (
4 : "errors"
5 : "fmt"
6 :
7 : gc "github.com/kijimaD/ruins/internal/components"
8 : "github.com/kijimaD/ruins/internal/consts"
9 : w "github.com/kijimaD/ruins/internal/world"
10 : "github.com/kijimaD/ruins/internal/world/query"
11 : "github.com/mlange-42/ark/ecs"
12 : )
13 :
14 : // MoveToBackpack はエンティティをバックパックに移動する。
15 : // 1個1エンティティなので統合はしない。同一スタックの束ねは表示側が stackKey で行う。
16 : func MoveToBackpack(world w.World, entity ecs.Entity, owner ecs.Entity) error {
17 1 : clearLocation(world, entity)
18 1 : world.Components.LocationInBackpack.Add(entity, &gc.LocationInBackpack{Owner: owner})
19 1 : ensureRemoved(world.Components.GridElement, entity)
20 1 : ensureMarker(world, world.Components.StatsChanged, owner, &gc.StatsChanged{})
21 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
22 1 : return nil
23 1 : }
24 :
25 : // TransferUnits は item が属するスタックのうち count 個を recipient のバックパックへ移す。
26 : // count が0以下、または在庫数以上ならスタックを丸ごと移す。1個1エンティティなので、
27 : // 同一スタックのエンティティを count 個選んで移すだけでよい。生成や分割は不要。
28 : func TransferUnits(world w.World, item ecs.Entity, recipient ecs.Entity, count int) error {
29 1 : members := query.StackMembers(world, item)
30 1 : move := count
31 1 : if count <= 0 || count >= len(members) {
32 1 : move = len(members)
33 1 : }
34 1 : if _, err := MoveMembersToBackpack(world, members[:move], recipient); err != nil {
35 0 : return fmt.Errorf("failed to transfer unit: %w", err)
36 0 : }
37 1 : return nil
38 : }
39 :
40 : // MoveStackToBackpack は rep と同一スタックを丸ごとバックパックへ移す。移せた個数を返す。
41 : // 同一スタックの実体は呼び出し時点の世界から束ね直す。前フレームの一覧から実体列を持ち越すと
42 : // 消えた実体が混ざりうるため、呼び出し側は代表だけを渡す
43 : func MoveStackToBackpack(world w.World, rep ecs.Entity, owner ecs.Entity) (int, error) {
44 1 : return MoveMembersToBackpack(world, query.StackMembers(world, rep), owner)
45 1 : }
46 :
47 : // MoveStackToStorage は rep と同一スタックを丸ごと収納へ移す。移せた個数を返す。
48 : // 容量判定は呼び出し側が事前に行う
49 : func MoveStackToStorage(world w.World, rep ecs.Entity, storage ecs.Entity) (int, error) {
50 1 : return MoveMembersToStorage(world, query.StackMembers(world, rep), storage)
51 1 : }
52 :
53 : // MoveStackToField は rep と同一スタックを丸ごと指定タイルへ落とす。移した個数を返す
54 : func MoveStackToField(world w.World, rep ecs.Entity, coord consts.Coord[consts.Tile], previousOwner ecs.Entity) int {
55 1 : return MoveMembersToField(world, query.StackMembers(world, rep), coord, previousOwner)
56 1 : }
57 :
58 : // MoveMembersToBackpack は members を全てバックパックへ移す。移せた個数を返す。
59 : // スタック丸ごとの移動は MoveStackTo* が代表から束ねて委譲する。実体列を直接受けるこの層は、
60 : // 部分移動や、スタックに限らない一括移動が使う。移動先の詳細だけをここに集約する。
61 : func MoveMembersToBackpack(world w.World, members []ecs.Entity, owner ecs.Entity) (int, error) {
62 1 : moved := 0
63 1 : var errs []error
64 1 : for _, member := range members {
65 1 : if err := MoveToBackpack(world, member, owner); err != nil {
66 0 : errs = append(errs, err)
67 0 : continue
68 : }
69 1 : moved++
70 : }
71 1 : return moved, errors.Join(errs...)
72 : }
73 :
74 : // MoveMembersToStorage は members を全て収納へ移す。移せた個数を返す。容量判定は呼び出し側が事前に行う。
75 : func MoveMembersToStorage(world w.World, members []ecs.Entity, storage ecs.Entity) (int, error) {
76 1 : moved := 0
77 1 : var errs []error
78 1 : for _, member := range members {
79 1 : if err := MoveToStorage(world, member, storage); err != nil {
80 0 : errs = append(errs, err)
81 0 : continue
82 : }
83 1 : moved++
84 : }
85 1 : return moved, errors.Join(errs...)
86 : }
87 :
88 : // MoveMembersToField は members を全て指定タイルへ落とす。各個体に GridElement を付け、床の同一スタックへ束ねる。
89 : // GridElement 付与を移動と対にしてここへ集約し、片方だけ忘れて床に出ないバグを防ぐ。移した個数を返す。
90 : func MoveMembersToField(world w.World, members []ecs.Entity, coord consts.Coord[consts.Tile], previousOwner ecs.Entity) int {
91 1 : for _, member := range members {
92 1 : MoveToField(world, member, &previousOwner)
93 1 : world.Components.GridElement.Add(member, &gc.GridElement{Coord: coord})
94 1 : }
95 1 : return len(members)
96 : }
97 :
98 : // MoveToEquip はエンティティを指定スロットに装備する
99 : func MoveToEquip(world w.World, entity ecs.Entity, owner ecs.Entity, slot gc.EquipmentSlotNumber) {
100 1 : clearLocation(world, entity)
101 1 : world.Components.LocationEquipped.Add(entity, &gc.LocationEquipped{
102 1 : Owner: owner,
103 1 : EquipmentSlot: slot,
104 1 : })
105 1 : ensureRemoved(world.Components.GridElement, entity)
106 1 : ensureMarker(world, world.Components.StatsChanged, owner, &gc.StatsChanged{})
107 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
108 1 : }
109 :
110 : // MoveToField はエンティティをフィールドに移動する。
111 : // previousOwnerは移動元の所有者で、nilでなければWeightDirtyマーカーを付与する。
112 : // 新規生成時など前のOwnerが存在しない場合はnilを渡す
113 : func MoveToField(world w.World, entity ecs.Entity, previousOwner *ecs.Entity) {
114 1 : clearLocation(world, entity)
115 1 : world.Components.LocationOnField.Add(entity, &gc.LocationOnField{})
116 1 : // フィールド配置ではGridElement(座標)を残す
117 1 : if previousOwner != nil {
118 1 : ensureMarker(world, world.Components.WeightDirty, *previousOwner, &gc.WeightDirty{})
119 1 : // 所有者からフィールドへ移す実行時の移送は現ステージに属す。すぐ現ステージへ束縛し、
120 : // 置いた物が総重量など現ステージのクエリに即座に乗るようにする。次の swap を待つ遅延束縛
121 : // では、内部で置いた物が退場するまで総重量に現れない。
122 : // 生成時のフィールド生成は previousOwner が nil で来るのでここを通らず、生成後の
123 : // stage.Bind に束縛を委ねる。生成中は CurrentStage がまだ旧ステージなので誤束縛を避ける。
124 1 : if d := query.GetDungeon(world); d != nil {
125 : // entity は直前に LocationOnField を付けたので生存が保証され、Upsert は失敗しない
126 1 : _ = gc.Upsert(world.ECS, world.Components.StageBound, entity, &gc.StageBound{Key: d.CurrentStage})
127 1 : }
128 : }
129 : }
130 :
131 : // SpillStorageItems は収納の中身をすべて指定タイルのフィールドへ落とす。
132 : // 収納エンティティを取り壊す前に呼び、中身が孤児化するのを防ぐ
133 : func SpillStorageItems(world w.World, storage ecs.Entity, x consts.Tile, y consts.Tile) {
134 : // クエリ走査中の構造変更を避けるため、先に集めてから移動する
135 1 : var items []ecs.Entity
136 1 : q := ecs.NewFilter1[gc.LocationInStorage](world.ECS).Query()
137 1 : for q.Next() {
138 1 : entity := q.Entity()
139 1 : if world.Components.LocationInStorage.Get(entity).Owner == storage {
140 1 : items = append(items, entity)
141 1 : }
142 : }
143 1 : for _, item := range items {
144 1 : world.Components.GridElement.Add(item, &gc.GridElement{Coord: consts.Coord[consts.Tile]{X: x, Y: y}})
145 1 : MoveToField(world, item, &storage)
146 1 : }
147 : }
148 :
149 : // MoveToStorage はエンティティを収納に移動する。
150 : // 1個1エンティティなので統合はしない。同一スタックの束ねは表示側が stackKey で行う。
151 : func MoveToStorage(world w.World, entity ecs.Entity, storage ecs.Entity) error {
152 1 : clearLocation(world, entity)
153 1 : world.Components.LocationInStorage.Add(entity, &gc.LocationInStorage{Owner: storage})
154 1 : ensureRemoved(world.Components.GridElement, entity)
155 1 : ensureMarker(world, world.Components.WeightDirty, storage, &gc.WeightDirty{})
156 1 : return nil
157 1 : }
158 :
159 : // UnequipAll はプレイヤーの装備中アイテムを全てバックパックに移動する
160 : func UnequipAll(world w.World, playerEntity ecs.Entity) error {
161 1 : var equipped []ecs.Entity
162 1 : equippedQuery := ecs.NewFilter1[gc.LocationEquipped](world.ECS).Query()
163 1 : for equippedQuery.Next() {
164 1 : entity := equippedQuery.Entity()
165 1 : loc := world.Components.LocationEquipped.Get(entity)
166 1 : if loc.Owner == playerEntity {
167 1 : equipped = append(equipped, entity)
168 1 : }
169 : }
170 :
171 1 : for _, item := range equipped {
172 1 : if err := MoveToBackpack(world, item, playerEntity); err != nil {
173 0 : return err
174 0 : }
175 : }
176 1 : return nil
177 : }
178 :
179 : // ensureMarker はマーカーコンポーネントを冪等に付与する。
180 : // エンティティが死亡している場合や既に付与済みの場合は何もしない。
181 : // Arkは死亡エンティティへの付与と二重付与でパニックするため、ここで吸収する
182 : func ensureMarker[T any](world w.World, comp *ecs.Map[T], entity ecs.Entity, data *T) {
183 1 : if !world.ECS.Alive(entity) {
184 0 : return
185 0 : }
186 1 : if !comp.Has(entity) {
187 1 : comp.Add(entity, data)
188 1 : }
189 : }
190 :
191 : // ensureRemoved はコンポーネントを保持している場合のみ取り除く。
192 : // Arkは不在コンポーネントのRemoveでパニックするため、ここで吸収する
193 : func ensureRemoved[T any](comp *ecs.Map[T], entity ecs.Entity) {
194 1 : if comp.Has(entity) {
195 1 : comp.Remove(entity)
196 1 : }
197 : }
198 :
199 : // clearLocation はエンティティの既存の位置コンポーネントをすべて取り除く。
200 : // 排他制御のため、新しい位置を設定する前に呼ぶ(内部用)。
201 : // 移動元にOwnerがある場合はそのOwnerに WeightDirty マーカーを付与する。装備とモジュールなら StatsChanged も付ける
202 : func clearLocation(world w.World, entity ecs.Entity) {
203 1 : if world.Components.LocationInBackpack.Has(entity) {
204 1 : owner := world.Components.LocationInBackpack.Get(entity).Owner
205 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
206 1 : }
207 1 : if world.Components.LocationEquipped.Has(entity) {
208 1 : owner := world.Components.LocationEquipped.Get(entity).Owner
209 1 : ensureMarker(world, world.Components.StatsChanged, owner, &gc.StatsChanged{})
210 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
211 1 : }
212 1 : if world.Components.LocationInStorage.Has(entity) {
213 1 : owner := world.Components.LocationInStorage.Get(entity).Owner
214 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
215 1 : }
216 1 : if world.Components.LocationStowed.Has(entity) {
217 1 : owner := world.Components.LocationStowed.Get(entity).Owner
218 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
219 1 : }
220 1 : if world.Components.LocationInstalled.Has(entity) {
221 1 : owner := world.Components.LocationInstalled.Get(entity).Owner
222 1 : ensureMarker(world, world.Components.StatsChanged, owner, &gc.StatsChanged{})
223 1 : ensureMarker(world, world.Components.WeightDirty, owner, &gc.WeightDirty{})
224 1 : }
225 :
226 1 : ensureRemoved(world.Components.LocationInBackpack, entity)
227 1 : ensureRemoved(world.Components.LocationEquipped, entity)
228 1 : ensureRemoved(world.Components.LocationOnField, entity)
229 1 : ensureRemoved(world.Components.LocationInStorage, entity)
230 1 : ensureRemoved(world.Components.LocationStowed, entity)
231 1 : ensureRemoved(world.Components.LocationInstalled, entity)
232 : }
233 :
234 : // MoveToInstalled はモジュールアイテムをキューブの指定スロットへ装着する。
235 : func MoveToInstalled(world w.World, entity ecs.Entity, cube ecs.Entity, slot int) {
236 1 : clearLocation(world, entity)
237 1 : world.Components.LocationInstalled.Add(entity, &gc.LocationInstalled{Owner: cube, Slot: slot})
238 1 : ensureRemoved(world.Components.GridElement, entity)
239 1 : ensureMarker(world, world.Components.StatsChanged, cube, &gc.StatsChanged{})
240 1 : ensureMarker(world, world.Components.WeightDirty, cube, &gc.WeightDirty{})
241 1 : }
242 :
243 : // MoveToStowed はアイテムをキューブへ畳み込む。他ロケーションと排他になるよう clearLocation してから
244 : // LocationStowed を付ける。offset はキューブからの相対位置で、展開時に同じ配置へ戻すために持つ。
245 : func MoveToStowed(world w.World, entity ecs.Entity, cube ecs.Entity, offset consts.Coord[consts.Tile]) {
246 1 : clearLocation(world, entity)
247 1 : world.Components.LocationStowed.Add(entity, &gc.LocationStowed{Owner: cube, Offset: offset})
248 1 : ensureRemoved(world.Components.GridElement, entity)
249 1 : ensureMarker(world, world.Components.WeightDirty, cube, &gc.WeightDirty{})
250 1 : }
251 :
252 : // errPlayerNotPlaceable は座標・スプライト・カメラのそろったプレイヤーがいないときに返す
253 : var errPlayerNotPlaceable = errors.New("no player entity with required components found")
254 :
255 : // MovePlayerToPosition は既存のプレイヤーエンティティを指定位置に移動させる
256 : func MovePlayerToPosition(world w.World, pos consts.Coord[consts.Tile]) error {
257 1 : var playerEntity ecs.Entity
258 1 : var found bool
259 1 :
260 : // query.GetPlayerEntity でなくフィルタで探す。後続の Get が座標・スプライト・カメラの
261 : // 存在を前提にするため、4成分そろったプレイヤーだけをここで担保する。
262 : // プレイヤーは1体なので最初の1件で確定し、残りの走査を打ち切る
263 1 : playerQuery := ecs.NewFilter4[gc.Player, gc.GridElement, gc.SpriteRender, gc.Camera](world.ECS).Query()
264 1 : if playerQuery.Next() {
265 1 : playerEntity = playerQuery.Entity()
266 1 : found = true
267 1 : playerQuery.Close()
268 1 : }
269 1 : if !found {
270 1 : return errPlayerNotPlaceable
271 1 : }
272 :
273 : // プレイヤーの位置を更新する
274 1 : gridElement := world.Components.GridElement.Get(playerEntity)
275 1 : gridElement.X = pos.X
276 1 : gridElement.Y = pos.Y
277 1 :
278 : // カメラ位置も同期する
279 1 : camera := world.Components.Camera.Get(playerEntity)
280 1 : camera.Pos = consts.TileCenterToWorld(pos)
281 1 : camera.Target = camera.Pos
282 1 :
283 1 : return nil
284 : }
285 :
286 : // RemoveOwnedEntities は owners のいずれかが所有する、座標を持たないロケーションの実体を削除する。
287 : // 収納在庫 LocationInStorage・畳んだ貨物 LocationStowed・装着モジュール LocationInstalled はどれも
288 : // GridElement を持たず、座標カリングやステージ束縛の走査に載らない。所有者を消すときに一緒に消さないと、
289 : // 死んだ所有者を指す孤児として world に残り serde で蓄積する。反復中の削除を避け、収集してから削除する。
290 : func RemoveOwnedEntities(world w.World, owners []ecs.Entity) {
291 1 : if len(owners) == 0 {
292 1 : return
293 1 : }
294 1 : ownerSet := make(map[ecs.Entity]bool, len(owners))
295 1 : for _, o := range owners {
296 1 : ownerSet[o] = true
297 1 : }
298 :
299 1 : var toRemove []ecs.Entity
300 1 : qs := ecs.NewFilter1[gc.LocationInStorage](world.ECS).Query()
301 1 : for qs.Next() {
302 1 : e := qs.Entity()
303 1 : if ownerSet[world.Components.LocationInStorage.Get(e).Owner] {
304 1 : toRemove = append(toRemove, e)
305 1 : }
306 : }
307 1 : qw := ecs.NewFilter1[gc.LocationStowed](world.ECS).Query()
308 1 : for qw.Next() {
309 1 : e := qw.Entity()
310 1 : if ownerSet[world.Components.LocationStowed.Get(e).Owner] {
311 1 : toRemove = append(toRemove, e)
312 1 : }
313 : }
314 1 : qi := ecs.NewFilter1[gc.LocationInstalled](world.ECS).Query()
315 1 : for qi.Next() {
316 1 : e := qi.Entity()
317 1 : if ownerSet[world.Components.LocationInstalled.Get(e).Owner] {
318 1 : toRemove = append(toRemove, e)
319 1 : }
320 : }
321 1 : for _, e := range toRemove {
322 1 : if world.ECS.Alive(e) {
323 1 : world.ECS.RemoveEntity(e)
324 1 : }
325 : }
326 : }
|