@m3ui-vue/m3ui-vue 0.5.8 → 0.5.10
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/dist/components/MShader.vue.d.ts +54 -0
- package/dist/index.d.ts +2 -0
- package/dist/m3ui.js +1557 -1252
- package/dist/m3ui.js.map +1 -1
- package/package.json +4 -3
- package/src/__tests__/MShader.test.ts +50 -0
- package/src/components/MShader.vue +579 -0
- package/src/index.ts +2 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@m3ui-vue/m3ui-vue",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.10",
|
|
4
4
|
"description": "Material 3 component library for Vue 3 + Tailwind CSS v4",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -185,6 +185,7 @@
|
|
|
185
185
|
"@vitejs/plugin-vue": "^6.0.7",
|
|
186
186
|
"@vue/test-utils": "^2.4.11",
|
|
187
187
|
"@vue/tsconfig": "^0.9.1",
|
|
188
|
+
"@webgpu/types": "^0.1.71",
|
|
188
189
|
"@xterm/addon-fit": "^0.11.0",
|
|
189
190
|
"@xterm/xterm": "^6.0.0",
|
|
190
191
|
"chart.js": "^4.5.1",
|
|
@@ -195,9 +196,9 @@
|
|
|
195
196
|
"typescript": "~6.0.3",
|
|
196
197
|
"vite": "^8.0.16",
|
|
197
198
|
"vitest": "^4.1.9",
|
|
198
|
-
"vue": "^3.5.
|
|
199
|
+
"vue": "^3.5.42",
|
|
199
200
|
"vue-chartjs": "^5.3.3",
|
|
200
|
-
"vue-tsc": "^3.3.
|
|
201
|
+
"vue-tsc": "^3.3.11"
|
|
201
202
|
},
|
|
202
203
|
"publishConfig": {
|
|
203
204
|
"access": "public"
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { mount, flushPromises } from '@vue/test-utils'
|
|
3
|
+
import MShader from '../components/MShader.vue'
|
|
4
|
+
|
|
5
|
+
const BASIC_CODE = `void mainImage(out vec4 fragColor, in vec2 fragCoord) {
|
|
6
|
+
fragColor = vec4(fragCoord / iResolution.xy, 0.0, 1.0);
|
|
7
|
+
}`
|
|
8
|
+
|
|
9
|
+
describe('MShader', () => {
|
|
10
|
+
it('shows the fallback slot when neither WebGL2 nor WebGPU is available', async () => {
|
|
11
|
+
// happy-dom returns null from canvas.getContext('webgl2') and has no navigator.gpu,
|
|
12
|
+
// so this exercises the same "unsupported browser" path real old browsers hit.
|
|
13
|
+
const wrapper = mount(MShader, { props: { code: BASIC_CODE } })
|
|
14
|
+
await flushPromises()
|
|
15
|
+
|
|
16
|
+
expect(wrapper.text()).toContain('Shaders are not supported in this browser')
|
|
17
|
+
expect(wrapper.emitted('error')).toBeTruthy()
|
|
18
|
+
expect(wrapper.emitted('ready')).toBeFalsy()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('renders a custom #fallback slot', async () => {
|
|
22
|
+
const wrapper = mount(MShader, {
|
|
23
|
+
props: { code: BASIC_CODE },
|
|
24
|
+
slots: { fallback: '<p>custom fallback</p>' },
|
|
25
|
+
})
|
|
26
|
+
await flushPromises()
|
|
27
|
+
|
|
28
|
+
expect(wrapper.text()).toContain('custom fallback')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('errors immediately when renderer="webgpu" is forced without a wgsl prop', async () => {
|
|
32
|
+
const wrapper = mount(MShader, { props: { code: BASIC_CODE, renderer: 'webgpu' } })
|
|
33
|
+
await flushPromises()
|
|
34
|
+
|
|
35
|
+
const errors = wrapper.emitted('error')
|
|
36
|
+
expect(errors).toBeTruthy()
|
|
37
|
+
expect(errors![0]![0]).toContain('no `wgsl` prop was provided')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('exposes canvas, status and imperative controls', async () => {
|
|
41
|
+
const wrapper = mount(MShader, { props: { code: BASIC_CODE } })
|
|
42
|
+
await flushPromises()
|
|
43
|
+
|
|
44
|
+
expect(wrapper.vm.canvas).toBeTruthy()
|
|
45
|
+
expect(wrapper.vm.status).toBe('fallback')
|
|
46
|
+
expect(typeof wrapper.vm.pause).toBe('function')
|
|
47
|
+
expect(typeof wrapper.vm.play).toBe('function')
|
|
48
|
+
expect(typeof wrapper.vm.restart).toBe('function')
|
|
49
|
+
})
|
|
50
|
+
})
|
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/// <reference types="@webgpu/types" />
|
|
3
|
+
import { ref, shallowRef, onMounted, onBeforeUnmount, watch } from 'vue'
|
|
4
|
+
import MSpinner from './MSpinner.vue'
|
|
5
|
+
|
|
6
|
+
/** Thrown when a backend can't run at all in this browser (no API, no adapter, no context) — as
|
|
7
|
+
* opposed to a shader authoring error — so the component can show #fallback instead of #error. */
|
|
8
|
+
class UnsupportedError extends Error {}
|
|
9
|
+
|
|
10
|
+
export type ShaderRenderer = 'auto' | 'webgpu' | 'webgl'
|
|
11
|
+
export type ShaderStatus = 'loading' | 'ready' | 'error' | 'fallback'
|
|
12
|
+
|
|
13
|
+
const props = withDefaults(
|
|
14
|
+
defineProps<{
|
|
15
|
+
/** GLSL fragment shader body (Shadertoy-style): must define `mainImage(out vec4 fragColor, in vec2 fragCoord)`.
|
|
16
|
+
* Runs on WebGL2. Always required as the compatible baseline. */
|
|
17
|
+
code: string
|
|
18
|
+
/** Optional WGSL fragment shader module, e.g. `@fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f`.
|
|
19
|
+
* Runs on WebGPU when available. Must declare its own bindings — see docs for the required uniform buffer layout. */
|
|
20
|
+
wgsl?: string
|
|
21
|
+
/** Which backend to use. 'auto' picks WebGPU when `wgsl` is set and supported, else WebGL2. */
|
|
22
|
+
renderer?: ShaderRenderer
|
|
23
|
+
/** Custom uniforms. Keys/shape are locked in at mount time; only values are reactive per frame. */
|
|
24
|
+
uniforms?: Record<string, number | number[]>
|
|
25
|
+
paused?: boolean
|
|
26
|
+
/** Device pixel ratio to render at. Defaults to devicePixelRatio, capped at 2 for performance. */
|
|
27
|
+
pixelRatio?: number
|
|
28
|
+
}>(),
|
|
29
|
+
{ renderer: 'auto' },
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
const emit = defineEmits<{
|
|
33
|
+
ready: [renderer: 'webgpu' | 'webgl']
|
|
34
|
+
error: [message: string]
|
|
35
|
+
}>()
|
|
36
|
+
|
|
37
|
+
const containerRef = ref<HTMLDivElement | null>(null)
|
|
38
|
+
const canvasRef = ref<HTMLCanvasElement | null>(null)
|
|
39
|
+
|
|
40
|
+
const status = ref<ShaderStatus>('loading')
|
|
41
|
+
const errorMessage = ref('')
|
|
42
|
+
const activeRenderer = shallowRef<'webgpu' | 'webgl' | null>(null)
|
|
43
|
+
|
|
44
|
+
interface MouseState {
|
|
45
|
+
x: number
|
|
46
|
+
y: number
|
|
47
|
+
clickX: number
|
|
48
|
+
clickY: number
|
|
49
|
+
down: boolean
|
|
50
|
+
}
|
|
51
|
+
const mouse: MouseState = { x: 0, y: 0, clickX: 0, clickY: 0, down: false }
|
|
52
|
+
|
|
53
|
+
interface ShaderBackend {
|
|
54
|
+
init(canvas: HTMLCanvasElement): Promise<void>
|
|
55
|
+
resize(width: number, height: number): void
|
|
56
|
+
render(time: number, frame: number): void
|
|
57
|
+
/** `final` is true only on component unmount — the canvas won't be reused, so it's safe to force
|
|
58
|
+
* the context to release its GPU resources immediately instead of waiting on garbage collection. */
|
|
59
|
+
destroy(final: boolean): void
|
|
60
|
+
/** Raw context/device for power users who want to go beyond the declarative props. */
|
|
61
|
+
raw(): WebGL2RenderingContext | GPUDevice | null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let backend: ShaderBackend | null = null
|
|
65
|
+
let resizeObserver: ResizeObserver | null = null
|
|
66
|
+
let intersectionObserver: IntersectionObserver | null = null
|
|
67
|
+
let rafId = 0
|
|
68
|
+
let running = false
|
|
69
|
+
let visible = true
|
|
70
|
+
let startTime = 0
|
|
71
|
+
let pausedElapsed = 0
|
|
72
|
+
let frameCount = 0
|
|
73
|
+
let uniformKeys: string[] = []
|
|
74
|
+
|
|
75
|
+
function effectivePixelRatio() {
|
|
76
|
+
return props.pixelRatio ?? Math.min(window.devicePixelRatio || 1, 2)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function uniformType(value: number | number[]): 'float' | 'vec2' | 'vec3' | 'vec4' {
|
|
80
|
+
if (typeof value === 'number') return 'float'
|
|
81
|
+
if (value.length === 2) return 'vec2'
|
|
82
|
+
if (value.length === 3) return 'vec3'
|
|
83
|
+
return 'vec4'
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function currentUniformValues() {
|
|
87
|
+
return props.uniforms ?? {}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/* ── WebGL2 backend ───────────────────────────────────────────────────── */
|
|
91
|
+
|
|
92
|
+
function createWebGLBackend(): ShaderBackend {
|
|
93
|
+
let gl: WebGL2RenderingContext | null = null
|
|
94
|
+
let program: WebGLProgram | null = null
|
|
95
|
+
let locITime: WebGLUniformLocation | null = null
|
|
96
|
+
let locIResolution: WebGLUniformLocation | null = null
|
|
97
|
+
let locIMouse: WebGLUniformLocation | null = null
|
|
98
|
+
let locIFrame: WebGLUniformLocation | null = null
|
|
99
|
+
const customLocations = new Map<string, WebGLUniformLocation>()
|
|
100
|
+
|
|
101
|
+
const VERTEX_SRC = `#version 300 es
|
|
102
|
+
void main() {
|
|
103
|
+
vec2 pos = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
|
|
104
|
+
gl_Position = vec4(pos * 2.0 - 1.0, 0.0, 1.0);
|
|
105
|
+
}`
|
|
106
|
+
|
|
107
|
+
function buildFragmentSource() {
|
|
108
|
+
const declarations = uniformKeys
|
|
109
|
+
.map((key) => `uniform ${uniformType(currentUniformValues()[key] ?? 0)} ${key};`)
|
|
110
|
+
.join('\n')
|
|
111
|
+
return `#version 300 es
|
|
112
|
+
precision highp float;
|
|
113
|
+
uniform float iTime;
|
|
114
|
+
uniform vec3 iResolution;
|
|
115
|
+
uniform vec4 iMouse;
|
|
116
|
+
uniform int iFrame;
|
|
117
|
+
${declarations}
|
|
118
|
+
out vec4 fragColor;
|
|
119
|
+
${props.code}
|
|
120
|
+
void main() {
|
|
121
|
+
mainImage(fragColor, gl_FragCoord.xy);
|
|
122
|
+
}`
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function compileShader(source: string, type: number) {
|
|
126
|
+
const gl2 = gl!
|
|
127
|
+
const shader = gl2.createShader(type)!
|
|
128
|
+
gl2.shaderSource(shader, source)
|
|
129
|
+
gl2.compileShader(shader)
|
|
130
|
+
if (!gl2.getShaderParameter(shader, gl2.COMPILE_STATUS)) {
|
|
131
|
+
const log = gl2.getShaderInfoLog(shader) || 'unknown compile error'
|
|
132
|
+
gl2.deleteShader(shader)
|
|
133
|
+
throw new Error(`${type === gl2.VERTEX_SHADER ? 'Vertex' : 'Fragment'} shader failed to compile:\n${log}`)
|
|
134
|
+
}
|
|
135
|
+
return shader
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function buildProgram() {
|
|
139
|
+
const gl2 = gl!
|
|
140
|
+
const vs = compileShader(VERTEX_SRC, gl2.VERTEX_SHADER)
|
|
141
|
+
const fs = compileShader(buildFragmentSource(), gl2.FRAGMENT_SHADER)
|
|
142
|
+
const prog = gl2.createProgram()!
|
|
143
|
+
gl2.attachShader(prog, vs)
|
|
144
|
+
gl2.attachShader(prog, fs)
|
|
145
|
+
gl2.linkProgram(prog)
|
|
146
|
+
gl2.deleteShader(vs)
|
|
147
|
+
gl2.deleteShader(fs)
|
|
148
|
+
if (!gl2.getProgramParameter(prog, gl2.LINK_STATUS)) {
|
|
149
|
+
const log = gl2.getProgramInfoLog(prog) || 'unknown link error'
|
|
150
|
+
gl2.deleteProgram(prog)
|
|
151
|
+
throw new Error(`Shader program failed to link:\n${log}`)
|
|
152
|
+
}
|
|
153
|
+
program = prog
|
|
154
|
+
locITime = gl2.getUniformLocation(prog, 'iTime')
|
|
155
|
+
locIResolution = gl2.getUniformLocation(prog, 'iResolution')
|
|
156
|
+
locIMouse = gl2.getUniformLocation(prog, 'iMouse')
|
|
157
|
+
locIFrame = gl2.getUniformLocation(prog, 'iFrame')
|
|
158
|
+
customLocations.clear()
|
|
159
|
+
for (const key of uniformKeys) {
|
|
160
|
+
const loc = gl2.getUniformLocation(prog, key)
|
|
161
|
+
if (loc) customLocations.set(key, loc)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
async init(canvas) {
|
|
167
|
+
gl = canvas.getContext('webgl2', { antialias: true, alpha: true })
|
|
168
|
+
if (!gl) throw new UnsupportedError('WebGL2 is not supported in this browser.')
|
|
169
|
+
buildProgram()
|
|
170
|
+
},
|
|
171
|
+
resize(width, height) {
|
|
172
|
+
gl?.viewport(0, 0, width, height)
|
|
173
|
+
},
|
|
174
|
+
render(time) {
|
|
175
|
+
const gl2 = gl
|
|
176
|
+
if (!gl2 || !program) return
|
|
177
|
+
gl2.useProgram(program)
|
|
178
|
+
gl2.uniform1f(locITime, time)
|
|
179
|
+
gl2.uniform3f(locIResolution, gl2.drawingBufferWidth, gl2.drawingBufferHeight, effectivePixelRatio())
|
|
180
|
+
gl2.uniform4f(
|
|
181
|
+
locIMouse,
|
|
182
|
+
mouse.x,
|
|
183
|
+
mouse.y,
|
|
184
|
+
mouse.down ? mouse.clickX : -mouse.clickX,
|
|
185
|
+
mouse.down ? mouse.clickY : -mouse.clickY,
|
|
186
|
+
)
|
|
187
|
+
gl2.uniform1i(locIFrame, frameCount)
|
|
188
|
+
const values = currentUniformValues()
|
|
189
|
+
for (const key of uniformKeys) {
|
|
190
|
+
const loc = customLocations.get(key)
|
|
191
|
+
if (!loc) continue
|
|
192
|
+
const v = values[key] ?? 0
|
|
193
|
+
if (typeof v === 'number') gl2.uniform1f(loc, v)
|
|
194
|
+
else if (v.length === 2) gl2.uniform2f(loc, v[0]!, v[1]!)
|
|
195
|
+
else if (v.length === 3) gl2.uniform3f(loc, v[0]!, v[1]!, v[2]!)
|
|
196
|
+
else gl2.uniform4f(loc, v[0]!, v[1]!, v[2]!, v[3]!)
|
|
197
|
+
}
|
|
198
|
+
gl2.drawArrays(gl2.TRIANGLES, 0, 3)
|
|
199
|
+
},
|
|
200
|
+
destroy(final) {
|
|
201
|
+
if (program) gl?.deleteProgram(program)
|
|
202
|
+
// Only force-lose the context on final unmount: the canvas is reused across restart()/prop
|
|
203
|
+
// rebuilds, and a canvas only ever gets one context instance per type — losing it here would
|
|
204
|
+
// permanently break every future getContext('webgl2') call on the same element.
|
|
205
|
+
if (final) gl?.getExtension('WEBGL_lose_context')?.loseContext()
|
|
206
|
+
gl = null
|
|
207
|
+
program = null
|
|
208
|
+
},
|
|
209
|
+
raw: () => gl,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/* ── WebGPU backend ───────────────────────────────────────────────────── */
|
|
214
|
+
|
|
215
|
+
function createWebGPUBackend(): ShaderBackend {
|
|
216
|
+
let context: GPUCanvasContext | null = null
|
|
217
|
+
let device: GPUDevice | null = null
|
|
218
|
+
let pipeline: GPURenderPipeline | null = null
|
|
219
|
+
let bindGroup: GPUBindGroup | null = null
|
|
220
|
+
let builtinBuffer: GPUBuffer | null = null
|
|
221
|
+
let customBuffer: GPUBuffer | null = null
|
|
222
|
+
const builtinData = new Float32Array(12)
|
|
223
|
+
let customData: Float32Array | null = null
|
|
224
|
+
let format: GPUTextureFormat = 'bgra8unorm'
|
|
225
|
+
|
|
226
|
+
const VERTEX_SRC = `@vertex
|
|
227
|
+
fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4f {
|
|
228
|
+
var pos = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
|
|
229
|
+
return vec4f(pos[idx], 0.0, 1.0);
|
|
230
|
+
}`
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
async init(canvas) {
|
|
234
|
+
if (!navigator.gpu) throw new UnsupportedError('WebGPU is not supported in this browser.')
|
|
235
|
+
const adapter = await navigator.gpu.requestAdapter()
|
|
236
|
+
if (!adapter) throw new UnsupportedError('No WebGPU adapter available.')
|
|
237
|
+
device = await adapter.requestDevice()
|
|
238
|
+
context = canvas.getContext('webgpu')
|
|
239
|
+
if (!context) throw new UnsupportedError('Failed to acquire a WebGPU canvas context.')
|
|
240
|
+
format = navigator.gpu.getPreferredCanvasFormat()
|
|
241
|
+
context.configure({ device, format, alphaMode: 'opaque' })
|
|
242
|
+
|
|
243
|
+
device.addEventListener('uncapturederror', (ev) => {
|
|
244
|
+
const message = (ev as GPUUncapturedErrorEvent).error.message
|
|
245
|
+
errorMessage.value = message
|
|
246
|
+
status.value = 'error'
|
|
247
|
+
emit('error', message)
|
|
248
|
+
stopLoop()
|
|
249
|
+
})
|
|
250
|
+
device.lost.then((info) => {
|
|
251
|
+
if (info.reason === 'destroyed') return
|
|
252
|
+
errorMessage.value = `WebGPU device was lost: ${info.message}`
|
|
253
|
+
status.value = 'error'
|
|
254
|
+
emit('error', errorMessage.value)
|
|
255
|
+
stopLoop()
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
const vsModule = device.createShaderModule({ code: VERTEX_SRC })
|
|
259
|
+
const fsModule = device.createShaderModule({ code: props.wgsl! })
|
|
260
|
+
const info = await fsModule.getCompilationInfo()
|
|
261
|
+
const compileErrors = info.messages.filter((m) => m.type === 'error')
|
|
262
|
+
if (compileErrors.length) {
|
|
263
|
+
throw new Error(compileErrors.map((m) => `${m.lineNum}:${m.linePos}: ${m.message}`).join('\n'))
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
device.pushErrorScope('validation')
|
|
267
|
+
|
|
268
|
+
const entries: GPUBindGroupLayoutEntry[] = [
|
|
269
|
+
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } },
|
|
270
|
+
]
|
|
271
|
+
if (uniformKeys.length) {
|
|
272
|
+
entries.push({ binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } })
|
|
273
|
+
}
|
|
274
|
+
const bindGroupLayout = device.createBindGroupLayout({ entries })
|
|
275
|
+
const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] })
|
|
276
|
+
|
|
277
|
+
pipeline = device.createRenderPipeline({
|
|
278
|
+
layout: pipelineLayout,
|
|
279
|
+
vertex: { module: vsModule, entryPoint: 'vs_main' },
|
|
280
|
+
fragment: { module: fsModule, entryPoint: 'fs_main', targets: [{ format }] },
|
|
281
|
+
primitive: { topology: 'triangle-list' },
|
|
282
|
+
})
|
|
283
|
+
|
|
284
|
+
builtinBuffer = device.createBuffer({
|
|
285
|
+
size: builtinData.byteLength,
|
|
286
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
const bindGroupEntries: GPUBindGroupEntry[] = [{ binding: 0, resource: { buffer: builtinBuffer } }]
|
|
290
|
+
if (uniformKeys.length) {
|
|
291
|
+
customData = new Float32Array(uniformKeys.length * 4)
|
|
292
|
+
customBuffer = device.createBuffer({
|
|
293
|
+
size: customData.byteLength,
|
|
294
|
+
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
|
|
295
|
+
})
|
|
296
|
+
bindGroupEntries.push({ binding: 1, resource: { buffer: customBuffer } })
|
|
297
|
+
}
|
|
298
|
+
bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: bindGroupEntries })
|
|
299
|
+
|
|
300
|
+
const validationError = await device.popErrorScope()
|
|
301
|
+
if (validationError) throw new Error(validationError.message)
|
|
302
|
+
},
|
|
303
|
+
resize(width, height) {
|
|
304
|
+
// canvas backing store resize is enough; WebGPU reconfigure not required per-frame
|
|
305
|
+
void width
|
|
306
|
+
void height
|
|
307
|
+
},
|
|
308
|
+
render(time) {
|
|
309
|
+
if (!device || !context || !pipeline || !bindGroup || !builtinBuffer) return
|
|
310
|
+
const canvas = context.canvas as HTMLCanvasElement
|
|
311
|
+
builtinData[0] = time
|
|
312
|
+
builtinData[2] = canvas.width
|
|
313
|
+
builtinData[3] = canvas.height
|
|
314
|
+
builtinData[4] = mouse.x
|
|
315
|
+
builtinData[5] = mouse.y
|
|
316
|
+
builtinData[6] = mouse.down ? mouse.clickX : -mouse.clickX
|
|
317
|
+
builtinData[7] = mouse.down ? mouse.clickY : -mouse.clickY
|
|
318
|
+
builtinData[8] = frameCount
|
|
319
|
+
device.queue.writeBuffer(builtinBuffer, 0, builtinData)
|
|
320
|
+
|
|
321
|
+
if (customBuffer && customData) {
|
|
322
|
+
const values = currentUniformValues()
|
|
323
|
+
uniformKeys.forEach((key, i) => {
|
|
324
|
+
const v = values[key] ?? 0
|
|
325
|
+
const base = i * 4
|
|
326
|
+
if (typeof v === 'number') {
|
|
327
|
+
customData![base] = v
|
|
328
|
+
} else {
|
|
329
|
+
customData![base] = v[0] ?? 0
|
|
330
|
+
customData![base + 1] = v[1] ?? 0
|
|
331
|
+
customData![base + 2] = v[2] ?? 0
|
|
332
|
+
customData![base + 3] = v[3] ?? 0
|
|
333
|
+
}
|
|
334
|
+
})
|
|
335
|
+
device.queue.writeBuffer(customBuffer, 0, customData)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const encoder = device.createCommandEncoder()
|
|
339
|
+
const view = context.getCurrentTexture().createView()
|
|
340
|
+
const pass = encoder.beginRenderPass({
|
|
341
|
+
colorAttachments: [{ view, clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: 'clear', storeOp: 'store' }],
|
|
342
|
+
})
|
|
343
|
+
pass.setPipeline(pipeline)
|
|
344
|
+
pass.setBindGroup(0, bindGroup)
|
|
345
|
+
pass.draw(3)
|
|
346
|
+
pass.end()
|
|
347
|
+
device.queue.submit([encoder.finish()])
|
|
348
|
+
},
|
|
349
|
+
destroy() {
|
|
350
|
+
builtinBuffer?.destroy()
|
|
351
|
+
customBuffer?.destroy()
|
|
352
|
+
device?.destroy()
|
|
353
|
+
context = null
|
|
354
|
+
device = null
|
|
355
|
+
pipeline = null
|
|
356
|
+
bindGroup = null
|
|
357
|
+
},
|
|
358
|
+
raw: () => device,
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/* ── lifecycle / render loop ─────────────────────────────────────────── */
|
|
363
|
+
|
|
364
|
+
function pickRenderer(): 'webgpu' | 'webgl' {
|
|
365
|
+
if (props.renderer === 'webgl') return 'webgl'
|
|
366
|
+
if (props.renderer === 'webgpu') return 'webgpu'
|
|
367
|
+
return typeof navigator !== 'undefined' && !!navigator.gpu && props.wgsl ? 'webgpu' : 'webgl'
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function tick(now: number) {
|
|
371
|
+
if (!running || !visible) return
|
|
372
|
+
const time = (now - startTime) / 1000 + pausedElapsed
|
|
373
|
+
frameCount++
|
|
374
|
+
backend?.render(time, frameCount)
|
|
375
|
+
rafId = requestAnimationFrame(tick)
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function startLoop() {
|
|
379
|
+
if (rafId || !running || !visible || status.value !== 'ready') return
|
|
380
|
+
startTime = performance.now()
|
|
381
|
+
rafId = requestAnimationFrame(tick)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function stopLoop(keepElapsed = true) {
|
|
385
|
+
if (rafId) cancelAnimationFrame(rafId)
|
|
386
|
+
rafId = 0
|
|
387
|
+
if (keepElapsed && startTime) {
|
|
388
|
+
pausedElapsed += (performance.now() - startTime) / 1000
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function setup() {
|
|
393
|
+
const canvas = canvasRef.value
|
|
394
|
+
const container = containerRef.value
|
|
395
|
+
if (!canvas || !container) return
|
|
396
|
+
|
|
397
|
+
status.value = 'loading'
|
|
398
|
+
uniformKeys = Object.keys(props.uniforms ?? {})
|
|
399
|
+
|
|
400
|
+
const wanted = pickRenderer()
|
|
401
|
+
if (wanted === 'webgpu' && !props.wgsl) {
|
|
402
|
+
status.value = 'error'
|
|
403
|
+
errorMessage.value = 'renderer="webgpu" was forced but no `wgsl` prop was provided.'
|
|
404
|
+
emit('error', errorMessage.value)
|
|
405
|
+
return
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
backend = wanted === 'webgpu' ? createWebGPUBackend() : createWebGLBackend()
|
|
409
|
+
|
|
410
|
+
async function finish(name: 'webgpu' | 'webgl') {
|
|
411
|
+
activeRenderer.value = name
|
|
412
|
+
resize()
|
|
413
|
+
status.value = 'ready'
|
|
414
|
+
running = !props.paused
|
|
415
|
+
startLoop()
|
|
416
|
+
emit('ready', name)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
try {
|
|
420
|
+
await backend.init(canvas)
|
|
421
|
+
await finish(wanted)
|
|
422
|
+
} catch (err) {
|
|
423
|
+
// Only silently downgrade when WebGPU itself is unavailable in 'auto' mode — a broken WGSL
|
|
424
|
+
// shader should surface as an error, not get quietly masked by a fallback render.
|
|
425
|
+
if (wanted === 'webgpu' && props.renderer === 'auto' && err instanceof UnsupportedError) {
|
|
426
|
+
backend = createWebGLBackend()
|
|
427
|
+
try {
|
|
428
|
+
await backend.init(canvas)
|
|
429
|
+
await finish('webgl')
|
|
430
|
+
return
|
|
431
|
+
} catch (fallbackErr) {
|
|
432
|
+
setFailure(fallbackErr)
|
|
433
|
+
return
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
setFailure(err)
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function setFailure(err: unknown) {
|
|
441
|
+
errorMessage.value = err instanceof Error ? err.message : String(err)
|
|
442
|
+
status.value = err instanceof UnsupportedError ? 'fallback' : 'error'
|
|
443
|
+
emit('error', errorMessage.value)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function resize() {
|
|
447
|
+
const canvas = canvasRef.value
|
|
448
|
+
const container = containerRef.value
|
|
449
|
+
if (!canvas || !container) return
|
|
450
|
+
const ratio = effectivePixelRatio()
|
|
451
|
+
const width = Math.max(1, Math.round(container.clientWidth * ratio))
|
|
452
|
+
const height = Math.max(1, Math.round(container.clientHeight * ratio))
|
|
453
|
+
if (canvas.width !== width || canvas.height !== height) {
|
|
454
|
+
canvas.width = width
|
|
455
|
+
canvas.height = height
|
|
456
|
+
backend?.resize(width, height)
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function teardown(final = false) {
|
|
461
|
+
stopLoop(false)
|
|
462
|
+
backend?.destroy(final)
|
|
463
|
+
backend = null
|
|
464
|
+
activeRenderer.value = null
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function onPointerMove(e: PointerEvent) {
|
|
468
|
+
const canvas = canvasRef.value
|
|
469
|
+
if (!canvas) return
|
|
470
|
+
const rect = canvas.getBoundingClientRect()
|
|
471
|
+
const ratio = effectivePixelRatio()
|
|
472
|
+
mouse.x = (e.clientX - rect.left) * ratio
|
|
473
|
+
mouse.y = (rect.height - (e.clientY - rect.top)) * ratio
|
|
474
|
+
}
|
|
475
|
+
function onPointerDown(e: PointerEvent) {
|
|
476
|
+
onPointerMove(e)
|
|
477
|
+
mouse.down = true
|
|
478
|
+
mouse.clickX = mouse.x
|
|
479
|
+
mouse.clickY = mouse.y
|
|
480
|
+
}
|
|
481
|
+
function onPointerUp() {
|
|
482
|
+
mouse.down = false
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
onMounted(async () => {
|
|
486
|
+
const canvas = canvasRef.value!
|
|
487
|
+
canvas.addEventListener('pointermove', onPointerMove)
|
|
488
|
+
canvas.addEventListener('pointerdown', onPointerDown)
|
|
489
|
+
window.addEventListener('pointerup', onPointerUp)
|
|
490
|
+
|
|
491
|
+
resizeObserver = new ResizeObserver(() => resize())
|
|
492
|
+
resizeObserver.observe(containerRef.value!)
|
|
493
|
+
|
|
494
|
+
intersectionObserver = new IntersectionObserver(([entry]) => {
|
|
495
|
+
visible = !!entry?.isIntersecting
|
|
496
|
+
if (visible) startLoop()
|
|
497
|
+
else stopLoop()
|
|
498
|
+
})
|
|
499
|
+
intersectionObserver.observe(containerRef.value!)
|
|
500
|
+
|
|
501
|
+
await setup()
|
|
502
|
+
})
|
|
503
|
+
|
|
504
|
+
onBeforeUnmount(() => {
|
|
505
|
+
const canvas = canvasRef.value
|
|
506
|
+
canvas?.removeEventListener('pointermove', onPointerMove)
|
|
507
|
+
canvas?.removeEventListener('pointerdown', onPointerDown)
|
|
508
|
+
window.removeEventListener('pointerup', onPointerUp)
|
|
509
|
+
resizeObserver?.disconnect()
|
|
510
|
+
intersectionObserver?.disconnect()
|
|
511
|
+
teardown(true)
|
|
512
|
+
})
|
|
513
|
+
|
|
514
|
+
watch(
|
|
515
|
+
[() => props.code, () => props.wgsl, () => props.renderer],
|
|
516
|
+
async () => {
|
|
517
|
+
teardown()
|
|
518
|
+
await setup()
|
|
519
|
+
},
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
watch(
|
|
523
|
+
() => props.paused,
|
|
524
|
+
(isPaused) => {
|
|
525
|
+
running = !isPaused
|
|
526
|
+
if (running) startLoop()
|
|
527
|
+
else stopLoop()
|
|
528
|
+
},
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
defineExpose({
|
|
532
|
+
canvas: canvasRef,
|
|
533
|
+
/** 'webgpu' | 'webgl' | null — which backend is actually driving the canvas right now. */
|
|
534
|
+
renderer: activeRenderer,
|
|
535
|
+
status,
|
|
536
|
+
/** Raw WebGL2RenderingContext or GPUDevice, for consumers who want to go beyond the props API. */
|
|
537
|
+
context: () => backend?.raw() ?? null,
|
|
538
|
+
pause: () => {
|
|
539
|
+
running = false
|
|
540
|
+
stopLoop()
|
|
541
|
+
},
|
|
542
|
+
play: () => {
|
|
543
|
+
running = true
|
|
544
|
+
startLoop()
|
|
545
|
+
},
|
|
546
|
+
restart: async () => {
|
|
547
|
+
pausedElapsed = 0
|
|
548
|
+
frameCount = 0
|
|
549
|
+
teardown()
|
|
550
|
+
await setup()
|
|
551
|
+
},
|
|
552
|
+
})
|
|
553
|
+
</script>
|
|
554
|
+
|
|
555
|
+
<template>
|
|
556
|
+
<div ref="containerRef" class="relative h-full w-full overflow-hidden">
|
|
557
|
+
<canvas ref="canvasRef" class="block h-full w-full touch-none" />
|
|
558
|
+
|
|
559
|
+
<div v-if="status === 'loading'" class="absolute inset-0 flex items-center justify-center">
|
|
560
|
+
<slot name="loading">
|
|
561
|
+
<MSpinner />
|
|
562
|
+
</slot>
|
|
563
|
+
</div>
|
|
564
|
+
|
|
565
|
+
<div v-else-if="status === 'fallback'" class="absolute inset-0 flex items-center justify-center p-4">
|
|
566
|
+
<slot name="fallback">
|
|
567
|
+
<p class="text-center text-body-medium text-on-surface-variant">
|
|
568
|
+
Shaders are not supported in this browser.
|
|
569
|
+
</p>
|
|
570
|
+
</slot>
|
|
571
|
+
</div>
|
|
572
|
+
|
|
573
|
+
<div v-else-if="status === 'error'" class="absolute inset-0 flex items-center justify-center overflow-auto p-4">
|
|
574
|
+
<slot name="error" :message="errorMessage">
|
|
575
|
+
<pre class="max-h-full w-full overflow-auto whitespace-pre-wrap text-body-small text-error">{{ errorMessage }}</pre>
|
|
576
|
+
</slot>
|
|
577
|
+
</div>
|
|
578
|
+
</div>
|
|
579
|
+
</template>
|
package/src/index.ts
CHANGED
|
@@ -109,6 +109,8 @@ export { default as MSection } from './components/MSection.vue'
|
|
|
109
109
|
export { default as MSegmentedButton } from './components/MSegmentedButton.vue'
|
|
110
110
|
export { default as MSelect } from './components/MSelect.vue'
|
|
111
111
|
export type { SelectOption } from './components/MSelect.vue'
|
|
112
|
+
export { default as MShader } from './components/MShader.vue'
|
|
113
|
+
export type { ShaderRenderer, ShaderStatus } from './components/MShader.vue'
|
|
112
114
|
export { default as MSideSheet } from './components/MSideSheet.vue'
|
|
113
115
|
export { default as MSkeleton } from './components/MSkeleton.vue'
|
|
114
116
|
export { default as MSlider } from './components/MSlider.vue'
|