Documentation
¶
Overview ¶
Package gametime is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package gametime provides deterministic in-game calendar clocks, versioned YAML calendar and daily-schedule formats, timed calendar events, day-night lighting gradients for 2D and 3D scenes, and variable bindings for flow, dialogue, and quests.
Index ¶
- Constants
- Variables
- func AppendVarDecls(doc *flow.VarsDoc) *flow.VarsDoc
- func EncodeCalendar(c *Calendar) ([]byte, error)
- func EncodeDayNight(dn *DayNight) ([]byte, error)
- func EncodeSchedules(b *ScheduleBook) ([]byte, error)
- func ValidateCalendar(c *Calendar) error
- func ValidateDayNight(dn *DayNight) error
- func ValidateSchedules(b *ScheduleBook) error
- func VarDecls() []flow.VarDecl
- type ActorSchedule
- type Calendar
- func (c *Calendar) ActiveDayMinutes() int
- func (c *Calendar) Clone() *Calendar
- func (c *Calendar) DayLength() time.Duration
- func (c *Calendar) EffectiveDayEndHour() int
- func (c *Calendar) EffectiveDayStartHour() int
- func (c *Calendar) EffectiveHoursPerDay() int
- func (c *Calendar) EffectiveMinutesPerHour() int
- func (c *Calendar) MinutesPerDay() int
- func (c *Calendar) SeasonIndex(name string) int
- func (c *Calendar) WeekdayIndex(name string) int
- func (c *Calendar) YearDays() int
- type Clock
- func (c *Clock) At(clockTime string, fn func(Date)) (*EventHandle, error)
- func (c *Clock) AttachLoop(l *game.Loop) (detach func())
- func (c *Clock) BindVars(vars *flow.Vars) (unbind func(), err error)
- func (c *Clock) Calendar() *Calendar
- func (c *Clock) Every(days int, fn func(Date)) (*EventHandle, error)
- func (c Clock) Now() Date
- func (c *Clock) OnDayEnd(fn func(Date)) *EventHandle
- func (c *Clock) OnSeason(fn func(Date)) *EventHandle
- func (c *Clock) RegisterSystem(s *entities.Scheduler, name string, opts ...entities.SystemOption) error
- func (c *Clock) Restore(snap Snapshot) error
- func (c *Clock) SetPaused(paused bool)
- func (c *Clock) SetProcessMode(mode entities.ProcessMode)
- func (c *Clock) SkipDays(days int)
- func (c *Clock) SkipTo(hour int)
- func (c *Clock) SkipToTime(hour, minute int)
- func (c *Clock) Snapshot() Snapshot
- func (c *Clock) Step(dt time.Duration)
- func (c *Clock) StepAtRate(rate int)
- func (c *Clock) StepForPauseState(paused bool, dt time.Duration)
- func (c *Clock) StepPaused(dt time.Duration)
- func (c *Clock) SyncVars(vars *flow.Vars) error
- func (c *Clock) TimeOfDay() float64
- type Date
- type DayNight
- type DayNightSample
- type DayNightStop
- type EventHandle
- type ScheduleBook
- func (b *ScheduleBook) Actor(id string) *ActorSchedule
- func (b *ScheduleBook) Resolve(actor string, at Date) (ScheduleEntry, bool)
- func (b *ScheduleBook) ResolveClock(actor string, c *Clock) (ScheduleEntry, bool)
- func (b *ScheduleBook) ResolveForCalendar(actor string, at Date, cal *Calendar) (ScheduleEntry, bool)
- func (b *ScheduleBook) ValidateWithCalendar(cal *Calendar) error
- type ScheduleEntry
- type SeasonDef
- type Snapshot
Examples ¶
Constants ¶
const ( // CalendarFormatVersion is the schema version of versioned YAML calendar files that [ParseCalendar] reads and [EncodeCalendar] writes. CalendarFormatVersion = 1 // CalendarSchemaURL is where the JSON Schema of version 1 calendar files is published. CalendarSchemaURL = "https://nsgo.games/schemas/calendar.v1.json" )
const ( // DayNightFormatVersion is the schema version of day-night lighting YAML files read by [ParseDayNight] and written by [EncodeDayNight]. DayNightFormatVersion = 1 // DayNightSchemaURL is where the JSON Schema of version 1 day-night lighting files is published. DayNightSchemaURL = "https://nsgo.games/schemas/daynight.v1.json" )
const ( // ScheduleFormatVersion is the schema version of daily schedule YAML files read by [ParseSchedules] and written by [EncodeSchedules]. ScheduleFormatVersion = 1 // ScheduleSchemaURL is where the JSON Schema of version 1 daily schedule files is published. ScheduleSchemaURL = "https://nsgo.games/schemas/schedules.v1.json" )
const ( // VarYear is the integer calendar year variable ("time_year"). VarYear = "time_year" // VarSeason is the string season name variable ("time_season"). VarSeason = "time_season" // VarSeasonIndex is the zero-based integer season index variable ("time_season_index"). VarSeasonIndex = "time_season_index" // VarDay is the one-based integer day-of-season variable ("time_day"). VarDay = "time_day" // VarWeekday is the string weekday name variable ("time_weekday"). VarWeekday = "time_weekday" // VarWeekdayIndex is the zero-based integer weekday index variable ("time_weekday_index"). VarWeekdayIndex = "time_weekday_index" // VarHour is the integer hour-of-day variable ("time_hour"). VarHour = "time_hour" // VarMinute is the integer minute-of-hour variable ("time_minute"). VarMinute = "time_minute" )
Standard flow.Vars variable names exposed by VarDecls, Date.SyncVars, and Clock.BindVars so Yarn dialogue scripts, quest conditions, and expressions can query the in-game date and time.
const SnapshotVersion = 1
SnapshotVersion is the schema version written and read by Clock.Snapshot and Clock.Restore.
Variables ¶
var ( // ErrInvalidTime reports an invalid "HH:MM" clock time or a time outside the calendar's active day window. ErrInvalidTime = errors.New("gametime: invalid clock time") // ErrInvalidInterval reports a non-positive day interval passed to [Clock.Every]. ErrInvalidInterval = errors.New("gametime: invalid day interval") )
var ErrInvalidCalendar = errors.New("gametime: invalid calendar")
ErrInvalidCalendar reports that a YAML calendar document breaks the schema: a wrong version, non-positive or overflowing time units, invalid day start/end hours, non-positive realPerGameMinute, or empty/duplicate season or weekday names.
var ErrInvalidDayNight = errors.New("gametime: invalid day-night gradient")
ErrInvalidDayNight reports that a day-night lighting gradient breaks the schema: a wrong version, non-positive hoursPerDay, empty or unsorted stops, invalid colors, non-finite values, zero sunDirection, or negative intensity.
var ErrInvalidSchedule = errors.New("gametime: invalid schedule")
ErrInvalidSchedule reports that a YAML schedule document breaks the schema: a wrong version, missing or duplicate actor IDs, empty entry lists, malformed times, duplicate days, or missing places.
var ErrInvalidSnapshot = errors.New("gametime: invalid snapshot")
ErrInvalidSnapshot reports a malformed or out-of-range Snapshot passed to Clock.Restore.
Functions ¶
func AppendVarDecls ¶
AppendVarDecls returns a copy of doc (or a fresh version-1 flow.VarsDoc if doc is nil) with any missing gametime variable declarations from VarDecls appended.
func EncodeCalendar ¶
EncodeCalendar validates c and writes it in canonical deterministic YAML (2-space indentation, fixed field order, flow-style weekdays). ParseCalendar(EncodeCalendar(c)) equals c, and EncodeCalendar(ParseCalendar(f)) returns f byte-for-byte when f is already canonical.
func EncodeDayNight ¶
EncodeDayNight validates dn and writes it in canonical deterministic YAML (2-space indentation, fixed field order, flow-style sunDirection).
func EncodeSchedules ¶
func EncodeSchedules(b *ScheduleBook) ([]byte, error)
EncodeSchedules validates b and writes it in canonical deterministic YAML (2-space indentation, fixed field order, flow-style days).
func ValidateCalendar ¶
ValidateCalendar checks c against the version 1 calendar schema. Errors are *loaderr.Error values wrapping ErrInvalidCalendar.
func ValidateDayNight ¶
ValidateDayNight checks dn against the version 1 day-night gradient schema. Errors are *loaderr.Error values wrapping ErrInvalidDayNight.
func ValidateSchedules ¶
func ValidateSchedules(b *ScheduleBook) error
ValidateSchedules checks b against the version 1 schedule schema. Errors are *loaderr.Error values wrapping ErrInvalidSchedule.
func VarDecls ¶
VarDecls returns the flow.VarDecl declarations for all calendar date/time variables so games can include them in a flow.VarsDoc before creating a flow.Vars store.
Types ¶
type ActorSchedule ¶
type ActorSchedule struct {
// Actor uniquely identifies the NPC, shop, or building within the [ScheduleBook].
Actor string `yaml:"actor" schema:"required"`
// Entries lists the actor's schedule entries in evaluation order. At least one entry is required.
Entries []ScheduleEntry `yaml:"entries" schema:"required"`
}
ActorSchedule is one actor's ordered list of daily schedule entries.
func (*ActorSchedule) Resolve ¶
func (s *ActorSchedule) Resolve(at Date) (ScheduleEntry, bool)
Resolve returns the active ScheduleEntry in s at date at under standard 24-hour 00:00..24:00 rules.
func (*ActorSchedule) ResolveForCalendar ¶
func (s *ActorSchedule) ResolveForCalendar(at Date, cal *Calendar) (ScheduleEntry, bool)
ResolveForCalendar returns the active ScheduleEntry in s at date at under cal's rules.
type Calendar ¶
type Calendar struct {
// Version is the schema version; it must equal CalendarFormatVersion (1).
Version int `yaml:"version" schema:"required"`
// MinutesPerHour is how many in-game minutes make one hour; 0 defaults to 60.
MinutesPerHour int `yaml:"minutesPerHour,omitempty" schema:"minimum=1"`
// HoursPerDay is how many in-game hours make one full clock day; 0 defaults to 24.
HoursPerDay int `yaml:"hoursPerDay,omitempty" schema:"minimum=1"`
// DayStartHour is the hour at which a new day begins, in [0, HoursPerDay). Zero starts at 00:00.
DayStartHour int `yaml:"dayStartHour,omitempty" schema:"minimum=0"`
// DayEndHour is the hour at which a day ends (for example 26 or 2 for 02:00 next morning when DayStartHour is 6). Zero defaults to DayStartHour + HoursPerDay (a full clock day).
DayEndHour int `yaml:"dayEndHour,omitempty" schema:"minimum=1"`
// RealPerGameMinute is the real-time duration of one in-game minute (for example "10s" or "1s"). Must be positive.
RealPerGameMinute time.Duration `yaml:"realPerGameMinute" schema:"required"`
// Seasons lists the named seasons in order; each has a unique name and positive day count.
Seasons []SeasonDef `yaml:"seasons,omitempty"`
// Weekdays lists the weekday names in order (for example ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]).
Weekdays []string `yaml:"weekdays,omitempty,flow"`
}
Calendar defines the rules of an in-game calendar in versioned YAML.
func DefaultCalendar ¶
func DefaultCalendar() *Calendar
DefaultCalendar returns a validated 4-season, 28-day-per-season, 7-weekday calendar with 60 minutes per hour, 24 hours per day, and 1 real second per in-game minute.
func LoadCalendarFS ¶
LoadCalendarFS reads and parses the YAML calendar at name in fsys. Errors are *loaderr.Error values naming name.
func ParseCalendar ¶
ParseCalendar decodes a versioned YAML calendar and validates it. Unknown fields and trailing YAML documents are refused. Errors are *loaderr.Error values wrapping ErrInvalidCalendar with line, field, and fix.
func (*Calendar) ActiveDayMinutes ¶
ActiveDayMinutes returns the number of in-game minutes from DayStartHour to EffectiveDayEndHour.
func (*Calendar) DayLength ¶
DayLength returns the real-time duration of one active in-game day. It returns 0 when c is nil or RealPerGameMinute is non-positive.
func (*Calendar) EffectiveDayEndHour ¶
EffectiveDayEndHour returns the active day's end hour offset from 00:00, in (DayStartHour, DayStartHour+HoursPerDay]. When DayEndHour is 0, it returns DayStartHour + HoursPerDay (a full clock day). When 0 < DayEndHour <= DayStartHour, it wraps past midnight to DayEndHour + HoursPerDay.
func (*Calendar) EffectiveDayStartHour ¶
EffectiveDayStartHour returns DayStartHour clamped into [0, EffectiveHoursPerDay()).
func (*Calendar) EffectiveHoursPerDay ¶
EffectiveHoursPerDay returns HoursPerDay when positive, or 24 otherwise.
func (*Calendar) EffectiveMinutesPerHour ¶
EffectiveMinutesPerHour returns MinutesPerHour when positive, or 60 otherwise.
func (*Calendar) MinutesPerDay ¶
MinutesPerDay returns the number of in-game minutes in one full clock cycle (HoursPerDay * MinutesPerHour).
func (*Calendar) SeasonIndex ¶
SeasonIndex returns the zero-based index of the named season, or -1 if not found.
func (*Calendar) WeekdayIndex ¶
WeekdayIndex returns the zero-based index of the named weekday, or -1 if not found.
type Clock ¶
type Clock struct {
// DayLength is the real duration of one in-game day (or active day when a Calendar configures DayStartHour/DayEndHour).
DayLength time.Duration
// DaysPerSeason is the number of days before Season advances when no Calendar is attached. Zero disables rollover.
DaysPerSeason int
// Year is the one-based current year for Calendar clocks (0 on bare struct literals unless set).
Year int
// Season is the zero-based current season.
Season int
// Day is the one-based current day within the season.
Day int
// Minute is the current minute offset within the active day cycle. For a standard 24-hour day starting at 00:00, Minute is in [0, 1440). For a Calendar with DayStartHour > 0 and DayEndHour extending past midnight (for example 06:00 to 02:00), Minute lies in [DayStartHour*MinutesPerHour, EffectiveDayEndHour*MinutesPerHour) and [Clock.Now] wraps Hour modulo HoursPerDay.
Minute int
// Partial is the progress toward the next in-game minute. For Calendar clocks created with [NewClock], Partial is in [0, Calendar.RealPerGameMinute) in nanoseconds. For bare Clock literals without a Calendar, Partial is in [0, DayLength) as the fraction Partial/DayLength of one minute. Step keeps it so that many short steps add up to the same time as one long step, and a saved and restored clock keeps stepping as one that was never saved.
Partial time.Duration
// Paused stops Step, StepAtRate, and loop/scheduler hooks from advancing the clock when true.
Paused bool
// ProcessMode controls how the clock responds to game.Loop and entities.Scheduler pause states (ProcessPausable by default, ProcessWhenPaused, or ProcessAlways).
ProcessMode entities.ProcessMode
// contains filtered or unexported fields
}
Clock advances a deterministic in-game calendar without reading the device clock.
Construct a Clock with NewClock for a full versioned Calendar (named seasons, weekdays, custom hours/minutes, and day start/end hours), or as a plain struct literal with DayLength and DaysPerSeason for simple 24-hour clocks.
Example ¶
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/gametime"
)
func main() {
// One in-game day lasts 24 real minutes, so one real second is one in-game minute.
c := gametime.Clock{DayLength: 24 * time.Minute, DaysPerSeason: 28, Day: 1, Minute: 6 * 60}
show := func() {
now := c.Now()
fmt.Printf("season %d day %d %02d:%02d\n", c.Season, now.Day, now.Hour, now.Minute)
}
show()
// Ninety real seconds advance the clock by ninety in-game minutes.
c.Step(90 * time.Second)
show()
// Sleeping skips to six o'clock on the next day, because six has already passed today.
c.SkipTo(6)
show()
// Stepping 27 whole days rolls past day 28 into the next season.
c.Step(27 * c.DayLength)
show()
}
Output: season 0 day 1 06:00 season 0 day 1 07:30 season 0 day 2 06:00 season 1 day 1 06:00
func NewClock ¶
NewClock constructs a Clock governed by cal, starting at Year 1, Season 0, Day 1, and cal.DayStartHour:00. Passing nil uses DefaultCalendar. Cal is validated and cloned so later mutations to cal do not affect the clock.
Example ¶
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/gametime"
)
func main() {
cal, err := gametime.ParseCalendar([]byte(`version: 1
minutesPerHour: 60
hoursPerDay: 24
dayStartHour: 6
dayEndHour: 26
realPerGameMinute: 1s
seasons:
- name: spring
days: 28
- name: summer
days: 28
weekdays: [mon, tue, wed, thu, fri, sat, sun]
`))
if err != nil {
panic(err)
}
clk, err := gametime.NewClock(cal)
if err != nil {
panic(err)
}
_, _ = clk.At("08:00", func(d gametime.Date) {
fmt.Println("shop opens:", d)
})
clk.Step(2 * time.Minute) // 2 real minutes = 120 game minutes -> 08:00
fmt.Println("now:", clk.Now())
}
Output: shop opens: Year 1 spring Day 1 mon 08:00 now: Year 1 spring Day 1 mon 08:00
func (*Clock) At ¶
func (c *Clock) At(clockTime string, fn func(Date)) (*EventHandle, error)
At registers fn to fire once per day whenever the clock crosses or reaches clockTime ("HH:MM"). Even when a single Step or Skip crosses several days, fn fires once for each crossing in chronological order. Returns an error wrapping ErrInvalidTime if c is nil, clockTime is malformed, or clockTime falls outside the active day.
func (*Clock) AttachLoop ¶
AttachLoop connects c to l's fixed update streams using exact rational step accounting (1/l.StepRate() seconds per step), honoring c.Paused and c.ProcessMode across l.Update, l.PausedUpdate, and l.RealUpdate. Calling the returned detach function restores l's prior callbacks.
func (*Clock) BindVars ¶
BindVars immediately synchronizes c.Now() into vars and keeps vars updated whenever Step, SkipTo, SkipDays, or Restore changes c.Now(). Calling the returned unbind function stops automatic updates.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/flow"
"github.com/nsgo-dev/game/pkg/gametime"
)
func main() {
clk, _ := gametime.NewClock(gametime.DefaultCalendar())
vars, _ := flow.NewVars(gametime.AppendVarDecls(nil))
unbind, _ := clk.BindVars(vars)
defer unbind()
clk.SkipTo(18)
season, _ := vars.String(gametime.VarSeason)
hour, _ := vars.Int(gametime.VarHour)
fmt.Printf("season=%s hour=%d\n", season, hour)
}
Output: season=spring hour=18
func (*Clock) Calendar ¶
Calendar returns a defensive copy of the clock's Calendar, or nil if the clock was constructed without one.
func (*Clock) Every ¶
func (c *Clock) Every(days int, fn func(Date)) (*EventHandle, error)
Every registers fn to fire once every days day rollovers (for example Every(1, fn) for every new day, or Every(7, fn) for every week). Each crossing fires fn once with the new day's start Date. Returns an error wrapping ErrInvalidInterval if c is nil or days <= 0.
func (*Clock) OnDayEnd ¶
func (c *Clock) OnDayEnd(fn func(Date)) *EventHandle
OnDayEnd registers fn to fire once each time a day reaches its end hour (for example 02:00 pass-out) immediately before rolling over to the next day's start hour.
func (*Clock) OnSeason ¶
func (c *Clock) OnSeason(fn func(Date)) *EventHandle
OnSeason registers fn to fire once each time the clock crosses into a new season, passing day 1 of the new season at the calendar's day start hour.
func (*Clock) RegisterSystem ¶
func (c *Clock) RegisterSystem(s *entities.Scheduler, name string, opts ...entities.SystemOption) error
RegisterSystem registers c as a named system on s with entities.Mode(c.ProcessMode) plus any extra opts.
func (*Clock) Restore ¶
Restore validates snap against c's calendar rules and replaces c's state atomically without firing events. Bound flow.Vars stores are synchronized to the restored date. If validation fails, c is left untouched and an error wrapping ErrInvalidSnapshot is returned.
func (*Clock) SetProcessMode ¶
func (c *Clock) SetProcessMode(mode entities.ProcessMode)
SetProcessMode configures how the clock interacts with game.Loop and entities.Scheduler pause states. Unrecognized mode values are ignored.
func (*Clock) SkipDays ¶
SkipDays advances the clock by days whole active days, preserving the time of day and clearing Partial. Non-positive values or a nil clock are ignored. Every event crossed fires once per crossing.
func (*Clock) SkipTo ¶
SkipTo advances to the next occurrence of hour:00, or to that hour today when it has not passed yet. Invalid hours outside [0, HoursPerDay) or outside the Calendar's active day window are ignored. Events crossed between the current time and the destination fire once per crossing in chronological order.
func (*Clock) SkipToTime ¶
SkipToTime advances to the next occurrence of hour:minute, or to that time today when it has not passed yet. Invalid times outside the active day window are ignored.
func (*Clock) Snapshot ¶
Snapshot captures c's deterministic state into a plain value suitable for JSON or YAML save slots.
func (*Clock) Step ¶
Step advances the clock by dt. Non-positive durations, nil or paused clocks, and clocks without a positive DayLength / RealPerGameMinute are ignored. Time shorter than an in-game minute is kept in Partial rather than dropped, so many short steps advance the clock as far as one step of their total length.
func (*Clock) StepAtRate ¶
StepAtRate advances the clock by one fixed step at rate Hz (exact 1/rate seconds), tracking any sub-nanosecond rational remainder so 30 Hz and 60 Hz loops stay in exact nanosecond agreement.
func (*Clock) StepForPauseState ¶
StepForPauseState advances the clock by dt when !c.Paused and c.ProcessMode runs under the given paused state: ProcessPausable runs when !paused, ProcessWhenPaused runs when paused, and ProcessAlways runs in both states.
func (*Clock) StepPaused ¶
StepPaused advances the clock by dt for a paused simulation step (matching entities.Scheduler.StepPaused and game.Loop.PausedUpdate): it advances only when ProcessMode is ProcessWhenPaused or ProcessAlways.
type Date ¶
type Date struct {
// Year is the one-based calendar year (0 on a bare Clock literal without a Calendar unless set).
Year int
// Season is the zero-based season index.
Season int
// SeasonName is the current season's name from the Calendar, or empty when unnamed.
SeasonName string
// Day is the one-based day within the current season.
Day int
// Weekday is the zero-based weekday index within the Calendar's weekdays, or 0 when unnamed.
Weekday int
// WeekdayName is the current weekday's name from the Calendar, or empty when unnamed.
WeekdayName string
// Hour is the in-game hour within [0, HoursPerDay).
Hour int
// Minute is the in-game minute within [0, MinutesPerHour).
Minute int
}
Date is a snapshot value of the current in-game calendar date and time.
func (Date) ClockString ¶
ClockString formats the time-of-day portion of d as zero-padded "HH:MM".
type DayNight ¶
type DayNight struct {
// Version is the schema version; it must equal DayNightFormatVersion (1).
Version int `yaml:"version" schema:"required"`
// HoursPerDay is the cycle length in hours; 0 defaults to 24.
HoursPerDay float64 `yaml:"hoursPerDay,omitempty" schema:"exclusiveMinimum=0"`
// Stops lists at least one lighting keyframe in strictly ascending Hour order within [0, HoursPerDay).
Stops []DayNightStop `yaml:"stops" schema:"required"`
}
DayNight is a cyclic day-night lighting gradient keyed by hour of day.
func DefaultDayNight ¶
func DefaultDayNight() *DayNight
DefaultDayNight returns a validated 24-hour day-night gradient with midnight, pre-dawn, dawn, noon, sunset, and twilight keyframes tuned for both 2D ambient overlays and 3D directional sunlight.
func LoadDayNightFS ¶
LoadDayNightFS reads and parses the YAML day-night gradient at name in fsys. Errors are *loaderr.Error values naming name.
func ParseDayNight ¶
ParseDayNight decodes and validates a versioned YAML day-night lighting file. Unknown fields and trailing YAML documents are refused. Errors are *loaderr.Error values wrapping ErrInvalidDayNight.
func (*DayNight) Sample ¶
func (dn *DayNight) Sample(hour float64) DayNightSample
Sample evaluates the cyclic day-night gradient at hour (wrapped modulo HoursPerDay). Non-finite inputs (NaN or Inf) are treated as 0 so Sample always returns finite colors and a unit SunDirection. If dn is nil or has no stops, Sample returns a safe neutral daylight sample.
func (*DayNight) SampleClock ¶
func (dn *DayNight) SampleClock(c *Clock) DayNightSample
SampleClock samples dn at c.TimeOfDay() (smooth continuous fractional hour including sub-minute progress). When the clock's calendar day and the gradient's HoursPerDay differ, the clock hour is rescaled so the same fraction of the day maps to the same point on the gradient. If c is nil, it samples at hour 0.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/gametime"
"github.com/nsgo-dev/game/pkg/lights2d"
"github.com/nsgo-dev/game/pkg/render3d"
)
func main() {
clk, _ := gametime.NewClock(gametime.DefaultCalendar())
clk.SkipTo(12)
dn := gametime.DefaultDayNight()
sample := dn.SampleClock(clk)
var scene2d lights2d.Scene
var sun render3d.DirectionalLight
sample.Apply2D(&scene2d)
sample.Apply3D(&sun)
fmt.Printf("hour=%.0f intensity=%.2f valid3d=%v\n", sample.Hour, sun.Intensity, sun.Validate() == nil)
}
Output: hour=12 intensity=1.35 valid3d=true
type DayNightSample ¶
type DayNightSample struct {
// Hour is the sampled hour wrapped into [0, HoursPerDay).
Hour float64
// Ambient is the interpolated 2D ambient darkness/tint color for lights2d.Scene.Ambient.
Ambient core.Color
// AmbientLinear is the linear RGB color derived from Ambient for 3D ambient fill.
AmbientLinear math3d.Vec3
// AmbientIntensity is the interpolated 3D ambient fill intensity.
AmbientIntensity float32
// SunColor is the interpolated linear RGB directional light tint for render3d.DirectionalLight.Color.
SunColor math3d.Vec3
// SunDirection is the interpolated unit travel direction of directional sunlight for render3d.DirectionalLight.Direction.
SunDirection math3d.Vec3
// Intensity is the interpolated directional light intensity for render3d.DirectionalLight.Intensity.
Intensity float32
}
DayNightSample is the interpolated lighting state at one moment in the day cycle, ready to apply to lights2d.Scene.Ambient, render3d.DirectionalLight, or render3d.LightRig.
func (DayNightSample) Apply2D ¶
func (s DayNightSample) Apply2D(scene *lights2d.Scene)
Apply2D writes s.Ambient to scene.Ambient. Passing a nil scene is a no-op.
func (DayNightSample) Apply3D ¶
func (s DayNightSample) Apply3D(light *render3d.DirectionalLight)
Apply3D writes s.SunDirection, s.SunColor, and s.Intensity to light, ensuring finite non-zero direction and finite non-negative color and intensity. Passing a nil light is a no-op.
func (DayNightSample) ApplyLightRig ¶
func (s DayNightSample) ApplyLightRig(rig *render3d.LightRig)
ApplyLightRig updates rig's primary directional light (appending one if rig.Directional is empty) and sets rig.Ambient from s.AmbientLinear and s.AmbientIntensity. Passing a nil rig is a no-op.
type DayNightStop ¶
type DayNightStop struct {
// Hour is the keyframe hour in [0, HoursPerDay) (for example 6.0 for dawn, 12.0 for noon, 18.5 for dusk).
Hour float64 `yaml:"hour" schema:"required,minimum=0"`
// Ambient is the 2D ambient darkness/tint color parsed by core.ParseColor (for example "#0d1633b8" at night or "#ffffff00" at noon).
Ambient string `yaml:"ambient" schema:"required"`
// SunColor is the optional 3D directional sun light sRGB color parsed by core.ParseColor (defaults to "#ffffff"); converted to linear RGB when sampled for render3d.DirectionalLight.
SunColor string `yaml:"sunColor,omitempty"`
// SunDirection is the world-space travel direction [x, y, z] of directional sunlight rays (for example [0, -1, 0] shining straight down). Must be finite and non-zero.
SunDirection [3]float32 `yaml:"sunDirection,flow" schema:"required"`
// Intensity scales the 3D directional sunlight; must be finite and non-negative.
Intensity float32 `yaml:"intensity" schema:"minimum=0"`
// AmbientIntensity optionally sets the 3D isotropic ambient fill intensity; must be finite and non-negative.
AmbientIntensity float32 `yaml:"ambientIntensity,omitempty" schema:"minimum=0"`
}
DayNightStop defines the 2D and 3D lighting state at one keyframe hour of the day.
type EventHandle ¶
type EventHandle struct {
// contains filtered or unexported fields
}
EventHandle is a cancellation handle for a clock event registered with Clock.At, Clock.Every, Clock.OnSeason, or Clock.OnDayEnd.
func (*EventHandle) Active ¶
func (h *EventHandle) Active() bool
Active reports whether the event is still registered on its clock.
func (*EventHandle) Cancel ¶
func (h *EventHandle) Cancel()
Cancel unregisters the event so it will not fire again. Calling Cancel on a nil or already-cancelled handle is a no-op.
type ScheduleBook ¶
type ScheduleBook struct {
// Version is the schema version; it must equal ScheduleFormatVersion (1).
Version int `yaml:"version" schema:"required"`
// Actors lists each actor's daily schedule in declaration order.
Actors []ActorSchedule `yaml:"actors,omitempty"`
}
ScheduleBook is the root of a versioned YAML daily schedules file.
func LoadSchedulesFS ¶
func LoadSchedulesFS(fsys fs.FS, name string) (*ScheduleBook, error)
LoadSchedulesFS reads and parses the YAML schedule book at name in fsys. Errors are *loaderr.Error values naming name.
func ParseSchedules ¶
func ParseSchedules(data []byte) (*ScheduleBook, error)
ParseSchedules decodes and validates a versioned YAML daily schedules file. Unknown fields and trailing YAML documents are refused. Errors are *loaderr.Error values wrapping ErrInvalidSchedule.
func (*ScheduleBook) Actor ¶
func (b *ScheduleBook) Actor(id string) *ActorSchedule
Actor returns the ActorSchedule for id, or nil if b is nil or does not define id.
func (*ScheduleBook) Resolve ¶
func (b *ScheduleBook) Resolve(actor string, at Date) (ScheduleEntry, bool)
Resolve returns the active ScheduleEntry for actor at date at, or (ScheduleEntry{}, false) if actor is unknown or no matching entry has started by at.
Matching entries filter by Season (empty matches all) and Days (empty matches all, otherwise matches at.WeekdayName or decimal at.Day). Among matching entries whose At time is <= at, the latest time wins; ties at the same At time prefer higher specificity (season+days > season or days > generic), and equal specificity prefers the later entry in list order.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/gametime"
)
func main() {
book, err := gametime.ParseSchedules([]byte(`version: 1
actors:
- actor: baker
entries:
- at: "08:00"
days: [mon, tue, wed, thu, fri]
place: bakery
activity: open
- at: "17:00"
place: home
activity: rest
`))
if err != nil {
panic(err)
}
entry, ok := book.Resolve("baker", gametime.Date{WeekdayName: "tue", Hour: 10, Minute: 30})
fmt.Println(ok, entry.Place, entry.Activity)
}
Output: true bakery open
func (*ScheduleBook) ResolveClock ¶
func (b *ScheduleBook) ResolveClock(actor string, c *Clock) (ScheduleEntry, bool)
ResolveClock returns the active ScheduleEntry for actor at c.Now(), honoring c's Calendar (including extended active days that wrap past midnight, such as 06:00 to 02:00).
func (*ScheduleBook) ResolveForCalendar ¶
func (b *ScheduleBook) ResolveForCalendar(actor string, at Date, cal *Calendar) (ScheduleEntry, bool)
ResolveForCalendar returns the active ScheduleEntry for actor at date at under cal's hour/minute and day-start rules. When cal is nil, standard 24-hour 00:00..24:00 rules apply.
func (*ScheduleBook) ValidateWithCalendar ¶
func (b *ScheduleBook) ValidateWithCalendar(cal *Calendar) error
ValidateWithCalendar validates b against both the schedule schema and cal's declared seasons, weekdays, hour/minute bounds, and active day window.
type ScheduleEntry ¶
type ScheduleEntry struct {
// At is the start time in zero-padded "HH:MM" 24-hour form (for example "08:00" or "17:30").
At string `yaml:"at" schema:"required"`
// Days optionally restricts this entry to matching weekday names (for example ["mon", "tue", "wed", "thu", "fri"]) or one-based day-of-season numbers written as decimal strings (for example "1", "15"). Empty matches every day.
Days []string `yaml:"days,omitempty,flow"`
// Season optionally restricts this entry to a named season (for example "summer"). Empty matches every season.
Season string `yaml:"season,omitempty"`
// Place is the location identifier where the actor is during this entry (for example "bakery" or "home").
Place string `yaml:"place" schema:"required"`
// Activity describes what the actor is doing during this entry (for example "open", "work", "sleep").
Activity string `yaml:"activity,omitempty"`
}
ScheduleEntry is one scheduled time slot for an actor (NPC routine or shop hours).
type SeasonDef ¶
type SeasonDef struct {
// Name uniquely identifies the season (for example "spring", "summer", "autumn", "winter").
Name string `yaml:"name" schema:"required"`
// Days is the number of days in the season; must be at least 1.
Days int `yaml:"days" schema:"required,minimum=1"`
}
SeasonDef defines one named season and its length in days within a Calendar.
type Snapshot ¶
type Snapshot struct {
// Version is SnapshotVersion (1).
Version int `json:"version" yaml:"version"`
// Year is the one-based calendar year (or 0 on legacy bare clocks).
Year int `json:"year" yaml:"year"`
// Season is the zero-based season index.
Season int `json:"season" yaml:"season"`
// Day is the one-based day within the current season.
Day int `json:"day" yaml:"day"`
// Minute is the current minute offset within the active day.
Minute int `json:"minute" yaml:"minute"`
// PartialNanos is the sub-minute accumulator (Clock.Partial) in nanoseconds.
PartialNanos int64 `json:"partialNanos,omitempty" yaml:"partialNanos,omitempty"`
// TotalDays is the monotonic zero-based day count used for weekday and Every(days) alignment.
TotalDays int64 `json:"totalDays,omitempty" yaml:"totalDays,omitempty"`
// Paused records Clock.Paused.
Paused bool `json:"paused,omitempty" yaml:"paused,omitempty"`
// ProcessMode records Clock.ProcessMode when non-default ("when_paused" or "always").
ProcessMode string `json:"processMode,omitempty" yaml:"processMode,omitempty"`
// SubStepNum is the numerator of the rational sub-nanosecond accumulator used by StepAtRate and AttachLoop.
SubStepNum int64 `json:"subStepNum,omitempty" yaml:"subStepNum,omitempty"`
// SubStepDen is the denominator of the rational sub-nanosecond accumulator used by StepAtRate and AttachLoop.
SubStepDen int64 `json:"subStepDen,omitempty" yaml:"subStepDen,omitempty"`
}
Snapshot is a plain JSON- and YAML-serializable capture of a Clock's full deterministic state. Restoring a Snapshot resumes stepping at the exact nanosecond progress, date, weekday alignment, pause state, and process mode without firing events for the restored timestamp.