Files
mirage_slang/compiler.py
2025-06-06 18:22:46 +08:00

70 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
SDL3_GPU Slang Compiler - Main Compiler
主编译器类,整合所有功能模块
"""
import os
import subprocess
import tempfile
from typing import List, Dict
from binding_manager import BindingManager
from code_generator import CodeGenerator
from compiler_cmd import make_cmd
from shader_parser import ShaderParser
from shader_types import ShaderInfo, TargetFormat
class SDL3GPUSlangCompiler:
def __init__(self, include_paths: List[str] = None):
self.include_paths = include_paths or []
self.parser = ShaderParser(self.include_paths)
self.binding_manager = BindingManager()
self.code_generator = CodeGenerator()
def parse_slang_shader(self, source_path: str, target: TargetFormat, include_paths: List[str] = None) -> Dict[str, ShaderInfo]:
"""解析Slang着色器源码提取资源信息"""
return self.parser.parse_slang_shader(source_path, target, include_paths)
def compile_shader(self, shader_info: ShaderInfo, target: TargetFormat) -> tuple[str, dict]:
"""编译着色器并返回二进制路径和绑定信息"""
output_path = tempfile.mktemp()
# 根据目标格式分配绑定点
if target == TargetFormat.SPIRV:
self.binding_manager.assign_bindings_spirv(shader_info)
elif target in [TargetFormat.DXIL, TargetFormat.DXBC]:
self.binding_manager.assign_bindings_dxil(shader_info)
elif target == TargetFormat.MSL:
self.binding_manager.assign_bindings_msl(shader_info)
# 生成带绑定信息的着色器代码
modified_source = self.binding_manager.inject_bindings(shader_info, target)
# 写入临时文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.slang', delete=False, encoding='utf8') as tmp:
tmp.write(modified_source)
tmp_path = tmp.name
try:
# 编译着色器
cmd = make_cmd(tmp_path, target, shader_info.stage, shader_info.entry_point, self.include_paths, output_path)
print(f"Compiling shader with command: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
print(f"Shader compiled successfully")
# 生成绑定信息
binding_info = self.binding_manager.generate_binding_info(shader_info, target, output_path)
return binding_info
finally:
# 清理临时文件
os.unlink(tmp_path)
os.unlink(output_path)
def generate_binding_functions(self, source_file_pathname, binding_infos: List[Dict], output_path: str):
"""生成C/C++绑定函数"""
self.code_generator.generate_binding_functions(source_file_pathname, binding_infos, output_path)