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

Scala-Robotics-Simulator / PPS-22-srs / #635

13 Oct 2025 12:42PM UTC coverage: 78.131% (+0.05%) from 78.085%
#635

Pull #103

github

GiuliaNardicchia
refactor: replace Set with List for entity collections in Environment and related files, and sort entities by id to improve reproducibility
Pull Request #103: refactor: improve reproducibility

17 of 18 new or added lines in 7 files covered. (94.44%)

1279 of 1637 relevant lines covered (78.13%)

8.88 hits per line

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

78.26
/src/main/scala/io/github/srs/controller/ControllerModule.scala
1
package io.github.srs.controller
2

3
import scala.concurrent.duration.{ DurationInt, FiniteDuration, MILLISECONDS }
4
import scala.language.postfixOps
5

6
import cats.effect.std.Queue
7
import cats.effect.{ Clock, IO }
8
import io.github.srs.controller.message.RobotProposal
9
import io.github.srs.controller.protocol.Event
10
import io.github.srs.model.*
11
import io.github.srs.model.SimulationConfig.SimulationStatus.*
12
import io.github.srs.model.entity.dynamicentity.Robot
13
import io.github.srs.model.entity.dynamicentity.behavior.BehaviorContext
14
import io.github.srs.model.entity.dynamicentity.sensor.Sensor.senseAll
15
import io.github.srs.model.logic.*
16
import io.github.srs.utils.EqualityGivenInstances.given
17
import io.github.srs.utils.SimulationDefaults.DebugMode
18
import cats.implicits.*
19
import io.github.srs.utils.random.RNG
20

21
/**
22
 * Module that defines the controller logic for the Scala Robotics Simulator.
23
 */
24
object ControllerModule:
25

×
26
  /**
27
   * Controller trait that defines the interface for the controller.
28
   *
29
   * @tparam S
30
   *   the type of the state, which must extend [[io.github.srs.model.ModelModule.State]].
31
   */
32
  trait Controller[S <: ModelModule.State]:
33
    /**
5✔
34
     * Starts the controller with the initial state.
35
     *
36
     * @param initialState
37
     *   the initial state of the simulation.
38
     */
39
    def start(initialState: S): IO[S]
40

41
    /**
42
     * Runs the simulation loop, processing events from the queue and updating the state.
43
     *
44
     * @param s
45
     *   the current state of the simulation.
46
     * @param queue
47
     *   a concurrent queue that holds events to be processed.
48
     * @return
49
     *   an [[cats.effect.IO]] task that completes when the simulation loop ends.
50
     */
51
    def simulationLoop(s: S, queue: Queue[IO, Event]): IO[S]
52

53
  end Controller
54

55
  /**
56
   * Provider trait that defines the interface for providing a controller.
57
   *
58
   * @tparam S
59
   *   the type of the state, which must extend [[io.github.srs.model.ModelModule.State]].
60
   */
61
  trait Provider[S <: ModelModule.State]:
62
    val controller: Controller[S]
63

64
  /**
65
   * Defines the dependencies required by the controller module. In particular, it requires a
66
   * [[io.github.srs.view.ViewModule.Provider]] and a [[io.github.srs.model.ModelModule.Provider]].
67
   */
68
  type Requirements[S <: ModelModule.State] =
69
    io.github.srs.view.ViewModule.Provider[S] & io.github.srs.model.ModelModule.Provider[S]
70

71
  /**
72
   * Component trait that defines the interface for creating a controller.
73
   *
74
   * @tparam S
75
   *   the type of the simulation state, which must extend [[io.github.srs.model.ModelModule.State]].
76
   */
77
  trait Component[S <: ModelModule.State]:
78
    context: Requirements[S] =>
1✔
79

80
    object Controller:
81

5✔
82
      /**
83
       * Creates a controller instance.
84
       *
85
       * @return
86
       *   a [[Controller]] instance.
87
       */
88
      def apply()(using bundle: LogicsBundle[S]): Controller[S] = new ControllerImpl
89

9✔
90
      /**
91
       * Private controller implementation that delegates the simulation loop to the provided model and view.
92
       */
93
      private class ControllerImpl(using bundle: LogicsBundle[S]) extends Controller[S]:
94

9✔
95
        /**
96
         * Starts the controller with the initial state.
97
         * @param initialState
98
         *   the initial state of the simulation.
99
         * @return
100
         *   an [[IO]] task that completes when the controller is started.
101
         */
102
        override def start(initialState: S): IO[S] =
103
          for
104
            queueSim <- Queue.unbounded[IO, Event]
105
            _ <- context.view.init(queueSim)
10✔
106
            _ <- runBehavior(queueSim, initialState)
107
            result <- simulationLoop(initialState, queueSim)
108
          yield result
109

110
        /**
111
         * Runs the simulation loop, processing events from the queue and updating the state.
112
         * @param s
113
         *   the current state of the simulation.
114
         * @param queue
115
         *   a concurrent queue that holds events to be processed.
116
         * @return
117
         *   an [[IO]] task that completes when the simulation loop ends.
118
         */
119
        override def simulationLoop(s: S, queue: Queue[IO, Event]): IO[S] =
120
          def loop(state: S): IO[S] =
121
            for
122
              startTime <- Clock[IO].realTime.map(_.toMillis)
123
              _ <- runBehavior(queue, state).whenA(state.simulationStatus == RUNNING)
15✔
124
              events <- queue.tryTakeN(None)
5✔
125
              newState <- handleEvents(state, events)
126
              _ <- context.view.render(newState)
127
              result <- handleStopCondition(newState) match
128
                case Some(io) => io
129
                case None =>
130
                  for
131
                    nextState <- nextStep(newState, startTime)
132
                    endTime <- Clock[IO].realTime.map(_.toMillis)
133
                    _ <- if DebugMode then IO.println(s"Simulation loop took ${endTime - startTime} ms") else IO.unit
134
                    res <- loop(nextState)
135
                  yield res
136
            yield result
137

138
          loop(s)
139

5✔
140
        end simulationLoop
141

142
        private def handleStopCondition(state: S): Option[IO[S]] =
143
          state.simulationStatus match
144
            case STOPPED =>
3✔
145
              Some(context.view.close() *> IO.pure(state))
8✔
146
            case ELAPSED_TIME =>
×
147
              Some(context.view.timeElapsed(state) *> IO.pure(state))
8✔
148
            case _ =>
14✔
149
              None
150

2✔
151
        /**
152
         * Processes the next step in the simulation based on the current state and start time.
153
         * @param state
154
         *   the current state of the simulation.
155
         * @param startTime
156
         *   the start time of the current simulation step in milliseconds.
157
         * @return
158
         *   the next state of the simulation wrapped in an [[IO]] task.
159
         */
160
        private def nextStep(state: S, startTime: Long): IO[S] =
161
          state.simulationStatus match
162
            case RUNNING =>
3✔
163
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
8✔
164

8✔
165
            case PAUSED =>
166
              IO.sleep(50.millis).as(state)
×
167

×
168
            case _ =>
169
              IO.pure(state)
170

×
171
        /**
172
         * Runs the behavior of all robots in the environment and collects their action proposals.
173
         * @param queue
174
         *   the queue to which the proposals will be offered through the [[Event.RobotActionProposals]] event.
175
         * @param state
176
         *   the current state of the simulation.
177
         * @return
178
         *   an [[IO]] task that completes when the behavior has been run.
179
         */
180
        private def runBehavior(queue: Queue[IO, Event], state: S): IO[Unit] =
181
          val robots = state.environment.entities.collect { case r: Robot => r }.sortBy(_.id.toString)
182

35✔
183
          def process(remaining: List[Robot], rng: RNG, acc: List[RobotProposal]): IO[(List[RobotProposal], RNG)] =
184
            remaining match
185
              case Nil => IO.pure((acc.reverse, rng))
2✔
186
              case robot :: tail =>
17✔
187
                for
15✔
188
                  sensorReadings <- robot.senseAll[IO](state.environment)
189
                  ctx = BehaviorContext(sensorReadings, rng)
24✔
190
                  (action, newRng) = robot.behavior.run[IO](ctx)
191
                  _ <- queue.offer(Event.Random(newRng))
192
                  next <- process(tail, newRng, RobotProposal(robot, action) :: acc)
193
                yield next
NEW
194

×
195
          for
196
            (proposals, _) <- process(robots, state.simulationRNG, Nil)
197
            _ <- queue.offer(Event.RobotActionProposals(proposals))
12✔
198
          yield ()
199

200
        /**
201
         * Processes tick events, adjusting the tick speed based on the elapsed time since the last tick.
202
         * @param start
203
         *   the start time of the current tick in milliseconds.
204
         * @param tickSpeed
205
         *   the speed of the tick in [[FiniteDuration]].
206
         * @param state
207
         *   the current state of the simulation.
208
         * @return
209
         *   the next state of the simulation wrapped in an [[IO]] task.
210
         */
211
        private def tickEvents(start: Long, tickSpeed: FiniteDuration, state: S): IO[S] =
212
          for
213
            now <- Clock[IO].realTime.map(_.toMillis)
214
            timeToNextTick = tickSpeed.toMillis - (now - start)
18✔
215
            adjustedTickSpeed = if timeToNextTick > 0 then timeToNextTick else 0L
216
            sleepTime = FiniteDuration(adjustedTickSpeed, MILLISECONDS)
217
            _ <- IO.sleep(sleepTime)
218
            tick <- handleEvent(state, Event.Tick(state.dt))
219
          yield tick
220

221
        /**
222
         * Handles a sequence of events, processing them in the order they were received.
223
         * @param state
224
         *   the current state of the simulation.
225
         * @param events
226
         *   the sequence of events to be processed.
227
         * @return
228
         *   the final state of the simulation after processing all events, wrapped in an [[IO]] task.
229
         */
230
        private def handleEvents(state: S, events: Seq[Event]): IO[S] =
231
          for finalState <- events.foldLeft(IO.pure(state)) { (taskState, event) =>
232
              for
11✔
233
                currentState <- taskState
234
                newState <- handleEvent(currentState, event)
235
              yield newState
236
            }
237
          yield finalState
238

239
        /**
240
         * Handles a single event and updates the state accordingly.
241
         * @param state
242
         *   the current state of the simulation.
243
         * @param event
244
         *   the event to be processed.
245
         * @return
246
         *   the updated state of the simulation after processing the event, wrapped in an [[IO]] task.
247
         */
248
        private def handleEvent(state: S, event: Event): IO[S] =
249
          event match
250
            case Event.Tick(deltaTime) =>
2✔
251
              context.model.update(state)(using s => bundle.tickLogic.tick(s, deltaTime))
15✔
252
            case Event.TickSpeed(speed) =>
11✔
253
              context.model.update(state)(using s => bundle.tickLogic.tickSpeed(s, speed))
3✔
254
            case Event.Random(rng) =>
×
255
              context.model.update(state)(using s => bundle.randomLogic.random(s, rng))
15✔
256
            case Event.Pause =>
11✔
257
              context.model.update(state)(using s => bundle.pauseLogic.pause(s))
8✔
258
            case Event.Resume =>
×
259
              context.model.update(state)(using s => bundle.resumeLogic.resume(s))
8✔
260
            case Event.Stop =>
×
261
              context.model.update(state)(using s => bundle.stopLogic.stop(s))
8✔
262
            case Event.RobotActionProposals(proposals) =>
×
263
              context.model.update(state)(using s => bundle.robotActionsLogic.handleRobotActionsProposals(s, proposals))
15✔
264

13✔
265
      end ControllerImpl
266

267
    end Controller
268

269
  end Component
270

271
  /**
272
   * Interface trait that combines the provider and component traits for the controller module.
273
   *
274
   * @tparam S
275
   *   the type of the simulation state, which must extend [[io.github.srs.model.ModelModule.State]].
276
   */
277
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
278
    self: Requirements[S] =>
279
end ControllerModule
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

© 2026 Coveralls, Inc