[go: up one dir, main page]

glam 0.30.1

A simple and fast 3D math library for games and graphics
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// Generated from {{template_path}} template. Edit the template, not the generated file.

{% if scalar_t == "bool" %}
    {% set self_t = "BVec" ~ dim %}
    {% set align = 1 %}
    {% set is_bool = true %}
{% else %}
    {% set self_t = "BVec" ~ dim ~ "A" %}
    {% if dim == 4 %}
        {% set vec_t = "Vec4" %}
    {% elif dim == 3 %}
        {% set vec_t = "Vec3A" %}
    {% endif %}
    {% set align = 16 %}
    {% set is_u32 = true %}
    {% if is_sse2 %}
        {% set simd_t = "__m128" %}
    {% elif is_wasm32 %}
        {% set simd_t = "v128" %}
    {% elif is_neon %}
        {% set simd_t = "uint32x4_t" %}
    {% elif is_coresimd %}
        {% set simd_t = "mask32x4" %}
    {% endif %}
{% endif %}

{% set components = ["x", "y", "z", "w"] | slice(end = dim) %}

use core::fmt;
use core::ops::*;

{% if is_sse2 %}
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
{% elif is_wasm32 %}
use core::arch::wasm32::*;
{% elif is_neon %}
use core::arch::aarch64::*;
{% elif is_coresimd %}
use core::simd::*;
{% endif %}

{% if is_sse2 or is_neon or is_coresimd %}
#[repr(C)]
union UnionCast {
    a: [u32; 4],
    v: {{ self_t }}
}
{% endif %}

/// Creates a {{ dim }}-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn {{ self_t | lower }}(
    {% for c in components %}
        {{ c }}: bool,
    {% endfor %}
) -> {{ self_t }} {
    {{ self_t }}::new({{ components | join(sep=",") }})
}

{% if is_scalar and is_bool %}
/// A {{ dim }}-dimensional `bool` vector mask.
{%- elif is_scalar and is_u32 %}
/// A {{ dim }}-dimensional `u32` vector mask.
{%- else %}
/// A {{ dim }}-dimensional SIMD vector mask.
///
/// This type is {{ align }} byte aligned.
{%- endif %}
{%- if is_scalar or is_bool %}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
{%- else %}
#[derive(Clone, Copy)]
{%- endif %}
{%- if is_scalar %}
#[repr(C, align({{ align }}))]
pub struct {{ self_t }}
{
{% for c in components %}
    pub {{ c }}: {{ scalar_t }},
{%- endfor %}
}
{%- else %}
#[repr(transparent)]
pub struct {{ self_t }}(pub(crate) {{ simd_t }});
{% endif %}

const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];

impl {{ self_t }} {
    /// All false.
    pub const FALSE: Self = Self::splat(false);

    /// All true.
    pub const TRUE: Self = Self::splat(true);

    /// Creates a new vector mask.
    #[inline(always)]
    #[must_use]
    pub const fn new(
        {% for c in components %}
            {{ c }}: bool,
        {% endfor %}
    ) -> Self {
        {% if is_scalar and is_bool %}
            Self {
                {% for c in components %}
                    {{ c }},
                {%- endfor %}
            }
        {% elif is_scalar and is_u32 %}
            Self {
                {% for c in components %}
                    {{ c }}: MASK[{{ c }} as usize],
                {%- endfor %}
            }
        {% elif is_sse2 or is_neon or is_coresimd %}
            unsafe {
                UnionCast { a: [
                    MASK[x as usize],
                    MASK[y as usize],
                    MASK[z as usize],
                    {% if dim == 3 %}
                        0,
                    {% elif dim == 4 %}
                        MASK[w as usize],
                    {% endif %}
                ] }.v
            }
        {% elif is_wasm32 %}
            Self(u32x4(
                MASK[x as usize],
                MASK[y as usize],
                MASK[z as usize],
                {% if dim == 3 %}
                    0,
                {% elif dim == 4 %}
                    MASK[w as usize],
                {% endif %}
            ))
        {% endif %}
    }

    /// Creates a vector mask with all elements set to `v`.
    #[inline]
    #[must_use]
    pub const fn splat(v: bool) -> Self {
        Self::new(
            {% for c in components %}
                v,
            {%- endfor %}
        )
    }

    /// Creates a new vector mask from a bool array.
    #[inline]
    #[must_use]
    pub const fn from_array(a: [bool; {{ dim }}]) -> Self {
        Self::new(
            {% for c in components %}
                a[{{ loop.index0 }}],
            {%- endfor %}
        )
    }

    /// Returns a bitmask with the lowest {{ dim }} bits set from the elements of `self`.
    ///
    /// A true element results in a `1` bit and a false element in a `0` bit.  Element `x` goes
    /// into the first lowest bit, element `y` into the second, etc.
    #[inline]
    #[must_use]
    pub fn bitmask(self) -> u32 {
        {% if is_scalar and is_bool %}
            {% for c in components %}
                {% if loop.first %}
                    (self.{{ c }} as u32) |
                {% else %}
                    ((self.{{ c }} as u32) << {{ loop.index0 }}) {% if not loop.last %} | {% endif %}
                {% endif %}
            {% endfor %}
        {% elif is_scalar and is_u32 %}
            {% for c in components %}
                {% if loop.first %}
                    (self.{{ c }} & 0x1) |
                {% else %}
                    ((self.{{ c }} & 0x1) << {{ loop.index0 }}) {% if not loop.last %} | {% endif %}
                {% endif %}
            {% endfor %}
        {% elif is_sse2 %}
            {% if dim == 3 %}
                unsafe { (_mm_movemask_ps(self.0) as u32) & 0x7 }
            {% elif dim == 4 %}
                unsafe { _mm_movemask_ps(self.0) as u32 }
            {% endif %}
        {% elif is_wasm32 %}
            {% if dim == 3 %}
                (u32x4_bitmask(self.0) & 0x7) as u32
            {% elif dim == 4 %}
                u32x4_bitmask(self.0) as u32
            {% endif %}
        {% elif is_neon %}
            {% if dim == 3 %}
                let movemask = unsafe {
            {% elif dim == 4 %}
                unsafe {
            {% endif %}
                let mma = vandq_u32(self.0, vld1q_u32([1, 2, 4, 8].as_ptr())); // [0 1 2 3]
                let mmb = vextq_u32(mma, mma, 2);                              // [2 3 0 1]
                let mmc = vorrq_u32(mma, mmb);                                 // [0+2 1+3 0+2 1+3]
                let mmd = vextq_u32(mmc, mmc, 3);                              // [1+3 0+2 1+3 0+2]
                let mme = vorrq_u32(mmc, mmd);                                 // [0+1+2+3 ...]
                vgetq_lane_u32(mme, 0)
            {% if dim == 3 %}
                };

                movemask & 0x7
            {% elif dim == 4 %}
                }
            {% endif %}
        {% elif is_coresimd %}
            {% if dim == 3 %}
                (self.0.to_bitmask() & 0x7) as u32
            {% elif dim == 4 %}
                self.0.to_bitmask() as u32
            {% endif %}
        {% else %}
            unimplemented!()
        {% endif %}
    }

    /// Returns true if any of the elements are true, false otherwise.
    #[inline]
    #[must_use]
    pub fn any(self) -> bool {
        {% if is_scalar and is_bool %}
            {% for c in components %}
                self.{{ c }} {% if not loop.last %} || {% endif %}
            {%- endfor %}
        {% elif is_scalar and is_u32 %}
            ((
                {% for c in components %}
                    self.{{ c }} {% if not loop.last %} | {% endif %}
                {%- endfor %}
            ) & 0x1) != 0
        {% else %}
            self.bitmask() != 0
        {% endif %}
    }

    /// Returns true if all the elements are true, false otherwise.
    #[inline]
    #[must_use]
    pub fn all(self) -> bool {
        {% if is_scalar and is_bool %}
            {% for c in components %}
                self.{{ c }} {% if not loop.last %} && {% endif %}
            {%- endfor %}
        {% elif is_scalar and is_u32 %}
            ((
                {% for c in components %}
                    self.{{ c }} {% if not loop.last %} & {% endif %}
                {%- endfor %}
            ) & 0x1) != 0
        {% else %}
            {% if dim == 3 %}
                self.bitmask() == 0x7
            {% elif dim == 4 %}
                self.bitmask() == 0xf
            {% endif %}
        {% endif %}
    }

    /// Tests the value at `index`.
    ///
    /// Panics if `index` is greater than {{ dim  - 1 }}.
    #[inline]
    #[must_use]
    pub fn test(&self, index: usize) -> bool {
        {% if is_coresimd %}
            self.0.test(index)
        {% else %}
            match index {
                {% for c in components %}
                    {%- if is_scalar and is_bool %}
                        {{ loop.index0 }} => self.{{ c }},
                    {%- elif is_scalar and is_u32 %}
                        {{ loop.index0 }} => (self.{{ c }} & 0x1) != 0,
                    {%- else %}
                        {{ loop.index0 }} => (self.bitmask() & (1 << {{ loop.index0 }})) != 0,
                    {%- endif %}
                {%- endfor %}
                _ => panic!("index out of bounds")
            }
        {% endif %}
    }

    /// Sets the element at `index`.
    ///
    /// Panics if `index` is greater than {{ dim  - 1 }}.
    #[inline]
    pub fn set(&mut self, index: usize, value: bool) {
        {% if is_scalar %}
            match index {
                {% for c in components %}
                    {%- if is_bool %}
                        {{ loop.index0 }} => self.{{ c }} = value,
                    {%- elif is_u32 %}
                        {{ loop.index0 }} => self.{{ c }} = MASK[value as usize],
                    {%- endif %}
                {%- endfor %}
                _ => panic!("index out of bounds")
            }
        {% elif is_coresimd %}
            self.0.set(index, value)
        {% elif is_neon %}
            self.0 = match index { 
                {% for c in components %}
                    {{ loop.index0 }} => unsafe {
                        vsetq_lane_u32(MASK[value as usize], self.0, {{ loop.index0 }})
                    },
                {%- endfor %}
                _ => panic!("index out of bounds")
            }
        {% else %}
            use crate::{{ vec_t }};
            let mut v = {{ vec_t }}(self.0);
            v[index] = f32::from_bits(MASK[value as usize]);
            self.0 = v.0;
        {% endif %}
    }

    #[inline]
    #[must_use]
    fn into_bool_array(self) -> [bool; {{ dim }}] {
        {% if is_scalar and is_bool %}
            [
                {% for c in components %}
                    self.{{ c }},
                {%- endfor %}
            ]
        {% elif is_scalar and is_u32 %}
            [
                {% for c in components %}
                    (self.{{ c }} & 0x1) != 0,
                {%- endfor %}
            ]
        {% else %}
            {% set bits = [1, 2, 4, 8] | slice(end = dim) %}
            let bitmask = self.bitmask();
            [
                {% for b in bits %}
                    (bitmask & {{ b }}) != 0,
                {%- endfor %}
            ]
        {% endif %}
    }

    #[inline]
    #[must_use]
    fn into_u32_array(self) -> [u32; {{ dim }}] {
        {% if is_scalar and is_bool %}
            [
                {% for c in components %}
                    MASK[self.{{ c }} as usize],
                {%- endfor %}
            ]
        {% elif is_scalar and is_u32 %}
            [
                {% for c in components %}
                    self.{{ c }},
                {%- endfor %}
            ]
        {% else %}
            let bitmask = self.bitmask();
            [
                {% for c in components %}
                    {% if loop.first %}
                        MASK[(bitmask & 1) as usize],
                    {% else %}
                        MASK[((bitmask >> {{ loop.index0 }}) & 1) as usize],
                    {% endif %}
                {%- endfor %}
            ]
        {% endif %}
    }
}


impl Default for {{ self_t }} {
    #[inline]
    fn default() -> Self {
        Self::FALSE
    }
}

{% if not is_scalar and not is_bool %}
impl PartialEq for {{ self_t }} {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.bitmask().eq(&rhs.bitmask())
    }
}

impl Eq for {{ self_t }} {}

impl core::hash::Hash for {{ self_t }} {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.bitmask().hash(state);
    }
}
{%- endif %}

impl BitAnd for {{ self_t }} {
    type Output = Self;
    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        {% if is_scalar %}
            Self {
                {% for c in components %}
                    {{ c }}: self.{{ c }} & rhs.{{ c }},
                {%- endfor %}
            }
        {% elif is_sse2 %}
            Self(unsafe { _mm_and_ps(self.0, rhs.0) })
        {% elif is_wasm32 %}
            Self(v128_and(self.0, rhs.0))
        {% elif is_neon %}
            Self(unsafe { vandq_u32(self.0, rhs.0) })
        {% elif is_coresimd %}
            Self(self.0 & rhs.0)
        {% else %}
            unimplemented!()
        {% endif %}
    }
}

impl BitAndAssign for {{ self_t }} {
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        *self = self.bitand(rhs);
    }
}

impl BitOr for {{ self_t }} {
    type Output = Self;
    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        {% if is_scalar %}
            Self {
                {% for c in components %}
                    {{ c }}: self.{{ c }} | rhs.{{ c }},
                {%- endfor %}
            }
        {% elif is_sse2 %}
            Self(unsafe { _mm_or_ps(self.0, rhs.0) })
        {% elif is_wasm32 %}
            Self(v128_or(self.0, rhs.0))
        {% elif is_neon %}
            Self(unsafe { vorrq_u32(self.0, rhs.0) })
        {% elif is_coresimd %}
            Self(self.0 | rhs.0)
        {% else %}
            unimplemented!()
        {% endif %}
    }
}

impl BitOrAssign for {{ self_t }} {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        *self = self.bitor(rhs);
    }
}

impl BitXor for {{ self_t }} {
    type Output = Self;
    #[inline]
    fn bitxor(self, rhs: Self) -> Self {
        {% if is_scalar %}
            Self {
                {% for c in components %}
                    {{ c }}: self.{{ c }} ^ rhs.{{ c }},
                {%- endfor %}
            }
        {% elif is_sse2 %}
            Self(unsafe { _mm_xor_ps(self.0, rhs.0) })
        {% elif is_wasm32 %}
            Self(v128_xor(self.0, rhs.0))
        {% elif is_neon %}
            Self(unsafe { veorq_u32(self.0, rhs.0) })
        {% elif is_coresimd %}
            Self(self.0 ^ rhs.0)
        {% else %}
            unimplemented!()
        {% endif %}
    }
}

impl BitXorAssign for {{ self_t }} {
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        *self = self.bitxor(rhs);
    }
}

impl Not for {{ self_t }} {
    type Output = Self;
    #[inline]
    fn not(self) -> Self {
        {% if is_scalar %}
            Self {
                {% for c in components %}
                    {{ c }}: !self.{{ c }},
                {%- endfor %}
            }
        {% elif is_sse2 %}
            Self(unsafe {
                _mm_andnot_ps(self.0, _mm_set_ps1(f32::from_bits(0xff_ff_ff_ff)))
            })
        {% elif is_wasm32 %}
            Self(v128_not(self.0))
        {% elif is_neon %}
            Self(unsafe { vmvnq_u32(self.0) })
        {% elif is_coresimd %}
            Self(!self.0)
        {% else %}
            unimplemented!()
        {% endif %}
    }
}

{% if not is_scalar %}
impl From<{{ self_t }}> for {{ simd_t }} {
    #[inline]
    fn from(t: {{ self_t }}) -> Self {
        t.0
    }
}
{% endif %}

impl fmt::Debug for {{ self_t }} {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let arr = self.into_u32_array();
{%- if dim == 2 %}
        write!(f, "{}({:#x}, {:#x})", stringify!({{ self_t }}), arr[0], arr[1])
{% elif dim == 3 %}
        write!(f, "{}({:#x}, {:#x}, {:#x})", stringify!({{ self_t }}), arr[0], arr[1], arr[2])
{% elif dim == 4 %}
        write!(f, "{}({:#x}, {:#x}, {:#x}, {:#x})", stringify!({{ self_t }}), arr[0], arr[1], arr[2], arr[3])
{% endif %}
    }
}

impl fmt::Display for {{ self_t }} {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let arr = self.into_bool_array();
{%- if dim == 2 %}
        write!(f, "[{}, {}]", arr[0], arr[1])
{% elif dim == 3 %}
        write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
{% elif dim == 4 %}
        write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
{% endif %}
    }
}

impl From<[bool; {{ dim }}]> for {{ self_t }} {
    #[inline]
    fn from(a: [bool; {{ dim }}]) -> Self {
        Self::from_array(a)
    }
}

impl From<{{ self_t }}> for [bool; {{ dim }}] {
    #[inline]
    fn from(mask: {{ self_t }}) -> Self {
        mask.into_bool_array()
    }
}

impl From<{{ self_t }}> for [u32; {{ dim }}] {
    #[inline]
    fn from(mask: {{ self_t }}) -> Self {
        mask.into_u32_array()
    }
}