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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//! High level Rendering API designed for cross platform rendering and
//! windowing.

// Module Exports
pub mod buffer;
pub mod command;
pub mod mesh;
pub mod pipeline;
pub mod render_pass;
pub mod shader;
pub mod vertex;
pub mod viewport;
pub mod window;

use std::{
  mem::swap,
  rc::Rc,
};

/// ColorFormat is a type alias for the color format used by the surface and
/// vertex buffers. They denote the size of the color channels and the number of
/// channels being used.
pub use lambda_platform::gfx::surface::ColorFormat;
use lambda_platform::gfx::{
  command::{
    Command,
    CommandBufferBuilder,
    CommandBufferFeatures,
    CommandBufferLevel,
  },
  framebuffer::FramebufferBuilder,
  surface::SwapchainBuilder,
};

use self::{
  command::RenderCommand,
  pipeline::RenderPipeline,
  render_pass::RenderPass,
};

/// A RenderContext is a localized rendering context that can be used to render
/// to a window. It is localized to a single window at the moment.
pub struct RenderContextBuilder {
  name: String,
  render_timeout: u64,
}

impl RenderContextBuilder {
  /// Create a new localized RenderContext with the given name.
  pub fn new(name: &str) -> Self {
    return Self {
      name: name.to_string(),
      render_timeout: 1_000_000_000,
    };
  }

  /// The time rendering has to complete before a timeout occurs.
  pub fn with_render_timeout(mut self, render_timeout: u64) -> Self {
    self.render_timeout = render_timeout;
    return self;
  }

  /// Builds a RenderContext and injects it into the application window.
  /// Currently only supports building a Rendering Context utilizing the
  /// systems primary GPU.
  pub fn build(self, window: &window::Window) -> RenderContext {
    let RenderContextBuilder {
      name,
      render_timeout,
    } = self;

    let mut instance = internal::InstanceBuilder::new()
      .build::<internal::RenderBackend>(name.as_str());
    let surface = Rc::new(
      internal::SurfaceBuilder::new().build(&instance, window.window_handle()),
    );

    // Build a GPU with a Graphical Render queue that can render to our surface.
    let mut gpu = internal::GpuBuilder::new()
      .with_render_queue_type(internal::RenderQueueType::Graphical)
      .build(&mut instance, Some(&surface))
      .expect("Failed to build a GPU with a graphical render queue.");

    // Build command pool and allocate a single buffer named Primary
    let command_pool = internal::CommandPoolBuilder::new().build(&gpu);

    // Build our rendering submission fence and semaphore.
    let submission_fence = internal::RenderSubmissionFenceBuilder::new()
      .with_render_timeout(render_timeout)
      .build(&mut gpu);

    let render_semaphore =
      internal::RenderSemaphoreBuilder::new().build(&mut gpu);

    return RenderContext {
      name,
      instance,
      gpu,
      surface: surface.clone(),
      frame_buffer: None,
      submission_fence: Some(submission_fence),
      render_semaphore: Some(render_semaphore),
      command_pool: Some(command_pool),
      render_passes: vec![],
      render_pipelines: vec![],
    };
  }
}

/// Generic Rendering API setup to use the current platforms primary
/// Rendering Backend
pub struct RenderContext {
  name: String,
  instance: internal::Instance<internal::RenderBackend>,
  gpu: internal::Gpu<internal::RenderBackend>,
  surface: Rc<internal::Surface<internal::RenderBackend>>,
  frame_buffer: Option<Rc<internal::Framebuffer<internal::RenderBackend>>>,
  submission_fence:
    Option<internal::RenderSubmissionFence<internal::RenderBackend>>,
  render_semaphore: Option<internal::RenderSemaphore<internal::RenderBackend>>,
  command_pool: Option<internal::CommandPool<internal::RenderBackend>>,
  render_passes: Vec<RenderPass>,
  render_pipelines: Vec<RenderPipeline>,
}

pub type ResourceId = usize;

impl RenderContext {
  /// Permanently transfer a render pipeline to the render context in exchange
  /// for a resource ID that you can use in render commands.
  pub fn attach_pipeline(&mut self, pipeline: RenderPipeline) -> ResourceId {
    let index = self.render_pipelines.len();
    self.render_pipelines.push(pipeline);
    return index;
  }

  /// Permanently transfer a render pipeline to the render context in exchange
  /// for a resource ID that you can use in render commands.
  pub fn attach_render_pass(&mut self, render_pass: RenderPass) -> ResourceId {
    let index = self.render_passes.len();
    self.render_passes.push(render_pass);
    return index;
  }

  /// destroys the RenderContext and all associated resources.
  pub fn destroy(mut self) {
    println!("{} will now start destroying resources.", self.name);

    // Destroy the submission fence and rendering semaphore.
    self
      .submission_fence
      .take()
      .expect(
        "Couldn't take the submission fence from the context and destroy it.",
      )
      .destroy(&self.gpu);
    self
      .render_semaphore
      .take()
      .expect("Couldn't take the rendering semaphore from the context and destroy it.")
      .destroy(&self.gpu);

    self
      .command_pool
      .as_mut()
      .unwrap()
      .deallocate_command_buffer("primary");

    self
      .command_pool
      .take()
      .expect("Couldn't take the command pool from the context and destroy it.")
      .destroy(&self.gpu);

    // Destroy render passes.
    let mut render_passes = vec![];
    swap(&mut self.render_passes, &mut render_passes);

    for render_pass in render_passes {
      render_pass.destroy(&self);
    }

    // Destroy render pipelines.
    let mut render_pipelines = vec![];
    swap(&mut self.render_pipelines, &mut render_pipelines);

    for render_pipeline in render_pipelines {
      render_pipeline.destroy(&self);
    }

    // Takes the inner surface and destroys it.
    let mut surface = Rc::try_unwrap(self.surface)
      .expect("Couldn't obtain the surface from the context.");

    surface.remove_swapchain(&self.gpu);
    surface.destroy(&self.instance);
  }

  pub fn allocate_and_get_frame_buffer(
    &mut self,
    render_pass: &internal::RenderPass<internal::RenderBackend>,
  ) -> Rc<lambda_platform::gfx::framebuffer::Framebuffer<internal::RenderBackend>>
  {
    let frame_buffer = FramebufferBuilder::new().build(
      &mut self.gpu,
      &render_pass,
      self.surface.as_ref(),
    );

    // TODO(vmarcella): Update the framebuffer allocation to not be so hacky.
    // FBAs can only be allocated once a render pass has begun, but must be
    // cleaned up after commands have been submitted forcing us
    self.frame_buffer = Some(Rc::new(frame_buffer));
    return self.frame_buffer.as_ref().unwrap().clone();
  }

  /// Allocates a command buffer and records commands to the GPU. This is the
  /// primary entry point for submitting commands to the GPU and where rendering
  /// will occur.
  pub fn render(&mut self, commands: Vec<RenderCommand>) {
    let (width, height) = self
      .surface
      .size()
      .expect("Surface has no size configured.");

    let swapchain = SwapchainBuilder::new()
      .with_size(width, height)
      .build(&self.gpu, &self.surface);

    if self.surface.needs_swapchain() {
      Rc::get_mut(&mut self.surface)
        .expect("Failed to get mutable reference to surface.")
        .apply_swapchain(&self.gpu, swapchain, 1_000_000_000)
        .expect("Failed to apply the swapchain to the surface.");
    }

    self
      .submission_fence
      .as_mut()
      .expect("Failed to get the submission fence.")
      .block_until_ready(&mut self.gpu, None);

    let platform_command_list = commands
      .into_iter()
      .map(|command| command.into_platform_command(self))
      .collect();

    let mut command_buffer =
      CommandBufferBuilder::new(CommandBufferLevel::Primary)
        .with_feature(CommandBufferFeatures::ResetEverySubmission)
        .build(
          self
            .command_pool
            .as_mut()
            .expect("No command pool to create a buffer from"),
          "primary",
        );

    // Start recording commands, issue the high level render commands
    // that came from an application, and then submit the commands to the GPU
    // for rendering.
    command_buffer.issue_command(PlatformRenderCommand::BeginRecording);
    command_buffer.issue_commands(platform_command_list);
    command_buffer.issue_command(PlatformRenderCommand::EndRecording);

    self.gpu.submit_command_buffer(
      &mut command_buffer,
      vec![self.render_semaphore.as_ref().unwrap()],
      self.submission_fence.as_mut().unwrap(),
    );

    self
      .gpu
      .render_to_surface(
        Rc::get_mut(&mut self.surface)
          .expect("Failed to obtain a surface to render on."),
        self.render_semaphore.as_mut().unwrap(),
      )
      .expect("Failed to render to the surface");

    // Destroys the frame buffer after the commands have been submitted and the
    // frame buffer is no longer needed.
    match self.frame_buffer {
      Some(_) => {
        Rc::try_unwrap(self.frame_buffer.take().unwrap())
          .expect("Failed to unwrap the frame buffer.")
          .destroy(&self.gpu);
      }
      None => {}
    }
  }

  pub fn resize(&mut self, width: u32, height: u32) {
    let swapchain = SwapchainBuilder::new()
      .with_size(width, height)
      .build(&self.gpu, &self.surface);

    if self.surface.needs_swapchain() {
      Rc::get_mut(&mut self.surface)
        .expect("Failed to get mutable reference to surface.")
        .apply_swapchain(&self.gpu, swapchain, 1_000_000_000)
        .expect("Failed to apply the swapchain to the surface.");
    }
  }

  /// Get the render pass with the resource ID that was provided upon
  /// attachment.
  pub fn get_render_pass(&self, id: ResourceId) -> &RenderPass {
    return &self.render_passes[id];
  }

  /// Get the render pipeline with the resource ID that was provided upon
  /// attachment.
  pub fn get_render_pipeline(&mut self, id: ResourceId) -> &RenderPipeline {
    return &self.render_pipelines[id];
  }
}

impl RenderContext {
  /// Internal access to the RenderContext's GPU.
  pub(super) fn internal_gpu(&self) -> &internal::Gpu<internal::RenderBackend> {
    return &self.gpu;
  }

  /// Internal mutable access to the RenderContext's GPU.
  pub(super) fn internal_mutable_gpu(
    &mut self,
  ) -> &mut internal::Gpu<internal::RenderBackend> {
    return &mut self.gpu;
  }

  pub(super) fn internal_surface(
    &self,
  ) -> Rc<lambda_platform::gfx::surface::Surface<internal::RenderBackend>> {
    return self.surface.clone();
  }
}

type PlatformRenderCommand = Command<internal::RenderBackend>;

pub(crate) mod internal {

  use lambda_platform::gfx::api::RenderingAPI as RenderContext;
  pub type RenderBackend = RenderContext::Backend;

  pub use lambda_platform::{
    gfx::{
      command::{
        CommandBuffer,
        CommandBufferBuilder,
        CommandPool,
        CommandPoolBuilder,
      },
      fence::{
        RenderSemaphore,
        RenderSemaphoreBuilder,
        RenderSubmissionFence,
        RenderSubmissionFenceBuilder,
      },
      framebuffer::Framebuffer,
      gpu::{
        Gpu,
        GpuBuilder,
        RenderQueueType,
      },
      pipeline::RenderPipelineBuilder,
      render_pass::{
        RenderPass,
        RenderPassBuilder,
      },
      surface::{
        Surface,
        SurfaceBuilder,
      },
      Instance,
      InstanceBuilder,
    },
    shaderc::ShaderKind,
  };
}