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

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

27 Aug 2025 08:44AM UTC coverage: 45.321% (-0.4%) from 45.671%
#392

Pull #58

github

GiuliaNardicchia
refactor: remove unused methods and imports from SimulationDSLTest
Pull Request #58: feat: command line interface and dsl simulation

57 of 268 new or added lines in 15 files covered. (21.27%)

7 existing lines in 5 files now uncovered.

1172 of 2586 relevant lines covered (45.32%)

6.35 hits per line

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

0.0
/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 cats.syntax.all.*
9
import io.github.srs.controller.message.RobotProposal
10
import io.github.srs.controller.protocol.Event
11
import io.github.srs.model.*
12
import io.github.srs.model.SimulationConfig.SimulationStatus.{ PAUSED, RUNNING, STOPPED }
13
import io.github.srs.model.UpdateLogic.*
14
import io.github.srs.model.entity.dynamicentity.Robot
15
import io.github.srs.model.entity.dynamicentity.behavior.BehaviorContext
16
import io.github.srs.model.entity.dynamicentity.sensor.Sensor.senseAll
17
import io.github.srs.model.logic.*
18
import io.github.srs.utils.EqualityGivenInstances.given_CanEqual_Event_Event
19
import io.github.srs.utils.SimulationDefaults.debugMode
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 [[ModelModule.State]].
31
   */
32
  trait Controller[S <: ModelModule.State]:
33
    /**
×
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 [[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 [[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 [[ModelModule.State]].
76
   */
77
  trait Component[S <: ModelModule.State]:
78
    context: Requirements[S] =>
×
79

80
    object Controller:
81

×
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

×
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

×
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)
×
106
            _ <- runBehavior(queueSim, initialState)
107
            result <- simulationLoop(initialState, queueSim)
108
          yield result
UNCOV
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] =
NEW
120
          def loop(state: S): IO[S] =
×
121
            for
×
122
              startTime <- Clock[IO].realTime.map(_.toMillis)
×
123
              _ <- runBehavior(queue, state).whenA(state.simulationStatus == RUNNING)
×
124
              events <- queue.tryTakeN(Some(50))
×
125
              newState <- handleEvents(state, events)
126
              _ <- context.view.render(newState)
127
              result <-
128
                if stopCondition(newState) then IO.pure(newState)
129
                else
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
UNCOV
137

×
138
          loop(s)
139

×
140
        end simulationLoop
141

142
        /**
143
         * Checks if the simulation should stop based on the current state.
144
         * @param state
145
         *   the current state of the simulation.
146
         * @return
147
         *   a boolean indicating whether the simulation should stop.
148
         */
149
        private def stopCondition(state: S): Boolean =
150
          state.simulationStatus == STOPPED ||
×
151
            elapsedTimeReached(state.simulationTime, state.elapsedTime)
×
152

×
153
        /**
154
         * Checks if the elapsed time has reached the maximum simulation time.
155
         * @param simulationTime
156
         *   the maximum simulation time, if defined.
157
         * @param elapsedTime
158
         *   the elapsed time since the simulation started.
159
         * @return
160
         *   a boolean indicating whether the elapsed time has reached the maximum simulation time.
161
         */
162
        private def elapsedTimeReached(simulationTime: Option[FiniteDuration], elapsedTime: FiniteDuration): Boolean =
163
          simulationTime.exists(max => elapsedTime >= max)
×
164

×
165
        /**
166
         * Processes the next step in the simulation based on the current state and start time.
167
         * @param state
168
         *   the current state of the simulation.
169
         * @param startTime
170
         *   the start time of the current simulation step in milliseconds.
171
         * @return
172
         *   the next state of the simulation wrapped in an [[IO]] task.
173
         */
174
        private def nextStep(state: S, startTime: Long): IO[S] =
175
          state.simulationStatus match
×
176
            case RUNNING =>
×
177
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
×
178

×
179
            case PAUSED =>
180
              IO.sleep(50.millis).as(state)
×
181

×
182
            case STOPPED =>
183
              IO.pure(state)
×
184

×
185
        /**
186
         * Runs the behavior of all robots in the environment and collects their action proposals.
187
         * @param queue
188
         *   the queue to which the proposals will be offered through the [[Event.RobotActionProposals]] event.
189
         * @param state
190
         *   the current state of the simulation.
191
         * @return
192
         *   an [[IO]] task that completes when the behavior has been run.
193
         */
194
        private def runBehavior(queue: Queue[IO, Event], state: S): IO[Unit] =
195
          for
×
196
            proposals <- state.environment.entities.collect { case robot: Robot => robot }.toList.parTraverse { robot =>
×
197
              for
×
198
                sensorReadings <- robot.senseAll[IO](state.environment)
199
                ctx = BehaviorContext(sensorReadings, state.simulationRNG)
200
                (action, rng) = robot.behavior.run[IO](ctx)
201
                _ <- queue.offer(Event.Random(rng))
202
              yield RobotProposal(robot, action)
203
            }
204
            _ <- queue.offer(Event.RobotActionProposals(proposals))
×
205
          yield ()
206

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

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

×
246
        /**
247
         * Handles a single event and updates the state accordingly.
248
         * @param state
249
         *   the current state of the simulation.
250
         * @param event
251
         *   the event to be processed.
252
         * @return
253
         *   the updated state of the simulation after processing the event, wrapped in an [[IO]] task.
254
         */
255
        private def handleEvent(state: S, event: Event): IO[S] =
256
          event match
×
257
            case Event.Tick(deltaTime) => context.model.tick(state, deltaTime)
×
258
            case Event.TickSpeed(speed) => context.model.tickSpeed(state, speed)
×
259
            case Event.Random(rng) => context.model.random(state, rng)
×
260
            case Event.Pause => context.model.pause(state)
×
261
            case Event.Resume => context.model.resume(state)
×
262
            case Event.Stop => context.model.stop(state)
×
263
            case Event.RobotActionProposals(proposals) => context.model.handleRobotActionsProposals(state, proposals)
×
264

×
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 [[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