-
Notifications
You must be signed in to change notification settings - Fork 32
/
g2d.rs
393 lines (335 loc) · 10 KB
/
g2d.rs
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
381
382
383
384
385
386
387
388
389
390
391
392
393
use gfx;
use gfx::DeviceHelper;
use graphics::{ Context, BackEnd };
use graphics::BACK_END_MAX_VERTEX_COUNT as BUFFER_SIZE;
use Texture;
static VERTEX_SHADER: gfx::ShaderSource<'static> = shaders!{
glsl_120: b"
#version 120
uniform vec4 color;
attribute vec2 pos;
void main() {
gl_Position = vec4(pos, 0.0, 1.0);
}
",
glsl_150: b"
#version 150 core
uniform vec4 color;
in vec2 pos;
void main() {
gl_Position = vec4(pos, 0.0, 1.0);
}
"
};
static FRAGMENT_SHADER: gfx::ShaderSource<'static> = shaders!{
glsl_120: b"
#version 120
uniform vec4 color;
void main() {
gl_FragColor = color;
}
",
glsl_150: b"
#version 150 core
uniform vec4 color;
out vec4 o_Color;
void main() {
o_Color = color;
}
"
};
static VERTEX_SHADER_UV: gfx::ShaderSource<'static> = shaders!{
glsl_120: b"
#version 120
uniform sampler2D s_texture;
uniform vec4 color;
attribute vec2 pos;
attribute vec2 uv;
varying vec2 v_UV;
void main() {
v_UV = uv;
gl_Position = vec4(pos, 0.0, 1.0);
}
",
glsl_150: b"
#version 150 core
uniform sampler2D s_texture;
uniform vec4 color;
in vec2 pos;
in vec2 uv;
out vec2 v_UV;
void main() {
v_UV = uv;
gl_Position = vec4(pos, 0.0, 1.0);
}
"
};
static FRAGMENT_SHADER_UV: gfx::ShaderSource<'static> = shaders!{
glsl_120: b"
#version 120
uniform sampler2D s_texture;
uniform vec4 color;
varying vec2 v_UV;
void main()
{
gl_FragColor = texture2D(s_texture, v_UV) * color;
}
",
glsl_150: b"
#version 150 core
uniform sampler2D s_texture;
uniform vec4 color;
out vec4 o_Color;
in vec2 v_UV;
void main()
{
o_Color = texture(s_texture, v_UV) * color;
}
"
};
static POS_COMPONENTS: usize = 2;
static UV_COMPONENTS: usize = 2;
// Boiler plate for automatic attribute construction.
// Needs to be improved on gfx-rs side.
// For some reason, using ``*_COMPONENT` triggers some macros errors.
#[vertex_format]
struct PositionFormat { pos: [f32; 2] }
#[vertex_format]
struct ColorFormat { color: [f32; 4] }
#[vertex_format]
struct TexCoordsFormat { uv: [f32; 2] }
#[shader_param]
struct Params {
color: [f32; 4],
}
#[shader_param]
struct ParamsUV {
color: [f32; 4],
s_texture: gfx::shade::TextureParam,
}
/// The graphics back-end.
pub struct G2D {
buffer_pos: gfx::BufferHandle<f32>,
buffer_uv: gfx::BufferHandle<f32>,
batch: gfx::batch::OwnedBatch<Params>,
batch_uv: gfx::batch::OwnedBatch<ParamsUV>,
}
impl G2D {
/// Creates a new G2D object.
pub fn new<D: gfx::Device>(device: &mut D) -> G2D {
let program = device.link_program(
VERTEX_SHADER.clone(),
FRAGMENT_SHADER.clone()
).ok().expect("Could not link `VERTEX_SHADER` and `FRAGMENT_SHADER`");
let program_uv = device.link_program(
VERTEX_SHADER_UV.clone(),
FRAGMENT_SHADER_UV.clone()
).ok().expect("Could not link `VERTEX_SHADER_UV` and `FRAGMENT_SHADER_UV`");
let buffer_pos = device.create_buffer(
POS_COMPONENTS * BUFFER_SIZE,
gfx::BufferUsage::Dynamic);
let buffer_uv = device.create_buffer(
UV_COMPONENTS * BUFFER_SIZE,
gfx::BufferUsage::Dynamic);
let mut mesh = gfx::Mesh::new(BUFFER_SIZE as u32);
mesh.attributes.extend(gfx::VertexFormat::generate(
None::<PositionFormat>,
buffer_pos.raw()
).into_iter());
// Reuse parameters from `mesh`.
let mut mesh_uv = mesh.clone();
mesh_uv.attributes.extend(gfx::VertexFormat::generate(
None::<TexCoordsFormat>,
buffer_uv.raw()
).into_iter());
let params = Params {
color: [1.0; 4],
};
let mut batch = gfx::batch::OwnedBatch::new(mesh, program, params)
.ok().expect("Could not create `OwnedBatch` for `batch`");
let sampler = device.create_sampler(
gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Trilinear,
gfx::tex::WrapMode::Clamp)
);
// Create a dummy texture
let texture_info = gfx::tex::TextureInfo {
width: 1,
height: 1,
depth: 1,
levels: 1,
kind: gfx::tex::TextureKind::Texture2D,
format: gfx::tex::RGBA8,
};
let image_info = texture_info.to_image_info();
let texture = device.create_texture(texture_info)
.ok().expect("Could not create texture");
device.update_texture(&texture, &image_info,
&[0x20u8, 0xA0u8, 0xC0u8, 0x00u8])
.ok().expect("Could not update texture");
let params_uv = ParamsUV {
color: [1.0; 4],
s_texture: (texture, Some(sampler))
};
let mut batch_uv = gfx::batch::OwnedBatch::new(
mesh_uv, program_uv, params_uv)
.ok().expect("Could not created `OwnedBatch` for `batch_uv`");
// Disable culling.
batch.state.primitive.method =
gfx::state::RasterMethod::Fill(gfx::state::CullMode::Nothing);
batch_uv.state.primitive.method =
gfx::state::RasterMethod::Fill(gfx::state::CullMode::Nothing);
G2D {
buffer_pos: buffer_pos,
buffer_uv: buffer_uv,
batch: batch,
batch_uv: batch_uv,
}
}
/// Renders graphics to a Gfx renderer.
pub fn draw<C, F>(
&mut self,
renderer: &mut gfx::Renderer<C>,
frame: &gfx::Frame,
mut f: F
)
where
C: gfx::CommandBuffer,
F: FnMut(Context, &mut GraphicsBackEnd<C>)
{
let ref mut g = GraphicsBackEnd::new(
renderer,
frame,
self
);
let c = Context::abs(
frame.width as f64,
frame.height as f64
);
g.enable_alpha_blend();
f(c, g);
g.disable_alpha_blend();
}
}
/// Used for rendering 2D graphics.
pub struct GraphicsBackEnd<'a, C: 'a + gfx::CommandBuffer> {
renderer: &'a mut gfx::Renderer<C>,
frame: &'a gfx::Frame,
g2d: &'a mut G2D,
}
impl<'a, C: gfx::CommandBuffer> GraphicsBackEnd<'a, C> {
/// Creates a new object for rendering 2D graphics.
pub fn new(renderer: &'a mut gfx::Renderer<C>,
frame: &'a gfx::Frame,
g2d: &'a mut G2D) -> GraphicsBackEnd<'a, C> {
GraphicsBackEnd {
renderer: renderer,
frame: frame,
g2d: g2d,
}
}
/// Returns true if texture has alpha channel.
pub fn has_texture_alpha(&self, texture: &Texture) -> bool {
use gfx::tex::Components::RGBA;
texture.handle.get_info().format.get_components() == Some(RGBA)
}
/// Enabled alpha blending.
pub fn enable_alpha_blend(&mut self) {
use std::default::Default;
use gfx::state::InverseFlag::{Normal, Inverse};
use gfx::state::Factor;
use gfx::state::BlendValue::SourceAlpha;
let blend = gfx::state::Blend {
value: [1.0, 1.0, 1.0, 1.0],
color: gfx::state::BlendChannel {
equation: gfx::state::Equation::Add,
source: Factor(Normal, SourceAlpha),
destination: Factor(Inverse, SourceAlpha)
},
alpha: Default::default()
};
self.g2d.batch.state.blend = Some(blend);
self.g2d.batch_uv.state.blend = Some(blend);
}
/// Disables alpha blending.
pub fn disable_alpha_blend(&mut self) {
self.g2d.batch.state.blend = None;
self.g2d.batch_uv.state.blend = None;
}
}
impl<'a, C: gfx::CommandBuffer> BackEnd
for GraphicsBackEnd<'a, C> {
type Texture = Texture;
fn clear(&mut self, color: [f32; 4]) {
let &mut GraphicsBackEnd {
ref mut renderer,
frame,
..
} = self;
renderer.clear(
gfx::ClearData {
color: color,
depth: 0.0,
stencil: 0,
},
gfx::COLOR,
frame
);
}
fn tri_list<F>(&mut self, color: &[f32; 4], mut f: F)
where F: FnMut(&mut FnMut(&[f32]))
{
let &mut GraphicsBackEnd {
ref mut renderer,
ref frame,
g2d: &mut G2D {
ref mut buffer_pos,
ref mut batch,
..
},
} = self;
batch.param.color = *color;
f(&mut |vertices: &[f32]| {
renderer.update_buffer_vec(*buffer_pos, vertices, 0);
let n = vertices.len() / POS_COMPONENTS;
batch.slice = gfx::Slice {
prim_type: gfx::PrimitiveType::TriangleList,
start: 0,
end: n as u32,
kind: gfx::SliceKind::Vertex
};
let _ = renderer.draw(batch, *frame);
})
}
fn tri_list_uv<F>(&mut self, color: &[f32; 4], texture: &Texture, mut f: F)
where F: FnMut(&mut FnMut(&[f32], &[f32]))
{
let &mut GraphicsBackEnd {
ref mut renderer,
ref frame,
g2d: &mut G2D {
ref mut buffer_pos,
ref mut buffer_uv,
ref mut batch_uv,
..
},
} = self;
batch_uv.param.s_texture.0 = texture.handle;
batch_uv.param.color = *color;
f(&mut |vertices: &[f32], texture_coords: &[f32]| {
assert_eq!(
vertices.len() * UV_COMPONENTS,
texture_coords.len() * POS_COMPONENTS
);
renderer.update_buffer_vec(*buffer_pos, vertices, 0);
renderer.update_buffer_vec(*buffer_uv, texture_coords, 0);
let n = vertices.len() / POS_COMPONENTS;
batch_uv.slice = gfx::Slice {
prim_type: gfx::PrimitiveType::TriangleList,
start: 0,
end: n as u32,
kind: gfx::SliceKind::Vertex
};
let _ = renderer.draw(batch_uv, *frame);
})
}
}