feat: 纹理路径稳定 ID 与架构改进 (#305)
* feat(asset-system): 实现路径稳定 ID 生成器 使用 FNV-1a hash 算法为纹理生成稳定的运行时 ID: - 新增 _pathIdCache 静态缓存,跨 Play/Stop 循环保持稳定 - 新增 getStableIdForPath() 方法,相同路径永远返回相同 ID - 修改 loadTextureForComponent/loadTextureByGuid 使用稳定 ID - clearTextureMappings() 不再清除 _pathIdCache 这解决了 Play/Stop 后纹理 ID 失效的根本问题。 * fix(runtime-core): 移除 Play/Stop 循环中的 clearTextureMappings 调用 使用路径稳定 ID 后,不再需要在快照保存/恢复时清除纹理缓存: - saveSceneSnapshot() 移除 clearTextureMappings() 调用 - restoreSceneSnapshot() 移除 clearTextureMappings() 调用 - 组件保存的 textureId 在 Play/Stop 后仍然有效 * fix(editor-core): 修复场景切换时的资源泄漏 在 openScene() 加载新场景前先卸载旧场景资源: - 调用 sceneResourceManager.unloadSceneResources() 释放旧资源 - 使用引用计数机制,仅卸载不再被引用的资源 - 路径稳定 ID 缓存不受影响,保持 ID 稳定性 * fix(runtime-core): 修复 PluginManager 组件注册类型错误 将 ComponentRegistry 类改为 GlobalComponentRegistry 实例: - registerComponents() 期望 IComponentRegistry 接口实例 - GlobalComponentRegistry 是 ComponentRegistry 的全局实例 * refactor(core): 提取 IComponentRegistry 接口 将组件注册表抽象为接口,支持场景级组件注册: - 新增 IComponentRegistry 接口定义 - Scene 持有独立的 componentRegistry 实例 - 支持从 GlobalComponentRegistry 克隆 - 各系统支持传入自定义注册表 * refactor(engine-core): 改进插件服务注册机制 - 更新 IComponentRegistry 类型引用 - 优化 PluginServiceRegistry 服务管理 * refactor(modules): 适配新的组件注册接口 更新各模块 RuntimeModule 使用 IComponentRegistry 接口: - audio, behavior-tree, camera - sprite, tilemap, world-streaming * fix(physics-rapier2d): 修复物理插件组件注册 - PhysicsEditorPlugin 添加 runtimeModule 引用 - 适配 IComponentRegistry 接口 - 修复物理组件在场景加载时未注册的问题 * feat(editor-core): 添加 UserCodeService 就绪信号机制 - 新增 waitForReady()/signalReady() API - 支持等待用户脚本编译完成 - 解决场景加载时组件未注册的时序问题 * fix(editor-app): 在编译完成后调用 signalReady() 确保用户脚本编译完成后发出就绪信号: - 编译成功后调用 userCodeService.signalReady() - 编译失败也要发出信号,避免阻塞场景加载 * feat(editor-core): 改进编辑器核心服务 - EntityStoreService 添加调试日志 - AssetRegistryService 优化资产注册 - PluginManager 改进插件管理 - IFileAPI 添加 getFileMtime 接口 * feat(engine): 改进 Rust 纹理管理器 - 支持任意 ID 的纹理加载(非递增) - 添加纹理状态追踪 API - 优化纹理缓存清理机制 - 更新 TypeScript 绑定 * feat(ui): 添加场景切换和文本闪烁组件 新增组件: - SceneLoadTriggerComponent: 场景切换触发器 - TextBlinkComponent: 文本闪烁效果 新增系统: - SceneLoadTriggerSystem: 处理场景切换逻辑 - TextBlinkSystem: 处理文本闪烁动画 其他改进: - UIRuntimeModule 适配新组件注册接口 - UI 渲染系统优化 * feat(editor-app): 添加外部文件修改检测 - 新增 ExternalModificationDialog 组件 - TauriFileAPI 支持 getFileMtime - 场景文件被外部修改时提示用户 * feat(editor-app): 添加渲染调试面板 - 新增 RenderDebugService 和调试面板 UI - App/ContentBrowser 添加调试日志 - TitleBar/Viewport 优化 - DialogManager 改进 * refactor(editor-app): 编辑器服务和组件优化 - EngineService 改进引擎集成 - EditorEngineSync 同步优化 - AssetFileInspector 改进 - VectorFieldEditors 优化 - InstantiatePrefabCommand 改进 * feat(i18n): 更新国际化翻译 - 添加新功能相关翻译 - 更新中文、英文、西班牙文 * feat(tauri): 添加文件修改时间查询命令 - 新增 get_file_mtime 命令 - 支持检测文件外部修改 * refactor(particle): 粒子系统改进 - 适配新的组件注册接口 - ParticleSystem 优化 - 添加单元测试 * refactor(platform): 平台适配层优化 - BrowserRuntime 改进 - 新增 RuntimeSceneManager 服务 - 导出优化 * refactor(asset-system-editor): 资产元数据改进 - AssetMetaFile 优化 - 导出调整 * fix(asset-system): 移除未使用的 TextureLoader 导入 * fix(tests): 更新测试以使用 GlobalComponentRegistry 实例 修复多个测试文件以适配 ComponentRegistry 从静态类变为实例类的变更: - ComponentStorage.test.ts: 使用 GlobalComponentRegistry.reset() - EntitySerializer.test.ts: 使用 GlobalComponentRegistry 实例 - IncrementalSerialization.test.ts: 使用 GlobalComponentRegistry 实例 - SceneSerializer.test.ts: 使用 GlobalComponentRegistry 实例 - ComponentRegistry.extended.test.ts: 使用 GlobalComponentRegistry,同时注册到 scene.componentRegistry - SystemTypes.test.ts: 在 Scene 创建前注册组件 - QuerySystem.test.ts: mockScene 添加 componentRegistry
This commit is contained in:
401
packages/particle/src/__tests__/particle-e2e-test.html
Normal file
401
packages/particle/src/__tests__/particle-e2e-test.html
Normal file
@@ -0,0 +1,401 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Particle System End-to-End Test</title>
|
||||
<style>
|
||||
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
|
||||
canvas { border: 1px solid #444; margin: 10px; background: #333; }
|
||||
.section { margin: 20px 0; padding: 15px; background: #252525; border-radius: 8px; }
|
||||
h2 { color: #8cf; margin-top: 0; }
|
||||
pre { background: #333; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 11px; }
|
||||
.pass { color: #2a5; }
|
||||
.fail { color: #f55; }
|
||||
.log { color: #aaa; font-size: 11px; }
|
||||
table { border-collapse: collapse; margin: 10px 0; }
|
||||
td, th { border: 1px solid #444; padding: 5px 10px; text-align: left; }
|
||||
th { background: #333; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Particle System End-to-End Test</h1>
|
||||
<p>This test simulates the COMPLETE particle rendering pipeline.</p>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 1: Test Texture</h2>
|
||||
<pre>
|
||||
2x2 Spritesheet (128x128 pixels):
|
||||
┌───────────┬───────────┐
|
||||
│ RED (0) │ GREEN (1) │ row=0, v: 0.0 - 0.5
|
||||
├───────────┼───────────┤
|
||||
│ BLUE (2) │ YELLOW(3) │ row=1, v: 0.5 - 1.0
|
||||
└───────────┴───────────┘
|
||||
</pre>
|
||||
<canvas id="texturePreview" width="128" height="128"></canvas>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 2: TextureSheetAnimationModule._setParticleUV()</h2>
|
||||
<pre id="step2Log"></pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 3: ParticleRenderDataProvider._updateRenderData()</h2>
|
||||
<pre id="step3Log"></pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 4: EngineRenderSystem.convertProviderDataToSprites()</h2>
|
||||
<pre id="step4Log"></pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 5: sprite_batch.rs add_sprite_vertices_to_batch()</h2>
|
||||
<pre id="step5Log"></pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Step 6: Final Rendering Result</h2>
|
||||
<canvas id="mainCanvas" width="500" height="150"></canvas>
|
||||
<div id="renderResult"></div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Test Results</h2>
|
||||
<table>
|
||||
<tr><th>Frame</th><th>Expected</th><th>Got</th><th>Status</th></tr>
|
||||
<tbody id="resultsTable"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Conclusion</h2>
|
||||
<pre id="conclusion"></pre>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// ========== Shaders ==========
|
||||
const vsSource = `
|
||||
attribute vec2 aPosition;
|
||||
attribute vec2 aTexCoord;
|
||||
varying vec2 vTexCoord;
|
||||
uniform mat4 uProjection;
|
||||
void main() {
|
||||
gl_Position = uProjection * vec4(aPosition, 0.0, 1.0);
|
||||
vTexCoord = aTexCoord;
|
||||
}
|
||||
`;
|
||||
|
||||
const fsSource = `
|
||||
precision mediump float;
|
||||
varying vec2 vTexCoord;
|
||||
uniform sampler2D uTexture;
|
||||
void main() {
|
||||
gl_FragColor = texture2D(uTexture, vTexCoord);
|
||||
}
|
||||
`;
|
||||
|
||||
// ========== WebGL Setup ==========
|
||||
function createShader(gl, type, source) {
|
||||
const shader = gl.createShader(type);
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
return shader;
|
||||
}
|
||||
|
||||
function createProgram(gl) {
|
||||
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
|
||||
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
|
||||
const program = gl.createProgram();
|
||||
gl.attachShader(program, vs);
|
||||
gl.attachShader(program, fs);
|
||||
gl.linkProgram(program);
|
||||
return program;
|
||||
}
|
||||
|
||||
function createTestTexture(gl) {
|
||||
const texture = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); // NO FLIP - same as engine
|
||||
|
||||
const data = new Uint8Array([
|
||||
255, 50, 50, 255, 50, 255, 50, 255, // Row 0: Red, Green
|
||||
50, 50, 255, 255, 255, 255, 50, 255 // Row 1: Blue, Yellow
|
||||
]);
|
||||
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
return texture;
|
||||
}
|
||||
|
||||
// ========== Step 2: TextureSheetAnimationModule._setParticleUV ==========
|
||||
function simulateTextureSheetAnimationModule(frameIndex, tilesX, tilesY) {
|
||||
const col = frameIndex % tilesX;
|
||||
const row = Math.floor(frameIndex / tilesX);
|
||||
|
||||
// This is what TextureSheetAnimationModule stores on the particle
|
||||
return {
|
||||
_animFrame: frameIndex,
|
||||
_animTilesX: tilesX,
|
||||
_animTilesY: tilesY,
|
||||
col,
|
||||
row
|
||||
};
|
||||
}
|
||||
|
||||
// ========== Step 3: ParticleRenderDataProvider._updateRenderData ==========
|
||||
function simulateParticleRenderDataProvider(particle, tilesX, tilesY) {
|
||||
const frame = particle._animFrame;
|
||||
const col = frame % tilesX;
|
||||
const row = Math.floor(frame / tilesX);
|
||||
const uWidth = 1 / tilesX;
|
||||
const vHeight = 1 / tilesY;
|
||||
|
||||
// This is exactly what ParticleRenderDataProvider does
|
||||
const u0 = col * uWidth;
|
||||
const u1 = (col + 1) * uWidth;
|
||||
const v0 = row * vHeight;
|
||||
const v1 = (row + 1) * vHeight;
|
||||
|
||||
return {
|
||||
uvs: [u0, v0, u1, v1],
|
||||
transforms: [0, 0, 0, 64, 64, 0.5, 0.5], // x, y, rotation, scaleX, scaleY, originX, originY
|
||||
tileCount: 1
|
||||
};
|
||||
}
|
||||
|
||||
// ========== Step 4: EngineRenderSystem.convertProviderDataToSprites ==========
|
||||
function simulateConvertProviderDataToSprites(providerData, x, y) {
|
||||
const tOffset = 0;
|
||||
const uvOffset = 0;
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y,
|
||||
rotation: providerData.transforms[tOffset + 2],
|
||||
scaleX: providerData.transforms[tOffset + 3],
|
||||
scaleY: providerData.transforms[tOffset + 4],
|
||||
originX: providerData.transforms[tOffset + 5],
|
||||
originY: providerData.transforms[tOffset + 6],
|
||||
uv: [
|
||||
providerData.uvs[0],
|
||||
providerData.uvs[1],
|
||||
providerData.uvs[2],
|
||||
providerData.uvs[3]
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
// ========== Step 5: sprite_batch.rs add_sprite_vertices_to_batch ==========
|
||||
function simulateSpriteBatch(sprite, batch) {
|
||||
const { x, y, scaleX: width, scaleY: height, rotation, originX, originY } = sprite;
|
||||
const [u0, v0, u1, v1] = sprite.uv;
|
||||
|
||||
const ox = originX * width;
|
||||
const oy = originY * height;
|
||||
|
||||
const cos = Math.cos(rotation);
|
||||
const sin = Math.sin(rotation);
|
||||
|
||||
// Exactly as sprite_batch.rs
|
||||
const corners = [
|
||||
[-ox, height - oy], // 0: Top-left (high Y)
|
||||
[width - ox, height - oy], // 1: Top-right
|
||||
[width - ox, -oy], // 2: Bottom-right (low Y)
|
||||
[-ox, -oy] // 3: Bottom-left
|
||||
];
|
||||
|
||||
const texCoords = [
|
||||
[u0, v0], // 0: Top-left vertex gets (u0, v0)
|
||||
[u1, v0], // 1: Top-right vertex gets (u1, v0)
|
||||
[u1, v1], // 2: Bottom-right vertex gets (u1, v1)
|
||||
[u0, v1] // 3: Bottom-left vertex gets (u0, v1)
|
||||
];
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const [lx, ly] = corners[i];
|
||||
const rx = lx * cos - ly * sin;
|
||||
const ry = lx * sin + ly * cos;
|
||||
const px = rx + x;
|
||||
const py = ry + y;
|
||||
|
||||
batch.positions.push(px, py);
|
||||
batch.texCoords.push(texCoords[i][0], texCoords[i][1]);
|
||||
}
|
||||
|
||||
const base = batch.vertexCount;
|
||||
batch.indices.push(base, base + 1, base + 2, base + 2, base + 3, base);
|
||||
batch.vertexCount += 4;
|
||||
|
||||
return { corners, texCoords };
|
||||
}
|
||||
|
||||
// ========== Utility ==========
|
||||
function colorName(r, g, b) {
|
||||
if (r > 200 && g < 100 && b < 100) return 'RED';
|
||||
if (r < 100 && g > 200 && b < 100) return 'GREEN';
|
||||
if (r < 100 && g < 100 && b > 200) return 'BLUE';
|
||||
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
|
||||
return `RGB(${r},${g},${b})`;
|
||||
}
|
||||
|
||||
// ========== Main Test ==========
|
||||
function runTest() {
|
||||
const tilesX = 2, tilesY = 2;
|
||||
const expectedColors = ['RED', 'GREEN', 'BLUE', 'YELLOW'];
|
||||
const results = [];
|
||||
|
||||
let step2Log = '';
|
||||
let step3Log = '';
|
||||
let step4Log = '';
|
||||
let step5Log = '';
|
||||
|
||||
// Draw texture preview
|
||||
const previewCanvas = document.getElementById('texturePreview');
|
||||
const previewCtx = previewCanvas.getContext('2d');
|
||||
previewCtx.fillStyle = '#ff3232'; previewCtx.fillRect(0, 0, 64, 64);
|
||||
previewCtx.fillStyle = '#32ff32'; previewCtx.fillRect(64, 0, 64, 64);
|
||||
previewCtx.fillStyle = '#3232ff'; previewCtx.fillRect(0, 64, 64, 64);
|
||||
previewCtx.fillStyle = '#ffff32'; previewCtx.fillRect(64, 64, 64, 64);
|
||||
previewCtx.fillStyle = '#fff'; previewCtx.font = '20px monospace';
|
||||
previewCtx.fillText('0', 28, 38); previewCtx.fillText('1', 92, 38);
|
||||
previewCtx.fillText('2', 28, 102); previewCtx.fillText('3', 92, 102);
|
||||
|
||||
// Setup WebGL
|
||||
const canvas = document.getElementById('mainCanvas');
|
||||
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
|
||||
const program = createProgram(gl);
|
||||
const texture = createTestTexture(gl);
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
const left = 0, right = 500, bottom = 0, top = 150;
|
||||
const projection = new Float32Array([
|
||||
2/(right-left), 0, 0, 0,
|
||||
0, 2/(top-bottom), 0, 0,
|
||||
0, 0, -1, 0,
|
||||
-(right+left)/(right-left), -(top+bottom)/(top-bottom), 0, 1
|
||||
]);
|
||||
gl.uniformMatrix4fv(projLoc, false, projection);
|
||||
|
||||
gl.viewport(0, 0, 500, 150);
|
||||
gl.clearColor(0.15, 0.15, 0.15, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
|
||||
const batch = { positions: [], texCoords: [], indices: [], vertexCount: 0 };
|
||||
|
||||
// Process each frame
|
||||
for (let frame = 0; frame < 4; frame++) {
|
||||
const x = 60 + frame * 110;
|
||||
const y = 75;
|
||||
|
||||
// Step 2
|
||||
const particleData = simulateTextureSheetAnimationModule(frame, tilesX, tilesY);
|
||||
step2Log += `Frame ${frame}: _animFrame=${particleData._animFrame}, col=${particleData.col}, row=${particleData.row}\n`;
|
||||
|
||||
// Step 3
|
||||
const providerData = simulateParticleRenderDataProvider(particleData, tilesX, tilesY);
|
||||
step3Log += `Frame ${frame}: uvs=[${providerData.uvs.map(v => v.toFixed(2)).join(', ')}]\n`;
|
||||
|
||||
// Step 4
|
||||
const sprite = simulateConvertProviderDataToSprites(providerData, x, y);
|
||||
step4Log += `Frame ${frame}: uv=[${sprite.uv.map(v => v.toFixed(2)).join(', ')}], pos=(${x}, ${y})\n`;
|
||||
|
||||
// Step 5
|
||||
const batchResult = simulateSpriteBatch(sprite, batch);
|
||||
step5Log += `Frame ${frame}: vertex0(top-left)=[${batchResult.texCoords[0].map(v => v.toFixed(2)).join(', ')}], `;
|
||||
step5Log += `vertex2(bottom-right)=[${batchResult.texCoords[2].map(v => v.toFixed(2)).join(', ')}]\n`;
|
||||
}
|
||||
|
||||
document.getElementById('step2Log').textContent = step2Log;
|
||||
document.getElementById('step3Log').textContent = step3Log;
|
||||
document.getElementById('step4Log').textContent = step4Log;
|
||||
document.getElementById('step5Log').textContent = step5Log;
|
||||
|
||||
// Render
|
||||
const posLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
|
||||
|
||||
const posBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.positions), gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(posLoc);
|
||||
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
const texBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.texCoords), gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(texLoc);
|
||||
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
const idxBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuf);
|
||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(batch.indices), gl.STATIC_DRAW);
|
||||
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
|
||||
gl.drawElements(gl.TRIANGLES, batch.indices.length, gl.UNSIGNED_SHORT, 0);
|
||||
|
||||
// Read back and verify
|
||||
const tableBody = document.getElementById('resultsTable');
|
||||
let allPassed = true;
|
||||
|
||||
for (let frame = 0; frame < 4; frame++) {
|
||||
const x = 60 + frame * 110;
|
||||
const y = 75;
|
||||
|
||||
const pixels = new Uint8Array(4);
|
||||
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
|
||||
const actual = colorName(pixels[0], pixels[1], pixels[2]);
|
||||
const expected = expectedColors[frame];
|
||||
const passed = actual === expected;
|
||||
|
||||
if (!passed) allPassed = false;
|
||||
results.push({ frame, expected, actual, passed });
|
||||
|
||||
tableBody.innerHTML += `
|
||||
<tr class="${passed ? 'pass' : 'fail'}">
|
||||
<td>Frame ${frame}</td>
|
||||
<td>${expected}</td>
|
||||
<td>${actual}</td>
|
||||
<td>${passed ? '✓ PASS' : '✗ FAIL'}</td>
|
||||
</tr>
|
||||
`;
|
||||
}
|
||||
|
||||
// Conclusion
|
||||
const conclusionEl = document.getElementById('conclusion');
|
||||
if (allPassed) {
|
||||
conclusionEl.innerHTML = `<span class="pass">ALL TESTS PASSED!</span>
|
||||
|
||||
The entire particle rendering pipeline is CORRECT:
|
||||
- TextureSheetAnimationModule ✓
|
||||
- ParticleRenderDataProvider ✓
|
||||
- EngineRenderSystem ✓
|
||||
- sprite_batch.rs ✓
|
||||
|
||||
If your actual particles still show wrong colors, the problem must be:
|
||||
1. Your spritesheet image has a different layout
|
||||
2. Something else is modifying the UV values
|
||||
3. The texture is being loaded differently
|
||||
|
||||
Try using the test image: F:\\ecs-framework\\test_spritesheet_2x2.png`;
|
||||
} else {
|
||||
const failedFrames = results.filter(r => !r.passed);
|
||||
conclusionEl.innerHTML = `<span class="fail">TESTS FAILED!</span>
|
||||
|
||||
Failed frames:
|
||||
${failedFrames.map(f => `Frame ${f.frame}: expected ${f.expected}, got ${f.actual}`).join('\n')}
|
||||
|
||||
This indicates a bug in the rendering pipeline.`;
|
||||
}
|
||||
}
|
||||
|
||||
window.onload = runTest;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
328
packages/particle/src/__tests__/sprite-batch-test.html
Normal file
328
packages/particle/src/__tests__/sprite-batch-test.html
Normal file
@@ -0,0 +1,328 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sprite Batch Rendering Test (模拟 sprite_batch.rs)</title>
|
||||
<style>
|
||||
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
|
||||
canvas { border: 1px solid #444; margin: 10px; background: #333; }
|
||||
.test-row { display: flex; align-items: flex-start; margin: 20px 0; gap: 20px; }
|
||||
.info { background: #333; padding: 10px; border-radius: 4px; font-size: 12px; }
|
||||
h2 { color: #8cf; }
|
||||
pre { background: #333; padding: 10px; border-radius: 4px; overflow-x: auto; }
|
||||
.pass { color: #2a5; }
|
||||
.fail { color: #f55; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Sprite Batch Rendering Test</h1>
|
||||
<p>This test simulates exactly how sprite_batch.rs renders sprites with UV coordinates.</p>
|
||||
|
||||
<h2>Test Texture (2x2 spritesheet)</h2>
|
||||
<pre>
|
||||
┌─────────┬─────────┐
|
||||
│ RED (0) │ GREEN(1)│ v: 0.0 - 0.5
|
||||
├─────────┼─────────┤
|
||||
│ BLUE(2) │ YELLOW(3)│ v: 0.5 - 1.0
|
||||
└─────────┴─────────┘
|
||||
</pre>
|
||||
|
||||
<h2>Rendering Test (same as sprite_batch.rs)</h2>
|
||||
<div class="test-row">
|
||||
<div>
|
||||
<canvas id="mainCanvas" width="400" height="300"></canvas>
|
||||
<div>Main rendering canvas</div>
|
||||
</div>
|
||||
<div class="info">
|
||||
<h3>sprite_batch.rs vertex mapping:</h3>
|
||||
<pre>
|
||||
corners = [
|
||||
(-ox, height-oy), // 0: Top-left (high Y)
|
||||
(width-ox, height-oy), // 1: Top-right
|
||||
(width-ox, -oy), // 2: Bottom-right (low Y)
|
||||
(-ox, -oy), // 3: Bottom-left
|
||||
];
|
||||
|
||||
tex_coords = [
|
||||
[u0, v0], // 0: Top-left
|
||||
[u1, v0], // 1: Top-right
|
||||
[u1, v1], // 2: Bottom-right
|
||||
[u0, v1], // 3: Bottom-left
|
||||
];
|
||||
|
||||
indices = [0, 1, 2, 2, 3, 0];
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Frame-by-Frame Test Results</h2>
|
||||
<div id="results"></div>
|
||||
|
||||
<h2>Conclusion</h2>
|
||||
<pre id="conclusion"></pre>
|
||||
|
||||
<script>
|
||||
const vsSource = `
|
||||
attribute vec2 aPosition;
|
||||
attribute vec2 aTexCoord;
|
||||
varying vec2 vTexCoord;
|
||||
uniform mat4 uProjection;
|
||||
void main() {
|
||||
gl_Position = uProjection * vec4(aPosition, 0.0, 1.0);
|
||||
vTexCoord = aTexCoord;
|
||||
}
|
||||
`;
|
||||
|
||||
const fsSource = `
|
||||
precision mediump float;
|
||||
varying vec2 vTexCoord;
|
||||
uniform sampler2D uTexture;
|
||||
void main() {
|
||||
gl_FragColor = texture2D(uTexture, vTexCoord);
|
||||
}
|
||||
`;
|
||||
|
||||
function createShader(gl, type, source) {
|
||||
const shader = gl.createShader(type);
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
||||
console.error(gl.getShaderInfoLog(shader));
|
||||
return null;
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
|
||||
function createProgram(gl, vsSource, fsSource) {
|
||||
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
|
||||
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
|
||||
const program = gl.createProgram();
|
||||
gl.attachShader(program, vs);
|
||||
gl.attachShader(program, fs);
|
||||
gl.linkProgram(program);
|
||||
return program;
|
||||
}
|
||||
|
||||
function createTestTexture(gl) {
|
||||
const texture = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
|
||||
// NO FLIP_Y - same as our engine
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
|
||||
|
||||
// 2x2 texture: Red, Green, Blue, Yellow
|
||||
const data = new Uint8Array([
|
||||
255, 0, 0, 255, 0, 255, 0, 255, // Row 0: Red, Green
|
||||
0, 0, 255, 255, 255, 255, 0, 255 // Row 1: Blue, Yellow
|
||||
]);
|
||||
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
||||
// Simulate sprite_batch.rs add_sprite_vertices_to_batch
|
||||
function addSpriteVertices(batch, x, y, width, height, rotation, originX, originY, u0, v0, u1, v1, color) {
|
||||
const ox = originX * width;
|
||||
const oy = originY * height;
|
||||
|
||||
const cos = Math.cos(rotation);
|
||||
const sin = Math.sin(rotation);
|
||||
|
||||
// Same as sprite_batch.rs
|
||||
const corners = [
|
||||
[-ox, height - oy], // 0: Top-left
|
||||
[width - ox, height - oy], // 1: Top-right
|
||||
[width - ox, -oy], // 2: Bottom-right
|
||||
[-ox, -oy] // 3: Bottom-left
|
||||
];
|
||||
|
||||
const texCoords = [
|
||||
[u0, v0], // 0: Top-left
|
||||
[u1, v0], // 1: Top-right
|
||||
[u1, v1], // 2: Bottom-right
|
||||
[u0, v1] // 3: Bottom-left
|
||||
];
|
||||
|
||||
// Transform and add vertices
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const [lx, ly] = corners[i];
|
||||
|
||||
// Apply rotation
|
||||
const rx = lx * cos - ly * sin;
|
||||
const ry = lx * sin + ly * cos;
|
||||
|
||||
// Apply translation
|
||||
const px = rx + x;
|
||||
const py = ry + y;
|
||||
|
||||
batch.positions.push(px, py);
|
||||
batch.texCoords.push(texCoords[i][0], texCoords[i][1]);
|
||||
}
|
||||
|
||||
// Add indices (0, 1, 2, 2, 3, 0)
|
||||
const base = batch.vertexCount;
|
||||
batch.indices.push(base, base + 1, base + 2, base + 2, base + 3, base);
|
||||
batch.vertexCount += 4;
|
||||
}
|
||||
|
||||
function calculateUV(frame, tilesX, tilesY) {
|
||||
const col = frame % tilesX;
|
||||
const row = Math.floor(frame / tilesX);
|
||||
const uWidth = 1 / tilesX;
|
||||
const vHeight = 1 / tilesY;
|
||||
return {
|
||||
u0: col * uWidth,
|
||||
v0: row * vHeight,
|
||||
u1: (col + 1) * uWidth,
|
||||
v1: (row + 1) * vHeight
|
||||
};
|
||||
}
|
||||
|
||||
function colorName(r, g, b) {
|
||||
if (r > 200 && g < 100 && b < 100) return 'RED';
|
||||
if (r < 100 && g > 200 && b < 100) return 'GREEN';
|
||||
if (r < 100 && g < 100 && b > 200) return 'BLUE';
|
||||
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
|
||||
return `RGB(${r},${g},${b})`;
|
||||
}
|
||||
|
||||
function runTest() {
|
||||
const canvas = document.getElementById('mainCanvas');
|
||||
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
|
||||
|
||||
if (!gl) {
|
||||
document.getElementById('conclusion').textContent = 'WebGL not supported!';
|
||||
return;
|
||||
}
|
||||
|
||||
const program = createProgram(gl, vsSource, fsSource);
|
||||
const texture = createTestTexture(gl);
|
||||
|
||||
gl.useProgram(program);
|
||||
|
||||
// Set up orthographic projection (Y-up, like our engine)
|
||||
const projLoc = gl.getUniformLocation(program, 'uProjection');
|
||||
const left = 0, right = 400, bottom = 0, top = 300;
|
||||
const projection = new Float32Array([
|
||||
2/(right-left), 0, 0, 0,
|
||||
0, 2/(top-bottom), 0, 0,
|
||||
0, 0, -1, 0,
|
||||
-(right+left)/(right-left), -(top+bottom)/(top-bottom), 0, 1
|
||||
]);
|
||||
gl.uniformMatrix4fv(projLoc, false, projection);
|
||||
|
||||
// Clear
|
||||
gl.viewport(0, 0, 400, 300);
|
||||
gl.clearColor(0.2, 0.2, 0.2, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
|
||||
// Create batch
|
||||
const batch = { positions: [], texCoords: [], indices: [], vertexCount: 0 };
|
||||
|
||||
// Add 4 sprites for 4 frames
|
||||
const spriteSize = 80;
|
||||
const spacing = 90;
|
||||
const startX = 50;
|
||||
const startY = 150;
|
||||
|
||||
const expectedColors = ['RED', 'GREEN', 'BLUE', 'YELLOW'];
|
||||
|
||||
for (let frame = 0; frame < 4; frame++) {
|
||||
const uv = calculateUV(frame, 2, 2);
|
||||
const x = startX + frame * spacing;
|
||||
const y = startY;
|
||||
|
||||
addSpriteVertices(
|
||||
batch,
|
||||
x, y, // position
|
||||
spriteSize, spriteSize, // size
|
||||
0, // rotation
|
||||
0.5, 0.5, // origin (center)
|
||||
uv.u0, uv.v0, uv.u1, uv.v1, // UV
|
||||
[1, 1, 1, 1] // color
|
||||
);
|
||||
}
|
||||
|
||||
// Upload and render
|
||||
const posLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
|
||||
|
||||
const posBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.positions), gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(posLoc);
|
||||
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
const texBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.texCoords), gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(texLoc);
|
||||
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
const idxBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuf);
|
||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(batch.indices), gl.STATIC_DRAW);
|
||||
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
|
||||
gl.drawElements(gl.TRIANGLES, batch.indices.length, gl.UNSIGNED_SHORT, 0);
|
||||
|
||||
// Read back colors and verify
|
||||
const resultsDiv = document.getElementById('results');
|
||||
let allPassed = true;
|
||||
|
||||
for (let frame = 0; frame < 4; frame++) {
|
||||
const x = startX + frame * spacing;
|
||||
const y = startY;
|
||||
|
||||
const pixels = new Uint8Array(4);
|
||||
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
|
||||
const actual = colorName(pixels[0], pixels[1], pixels[2]);
|
||||
const expected = expectedColors[frame];
|
||||
const passed = actual === expected;
|
||||
|
||||
if (!passed) allPassed = false;
|
||||
|
||||
const uv = calculateUV(frame, 2, 2);
|
||||
resultsDiv.innerHTML += `
|
||||
<div class="${passed ? 'pass' : 'fail'}">
|
||||
Frame ${frame}: UV=[${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]
|
||||
→ Expected: ${expected}, Got: ${actual} ${passed ? '✓' : '✗'}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const conclusionEl = document.getElementById('conclusion');
|
||||
if (allPassed) {
|
||||
conclusionEl.innerHTML = `
|
||||
<span class="pass">ALL TESTS PASSED!</span>
|
||||
|
||||
The sprite_batch.rs rendering logic is CORRECT.
|
||||
UV calculation is CORRECT.
|
||||
|
||||
If particles still show wrong frames in the actual engine, possible causes:
|
||||
1. The spritesheet image layout is different (frame 0 not at top-left)
|
||||
2. Image loading is flipping the texture somewhere
|
||||
3. The particle system is using different UV values than expected
|
||||
|
||||
<b>NEXT STEP:</b> Check the actual spritesheet image in the editor.
|
||||
Is frame 0 really at the top-left corner of the image?
|
||||
`;
|
||||
} else {
|
||||
conclusionEl.innerHTML = `
|
||||
<span class="fail">SOME TESTS FAILED!</span>
|
||||
|
||||
There's a bug in the vertex/UV mapping logic.
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
window.onload = runTest;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
142
packages/particle/src/__tests__/uv-calculation.test.ts
Normal file
142
packages/particle/src/__tests__/uv-calculation.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* UV 计算测试
|
||||
* UV Calculation Test
|
||||
*
|
||||
* 用于验证 TextureSheetAnimation 的 UV 坐标计算是否正确
|
||||
* Used to verify TextureSheetAnimation UV coordinate calculation
|
||||
*/
|
||||
|
||||
/**
|
||||
* 模拟 ParticleRenderDataProvider 中的 UV 计算
|
||||
* Simulate UV calculation from ParticleRenderDataProvider
|
||||
*/
|
||||
function calculateUV(frame: number, tilesX: number, tilesY: number) {
|
||||
const col = frame % tilesX;
|
||||
const row = Math.floor(frame / tilesX);
|
||||
const uWidth = 1 / tilesX;
|
||||
const vHeight = 1 / tilesY;
|
||||
|
||||
const u0 = col * uWidth;
|
||||
const u1 = (col + 1) * uWidth;
|
||||
const v0 = row * vHeight;
|
||||
const v1 = (row + 1) * vHeight;
|
||||
|
||||
return { u0, v0, u1, v1, col, row };
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 4x4 spritesheet (16帧)
|
||||
*
|
||||
* 预期布局(标准 spritesheet,从左上角开始):
|
||||
* ┌────┬────┬────┬────┐
|
||||
* │ 0 │ 1 │ 2 │ 3 │ row=0, v: 0.00 - 0.25
|
||||
* ├────┼────┼────┼────┤
|
||||
* │ 4 │ 5 │ 6 │ 7 │ row=1, v: 0.25 - 0.50
|
||||
* ├────┼────┼────┼────┤
|
||||
* │ 8 │ 9 │ 10 │ 11 │ row=2, v: 0.50 - 0.75
|
||||
* ├────┼────┼────┼────┤
|
||||
* │ 12 │ 13 │ 14 │ 15 │ row=3, v: 0.75 - 1.00
|
||||
* └────┴────┴────┴────┘
|
||||
*/
|
||||
function test4x4Spritesheet() {
|
||||
console.log('=== 4x4 Spritesheet UV Test ===\n');
|
||||
|
||||
const tilesX = 4;
|
||||
const tilesY = 4;
|
||||
|
||||
console.log('Expected layout (standard spritesheet, top-left origin):');
|
||||
console.log('Frame 0 should be at TOP-LEFT (v: 0.00-0.25)');
|
||||
console.log('Frame 12 should be at BOTTOM-LEFT (v: 0.75-1.00)\n');
|
||||
|
||||
// 测试关键帧
|
||||
const testFrames = [0, 1, 4, 5, 12, 15];
|
||||
|
||||
for (const frame of testFrames) {
|
||||
const uv = calculateUV(frame, tilesX, tilesY);
|
||||
console.log(`Frame ${frame.toString().padStart(2)}: col=${uv.col}, row=${uv.row}`);
|
||||
console.log(` UV: [${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]`);
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 2x2 spritesheet (4帧) - 最简单的情况
|
||||
*/
|
||||
function test2x2Spritesheet() {
|
||||
console.log('=== 2x2 Spritesheet UV Test ===\n');
|
||||
|
||||
const tilesX = 2;
|
||||
const tilesY = 2;
|
||||
|
||||
console.log('Layout:');
|
||||
console.log('┌─────┬─────┐');
|
||||
console.log('│ 0 │ 1 │ v: 0.0 - 0.5');
|
||||
console.log('├─────┼─────┤');
|
||||
console.log('│ 2 │ 3 │ v: 0.5 - 1.0');
|
||||
console.log('└─────┴─────┘\n');
|
||||
|
||||
for (let frame = 0; frame < 4; frame++) {
|
||||
const uv = calculateUV(frame, tilesX, tilesY);
|
||||
console.log(`Frame ${frame}: col=${uv.col}, row=${uv.row}`);
|
||||
console.log(` UV: [${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]`);
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
/**
|
||||
* WebGL 纹理坐标系说明
|
||||
*/
|
||||
function explainWebGLTextureCoords() {
|
||||
console.log('=== WebGL Texture Coordinate System ===\n');
|
||||
|
||||
console.log('Without UNPACK_FLIP_Y_WEBGL:');
|
||||
console.log('- Image row 0 (top of image file) -> stored at texture row 0');
|
||||
console.log('- Texture coordinate V=0 samples texture row 0');
|
||||
console.log('- Therefore: V=0 = image top, V=1 = image bottom');
|
||||
console.log('');
|
||||
|
||||
console.log('sprite_batch.rs vertex mapping:');
|
||||
console.log('- Vertex 0 (top-left on screen, high Y) uses tex_coords[0] = [u0, v0]');
|
||||
console.log('- Vertex 2 (bottom-right on screen, low Y) uses tex_coords[2] = [u1, v1]');
|
||||
console.log('');
|
||||
|
||||
console.log('Expected behavior:');
|
||||
console.log('- Frame 0 UV [0, 0, 0.25, 0.25] should show TOP-LEFT quarter of spritesheet');
|
||||
console.log('- If frame 0 shows BOTTOM-LEFT, the image is being rendered upside down');
|
||||
console.log('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断当前问题
|
||||
*/
|
||||
function diagnoseIssue() {
|
||||
console.log('=== Diagnosis ===\n');
|
||||
|
||||
console.log('If TextureSheetAnimation shows wrong frames, check:');
|
||||
console.log('');
|
||||
console.log('1. Is frame 0 showing the TOP-LEFT of the spritesheet?');
|
||||
console.log(' - YES: UV calculation is correct');
|
||||
console.log(' - NO (shows bottom-left): Image is flipped vertically in WebGL');
|
||||
console.log('');
|
||||
console.log('2. Are frames playing in wrong ORDER (e.g., 3,2,1,0 instead of 0,1,2,3)?');
|
||||
console.log(' - Check animation frame index calculation');
|
||||
console.log('');
|
||||
console.log('3. Is the spritesheet itself laid out correctly?');
|
||||
console.log(' - Frame 0 should be at TOP-LEFT of the image file');
|
||||
console.log('');
|
||||
}
|
||||
|
||||
// 运行所有测试
|
||||
export function runUVTests() {
|
||||
explainWebGLTextureCoords();
|
||||
test2x2Spritesheet();
|
||||
test4x4Spritesheet();
|
||||
diagnoseIssue();
|
||||
}
|
||||
|
||||
// 如果直接运行此文件
|
||||
if (typeof window !== 'undefined') {
|
||||
runUVTests();
|
||||
}
|
||||
|
||||
export { calculateUV, test2x2Spritesheet, test4x4Spritesheet };
|
||||
278
packages/particle/src/__tests__/webgl-uv-test.html
Normal file
278
packages/particle/src/__tests__/webgl-uv-test.html
Normal file
@@ -0,0 +1,278 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>WebGL UV Coordinate Test</title>
|
||||
<style>
|
||||
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
|
||||
canvas { border: 1px solid #444; margin: 10px; }
|
||||
.test-row { display: flex; align-items: center; margin: 20px 0; }
|
||||
.label { width: 200px; }
|
||||
.result { margin-left: 20px; padding: 5px 10px; border-radius: 4px; }
|
||||
.pass { background: #2a5; }
|
||||
.fail { background: #a33; }
|
||||
h2 { color: #8cf; }
|
||||
pre { background: #333; padding: 10px; border-radius: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WebGL UV Coordinate System Test</h1>
|
||||
|
||||
<h2>1. Test Texture (2x2 grid)</h2>
|
||||
<pre>
|
||||
Image file layout (how it looks in image editor):
|
||||
┌─────────┬─────────┐
|
||||
│ RED (0) │ GREEN(1)│ row 0 (top of image file)
|
||||
├─────────┼─────────┤
|
||||
│ BLUE(2) │ YELLOW(3)│ row 1 (bottom of image file)
|
||||
└─────────┴─────────┘
|
||||
</pre>
|
||||
<canvas id="texturePreview" width="128" height="128"></canvas>
|
||||
<span>← This is the source texture</span>
|
||||
|
||||
<h2>2. UV Sampling Test</h2>
|
||||
<p>Each square below samples a different UV region. We test what color appears.</p>
|
||||
|
||||
<div class="test-row">
|
||||
<div class="label">UV [0, 0, 0.5, 0.5] (Frame 0):</div>
|
||||
<canvas id="uv0" width="64" height="64"></canvas>
|
||||
<div id="result0" class="result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-row">
|
||||
<div class="label">UV [0.5, 0, 1, 0.5] (Frame 1):</div>
|
||||
<canvas id="uv1" width="64" height="64"></canvas>
|
||||
<div id="result1" class="result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-row">
|
||||
<div class="label">UV [0, 0.5, 0.5, 1] (Frame 2):</div>
|
||||
<canvas id="uv2" width="64" height="64"></canvas>
|
||||
<div id="result2" class="result"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-row">
|
||||
<div class="label">UV [0.5, 0.5, 1, 1] (Frame 3):</div>
|
||||
<canvas id="uv3" width="64" height="64"></canvas>
|
||||
<div id="result3" class="result"></div>
|
||||
</div>
|
||||
|
||||
<h2>3. Conclusion</h2>
|
||||
<pre id="conclusion"></pre>
|
||||
|
||||
<script>
|
||||
// Vertex shader
|
||||
const vsSource = `
|
||||
attribute vec2 aPosition;
|
||||
attribute vec2 aTexCoord;
|
||||
varying vec2 vTexCoord;
|
||||
void main() {
|
||||
gl_Position = vec4(aPosition, 0.0, 1.0);
|
||||
vTexCoord = aTexCoord;
|
||||
}
|
||||
`;
|
||||
|
||||
// Fragment shader
|
||||
const fsSource = `
|
||||
precision mediump float;
|
||||
varying vec2 vTexCoord;
|
||||
uniform sampler2D uTexture;
|
||||
void main() {
|
||||
gl_FragColor = texture2D(uTexture, vTexCoord);
|
||||
}
|
||||
`;
|
||||
|
||||
function createShader(gl, type, source) {
|
||||
const shader = gl.createShader(type);
|
||||
gl.shaderSource(shader, source);
|
||||
gl.compileShader(shader);
|
||||
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
||||
console.error(gl.getShaderInfoLog(shader));
|
||||
return null;
|
||||
}
|
||||
return shader;
|
||||
}
|
||||
|
||||
function createProgram(gl) {
|
||||
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
|
||||
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
|
||||
const program = gl.createProgram();
|
||||
gl.attachShader(program, vs);
|
||||
gl.attachShader(program, fs);
|
||||
gl.linkProgram(program);
|
||||
return program;
|
||||
}
|
||||
|
||||
// Create 2x2 test texture data
|
||||
// Row 0: Red, Green
|
||||
// Row 1: Blue, Yellow
|
||||
function createTestTextureData() {
|
||||
const size = 2;
|
||||
const data = new Uint8Array(size * size * 4);
|
||||
// Row 0 (will be uploaded first)
|
||||
data[0] = 255; data[1] = 0; data[2] = 0; data[3] = 255; // Red
|
||||
data[4] = 0; data[5] = 255; data[6] = 0; data[7] = 255; // Green
|
||||
// Row 1
|
||||
data[8] = 0; data[9] = 0; data[10] = 255; data[11] = 255; // Blue
|
||||
data[12] = 255; data[13] = 255; data[14] = 0; data[15] = 255; // Yellow
|
||||
return data;
|
||||
}
|
||||
|
||||
function createTexture(gl, flipY = false) {
|
||||
const texture = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, texture);
|
||||
|
||||
// Set FLIP_Y if requested
|
||||
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY ? 1 : 0);
|
||||
|
||||
const data = createTestTextureData();
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
|
||||
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
||||
function renderQuad(gl, program, u0, v0, u1, v1) {
|
||||
gl.useProgram(program);
|
||||
|
||||
const posLoc = gl.getAttribLocation(program, 'aPosition');
|
||||
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
|
||||
|
||||
// Full screen quad
|
||||
const positions = new Float32Array([
|
||||
-1, -1, 1, -1, -1, 1,
|
||||
-1, 1, 1, -1, 1, 1
|
||||
]);
|
||||
|
||||
// UV coordinates - map corners to the specified UV region
|
||||
// Vertex order: bottom-left, bottom-right, top-left, top-left, bottom-right, top-right
|
||||
const texCoords = new Float32Array([
|
||||
u0, v1, u1, v1, u0, v0,
|
||||
u0, v0, u1, v1, u1, v0
|
||||
]);
|
||||
|
||||
const posBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(posLoc);
|
||||
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
const texBuf = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, texCoords, gl.STATIC_DRAW);
|
||||
gl.enableVertexAttribArray(texLoc);
|
||||
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
|
||||
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 6);
|
||||
}
|
||||
|
||||
function getCanvasColor(canvas) {
|
||||
const ctx = canvas.getContext('2d') || canvas.getContext('webgl2') || canvas.getContext('webgl');
|
||||
if (ctx instanceof WebGLRenderingContext || ctx instanceof WebGL2RenderingContext) {
|
||||
const pixels = new Uint8Array(4);
|
||||
ctx.readPixels(32, 32, 1, 1, ctx.RGBA, ctx.UNSIGNED_BYTE, pixels);
|
||||
return { r: pixels[0], g: pixels[1], b: pixels[2] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function colorName(r, g, b) {
|
||||
if (r > 200 && g < 100 && b < 100) return 'RED';
|
||||
if (r < 100 && g > 200 && b < 100) return 'GREEN';
|
||||
if (r < 100 && g < 100 && b > 200) return 'BLUE';
|
||||
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
|
||||
return `RGB(${r},${g},${b})`;
|
||||
}
|
||||
|
||||
function runTest() {
|
||||
// Draw texture preview
|
||||
const previewCanvas = document.getElementById('texturePreview');
|
||||
const previewCtx = previewCanvas.getContext('2d');
|
||||
previewCtx.fillStyle = 'red';
|
||||
previewCtx.fillRect(0, 0, 64, 64);
|
||||
previewCtx.fillStyle = 'green';
|
||||
previewCtx.fillRect(64, 0, 64, 64);
|
||||
previewCtx.fillStyle = 'blue';
|
||||
previewCtx.fillRect(0, 64, 64, 64);
|
||||
previewCtx.fillStyle = 'yellow';
|
||||
previewCtx.fillRect(64, 64, 64, 64);
|
||||
|
||||
// Test UV regions
|
||||
const uvTests = [
|
||||
{ id: 'uv0', uv: [0, 0, 0.5, 0.5], expected: 'RED' },
|
||||
{ id: 'uv1', uv: [0.5, 0, 1, 0.5], expected: 'GREEN' },
|
||||
{ id: 'uv2', uv: [0, 0.5, 0.5, 1], expected: 'BLUE' },
|
||||
{ id: 'uv3', uv: [0.5, 0.5, 1, 1], expected: 'YELLOW' }
|
||||
];
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const test of uvTests) {
|
||||
const canvas = document.getElementById(test.id);
|
||||
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
|
||||
|
||||
if (!gl) {
|
||||
document.getElementById('result' + test.id.slice(-1)).textContent = 'WebGL not supported';
|
||||
continue;
|
||||
}
|
||||
|
||||
const program = createProgram(gl);
|
||||
const texture = createTexture(gl, false); // No FLIP_Y
|
||||
|
||||
gl.viewport(0, 0, 64, 64);
|
||||
gl.clearColor(0, 0, 0, 1);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
|
||||
renderQuad(gl, program, ...test.uv);
|
||||
|
||||
// Read back color
|
||||
const pixels = new Uint8Array(4);
|
||||
gl.readPixels(32, 32, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
|
||||
const actual = colorName(pixels[0], pixels[1], pixels[2]);
|
||||
|
||||
const passed = actual === test.expected;
|
||||
results.push({ test: test.id, expected: test.expected, actual, passed });
|
||||
|
||||
const resultEl = document.getElementById('result' + test.id.slice(-1));
|
||||
resultEl.textContent = `Expected: ${test.expected}, Got: ${actual}`;
|
||||
resultEl.className = 'result ' + (passed ? 'pass' : 'fail');
|
||||
}
|
||||
|
||||
// Conclusion
|
||||
const allPassed = results.every(r => r.passed);
|
||||
const conclusionEl = document.getElementById('conclusion');
|
||||
|
||||
if (allPassed) {
|
||||
conclusionEl.textContent = `
|
||||
ALL TESTS PASSED!
|
||||
|
||||
UV coordinate system (without FLIP_Y):
|
||||
- V=0 samples the TOP of the image (row 0)
|
||||
- V=1 samples the BOTTOM of the image (row N)
|
||||
|
||||
This means the current particle UV calculation should be CORRECT:
|
||||
v0 = row * vHeight; // row 0 -> v0=0 -> image top
|
||||
v1 = (row + 1) * vHeight;
|
||||
|
||||
If particles still show wrong frames, the problem is elsewhere.
|
||||
`;
|
||||
} else {
|
||||
const failedTests = results.filter(r => !r.passed);
|
||||
conclusionEl.textContent = `
|
||||
SOME TESTS FAILED!
|
||||
|
||||
${failedTests.map(t => `${t.test}: expected ${t.expected}, got ${t.actual}`).join('\n')}
|
||||
|
||||
This indicates the UV coordinate system behaves differently than expected.
|
||||
The V axis may need to be flipped in particle UV calculation.
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
window.onload = runTest;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user