Skip to main content

nadir_render/
shader.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The renderer's shaders and their interfaces.
16//!
17//! Each program's GLSL lives in `shaders/<name>/` and is included here.
18//! Its interface constant names every vertex attribute, uniform block and
19//! sampler; the pipelines are built from it, and [`Interface::check`]
20//! checks GLSL against it: the included sources in the tests, and sources
21//! given to [`Renderer::reload_program`](crate::Renderer::reload_program)
22//! before they are built. The Metal sources come with roadmap M10.3.
23
24use std::iter::Peekable;
25use std::str::Chars;
26
27use nadir_gfx::{BlendMode, ShaderSource, UniformBlockDesc, VertexAttribute, VertexFormat};
28
29/// The folder of the renderer's GLSL sources: this crate's `shaders/`,
30/// where it was compiled. Each [`Program`]'s files are under it, at
31/// [`Program::vertex_file`] and [`Program::fragment_file`].
32///
33/// The renderer includes the sources when it is compiled, and reads no
34/// file. The folder is for a game that watches the files and gives them to
35/// [`Renderer::reload_program`](crate::Renderer::reload_program) when they
36/// change, as the engine's facade does in development builds, under its
37/// `dev` feature (roadmap M5.8). It is the path on the machine that compiled the crate: for a
38/// crate taken from crates.io, a folder in cargo's registry, which cargo
39/// does not rebuild when its files change, so that the files edited there
40/// and the sources compiled in drift apart. Edit the shaders of a path dependency, or of a
41/// `[patch]`, instead.
42pub const SHADER_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/shaders");
43
44/// One of the renderer's programs, for
45/// [`Renderer::reload_program`](crate::Renderer::reload_program).
46#[non_exhaustive]
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum Program {
49    /// Instanced sprites, textured and tinted.
50    Sprite,
51    /// Instanced tiles, a chunk of a tile layer at a time.
52    TileChunk,
53    /// The integer upscale of the virtual image into the output.
54    Blit,
55    /// Instanced glyphs of texts: the sprite's quads, with the texture's
56    /// alpha as a mask in the tint's color.
57    Text,
58}
59
60impl Program {
61    /// Every program.
62    pub const ALL: &'static [Self] = &[Self::Sprite, Self::TileChunk, Self::Blit, Self::Text];
63
64    /// Its name: its folder under [`SHADER_DIR`], and its pipeline's label.
65    pub fn name(self) -> &'static str {
66        self.interface().name
67    }
68
69    /// Its vertex shader's file, under [`SHADER_DIR`], such as
70    /// `sprite/sprite.vert.glsl`.
71    pub fn vertex_file(self) -> &'static str {
72        match self {
73            Self::Sprite => "sprite/sprite.vert.glsl",
74            Self::TileChunk => "tile_chunk/tile_chunk.vert.glsl",
75            Self::Blit => "blit/blit.vert.glsl",
76            Self::Text => "text/text.vert.glsl",
77        }
78    }
79
80    /// Its fragment shader's file, under [`SHADER_DIR`], such as
81    /// `sprite/sprite.frag.glsl`.
82    pub fn fragment_file(self) -> &'static str {
83        match self {
84            Self::Sprite => "sprite/sprite.frag.glsl",
85            Self::TileChunk => "tile_chunk/tile_chunk.frag.glsl",
86            Self::Blit => "blit/blit.frag.glsl",
87            Self::Text => "text/text.frag.glsl",
88        }
89    }
90
91    pub(crate) fn interface(self) -> &'static Interface {
92        match self {
93            Self::Sprite => &SPRITE,
94            Self::TileChunk => &TILE_CHUNK,
95            Self::Blit => &BLIT,
96            Self::Text => &TEXT,
97        }
98    }
99}
100
101/// A vertex attribute of a shader: its name, location and format.
102#[derive(Clone, Copy, Debug)]
103pub(crate) struct Attribute {
104    pub(crate) name: &'static str,
105    pub(crate) location: u32,
106    pub(crate) format: VertexFormat,
107}
108
109/// What a program reads.
110#[derive(Clone, Copy, Debug)]
111pub(crate) struct Interface {
112    /// The program's name: its directory under `shaders/`.
113    pub(crate) name: &'static str,
114    pub(crate) vertex: &'static str,
115    pub(crate) fragment: &'static str,
116    /// The per-instance attributes, in the order they are packed: vertex
117    /// buffer slot 0. A program with none has only the per-vertex ones.
118    pub(crate) instance: &'static [Attribute],
119    /// The per-vertex attributes: the unit quad, in the slot after the
120    /// instances'.
121    pub(crate) vertex_attributes: &'static [Attribute],
122    pub(crate) uniform_blocks: &'static [UniformBlockDesc<'static>],
123    pub(crate) textures: &'static [&'static str],
124    pub(crate) blend: BlendMode,
125}
126
127impl Interface {
128    /// The sources it was compiled with.
129    pub(crate) fn source(&self) -> ShaderSource<'static> {
130        ShaderSource {
131            glsl_vs: self.vertex,
132            glsl_fs: self.fragment,
133            msl: "",
134        }
135    }
136
137    /// Checks that GLSL sources declare nothing that differs from this
138    /// interface:
139    ///
140    /// - each `in` variable of the vertex shader is one of its attributes,
141    ///   with its location, and no other layout qualifier, its type and its
142    ///   name;
143    /// - each uniform block of either shader is one of its blocks;
144    /// - each other uniform of either shader is one of its samplers, a
145    ///   `sampler2D`, unless it has a value of its own (`= …`);
146    /// - the fragment shader has one output, an `out vec4` at location 0
147    ///   and index 0, and writes no `gl_FragColor` or `gl_FragData`.
148    ///
149    /// An attribute, a block or a sampler that the sources leave out is
150    /// taken: the device enables an attribute the program does not read,
151    /// and warns of a block or a sampler it does not use. The device checks
152    /// the rest when it builds the program: that the sources compile and
153    /// link, and the blocks' sizes. A block's members are checked by its
154    /// size alone.
155    ///
156    /// The declarations are read at the top level, as written once the
157    /// preprocessor has joined the lines a `\` ends, made each comment a
158    /// space and each newline one, and the directives are left out, but
159    /// before it would expand a macro or choose a branch of an `#if`: a
160    /// declaration a macro makes is not seen, and every branch is read.
161    /// Sources whose branches do not each hold whole declarations, with the
162    /// braces as deep at the end of each, are refused, as are braces that
163    /// do not pair up.
164    ///
165    /// # Errors
166    ///
167    /// What differs, each difference once, joined by `; `.
168    pub(crate) fn check(&self, vertex: &str, fragment: &str) -> Result<(), String> {
169        let vertex = declarations(vertex);
170        let fragment = declarations(fragment);
171        let mut problems = Vec::new();
172        for (stage, found) in [("vertex", &vertex), ("fragment", &fragment)] {
173            if !found.readable {
174                problems.push(format!(
175                    "the {stage} shader's braces, or the branches of its `#if`s, do not hold \
176                     whole declarations as written, so its declarations cannot be read"
177                ));
178            }
179        }
180
181        let attributes = || self.instance.iter().chain(self.vertex_attributes);
182        let mut inputs = vertex.inputs;
183        inputs.sort_unstable();
184        // The same declaration twice comes from two branches of an `#if`.
185        inputs.dedup();
186        for input in &inputs {
187            let location = input.qualifier("location").flatten();
188            let fits = attributes().any(|attribute| {
189                input.layout.len() == 1
190                    && location == Some(attribute.location)
191                    && glsl_type(attribute.format) == input.kind
192                    && attribute.name == input.name
193            });
194            if fits {
195                continue;
196            }
197            let declared = input.declaration("in");
198            let mut problem = if input.layout.is_empty() {
199                format!("`{declared}` has no location, and is not one of the program's attributes")
200            } else {
201                format!("`{declared}` is not one of the program's attributes")
202            };
203            let near = attributes()
204                .find(|attribute| attribute.name == input.name)
205                .or_else(|| attributes().find(|attribute| Some(attribute.location) == location));
206            if let Some(attribute) = near {
207                problem.push_str(&format!(
208                    " (it has `layout(location = {}) in {} {};`)",
209                    attribute.location,
210                    glsl_type(attribute.format),
211                    attribute.name
212                ));
213            }
214            problems.push(problem);
215        }
216
217        let mut blocks = vertex.blocks;
218        blocks.extend(fragment.blocks);
219        blocks.sort_unstable();
220        blocks.dedup();
221        for name in blocks {
222            if !self.uniform_blocks.iter().any(|block| block.name == name) {
223                let names: Vec<String> = self
224                    .uniform_blocks
225                    .iter()
226                    .map(|block| format!("`{}`", block.name))
227                    .collect();
228                problems.push(if names.is_empty() {
229                    format!("uniform block `{name}` is not one of the program's, which has none")
230                } else {
231                    format!(
232                        "uniform block `{name}` is not one of the program's (it has {})",
233                        names.join(", ")
234                    )
235                });
236            }
237        }
238
239        let mut uniforms = vertex.uniforms;
240        uniforms.extend(fragment.uniforms);
241        uniforms.sort_unstable();
242        uniforms.dedup();
243        for (kind, name) in uniforms {
244            if kind == "sampler2D" && self.textures.contains(&name.as_str()) {
245                continue;
246            }
247            let mut problem = format!(
248                "`uniform {kind} {name};` is not one of the program's: the renderer sets only \
249                 its uniform blocks and its samplers"
250            );
251            if self.textures.contains(&name.as_str()) {
252                problem.push_str(&format!(" (`{name}` is a `sampler2D`)"));
253            }
254            problems.push(problem);
255        }
256
257        let mut outputs = fragment.outputs;
258        outputs.sort_unstable();
259        outputs.dedup();
260        let is_color = |output: &Variable| {
261            output.kind == "vec4"
262                && !output.name.contains('[')
263                && output.layout.iter().all(|(key, value)| {
264                    (key.eq_ignore_ascii_case("location") || key.eq_ignore_ascii_case("index"))
265                        && value.as_deref().and_then(integer) == Some(0)
266                })
267        };
268        match outputs.as_slice() {
269            [output] if is_color(output) => {}
270            [] => problems.push(
271                "the fragment shader has no output: it must have one `out vec4`, at location 0"
272                    .to_string(),
273            ),
274            many => {
275                let declared: Vec<String> = many
276                    .iter()
277                    .map(|output| format!("`{}`", output.declaration("out")))
278                    .collect();
279                problems.push(format!(
280                    "the fragment shader has {}, and must have one `out vec4`, at location 0: \
281                     the renderer draws into one color",
282                    declared.join(", ")
283                ));
284            }
285        }
286        for name in fragment.built_in_outputs {
287            problems.push(format!(
288                "the fragment shader writes `{name}`: the renderer draws only its `out vec4`"
289            ));
290        }
291
292        if problems.is_empty() {
293            Ok(())
294        } else {
295            Err(problems.join("; "))
296        }
297    }
298}
299
300const fn attribute(name: &'static str, location: u32, format: VertexFormat) -> Attribute {
301    Attribute {
302        name,
303        location,
304        format,
305    }
306}
307
308/// Instanced sprites: one quad each, textured and tinted.
309pub(crate) const SPRITE: Interface = Interface {
310    name: "sprite",
311    vertex: include_str!("../shaders/sprite/sprite.vert.glsl"),
312    fragment: include_str!("../shaders/sprite/sprite.frag.glsl"),
313    instance: &[
314        attribute("position", 0, VertexFormat::Float32x2),
315        attribute("size", 1, VertexFormat::Float32x2),
316        attribute("pivot", 2, VertexFormat::Float32x2),
317        attribute("uv_rect", 3, VertexFormat::Float32x4),
318        attribute("color", 4, VertexFormat::Float32x4),
319        attribute("rotation", 5, VertexFormat::Float32),
320    ],
321    vertex_attributes: &[attribute("corner", 6, VertexFormat::Float32x2)],
322    uniform_blocks: &[UniformBlockDesc {
323        name: "Camera",
324        binding: 0,
325        size: 16,
326    }],
327    textures: &["sprite_texture"],
328    blend: BlendMode::Alpha,
329};
330
331/// Instanced tiles: one quad each, from a chunk's instance buffer, with
332/// the tile picked from the layer's tile set and the frame's time.
333pub(crate) const TILE_CHUNK: Interface = Interface {
334    name: "tile_chunk",
335    vertex: include_str!("../shaders/tile_chunk/tile_chunk.vert.glsl"),
336    fragment: include_str!("../shaders/tile_chunk/tile_chunk.frag.glsl"),
337    instance: &[
338        attribute("cell", 0, VertexFormat::Float32x2),
339        attribute("tile", 1, VertexFormat::Float32x4),
340    ],
341    vertex_attributes: &[attribute("corner", 2, VertexFormat::Float32x2)],
342    uniform_blocks: &[
343        UniformBlockDesc {
344            name: "Camera",
345            binding: 0,
346            size: 16,
347        },
348        UniformBlockDesc {
349            name: "TileLayer",
350            binding: 1,
351            size: 48,
352        },
353    ],
354    textures: &["tile_texture"],
355    blend: BlendMode::Alpha,
356};
357
358/// The integer upscale: the virtual image over the viewport.
359pub(crate) const BLIT: Interface = Interface {
360    name: "blit",
361    vertex: include_str!("../shaders/blit/blit.vert.glsl"),
362    fragment: include_str!("../shaders/blit/blit.frag.glsl"),
363    instance: &[],
364    vertex_attributes: &[
365        attribute("position", 0, VertexFormat::Float32x2),
366        attribute("uv", 1, VertexFormat::Float32x2),
367    ],
368    uniform_blocks: &[],
369    textures: &["source"],
370    blend: BlendMode::Opaque,
371};
372
373/// Instanced glyphs: the sprite's instances and quad, with the texture's
374/// alpha as a mask in the tint's color (`docs/subsystems/render.md`,
375/// "Text").
376pub(crate) const TEXT: Interface = Interface {
377    name: "text",
378    vertex: include_str!("../shaders/text/text.vert.glsl"),
379    fragment: include_str!("../shaders/text/text.frag.glsl"),
380    instance: SPRITE.instance,
381    vertex_attributes: SPRITE.vertex_attributes,
382    uniform_blocks: SPRITE.uniform_blocks,
383    textures: &["text_texture"],
384    blend: BlendMode::Alpha,
385};
386
387/// The vertex attributes of `attributes`, packed one after another, and
388/// the bytes from one record to the next. Past `attributes`, the array
389/// holds zeros.
390pub(crate) fn packed<const N: usize>(attributes: &[Attribute]) -> ([VertexAttribute; N], u32) {
391    let mut out = [VertexAttribute {
392        location: 0,
393        format: VertexFormat::Float32,
394        offset: 0,
395    }; N];
396    let mut offset = 0;
397    for (slot, attribute) in out.iter_mut().zip(attributes) {
398        *slot = VertexAttribute {
399            location: attribute.location,
400            format: attribute.format,
401            offset,
402        };
403        offset += attribute.format.size();
404    }
405    (out, offset)
406}
407
408/// The GLSL type of a format.
409fn glsl_type(format: VertexFormat) -> &'static str {
410    match format {
411        VertexFormat::Float32 => "float",
412        VertexFormat::Float32x2 => "vec2",
413        VertexFormat::Float32x3 => "vec3",
414        VertexFormat::Float32x4 => "vec4",
415        // A format gfx adds later needs its type here; until then, no
416        // declaration matches it.
417        _ => "?",
418    }
419}
420
421/// `source` as the GLSL preprocessor reads it before it runs its
422/// directives, in one pass that never reads again what it made: each `\`
423/// before a newline joins the two lines; each newline is a `\n`, `\r\n`,
424/// `\n\r` and a `\r` alone each being one, as GLSL has it; each comment is
425/// a space; and a `"` starts a string, to the next `"` or the end of the
426/// line, in which no comment starts. As Mesa's preprocessor does, the line
427/// of a directive it does not take apart, such as `#pragma`, `#error` or
428/// `#extension`, keeps the rest of its text as it is.
429fn preprocessed(source: &str) -> String {
430    // `\r\n` and `\n\r` are one newline: the second of the pair goes with
431    // the first.
432    fn pair(first: char, chars: &mut Peekable<Chars<'_>>) {
433        chars.next_if_eq(&if first == '\r' { '\n' } else { '\r' });
434    }
435    // Past a block comment whose `/*` was read.
436    fn comment(chars: &mut Peekable<Chars<'_>>) {
437        let mut last = ' ';
438        for c in chars.by_ref() {
439            if last == '*' && c == '/' {
440                break;
441            }
442            last = c;
443        }
444    }
445    let mut lines = String::with_capacity(source.len());
446    let mut chars = source.chars().peekable();
447    while let Some(c) = chars.next() {
448        if c == '\\'
449            && let Some(newline) = chars.next_if(|&c| c == '\r' || c == '\n')
450        {
451            pair(newline, &mut chars);
452        } else if c == '\r' || c == '\n' {
453            pair(c, &mut chars);
454            lines.push('\n');
455        } else {
456            lines.push(c);
457        }
458    }
459
460    let mut text = String::with_capacity(lines.len());
461    let mut chars = lines.chars().peekable();
462    // Whether only spaces and comments have come since the last newline.
463    let mut line_start = true;
464    while let Some(c) = chars.next() {
465        match (c, chars.peek()) {
466            ('\n', _) => {
467                text.push('\n');
468                line_start = true;
469            }
470            ('/', Some('/')) => {
471                while chars.next_if(|&c| c != '\n').is_some() {}
472                text.push(' ');
473            }
474            ('/', Some('*')) => {
475                chars.next();
476                comment(&mut chars);
477                text.push(' ');
478            }
479            ('"', _) => {
480                text.push('"');
481                while let Some(c) = chars.next_if(|&c| c != '"' && c != '\n') {
482                    text.push(c);
483                }
484                if chars.next_if_eq(&'"').is_some() {
485                    text.push('"');
486                }
487                line_start = false;
488            }
489            ('#', _) if line_start => {
490                // The directive's name, after spaces and comments.
491                let mut ahead = chars.clone();
492                loop {
493                    while ahead.next_if(|&c| is_space(c) && c != '\n').is_some() {}
494                    let mut opening = ahead.clone();
495                    if opening.next() != Some('/') || opening.next() != Some('*') {
496                        break;
497                    }
498                    ahead = opening;
499                    comment(&mut ahead);
500                }
501                let mut name = String::new();
502                while let Some(c) = ahead.next_if(|&c| c.is_ascii_alphanumeric() || c == '_') {
503                    name.push(c);
504                }
505                text.push('#');
506                let taken_apart = matches!(
507                    name.as_str(),
508                    "" | "define"
509                        | "undef"
510                        | "if"
511                        | "ifdef"
512                        | "ifndef"
513                        | "elif"
514                        | "else"
515                        | "endif"
516                        | "line"
517                        | "version"
518                );
519                if !taken_apart {
520                    chars = ahead;
521                    text.push(' ');
522                    text.push_str(&name);
523                    while let Some(c) = chars.next_if(|&c| c != '\n') {
524                        text.push(c);
525                    }
526                }
527                line_start = false;
528            }
529            (c, _) => {
530                line_start &= is_space(c);
531                text.push(c);
532            }
533        }
534    }
535    text
536}
537
538/// Whether GLSL reads `c` as a space between tokens.
539fn is_space(c: char) -> bool {
540    matches!(c, ' ' | '\t' | '\n' | '\x0B' | '\x0C')
541}
542
543/// What a conditional directive does to its group of branches.
544#[derive(Clone, Copy, Debug, PartialEq, Eq)]
545enum Branch {
546    /// `#if`, `#ifdef` or `#ifndef`: a group starts.
547    If,
548    /// `#elif` or `#else`: another branch of it.
549    Else,
550    /// `#endif`: the group ends.
551    End,
552}
553
554/// A piece of GLSL: a word (a name, a keyword, or a number up to a `.`),
555/// one other character, or a conditional directive.
556#[derive(Clone, Copy, Debug, PartialEq, Eq)]
557enum Token<'a> {
558    Word(&'a str),
559    Mark(char),
560    Branch(Branch),
561}
562
563/// The tokens of `text`, a [`preprocessed`] source. Of its directives,
564/// each line whose first character, after spaces, is `#`, only the
565/// conditional ones are kept, each as a [`Token::Branch`].
566fn tokens(text: &str) -> Vec<Token<'_>> {
567    let mut out = Vec::new();
568    for line in text.split('\n') {
569        if let Some(directive) = line.trim_start_matches(is_space).strip_prefix('#') {
570            let name = directive.trim_start_matches(is_space);
571            let end = name
572                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
573                .unwrap_or(name.len());
574            match &name[..end] {
575                "if" | "ifdef" | "ifndef" => out.push(Token::Branch(Branch::If)),
576                "elif" | "else" => out.push(Token::Branch(Branch::Else)),
577                "endif" => out.push(Token::Branch(Branch::End)),
578                _ => {}
579            }
580            continue;
581        }
582        let mut rest = line;
583        while let Some(c) = rest.chars().next() {
584            if is_space(c) {
585                rest = &rest[c.len_utf8()..];
586            } else if c.is_ascii_alphanumeric() || c == '_' {
587                let length = rest
588                    .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
589                    .unwrap_or(rest.len());
590                out.push(Token::Word(&rest[..length]));
591                rest = &rest[length..];
592            } else {
593                out.push(Token::Mark(c));
594                rest = &rest[c.len_utf8()..];
595            }
596        }
597    }
598    out
599}
600
601/// The text of `tokens`, with nothing between them.
602fn text(tokens: &[Token<'_>]) -> String {
603    let mut text = String::new();
604    for &token in tokens {
605        match token {
606            Token::Word(word) => text.push_str(word),
607            Token::Mark(mark) => text.push(mark),
608            Token::Branch(_) => {}
609        }
610    }
611    text
612}
613
614/// `tokens` cut at each `mark` outside parentheses and brackets.
615fn split_outside<'t, 'a>(tokens: &'t [Token<'a>], mark: char) -> Vec<&'t [Token<'a>]> {
616    let mut parts = Vec::new();
617    let mut depth = 0_usize;
618    let mut start = 0;
619    for (index, &token) in tokens.iter().enumerate() {
620        match token {
621            Token::Mark('(' | '[') => depth += 1,
622            Token::Mark(')' | ']') => depth = depth.saturating_sub(1),
623            Token::Mark(found) if found == mark && depth == 0 => {
624                parts.push(&tokens[start..index]);
625                start = index + 1;
626            }
627            _ => {}
628        }
629    }
630    parts.push(&tokens[start..]);
631    parts
632}
633
634/// One qualifier of a layout: its name as written, and its value as
635/// written, if it has one.
636type Qualifier = (String, Option<String>);
637
638/// A variable a shader takes in or gives out.
639#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
640struct Variable {
641    /// Its layout's qualifiers.
642    layout: Vec<Qualifier>,
643    kind: String,
644    /// Its name, with any array size.
645    name: String,
646}
647
648impl Variable {
649    /// The value of its layout's qualifier `key`, of any case, read as a
650    /// GLSL integer: `None` without that qualifier, and `Some(None)` with a
651    /// value that is not an integer, or no value.
652    fn qualifier(&self, key: &str) -> Option<Option<u32>> {
653        self.layout
654            .iter()
655            .find(|(name, _)| name.eq_ignore_ascii_case(key))
656            .map(|(_, value)| value.as_deref().and_then(integer))
657    }
658
659    /// Its declaration, such as `layout(location = 6) in vec2 corner;`.
660    fn declaration(&self, storage: &str) -> String {
661        let mut declared = String::new();
662        if !self.layout.is_empty() {
663            let qualifiers: Vec<String> = self
664                .layout
665                .iter()
666                .map(|(key, value)| match value {
667                    Some(value) => format!("{key} = {value}"),
668                    None => key.clone(),
669                })
670                .collect();
671            declared = format!("layout({}) ", qualifiers.join(", "));
672        }
673        declared.push_str(&format!("{storage} {} {};", self.kind, self.name));
674        declared
675    }
676}
677
678/// What a GLSL source declares at its top level.
679#[derive(Debug, PartialEq, Eq)]
680struct Declarations {
681    /// The `in` variables (`attribute` ones too).
682    inputs: Vec<Variable>,
683    /// The `out` variables.
684    outputs: Vec<Variable>,
685    /// The uniform blocks' names.
686    blocks: Vec<String>,
687    /// The other uniforms without a value of their own: type, and name with
688    /// any array size. A struct's type is `struct`.
689    uniforms: Vec<(String, String)>,
690    /// The built-in outputs of GLSL before 1.30 it names anywhere:
691    /// `gl_FragColor` and `gl_FragData`.
692    built_in_outputs: Vec<String>,
693    /// Whether its braces pair up, and each branch of its `#if`s holds whole
694    /// statements and leaves the braces as deep as the others, as written.
695    readable: bool,
696}
697
698/// The declarations of `source`: each statement at the top level, up to
699/// its `;`, or to the `{` of a body, which is passed over.
700fn declarations(source: &str) -> Declarations {
701    let text = preprocessed(source);
702    let mut out = Declarations {
703        inputs: Vec::new(),
704        outputs: Vec::new(),
705        blocks: Vec::new(),
706        uniforms: Vec::new(),
707        built_in_outputs: Vec::new(),
708        readable: true,
709    };
710    let mut statement = Vec::new();
711    let mut depth = 0_usize;
712    // Each group of branches open: the depth it starts at, and the depth
713    // its branches so far end at.
714    let mut groups: Vec<(usize, Option<usize>)> = Vec::new();
715    for token in tokens(&text) {
716        if let Token::Word(word @ ("gl_FragColor" | "gl_FragData")) = token {
717            out.built_in_outputs.push(word.to_string());
718        }
719        match (depth, token) {
720            (_, Token::Branch(branch)) => {
721                if depth == 0 && !statement.is_empty() {
722                    out.readable = false;
723                }
724                match branch {
725                    Branch::If => groups.push((depth, None)),
726                    Branch::Else => match groups.last_mut() {
727                        Some((start, end)) => {
728                            if end.is_some_and(|end| end != depth) {
729                                out.readable = false;
730                            }
731                            *end = Some(depth);
732                            depth = *start;
733                        }
734                        None => out.readable = false,
735                    },
736                    Branch::End => match groups.pop() {
737                        Some((start, end)) => {
738                            if end.unwrap_or(start) != depth {
739                                out.readable = false;
740                            }
741                        }
742                        None => out.readable = false,
743                    },
744                }
745            }
746            (0, Token::Mark(';')) => {
747                declare(&statement, false, &mut out);
748                statement.clear();
749            }
750            (0, Token::Mark('{')) => {
751                declare(&statement, true, &mut out);
752                statement.clear();
753                depth = 1;
754            }
755            (0, Token::Mark('}')) => out.readable = false,
756            (0, token) => statement.push(token),
757            (_, Token::Mark('{')) => depth += 1,
758            (_, Token::Mark('}')) => depth -= 1,
759            _ => {}
760        }
761    }
762    if depth != 0 || !groups.is_empty() {
763        out.readable = false;
764    }
765    out.built_in_outputs.sort_unstable();
766    out.built_in_outputs.dedup();
767    out
768}
769
770/// The value of a GLSL integer: decimal, octal after a `0`, or hexadecimal
771/// after `0x`, with an optional `u`.
772fn integer(text: &str) -> Option<u32> {
773    let digits = text.strip_suffix(['u', 'U']).unwrap_or(text);
774    if let Some(hex) = digits
775        .strip_prefix("0x")
776        .or_else(|| digits.strip_prefix("0X"))
777    {
778        u32::from_str_radix(hex, 16).ok()
779    } else if let Some(octal) = digits.strip_prefix('0').filter(|octal| !octal.is_empty()) {
780        u32::from_str_radix(octal, 8).ok()
781    } else {
782        digits.parse().ok()
783    }
784}
785
786/// Adds what one statement declares to `out`: an `in` or `out` variable,
787/// a uniform, or, before a body, a uniform block or a uniform struct.
788/// Anything else, such as a function, a struct type or a block of `in` or
789/// `out` variables, declares nothing the check reads.
790fn declare(statement: &[Token<'_>], opens_body: bool, out: &mut Declarations) {
791    let mut rest = statement;
792    let mut layout = Vec::new();
793    let mut storage = None;
794    loop {
795        match rest {
796            [Token::Word("layout"), Token::Mark('('), tail @ ..] => {
797                let end = tail
798                    .iter()
799                    .position(|&token| token == Token::Mark(')'))
800                    .unwrap_or(tail.len());
801                for part in tail[..end].split(|&token| token == Token::Mark(',')) {
802                    layout.push(match part {
803                        [Token::Word(key)] => ((*key).to_string(), None),
804                        [Token::Word(key), Token::Mark('='), value @ ..] => {
805                            ((*key).to_string(), Some(text(value)))
806                        }
807                        _ => (text(part), None),
808                    });
809                }
810                rest = tail.get(end + 1..).unwrap_or(&[]);
811            }
812            // `attribute`, from before GLSL 1.30, is an `in` of the vertex
813            // shader.
814            [
815                Token::Word(word @ ("in" | "attribute" | "out" | "uniform")),
816                tail @ ..,
817            ] => {
818                storage = Some(if *word == "attribute" { "in" } else { *word });
819                rest = tail;
820            }
821            [
822                Token::Word(
823                    "flat" | "smooth" | "noperspective" | "centroid" | "invariant" | "highp"
824                    | "mediump" | "lowp" | "const",
825                ),
826                tail @ ..,
827            ] => rest = tail,
828            _ => break,
829        }
830    }
831    let [Token::Word(kind), names @ ..] = rest else {
832        return;
833    };
834    if opens_body {
835        match (storage, *kind) {
836            (Some("uniform"), "struct") => {
837                let name = text(names);
838                let name = if name.is_empty() {
839                    "{…}".to_string()
840                } else {
841                    format!("{name} {{…}}")
842                };
843                out.uniforms.push(("struct".to_string(), name));
844            }
845            (Some("uniform"), _) if names.is_empty() => out.blocks.push((*kind).to_string()),
846            _ => {}
847        }
848        return;
849    }
850    for declared in split_outside(names, ',') {
851        let parts = split_outside(declared, '=');
852        let name = parts.first().map_or_else(String::new, |name| text(name));
853        let has_value = parts.len() > 1;
854        let list = match storage {
855            Some("in") => &mut out.inputs,
856            Some("out") => &mut out.outputs,
857            Some("uniform") if !has_value => {
858                out.uniforms.push(((*kind).to_string(), name));
859                continue;
860            }
861            _ => continue,
862        };
863        list.push(Variable {
864            layout: layout.clone(),
865            kind: (*kind).to_string(),
866            name,
867        });
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use std::fs;
874    use std::path::Path;
875
876    use super::*;
877    use crate::{SPRITE_INSTANCE_FLOATS, TILE_INSTANCE_FLOATS};
878
879    /// A variable as (its location, type, name).
880    type Read = (Option<u32>, String, String);
881
882    fn read(variables: &[Variable]) -> Vec<Read> {
883        variables
884            .iter()
885            .map(|v| {
886                (
887                    v.qualifier("location").flatten(),
888                    v.kind.clone(),
889                    v.name.clone(),
890                )
891            })
892            .collect()
893    }
894
895    fn at(location: Option<u32>, kind: &str, name: &str) -> Read {
896        (location, kind.to_string(), name.to_string())
897    }
898
899    fn uniform(kind: &str, name: &str) -> (String, String) {
900        (kind.to_string(), name.to_string())
901    }
902
903    #[test]
904    fn the_glsl_declares_exactly_the_interface() {
905        for &program in Program::ALL {
906            let interface = program.interface();
907            let name = program.name();
908            assert_eq!(
909                interface.check(interface.vertex, interface.fragment),
910                Ok(()),
911                "{name}"
912            );
913            // The check takes sources that leave something out; the
914            // renderer's own declare it all.
915            let vertex = declarations(interface.vertex);
916            let fragment = declarations(interface.fragment);
917            let inputs = read(&vertex.inputs);
918            for attribute in interface.instance.iter().chain(interface.vertex_attributes) {
919                let declared = at(
920                    Some(attribute.location),
921                    glsl_type(attribute.format),
922                    attribute.name,
923                );
924                assert!(inputs.contains(&declared), "{name} {declared:?}");
925            }
926            for block in interface.uniform_blocks {
927                let declared = block.name.to_string();
928                assert!(
929                    vertex.blocks.contains(&declared) || fragment.blocks.contains(&declared),
930                    "{name} {declared}"
931                );
932            }
933            for texture in interface.textures {
934                let declared = uniform("sampler2D", texture);
935                assert!(
936                    vertex.uniforms.contains(&declared) || fragment.uniforms.contains(&declared),
937                    "{name} {texture}"
938                );
939            }
940        }
941    }
942
943    #[test]
944    fn the_shader_folder_holds_the_sources_compiled_in() {
945        for &program in Program::ALL {
946            let interface = program.interface();
947            let read = |file: &str| {
948                fs::read_to_string(Path::new(SHADER_DIR).join(file)).expect("a shader file")
949            };
950            assert_eq!(read(program.vertex_file()), interface.vertex);
951            assert_eq!(read(program.fragment_file()), interface.fragment);
952            assert!(program.vertex_file().starts_with(program.name()));
953        }
954    }
955
956    #[test]
957    fn the_reader_finds_declarations_however_they_are_written() {
958        let source = "#version 330 core
959// layout(location = 9) in vec2 commented;
960/* layout(location = 8) in vec2 also;
961   uniform float commented_too; */
962#define DECLARE(x) \\
963    in vec2 x;
964layout( location=3 )in vec4 uv_rect ;
965layout(location = 12) in highp float a;
966in vec2 unplaced;
967attribute vec2 old;
968layout(location = N) in vec2 by_macro;
969layout(LOCATION = 0x1A) in vec2 hex;
970layout(location = 010) in vec2 octal;
971layout(location = 2, component = 2) in vec2 split;
972flat out vec4 v_color;
973out Varyings { vec2 uv; } vary;
974layout(std140) uniform Camera { vec4 view; } camera;
975uniform sampler2D first, second[2];
976uniform float strength = 1.0, unset;
977uniform vec4 tint = vec4(1.0, 0.5, 0.5, 1.0), weights[2] = vec4[2](vec4(1.0), vec4(0.0));
978uniform struct Fx { float strength; } fx;
979struct Light { vec2 at; float radius; };
980vec2 helper(vec2 a) { return a; }
981void main() { in_body(); { gl_Position = vec4(0.0); } }
982";
983        let found = declarations(source);
984        assert_eq!(
985            read(&found.inputs),
986            [
987                at(Some(3), "vec4", "uv_rect"),
988                at(Some(12), "float", "a"),
989                at(None, "vec2", "unplaced"),
990                at(None, "vec2", "old"),
991                at(None, "vec2", "by_macro"),
992                at(Some(26), "vec2", "hex"),
993                at(Some(8), "vec2", "octal"),
994                at(Some(2), "vec2", "split"),
995            ]
996        );
997        assert_eq!(
998            found.inputs[7].declaration("in"),
999            "layout(location = 2, component = 2) in vec2 split;"
1000        );
1001        assert_eq!(read(&found.outputs), [at(None, "vec4", "v_color")]);
1002        assert_eq!(found.blocks, ["Camera"]);
1003        assert_eq!(
1004            found.uniforms,
1005            [
1006                uniform("sampler2D", "first"),
1007                uniform("sampler2D", "second[2]"),
1008                uniform("float", "unset"),
1009                uniform("struct", "Fx {…}"),
1010            ]
1011        );
1012        assert!(found.built_in_outputs.is_empty());
1013        assert!(found.readable);
1014    }
1015
1016    #[test]
1017    fn the_lines_are_read_as_the_preprocessor_reads_them() {
1018        let inputs = |source: &str| read(&declarations(source).inputs);
1019        let corner = |location| vec![at(Some(location), "vec2", "corner")];
1020        // A `\` before a newline joins the lines anywhere: a comment's line
1021        // takes the next, and a word is made whole.
1022        assert_eq!(
1023            inputs(
1024                "// \\\nlayout(location = 6) in vec2 corner;\nlay\\\nout(location = 7) in vec2 corner;"
1025            ),
1026            corner(7)
1027        );
1028        // A `\` before a space joins nothing, and one join never makes
1029        // another: the `\` before the `\` and its `\r\n` stays.
1030        assert_eq!(
1031            inputs("#define NOTHING \\ \nlayout(location = 7) in vec2 corner;"),
1032            corner(7)
1033        );
1034        assert_eq!(
1035            inputs("// path \\\\\r\n\nlayout(location = 7) in vec2 corner;"),
1036            corner(7)
1037        );
1038        // `\n\r` is one newline, joined by a `\` as `\r\n` is.
1039        assert_eq!(
1040            inputs(
1041                "#define OPEN \\\n\r{\nlayout(location = 7) in vec2 corner;\n#define CLOSE \\\n\r}"
1042            ),
1043            corner(7)
1044        );
1045        assert!(declarations("#define OPEN \\\n\r{\nvoid f() {}\n").readable);
1046        // A comment opened in a `#define` ends the directive where it ends;
1047        // on a `#pragma`, `#error` or `#extension` line it is the line's
1048        // own text.
1049        assert_eq!(
1050            inputs(
1051                "#define NOTHING /*\nlayout(location = 6) in vec2 corner;\n*/\nlayout(location = 7) in vec2 corner;"
1052            ),
1053            corner(7)
1054        );
1055        for directive in ["#pragma", "#error", "  #  extension", "# /*\n*/ pragma"] {
1056            assert_eq!(
1057                inputs(&format!(
1058                    "{directive} /*\nlayout(location = 7) in vec2 corner;\n{directive} */"
1059                )),
1060                corner(7),
1061                "{directive}"
1062            );
1063        }
1064        // Nor on the line of a directive Mesa does not know, and a string
1065        // holds no comment; but a comment on a `#line` is one.
1066        assert_eq!(
1067            inputs("#if 0\n#errorX /*\n#endif\nlayout(location = 7) in vec2 corner;\n// */"),
1068            corner(7)
1069        );
1070        assert_eq!(
1071            inputs("#define S \"/*\"\nlayout(location = 7) in vec2 corner;\n// */"),
1072            corner(7)
1073        );
1074        assert_eq!(
1075            inputs(
1076                "#line 20 /*\nlayout(location = 6) in vec2 corner;\n*/\nlayout(location = 7) in vec2 corner;"
1077            ),
1078            corner(7)
1079        );
1080        // A `#` alone is a directive of its own, and the next line is not
1081        // its name.
1082        assert_eq!(
1083            inputs("#\nerror e; layout(location = 7) in vec2 corner;"),
1084            corner(7)
1085        );
1086        // A comment before a `#` leaves it first on its line, and a line
1087        // comment after code leaves the next line a line of its own.
1088        assert_eq!(
1089            inputs("/* a\nb */ #define X\nlayout(location = 7) in vec2 corner;"),
1090            corner(7)
1091        );
1092        assert_eq!(
1093            inputs("in vec2 a; // c\n#define X\nlayout(location = 7) in vec2 corner;"),
1094            [at(None, "vec2", "a"), at(Some(7), "vec2", "corner")]
1095        );
1096        // A `\r` alone, or a `\r\n`, is a newline, and a vertical tab a
1097        // space.
1098        assert_eq!(
1099            inputs("// note\rlayout(location = 7) in vec2 corner;"),
1100            corner(7)
1101        );
1102        assert_eq!(
1103            inputs("#define X\r\nlayout(location = 7)\x0Bin vec2 corner;"),
1104            corner(7)
1105        );
1106        // An unterminated comment, or a directive on the last line, runs
1107        // to the end.
1108        assert_eq!(
1109            inputs("layout(location = 7) in vec2 corner; /* in vec2 x;"),
1110            corner(7)
1111        );
1112        assert_eq!(
1113            inputs("layout(location = 7) in vec2 corner;\n#define B"),
1114            corner(7)
1115        );
1116        // A `#` that is not first on its line is a mark.
1117        assert_eq!(
1118            tokens("a # b"),
1119            [Token::Word("a"), Token::Mark('#'), Token::Word("b")]
1120        );
1121        assert_eq!(tokens("é;"), [Token::Mark('é'), Token::Mark(';')]);
1122        assert_eq!(
1123            tokens("#ifdef A\n# elif B\n#else\n#endif\n#define C"),
1124            [
1125                Token::Branch(Branch::If),
1126                Token::Branch(Branch::Else),
1127                Token::Branch(Branch::Else),
1128                Token::Branch(Branch::End),
1129            ]
1130        );
1131    }
1132
1133    #[test]
1134    fn integers_are_read_as_glsl_writes_them() {
1135        assert_eq!(integer("6"), Some(6));
1136        assert_eq!(integer("6u"), Some(6));
1137        assert_eq!(integer("0"), Some(0));
1138        assert_eq!(integer("010"), Some(8));
1139        assert_eq!(integer("0x1f"), Some(31));
1140        assert_eq!(integer("0XAU"), Some(10));
1141        assert_eq!(integer("08"), None);
1142        assert_eq!(integer("0x"), None);
1143        assert_eq!(integer("N"), None);
1144    }
1145
1146    #[test]
1147    fn branches_and_braces_that_do_not_hold_whole_declarations_are_refused() {
1148        let readable = |source: &str| declarations(source).readable;
1149        // Each branch opens a brace, closed after the group: the uniform
1150        // after it is read.
1151        let paired =
1152            "#if 1\nvoid helper() {\n#else\nvoid helper2() {\n#endif\n}\nuniform float seen;";
1153        assert!(readable(paired));
1154        assert_eq!(declarations(paired).uniforms, [uniform("float", "seen")]);
1155        assert!(!readable("}"));
1156        assert!(!readable("void f() {"));
1157        // Braces paired across two groups of branches.
1158        assert!(!readable(
1159            "#if 0\nvoid hidden_a() {\n#endif\nuniform vec4 tint;\n#if 0\n}\n#endif"
1160        ));
1161        // A branch that splits a statement, or holds part of one.
1162        assert!(!readable("uniform\n#if 0\n;\n#endif\nvec4 tint;"));
1163        assert!(!readable("#if 0\nfoo\n#endif\nuniform vec4 tint;"));
1164        assert!(!readable(
1165            "#if 1\n#else\nfoo\n#endif\nlayout(location = 0) in vec2 corner;"
1166        ));
1167        // A group not closed, or not opened.
1168        assert!(!readable("#ifdef A\nin vec2 a;"));
1169        assert!(!readable("#endif"));
1170        assert!(!readable("#else"));
1171        // Whole declarations in each branch, and branches in a body that
1172        // each open a brace closed after them, are read.
1173        assert!(readable(
1174            "#ifdef A\nin vec2 a;\n#elif B\nin vec2 b;\n#else\n#endif\n"
1175        ));
1176        assert!(readable(
1177            "void main() {\n#ifdef A\n    if (a) {\n#else\n    if (b) {\n#endif\n    }\n}\nuniform float x;"
1178        ));
1179        assert!(readable(
1180            "#ifdef A\nvoid f() {\n#else\nvoid f() {\n#endif\n}"
1181        ));
1182        let hidden = "#if 0\nvoid hidden_a() {\n#endif\nuniform vec4 tint;\n#if 0\n}\n#endif";
1183        let fragment = format!("{}\n{hidden}", SPRITE.fragment);
1184        assert!(
1185            SPRITE
1186                .check(SPRITE.vertex, &fragment)
1187                .is_err_and(|e| e.starts_with("the fragment shader's braces, or the branches"))
1188        );
1189    }
1190
1191    /// The sprite program's sources, with `from` replaced by `to`.
1192    fn sprite_with(from: &str, to: &str) -> Result<(), String> {
1193        let vertex = SPRITE.vertex.replace(from, to);
1194        let fragment = SPRITE.fragment.replace(from, to);
1195        assert!(
1196            vertex != SPRITE.vertex || fragment != SPRITE.fragment,
1197            "`{from}` is in the sources"
1198        );
1199        SPRITE.check(&vertex, &fragment)
1200    }
1201
1202    #[test]
1203    fn an_attribute_moved_retyped_or_added_is_refused() {
1204        assert_eq!(
1205            sprite_with(
1206                "location = 6) in vec2 corner",
1207                "location = 7) in vec2 corner"
1208            ),
1209            Err(
1210                "`layout(location = 7) in vec2 corner;` is not one of the program's attributes \
1211                 (it has `layout(location = 6) in vec2 corner;`)"
1212                    .to_string()
1213            )
1214        );
1215        assert_eq!(
1216            sprite_with("in float rotation", "in vec2 rotation"),
1217            Err(
1218                "`layout(location = 5) in vec2 rotation;` is not one of the program's attributes \
1219                 (it has `layout(location = 5) in float rotation;`)"
1220                    .to_string()
1221            )
1222        );
1223        for added in ["in vec2 extra;", "attribute vec2 extra;"] {
1224            assert_eq!(
1225                sprite_with("out vec2 v_uv;", &format!("{added}\nout vec2 v_uv;")),
1226                Err(
1227                    "`in vec2 extra;` has no location, and is not one of the program's attributes"
1228                        .to_string()
1229                ),
1230                "{added}"
1231            );
1232        }
1233        // Read as GLSL reads it, `010` is location 8.
1234        assert!(
1235            sprite_with(
1236                "location = 6) in vec2 corner",
1237                "location = 010) in vec2 corner"
1238            )
1239            .is_err_and(|e| e.starts_with("`layout(location = 010) in vec2 corner;` is not"))
1240        );
1241        // Another layout qualifier binds it elsewhere.
1242        assert_eq!(
1243            sprite_with(
1244                "location = 6) in vec2 corner",
1245                "location = 6, component = 2) in vec2 corner"
1246            ),
1247            Err(
1248                "`layout(location = 6, component = 2) in vec2 corner;` is not one of the \
1249                 program's attributes (it has `layout(location = 6) in vec2 corner;`)"
1250                    .to_string()
1251            )
1252        );
1253        // In both branches of an `#if`, the difference is said once.
1254        assert_eq!(
1255            sprite_with(
1256                "layout(location = 6) in vec2 corner;",
1257                "#ifdef A\nlayout(location = 7) in vec2 corner;\n#else\nlayout(location = 7) \
1258                 in vec2 corner;\n#endif"
1259            ),
1260            Err(
1261                "`layout(location = 7) in vec2 corner;` is not one of the program's attributes \
1262                 (it has `layout(location = 6) in vec2 corner;`)"
1263                    .to_string()
1264            )
1265        );
1266    }
1267
1268    #[test]
1269    fn a_uniform_the_renderer_does_not_set_is_refused() {
1270        assert_eq!(
1271            sprite_with("sprite_texture", "picture"),
1272            Err(
1273                "`uniform sampler2D picture;` is not one of the program's: the renderer sets \
1274                 only its uniform blocks and its samplers"
1275                    .to_string()
1276            )
1277        );
1278        assert_eq!(
1279            sprite_with(
1280                "uniform sampler2D sprite_texture;",
1281                "uniform isampler2D sprite_texture;"
1282            ),
1283            Err(
1284                "`uniform isampler2D sprite_texture;` is not one of the program's: the renderer \
1285                 sets only its uniform blocks and its samplers (`sprite_texture` is a `sampler2D`)"
1286                    .to_string()
1287            )
1288        );
1289        // In either shader.
1290        for shader in ["out vec2 v_uv;", "in vec2 v_uv;"] {
1291            let plain = sprite_with(shader, &format!("uniform float strength;\n{shader}"));
1292            assert!(
1293                plain.is_err_and(|e| e.starts_with("`uniform float strength;` is not one of")),
1294                "{shader}"
1295            );
1296            let block = sprite_with(
1297                shader,
1298                &format!("layout(std140) uniform Extra {{ vec4 e; }};\n{shader}"),
1299            );
1300            assert_eq!(
1301                block,
1302                Err(
1303                    "uniform block `Extra` is not one of the program's (it has `Camera`)"
1304                        .to_string()
1305                ),
1306                "{shader}"
1307            );
1308        }
1309        assert!(
1310            sprite_with(
1311                "in vec2 v_uv;",
1312                "uniform struct Fx { float strength; } fx;\nin vec2 v_uv;"
1313            )
1314            .is_err_and(|e| e.starts_with("`uniform struct Fx {…};` is not one of"))
1315        );
1316        assert!(
1317            sprite_with(
1318                "in vec2 v_uv;",
1319                "uniform struct { float strength; } fx;\nin vec2 v_uv;"
1320            )
1321            .is_err_and(|e| e.starts_with("`uniform struct {…};` is not one of"))
1322        );
1323        // A uniform after one with a value is still one without.
1324        assert!(
1325            sprite_with(
1326                "in vec2 v_uv;",
1327                "uniform vec2 offset = vec2(0.5, 0.5), scale;\nin vec2 v_uv;"
1328            )
1329            .is_err_and(|e| e.starts_with("`uniform vec2 scale;` is not one of"))
1330        );
1331        assert_eq!(
1332            sprite_with("uniform Camera", "uniform View"),
1333            Err("uniform block `View` is not one of the program's (it has `Camera`)".to_string())
1334        );
1335        assert_eq!(
1336            BLIT.check(
1337                &format!(
1338                    "{}\nlayout(std140) uniform Camera {{ vec4 view; }};",
1339                    BLIT.vertex
1340                ),
1341                BLIT.fragment
1342            ),
1343            Err("uniform block `Camera` is not one of the program's, which has none".to_string())
1344        );
1345    }
1346
1347    #[test]
1348    fn the_fragment_shader_has_one_color_at_location_0() {
1349        for written in [
1350            "layout(location = 0) out vec4 out_color;",
1351            "layout(location = 0, index = 0) out vec4 out_color;",
1352            "#ifdef A\nout vec4 out_color;\n#else\nout vec4 out_color;\n#endif",
1353        ] {
1354            assert_eq!(
1355                sprite_with("out vec4 out_color;", written),
1356                Ok(()),
1357                "{written}"
1358            );
1359        }
1360        assert_eq!(
1361            sprite_with(
1362                "out vec4 out_color;",
1363                "layout(location = 1) out vec4 out_color;"
1364            ),
1365            Err(
1366                "the fragment shader has `layout(location = 1) out vec4 out_color;`, and must \
1367                 have one `out vec4`, at location 0: the renderer draws into one color"
1368                    .to_string()
1369            )
1370        );
1371        for (written, says) in [
1372            (
1373                "layout(location = 0, index = 1) out vec4 out_color;",
1374                "`layout(location = 0, index = 1) out vec4 out_color;`",
1375            ),
1376            (
1377                "layout(location = 0, INDEX = 0x1) out vec4 out_color;",
1378                "`layout(location = 0, INDEX = 0x1) out vec4 out_color;`",
1379            ),
1380            (
1381                "out vec4 debug;\nout vec4 out_color;",
1382                "`out vec4 debug;`, `out vec4 out_color;`",
1383            ),
1384            ("out vec3 out_color;", "`out vec3 out_color;`"),
1385            ("out vec4 out_color[2];", "`out vec4 out_color[2];`"),
1386        ] {
1387            assert!(
1388                sprite_with("out vec4 out_color;", written)
1389                    .is_err_and(|e| e.starts_with(&format!("the fragment shader has {says}, and"))),
1390                "{written}"
1391            );
1392        }
1393        assert_eq!(
1394            sprite_with("out vec4 out_color;", ""),
1395            Err(
1396                "the fragment shader has no output: it must have one `out vec4`, at location 0"
1397                    .to_string()
1398            )
1399        );
1400        for written in ["gl_FragData[1] = ", "gl_FragColor = "] {
1401            assert_eq!(
1402                sprite_with("out_color = ", written),
1403                Err(format!(
1404                    "the fragment shader writes `{}`: the renderer draws only its `out vec4`",
1405                    &written[..written.find([' ', '[']).unwrap_or(written.len())]
1406                )),
1407                "{written}"
1408            );
1409        }
1410    }
1411
1412    #[test]
1413    fn an_edit_inside_the_interface_is_taken() {
1414        // A new body, a comment, a helper function and the layout written
1415        // another way change no declaration.
1416        assert_eq!(
1417            sprite_with(
1418                "out_color = texture(sprite_texture, v_uv) * v_color;",
1419                "out_color = tint(texture(sprite_texture, v_uv)) * v_color; // brighter"
1420            ),
1421            Ok(())
1422        );
1423        for written in [
1424            "layout (location=0)\nin vec2 position ;",
1425            "layout(LOCATION = 0x0) in highp vec2 position;",
1426            "layout(location = 0u) in mediump vec2 position;",
1427            "layout(location = 0) in lowp vec2 position;",
1428            "layout(location = 0) const in vec2 position;",
1429        ] {
1430            assert_eq!(
1431                sprite_with("layout(location = 0) in vec2 position;", written),
1432                Ok(()),
1433                "{written}"
1434            );
1435        }
1436        for (from, to) in [
1437            ("in vec4 v_color;", "flat in vec4 v_color;"),
1438            ("in vec4 v_color;", "smooth in vec4 v_color;"),
1439            (
1440                "in vec4 v_color;",
1441                "noperspective centroid in vec4 v_color;",
1442            ),
1443            ("out vec4 v_color;", "invariant out vec4 v_color;"),
1444        ] {
1445            assert_eq!(sprite_with(from, to), Ok(()), "{to}");
1446        }
1447        // The same declaration in both branches of an `#if`.
1448        assert_eq!(
1449            sprite_with(
1450                "layout(location = 6) in vec2 corner;",
1451                "#ifdef FAST\nlayout(location = 6) in vec2 corner;\n#else\nlayout(location = 6) \
1452                 in vec2 corner;\n#endif"
1453            ),
1454            Ok(())
1455        );
1456        // Varyings in a block of their own.
1457        let vertex = SPRITE
1458            .vertex
1459            .replace("out vec2 v_uv;", "out Varyings { vec2 uv; } vary;");
1460        let fragment = SPRITE
1461            .fragment
1462            .replace("in vec2 v_uv;", "in Varyings { vec2 uv; } vary;");
1463        assert_eq!(SPRITE.check(&vertex, &fragment), Ok(()));
1464        // A uniform with a value of its own needs none from the renderer.
1465        for written in [
1466            "uniform float strength = 1.5;",
1467            "uniform vec4 tint = vec4(1.0, 1.0, 1.0, 1.0);",
1468            "uniform float weights[2] = float[2](1.0, max(1.0, 2.0));",
1469        ] {
1470            assert_eq!(
1471                sprite_with("in vec2 v_uv;", &format!("{written}\nin vec2 v_uv;")),
1472                Ok(()),
1473                "{written}"
1474            );
1475        }
1476        // An attribute or a sampler left out is taken: the device enables
1477        // an attribute the program does not read, and warns of a sampler.
1478        assert_eq!(
1479            sprite_with("layout(location = 5) in float rotation;", ""),
1480            Ok(())
1481        );
1482        assert_eq!(sprite_with("uniform sampler2D sprite_texture;", ""), Ok(()));
1483        // The block and the sampler may be declared in either shader, or
1484        // in both.
1485        let fragment = format!(
1486            "{}\nlayout(std140) uniform Camera {{ vec4 view; }};",
1487            SPRITE.fragment
1488        );
1489        assert_eq!(SPRITE.check(SPRITE.vertex, &fragment), Ok(()));
1490    }
1491
1492    #[test]
1493    fn the_reader_never_panics() {
1494        // Pieces of GLSL and of what breaks it, strung at random from a
1495        // fixed seed, then random bytes made text: the check reads edited
1496        // files, and must refuse, not panic.
1497        const PIECES: &[&str] = &[
1498            "layout",
1499            "(",
1500            ")",
1501            "location",
1502            "LOCATION",
1503            "index",
1504            "=",
1505            "0x1",
1506            "010",
1507            "6u",
1508            "in",
1509            "out",
1510            "attribute",
1511            "uniform",
1512            "struct",
1513            "flat",
1514            "{",
1515            "}",
1516            ";",
1517            ",",
1518            "[",
1519            "]",
1520            "#if",
1521            "#else",
1522            "#elif",
1523            "#endif",
1524            "#pragma",
1525            "#define",
1526            "#",
1527            "/*",
1528            "*/",
1529            "//",
1530            "\\",
1531            "\n",
1532            "\r",
1533            "\x0B",
1534            " ",
1535            "vec4",
1536            "vec2",
1537            "sampler2D",
1538            "x",
1539            "é",
1540            "gl_FragColor",
1541            "Camera",
1542        ];
1543        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
1544        let mut next = move || {
1545            state ^= state << 13;
1546            state ^= state >> 7;
1547            state ^= state << 17;
1548            state
1549        };
1550        for round in 0..4_000 {
1551            let length = (next() % 64) as usize;
1552            let source: String = if round % 4 == 3 {
1553                let bytes: Vec<u8> = (0..length).map(|_| next() as u8).collect();
1554                String::from_utf8_lossy(&bytes).into_owned()
1555            } else {
1556                (0..length)
1557                    .map(|_| PIECES[(next() % PIECES.len() as u64) as usize])
1558                    .collect()
1559            };
1560            for interface in [&SPRITE, &TILE_CHUNK, &BLIT, &TEXT] {
1561                let _ = interface.check(&source, &source);
1562                let _ = interface.check(interface.vertex, &source);
1563            }
1564        }
1565    }
1566
1567    #[test]
1568    fn the_sprite_instance_is_its_floats() {
1569        let (attributes, stride) = packed::<6>(SPRITE.instance);
1570        assert_eq!(stride, SPRITE_INSTANCE_FLOATS as u32 * 4);
1571        let offsets: Vec<u32> = attributes.iter().map(|a| a.offset / 4).collect();
1572        // The float each attribute starts at, as `push_instance` packs them.
1573        assert_eq!(offsets, [0, 2, 4, 6, 10, 14]);
1574    }
1575
1576    #[test]
1577    fn the_text_program_takes_the_sprite_s_instances_and_vertices() {
1578        // The renderer packs a glyph as a sprite, into the same buffer.
1579        assert!(std::ptr::eq(TEXT.instance, SPRITE.instance));
1580        assert!(std::ptr::eq(
1581            TEXT.vertex_attributes,
1582            SPRITE.vertex_attributes
1583        ));
1584        assert_eq!(TEXT.uniform_blocks, SPRITE.uniform_blocks);
1585        // Its vertex shader is the sprite's, its comments aside.
1586        let code = |source: &str| -> Vec<String> {
1587            source
1588                .lines()
1589                .map(str::trim)
1590                .filter(|line| !line.is_empty() && !line.starts_with("//"))
1591                .map(str::to_string)
1592                .collect()
1593        };
1594        assert_eq!(code(TEXT.vertex), code(SPRITE.vertex));
1595    }
1596
1597    #[test]
1598    fn the_tile_instance_is_its_floats() {
1599        let (attributes, stride) = packed::<2>(TILE_CHUNK.instance);
1600        assert_eq!(stride, TILE_INSTANCE_FLOATS as u32 * 4);
1601        let offsets: Vec<u32> = attributes.iter().map(|a| a.offset / 4).collect();
1602        // The float each attribute starts at, as `TileLayer::pack_chunk`
1603        // packs them.
1604        assert_eq!(offsets, [0, 2]);
1605    }
1606}