glre 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/node/scope.ts CHANGED
@@ -4,10 +4,10 @@ import type { NodeProxy, X } from './types'
4
4
 
5
5
  let _scope: NodeProxy | null = null
6
6
 
7
- const scoped = (x: NodeProxy | null, callback = () => {}) => {
7
+ const scoped = (x: NodeProxy | null, fun = () => {}) => {
8
8
  const prev = _scope
9
9
  _scope = x
10
- callback()
10
+ fun()
11
11
  _scope = prev
12
12
  }
13
13
 
@@ -17,52 +17,86 @@ const addToScope = (x: NodeProxy) => {
17
17
  _scope.props.children.push(x)
18
18
  }
19
19
 
20
- export const If = (x: X, callback: () => void) => {
21
- const y = node('scope')
22
- scoped(y, callback)
23
- const ifNode = node('if', null, x, y)
20
+ export const toVar = (x: X, id?: string) => {
21
+ if (!id) id = getId()
22
+ const y = node('variable', { id })
23
+ const z = node('declare', null, y, x)
24
+ addToScope(z)
25
+ return y
26
+ }
27
+
28
+ export const assign = (x: X, y: X) => {
29
+ const z = node('assign', null, x, y)
30
+ addToScope(z)
31
+ return x
32
+ }
33
+
34
+ export const If = (condition: X, fun: () => void) => {
35
+ const scope = node('scope')
36
+ scoped(scope, fun)
37
+ const ifNode = node('if', null, condition, scope)
24
38
  addToScope(ifNode)
25
- return {
26
- ElseIf: (y: X, elseCallback: () => void) => {
27
- const z = node('scope')
28
- scoped(z, elseCallback)
29
- ifNode.props.children!.push(y, z)
39
+ const createChain = () => ({
40
+ ElseIf: (x: X, _fun: () => void) => {
41
+ const y = node('scope')
42
+ scoped(y, _fun)
43
+ ifNode.props.children!.push(x, y)
44
+ return createChain()
30
45
  },
31
- Else: (elseCallback: () => void) => {
32
- const z = node('scope')
33
- scoped(z, elseCallback)
34
- ifNode.props.children!.push(z)
46
+ Else: (_fun: () => void) => {
47
+ const x = node('scope')
48
+ scoped(x, _fun)
49
+ ifNode.props.children!.push(x)
35
50
  },
36
- }
51
+ })
52
+ return createChain()
37
53
  }
38
54
 
39
- export const Loop = (x: X, callback?: (params: { i: NodeProxy }) => void) => {
55
+ export const Loop = (x: X, fun: (params: { i?: NodeProxy }) => void) => {
40
56
  const y = node('scope')
41
- scoped(y, () => callback?.({ i: node('variable', { id: 'i' }) }))
57
+ scoped(y, () => fun({ i: node('variable', { id: 'i' }) }))
42
58
  const ret = node('loop', null, x, y)
43
59
  addToScope(ret)
44
60
  return ret
45
61
  }
46
62
 
47
- export const Fn = (callback: (args: X[]) => NodeProxy) => {
48
- return (...args: X[]) => {
49
- let result
50
- const fnScope = node('scope')
51
- scoped(fnScope, () => (result = callback(args)))
52
- return node('fn', null, fnScope, result)
53
- }
54
- }
63
+ export const Switch = (value: X) => {
64
+ const switchNode = node('switch', null, value)
65
+ addToScope(switchNode)
66
+ const createChain = () => ({
67
+ Case: (...values: X[]) => {
68
+ return (fun: () => void) => {
69
+ const scope = node('scope')
70
+ scoped(scope, fun)
71
+ // 複数のcase値を処理
72
+ for (const val of values) {
73
+ switchNode.props.children!.push(val, scope)
74
+ }
75
+ return createChain()
76
+ }
77
+ },
78
+ Default: (fun: () => void) => {
79
+ const scope = node('scope')
80
+ scoped(scope, fun)
81
+ switchNode.props.children!.push(scope)
82
+ },
83
+ })
55
84
 
56
- export const toVar = (x: X) => (id: string) => {
57
- if (!id) id = getId()
58
- const y = node('variable', { id })
59
- const z = node('declare', null, y, x)
60
- addToScope(z)
61
- return y
85
+ return createChain()
62
86
  }
63
87
 
64
- export const assign = (x: X) => (y: X) => {
65
- const assignNode = node('assign', null, x, y)
66
- addToScope(assignNode)
67
- return x
88
+ export const Fn = (fun: (paramVars: NodeProxy[]) => NodeProxy) => {
89
+ const id = getId()
90
+ return (...args: X[]) => {
91
+ const x = node('scope')
92
+ let y: NodeProxy | undefined
93
+ const paramVars: NodeProxy[] = []
94
+ for (let i = 0; i < args.length; i++) {
95
+ const paramId = `p${i}`
96
+ const paramVar = node('variable', { id: paramId })
97
+ paramVars.push(paramVar)
98
+ }
99
+ scoped(x, () => (y = fun(paramVars)))
100
+ return node('define', { id }, x, y, ...args)
101
+ }
68
102
  }
package/src/node/types.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { FUNCTIONS, NODE_TYPES, OPERATOR_KEYS } from './const'
1
+ import { CONSTANTS, CONVERSIONS, FUNCTIONS, OPERATOR_KEYS } from './const'
2
2
 
3
- export type NodeType = (typeof NODE_TYPES)[number]
3
+ export type Constants = (typeof CONSTANTS)[number] | 'void'
4
+
5
+ export type Conversions = (typeof CONVERSIONS)[number]
4
6
 
5
7
  export type Functions = (typeof FUNCTIONS)[number]
6
8
 
@@ -8,14 +10,18 @@ export type Operators = (typeof OPERATOR_KEYS)[number]
8
10
 
9
11
  export interface NodeProps {
10
12
  id?: string
13
+ args?: X[]
14
+ type?: string
11
15
  children?: X[]
12
- defaultValue?: number | number[]
16
+ value?: number | number[] | boolean
13
17
  }
14
18
 
15
19
  export interface NodeConfig {
16
20
  isWebGL?: boolean
17
- uniforms?: Set<string>
18
- onUniform?: (name: string, value: any) => void
21
+ binding?: number
22
+ infers?: WeakMap<NodeProxy, Constants>
23
+ headers?: Map<string, string>
24
+ onMount?: (name: string, value: any) => void
19
25
  }
20
26
 
21
27
  type _Swizzles<T extends string> = T | `${T}${T}` | `${T}${T}${T}` | `${T}${T}${T}${T}`
@@ -31,16 +37,23 @@ export type NodeTypes =
31
37
  | 'variable'
32
38
  | 'swizzle'
33
39
  | 'operator'
34
- | 'node_type'
35
- | 'math_fun'
40
+ | 'conversion'
41
+ | 'function'
36
42
  | 'declare'
37
43
  | 'assign'
38
- | 'fn'
44
+ | 'define'
39
45
  | 'if'
40
46
  | 'loop'
41
47
  | 'scope'
48
+ | 'switch'
49
+ | 'ternary'
50
+ | 'attribute'
51
+ | 'varying'
52
+ | 'builtin'
53
+ | 'constant'
42
54
 
43
- export interface NodeProxy extends Record<Swizzles, NodeProxy> {
55
+ export interface NodeProxy extends Record<Swizzles | Conversions, NodeProxy> {
56
+ // Operators
44
57
  add(n: X): NodeProxy
45
58
  sub(n: X): NodeProxy
46
59
  mul(n: X): NodeProxy
@@ -55,12 +68,63 @@ export interface NodeProxy extends Record<Swizzles, NodeProxy> {
55
68
  and(n: X): NodeProxy
56
69
  or(n: X): NodeProxy
57
70
  not(): NodeProxy
71
+
72
+ // Variable manipulation
58
73
  assign(n: X): NodeProxy
59
74
  toVar(name?: string): NodeProxy
75
+ toConst(name?: string): NodeProxy
76
+
77
+ // Math function methods
78
+ abs(): NodeProxy
79
+ sin(): NodeProxy
80
+ cos(): NodeProxy
81
+ tan(): NodeProxy
82
+ asin(): NodeProxy
83
+ acos(): NodeProxy
84
+ atan(): NodeProxy
85
+ atan2(x: X): NodeProxy
86
+ pow(y: X): NodeProxy
87
+ pow2(): NodeProxy
88
+ pow3(): NodeProxy
89
+ pow4(): NodeProxy
90
+ sqrt(): NodeProxy
91
+ inverseSqrt(): NodeProxy
92
+ exp(): NodeProxy
93
+ exp2(): NodeProxy
94
+ log(): NodeProxy
95
+ log2(): NodeProxy
96
+ floor(): NodeProxy
97
+ ceil(): NodeProxy
98
+ round(): NodeProxy
99
+ fract(): NodeProxy
100
+ trunc(): NodeProxy
101
+ min(y: X): NodeProxy
102
+ max(y: X): NodeProxy
103
+ clamp(min: X, max: X): NodeProxy
104
+ saturate(): NodeProxy
105
+ mix(y: X, a: X): NodeProxy
106
+ step(edge: X): NodeProxy
107
+ smoothstep(edge0: X, edge1: X): NodeProxy
108
+ length(): NodeProxy
109
+ distance(y: X): NodeProxy
110
+ dot(y: X): NodeProxy
111
+ cross(y: X): NodeProxy
112
+ normalize(): NodeProxy
113
+ reflect(N: X): NodeProxy
114
+ refract(N: X, eta: X): NodeProxy
115
+ sign(): NodeProxy
116
+ oneMinus(): NodeProxy
117
+ reciprocal(): NodeProxy
118
+ negate(): NodeProxy
119
+ dFdx(): NodeProxy
120
+ dFdy(): NodeProxy
121
+ fwidth(): NodeProxy
122
+
123
+ // System properties
60
124
  toString(c?: NodeConfig): string
61
125
  type: NodeTypes
62
126
  props: NodeProps
63
127
  isProxy: true
64
128
  }
65
129
 
66
- export type X = NodeProxy | number | string | null | undefined
130
+ export type X = NodeProxy | number | string | boolean | undefined
package/src/node/utils.ts CHANGED
@@ -1,7 +1,9 @@
1
+ import { NodeProps } from './../../../../node_modules/glre/src/node/types'
1
2
  import { is } from '../utils/helpers'
2
3
  import { code } from './code'
3
- import { FUNCTIONS, NODE_TYPES, OPERATOR_KEYS } from './const'
4
- import type { Functions, NodeConfig, NodeType, Operators, Swizzles, X } from './types'
4
+ import { CONVERSIONS, FUNCTIONS, OPERATOR_KEYS, OPERATORS, TYPE_MAPPING } from './const'
5
+ import type { Conversions, Functions, NodeConfig, NodeProxy, Operators, Swizzles, X } from './types'
6
+ import { infer } from './infer'
5
7
 
6
8
  export const isSwizzle = (key: unknown): key is Swizzles => {
7
9
  return is.str(key) && /^[xyzwrgbastpq]{1,4}$/.test(key)
@@ -11,16 +13,29 @@ export const isOperator = (key: unknown): key is Operators => {
11
13
  return OPERATOR_KEYS.includes(key as Operators)
12
14
  }
13
15
 
14
- export const isNodeType = (key: unknown): key is NodeType => {
15
- return NODE_TYPES.includes(key as NodeType)
16
- }
17
-
18
16
  export const isFunction = (key: unknown): key is Functions => {
19
17
  return FUNCTIONS.includes(key as Functions)
20
18
  }
21
19
 
20
+ export const isConversion = (key: unknown): key is Conversions => {
21
+ return CONVERSIONS.includes(key as Conversions)
22
+ }
23
+
24
+ export const isNodeProxy = (x: unknown): x is NodeProxy => {
25
+ if (!x) return false
26
+ if (typeof x !== 'object') return false // @ts-ignore
27
+ return x.isProxy
28
+ }
29
+
22
30
  let count = 0
23
31
 
32
+ export const hex2rgb = (hex: number) => {
33
+ const r = ((hex >> 16) & 0xff) / 255
34
+ const g = ((hex >> 8) & 0xff) / 255
35
+ const b = (hex & 0xff) / 255
36
+ return [r, g, b]
37
+ }
38
+
24
39
  export const getId = () => `i${count++}`
25
40
 
26
41
  export const joins = (children: X[], c: NodeConfig) => {
@@ -30,73 +45,66 @@ export const joins = (children: X[], c: NodeConfig) => {
30
45
  .join(', ')
31
46
  }
32
47
 
33
- export const inferType = (target: X, c: NodeConfig): string => {
34
- if (!target || typeof target !== 'object') return 'float'
35
- const { type, props } = target
36
- const { children = [] } = props
37
- const [x, y, z] = children
38
- if (type === 'node_type') return x as string
39
- if (type === 'operator') {
40
- const left = inferType(y, c)
41
- const right = inferType(z, c)
42
- if (left === right) return left
43
- if (left.includes('vec')) return left
44
- if (right.includes('vec')) return right
45
- return 'float'
46
- }
47
- if (type === 'math_fun') {
48
- if (['normalize', 'cross', 'reflect'].includes(x as string)) return inferType(children[1], c)
49
- if (['dot', 'distance', 'length'].includes(x as string)) return 'float'
50
- return 'float'
51
- }
52
- return 'float'
48
+ export const formatConversions = (x: X, c?: NodeConfig) => {
49
+ if (!is.str(x)) return ''
50
+ if (c?.isWebGL) return x
51
+ return TYPE_MAPPING[x as keyof typeof TYPE_MAPPING]
52
+ }
53
+
54
+ export const getOperator = (op: X) => {
55
+ return OPERATORS[op as keyof typeof OPERATORS] || op
53
56
  }
54
57
 
55
- const generateUniforms = (c: NodeConfig): string => {
56
- if (!c.uniforms || c.uniforms.size === 0) return ''
57
- const uniformList = Array.from(c.uniforms)
58
- return (
59
- uniformList
60
- .map((name, i) => {
61
- if (c.isWebGL) return `uniform vec2 ${name};`
62
- else return `@group(0) @binding(${i}) var<uniform> ${name}: vec2f;`
63
- })
64
- .join('\n') + '\n'
65
- )
58
+ const generateHead = (c: NodeConfig) => {
59
+ return Array.from(c.headers!)
60
+ .map(([, v]) => v)
61
+ .join('\n')
62
+ }
63
+
64
+ export const generateDefine = (props: NodeProps, c: NodeConfig) => {
65
+ const { id, children = [] } = props
66
+ const [x, y, ...args] = children
67
+ const returnType = y ? infer(y, c) : 'void'
68
+ const params = args.map((arg, i) => [`p${i}`, infer(arg, c)])
69
+ const lines = [code(x, c)]
70
+ if (y) lines.push(`return ${code(y, c)};`)
71
+ if (c?.isWebGL) {
72
+ const paramList = params.map(([name, type]) => `${type} ${name}`)
73
+ return `${returnType} ${id}(${paramList}) {\n${lines.join('\n')}\n}`
74
+ }
75
+ const wgslReturnType = formatConversions(returnType, c)
76
+ const wgslParams = params.map(([name, type]) => `${name}: ${formatConversions(type, c)}`)
77
+ return `fn ${id}(${wgslParams}) -> ${wgslReturnType} {\n${lines.join('\n')}\n}`
66
78
  }
67
79
 
68
- const generateFragmentMain = (body: string, uniforms: string, isWebGL = true) => {
80
+ const generateFragmentMain = (body: string, head: string, isWebGL = true) => {
69
81
  if (isWebGL)
70
82
  return `
71
- ${uniforms}
72
83
  #version 300 es
73
84
  precision mediump float;
74
- uniform vec2 iResolution;
75
- uniform vec2 iMouse;
76
- uniform float iTime;
77
85
  out vec4 fragColor;
86
+ ${head}
78
87
  void main() {
79
- ${body}
88
+ fragColor = ${body};
80
89
  }`.trim()
81
90
  return `
82
- @group(0) @binding(0) var<uniform> iResolution: vec2f;
83
- @group(0) @binding(1) var<uniform> iMouse: vec2f;
84
- @group(0) @binding(2) var<uniform> iTime: f32;
85
- ${uniforms}
91
+ ${head}
86
92
  @fragment
87
93
  fn main(@builtin(position) position: vec4f) -> @location(0) vec4f {
88
- ${body}
94
+ return ${body};
89
95
  }`.trim()
90
96
  }
91
97
 
92
- export const fragment = (x: X, c: NodeConfig) => {
98
+ export const fragment = (x: X, c: NodeConfig = {}) => {
93
99
  const body = code(x, c)
94
- const uniforms = generateUniforms(c)
95
- return generateFragmentMain(body, uniforms, c.isWebGL)
100
+ const head = generateHead(c)
101
+ const main = generateFragmentMain(body, head, c.isWebGL)
102
+ console.log(`// ↓↓↓ generated ↓↓↓\n\n${main}\n\n`)
103
+ return main
96
104
  }
97
105
 
98
106
  export const vertex = (x: X, c: NodeConfig) => {
99
107
  const body = code(x, c)
100
- const uniforms = generateUniforms(c)
101
- return generateFragmentMain(body, uniforms, c.isWebGL)
108
+ const head = generateHead(c)
109
+ return generateFragmentMain(body, head, c.isWebGL)
102
110
  }
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EventState } from 'reev'
2
2
  import type { Fun, Queue, Frame } from 'refr'
3
- import type { X } from './node'
3
+ import type { NodeProxy } from './node'
4
4
  export type { Fun, Queue, Frame }
5
5
  export type GPUContext = any // GPUCanvasContext https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext
6
6
  export type GPUDevice = any //
@@ -52,12 +52,12 @@ export type GL = EventState<{
52
52
  mouse: [number, number]
53
53
  count: number
54
54
  el: HTMLCanvasElement
55
- vs: string | X
56
- fs: string | X
57
- vert: string | X
58
- frag: string | X
59
- vertex: string | X
60
- fragment: string | X
55
+ vs: string | NodeProxy
56
+ fs: string | NodeProxy
57
+ vert: string | NodeProxy
58
+ frag: string | NodeProxy
59
+ vertex: string | NodeProxy
60
+ fragment: string | NodeProxy
61
61
 
62
62
  /**
63
63
  * core state
@@ -1,5 +1,5 @@
1
- import { fragment, vertex, X } from '../node'
2
- import { is } from './helpers'
1
+ import { fragment, isNodeProxy, vertex } from '../node'
2
+ import type { NodeProxy } from '../node'
3
3
  import type { GPUContext, GPUDevice, GPUPipeline } from '../types'
4
4
 
5
5
  const defaultVertexWGSL = `
@@ -34,11 +34,11 @@ export const createPipeline = (
34
34
  format: string,
35
35
  bufferLayouts: any[],
36
36
  bindGroupLayouts: any[],
37
- vs: string | X = defaultVertexWGSL,
38
- fs: string | X = defaultFragmentWGSL
37
+ vs: string | NodeProxy = defaultVertexWGSL,
38
+ fs: string | NodeProxy = defaultFragmentWGSL
39
39
  ) => {
40
- if (!is.str(fs)) fs = fragment(fs, { isWebGL: false })
41
- if (!is.str(vs)) vs = vertex(vs, { isWebGL: false })
40
+ if (isNodeProxy(vs)) vs = vertex(vs, { isWebGL: false })
41
+ if (isNodeProxy(fs)) fs = fragment(fs, { isWebGL: false })
42
42
  const layout = device.createPipelineLayout({ bindGroupLayouts })
43
43
  return device.createRenderPipeline({
44
44
  vertex: {
@@ -1,5 +1,5 @@
1
- import { fragment, vertex, X } from '../node'
2
- import { is } from './helpers'
1
+ import { fragment, isNodeProxy, vertex } from '../node'
2
+ import type { NodeProxy } from '../node'
3
3
 
4
4
  export const defaultVertexGLSL = /* cpp */ `
5
5
  #version 300 es
@@ -33,21 +33,23 @@ const createShader = (c: WebGLRenderingContext, source: string, type: number) =>
33
33
 
34
34
  export const createProgram = (
35
35
  c: WebGLRenderingContext,
36
- vs: string | X = defaultVertexGLSL,
37
- fs: string | X = defaultFragmentGLSL
36
+ vs: string | NodeProxy = defaultVertexGLSL,
37
+ fs: string | NodeProxy = defaultFragmentGLSL,
38
+ onError = () => {}
38
39
  ) => {
39
- if (!is.str(fs)) fs = fragment(fs, { isWebGL: true })
40
- if (!is.str(vs)) vs = vertex(fs, { isWebGL: true })
40
+ if (isNodeProxy(fs)) fs = fragment(fs, { isWebGL: true })
41
+ if (isNodeProxy(vs)) vs = vertex(fs, { isWebGL: true })
41
42
  const pg = c.createProgram()
42
43
  const _vs = createShader(c, vs, c.VERTEX_SHADER)
43
44
  const _fs = createShader(c, fs, c.FRAGMENT_SHADER)
44
- if (!_vs || !_fs) return
45
+ if (!_vs || !_fs) return onError()
45
46
  c.attachShader(pg, _vs)
46
47
  c.attachShader(pg, _fs)
47
48
  c.linkProgram(pg)
48
49
  if (c.getProgramParameter(pg, c.LINK_STATUS)) return pg
49
50
  const error = c.getProgramInfoLog(pg)
50
51
  c.deleteProgram(pg)
52
+ onError()
51
53
  console.warn(`Could not link pg: ${error}`)
52
54
  }
53
55
 
package/src/webgl.ts CHANGED
@@ -5,14 +5,13 @@ import type { GL, WebGLState } from './types'
5
5
 
6
6
  export const webgl = async (gl: Partial<GL>) => {
7
7
  const c = gl.el!.getContext('webgl2')!
8
- const pg = createProgram(c, gl.vs, gl.fs)!
9
- const state = { context: c, program: pg } as WebGLState
8
+ const pg = createProgram(c, gl.vs, gl.fs, () => void (gl.isLoop = false))!
10
9
  c.useProgram(pg)
11
-
12
10
  let _activeUnit = 0
13
11
  const uniforms = cached((key) => c.getUniformLocation(pg, key))
14
12
  const attribs = cached((key) => c.getAttribLocation(pg, key))
15
13
  const units = cached(() => _activeUnit++)
14
+ const state = { context: c, program: pg } as WebGLState
16
15
 
17
16
  const clean = () => c.deleteProgram(pg)
18
17
 
package/dist/index.mjs DELETED
@@ -1,61 +0,0 @@
1
- import{durable as M,event as Pe}from"reev";import{createFrame as Ge,createQueue as Se}from"refr";import{nested as I}from"reev";var d={arr:Array.isArray,bol:e=>typeof e=="boolean",str:e=>typeof e=="string",num:e=>typeof e=="number",int:e=>Number.isInteger(e),fun:e=>typeof e=="function",und:e=>typeof e>"u",nul:e=>e===null,set:e=>e instanceof Set,map:e=>e instanceof Map,obj:e=>!!e&&e.constructor.name==="Object",nan:e=>typeof e=="number"&&Number.isNaN(e)},be=(e,t)=>e.forEach(t),Ne=(e,...t)=>{be(e,r=>r(...t))},ze=(e="",t="_",r="/")=>e.split(t).join(r),Be=(e=".pdf")=>e.split(".").pop()?.toLowerCase()??"",$e=(e=0)=>`${e}`.split(".")[1]?.length??0,Ie=(e=0)=>`${e}`.split(".")[0]?.length-(e<0?1:0),Ce=(e=0,t=-2)=>(t*=-1,t=Math.pow(10,t),e*=t,e=Math.round(e),e/=t,e);var Oe=["x","y","z","w","r","g","b","a","s","t","p","q"],D=["float","int","uint","bool","color","vec2","vec3","vec4","mat2","mat3","mat4","ivec2","ivec3","ivec4","uvec2","uvec3","uvec4","bvec2","bvec3","bvec4"],N={add:"+",sub:"-",mul:"*",div:"/",mod:"%",equal:"==",notEqual:"!=",lessThan:"<",lessThanEqual:"<=",greaterThan:">",greaterThanEqual:">=",and:"&&",or:"||",bitAnd:"&",bitOr:"|",bitXor:"^",shiftLeft:"<<",shiftRight:">>"},W=Object.keys(N),q=["abs","acos","asin","atan","atan2","ceil","clamp","cos","cross","degrees","distance","dot","exp","exp2","faceforward","floor","fract","length","all","any","bitcast","cbrt","dFdx","dFdy","difference","equals","fwidth","inverseSqrt","lengthSq","log","log2","max","min","mix","negate","normalize","oneMinus","pow","pow2","pow3","pow4","radians","reciprocal","reflect","refract","round","saturate","sign","sin","smoothstep","sqrt","step","tan","transformDirection","trunc"],V={float:"f32",int:"i32",uint:"u32",bool:"bool",vec2:"vec2f",vec3:"vec3f",vec4:"vec4f",mat2:"mat2x2f",mat3:"mat3x3f",mat4:"mat4x4f",ivec2:"vec2i",ivec3:"vec3i",ivec4:"vec4i",uvec2:"vec2u",uvec3:"vec3u",uvec4:"vec4u",bvec2:"vec2<bool>",bvec3:"vec3<bool>",bvec4:"vec4<bool>"};var z=e=>d.str(e)&&/^[xyzwrgbastpq]{1,4}$/.test(e),Y=e=>W.includes(e),Ye=e=>D.includes(e),k=e=>q.includes(e),Xe=0,P=()=>`i${Xe++}`,B=(e,t)=>e.filter(r=>!d.und(r)&&!d.nul(r)).map(r=>f(r,t)).join(", "),_=(e,t)=>{if(!e||typeof e!="object")return"float";let{type:r,props:o}=e,{children:n=[]}=o,[i,a,c]=n;if(r==="node_type")return i;if(r==="operator"){let v=_(a,t),m=_(c,t);return v===m||v.includes("vec")?v:m.includes("vec")?m:"float"}return r==="math_fun"?["normalize","cross","reflect"].includes(i)?_(n[1],t):(["dot","distance","length"].includes(i),"float"):"float"},j=e=>!e.uniforms||e.uniforms.size===0?"":Array.from(e.uniforms).map((r,o)=>e.isWebGL?`uniform vec2 ${r};`:`@group(0) @binding(${o}) var<uniform> ${r}: vec2f;`).join(`
2
- `)+`
3
- `,K=(e,t,r=!0)=>r?`
4
- ${t}
5
- #version 300 es
6
- precision mediump float;
7
- uniform vec2 iResolution;
8
- uniform vec2 iMouse;
9
- uniform float iTime;
10
- out vec4 fragColor;
11
- void main() {
12
- ${e}
13
- }`.trim():`
14
- @group(0) @binding(0) var<uniform> iResolution: vec2f;
15
- @group(0) @binding(1) var<uniform> iMouse: vec2f;
16
- @group(0) @binding(2) var<uniform> iTime: f32;
17
- ${t}
18
- @fragment
19
- fn main(@builtin(position) position: vec4f) -> @location(0) vec4f {
20
- ${e}
21
- }`.trim(),G=(e,t)=>{let r=f(e,t),o=j(t);return K(r,o,t.isWebGL)},S=(e,t)=>{let r=f(e,t),o=j(t);return K(r,o,t.isWebGL)};var f=(e,t)=>{if(t||(t={}),t.uniforms||(t.uniforms=new Set),d.num(e))return e.toFixed(1);if(d.str(e))return e;if(!e)return"";let{type:r,props:o}=e,{id:n="",children:i=[]}=o,[a,c,v]=i;if(r==="uniform")return t.uniforms.add(n),t.onUniform?.(n,o.defaultValue),n;if(r==="variable")return n;if(r==="swizzle")return`${f(c,t)}.${f(a,t)}`;if(r==="node_type"){if(!d.str(a))return n;let m=!t.isWebGL&&a.startsWith("vec")?`${a}f`:a,X=B(i.slice(1),t);return`${m}(${X})`}if(r==="operator"){if(a==="not"||a==="bitNot")return`!${f(c,t)}`;let m=N[a];return`(${f(c,t)} ${m} ${f(v,t)})`}if(r==="math_fun")return`${a}(${B(i.slice(1),t)})`;if(r==="assign")return`${f(a,t)} = ${f(c,t)};`;if(r==="scope")return i.map(m=>f(m,t)).join(`
22
- `);if(r==="loop")return`for (int i = 0; i < ${a}; i++) {
23
- ${f(c,t)}
24
- }`;if(r==="fn"){let m=f(a,t);return c&&(m+=`
25
- return ${f(c,t)};`),m}if(r==="if"){let m=`if (${f(a,t)}) {
26
- ${f(c,t)}
27
- }`;for(let X=2;X<i.length;X+=2){let R=X>=i.length-1;m+=R?` else {
28
- ${f(i[X],t)}
29
- }`:` else if (${f(i[X],t)}) {
30
- ${f(i[X+1],t)}
31
- }`}return m}if(r==="declare"){let m=_(c,t),X=a?.props?.id;if(t.isWebGL)return`${m} ${X} = ${f(c,t)};`;let R=V[m];return`var ${X}: ${R} = ${f(c,t)};`}return f(a,t)};var w=null,L=(e,t=()=>{})=>{let r=w;w=e,t(),w=r},A=e=>{w&&(w.props.children||(w.props.children=[]),w.props.children.push(e))},et=(e,t)=>{let r=l("scope");L(r,t);let o=l("if",null,e,r);return A(o),{ElseIf:(n,i)=>{let a=l("scope");L(a,i),o.props.children.push(n,a)},Else:n=>{let i=l("scope");L(i,n),o.props.children.push(i)}}},tt=(e,t)=>{let r=l("scope");L(r,()=>t?.({i:l("variable",{id:"i"})}));let o=l("loop",null,e,r);return A(o),o},rt=e=>(...t)=>{let r,o=l("scope");return L(o,()=>r=e(t)),l("fn",null,o,r)},$=e=>t=>{t||(t=P());let r=l("variable",{id:t}),o=l("declare",null,r,e);return A(o),r},H=e=>t=>{let r=l("assign",null,e,t);return A(r),e};var ve=e=>t=>{if(t==="string")return f(e)},l=(e,t,...r)=>{t||(t={}),r.length&&(t.children=r);let o=new Proxy(()=>{},{get(n,i){return i==="type"?e:i==="props"?t:i==="toVar"?$(o):i==="assign"?H(o):i==="isProxy"?!0:i==="toString"?f.bind(null,o):i===Symbol.toPrimitive?ve(o):z(i)?Z(i,o):Y(i)?(...a)=>ye(i,o,...a):k(i)?(...a)=>s(i,o,...a):$(o)("")},set(n,i,a){return z(i)?(Z(i,o).assign(a),!0):!1}});return o},at=(...e)=>l("variable",{id:P()},...e),F=(e,t)=>l("uniform",{defaultValue:t},e),Z=(e,t)=>l("swizzle",null,e,t),g=(e,...t)=>l("node_type",null,e,...t),ye=(e,...t)=>l("operator",null,e,...t),s=(e,...t)=>l("math_fun",null,e,...t);var ft=F("iResolution",[1280,800]),pt=F("iMouse",[0,0]),mt=F("iTime",0),lt=l("variable",{id:"fragCoord"}),xt=e=>g("float",e),dt=e=>g("int",e),gt=e=>g("uint",e),bt=e=>g("bool",e),Xt=(e,t)=>g("vec2",e,t),vt=(e,t,r)=>g("vec3",e,t,r),yt=(e,t,r,o)=>g("vec4",e,t,r,o),ht=(...e)=>g("mat2",...e),Tt=(...e)=>g("mat3",...e),Et=(...e)=>g("mat4",...e),wt=(e,t)=>g("ivec2",e,t),Rt=(e,t,r)=>g("ivec3",e,t,r),_t=(e,t,r,o)=>g("ivec4",e,t,r,o),Lt=(e,t)=>g("uvec2",e,t),Pt=(e,t,r)=>g("uvec3",e,t,r),Gt=(e,t,r,o)=>g("uvec4",e,t,r,o),St=(e,t)=>g("bvec2",e,t),At=(e,t,r)=>g("bvec3",e,t,r),Ft=(e,t,r,o)=>g("bvec4",e,t,r,o),Ut=e=>s("abs",e),Nt=e=>s("acos",e),zt=e=>s("all",e),Bt=e=>s("any",e),$t=e=>s("asin",e),It=(e,t)=>s("atan",e,t),Ct=(e,t)=>s("bitcast",e,t),Mt=e=>s("cbrt",e),Ot=e=>s("ceil",e),Dt=(e,t,r)=>s("clamp",e,t,r),Wt=e=>s("cos",e),qt=(e,t)=>s("cross",e,t),Vt=e=>s("dFdx",e),Yt=e=>s("dFdy",e),kt=e=>s("degrees",e),jt=(e,t)=>s("difference",e,t),Kt=(e,t)=>s("distance",e,t),Ht=(e,t)=>s("dot",e,t),Zt=(e,t)=>s("equals",e,t),Qt=e=>s("exp",e),Jt=e=>s("exp2",e),er=(e,t,r)=>s("faceforward",e,t,r),tr=e=>s("floor",e),rr=e=>s("fract",e),or=e=>s("fwidth",e),nr=e=>s("inverseSqrt",e),sr=e=>s("length",e),ir=e=>s("lengthSq",e),ar=e=>s("log",e),ur=e=>s("log2",e),cr=(e,t)=>s("max",e,t),fr=(e,t)=>s("min",e,t),pr=(e,t,r)=>s("mix",e,t,r),mr=e=>s("negate",e),lr=e=>s("normalize",e),xr=e=>s("oneMinus",e),dr=(e,t)=>s("pow",e,t),gr=e=>s("pow2",e),br=e=>s("pow3",e),Xr=e=>s("pow4",e),vr=e=>s("radians",e),yr=e=>s("reciprocal",e),hr=(e,t)=>s("reflect",e,t),Tr=(e,t,r)=>s("refract",e,t,r),Er=e=>s("round",e),wr=e=>s("saturate",e),Rr=e=>s("sign",e),_r=e=>s("sin",e),Lr=(e,t,r)=>s("smoothstep",e,t,r),Pr=e=>s("sqrt",e),Gr=(e,t)=>s("step",e,t),Sr=e=>s("tan",e),Ar=(e,t)=>s("transformDirection",e,t),Fr=e=>s("trunc",e);var he=`
32
- #version 300 es
33
- void main() {
34
- float x = float(gl_VertexID % 2) * 4.0 - 1.0;
35
- float y = float(gl_VertexID / 2) * 4.0 - 1.0;
36
- gl_Position = vec4(x, y, 0.0, 1.0);
37
- }
38
- `,Te=`
39
- #version 300 es
40
- precision mediump float;
41
- uniform vec2 iResolution;
42
- out vec4 fragColor;
43
- void main() {
44
- fragColor = vec4(fract(gl_FragCoord.xy / iResolution), 0, 1);
45
- }
46
- `,Q=(e,t,r)=>{let o=e.createShader(r);if(!o)throw new Error("Failed to create shader");if(e.shaderSource(o,t.trim()),e.compileShader(o),e.getShaderParameter(o,e.COMPILE_STATUS))return o;let n=e.getShaderInfoLog(o);e.deleteShader(o),console.warn(`Could not compile shader: ${n}`)},J=(e,t=he,r=Te)=>{d.str(r)||(r=G(r,{isWebGL:!0})),d.str(t)||(t=S(r,{isWebGL:!0}));let o=e.createProgram(),n=Q(e,t,e.VERTEX_SHADER),i=Q(e,r,e.FRAGMENT_SHADER);if(!n||!i)return;if(e.attachShader(o,n),e.attachShader(o,i),e.linkProgram(o),e.getProgramParameter(o,e.LINK_STATUS))return o;let a=e.getProgramInfoLog(o);e.deleteProgram(o),console.warn(`Could not link pg: ${a}`)},ee=(e,t)=>{let r=e.createBuffer();return e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,new Float32Array(t),e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,null),r},te=(e,t)=>{let r=e.createBuffer();return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r),e.bufferData(e.ELEMENT_ARRAY_BUFFER,new Int16Array(t),e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),r},re=(e,t,r)=>{r&&(e=Math.max(...r)+1);let o=t.length/e;return Math.floor(o)},oe=(e,t,r,o,n)=>{e.bindBuffer(e.ARRAY_BUFFER,o),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,t,e.FLOAT,!1,0,0),n&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)},ne=(e,t,r,o)=>{let n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.generateMipmap(e.TEXTURE_2D),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),e.uniform1i(r,o),e.activeTexture(e.TEXTURE0+o),e.bindTexture(e.TEXTURE_2D,n)};var se=async e=>{let t=e.el.getContext("webgl2"),r=J(t,e.vs,e.fs),o={context:t,program:r};t.useProgram(r);let n=0,i=I(y=>t.getUniformLocation(r,y)),a=I(y=>t.getAttribLocation(r,y)),c=I(()=>n++);return{webgl:o,render:()=>{t.clear(t.COLOR_BUFFER_BIT),t.viewport(0,0,...e.size),t.drawArrays(t.TRIANGLES,0,3)},clean:()=>t.deleteProgram(r),_attribute:(y="",h,T)=>{let E=a(y,!0),b=ee(t,h),u=te(t,T),p=re(e.count,h,T);oe(t,p,E,b,u)},_uniform:(y,h)=>{let T=i(y);if(d.num(h))return t.uniform1f(T,h);let E=h.length;if(E<=4)return t[`uniform${E}fv`](T,h);E=Math.sqrt(E)<<0,t[`uniformMatrix${E}fv`](T,!1,h)},_texture:(y,h)=>{let T=new Image;Object.assign(T,{src:h,crossOrigin:"anonymous"}),T.decode().then(()=>{let E=i(y),b=c(y);ne(t,T,E,b)})}}};import{nested as C}from"reev";var Ee=`
47
- @vertex
48
- fn main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4f {
49
- let x = f32(vertex_index % 2u) * 4.0 - 1.0;
50
- let y = f32(vertex_index / 2u) * 4.0 - 1.0;
51
- return vec4f(x, y, 0.0, 1.0);
52
- }
53
- `,we=`
54
- @group(0) @binding(0) var<uniform> iResolution: vec2f;
55
-
56
- @fragment
57
- fn main(@builtin(position) position: vec4f) -> @location(0) vec4f {
58
- return vec4f(position.xy / iResolution, 0.0, 1.0);
59
- }
60
- `,ie=async e=>{let t=navigator.gpu,r=t.getPreferredCanvasFormat(),n=await(await t.requestAdapter()).requestDevice();return e.configure({device:n,format:r,alphaMode:"opaque"}),{device:n,format:r}},ae=(e,t,r,o,n=Ee,i=we)=>{d.str(i)||(i=G(i,{isWebGL:!1})),d.str(n)||(n=S(n,{isWebGL:!1}));let a=e.createPipelineLayout({bindGroupLayouts:o});return e.createRenderPipeline({vertex:{module:e.createShaderModule({code:n.trim()}),entryPoint:"main",buffers:r},fragment:{module:e.createShaderModule({code:i.trim()}),entryPoint:"main",targets:[{format:t}]},layout:a,primitive:{topology:"triangle-list"}})},ue=(e,t)=>{let r=[],o=[];t.forEach((a,c)=>{if(!a)return;let v="buffer"in a,m=a instanceof GPUTextureView,X=a instanceof GPUSampler;if(v)r.push({binding:c,visibility:3,buffer:{type:"uniform"}});else if(m)r.push({binding:c,visibility:2,texture:{}});else if(X)r.push({binding:c,visibility:2,sampler:{}});else return;o.push({binding:c,resource:a})});let n=e.createBindGroupLayout({entries:r}),i=e.createBindGroup({layout:n,entries:o});return{layout:n,bindGroup:i}},ce=e=>({colorAttachments:[{view:e.getCurrentTexture().createView(),clearValue:{r:0,g:0,b:0,a:1},loadOp:"clear",storeOp:"store"}]}),Re=e=>Math.ceil(e/256)*256,fe=(e,t)=>{let r=new Float32Array(t),o=e.createBuffer({size:r.byteLength,usage:40});return{array:r,buffer:o}},pe=(e,t)=>{let r=new Float32Array(t),o=Re(r.byteLength),n=e.createBuffer({size:o,usage:72});return{array:r,buffer:n}},me=(e,t=1280,r=800)=>{let o=e.createTexture({size:[t,r],format:"rgba8unorm",usage:22}),n=e.createSampler({magFilter:"linear",minFilter:"linear"});return{texture:o,sampler:n}},_e=(e,t)=>e/t,Le=e=>e===2?"float32x2":e===3?"float32x3":e===4?"float32x4":"float32",le=(e,t,r=6)=>{let o=_e(t,r);return{arrayStride:o*4,attributes:[{shaderLocation:e,offset:0,format:Le(o)}]}};var xe=async e=>{let t=e.el.getContext("webgpu"),{device:r,format:o}=await ie(t),n={device:r,context:t,resources:[[],[]],loadingImg:0,needsUpdate:!0},i=[],a=[],c=[],v=C((b,u)=>{let{array:p,buffer:x}=fe(r,u);return a.push(x),c.push(le(c.length,p.length,e.count)),n.needsUpdate=!0,{array:p,buffer:x}}),m=C((b,u)=>{let{array:p,buffer:x}=pe(r,u);return n.resources[0].push({buffer:x}),n.needsUpdate=!0,{array:p,buffer:x}}),X=C((b,{width:u,height:p})=>{let{texture:x,sampler:U}=me(r,u,p);return n.resources[1].push(U,x.createView()),n.needsUpdate=!0,{texture:x,width:u,height:p}}),R=()=>{let b=[];i.length=0,n.resources.forEach(u=>{if(!u.length)return;let{layout:p,bindGroup:x}=ue(r,u);b.push(p),i.push(x)}),n.pipeline=ae(r,o,c,b,e.vs,e.fs)};return{webgpu:n,render:()=>{if(n.loadingImg)return;n.needsUpdate&&R(),n.needsUpdate=!1;let b=r.createCommandEncoder(),u=b.beginRenderPass(ce(t));u.setPipeline(n.pipeline),i.forEach((p,x)=>u.setBindGroup(x,p)),a.forEach((p,x)=>u.setVertexBuffer(x,p)),u.draw(e.count,1,0,0),u.end(),r.queue.submit([b.finish()])},clean:()=>{},_attribute:(b="",u)=>{let{array:p,buffer:x}=v(b,u);r.queue.writeBuffer(x,0,p)},_uniform:(b,u)=>{d.num(u)&&(u=[u]);let{array:p,buffer:x}=m(b,u);p.set(u),r.queue.writeBuffer(x,0,p)},_texture:(b,u)=>{n.loadingImg++;let p=Object.assign(new Image,{src:u,crossOrigin:"anonymous"});p.decode().then(()=>{let{texture:x,width:U,height:ge}=X(b,p);r.queue.copyExternalImageToTexture({source:p},{texture:x},{width:U,height:ge}),n.loadingImg--})}}};var ao=e=>d.obj(e)?"isGL"in e:!1,Ae=()=>typeof window>"u",Fe=()=>Ae()?!1:"gpu"in navigator,O=performance.now(),Ue=e=>{let t=Pe({isNative:!1,isWebGL:!0,isLoop:!0,isGL:!0,size:[0,0],mouse:[0,0],count:6,webgl:{},webgpu:{}});return t.queue=Se(),t.frame=Ge(),t.attribute=M((r,o,n)=>t.queue(()=>t._attribute?.(r,o,n))),t.texture=M((r,o)=>t.queue(()=>t._texture?.(r,o))),t.uniform=M((r,o,n)=>t.queue(()=>t._uniform?.(r,o,n))),t.uniform({iResolution:t.size,iMouse:[0,0],iTime:O}),t("mount",async()=>{t.vs=t.vs||t.vert||t.vertex,t.fs=t.fs||t.frag||t.fragment,Fe()||(t.isWebGL=!0),t.isWebGL?t(await se(t)):t(await xe(t)),t.resize(),t.frame(()=>(t.loop(),t.queue.flush(),t.render(),t.isLoop)),!t.isNative&&(window.addEventListener("resize",t.resize),t.el.addEventListener("mousemove",t.mousemove))}),t("clean",()=>{t.frame.stop(),t.frame.clean(t.render),!t.isNative&&(window.removeEventListener("resize",t.resize),t.el.removeEventListener("mousemove",t.mousemove))}),t("resize",()=>{let r=t.width||window.innerWidth,o=t.height||window.innerHeight;t.size[0]=t.el.width=r,t.size[1]=t.el.height=o,t.uniform("iResolution",t.size)}),t("mousemove",(r,o=r.clientX,n=r.clientY)=>{let[i,a]=t.size,{top:c,left:v}=t.el.getBoundingClientRect();t.mouse[0]=(o-c-i/2)/(i/2),t.mouse[1]=-(n-v-a/2)/(a/2),t.uniform("iMouse",t.mouse)}),t("loop",()=>{O=performance.now()/1e3,t.uniform("iTime",O)}),t(e)},uo=Ue;export{q as FUNCTIONS,rt as Fn,et as If,tt as Loop,D as NODE_TYPES,N as OPERATORS,W as OPERATOR_KEYS,Oe as SWIZZLES,V as TYPE_MAPPING,Ut as abs,Nt as acos,Re as alignTo256,zt as all,Bt as any,$t as asin,H as assign,It as atan,Ct as bitcast,bt as bool,St as bvec2,At as bvec3,Ft as bvec4,Mt as cbrt,Ot as ceil,Dt as clamp,f as code,Wt as cos,oe as createAttrib,ue as createBindGroup,le as createBufferLayout,ce as createDescriptor,ie as createDevice,Ue as createGL,te as createIbo,ae as createPipeline,J as createProgram,ne as createTexture,me as createTextureSampler,pe as createUniformBuffer,ee as createVbo,fe as createVertexBuffer,qt as cross,Vt as dFdx,Yt as dFdy,uo as default,Te as defaultFragmentGLSL,he as defaultVertexGLSL,kt as degrees,jt as difference,Ie as dig,Kt as distance,Ht as dot,be as each,Zt as equals,Qt as exp,Jt as exp2,Be as ext,s as f,er as faceforward,$e as fig,xt as float,tr as floor,Ne as flush,rr as fract,lt as fragCoord,G as fragment,or as fwidth,P as getId,re as getStride,pt as iMouse,ft as iResolution,mt as iTime,_ as inferType,dt as int,nr as inverseSqrt,d as is,k as isFunction,ao as isGL,Ye as isNodeType,Y as isOperator,Ae as isServer,z as isSwizzle,Fe as isWebGPUSupported,wt as ivec2,Rt as ivec3,_t as ivec4,B as joins,sr as length,ir as lengthSq,ar as log,ur as log2,ht as mat2,Tt as mat3,Et as mat4,cr as max,fr as min,pr as mix,g as n,mr as negate,l as node,lr as normalize,ye as o,xr as oneMinus,dr as pow,gr as pow2,br as pow3,Xr as pow4,vr as radians,yr as reciprocal,hr as reflect,Tr as refract,ze as replace,Er as round,Z as s,wr as saturate,Ce as sig,Rr as sign,_r as sin,Lr as smoothstep,Pr as sqrt,Gr as step,Sr as tan,$ as toVar,Ar as transformDirection,Fr as trunc,F as u,gt as uint,Lt as uvec2,Pt as uvec3,Gt as uvec4,at as v,Xt as vec2,vt as vec3,yt as vec4,S as vertex,se as webgl,xe as webgpu};
61
- //# sourceMappingURL=index.mjs.map