npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

naga-wasm

v1.0.0

Published

High-performance WebAssembly shader converter using Naga v26

Readme

Naga WASM - 着色器转换器

npm version License: MIT

一个基于 WebAssembly 的高性能着色器转换器,使用 Naga v26 作为核心转换引擎,支持多种着色器语言之间的转换。

✨ 特性

  • 🚀 高性能: 基于 WebAssembly 的快速转换
  • 🔄 多语言支持: 支持 GLSL、WGSL、HLSL、MSL、SPIR-V
  • 🎯 智能检测: 自动检测着色器语言类型和版本
  • 完整验证: 详细的着色器代码验证和错误报告
  • 📦 轻量级: 优化的 WASM 包大小
  • 🔧 灵活配置: 可自定义转换选项
  • 📝 TypeScript 支持: 完整的类型定义和智能提示

📦 安装

npm install naga-wasm

🚀 快速开始

基本着色器转换

import init, { convert_shader } from 'naga-wasm';

// 初始化 WASM 模块
await init();

// GLSL 转 WGSL
const glslCode = `
#version 330 core
layout(location = 0) in vec3 aPos;
void main() {
    gl_Position = vec4(aPos, 1.0);
}
`;

const wgslCode = convert_shader(glslCode, 'glsl', 'wgsl');
console.log(wgslCode);

着色器语言检测

import init, { detect_shader_language } from 'naga-wasm';

await init();

const shaderCode = `
@vertex
fn vs_main(@location(0) position: vec3<f32>) -> @builtin(position) vec4<f32> {
    return vec4<f32>(position, 1.0);
}
`;

const result = detect_shader_language(shaderCode);
console.log(result);
// 输出: { language: "wgsl", version: "1.0", stage: "vertex", confidence: 1.0 }

详细验证

import init, { validate_shader_detailed } from 'naga-wasm';

await init();

const validationResult = validate_shader_detailed(shaderCode, 'glsl');

if (validationResult.is_valid) {
    console.log('✅ 着色器验证通过');
} else {
    console.log('❌ 着色器验证失败');
    validationResult.errors.forEach(error => {
        console.error(`错误 [行 ${error.line}]: ${error.message}`);
    });
}

📚 API 文档

核心转换函数

convert_shader(source, inputFormat, outputFormat)

基本的着色器转换函数。

参数:

  • source (string): 着色器源代码
  • inputFormat (string): 输入格式 ('glsl', 'wgsl')
  • outputFormat (string): 输出格式 ('wgsl', 'hlsl', 'msl', 'spv')

返回值: string - 转换后的着色器代码

convert_shader_fast(source, inputFormat, outputFormat)

快速转换模式,跳过验证步骤。

convert_shader_with_config(source, inputFormat, outputFormat, options)

使用自定义配置进行转换。

验证函数

validate_shader(source, format)

简单验证,返回布尔值。

validate_shader_detailed(source, format)

详细验证,返回完整的验证结果。

返回值: ValidationResult

interface ValidationResult {
    is_valid: boolean;
    errors: ValidationErrorDetail[];
    warnings: ValidationWarning[];
}

检测函数

detect_shader_language(source)

自动检测着色器语言类型、版本和阶段。

返回值: ShaderDetectionResult

interface ShaderDetectionResult {
    language: string;
    version: string | null;
    stage: string | null;
    confidence: number;
}

工具函数

get_supported_formats()

获取支持的输入/输出格式列表。

get_supported_stages()

获取支持的着色器阶段列表。

is_format_supported(format)

检查特定格式是否支持。

is_stage_supported(stage)

检查特定阶段是否支持。

配置选项

create_conversion_options()

创建默认的转换配置。

返回值: ConversionOptions

interface ConversionOptions {
    validate: boolean;              // 是否验证着色器代码
    preserve_whitespace: boolean;   // 是否保留空白字符
    generate_debug_info: boolean;   // 是否生成调试信息
    optimization_level: number;     // 优化级别 (0-3)
}

🎯 支持的格式

输入格式

  • GLSL - OpenGL Shading Language
  • WGSL - WebGPU Shading Language

输出格式

  • WGSL - WebGPU Shading Language
  • HLSL - High-Level Shading Language
  • MSL - Metal Shading Language
  • SPIR-V - Standard Portable Intermediate Representation

着色器阶段

  • Vertex - 顶点着色器
  • Fragment - 片段着色器
  • Compute - 计算着色器

🔧 高级用法

自定义转换配置

import init, { create_conversion_options, convert_shader_with_config } from 'naga-wasm';

await init();

const options = {
    validate: false,                    // 跳过验证以提高速度
    preserve_whitespace: false,         // 不保留空白字符
    generate_debug_info: true,          // 生成调试信息
    optimization_level: 3               // 最高优化级别
};

const result = convert_shader_with_config(
    glslCode,
    'glsl',
    'wgsl',
    options
);

错误处理

import { get_conversion_error_type } from 'naga-wasm';

try {
    const result = convert_shader(invalidCode, 'glsl', 'wgsl');
} catch (error) {
    const errorType = get_conversion_error_type(error.message);
    console.error(`错误类型: ${errorType}`);
    console.error(`详细信息: ${error.message}`);
}

批量转换

async function convertMultipleShaders(shaders) {
    await init();

    const results = [];

    for (const shader of shaders) {
        try {
            const result = convert_shader(
                shader.code,
                shader.inputFormat,
                shader.outputFormat
            );
            results.push({ success: true, result, shader });
        } catch (error) {
            results.push({ success: false, error, shader });
        }
    }

    return results;
}

🌐 浏览器使用

HTML 示例

<!DOCTYPE html>
<html>
<head>
    <script type="module">
        import init, { convert_shader, detect_shader_language } from './node_modules/naga-wasm/pkg/wasm_naga.js';

        async function main() {
            await init();

            const shaderCode = document.getElementById('shader-input').value;
            const detection = detect_shader_language(shaderCode);

            console.log('检测结果:', detection);

            if (detection.language !== 'unknown') {
                const converted = convert_shader(shaderCode, detection.language, 'wgsl');
                document.getElementById('output').textContent = converted;
            }
        }

        main();
    </script>
</head>
<body>
    <textarea id="shader-input" placeholder="输入着色器代码..."></textarea>
    <button onclick="main()">转换</button>
    <pre id="output"></pre>
</body>
</html>

🧪 测试

运行测试

# Node.js 环境测试
npm test

# 浏览器环境测试
npm run test:browser

开发构建

# 开发构建
npm run build:dev

# 生产构建
npm run build

# 清理构建产物
npm run clean

📊 性能

  • 包大小: ~150KB (gzipped)
  • 初始化时间: <50ms
  • 转换速度: 1000+ 行/秒
  • 内存占用: <10MB

🔗 相关链接

🤝 贡献

欢迎贡献代码!请查看 CONTRIBUTING.md 了解详细信息。

开发环境设置

# 克隆仓库
git clone https://github.com/your-username/naga-wasm.git
cd naga-wasm

# 安装依赖
npm install

# 构建项目
npm run build

# 运行测试
npm test

📄 许可证

本项目采用 MIT 许可证

🙏 致谢

📞 支持

如果您遇到问题或有建议,请:

  1. 查看 FAQ
  2. 搜索 已有 Issues
  3. 创建新的 Issue

注意: 这是一个实验性项目,API 可能会在未来版本中发生变化。建议在生产环境使用前进行充分测试。