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
use {
    crate::{
        define::Define,
        eval::{GlobalOut, ReadIndex, Stage},
        group::{self, Group},
        instance::{self, Instance},
        ret::Ret,
        types::{MemberType, ValueType, VectorType},
        vertex::{self, Vertex},
    },
    std::{any::TypeId, mem, ops},
};

#[derive(Clone, Copy)]
pub struct GroupInfo {
    pub tyid: TypeId,
    pub def: Define<MemberType>,
    pub stages: Stages,
}

#[derive(Clone, Copy, Default)]
pub struct Stages {
    pub vs: bool,
    pub fs: bool,
}

impl Stages {
    pub(crate) fn with(self, stage: Stage) -> Self {
        match stage {
            Stage::Vertex => Self { vs: true, ..self },
            Stage::Fragment => Self { fs: true, ..self },
        }
    }
}

#[doc(hidden)]
#[derive(Clone, Copy)]
pub enum InputInfo {
    Vert(VertInfo),
    Inst(InstInfo),
    Index,
}

#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct VertInfo {
    pub def: Define<VectorType>,
    pub size: usize,
}

#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct InstInfo {
    pub ty: ValueType,
}

pub(crate) struct GroupEntry {
    tyid: TypeId,
    def: Define<MemberType>,
    out: GlobalOut,
}

impl GroupEntry {
    pub fn def(&self) -> Define<MemberType> {
        self.def
    }
}

struct Limits {
    index: u8,
    verts: u8,
    insts: u8,
    group: u8,
}

fn countdown(v: &mut u8, msg: &str) {
    match v.checked_sub(1) {
        Some(n) => *v = n,
        None => panic!("{msg}"),
    }
}

pub struct Context {
    pub(crate) inputs: Vec<InputInfo>,
    pub(crate) groups: Vec<GroupEntry>,
    limits: Limits,
}

impl Context {
    pub(crate) fn new() -> Self {
        Self {
            inputs: vec![],
            groups: vec![],
            limits: Limits {
                index: 1,
                verts: 1,
                insts: 2,
                group: 4,
            },
        }
    }

    fn add_index(&mut self) -> u32 {
        countdown(&mut self.limits.index, "too many indices in the shader");
        let id = self.inputs.len() as u32;
        self.inputs.push(InputInfo::Index);
        id
    }

    fn add_vertex(&mut self, def: Define<VectorType>, size: usize) -> u32 {
        countdown(&mut self.limits.verts, "too many vertices in the shader");
        let id = self.inputs.len() as u32;
        let info = VertInfo { def, size };
        self.inputs.push(InputInfo::Vert(info));
        id
    }

    fn add_instance(&mut self, ty: ValueType) -> u32 {
        countdown(&mut self.limits.insts, "too many instances in the shader");
        let id = self.inputs.len() as u32;
        let info = InstInfo { ty };
        self.inputs.push(InputInfo::Inst(info));
        id
    }

    fn add_group(&mut self, tyid: TypeId, def: Define<MemberType>) -> (u32, GlobalOut) {
        countdown(&mut self.limits.group, "too many groups in the shader");
        let out = GlobalOut::default();
        let en = GroupEntry {
            tyid,
            def,
            out: out.clone(),
        };

        let id = self.groups.len() as u32;
        self.groups.push(en);
        (id, out)
    }

    #[doc(hidden)]
    pub fn count_input(&self) -> usize {
        self.inputs
            .iter()
            .filter(|info| matches!(info, InputInfo::Vert(_) | InputInfo::Inst(_)))
            .count()
    }

    #[doc(hidden)]
    pub fn input(&self) -> impl Iterator<Item = InputInfo> + '_ {
        self.inputs.iter().copied()
    }

    #[doc(hidden)]
    pub fn groups(&self) -> impl Iterator<Item = GroupInfo> + '_ {
        self.groups.iter().map(|entry| GroupInfo {
            tyid: entry.tyid,
            def: entry.def,
            stages: entry.out.get(),
        })
    }
}

pub trait FromContextInput {
    type Vertex;
    type Instance;
    fn from_context_input(cx: &mut Context) -> Self;
}

impl<V> FromContextInput for V
where
    V: FromContext,
{
    type Vertex = ();
    type Instance = ();

    fn from_context_input(cx: &mut Context) -> Self {
        V::from_context(cx)
    }
}

pub struct InVertex<V>(V::Projection)
where
    V: Vertex;

impl<V> ops::Deref for InVertex<V>
where
    V: Vertex,
{
    type Target = V::Projection;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<V> FromContextInput for InVertex<V>
where
    V: Vertex,
{
    type Vertex = V;
    type Instance = ();

    fn from_context_input(cx: &mut Context) -> Self {
        let id = cx.add_vertex(V::DEF, mem::size_of::<V>());
        Self(vertex::Projection::projection(id))
    }
}

pub struct InInstance<I>(I::Projection)
where
    I: Instance;

impl<I> ops::Deref for InInstance<I>
where
    I: Instance,
{
    type Target = I::Projection;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<I> FromContextInput for InInstance<I>
where
    I: Instance,
{
    type Vertex = ();
    type Instance = I;

    fn from_context_input(cx: &mut Context) -> Self {
        let mut id = None;
        for ty in I::DEF {
            id.get_or_insert(cx.add_instance(ty));
        }

        let id = id.expect("the instance must have at least one field");
        Self(instance::Projection::projection(id))
    }
}

pub struct In<V, I>(pub V::Projection, pub I::Projection)
where
    V: Vertex,
    I: Instance;

impl<V, I> FromContextInput for In<V, I>
where
    V: Vertex,
    I: Instance,
{
    type Vertex = V;
    type Instance = I;

    fn from_context_input(cx: &mut Context) -> Self {
        let InVertex(vert): InVertex<V> = InVertex::from_context_input(cx);
        let InInstance(inst): InInstance<I> = InInstance::from_context_input(cx);
        Self(vert, inst)
    }
}

pub trait FromContext {
    fn from_context(cx: &mut Context) -> Self;
}

#[derive(Clone, Copy)]
pub struct Index(pub Ret<ReadIndex, u32>);

impl FromContext for Index {
    fn from_context(cx: &mut Context) -> Self {
        let id = cx.add_index();
        Self(ReadIndex::new(id))
    }
}

pub trait ProjectionFromContext {
    type Projection;
    fn from_context(cx: &mut Context) -> Self::Projection;
}

impl ProjectionFromContext for () {
    type Projection = ();
    fn from_context(_: &mut Context) -> Self::Projection {}
}

impl<A> ProjectionFromContext for A
where
    A: Group,
{
    type Projection = A::Projection;

    fn from_context(cx: &mut Context) -> Self::Projection {
        let (id, out) = cx.add_group(TypeId::of::<A::Projection>(), A::DEF);
        group::Projection::projection(id, out)
    }
}

macro_rules! impl_projection_from_context {
    ($($t:ident),*) => {
        impl<$($t),*> ProjectionFromContext for ($($t),*,)
        where
            $(
                $t: Group,
            )*
        {
            type Projection = ($($t::Projection),*,);

            fn from_context(cx: &mut Context) -> Self::Projection {
                (
                    $({
                        let (id, out) = cx.add_group(TypeId::of::<$t::Projection>(), $t::DEF);
                        group::Projection::projection(id, out)
                    }),*,
                )
            }
        }
    };
}

impl_projection_from_context!(A);
impl_projection_from_context!(A, B);
impl_projection_from_context!(A, B, C);
impl_projection_from_context!(A, B, C, D);

pub struct Groups<G>(pub G::Projection)
where
    G: ProjectionFromContext;

impl<G> FromContext for Groups<G>
where
    G: ProjectionFromContext,
{
    fn from_context(cx: &mut Context) -> Self {
        Self(G::from_context(cx))
    }
}