-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfft.js
More file actions
491 lines (402 loc) · 16.4 KB
/
fft.js
File metadata and controls
491 lines (402 loc) · 16.4 KB
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
/**
* WebGL 2D FFT実装
* 波動光学計算用の高速フーリエ変換
*/
class WebGLFFT {
constructor(webglUtils) {
this.gl = webglUtils.gl;
this.utils = webglUtils;
this.size = 0;
this.logSize = 0;
this.programs = new Map();
this.butterflyTexture = null;
this.tempTextures = [];
this.initialized = false;
}
/**
* FFTシステムを初期化
* @param {number} size FFTサイズ (2の冪乗)
*/
initialize(size) {
if (!this.isPowerOfTwo(size)) {
throw new Error('FFTサイズは2の冪乗である必要があります');
}
this.size = size;
this.logSize = Math.log2(size);
// バタフライテクスチャは不要 (シェーダーで直接計算)
this.createPrograms();
this.createTempTextures();
this.initialized = true;
console.log(`WebGL FFT initialized for size ${size}x${size}`);
}
/**
* 数値が2の冪乗かチェック
* @param {number} n
* @returns {boolean}
*/
isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
/**
* バタフライテクスチャを作成
* FFTの各段階で使用される係数を事前計算
*/
createButterflyTexture() {
const gl = this.gl;
const data = new Float32Array(this.size * this.logSize * 4);
let offset = 0;
for (let stage = 0; stage < this.logSize; stage++) {
const butterflyWidth = 1 << (stage + 1);
const butterflyHeight = this.size / butterflyWidth;
for (let y = 0; y < butterflyHeight; y++) {
for (let x = 0; x < this.size; x++) {
const butterflyX = x % butterflyWidth;
const isPingPong = Math.floor(x / butterflyWidth) % 2;
if (butterflyX < butterflyWidth / 2) {
// バタフライの左半分
const twiddle = -2.0 * Math.PI * butterflyX / butterflyWidth;
const twiddleReal = Math.cos(twiddle);
const twiddleImag = Math.sin(twiddle);
const sourceX = isPingPong ?
butterflyX + butterflyWidth / 2 :
butterflyX;
data[offset + 0] = twiddleReal;
data[offset + 1] = twiddleImag;
data[offset + 2] = sourceX;
data[offset + 3] = y;
} else {
// バタフライの右半分
const sourceX = isPingPong ?
butterflyX - butterflyWidth / 2 :
butterflyX;
data[offset + 0] = 1.0;
data[offset + 1] = 0.0;
data[offset + 2] = sourceX;
data[offset + 3] = y;
}
offset += 4;
}
}
}
this.butterflyTexture = this.utils.createTexture(
this.size, this.logSize,
gl.RGBA32F, gl.RGBA, gl.FLOAT,
data, 'butterfly'
);
}
/**
* FFT用のシェーダープログラムを作成
*/
createPrograms() {
const gl = this.gl;
// ビットリバーサルパス用
const bitReversalFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_input;
uniform int u_size;
uniform bool u_horizontal;
out vec4 fragColor;
int bitReverse(int x, int logSize) {
int result = 0;
for (int i = 0; i < 16; i++) {
if (i >= logSize) break;
if ((x & (1 << i)) != 0) {
result |= (1 << (logSize - 1 - i));
}
}
return result;
}
void main() {
ivec2 coord = ivec2(v_texCoord * float(u_size));
int logSize = int(log2(float(u_size)));
if (u_horizontal) {
int reversedX = bitReverse(coord.x, logSize);
fragColor = texelFetch(u_input, ivec2(reversedX, coord.y), 0);
} else {
int reversedY = bitReverse(coord.y, logSize);
fragColor = texelFetch(u_input, ivec2(coord.x, reversedY), 0);
}
}
`;
// バタフライパス用
const butterflyFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_input;
uniform int u_stage;
uniform int u_size;
uniform bool u_inverse;
out vec4 fragColor;
${CommonShaders.complexUtils}
void main() {
ivec2 coord = ivec2(v_texCoord * float(u_size));
int logSize = int(log2(float(u_size)));
// FFT段階のサイズを計算
int stageSize = 1 << (u_stage + 1);
int halfStageSize = stageSize >> 1;
// バタフライの位置を計算
int butterflyIndex = coord.x % stageSize;
bool isUpperHalf = butterflyIndex < halfStageSize;
// ペアの位置を計算
int pairOffset = isUpperHalf ? halfStageSize : -halfStageSize;
ivec2 pairCoord = ivec2(coord.x + pairOffset, coord.y);
// 現在の値とペアの値を取得
vec2 current = texture(u_input, v_texCoord).rg;
vec2 pair = texelFetch(u_input, pairCoord, 0).rg;
// ツイッドル因子を計算
float angle = -2.0 * 3.14159265 * float(butterflyIndex % halfStageSize) / float(stageSize);
if (u_inverse) {
angle = -angle;
}
vec2 twiddle = vec2(cos(angle), sin(angle));
// バタフライ演算
vec2 result;
if (isUpperHalf) {
vec2 product = cmul(pair, twiddle);
result = current + product;
} else {
vec2 product = cmul(current, twiddle);
result = pair - product;
}
fragColor = vec4(result.x, result.y, 0.0, 1.0);
}
`;
// 正規化パス用
const normalizeFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_input;
uniform float u_scale;
out vec4 fragColor;
void main() {
vec4 data = texture(u_input, v_texCoord);
fragColor = data * u_scale;
}
`;
// プログラム作成
this.programs.set('bitReversal',
this.utils.createProgram(CommonShaders.vertexShader, bitReversalFragment));
this.programs.set('butterfly',
this.utils.createProgram(CommonShaders.vertexShader, butterflyFragment));
this.programs.set('normalize',
this.utils.createProgram(CommonShaders.vertexShader, normalizeFragment));
}
/**
* 一時テクスチャを作成
*/
createTempTextures() {
const gl = this.gl;
// ping-pong用に2つの複素テクスチャペアを作成
for (let i = 0; i < 2; i++) {
this.tempTextures.push({
real: this.utils.createTexture(
this.size, this.size,
gl.R32F, gl.RED, gl.FLOAT,
null, `temp${i}_real`
),
imag: this.utils.createTexture(
this.size, this.size,
gl.R32F, gl.RED, gl.FLOAT,
null, `temp${i}_imag`
)
});
}
}
/**
* 複素テクスチャペアをパックしてRGBAテクスチャに変換
* @param {WebGLTexture} realTexture
* @param {WebGLTexture} imagTexture
* @returns {WebGLTexture}
*/
packComplexTexture(realTexture, imagTexture) {
const gl = this.gl;
const packFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_real;
uniform sampler2D u_imag;
out vec4 fragColor;
void main() {
float real = texture(u_real, v_texCoord).r;
float imag = texture(u_imag, v_texCoord).r;
// RGBAにパック (実部をRに、虚部をGに)
fragColor = vec4(real, imag, 0.0, 1.0);
}
`;
const program = this.utils.createProgram(CommonShaders.vertexShader, packFragment);
const outputTexture = this.utils.createTexture(
this.size, this.size,
gl.RGBA32F, gl.RGBA, gl.FLOAT
);
const framebuffer = this.utils.createFramebuffer(outputTexture);
const quad = this.utils.createFullscreenQuad();
this.utils.renderPass(program, framebuffer, {
u_real: realTexture,
u_imag: imagTexture
}, quad);
return outputTexture;
}
/**
* RGBAテクスチャを複素テクスチャペアにアンパック
* @param {WebGLTexture} packedTexture
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
unpackComplexTexture(packedTexture) {
const gl = this.gl;
const unpackFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_packed;
uniform int u_component; // 0: real, 1: imag
out vec4 fragColor;
void main() {
vec4 packed = texture(u_packed, v_texCoord);
float value = (u_component == 0) ? packed.r : packed.g;
fragColor = vec4(value, 0.0, 0.0, 1.0);
}
`;
const program = this.utils.createProgram(CommonShaders.vertexShader, unpackFragment);
const quad = this.utils.createFullscreenQuad();
const realTexture = this.utils.createTexture(
this.size, this.size, gl.R32F, gl.RED, gl.FLOAT);
const imagTexture = this.utils.createTexture(
this.size, this.size, gl.R32F, gl.RED, gl.FLOAT);
const realFramebuffer = this.utils.createFramebuffer(realTexture);
const imagFramebuffer = this.utils.createFramebuffer(imagTexture);
// 実部を抽出
this.utils.renderPass(program, realFramebuffer, {
u_packed: packedTexture,
u_component: 0
}, quad);
// 虚部を抽出
this.utils.renderPass(program, imagFramebuffer, {
u_packed: packedTexture,
u_component: 1
}, quad);
return { real: realTexture, imag: imagTexture };
}
/**
* 1D FFTを実行 (横方向または縦方向)
* @param {WebGLTexture} inputTexture
* @param {boolean} horizontal
* @param {boolean} inverse
* @returns {WebGLTexture}
*/
fft1D(inputTexture, horizontal = true, inverse = false) {
if (!this.initialized) {
throw new Error('FFTが初期化されていません');
}
const gl = this.gl;
const quad = this.utils.createFullscreenQuad();
let currentTexture = inputTexture;
let nextTexture = this.utils.createTexture(
this.size, this.size, gl.RGBA32F, gl.RGBA, gl.FLOAT);
// ビットリバーサル
const bitReversalFB = this.utils.createFramebuffer(nextTexture);
this.utils.renderPass(this.programs.get('bitReversal'), bitReversalFB, {
u_input: currentTexture,
u_size: this.size,
u_horizontal: horizontal
}, quad);
[currentTexture, nextTexture] = [nextTexture, currentTexture];
// バタフライパス
for (let stage = 0; stage < this.logSize; stage++) {
const framebuffer = this.utils.createFramebuffer(nextTexture);
this.utils.renderPass(this.programs.get('butterfly'), framebuffer, {
u_input: currentTexture,
u_stage: stage,
u_size: this.size,
u_inverse: inverse
}, quad);
[currentTexture, nextTexture] = [nextTexture, currentTexture];
}
// 逆変換の場合は正規化
if (inverse) {
const normalizedTexture = this.utils.createTexture(
this.size, this.size, gl.RGBA32F, gl.RGBA, gl.FLOAT);
const normalizeFB = this.utils.createFramebuffer(normalizedTexture);
this.utils.renderPass(this.programs.get('normalize'), normalizeFB, {
u_input: currentTexture,
u_scale: 1.0 / this.size
}, quad);
return normalizedTexture;
}
return currentTexture;
}
/**
* 2D FFTを実行
* @param {{real: WebGLTexture, imag: WebGLTexture}} inputPair
* @param {boolean} inverse
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
fft2D(inputPair, inverse = false) {
// 複素テクスチャペアをパック
const packedInput = this.packComplexTexture(inputPair.real, inputPair.imag);
// 横方向FFT
const horizontalFFT = this.fft1D(packedInput, true, inverse);
// 縦方向FFT
const verticalFFT = this.fft1D(horizontalFFT, false, inverse);
// 結果をアンパック
return this.unpackComplexTexture(verticalFFT);
}
/**
* 周波数シフト (FFTshift相当)
* @param {{real: WebGLTexture, imag: WebGLTexture}} inputPair
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
fftShift(inputPair) {
const gl = this.gl;
const shiftFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_input;
uniform int u_size;
out vec4 fragColor;
void main() {
ivec2 coord = ivec2(v_texCoord * float(u_size));
int halfSize = u_size / 2;
ivec2 shiftedCoord = coord;
shiftedCoord.x = (coord.x + halfSize) % u_size;
shiftedCoord.y = (coord.y + halfSize) % u_size;
fragColor = texelFetch(u_input, shiftedCoord, 0);
}
`;
const program = this.utils.createProgram(CommonShaders.vertexShader, shiftFragment);
const quad = this.utils.createFullscreenQuad();
const realOutput = this.utils.createTexture(
this.size, this.size, gl.R32F, gl.RED, gl.FLOAT);
const imagOutput = this.utils.createTexture(
this.size, this.size, gl.R32F, gl.RED, gl.FLOAT);
const realFB = this.utils.createFramebuffer(realOutput);
const imagFB = this.utils.createFramebuffer(imagOutput);
this.utils.renderPass(program, realFB, {
u_input: inputPair.real,
u_size: this.size
}, quad);
this.utils.renderPass(program, imagFB, {
u_input: inputPair.imag,
u_size: this.size
}, quad);
return { real: realOutput, imag: imagOutput };
}
/**
* リソースをクリーンアップ
*/
cleanup() {
const gl = this.gl;
if (this.butterflyTexture) {
gl.deleteTexture(this.butterflyTexture);
}
for (const texturePair of this.tempTextures) {
gl.deleteTexture(texturePair.real);
gl.deleteTexture(texturePair.imag);
}
for (const program of this.programs.values()) {
gl.deleteProgram(program);
}
this.tempTextures = [];
this.programs.clear();
this.initialized = false;
}
}