• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mlange-42 / arche-model / 7695440998

29 Jan 2024 11:38AM CUT coverage: 98.296% (+0.09%) from 98.208%
7695440998

push

github

web-flow
Add functionality to advance the model stepwise (#52)

577 of 587 relevant lines covered (98.3%)

121.34 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/model/systems.go
1
package model
2

3
import (
4
        "fmt"
5
        "time"
6

7
        "github.com/mlange-42/arche-model/resource"
8
        "github.com/mlange-42/arche/ecs"
9
        "github.com/mlange-42/arche/generic"
10
)
11

12
// System is the interface for ECS systems.
13
//
14
// See also [UISystem] for systems with an independent graphics step.
15
type System interface {
16
        Initialize(w *ecs.World) // Initialize the system.
17
        Update(w *ecs.World)     // Update the system.
18
        Finalize(w *ecs.World)   // Finalize the system.
19
}
20

21
// UISystem is the interface for ECS systems that display UI in an independent graphics step.
22
//
23
// See also [System] for normal systems.
24
type UISystem interface {
25
        InitializeUI(w *ecs.World) // InitializeUI the system.
26
        UpdateUI(w *ecs.World)     // UpdateUI/update the system.
27
        PostUpdateUI(w *ecs.World) // PostUpdateUI does the final part of updating, e.g. update the GL window.
28
        FinalizeUI(w *ecs.World)   // FinalizeUI the system.
29
}
30

31
// Systems manages and schedules ECS [System] and [UISystem] instances.
32
//
33
// [System] instances are updated with a frequency given by TPS (ticks per second).
34
// [UISystem] instances are updated independently of normal systems, with a frequency given by FPS (frames per second).
35
//
36
// [Systems] is an embed in [Model] and it's methods are usually only used through a [Model] instance.
37
// By also being a resource of each [Model], however, systems can access it and e.g. remove themselves from a model.
38
type Systems struct {
39
        // Ticks per second for normal systems.
40
        // Values <= 0 (the default) mean as fast as possible.
41
        TPS float64
42
        // Frames per second for UI systems.
43
        // A zero/unset value defaults to 30 FPS. Values < 0 sync FPS with TPS.
44
        // With fast movement, a value of 60 may be required for fluent graphics.
45
        FPS float64
46
        // Whether the simulation is currently paused.
47
        // When paused, only UI updates but no normal updates are performed.
48
        Paused bool
49

50
        world      *ecs.World
51
        systems    []System
52
        uiSystems  []UISystem
53
        toRemove   []System
54
        uiToRemove []UISystem
55

56
        nextDraw   time.Time
57
        nextUpdate time.Time
58

59
        initialized bool
60
        locked      bool
61

62
        tickRes generic.Resource[resource.Tick]
63
        termRes generic.Resource[resource.Termination]
64
}
65

66
// Systems returns the normal/non-UI systems.
67
func (s *Systems) Systems() []System {
3✔
68
        return s.systems
3✔
69
}
3✔
70

71
// UISystems returns the UI systems.
72
func (s *Systems) UISystems() []UISystem {
3✔
73
        return s.uiSystems
3✔
74
}
3✔
75

76
// AddSystem adds a [System] to the model.
77
//
78
// Panics if the system is also a [UISystem].
79
// To add systems that implement both [System] and [UISystem], use [Systems.AddUISystem]
80
func (s *Systems) AddSystem(sys System) {
39✔
81
        if s.initialized {
42✔
82
                panic("adding systems after model initialization is not implemented yet")
3✔
83
        }
84
        if sys, ok := sys.(UISystem); ok {
39✔
85
                panic(fmt.Sprintf("System %T is also an UI system. Must be added via AddSystem.", sys))
3✔
86
        }
87
        s.systems = append(s.systems, sys)
33✔
88
}
89

90
// AddUISystem adds an [UISystem] to the model.
91
//
92
// Adds the [UISystem] also as a normal [System] if it implements the interface.
93
func (s *Systems) AddUISystem(sys UISystem) {
14✔
94
        if s.initialized {
17✔
95
                panic("adding systems after model initialization is not implemented yet")
3✔
96
        }
97
        s.uiSystems = append(s.uiSystems, sys)
11✔
98
        if sys, ok := sys.(System); ok {
14✔
99
                s.systems = append(s.systems, sys)
3✔
100
        }
3✔
101
}
102

103
// RemoveSystem removes a system from the model.
104
//
105
// Systems can also be removed during a model run.
106
// However, this will take effect only after the end of the full model step.
107
func (s *Systems) RemoveSystem(sys System) {
10✔
108
        if sys, ok := sys.(UISystem); ok {
13✔
109
                panic(fmt.Sprintf("System %T is also an UI system. Must be removed via RemoveUISystem.", sys))
3✔
110
        }
111
        s.toRemove = append(s.toRemove, sys)
7✔
112
        if !s.locked {
11✔
113
                s.removeSystems()
4✔
114
        }
4✔
115
}
116

117
// RemoveUISystem removes an UI system from the model.
118
//
119
// Systems can also be removed during a model run.
120
// However, this will take effect only after the end of the full model step.
121
func (s *Systems) RemoveUISystem(sys UISystem) {
12✔
122
        s.uiToRemove = append(s.uiToRemove, sys)
12✔
123
        if !s.locked {
21✔
124
                s.removeSystems()
9✔
125
        }
9✔
126
}
127

128
// Removes systems that were removed during the model step.
129
func (s *Systems) removeSystems() {
1,524✔
130
        rem := s.toRemove
1,524✔
131
        remUI := s.uiToRemove
1,524✔
132

1,524✔
133
        s.toRemove = s.toRemove[:0]
1,524✔
134
        s.uiToRemove = s.uiToRemove[:0]
1,524✔
135

1,524✔
136
        for _, sys := range rem {
1,531✔
137
                s.removeSystem(sys)
7✔
138
        }
7✔
139
        for _, sys := range remUI {
1,533✔
140
                if sys, ok := sys.(System); ok {
18✔
141
                        s.removeSystem(sys)
6✔
142
                }
6✔
143
                s.removeUISystem(sys)
9✔
144
        }
145
}
146

147
func (s *Systems) removeSystem(sys System) {
16✔
148
        if s.locked {
19✔
149
                panic("can't remove a system in locked state")
3✔
150
        }
151
        idx := -1
13✔
152
        for i := 0; i < len(s.systems); i++ {
35✔
153
                if sys == s.systems[i] {
29✔
154
                        idx = i
7✔
155
                        break
7✔
156
                }
157
        }
158
        if idx < 0 {
19✔
159
                panic(fmt.Sprintf("can't remove system %T: not in the model", sys))
6✔
160
        }
161
        s.systems[idx].Finalize(s.world)
7✔
162
        s.systems = append(s.systems[:idx], s.systems[idx+1:]...)
7✔
163
}
164

165
func (s *Systems) removeUISystem(sys UISystem) {
12✔
166
        if s.locked {
15✔
167
                panic("can't remove a system in locked state")
3✔
168
        }
169
        idx := -1
9✔
170
        for i := 0; i < len(s.uiSystems); i++ {
15✔
171
                if sys == s.uiSystems[i] {
12✔
172
                        idx = i
6✔
173
                        break
6✔
174
                }
175
        }
176
        if idx < 0 {
12✔
177
                panic(fmt.Sprintf("can't remove UI system %T: not in the model", sys))
3✔
178
        }
179
        s.uiSystems[idx].FinalizeUI(s.world)
6✔
180
        s.uiSystems = append(s.uiSystems[:idx], s.uiSystems[idx+1:]...)
6✔
181
}
182

183
// Initialize all systems.
184
func (s *Systems) initialize() {
29✔
185
        if s.initialized {
32✔
186
                panic("model is already initialized")
3✔
187
        }
188

189
        if s.FPS == 0 {
28✔
190
                s.FPS = 30
2✔
191
        }
2✔
192

193
        s.tickRes = generic.NewResource[resource.Tick](s.world)
26✔
194
        s.termRes = generic.NewResource[resource.Termination](s.world)
26✔
195

26✔
196
        s.locked = true
26✔
197
        for _, sys := range s.systems {
61✔
198
                sys.Initialize(s.world)
35✔
199
        }
35✔
200
        for _, sys := range s.uiSystems {
37✔
201
                sys.InitializeUI(s.world)
11✔
202
        }
11✔
203
        s.locked = false
26✔
204
        s.removeSystems()
26✔
205
        s.initialized = true
26✔
206

26✔
207
        s.nextDraw = time.Time{}
26✔
208
        s.nextUpdate = time.Time{}
26✔
209

26✔
210
        s.tickRes.Get().Tick = 0
26✔
211
}
212

213
// Update all systems.
214
func (s *Systems) update() bool {
1,402✔
215
        s.locked = true
1,402✔
216
        update := s.updateSystems()
1,402✔
217
        s.updateUISystems(update)
1,402✔
218
        s.locked = false
1,402✔
219

1,402✔
220
        s.removeSystems()
1,402✔
221

1,402✔
222
        if update {
2,682✔
223
                time := s.tickRes.Get()
1,280✔
224
                time.Tick++
1,280✔
225
        } else {
1,402✔
226
                s.wait()
122✔
227
        }
122✔
228

229
        return !s.termRes.Get().Terminate
1,402✔
230
}
231

232
// UpdateSystems updates all normal systems
233
func (s *Systems) UpdateSystems() bool {
30✔
234
        s.locked = true
30✔
235
        updated := s.updateSystems()
30✔
236
        s.locked = false
30✔
237

30✔
238
        s.removeSystems()
30✔
239

30✔
240
        if updated {
60✔
241
                time := s.tickRes.Get()
30✔
242
                time.Tick++
30✔
243
        }
30✔
244
        return !s.termRes.Get().Terminate
30✔
245
}
246

247
// UpdateUISystems updates all UI systems
248
func (s *Systems) UpdateUISystems() {
27✔
249
        s.locked = true
27✔
250
        s.updateUISystems(true)
27✔
251
        s.locked = false
27✔
252

27✔
253
        s.removeSystems()
27✔
254
}
27✔
255

256
// Calculates and waits the time until the next update of UI update.
257
func (s *Systems) wait() {
122✔
258
        nextUpdate := s.nextUpdate
122✔
259

122✔
260
        if (s.Paused || s.FPS > 0) && s.nextDraw.Before(nextUpdate) {
201✔
261
                nextUpdate = s.nextDraw
79✔
262
        }
79✔
263

264
        t := time.Now()
122✔
265
        wait := nextUpdate.Sub(t)
122✔
266

122✔
267
        if wait > 0 {
243✔
268
                time.Sleep(wait)
121✔
269
        }
121✔
270
}
271

272
// Update normal systems.
273
func (s *Systems) updateSystems() bool {
1,432✔
274
        update := false
1,432✔
275
        if s.Paused {
1,533✔
276
                update = !time.Now().Before(s.nextUpdate)
101✔
277
                if update {
136✔
278
                        tps := s.limitedFps(s.TPS, 10)
35✔
279
                        s.nextUpdate = nextTime(s.nextUpdate, tps)
35✔
280
                }
35✔
281
                return false
101✔
282
        }
283
        if s.TPS <= 0 {
2,626✔
284
                update = true
1,295✔
285
                for _, sys := range s.systems {
2,662✔
286
                        sys.Update(s.world)
1,367✔
287
                }
1,367✔
288
        } else {
36✔
289
                update = !time.Now().Before(s.nextUpdate)
36✔
290
                if update {
51✔
291
                        s.nextUpdate = nextTime(s.nextUpdate, s.TPS)
15✔
292
                        for _, sys := range s.systems {
30✔
293
                                sys.Update(s.world)
15✔
294
                        }
15✔
295
                }
296
        }
297
        return update
1,331✔
298
}
299

300
// Update UI systems.
301
func (s *Systems) updateUISystems(updated bool) {
1,429✔
302
        if !s.Paused && s.FPS <= 0 {
1,437✔
303
                if updated {
13✔
304
                        for _, sys := range s.uiSystems {
10✔
305
                                sys.UpdateUI(s.world)
5✔
306
                        }
5✔
307
                        for _, sys := range s.uiSystems {
10✔
308
                                sys.PostUpdateUI(s.world)
5✔
309
                        }
5✔
310
                }
311
        } else {
1,421✔
312
                if !time.Now().Before(s.nextDraw) {
1,588✔
313
                        fps := s.FPS
167✔
314
                        if s.Paused {
268✔
315
                                fps = s.limitedFps(s.FPS, 30)
101✔
316
                        }
101✔
317
                        s.nextDraw = nextTime(s.nextDraw, fps)
167✔
318
                        for _, sys := range s.uiSystems {
304✔
319
                                sys.UpdateUI(s.world)
137✔
320
                        }
137✔
321
                        for _, sys := range s.uiSystems {
304✔
322
                                sys.PostUpdateUI(s.world)
137✔
323
                        }
137✔
324
                }
325
        }
326
}
327

328
// Finalize all systems.
329
func (s *Systems) finalize() {
26✔
330
        s.locked = true
26✔
331
        for _, sys := range s.systems {
58✔
332
                sys.Finalize(s.world)
32✔
333
        }
32✔
334
        for _, sys := range s.uiSystems {
34✔
335
                sys.FinalizeUI(s.world)
8✔
336
        }
8✔
337
        s.locked = false
26✔
338
        s.removeSystems()
26✔
339
}
340

341
// Run the model.
342
func (s *Systems) run() {
23✔
343
        if !s.initialized {
46✔
344
                s.initialize()
23✔
345
        }
23✔
346

347
        for s.update() {
1,402✔
348
        }
1,379✔
349

350
        s.finalize()
23✔
351
}
352

353
// Removes all systems.
354
func (s *Systems) reset() {
19✔
355
        s.systems = []System{}
19✔
356
        s.uiSystems = []UISystem{}
19✔
357
        s.toRemove = s.toRemove[:0]
19✔
358
        s.uiToRemove = s.uiToRemove[:0]
19✔
359

19✔
360
        s.nextDraw = time.Time{}
19✔
361
        s.nextUpdate = time.Time{}
19✔
362

19✔
363
        s.initialized = false
19✔
364
        s.tickRes = generic.Resource[resource.Tick]{}
19✔
365
}
19✔
366

367
// Calculates frame rate capped to target
368
func (s *Systems) limitedFps(actual, target float64) float64 {
136✔
369
        if actual > target || actual <= 0 {
171✔
370
                return target
35✔
371
        }
35✔
372
        return actual
101✔
373
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc