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
use crate::{
    makepad_live_compiler::{
        LiveType,
        LiveNode,
        LiveId,
        LiveModuleId,
        LiveTypeInfo,
        LiveNodeSliceApi
    },
    live_traits::{LiveNew, LiveApply, ApplyFrom},
    makepad_live_tokenizer::{LiveErrorOrigin, live_error_origin},
    makepad_live_id::*,
    makepad_math::*,
    id_pool::*,
    area::Area,
    window::WindowId,
    os::CxOsPass,
    cx::Cx,
    draw_list::DrawListId,
    live_traits::*,
    texture::{
        Texture,
        TextureId
    }
};

#[derive(Debug)]
pub struct Pass(PoolId);

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PassId(pub (crate) usize);

impl Pass {
}

#[derive(Default)]
pub struct CxPassPool(pub (crate) IdPool<CxPass>);
impl CxPassPool {
    fn alloc(&mut self) -> Pass {
        Pass(self.0.alloc())
    }
    
    pub fn id_iter(&self) -> PassIterator {
        PassIterator {
            cur: 0,
            len: self.0.pool.len()
        }
    }
}

pub struct PassIterator {
    cur: usize,
    len: usize
}

impl Iterator for PassIterator {
    type Item = PassId;
    fn next(&mut self) -> Option<Self::Item> {
        if self.cur >= self.len {
            return None;
        }
        let cur = self.cur;
        self.cur += 1;
        Some(PassId(cur))
    }
}

impl std::ops::Index<PassId> for CxPassPool {
    type Output = CxPass;
    fn index(&self, index: PassId) -> &Self::Output {
        &self.0.pool[index.0].item
    }
}

impl std::ops::IndexMut<PassId> for CxPassPool {
    fn index_mut(&mut self, index: PassId) -> &mut Self::Output {
        &mut self.0.pool[index.0].item
    }
}

impl LiveHook for Pass {}
impl LiveNew for Pass {
    fn live_design_with(_cx:&mut Cx){}
    fn new(cx: &mut Cx) -> Self {
        let pass = cx.passes.alloc();
        pass
    }
    
    fn live_type_info(_cx: &mut Cx) -> LiveTypeInfo {
        LiveTypeInfo {
            module_id: LiveModuleId::from_str(&module_path!()).unwrap(),
            live_type: LiveType::of::<Self>(),
            fields: Vec::new(),
            live_ignore: true,
            //kind: LiveTypeKind::Object,
            type_name: id_lut!(Pass)
        }
    }
}

impl LiveApply for Pass {
    
    fn apply(&mut self, cx: &mut Cx, from: ApplyFrom, start_index: usize, nodes: &[LiveNode]) -> usize {
        
        if !nodes[start_index].value.is_structy_type() {
            cx.apply_error_wrong_type_for_struct(live_error_origin!(), start_index, nodes, live_id!(View));
            return nodes.skip_node(start_index);
        }
        
        let mut index = start_index + 1;
        loop {
            if nodes[index].value.is_close() {
                index += 1;
                break;
            }
            match nodes[index].id {
                live_id!(clear_color) => cx.passes[self.pass_id()].clear_color = LiveNew::new_apply_mut_index(cx, from, &mut index, nodes),
                live_id!(dont_clear) => cx.passes[self.pass_id()].dont_clear = LiveNew::new_apply_mut_index(cx, from, &mut index, nodes),
                _ => {
                    cx.apply_error_no_matching_field(live_error_origin!(), index, nodes);
                    index = nodes.skip_node(index);
                }
            }
        }
        return index;
    }
}

impl Pass {
    pub fn id_equals(&self, id:usize)->bool{
        self.0.id == id
    }
    
    pub fn new_with_name(cx: &mut Cx, name:&str) -> Self {
        let pass = cx.passes.alloc();
        pass.set_pass_name(cx, name);
        pass
    }
    
    pub fn pass_id(&self) -> PassId {PassId(self.0.id)}
    
    pub fn set_pass_parent(&self, cx: &mut Cx, pass: &Pass) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.parent = CxPassParent::Pass(pass.pass_id());
    }
    
    pub fn set_pass_name(&self, cx: &mut Cx, name: &str) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.debug_name = name.to_string();
    }
    
    pub fn pass_name<'a>(&self, cx: &'a mut Cx)->&'a str{
        let cxpass = &mut cx.passes[self.pass_id()];
        &cxpass.debug_name
    }
    
    pub fn set_size(&self, cx: &mut Cx, pass_size: DVec2) {
        let mut pass_size = pass_size;
        if pass_size.x < 1.0 {pass_size.x = 1.0};
        if pass_size.y < 1.0 {pass_size.y = 1.0};
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.pass_rect = Some(CxPassRect::Size(pass_size));
    }
    
    pub fn set_window_clear_color(&self, cx: &mut Cx, clear_color: Vec4) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.clear_color = clear_color;
    }
    
    pub fn clear_color_textures(&self, cx: &mut Cx) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.color_textures.truncate(0);
    }
    
    pub fn add_color_texture(&self, cx: &mut Cx, texture: &Texture, clear_color: PassClearColor) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.color_textures.push(CxPassColorTexture {
            texture_id: texture.texture_id(),
            clear_color: clear_color
        })
    }
    
    pub fn set_depth_texture(&self, cx: &mut Cx, texture: &Texture, clear_depth: PassClearDepth) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.depth_texture = Some(texture.texture_id());
        cxpass.clear_depth = clear_depth;
    }
    
    pub fn set_matrix_mode(&self, cx: &mut Cx, pmm: PassMatrixMode) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.paint_dirty = true;
        cxpass.matrix_mode = pmm;
    }
    
    pub fn set_debug(&mut self, cx: &mut Cx, debug: bool) {
        let cxpass = &mut cx.passes[self.pass_id()];
        cxpass.debug = debug;
    }
    
}

#[derive(Clone)]
pub enum PassClearColor {
    InitWith(Vec4),
    ClearWith(Vec4)
}

impl Default for PassClearColor {
    fn default() -> Self {
        Self::ClearWith(Vec4::default())
    }
}

#[derive(Clone)]
pub enum PassClearDepth {
    InitWith(f32),
    ClearWith(f32)
}

#[derive(Clone)]
pub struct CxPassColorTexture {
    pub clear_color: PassClearColor,
    pub texture_id: TextureId
}

#[derive(Default, Clone)]
#[repr(C)]
pub struct PassUniforms {
    camera_projection: Mat4,
    camera_view: Mat4,
    camera_inv: Mat4,
    dpi_factor: f32,
    dpi_dilate: f32,
    time: f32,
    pad2: f32
}

impl PassUniforms {
    pub fn as_slice(&self) -> &[f32; std::mem::size_of::<PassUniforms>() >> 2] {
        unsafe {std::mem::transmute(self)}
    }
}

#[derive(Clone, Debug)]
pub enum PassMatrixMode {
    Ortho,
    Projection {fov_y: f32, near: f32, far: f32, cam: Mat4}
}

#[derive(Clone)]
pub enum CxPassRect {
    Area(Area),
    ScaledArea(Area,f64),
    Size(DVec2)
}

#[derive(Clone)]
pub struct CxPass {
    pub debug: bool,
    pub debug_name: String,
    pub matrix_mode: PassMatrixMode,
    pub color_textures: Vec<CxPassColorTexture>,
    pub depth_texture: Option<TextureId>,
    pub clear_depth: PassClearDepth,
    pub dont_clear: bool,
    pub depth_init: f64,
    pub clear_color: Vec4,
    pub dpi_factor: Option<f64>,
    pub main_draw_list_id: Option<DrawListId>,
    pub parent: CxPassParent,
    pub paint_dirty: bool,
    pub pass_rect: Option<CxPassRect>,
    pub pass_uniforms: PassUniforms,
    pub zbias_step: f32,
    pub os: CxOsPass,
}

impl Default for CxPass {
    fn default() -> Self {
        CxPass {
            debug: false,
            dont_clear: false,
            debug_name: String::new(),
            matrix_mode: PassMatrixMode::Ortho,
            zbias_step: 0.001,
            pass_uniforms: PassUniforms::default(),
            color_textures: Vec::new(),
            depth_texture: None,
            dpi_factor: None,
            clear_depth: PassClearDepth::ClearWith(1.0),
            clear_color: Vec4::default(),
            depth_init: 1.0,
            main_draw_list_id: None,
            parent: CxPassParent::None,
            paint_dirty: false,
            pass_rect: None,
            os: CxOsPass::default()
        }
    }
}

#[derive(Clone, Debug)]
pub enum CxPassParent {
    Window(WindowId),
    Pass(PassId),
    None
}

impl CxPass {
    pub fn set_time(&mut self, time: f32) {
        self.pass_uniforms.time = time;
    }
    
    pub fn set_dpi_factor(&mut self, dpi_factor: f64) {
        let dpi_dilate = (2. - dpi_factor).max(0.).min(1.);
        self.pass_uniforms.dpi_factor = dpi_factor as f32;
        self.pass_uniforms.dpi_dilate = dpi_dilate as f32;
    }
    
    pub fn set_matrix(&mut self, offset: DVec2, size: DVec2) {
        match self.matrix_mode {
            PassMatrixMode::Ortho => {
                let ortho = Mat4::ortho(
                    offset.x as f32,
                    (offset.x + size.x) as f32,
                    offset.y as f32,
                    (offset.y + size.y) as f32,
                    100.,
                    -100.,
                    1.0,
                    1.0
                );
                self.pass_uniforms.camera_projection = ortho;
                self.pass_uniforms.camera_view = Mat4::identity();
            }
            PassMatrixMode::Projection {fov_y, near, far, cam} => {
                let proj = Mat4::perspective(fov_y, (size.x / size.y) as f32, near, far);
                self.pass_uniforms.camera_projection = proj;
                self.pass_uniforms.camera_view = cam;
            }
        };
    }
}