egslava

Scala/Akka particle system 3

Sep 27th, 2014
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 6.09 KB | None | 0 0
  1. import akka.event.Logging
  2. import akka.actor.{Actor, ActorSystem, Props}
  3. import org.scalatest.time.Milliseconds
  4. import org.scalatest.time.Milliseconds
  5. import scala.concurrent.duration._
  6. import akka.actor.OneForOneStrategy
  7. import akka.actor.SupervisorStrategy._
  8. import scala.util.Random
  9. import scala.collection.immutable.Range
  10. import scala.collection.mutable.MutableList
  11. import scala.collection.mutable.ListBuffer
  12. import Messages._
  13. import akka.routing.Router
  14. import akka.routing.RoundRobinRouter
  15. import akka.routing.RoundRobinRoutingLogic
  16. import akka.routing.ActorRefRoutee
  17. import akka.io._
  18. import akka.routing._
  19. import akka.actor.Terminated
  20. import akka.actor.ActorLogging
  21.  
  22. object Messages{
  23.   /** from ParticleSystemManager to Worker update its particles */
  24.   val Process = "process"
  25.    
  26.   /** Request from ParticleSystemManager to Worker to grab its stats. */
  27.   val DoStats =     "stats"
  28.    
  29.   /** An answer from Worker to ParticleSystemManager about its stats */
  30.   case class ReadyStats( slowest: Particle, fastest: Particle, count: Int )
  31. }
  32.  
  33. object Config{
  34.   val FRAME_TIME = (1000 / 1) milliseconds
  35.   val NEXT_GENERATION_TIME = FRAME_TIME
  36.   val PARTICLE_SYSTEM = "particlesystem"
  37. }
  38.  
  39. import Config._
  40.  
  41. // Configuration parameters for Point class
  42. object Particle{
  43.   val MAX_LIFE = 64
  44.   val START_X = 0
  45.   val START_Y = 0
  46.   val START_VX  = 0
  47.   val START_VY  = 0
  48.   val START_AX  = 0
  49.   val START_AY  = 0
  50.   val MAX_DIFRACTION = 5
  51. }
  52.  
  53. // Configuration for Workers
  54. object Worker {
  55.   val PARTICLES_PER_WORKER = 64
  56.   val MAX_NEW_PARTICLES_PER_UPDATE = 5
  57. }
  58.  
  59. // Just another configuration object
  60. object ParticleSystemManager {
  61.   val ACTORS_COUNT  = 1
  62. }
  63.  
  64. /** Representation of Particle class -  
  65.  *  position, velocity, acceleration, "life"-time and toString-"rendering"
  66.  */
  67. class Particle{
  68.   protected var x: Int = 0
  69.   protected var y: Int  = Particle.START_Y
  70.   protected var vX: Int = Particle.START_VX
  71.   protected var vY: Int = Particle.START_VY
  72.   protected var aX: Int = Particle.START_AX
  73.   protected var aY: Int = Particle.START_AY
  74.   protected var life: Int = 0   // times of processing (countdown to 0)
  75.  
  76.   reset
  77.  
  78.   override def toString = s"($x, $y, $vX, $vY, $aX, $aY, $life)"
  79.  
  80.   def process(){
  81.     vX  += aX
  82.     vY  += aY
  83.     x   += vX
  84.     y   += vY
  85.     life += 1
  86.   }
  87.  
  88.   def reset(){
  89.     life = 0;
  90.     x   = Particle.START_X + distortion
  91.     y   = Particle.START_Y + distortion
  92.     vX  = Particle.START_VX + distortion
  93.     vY  = Particle.START_VY + distortion
  94.     aX  = Particle.START_AX + distortion
  95.     aY  = Particle.START_AY + distortion
  96.   }
  97.  
  98.   def isDying = life > Particle.MAX_LIFE
  99.  
  100.   def v = Math.abs(Math.sqrt(vX * vX + vY * vY)).toInt
  101.  
  102.   protected def distortion = Random.nextInt(Particle.MAX_DIFRACTION) - Particle.MAX_DIFRACTION / 2
  103. }
  104.  
  105. /**
  106.  * Worker - is a particles buffer (@see Particle) and processor.
  107.  * Receives messages from ParticleSystemManager and updates data.
  108.  * Also can grab some stats and send them to manager
  109.  */
  110. class Worker extends Actor {
  111.  
  112.   val runningParticles = ListBuffer[Particle](new Particle() )
  113.   val deadParticles = ListBuffer.fill(Worker.PARTICLES_PER_WORKER - 1){ new Particle() }
  114.  
  115.   val system = ActorSystem( PARTICLE_SYSTEM )
  116.   import system.dispatcher
  117.   system.scheduler.schedule(0 seconds, NEXT_GENERATION_TIME) { aliveParticles(numParticlesCanBeCreated) }
  118.  
  119.   def receive = {
  120.     case Process => {
  121.       processRunnings
  122.       val dyings = getDyings
  123.       deadParticles ++= dyings
  124.       runningParticles --= dyings
  125.     }
  126.    
  127.     case DoStats => {
  128.       sender ! ReadyStats(runningParticles.minBy( _.v ), runningParticles.maxBy { _.v }, runningParticles.size )  
  129.     }
  130.   }
  131.  
  132.   def aliveParticles(num: Int) {
  133.     for (i <- 0 to num - 1) {
  134.       deadParticles(i)
  135.       runningParticles += deadParticles(i)
  136.     }
  137.     deadParticles.remove(0, num)
  138.   }
  139.  
  140.   def numParticlesCanBeCreated = {
  141.     List(Random.nextInt(Worker.MAX_NEW_PARTICLES_PER_UPDATE - 1) + 1,
  142.         deadParticles.size - 1,
  143.         Worker.PARTICLES_PER_WORKER - runningParticles.size).min
  144.   }
  145.  
  146.   def processRunnings = runningParticles.foreach { _.process }
  147.   def getDyings = runningParticles.filter( _.isDying )
  148.  
  149.  
  150.  
  151.   implicit val timeout = 1 second
  152. }
  153.  
  154. /** Manager of all workers. Send update messages to workers (@see Messages#Process).
  155.  *  Also sends "grab stat"-messages (@see Messages#DoStat) and print stats
  156.  */
  157. class ParticleSystemManager extends Actor with ActorLogging{
  158.  
  159.   val router = context.actorOf( Props[ Worker ].withRouter(BroadcastRouter(ParticleSystemManager.ACTORS_COUNT)), "router" )
  160.  
  161.   val slowestAndFastests = ListBuffer[Particle]()
  162.   var count = 0;
  163.   var actorsAnsweredStatistics = 0
  164.  
  165.   def receive = {
  166.     case Process => {
  167.  
  168.       router ! Process
  169.     }
  170.    
  171.     case DoStats => {
  172.       router ! DoStats
  173.       actorsAnsweredStatistics = ParticleSystemManager.ACTORS_COUNT
  174.     }
  175.    
  176.     case ReadyStats(slowest, fastest, count) => stats(slowest, fastest, count)
  177.   }
  178.  
  179.   def stats(slowest: Particle, fastest: Particle, count: Int){
  180.       slowestAndFastests    += slowest += fastest
  181.       this.count += count
  182.      
  183.       actorsAnsweredStatistics -= 1
  184.       if ( actorsAnsweredStatistics <= 0){
  185.         printAndClearStats();
  186.       }
  187.   }
  188.  
  189.   def printAndClearStats(){
  190.     val slowest = slowestAndFastests.minBy(_.v)
  191.     val fastest = slowestAndFastests.maxBy(_.v)
  192.     log.info(s"Stats. Total particles count: ${count}. Particle with min speed: ${slowest}, particle with max speed: ${fastest}");
  193.     slowestAndFastests.clear
  194.     count = 0
  195.   }
  196.  
  197.   override val supervisorStrategy =
  198.           OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 millisecond) {
  199.     case _: Exception                => Resume
  200.   }
  201. }
  202.  
  203.  
  204. object Main extends App {
  205.   Random.setSeed(System.currentTimeMillis() )
  206.   val system = ActorSystem( PARTICLE_SYSTEM );
  207.   val actor = system.actorOf( Props[ParticleSystemManager], name = "manager" );
  208.  
  209.   import system.dispatcher
  210.   system.scheduler.schedule ( 0 milliseconds, FRAME_TIME, actor, Process)
  211.   system.scheduler.schedule ( 0 milliseconds, 3 seconds, actor, DoStats)
  212. }
Advertisement
Add Comment
Please, Sign In to add comment