|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | +import tgpu, { d } from '../src/index.ts'; |
| 3 | + |
| 4 | +describe('Math', () => { |
| 5 | + it('allows using Math.PI', () => { |
| 6 | + const myFn = () => { |
| 7 | + 'use gpu'; |
| 8 | + const a = Math.PI; |
| 9 | + }; |
| 10 | + |
| 11 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 12 | + "fn myFn() { |
| 13 | + const a = 3.141592653589793; |
| 14 | + }" |
| 15 | + `); |
| 16 | + }); |
| 17 | + |
| 18 | + it('allows using Math.sin', () => { |
| 19 | + const myFn = () => { |
| 20 | + 'use gpu'; |
| 21 | + const a = 0.5; |
| 22 | + const b = Math.sin(a); |
| 23 | + }; |
| 24 | + |
| 25 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 26 | + "fn myFn() { |
| 27 | + const a = 0.5; |
| 28 | + let b = sin(a); |
| 29 | + }" |
| 30 | + `); |
| 31 | + }); |
| 32 | + |
| 33 | + it('precomputes Math.sin when applicable', () => { |
| 34 | + const myFn = () => { |
| 35 | + 'use gpu'; |
| 36 | + const a = Math.sin(0.5); |
| 37 | + }; |
| 38 | + |
| 39 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 40 | + "fn myFn() { |
| 41 | + const a = 0.479425538604203; |
| 42 | + }" |
| 43 | + `); |
| 44 | + }); |
| 45 | + |
| 46 | + it('coerces Math.sin arguments', () => { |
| 47 | + const myFn = () => { |
| 48 | + 'use gpu'; |
| 49 | + const a = d.u32(); |
| 50 | + const b = Math.sin(a); |
| 51 | + }; |
| 52 | + |
| 53 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 54 | + "fn myFn() { |
| 55 | + const a = 0u; |
| 56 | + let b = sin(f32(a)); |
| 57 | + }" |
| 58 | + `); |
| 59 | + }); |
| 60 | + |
| 61 | + it('allows Math.min to accept multiple arguments', () => { |
| 62 | + const myFn = () => { |
| 63 | + 'use gpu'; |
| 64 | + const a = d.u32(); |
| 65 | + const b = Math.min(a, 1, 2, 3); |
| 66 | + }; |
| 67 | + |
| 68 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 69 | + "fn myFn() { |
| 70 | + const a = 0u; |
| 71 | + let b = min(min(min(a, 1u), 2u), 3u); |
| 72 | + }" |
| 73 | + `); |
| 74 | + }); |
| 75 | + |
| 76 | + it('throws a readable error when unsupported Math feature is used', () => { |
| 77 | + const myFn = () => { |
| 78 | + 'use gpu'; |
| 79 | + const a = Math.log1p(1); |
| 80 | + }; |
| 81 | + |
| 82 | + expect(() => tgpu.resolve([myFn])).toThrowErrorMatchingInlineSnapshot(` |
| 83 | + [Error: Resolution of the following tree failed: |
| 84 | + - <root> |
| 85 | + - fn*:myFn |
| 86 | + - fn*:myFn(): Unsupported functionality 'Math.log1p'. Use an std alternative, or implement the function manually.] |
| 87 | + `); |
| 88 | + }); |
| 89 | + |
| 90 | + it('correctly applies Math.fround', () => { |
| 91 | + const myFn = () => { |
| 92 | + 'use gpu'; |
| 93 | + const a = Math.fround(16777217); |
| 94 | + }; |
| 95 | + |
| 96 | + expect(tgpu.resolve([myFn])).toMatchInlineSnapshot(` |
| 97 | + "fn myFn() { |
| 98 | + const a = 16777216f; |
| 99 | + }" |
| 100 | + `); |
| 101 | + }); |
| 102 | +}); |
0 commit comments