Line data Source code
1 : package query
2 :
3 : import (
4 : "errors"
5 :
6 : gc "github.com/kijimaD/ruins/internal/components"
7 : "github.com/kijimaD/ruins/internal/consts"
8 : "github.com/kijimaD/ruins/internal/geometry"
9 : w "github.com/kijimaD/ruins/internal/world"
10 : "github.com/mlange-42/ark/ecs"
11 : )
12 :
13 : // ErrPlayerHasNoGridElement はプレイヤーが GridElement を持たないときに返す
14 : var ErrPlayerHasNoGridElement = errors.New("player has no GridElement")
15 :
16 : // GetVisibleEnemies は視界内の敵エンティティをすべて取得して返す
17 : func GetVisibleEnemies(world w.World) ([]ecs.Entity, error) {
18 1 : playerEntity, err := GetPlayerEntity(world)
19 1 : if err != nil {
20 1 : return nil, err
21 1 : }
22 :
23 1 : if !world.Components.GridElement.Has(playerEntity) {
24 1 : return nil, ErrPlayerHasNoGridElement
25 1 : }
26 :
27 1 : playerGrid := world.Components.GridElement.Get(playerEntity)
28 1 :
29 1 : var enemies []ecs.Entity
30 1 :
31 : // 座標が重なる退避中ステージの敵を可視判定に混ぜない。現ステージのみ対象にする
32 1 : enemiesQuery := ActiveFilter2[gc.GridElement, gc.FactionEnemy](world).Query()
33 1 : for enemiesQuery.Next() {
34 1 : entity := enemiesQuery.Entity()
35 1 : gridElement := world.Components.GridElement.Get(entity)
36 1 :
37 1 : if !IsInVision(world, playerGrid.Coord, gridElement.Coord) {
38 1 : continue
39 : }
40 :
41 1 : enemies = append(enemies, entity)
42 : }
43 :
44 1 : return enemies, nil
45 : }
46 :
47 : // IsInVision はプレイヤーから指定座標が現在見えるかをチェックする。
48 : // リアルタイムの可視性データを使用し、暗闇のタイルは見えないと判定する
49 : func IsInVision(world w.World, player, target consts.Coord[consts.Tile]) bool {
50 1 : distanceInPixels := geometry.Distance(float64(player.X), float64(player.Y), float64(target.X), float64(target.Y)) * float64(consts.TileSize)
51 1 : visionRadius := float64(consts.VisionRadiusTiles) * float64(consts.TileSize)
52 1 :
53 1 : if distanceInPixels > visionRadius {
54 1 : return false
55 1 : }
56 :
57 1 : vs := GetVisionState(world)
58 1 : if vs.VisibleTiles == nil {
59 1 : return false
60 1 : }
61 :
62 1 : return vs.VisibleTiles[gc.GridElement{Coord: target}]
63 : }
64 :
65 : // GetVisibleItems は視界内のアイテムエンティティをすべて取得して返す
66 : func GetVisibleItems(world w.World) ([]ecs.Entity, error) {
67 1 : playerEntity, err := GetPlayerEntity(world)
68 1 : if err != nil {
69 1 : return nil, err
70 1 : }
71 :
72 1 : if !world.Components.GridElement.Has(playerEntity) {
73 1 : return nil, ErrPlayerHasNoGridElement
74 1 : }
75 :
76 1 : playerGrid := world.Components.GridElement.Get(playerEntity)
77 1 :
78 1 : var items []ecs.Entity
79 1 :
80 1 : itemsQuery := ActiveFilter2[gc.GridElement, gc.LocationOnField](world).Query()
81 1 : for itemsQuery.Next() {
82 1 : entity := itemsQuery.Entity()
83 1 : gridElement := world.Components.GridElement.Get(entity)
84 1 :
85 1 : if !IsInVision(world, playerGrid.Coord, gridElement.Coord) {
86 1 : continue
87 : }
88 :
89 1 : items = append(items, entity)
90 : }
91 :
92 1 : return items, nil
93 : }
|