1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use rin::math::*;
use rin::graphics::{NodeRef, NodeMut};
use rin::events;
use rinecs::{Entities, Resources, Write, Read, ReadOption, Entity, CreationContext};
use crate::transformation::Transformation;
use crate::time::Clock;
use crate::Scene;

#[derive(Component, Clone, Debug, Serialize, Deserialize)]
pub struct Path(Polyline);

#[derive(Component, Clone, Debug, Serialize, Deserialize)]
pub struct Speed(f32);

impl Speed{
    pub fn set(&mut self, d: f32){
        self.0 = d
    }
}

#[derive(Component, Clone, Debug, Serialize, Deserialize)]
pub struct Delta(f32);

impl Delta{
    pub fn set(&mut self, d: f32){
        self.0 = d
    }
}

#[derive(Component, Clone, Debug, Serialize, Deserialize)]
pub struct CurrentPosition{
    idx: usize,
    pct: f64
}

impl CurrentPosition{
    pub fn idx(&self) -> usize{
        self.idx
    }

    pub fn fidx(&self) -> f64{
        self.idx as f64 + self.pct
    }

    pub fn pct_current_segment(&self) -> f64{
        self.pct
    }

    pub fn reset(&mut self){
        self.idx = 0;
        self.pct = 0.;
    }
}

#[derive(Component, Debug, Serialize)]
pub struct Parameters{
    pub doloop: events::Parameter<'static, bool>,
}

pub struct PathFollower;

impl crate::Bundle for PathFollower{
    fn setup(self, world: &mut Scene){
        world.add_system_with_name(path_follower, "path follower");
    }

    fn register(world: &mut Scene){
        world.register_component::<Path>();
        world.register_component::<Speed>();
        world.register_component::<Delta>();
        world.register_component::<CurrentPosition>();
    }
}

#[derive(Filter)]
struct EntityWithPath<'a>{
    transformation: Write<'a, Transformation>,
    path: Read<'a, Path>,
    speed: ReadOption<'a, Speed>,
    delta: ReadOption<'a, Delta>,
    current_position: Write<'a, CurrentPosition>,
    // parameters: Read<'a, Parameters>,
}

impl<'a> EntityWithPath<'a>{
    fn next_non_zero_segment(&mut self) -> Option<f32>{
        self.path.next_non_zero_segment(self.current_position.idx)
            .and_then(|idx| self.path.segment_length(idx))
    }

    fn arrived(&self) -> bool {
        self.current_position.idx == self.path.len() - 1
    }
}

fn path_follower(entities: Entities, resources: Resources){
    let tdelta = resources.get::<Clock>()
        .map(|clock| clock.last_frame_time()
            .elapsed_game_time()
            .as_seconds());

    for mut entity in entities.iter_for::<EntityWithPath>(){
        if !entity.path.is_empty() && (!entity.arrived() || entity.path.is_closed()){
            let delta = if let Some(delta) = *entity.delta {
                delta.0 as f64
            }else{
                tdelta.unwrap() * entity.speed.unwrap().0 as f64
            };

            if delta == 0. {
                continue;
            }

            let segment_distance = entity.next_non_zero_segment();

            if segment_distance.is_none() {
                continue;
            }

            let segment_distance = segment_distance.unwrap();

            let next_pct = entity.current_position.pct + delta / segment_distance as f64;
            if next_pct > 1. {
                entity.current_position.idx += 1;
                if entity.path.is_closed() {
                    entity.current_position.idx = entity.path
                        .wrap_index(entity.current_position.idx as isize)
                        .unwrap();
                }
                if !entity.arrived() {
                    let rem = (1. - entity.current_position.pct) * segment_distance as f64;
                    if let Some(segment_distance) = entity.next_non_zero_segment(){
                        let rem_delta = delta - rem;
                        entity.current_position.pct = rem_delta / segment_distance as f64;
                    }else if !entity.path.is_closed() {
                        entity.current_position.idx = entity.path.len() - 1;
                        entity.current_position.pct = 0.;
                    }else{
                        continue;
                    }
                }else{
                    entity.current_position.pct = 0.;
                }
            }else{
                entity.current_position.pct = next_pct;
            }

            let fidx = entity.current_position.idx as f64 + entity.current_position.pct;
            let next_position;
            let next_direction;
            if !entity.arrived() || entity.path.is_closed() {
                next_position = entity.path.lerped_point_at(fidx as f32).unwrap();
                next_direction = entity.path.lerped_tangent_at(fidx as f32);
            }else{
                next_position = *entity.path.last().unwrap();
                next_direction = entity.path.tangent_at(entity.path.len() - 1);
            }

            entity.transformation.set_position(pnt3!(next_position, 0.));
            if let Some(next_direction) = next_direction {
                let curr_direction = -entity.transformation.y_axis().xy();
                let delta_orientation = Rotation2::rotation_between(&curr_direction, &next_direction);
                let delta_angle = Rad(delta_orientation.angle());
                let delta_orientation = UnitQuat::from_axis_angle(&Vec3::z_axis(), delta_angle.value());
                let dst_orientation = delta_orientation * entity.transformation.orientation();
                entity.transformation.set_orientation(dst_orientation);
            }
        }
    }
}

pub trait PathFollowerBuilder{
    fn add_path_follower(&mut self, entity: &Entity, initial_speed: f32, path: Option<Polyline>);
    fn add_path_follower_with_delta_provider(&mut self, entity: &Entity, path: Option<Polyline>);
}

impl<C: CreationContext> PathFollowerBuilder for C{
    fn add_path_follower(&mut self, entity: &Entity, initial_speed: f32, path: Option<Polyline>){
        let path = path.unwrap_or(Polyline::new());
        self.add_component_to(entity, Path(path));
        self.add_component_to(entity, Speed(initial_speed));
        self.add_component_to(entity, CurrentPosition{idx: 0, pct: 0.});
    }

    fn add_path_follower_with_delta_provider(&mut self, entity: &Entity, path: Option<Polyline>){
        let path = path.unwrap_or(Polyline::new());
        self.add_component_to(entity, Path(path));
        self.add_component_to(entity, Delta(0.));
        self.add_component_to(entity, CurrentPosition{idx: 0, pct: 0.});
    }
}