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

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

27 Aug 2025 07:33AM UTC coverage: 45.671% (+0.004%) from 45.667%
#389

push

github

srs-mate
chore: format code

1113 of 2437 relevant lines covered (45.67%)

6.31 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[Unit]
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[Unit]
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[Unit] =
103
          for
×
104
            queueSim <- Queue.unbounded[IO, Event]
×
105
            _ <- context.view.init(queueSim)
×
106
            _ <- runBehavior(queueSim, initialState)
107
            _ <- simulationLoop(initialState, queueSim)
108
          yield ()
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[Unit] =
120
          def loop(state: S): IO[Unit] =
×
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
              nextState <- nextStep(newState, startTime)
128
              endTime <- Clock[IO].realTime.map(_.toMillis)
129
              _ <- if debugMode then IO.println(s"Simulation loop took ${endTime - startTime} ms") else IO.unit
130
              _ <- if stopCondition(nextState) then IO.unit else loop(nextState)
131
            yield ()
132

×
133
          loop(s)
134

×
135
        /**
136
         * Checks if the simulation should stop based on the current state.
137
         * @param state
138
         *   the current state of the simulation.
139
         * @return
140
         *   a boolean indicating whether the simulation should stop.
141
         */
142
        private def stopCondition(state: S): Boolean =
143
          state.simulationStatus == STOPPED ||
×
144
            elapsedTimeReached(state.simulationTime, state.elapsedTime)
×
145

×
146
        /**
147
         * Checks if the elapsed time has reached the maximum simulation time.
148
         * @param simulationTime
149
         *   the maximum simulation time, if defined.
150
         * @param elapsedTime
151
         *   the elapsed time since the simulation started.
152
         * @return
153
         *   a boolean indicating whether the elapsed time has reached the maximum simulation time.
154
         */
155
        private def elapsedTimeReached(simulationTime: Option[FiniteDuration], elapsedTime: FiniteDuration): Boolean =
156
          simulationTime.exists(max => elapsedTime >= max)
×
157

×
158
        /**
159
         * Processes the next step in the simulation based on the current state and start time.
160
         * @param state
161
         *   the current state of the simulation.
162
         * @param startTime
163
         *   the start time of the current simulation step in milliseconds.
164
         * @return
165
         *   the next state of the simulation wrapped in an [[IO]] task.
166
         */
167
        private def nextStep(state: S, startTime: Long): IO[S] =
168
          state.simulationStatus match
×
169
            case RUNNING =>
×
170
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
×
171

×
172
            case PAUSED =>
173
              IO.sleep(50.millis).as(state)
×
174

×
175
            case STOPPED =>
176
              IO.pure(state)
×
177

×
178
        /**
179
         * Runs the behavior of all robots in the environment and collects their action proposals.
180
         * @param queue
181
         *   the queue to which the proposals will be offered through the [[Event.RobotActionProposals]] event.
182
         * @param state
183
         *   the current state of the simulation.
184
         * @return
185
         *   an [[IO]] task that completes when the behavior has been run.
186
         */
187
        private def runBehavior(queue: Queue[IO, Event], state: S): IO[Unit] =
188
          for
×
189
            proposals <- state.environment.entities.collect { case robot: Robot => robot }.toList.parTraverse { robot =>
×
190
              for
×
191
                sensorReadings <- robot.senseAll[IO](state.environment)
192
                ctx = BehaviorContext(sensorReadings, state.simulationRNG)
193
                (action, rng) = robot.behavior.run[IO](ctx)
194
                _ <- queue.offer(Event.Random(rng))
195
              yield RobotProposal(robot, action)
196
            }
197
            _ <- queue.offer(Event.RobotActionProposals(proposals))
×
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)
×
215
            adjustedTickSpeed = if timeToNextTick > 0 then timeToNextTick else 0L
216
            sleepTime = FiniteDuration(adjustedTickSpeed, MILLISECONDS)
217
            _ <- IO.sleep(sleepTime)
×
218
            tick <- handleEvent(state, Event.Tick(tickSpeed))
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
×
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) => context.model.tick(state, deltaTime)
×
251
            case Event.TickSpeed(speed) => context.model.tickSpeed(state, speed)
×
252
            case Event.Random(rng) => context.model.random(state, rng)
×
253
            case Event.Pause => context.model.pause(state)
×
254
            case Event.Resume => context.model.resume(state)
×
255
            case Event.Stop => context.model.stop(state)
×
256
            case Event.RobotActionProposals(proposals) => context.model.handleRobotActionsProposals(state, proposals)
×
257

×
258
      end ControllerImpl
259

260
    end Controller
261

262
  end Component
263

264
  /**
265
   * Interface trait that combines the provider and component traits for the controller module.
266
   *
267
   * @tparam S
268
   *   the type of the simulation state, which must extend [[ModelModule.State]].
269
   */
270
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
271
    self: Requirements[S] =>
272
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