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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::Error;
use crate::Viewport;
use crate::Viewports;

use euclid::Rect;
use euclid::Size2D;

use std::fmt::Debug;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub struct ContextId(pub u64);

#[cfg(feature = "ipc")]
use serde::{Deserialize, Serialize};

pub trait GLTypes {
    type Device;
    type Context;
    type Bindings;
}

pub trait GLContexts<GL: GLTypes> {
    fn bindings(&mut self, device: &GL::Device, context_id: ContextId) -> Option<&GL::Bindings>;
    fn context(&mut self, device: &GL::Device, context_id: ContextId) -> Option<&mut GL::Context>;
}

impl GLTypes for () {
    type Bindings = ();
    type Device = ();
    type Context = ();
}

impl GLContexts<()> for () {
    fn context(&mut self, _: &(), _: ContextId) -> Option<&mut ()> {
        Some(self)
    }

    fn bindings(&mut self, _: &(), _: ContextId) -> Option<&()> {
        Some(self)
    }
}

pub trait LayerGrandManagerAPI<GL: GLTypes> {
    fn create_layer_manager(&self, factory: LayerManagerFactory<GL>)
        -> Result<LayerManager, Error>;

    fn clone_layer_grand_manager(&self) -> LayerGrandManager<GL>;
}

pub struct LayerGrandManager<GL>(Box<dyn Send + LayerGrandManagerAPI<GL>>);

impl<GL: GLTypes> Clone for LayerGrandManager<GL> {
    fn clone(&self) -> Self {
        self.0.clone_layer_grand_manager()
    }
}

impl<GL> Debug for LayerGrandManager<GL> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        "LayerGrandManager(...)".fmt(fmt)
    }
}

impl<GL: GLTypes> LayerGrandManager<GL> {
    pub fn new<GM>(grand_manager: GM) -> LayerGrandManager<GL>
    where
        GM: 'static + Send + LayerGrandManagerAPI<GL>,
    {
        LayerGrandManager(Box::new(grand_manager))
    }

    pub fn create_layer_manager<F, M>(&self, factory: F) -> Result<LayerManager, Error>
    where
        F: 'static + Send + FnOnce(&mut GL::Device, &mut dyn GLContexts<GL>) -> Result<M, Error>,
        M: 'static + LayerManagerAPI<GL>,
    {
        self.0
            .create_layer_manager(LayerManagerFactory::new(factory))
    }
}

pub trait LayerManagerAPI<GL: GLTypes> {
    fn create_layer(
        &mut self,
        device: &mut GL::Device,
        contexts: &mut dyn GLContexts<GL>,
        context_id: ContextId,
        init: LayerInit,
    ) -> Result<LayerId, Error>;

    fn destroy_layer(
        &mut self,
        device: &mut GL::Device,
        contexts: &mut dyn GLContexts<GL>,
        context_id: ContextId,
        layer_id: LayerId,
    );

    fn layers(&self) -> &[(ContextId, LayerId)];

    fn begin_frame(
        &mut self,
        device: &mut GL::Device,
        contexts: &mut dyn GLContexts<GL>,
        layers: &[(ContextId, LayerId)],
    ) -> Result<Vec<SubImages>, Error>;

    fn end_frame(
        &mut self,
        device: &mut GL::Device,
        contexts: &mut dyn GLContexts<GL>,
        layers: &[(ContextId, LayerId)],
    ) -> Result<(), Error>;
}

pub struct LayerManager(Box<dyn Send + LayerManagerAPI<()>>);

impl Debug for LayerManager {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        "LayerManager(...)".fmt(fmt)
    }
}

impl LayerManager {
    pub fn create_layer(
        &mut self,
        context_id: ContextId,
        init: LayerInit,
    ) -> Result<LayerId, Error> {
        self.0.create_layer(&mut (), &mut (), context_id, init)
    }

    pub fn destroy_layer(&mut self, context_id: ContextId, layer_id: LayerId) {
        self.0.destroy_layer(&mut (), &mut (), context_id, layer_id);
    }

    pub fn begin_frame(
        &mut self,
        layers: &[(ContextId, LayerId)],
    ) -> Result<Vec<SubImages>, Error> {
        self.0.begin_frame(&mut (), &mut (), layers)
    }

    pub fn end_frame(&mut self, layers: &[(ContextId, LayerId)]) -> Result<(), Error> {
        self.0.end_frame(&mut (), &mut (), layers)
    }
}

impl LayerManager {
    pub fn new<M>(manager: M) -> LayerManager
    where
        M: 'static + Send + LayerManagerAPI<()>,
    {
        LayerManager(Box::new(manager))
    }
}

impl Drop for LayerManager {
    fn drop(&mut self) {
        log::debug!("Dropping LayerManager");
        for (context_id, layer_id) in self.0.layers().to_vec() {
            self.destroy_layer(context_id, layer_id);
        }
    }
}

pub struct LayerManagerFactory<GL: GLTypes>(
    Box<
        dyn Send
            + FnOnce(
                &mut GL::Device,
                &mut dyn GLContexts<GL>,
            ) -> Result<Box<dyn LayerManagerAPI<GL>>, Error>,
    >,
);

impl<GL: GLTypes> Debug for LayerManagerFactory<GL> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        "LayerManagerFactory(...)".fmt(fmt)
    }
}

impl<GL: GLTypes> LayerManagerFactory<GL> {
    pub fn new<F, M>(factory: F) -> LayerManagerFactory<GL>
    where
        F: 'static + Send + FnOnce(&mut GL::Device, &mut dyn GLContexts<GL>) -> Result<M, Error>,
        M: 'static + LayerManagerAPI<GL>,
    {
        LayerManagerFactory(Box::new(move |device, contexts| {
            Ok(Box::new(factory(device, contexts)?))
        }))
    }

    pub fn build(
        self,
        device: &mut GL::Device,
        contexts: &mut dyn GLContexts<GL>,
    ) -> Result<Box<dyn LayerManagerAPI<GL>>, Error> {
        (self.0)(device, contexts)
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub struct LayerId(usize);

static NEXT_LAYER_ID: AtomicUsize = AtomicUsize::new(0);

impl LayerId {
    pub fn new() -> LayerId {
        LayerId(NEXT_LAYER_ID.fetch_add(1, Ordering::SeqCst))
    }
}

#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub enum LayerInit {
    // https://www.w3.org/TR/webxr/#dictdef-xrwebgllayerinit
    WebGLLayer {
        antialias: bool,
        depth: bool,
        stencil: bool,
        alpha: bool,
        ignore_depth_values: bool,
        framebuffer_scale_factor: f32,
    },
    // https://immersive-web.github.io/layers/#xrprojectionlayerinittype
    ProjectionLayer {
        depth: bool,
        stencil: bool,
        alpha: bool,
        scale_factor: f32,
    },
    // TODO: other layer types
}

impl LayerInit {
    pub fn texture_size(&self, viewports: &Viewports) -> Size2D<i32, Viewport> {
        match self {
            LayerInit::WebGLLayer {
                framebuffer_scale_factor: scale,
                ..
            }
            | LayerInit::ProjectionLayer {
                scale_factor: scale,
                ..
            } => {
                let native_size = viewports
                    .viewports
                    .iter()
                    .fold(Rect::zero(), |acc, view| acc.union(view))
                    .size;
                (native_size.to_f32() * *scale).to_i32()
            }
        }
    }
}

/// https://immersive-web.github.io/layers/#enumdef-xrlayerlayout
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub enum LayerLayout {
    // TODO: Default
    // Allocates one texture
    Mono,
    // Allocates one texture, which is split in half vertically, giving two subimages
    StereoLeftRight,
    // Allocates one texture, which is split in half horizonally, giving two subimages
    StereoTopBottom,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub struct SubImages {
    pub layer_id: LayerId,
    pub sub_image: Option<SubImage>,
    pub view_sub_images: Vec<SubImage>,
}

/// https://immersive-web.github.io/layers/#xrsubimagetype
#[derive(Clone, Debug)]
#[cfg_attr(feature = "ipc", derive(Deserialize, Serialize))]
pub struct SubImage {
    pub color_texture: u32,
    pub depth_stencil_texture: Option<u32>,
    pub texture_array_index: Option<u32>,
    pub viewport: Rect<i32, Viewport>,
}