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
#![allow(missing_docs)]
use std::mem;
use fnv::FnvHashMap as HashMap;
use gfx::buffer::{Info as BufferInfo, Role as BufferRole};
use gfx::memory::{Bind, Usage};
use gfx::preset::depth::{LESS_EQUAL_TEST, LESS_EQUAL_WRITE};
use gfx::pso::buffer::{ElemStride, InstanceRate};
use gfx::shade::core::UniformValue;
use gfx::shade::{ProgramError, ToUniform};
use gfx::state::{Blend, ColorMask, Comparison, Depth, MultiSample, Rasterizer, Stencil};
use gfx::traits::Pod;
use gfx::{Primitive, ShaderSet};
use glsl_layout::Std140;
pub use self::pso::{Data, Init, Meta};
use error::{Error, Result};
use pipe::Target;
use types::{Encoder, Factory, PipelineState, Resources, Slice};
use vertex::Attributes;
mod pso;
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum DepthMode {
LessEqualTest,
LessEqualWrite,
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub(crate) enum ProgramSource<'a> {
Simple(&'a [u8], &'a [u8]),
Geometry(&'a [u8], &'a [u8], &'a [u8]),
Tessellated(&'a [u8], &'a [u8], &'a [u8], &'a [u8]),
}
impl<'a> ProgramSource<'a> {
pub fn compile(&self, fac: &mut Factory) -> Result<ShaderSet<Resources>> {
use gfx::Factory;
use gfx::traits::FactoryExt;
match *self {
ProgramSource::Simple(ref vs, ref ps) => fac.create_shader_set(vs, ps)
.map_err(|e| Error::ProgramCreation(e)),
ProgramSource::Geometry(ref vs, ref gs, ref ps) => {
let v = fac.create_shader_vertex(vs)
.map_err(|e| ProgramError::Vertex(e))?;
let g = fac.create_shader_geometry(gs)
.expect("Geometry shader creation failed");
let p = fac.create_shader_pixel(ps)
.map_err(|e| ProgramError::Pixel(e))?;
Ok(ShaderSet::Geometry(v, g, p))
}
ProgramSource::Tessellated(ref vs, ref hs, ref ds, ref ps) => {
fac.create_shader_set_tessellation(vs, hs, ds, ps)
.map_err(|e| Error::ProgramCreation(e))
}
}
}
}
#[derive(Derivative)]
#[derivative(Clone, Debug, Eq, PartialEq)]
pub struct Effect {
pub pso: PipelineState<Meta>,
pub data: Data,
const_bufs: HashMap<String, usize>,
globals: HashMap<String, usize>,
}
impl Effect {
pub fn update_global<N: AsRef<str>, T: ToUniform>(&mut self, name: N, data: T) {
match self.globals.get(name.as_ref()) {
Some(i) => self.data.globals[*i] = data.convert(),
None => {
eprintln!(
"WARNING: Global update for effect failed! Global not found: {:?}",
name.as_ref()
);
}
}
}
pub fn update_buffer<N, T>(&mut self, name: N, data: &[T], enc: &mut Encoder)
where
N: AsRef<str>,
T: Pod,
{
match self.const_bufs.get(name.as_ref()) {
Some(i) => {
let raw = &self.data.const_bufs[*i];
enc.update_buffer::<T>(unsafe { mem::transmute(raw) }, &data[..], 0)
.expect("Failed to update buffer (TODO: replace expect)");
}
None => {
eprintln!(
"WARNING: Buffer update for effect failed! Buffer not found: {:?}",
name.as_ref()
);
}
}
}
pub fn update_constant_buffer<N, T>(&mut self, name: N, data: &T, enc: &mut Encoder)
where
N: AsRef<str>,
T: Std140,
{
match self.const_bufs.get(name.as_ref()) {
Some(i) => {
let raw = &self.data.const_bufs[*i];
enc.update_constant_buffer::<T>(unsafe { mem::transmute(raw) }, &data)
}
None => {
eprintln!(
"WARNING: Buffer update for effect failed! Buffer not found: {:?}",
name.as_ref()
);
}
}
}
pub fn clear(&mut self) {
self.data.textures.clear();
self.data.samplers.clear();
self.data.vertex_bufs.clear();
}
pub fn draw(&mut self, slice: &Slice, enc: &mut Encoder) {
enc.draw(&slice, &self.pso, &self.data);
}
}
pub struct NewEffect<'f> {
pub factory: &'f mut Factory,
out: &'f Target,
multisampling: u16,
}
impl<'f> NewEffect<'f> {
pub(crate) fn new(fac: &'f mut Factory, out: &'f Target, multisampling: u16) -> Self {
NewEffect {
factory: fac,
out,
multisampling,
}
}
pub fn simple<S: Into<&'f [u8]>>(self, vs: S, ps: S) -> EffectBuilder<'f> {
let src = ProgramSource::Simple(vs.into(), ps.into());
EffectBuilder::new(self.factory, self.out, self.multisampling, src)
}
pub fn geom<S: Into<&'f [u8]>>(self, vs: S, gs: S, ps: S) -> EffectBuilder<'f> {
let src = ProgramSource::Geometry(vs.into(), gs.into(), ps.into());
EffectBuilder::new(self.factory, self.out, self.multisampling, src)
}
pub fn tess<S: Into<&'f [u8]>>(self, vs: S, hs: S, ds: S, ps: S) -> EffectBuilder<'f> {
let src = ProgramSource::Tessellated(vs.into(), hs.into(), ds.into(), ps.into());
EffectBuilder::new(self.factory, self.out, self.multisampling, src)
}
}
pub struct EffectBuilder<'a> {
factory: &'a mut Factory,
out: &'a Target,
init: Init<'a>,
prim: Primitive,
prog: ProgramSource<'a>,
rast: Rasterizer,
const_bufs: Vec<BufferInfo>,
}
impl<'a> EffectBuilder<'a> {
pub(crate) fn new(
fac: &'a mut Factory,
out: &'a Target,
multisampling: u16,
src: ProgramSource<'a>,
) -> Self {
let mut rast = Rasterizer::new_fill().with_cull_back();
if multisampling > 0 {
rast.samples = Some(MultiSample);
}
EffectBuilder {
factory: fac,
out: out,
init: Init::default(),
prim: Primitive::TriangleList,
rast,
prog: src,
const_bufs: Vec::new(),
}
}
pub fn with_raw_global(&mut self, name: &'a str) -> &mut Self {
self.init.globals.push(name);
self
}
pub fn with_raw_constant_buffer(
&mut self,
name: &'a str,
size: usize,
num: usize,
) -> &mut Self {
self.const_bufs.push(BufferInfo {
role: BufferRole::Constant,
bind: Bind::empty(),
usage: Usage::Dynamic,
size: num * size,
stride: size,
});
self.init.const_bufs.push(name);
self
}
pub fn with_primitive_type(&mut self, prim: Primitive) -> &mut Self {
self.prim = prim;
self
}
pub fn with_output(&mut self, name: &'a str, depth: Option<DepthMode>) -> &mut Self {
if let Some(depth) = depth {
self.init.out_depth = Some((
match depth {
DepthMode::LessEqualTest => LESS_EQUAL_TEST,
DepthMode::LessEqualWrite => LESS_EQUAL_WRITE,
},
Stencil::default(),
));
}
if cfg!(target_os = "macos") && depth.is_none() {
self.init.out_depth = Some((
Depth {
fun: Comparison::Always,
write: true,
},
Stencil::default(),
));
}
self.init.out_colors.push(name);
self
}
pub fn with_blended_output(
&mut self,
name: &'a str,
mask: ColorMask,
blend: Blend,
depth: Option<DepthMode>,
) -> &mut Self {
if let Some(depth) = depth {
self.init.out_depth = Some((
match depth {
DepthMode::LessEqualTest => LESS_EQUAL_TEST,
DepthMode::LessEqualWrite => LESS_EQUAL_WRITE,
},
Stencil::default(),
));
}
if cfg!(target_os = "macos") && depth.is_none() {
self.init.out_depth = Some((
Depth {
fun: Comparison::Always,
write: true,
},
Stencil::default(),
));
}
self.init.out_blends.push((name, mask, blend));
self
}
pub fn with_texture(&mut self, name: &'a str) -> &mut Self {
self.init.samplers.push(name);
self.init.textures.push(name);
self
}
pub fn with_raw_vertex_buffer(
&mut self,
attrs: Attributes<'a>,
stride: ElemStride,
rate: InstanceRate,
) -> &mut Self {
self.init.vertex_bufs.push((attrs, stride, rate));
self
}
pub fn build(&mut self) -> Result<Effect> {
use gfx::Factory;
use gfx::traits::FactoryExt;
debug!("Building effect");
debug!("Compiling shaders");
let ref mut fac = self.factory;
let prog = self.prog.compile(fac)?;
debug!("Creating pipeline state");
let pso = fac.create_pipeline_state(&prog, self.prim, self.rast, self.init.clone())?;
let mut data = Data::default();
debug!("Creating raw constant buffers");
let const_bufs = self.init
.const_bufs
.iter()
.enumerate()
.zip(self.const_bufs.drain(..))
.map(|((i, name), info)| {
let cbuf = fac.create_buffer_raw(info)?;
data.const_bufs.push(cbuf);
Ok((name.to_string(), i))
})
.collect::<Result<HashMap<_, _>>>()?;
debug!("Set global uniforms");
let globals = self.init
.globals
.iter()
.enumerate()
.map(|(i, name)| {
data.globals.push(UniformValue::F32Vector4([0.0; 4]));
(name.to_string(), i)
})
.collect::<HashMap<_, _>>();
debug!("Process Color/Depth/Blend outputs");
data.out_colors.extend(
self.out
.color_bufs()
.iter()
.map(|cb| &cb.as_output)
.cloned(),
);
data.out_blends.extend(
self.out
.color_bufs()
.iter()
.map(|cb| &cb.as_output)
.cloned(),
);
data.out_depth = self.out
.depth_buf()
.map(|db| (db.as_output.clone(), (0, 0)));
debug!("Finished building effect");
Ok(Effect {
pso,
data,
const_bufs,
globals,
})
}
}