-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaveoptics.js
More file actions
640 lines (545 loc) · 17.6 KB
/
waveoptics.js
File metadata and controls
640 lines (545 loc) · 17.6 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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/**
* 波動光学計算エンジン
* Fresnel積分、Fraunhofer近似、角スペクトル法による回折計算
*/
class WaveOpticsEngine {
constructor() {
this.webglUtils = new WebGLUtils();
this.shaderLoader = new ShaderLoader();
this.fft = null;
this.colorConverter = null;
this.gl = null;
this.canvas = null;
this.programs = new Map();
this.initialized = false;
// 計算パラメータ
this.params = {
resolution: 512,
aperture_size: 0.01, // m
screen_distance: 2.0, // m
source_distance: 1.0, // m
wavelength: 550e-9, // m
light_source: "point", // 'point' or 'plane'
incident_angle: [0, 0], // rad
calculation_method: "fresnel",
zero_padding: 2,
exposure: 1.0,
gamma: 2.2,
};
}
/**
* WebGLキャンバスで初期化
* @param {HTMLCanvasElement} canvas
*/
async initialize(canvas) {
this.canvas = canvas;
this.gl = this.webglUtils.initializeWebGL(canvas);
if (!this.gl) {
throw new Error("WebGL2の初期化に失敗しました");
}
// シェーダーローダー初期化
await this.shaderLoader.initialize();
// FFTシステム初期化
this.fft = new WebGLFFT(this.webglUtils);
this.fft.initialize(this.params.resolution);
// 色変換システム初期化
this.colorConverter = new ColorConversion(this.webglUtils);
this.colorConverter.initialize();
// シェーダープログラム作成
const shaderPrograms = await this.createPrograms();
// 色変換プログラムを設定 (shader-loaderから作成されたプログラムを直接使用)
this.colorConverter.setPrograms(shaderPrograms);
this.initialized = true;
console.log("Wave optics engine initialized");
}
/**
* 波動光学計算用シェーダープログラムを作成
*/
async createPrograms() {
try {
// シェーダーローダーでプログラムを作成
const shaderPrograms = await this.shaderLoader.createAllPrograms(
this.gl,
this.webglUtils
);
// プログラムマップに追加
for (const [name, program] of Object.entries(shaderPrograms)) {
this.programs.set(name, program);
}
console.log("Wave optics shader programs created");
return shaderPrograms; // Objectを返す
} catch (error) {
console.error("Failed to create wave optics programs:", error);
throw error;
}
}
/**
* パラメータを更新
* @param {Object} newParams
*/
updateParameters(newParams) {
Object.assign(this.params, newParams);
}
/**
* アパーチャテクスチャを前処理
* @param {WebGLTexture} apertureTexture
* @returns {WebGLTexture}
*/
preprocessAperture(apertureTexture) {
// アパーチャは既にCanvas 2Dから適切な形式で取得されているため
// 前処理は不要で、そのまま返す
return apertureTexture;
}
/**
* 入射波を生成
* @param {WebGLTexture} apertureTexture
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
generateIncidentWave(apertureTexture) {
const gl = this.gl;
const quad = this.webglUtils.createFullscreenQuad();
let program;
let uniforms;
if (this.params.light_source === "point") {
program = this.programs.get("pointSource");
uniforms = {
u_wavelength: this.params.wavelength,
u_sourceDistance: this.params.source_distance,
u_apertureSize: this.params.aperture_size,
u_resolution: this.params.resolution,
};
} else {
program = this.programs.get("planeWave");
uniforms = {
u_wavelength: this.params.wavelength,
u_apertureSize: this.params.aperture_size,
u_incidentAngle: this.params.incident_angle,
u_resolution: this.params.resolution,
};
}
// 複素振幅を計算 (RGBAテクスチャに実部・虚部)
const complexTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.RGBA32F,
gl.RGBA,
gl.FLOAT
);
const framebuffer = this.webglUtils.createFramebuffer(complexTexture);
this.webglUtils.renderPass(program, framebuffer, uniforms, quad);
// 実部と虚部を分離
const incidentField = this.separateComplexChannels(complexTexture);
// アパーチャ透過を適用
const transmittedField = this.applyApertureTransmission(
incidentField,
apertureTexture
);
return transmittedField;
}
/**
* アパーチャ透過を適用
* @param {{real: WebGLTexture, imag: WebGLTexture}} incidentField
* @param {WebGLTexture} apertureTexture
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
applyApertureTransmission(incidentField, apertureTexture) {
const gl = this.gl;
const program = this.programs.get("apertureTransmission");
const quad = this.webglUtils.createFullscreenQuad();
// RGBAテクスチャに出力
const complexTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.RGBA32F,
gl.RGBA,
gl.FLOAT
);
const framebuffer = this.webglUtils.createFramebuffer(complexTexture);
const uniforms = {
u_incidentReal: incidentField.real,
u_incidentImag: incidentField.imag,
u_aperture: apertureTexture,
u_apertureSize: this.params.aperture_size,
u_resolution: this.params.resolution,
};
this.webglUtils.renderPass(program, framebuffer, uniforms, quad);
// 実部と虚部を分離
return this.separateComplexChannels(complexTexture);
}
/**
* RGBAテクスチャのRG チャンネルを実部・虚部として分離
* @param {WebGLTexture} complexTexture
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
separateComplexChannels(complexTexture) {
const gl = this.gl;
const separateFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_complex;
uniform int u_component; // 0: real, 1: imag
out vec4 fragColor;
void main() {
vec4 complex = texture(u_complex, v_texCoord);
float value = (u_component == 0) ? complex.r : complex.g;
fragColor = vec4(value, 0.0, 0.0, 1.0);
}
`;
const program = this.webglUtils.createProgram(
CommonShaders.vertexShader,
separateFragment
);
const quad = this.webglUtils.createFullscreenQuad();
const realTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.R32F,
gl.RED,
gl.FLOAT
);
const imagTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.R32F,
gl.RED,
gl.FLOAT
);
const realFB = this.webglUtils.createFramebuffer(realTexture);
const imagFB = this.webglUtils.createFramebuffer(imagTexture);
// 実部を抽出
this.webglUtils.renderPass(
program,
realFB,
{
u_complex: complexTexture,
u_component: 0,
},
quad
);
// 虚部を抽出
this.webglUtils.renderPass(
program,
imagFB,
{
u_complex: complexTexture,
u_component: 1,
},
quad
);
return { real: realTexture, imag: imagTexture };
}
/**
* 複素テクスチャを実部と虚部に分離 (旧バージョン)
* @param {WebGLTexture} complexTexture
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
separateComplexTexture(complexTexture) {
const gl = this.gl;
const separateFragment = `#version 300 es
precision highp float;
in vec2 v_texCoord;
uniform sampler2D u_complex;
uniform int u_component; // 0: real, 1: imag
out vec4 fragColor;
void main() {
vec4 complex = texture(u_complex, v_texCoord);
float value = (u_component == 0) ? complex.r : complex.g;
fragColor = vec4(value, 0.0, 0.0, 1.0);
}
`;
const program = this.webglUtils.createProgram(
CommonShaders.vertexShader,
separateFragment
);
const quad = this.webglUtils.createFullscreenQuad();
const realTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.R32F,
gl.RED,
gl.FLOAT
);
const imagTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.R32F,
gl.RED,
gl.FLOAT
);
const realFB = this.webglUtils.createFramebuffer(realTexture);
const imagFB = this.webglUtils.createFramebuffer(imagTexture);
// 実部を抽出
this.webglUtils.renderPass(
program,
realFB,
{
u_complex: complexTexture,
u_component: 0,
},
quad
);
// 虚部を抽出
this.webglUtils.renderPass(
program,
imagFB,
{
u_complex: complexTexture,
u_component: 1,
},
quad
);
return { real: realTexture, imag: imagTexture };
}
/**
* 波動伝搬計算を実行 (Angular Spectrum法に統一)
* @param {{real: WebGLTexture, imag: WebGLTexture}} apertureField
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
propagateWave(apertureField) {
// Angular Spectrum法に統一 (最も汎用的で厳密)
return this.calculateAngularSpectrum(apertureField);
}
/**
* Fresnel積分による伝搬計算
* @param {{real: WebGLTexture, imag: WebGLTexture}} apertureField
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
calculateFresnel(apertureField) {
// 1. 前段階位相因子を適用
const prePhaseField = this.applyFresnelPhase(apertureField, true);
// 2. 2D FFT
const fftResult = this.fft.fft2D(prePhaseField);
// 3. 後段階位相因子を適用
const postPhaseField = this.applyFresnelPhase(fftResult, false);
return postPhaseField;
}
/**
* Fraunhofer近似による伝搬計算
* @param {{real: WebGLTexture, imag: WebGLTexture}} apertureField
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
calculateFraunhofer(apertureField) {
// Fraunhofer近似は単純にFFTを取るだけ
return this.fft.fft2D(apertureField);
}
/**
* 角スペクトル法による伝搬計算
* @param {{real: WebGLTexture, imag: WebGLTexture}} apertureField
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
calculateAngularSpectrum(apertureField) {
// 2D FFT
const spectrum = this.fft.fft2D(apertureField);
// 伝搬カーネル適用
const propagatedSpectrum = this.applyAngularSpectrumKernel(spectrum);
// 逆FFT
const screenField = this.fft.fft2D(propagatedSpectrum, true);
return screenField;
}
/**
* Fresnel位相因子を適用
* @param {{real: WebGLTexture, imag: WebGLTexture}} field
* @param {boolean} isPrePhase
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
applyFresnelPhase(field, isPrePhase) {
const gl = this.gl;
const program = this.programs.get("fresnelPhase");
const quad = this.webglUtils.createFullscreenQuad();
// 出力用複素テクスチャペアを作成
const outputField = this.webglUtils.createComplexTexturePair(
this.params.resolution,
this.params.resolution,
isPrePhase ? "pre_phase" : "post_phase"
);
const uniforms = {
u_inputReal: field.real,
u_inputImag: field.imag,
u_wavelength: this.params.wavelength,
u_screenDistance: this.params.screen_distance,
u_apertureSize: this.params.aperture_size,
u_isPrePhase: isPrePhase,
u_resolution: this.params.resolution,
};
// 実部の処理
const realFramebuffer = this.webglUtils.createFramebuffer(outputField.real);
this.webglUtils.renderPass(program, realFramebuffer, uniforms, quad);
// 虚部の処理
const imagFramebuffer = this.webglUtils.createFramebuffer(outputField.imag);
this.webglUtils.renderPass(program, imagFramebuffer, uniforms, quad);
return outputField;
}
/**
* 角スペクトル法の伝搬カーネルを適用
* @param {{real: WebGLTexture, imag: WebGLTexture}} spectrum
* @returns {{real: WebGLTexture, imag: WebGLTexture}}
*/
applyAngularSpectrumKernel(spectrum) {
const gl = this.gl;
const program = this.programs.get("angularSpectrum");
const quad = this.webglUtils.createFullscreenQuad();
// 複素数を一度に処理するためのRGBAテクスチャを作成
const complexTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.RGBA32F,
gl.RGBA,
gl.FLOAT
);
const framebuffer = this.webglUtils.createFramebuffer(complexTexture);
const uniforms = {
u_spectrumReal: spectrum.real,
u_spectrumImag: spectrum.imag,
u_wavelength: this.params.wavelength,
u_screenDistance: this.params.screen_distance,
u_apertureSize: this.params.aperture_size,
u_resolution: this.params.resolution,
};
// 一度の実行で実部・虚部をまとめて処理
this.webglUtils.renderPass(program, framebuffer, uniforms, quad);
// 結果を実部・虚部に分離
return this.separateComplexChannels(complexTexture);
}
/**
* 強度を計算
* @param {{real: WebGLTexture, imag: WebGLTexture}} field
* @param {number} scale
* @param {boolean} logScale 対数スケール表示
* @returns {WebGLTexture}
*/
calculateIntensity(field, scale = 1.0, logScale = false) {
const gl = this.gl;
const program = this.programs.get("intensity");
const quad = this.webglUtils.createFullscreenQuad();
const intensityTexture = this.webglUtils.createTexture(
this.params.resolution,
this.params.resolution,
gl.R32F,
gl.RED,
gl.FLOAT
);
const framebuffer = this.webglUtils.createFramebuffer(intensityTexture);
const uniforms = {
u_real: field.real,
u_imag: field.imag,
u_scale: scale,
u_logScale: logScale,
};
this.webglUtils.renderPass(program, framebuffer, uniforms, quad);
return intensityTexture;
}
/**
* メイン計算実行
* @param {WebGLTexture} apertureTexture
* @param {Array<number>} wavelengths
* @returns {WebGLTexture} 最終的な色画像
*/
async calculate(apertureTexture, wavelengths = null) {
if (!this.initialized) {
throw new Error("エンジンが初期化されていません");
}
const startTime = performance.now();
// 単色光の場合
if (!wavelengths) {
wavelengths = [this.params.wavelength];
}
const spectrumData = [];
for (const wavelength of wavelengths) {
// パラメータを一時的に更新
const originalWavelength = this.params.wavelength;
this.params.wavelength = wavelength;
// アパーチャ前処理
const processedAperture = this.preprocessAperture(apertureTexture);
// 入射波生成
const incidentField = this.generateIncidentWave(processedAperture);
// 波動伝搬
const screenField = this.propagateWave(incidentField);
// 強度計算
const intensity = this.calculateIntensity(
screenField,
this.params.exposure
);
spectrumData.push({
wavelength: wavelength,
texture: intensity,
weight: 1.0,
});
// パラメータ復元
this.params.wavelength = originalWavelength;
}
// 色変換
let finalTexture;
if (spectrumData.length === 1) {
// 単色光
finalTexture = this.colorConverter.convertMonochromaticToColor(
spectrumData[0].texture,
spectrumData[0].wavelength * 1e9, // m → nm
this.params.exposure * 5.0 // 輝度調整
);
} else {
// 多色光
const xyzTexture = this.colorConverter.convertSpectrumToXYZ(
spectrumData,
this.params.resolution,
this.params.resolution
);
finalTexture = this.colorConverter.convertXYZToSRGB(
xyzTexture,
this.params.exposure,
this.params.gamma
);
}
const endTime = performance.now();
console.log(
`Calculation completed in ${(endTime - startTime).toFixed(2)}ms`
);
return finalTexture;
}
/**
* 計算統計を取得
* @returns {Object}
*/
getCalculationStats() {
const fresnelNumber =
(this.params.aperture_size * this.params.aperture_size) /
(4 * this.params.wavelength * this.params.screen_distance);
const diffraction_limit =
(1.22 * this.params.wavelength * this.params.screen_distance) /
this.params.aperture_size;
const memory_usage = this.estimateMemoryUsage();
return {
fresnel_number: fresnelNumber,
diffraction_limit: diffraction_limit,
memory_usage: memory_usage,
resolution: this.params.resolution,
calculation_method: this.params.calculation_method,
};
}
/**
* メモリ使用量推定
* @returns {string}
*/
estimateMemoryUsage() {
const textureCount = 10; // 概算
const bytesPerPixel = 16; // RGBA32F
const totalBytes =
this.params.resolution *
this.params.resolution *
bytesPerPixel *
textureCount;
return `${(totalBytes / 1024 / 1024).toFixed(1)} MB`;
}
/**
* リソースをクリーンアップ
*/
cleanup() {
if (this.fft) {
this.fft.cleanup();
}
if (this.colorConverter) {
this.colorConverter.cleanup();
}
this.webglUtils.cleanup();
this.initialized = false;
}
}