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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use std::collections::BTreeMap;
use std::iter;
use std::sync::Arc;

use crossbeam::sync::{Parker, Unparker};
use ordered_float::OrderedFloat;
use parking_lot::Mutex;
use vulkano::buffer::cpu_access::CpuAccessibleBuffer;
use vulkano::buffer::device_local::DeviceLocalBuffer;
use vulkano::buffer::BufferUsage;
use vulkano::command_buffer::{
    AutoCommandBufferBuilder, CommandBufferUsage, CopyBufferInfo, PrimaryCommandBuffer,
};
use vulkano::descriptor_set::SingleLayoutDescSetPool;
use vulkano::device::{Device, Queue};
use vulkano::format::Format;
use vulkano::pipeline::{ComputePipeline, Pipeline};
use vulkano::shader::ShaderModule;
use vulkano::sync::GpuFuture;

use crate::shaders::glyph_cs;
use crate::{ImtError, ImtGlyphBitmap, ImtParser, ImtShapedGlyph};

#[derive(Clone, Debug, PartialEq)]
pub enum ImtFillQuality {
    Fast,
    Normal,
    Best,
}

impl ImtFillQuality {
    pub fn ray_count(&self) -> usize {
        match self {
            Self::Fast => 3,
            Self::Normal => 5,
            Self::Best => 13,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ImtSampleQuality {
    Fastest,
    Faster,
    Fast,
    Normal,
    Best,
}

impl ImtSampleQuality {
    pub fn sample_count(&self) -> usize {
        match self {
            Self::Fastest => 1,
            Self::Faster => 4,
            Self::Fast => 9,
            Self::Normal => 16,
            Self::Best => 25,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImtRasterOpts {
    /// This effects how many rays are casted
    pub fill_quality: ImtFillQuality,
    /// This effects how many samples will be used per subpixel
    pub sample_quality: ImtSampleQuality,
    /// Whether to align bitmaps to whole pixels. This will adjust bearings to whole
    /// pixels and offset the resulting bitmap.
    pub align_whole_pixels: bool,
    /// This option will be ignored and set by _cpu or _gpu constructors
    pub cpu_rasterization: bool,
    /// Whether or to output a image instead of raw data. Only effects gpu rasterization
    pub raster_to_image: bool,
    /// Format used for the bitmap image.
    pub raster_image_format: Format,
}

impl ImtRasterOpts {
    pub fn sample_count(&self) -> usize {
        self.sample_quality.sample_count()
    }

    pub fn ray_count(&self) -> usize {
        self.fill_quality.ray_count()
    }
}

impl Default for ImtRasterOpts {
    fn default() -> Self {
        ImtRasterOpts {
            fill_quality: ImtFillQuality::Normal,
            sample_quality: ImtSampleQuality::Normal,
            align_whole_pixels: true,
            cpu_rasterization: false,
            raster_to_image: true,
            raster_image_format: Format::R8G8B8A8_UNORM,
        }
    }
}

pub struct ImtRasteredGlyph {
    pub shaped: ImtShapedGlyph,
    pub bitmap: Arc<ImtGlyphBitmap>,
}

#[derive(Clone)]
enum RasterCacheState {
    Completed(Arc<ImtGlyphBitmap>),
    Incomplete(Vec<Unparker>),
    Errored(ImtError),
}

#[allow(dead_code)]
pub struct ImtRaster {
    opts: ImtRasterOpts,
    cache: Mutex<BTreeMap<(OrderedFloat<f32>, u16), RasterCacheState>>,
    gpu_raster_context: Option<GpuRasterContext>,
    cpu_raster_context: Option<CpuRasterContext>,
}

#[allow(dead_code)]
pub(crate) struct GpuRasterContext {
    pub device: Arc<Device>,
    pub queue: Arc<Queue>,
    pub glyph_cs: Arc<ShaderModule>,
    pub common_buf: Arc<DeviceLocalBuffer<glyph_cs::ty::Common>>,
    pub pipeline: Arc<ComputePipeline>,
    pub set_pool: Mutex<SingleLayoutDescSetPool>,
    pub raster_to_image: bool,
    pub raster_image_format: Format,
}

pub(crate) struct CpuRasterContext {
    pub samples: Vec<[f32; 2]>,
    pub rays: Vec<[f32; 2]>,
}

impl ImtRaster {
    pub fn new_gpu(
        device: Arc<Device>,
        queue: Arc<Queue>,
        mut opts: ImtRasterOpts,
    ) -> Result<Self, ImtError> {
        opts.cpu_rasterization = false;
        let glyph_cs = glyph_cs::load(device.clone()).unwrap();
        let mut samples_and_rays = [[0.0; 4]; 25];
        let sample_count = opts.sample_count();

        let w = (sample_count as f32).sqrt() as usize;
        let mut sar_i = 0;

        for x in 1..=w {
            for y in 1..=w {
                samples_and_rays[sar_i][0] = ((x as f32 / (w as f32 + 1.0)) * 2.0) - 1.0;
                samples_and_rays[sar_i][1] = ((y as f32 / (w as f32 + 1.0)) * 2.0) - 1.0;
                sar_i += 1;
            }
        }

        let ray_count = opts.ray_count();

        for i in 0..ray_count {
            let rad = (i as f32 * (360.0 / ray_count as f32)).to_radians();
            samples_and_rays[i][2] = rad.cos();
            samples_and_rays[i][3] = rad.sin();
        }

        let common_cpu_buf = CpuAccessibleBuffer::from_data(
            device.clone(),
            BufferUsage {
                transfer_src: true,
                ..BufferUsage::empty()
            },
            false,
            glyph_cs::ty::Common {
                samples_and_rays,
                sample_count: sample_count as u32,
                ray_count: ray_count as u32,
            },
        )
        .unwrap();

        let common_dev_buf = DeviceLocalBuffer::new(
            device.clone(),
            BufferUsage {
                transfer_dst: true,
                uniform_buffer: true,
                ..BufferUsage::empty()
            },
            iter::once(queue.queue_family_index()),
        )
        .unwrap();

        let mut cmd_buf = AutoCommandBufferBuilder::primary(
            device.clone(),
            queue.queue_family_index(),
            CommandBufferUsage::OneTimeSubmit,
        )
        .unwrap();

        cmd_buf
            .copy_buffer(CopyBufferInfo::buffers(
                common_cpu_buf,
                common_dev_buf.clone(),
            ))
            .unwrap();

        cmd_buf
            .build()
            .unwrap()
            .execute(queue.clone())
            .unwrap()
            .then_signal_fence_and_flush()
            .unwrap()
            .wait(None)
            .unwrap();

        let pipeline = ComputePipeline::new(
            device.clone(),
            glyph_cs.entry_point("main").unwrap(),
            &(),
            None,
            |_| {},
        )
        .unwrap();

        let set_pool = SingleLayoutDescSetPool::new(pipeline.layout().set_layouts()[0].clone()).unwrap();
        let raster_to_image = opts.raster_to_image;
        let raster_image_format = opts.raster_image_format;

        Ok(ImtRaster {
            opts,
            cache: Mutex::new(BTreeMap::new()),
            gpu_raster_context: Some(GpuRasterContext {
                device,
                queue,
                glyph_cs,
                common_buf: common_dev_buf,
                pipeline,
                set_pool: Mutex::new(set_pool),
                raster_to_image,
                raster_image_format,
            }),
            cpu_raster_context: None,
        })
    }

    pub fn new_cpu(mut opts: ImtRasterOpts) -> Result<Self, ImtError> {
        opts.cpu_rasterization = true;
        let sample_count = opts.sample_count();
        let ray_count = opts.ray_count();
        let mut samples = Vec::with_capacity(sample_count);
        let mut rays = Vec::with_capacity(ray_count);
        let w = (sample_count as f32).sqrt() as usize;

        for x in 1..=w {
            for y in 1..=w {
                samples.push([
                    ((x as f32 / (w as f32 + 1.0)) * 2.0) - 1.0,
                    ((y as f32 / (w as f32 + 1.0)) * 2.0) - 1.0,
                ]);
            }
        }

        for i in 0..ray_count {
            let rad = (i as f32 * (360.0 / ray_count as f32)).to_radians();
            rays.push([rad.cos(), rad.sin()]);
        }

        Ok(ImtRaster {
            opts,
            cache: Mutex::new(BTreeMap::new()),
            gpu_raster_context: None,
            cpu_raster_context: Some(CpuRasterContext {
                samples,
                rays,
            }),
        })
    }

    pub fn sample_count(&self) -> usize {
        self.opts.sample_count()
    }

    pub fn ray_count(&self) -> usize {
        self.opts.ray_count()
    }

    #[allow(unused_assignments)]
    pub fn raster_shaped_glyphs(
        &self,
        parser: &ImtParser,
        text_height: f32,
        shaped_glyphs: Vec<ImtShapedGlyph>,
    ) -> Result<Vec<ImtRasteredGlyph>, ImtError> {
        let mut rastered_glyphs_out = Vec::new();
        let mut cache_lk_op = None;
        let height_key = OrderedFloat::from(text_height);

        'glyphs: for shaped in shaped_glyphs {
            let index = shaped.parsed.inner.glyph_index;

            // Acquire a lock to the cache if it isn't already present
            if cache_lk_op.is_none() {
                cache_lk_op = Some(self.cache.lock());
            }

            let mut parker_op = None;

            // Obtain the current cache state
            if let Some(cache_state) = cache_lk_op.as_mut().unwrap().get_mut(&(height_key, index)) {
                match cache_state {
                    // This glyph has already be completed!
                    &mut RasterCacheState::Completed(ref bitmap) => {
                        rastered_glyphs_out.push(ImtRasteredGlyph {
                            shaped,
                            bitmap: bitmap.clone(),
                        });

                        continue;
                    },
                    // This glyph is currently in the progress of be rasterized. Add this
                    // thread's unparker so we can wait for it to complete.
                    &mut RasterCacheState::Incomplete(ref mut unparkers) => {
                        let parker = Parker::new();
                        unparkers.push(parker.unparker().clone());
                        parker_op = Some(parker);
                    },
                    // The last attempted seem'd to have error, try again why not.
                    &mut RasterCacheState::Errored(_) => (),
                }
            }

            // Another thread is in the progress of rasterizing, so park.
            if let Some(parker) = parker_op {
                // Loop as the parker my spuriously wake up!
                loop {
                    // Drop the lock to not hold things up.
                    cache_lk_op = None;
                    parker.park();

                    // Reobtain the lock
                    cache_lk_op = Some(self.cache.lock());

                    // Should be safe to unwrap as the state should already be present given
                    // the previous logic.
                    let cache_state = cache_lk_op
                        .as_ref()
                        .unwrap()
                        .get(&(height_key, index))
                        .unwrap();

                    match cache_state {
                        // As expected the glyph is completed.
                        &RasterCacheState::Completed(ref bitmap) => {
                            rastered_glyphs_out.push(ImtRasteredGlyph {
                                shaped,
                                bitmap: bitmap.clone(),
                            });

                            continue 'glyphs;
                        },
                        // Seems this thread has spuriously woken up, go back to sleep.
                        &RasterCacheState::Incomplete(_) => continue,
                        // The last attempted seem'd to have error, try again why not.
                        &RasterCacheState::Errored(_) => break,
                    }
                }
            }

            // Made it here, so assume that the glyph needs to be rasterized yet.

            // The cache lock should still be held, but check.
            if cache_lk_op.is_none() {
                cache_lk_op = Some(self.cache.lock());
            }

            // Update the cache to inform it that this thread is going to rasterize the glyph.
            cache_lk_op.as_mut().unwrap().insert(
                (height_key, index),
                RasterCacheState::Incomplete(Vec::new()),
            );

            // Drop the lock so other threads can keep doing things.
            cache_lk_op = None;

            let mut bitmap =
                ImtGlyphBitmap::new(parser, shaped.parsed.clone(), text_height, &self.opts);
            bitmap.create_outline();

            let raster_result = if self.opts.cpu_rasterization {
                bitmap.raster_cpu(self.cpu_raster_context.as_ref().unwrap())
            } else {
                bitmap.raster_gpu(self.gpu_raster_context.as_ref().unwrap())
            };

            if let Err(e) = raster_result {
                // Seems we have errored, up the cache and inform other threads.
                // Reobtain the lock
                cache_lk_op = Some(self.cache.lock());

                // Update the state to errored and retrieve the old one.
                let old_state = cache_lk_op
                    .as_mut()
                    .unwrap()
                    .insert((height_key, index), RasterCacheState::Errored(e.clone()));

                // Inform all the other threads that may have been waiting.
                if let Some(RasterCacheState::Incomplete(unparkers)) = old_state {
                    for unparker in unparkers {
                        unparker.unpark();
                    }
                }

                // Finally return the error
                return Err(e);
            }

            // The glyph seems to have rastered sucessfully!

            // Wrap the bitmap into its final form.
            let bitmap = Arc::new(bitmap);

            // Reobtain the lock
            cache_lk_op = Some(self.cache.lock());

            // Update the state to completed and retrieve the old one.
            let old_state = cache_lk_op.as_mut().unwrap().insert(
                (height_key, index),
                RasterCacheState::Completed(bitmap.clone()),
            );

            // Inform all the other threads that may have been waiting.
            if let Some(RasterCacheState::Incomplete(unparkers)) = old_state {
                for unparker in unparkers {
                    unparker.unpark();
                }
            }

            rastered_glyphs_out.push(ImtRasteredGlyph {
                shaped,
                bitmap: bitmap.clone(),
            });
        }

        Ok(rastered_glyphs_out)
    }
}