custom_material/
custom_material.rs1use macroquad::prelude::*;
2
3use macroquad::window::miniquad::*;
4
5const VERTEX: &str = r#"#version 100
6attribute vec3 position;
7attribute vec2 texcoord;
8
9varying lowp vec2 uv;
10
11uniform mat4 Model;
12uniform mat4 Projection;
13
14void main() {
15 gl_Position = Projection * Model * vec4(position, 1);
16 uv = texcoord;
17}"#;
18
19const FRAGMENT: &str = r#"#version 100
20varying lowp vec2 uv;
21
22uniform sampler2D Texture;
23uniform lowp vec4 test_color;
24
25void main() {
26 gl_FragColor = test_color * texture2D(Texture, uv);
27}"#;
28
29const FRAGMENT_WITH_ARRAY: &str = r#"#version 100
30varying lowp vec2 uv;
31
32uniform sampler2D Texture;
33uniform lowp vec4 test_color[10];
34
35void main() {
36 gl_FragColor = test_color[5] * texture2D(Texture, uv);
37}"#;
38
39#[macroquad::main("Shaders")]
40async fn main() {
41 let pipeline_params = PipelineParams {
42 color_blend: Some(BlendState::new(
43 Equation::Add,
44 BlendFactor::Value(BlendValue::SourceAlpha),
45 BlendFactor::OneMinusValue(BlendValue::SourceAlpha),
46 )),
47 ..Default::default()
48 };
49
50 let mat = load_material(
51 ShaderSource::Glsl {
52 vertex: VERTEX,
53 fragment: FRAGMENT,
54 },
55 MaterialParams {
56 uniforms: vec![UniformDesc::new("test_color", UniformType::Float4)],
57 pipeline_params,
58 ..Default::default()
59 },
60 )
61 .unwrap();
62
63 let mat_with_array = load_material(
64 ShaderSource::Glsl {
65 vertex: VERTEX,
66 fragment: FRAGMENT_WITH_ARRAY,
67 },
68 MaterialParams {
69 uniforms: vec![UniformDesc::array(
70 UniformDesc::new("test_color", UniformType::Float4),
71 10,
72 )],
73 pipeline_params,
74 ..Default::default()
75 },
76 )
77 .unwrap();
78
79 loop {
80 clear_background(GRAY);
81
82 gl_use_material(&mat);
83
84 mat.set_uniform("test_color", vec4(1., 0., 0., 1.));
85
86 draw_rectangle(50.0, 50.0, 100., 100., WHITE);
87
88 mat.set_uniform("test_color", vec4(0., 1., 0., 1.));
89 draw_rectangle(160.0, 50.0, 100., 100., WHITE);
90
91 mat.set_uniform("test_color", vec4(0., 0., 1., 1.));
92 draw_rectangle(270.0, 50.0, 100., 100., WHITE);
93
94 gl_use_material(&mat_with_array);
95 let mut colors: [Vec4; 10] = [vec4(0.0, 1.0, 0.0, 0.0); 10];
96 colors[5] = vec4(0.0, 1.0, 1.0, 1.0);
97 mat_with_array.set_uniform_array("test_color", &colors[..]);
98 draw_rectangle(50.0, 160.0, 100., 100., WHITE);
99
100 gl_use_default_material();
101
102 draw_rectangle(380.0, 50.0, 100., 100., YELLOW);
103
104 next_frame().await
105 }
106}