@@ -24,15 +24,17 @@ pub struct Props {
2424pub struct Simulation {
2525 boids : Vec < Boid > ,
2626 interval : Interval ,
27+ settings : Settings ,
28+ generation : usize ,
2729}
2830impl Component for Simulation {
2931 type Message = Msg ;
3032 type Properties = Props ;
3133
3234 fn create ( ctx : & Context < Self > ) -> Self {
33- let settings = & ctx. props ( ) . settings ;
35+ let settings = ctx. props ( ) . settings . clone ( ) ;
3436 let boids = ( 0 ..settings. boids )
35- . map ( |_| Boid :: new_random ( settings) )
37+ . map ( |_| Boid :: new_random ( & settings) )
3638 . collect ( ) ;
3739
3840 let interval = {
@@ -42,7 +44,13 @@ impl Component for Simulation {
4244 } )
4345 } ;
4446
45- Self { boids, interval }
47+ let generation = ctx. props ( ) . generation ;
48+ Self {
49+ boids,
50+ interval,
51+ settings,
52+ generation,
53+ }
4654 }
4755
4856 fn update ( & mut self , ctx : & Context < Self > , msg : Self :: Message ) -> bool {
@@ -65,22 +73,30 @@ impl Component for Simulation {
6573 }
6674
6775 fn changed ( & mut self , ctx : & Context < Self > ) -> bool {
68- self . boids . clear ( ) ;
76+ let props = ctx. props ( ) ;
77+ let should_reset = self . settings != props. settings || self . generation != props. generation ;
78+ self . settings = props. settings . clone ( ) ;
79+ self . generation = props. generation ;
80+ if should_reset {
81+ self . boids . clear ( ) ;
6982
70- let settings = & ctx . props ( ) . settings ;
71- self . boids
72- . resize_with ( settings. boids , || Boid :: new_random ( settings) ) ;
83+ let settings = & props. settings ;
84+ self . boids
85+ . resize_with ( settings. boids , || Boid :: new_random ( settings) ) ;
7386
74- // as soon as the previous task is dropped it is cancelled.
75- // We don't need to worry about manually stopping it.
76- self . interval = {
77- let link = ctx. link ( ) . clone ( ) ;
78- Interval :: new ( settings. tick_interval_ms as u32 , move || {
79- link. send_message ( Msg :: Tick )
80- } )
81- } ;
87+ // as soon as the previous task is dropped it is cancelled.
88+ // We don't need to worry about manually stopping it.
89+ self . interval = {
90+ let link = ctx. link ( ) . clone ( ) ;
91+ Interval :: new ( settings. tick_interval_ms as u32 , move || {
92+ link. send_message ( Msg :: Tick )
93+ } )
94+ } ;
8295
83- true
96+ true
97+ } else {
98+ false
99+ }
84100 }
85101
86102 fn view ( & self , _ctx : & Context < Self > ) -> Html {
0 commit comments