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
#![deny(missing_docs)]
#![feature(use_extern_macros)]

//! A Shadertoy rip-off.
//!
//! There are examples in the repository.

// Crates

pub extern crate gfx;
pub extern crate glutin;
pub extern crate image;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;

// Modules

mod error;
mod game;
mod pipeline;

// Imports

use gfx::{Device, Encoder, Factory, Slice};
use gfx::format::{Rgba8, DepthStencil};
use gfx::handle::Sampler;
use gfx::pso::{PipelineData, PipelineInit, PipelineState};
use gfx::texture::{AaMode, Kind, Mipmap};
use gfx::traits::FactoryExt;
use gfx_device_gl::{CommandBuffer, Device as GlDevice, Factory as GlFactory, Resources};
use glutin::{ContextBuilder, EventsLoop, GlContext, GlWindow, WindowBuilder};
use image::RgbaImage;

// Type Aliases

/// The `gfx-rs` resource used in this crate.
pub type R = Resources;
/// A color buffer handle.
pub type RenderTargetView = gfx::handle::RenderTargetView<R, Rgba8>;
/// A depth-stencil buffer handle.
pub type DepthStencilView = gfx::handle::DepthStencilView<R, DepthStencil>;
/// A texture handle.
pub type ShaderResourceView  = gfx::handle::ShaderResourceView<R, [f32; 4]>;

/// A compiled shader.
pub type Shader<T> = PipelineState<R, T>;
/// A loaded texture.
pub type Texture = (ShaderResourceView, Sampler<R>);

// Exports

pub use error::{Error, Result};
pub use game::Game;

// Data Types

pub use gfx::{Global, TextureSampler};
/// A link type for the color buffer.
pub type RenderTarget = gfx::RenderTarget<Rgba8>;
/// A link type for the depth buffer.
pub type DepthTarget = gfx::DepthTarget<DepthStencil>;

// Default Shaders

const VERTEX_SHADER: &'static [u8] = b"
#version 130

void main() {
    float x = -1.0 + float((gl_VertexID & 1) << 2);
    float y = -1.0 + float((gl_VertexID & 2) << 1);
    gl_Position = vec4(x, y, 0, 1);
}
";

// Window

/// A window that you can draw on.
pub struct Window {
    window: GlWindow,
    device: GlDevice,
    factory: GlFactory,
    rtv: RenderTargetView,
    stv: DepthStencilView,
    encoder: Encoder<R, CommandBuffer>,
}

impl Window {
    /// Make a new window that runs on the given event loop.
    pub fn new(events: &EventsLoop) -> Self {
        let (window, device, mut factory, rtv, stv) = gfx_window_glutin::init(
            WindowBuilder::new(),
            ContextBuilder::new().with_vsync(true),
            &events,
        );

        Window {
            encoder: factory.create_command_buffer().into(),
            window, device, factory, rtv, stv,
        }
    }

    /// Compile a shader.
    pub fn shader<I>(&mut self, init: I, shader: &[u8])
        -> Result<Shader<I::Meta>>
    where
        I: PipelineInit,
    {
        Ok(self.factory.create_pipeline_simple(
            VERTEX_SHADER,
            shader,
            init,
        )?)
    }

    /// Pass the given data to the shader and draw!
    pub fn draw<'a, D, F>(&'a mut self, shader: &Shader<D::Meta>, data: F)
    where
        D: PipelineData<R>,
        F: FnOnce(&'a RenderTargetView, &'a DepthStencilView) -> D
    {
        let slice = Slice {
            start: 0,
            end: 3,
            base_vertex: 0,
            instances: None,
            buffer: Default::default(),
        };

        self.encoder.draw(&slice, shader, &data(&self.rtv, &self.stv));
    }

    /// Finish the frame.
    pub fn flush(&mut self) {
        self.encoder.flush(&mut self.device);
        self.window.swap_buffers().unwrap();
        self.device.cleanup();
    }

    /// Handle a resize event, resizing the buffers appropriately.
    pub fn resize(&mut self) {
        gfx_window_glutin::update_views(&self.window, &mut self.rtv, &mut self.stv);
    }

    /// Load a texture, which can then be passed to the shader.
    ///
    /// The corresponding link type is `TextureSampler`.
    pub fn texture(&mut self, image: RgbaImage) -> Texture {
        let (width, height) = image.dimensions();

        let (_, view) = self.factory
            .create_texture_immutable_u8::<Rgba8>(
                Kind::D2(width as u16, height as u16, AaMode::Single),
                Mipmap::Provided,
                &[&image],
            )
            .unwrap();

        (view, self.factory.create_sampler_linear())
    }

    /// Get the size of this window, in pixels.
    ///
    /// This is the resolution you should pass to your shaders. The function
    /// returns `None` if the window has already been closed.
    pub fn size(&self) -> Option<(u32, u32)> {
        self.window().get_inner_size()
    }

    /// Get the raw window handle for this window.
    ///
    /// This might be useful for locking the mouse or resizing the window.
    pub fn window(&self) -> &glutin::Window { self.window.window() }

    /// Get the encoder for this window.
    ///
    /// You probably don't need this.
    pub fn encoder(&mut self) -> &mut Encoder<R, CommandBuffer> { &mut self.encoder }

    /// Get the factory for this window.
    ///
    /// You probably don't need this.
    pub fn factory(&mut self) -> &mut GlFactory { &mut self.factory }
}