summaryrefslogtreecommitdiffstats
path: root/src/tacmap/orbit_render.rs
blob: 7c0a0891d398dee8016edbec1fe0259b5986605d (plain) (blame)
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use std::error::Error;

use super::*;

use crate::solar_system::body::{BodyId, OrbitalBody};
use crate::solar_system::orbit::StaticOrbiter;
use crate::timeman::{self, Second};
use crate::wgpuctx::{WgpuCtx, pipeline::RenderPipelineBuilder};

pub struct OrbitRenderer
{
    needs_rebuild: bool,
    last_tick: Option<Second>,

    pipeline: wgpu::RenderPipeline,

    orbit_vertex_buffers: Option<Vec<(BodyId, wgpu::Buffer)>>,
    origin_buffer: Option<wgpu::Buffer>,
    origin_bind_group: Option<wgpu::BindGroup>,
    origin_bind_group_layout: wgpu::BindGroupLayout
}

impl OrbitRenderer
{
     pub fn new(
        wgpuctx: &WgpuCtx)
    -> Self {
        let shader = wgpuctx.create_shader(
            wgpu::include_wgsl!(concat!(
                    env!("CARGO_MANIFEST_DIR"),
                    "/assets/shaders/tacmap/orbit.wgsl")
        ));

        let origin_bind_group_layout = wgpuctx.device().create_bind_group_layout(
            &wgpu::BindGroupLayoutDescriptor {
                label: None,
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: true },
                            has_dynamic_offset: false,
                            min_binding_size: None
                        },
                        count: None
                    }
                ]
            }
        );

        let render_pipeline = RenderPipelineBuilder::new(&shader)
            .add_bindgroup(&Camera::bindgroup_layout(wgpuctx))
            .add_bindgroup(&origin_bind_group_layout)
            .add_vertex_layout(OrbitVertex::descr())
            .primitive_topology(wgpu::PrimitiveTopology::TriangleStrip)
            .cull_mode(None)
            .build(Some("Tactical map orbit render pipeline"), wgpuctx);

        Self {
            needs_rebuild: true,
            last_tick: None,
            pipeline: render_pipeline,
            orbit_vertex_buffers: None,
            origin_buffer: None,
            origin_bind_group: None,
            origin_bind_group_layout: origin_bind_group_layout
        }
    }

    pub fn mark_to_rebuild(&mut self)
    { self.needs_rebuild = true; }

    fn create_orbit_buffer<T: StaticOrbiter>(
        &self,
        wgpuctx: &WgpuCtx,
        orbiter: &T,
        time: Second)
    -> Option<(usize, wgpu::Buffer)>
    {
        let orbit = match orbiter.orbit() {
            Some(orbit) => orbit,
            None => { return None; }
        };

        let period = orbit.period(orbiter);

        let num_points = ((period / timeman::HOUR) as usize).clamp(90, 360);
        let period_interval = period as f64 / num_points as f64;

        let mut points = vec![
            OrbitVertex::default();(num_points+1)*2];

        for i in 0..num_points {
            let position = orbit.calculate_position_at(
                orbiter,
                time + (i as f64 * period_interval) as Second);

            points[i*2].origin_id = orbit.parent() as _;
            points[i*2].position = [
                position.x as f32,
                position.y as f32,
                position.z as f32
            ];
            
            points[(i*2)+1] = points[i*2];
        }
        points[num_points*2] = points[0];
        points[num_points*2+1] = points[1];

        let buffer = wgpuctx.create_buffer_init(
            &wgpu::util::BufferInitDescriptor {
                label: None,
                usage: wgpu::BufferUsages::VERTEX,
                contents: bytemuck::cast_slice(&points)
            }
        );
        Some(((num_points+1)*2, buffer))
    }

    pub fn rebuild(
        &mut self,
        wgpuctx: &WgpuCtx,
        solar_system: &SolarSystem)
    {
        if self.orbit_vertex_buffers.is_some() && !self.needs_rebuild {
            return;
        }
        self.needs_rebuild = false;

        match &self.orbit_vertex_buffers {
            Some(buffers) => {
                for buffer in buffers {
                    buffer.1.destroy();
                }
                self.orbit_vertex_buffers = None;
            },
            None => {}
        };

        //From the solar system's bodies, calculate the orbits.
        let bodies = solar_system.bodies();

        match &self.origin_buffer {
            Some(buffer) => {
                buffer.destroy();
            }
            None => {}
        };
        let origin_buffer = wgpuctx.create_buffer(
            &wgpu::BufferDescriptor {
                label: None,
                size: (std::mem::size_of::<[f32;3]>() * bodies.len()) as _,
                usage: wgpu::BufferUsages::COPY_DST
                    | wgpu::BufferUsages::STORAGE,
                mapped_at_creation: false
            }
        );

        self.origin_bind_group = Some(wgpuctx.device().create_bind_group(
            &wgpu::BindGroupDescriptor {
                label: None,
                layout: &self.origin_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: origin_buffer.as_entire_binding()
                    }
                ]
            }
        ));
        self.origin_buffer = Some(origin_buffer);

        self.orbit_vertex_buffers = Some(bodies.iter().filter_map(|body| {
            self.create_orbit_buffer(wgpuctx, body, 0)
        }).collect::<Vec<_>>());
    }

    pub fn update(
        &mut self,
        wgpuctx: &WgpuCtx,
        solar_system: &SolarSystem,
        time: Second)
    -> Result<(), Box<dyn Error>>
    {
        let tick = time / OrbitalBody::TICK_DURATION;
        if self.last_tick.is_some_and(|t| { t == tick }) {
            return Ok(());
        }
        
        self.last_tick = Some(time);
        let positions = solar_system.bodies().iter().map(|body| {
            let pos = solar_system.body_position(body, time);
            [ pos.x as f32, pos.y as f32, pos.z as f32 ]
        }).collect::<Vec<_>>();

        match &self.origin_buffer {
            Some(buffer) => {
                wgpuctx.queue().write_buffer(buffer, 0, bytemuck::cast_slice(&positions));
            },
            None => { return Err(Box::new(NeedsRebuildError)); }
        };

        //let bodies = solar_system.bodies();
        /*self.orbit_vertex_buffers = Some(bodies.iter().map(|body| {
            self.create_orbit_buffer_for_body(wgpuctx, body, tick_time)
        }).collect::<Vec<_>>());*/
        Ok(())
    }

    pub fn render(
        &self,
        pass: &mut wgpu::RenderPass,
        camera: &Camera)
    {
        let buffers = match &self.orbit_vertex_buffers {
            Some(v) => v,
            None => return
        };

        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, camera.bindgroup(), &[]);

        match &self.origin_bind_group {
            Some(bind_group) => { pass.set_bind_group(1, bind_group, &[]); },
            None => { return; }
        }

        for (num_points, buffer) in buffers {
            pass.set_vertex_buffer(0, buffer.slice(..));
            pass.draw(0..(*num_points as u32), 0..1);
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone, Default, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct OrbitVertex
{
    pub origin_id: u32,
    pub position: [f32;3]
}

impl OrbitVertex
{
    const ATTRIBS: [wgpu::VertexAttribute;2] =
        wgpu::vertex_attr_array![0 => Uint32, 1 => Float32x3];

    pub fn descr()
    -> wgpu::VertexBufferLayout<'static> {
        use std::mem;

        wgpu::VertexBufferLayout {
            array_stride: mem::size_of::<Self>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &Self::ATTRIBS
        }
    }
}