95 lines
2.7 KiB
Go
95 lines
2.7 KiB
Go
package store
|
|
|
|
import (
|
|
"aeternalis/server/internal/game"
|
|
p "aeternalis/server/internal/protocol"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
)
|
|
|
|
func (d *DB) syncHouseRooms(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
|
for id, c := range w.Characters {
|
|
var world, state string
|
|
if e := tx.QueryRowContext(ctx, d.q(`SELECT world_id,state FROM character_records WHERE character_id=?`), id).Scan(&world, &state); e != nil {
|
|
return e
|
|
}
|
|
if world != w.ID || state == "transit" {
|
|
continue
|
|
}
|
|
if house := game.HouseID(c); house != "" {
|
|
h, e := d.readHouse(ctx, tx, house, false)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
role, e := d.houseRole(ctx, tx, h, c)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if h.View.State != "active" || role == "" || !c.Online || c.Sheltered || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0 || !w.IsHub() {
|
|
game.LeaveHouse(c)
|
|
} else {
|
|
c.HouseRoom = w.HouseScene(h.View)
|
|
if c.View.HousePosition == nil || !w.HousePositionValid(c.HouseRoom, *c.View.HousePosition) {
|
|
pos, ok := w.HouseSpawn(c.HouseRoom)
|
|
if !ok {
|
|
game.LeaveHouse(c)
|
|
} else {
|
|
c.View.HousePosition = &pos
|
|
c.JumpVelocity = 0
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if game.HouseID(c) == "" {
|
|
if _, e := tx.ExecContext(ctx, d.q(`DELETE FROM house_visitors WHERE character_id=? AND world_id=?`), id, w.ID); e != nil {
|
|
return e
|
|
}
|
|
continue
|
|
}
|
|
v := c.View.Entity
|
|
v.Position = *c.View.HousePosition
|
|
raw, e := json.Marshal(v)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_visitors(character_id,house_id,world_id,updated_at,entity) VALUES(?,?,?,`+d.now()+`,?) ON CONFLICT(character_id) DO UPDATE SET house_id=excluded.house_id,world_id=excluded.world_id,updated_at=excluded.updated_at,entity=excluded.entity`), id, game.HouseID(c), w.ID, string(raw)); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
rooms := map[string][]p.Entity{}
|
|
for _, c := range w.Characters {
|
|
house := game.HouseID(c)
|
|
if house == "" || c.HouseRoom == nil {
|
|
continue
|
|
}
|
|
if _, ok := rooms[house]; !ok {
|
|
rooms[house] = []p.Entity{}
|
|
rows, e := tx.QueryContext(ctx, d.q(`SELECT v.entity FROM house_visitors v JOIN worlds w ON w.id=v.world_id WHERE v.house_id=? AND v.updated_at>=`+d.now()+`-5 AND w.owner<>'' AND w.lease_until>=`+d.now()+` ORDER BY v.character_id LIMIT 256`), house)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
for rows.Next() {
|
|
var raw string
|
|
var v p.Entity
|
|
if e = rows.Scan(&raw); e != nil {
|
|
rows.Close()
|
|
return e
|
|
}
|
|
if e = json.Unmarshal([]byte(raw), &v); e != nil {
|
|
rows.Close()
|
|
return e
|
|
}
|
|
rooms[house] = append(rooms[house], v)
|
|
}
|
|
e = rows.Err()
|
|
rows.Close()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
}
|
|
c.HouseRoom.People = rooms[house]
|
|
}
|
|
return nil
|
|
}
|