主题
运行时程序化纹理
Texture2D.CreateFromImage(...) 用于把客户端运行时生成的 Image 上传为 GPU 纹理。它适合程序化图案、小型运行时画布、调试图和会在游戏中重新生成的像素数据。
项目中已经发布的普通纹理继续使用 Texture2D.Load(...)。资源系统会通过 TextureX 容器链路按目标平台选择打包和压缩后的纹理产物,并保留 mip、采样参数与资源生命周期关系;不要为了使用新工厂而把静态美术图片改成运行时逐像素生成。RenderToTexture 则继续使用 Texture2D.CreateRenderTarget(...)。
创建棋盘纹理
csharp
#if CLIENT
using System.Drawing;
using GameGraph.ResourceSystem;
using var image = new Image();
if (!image.SetSize(width: 16, height: 16, components: 4))
throw new InvalidOperationException("Could not allocate image pixels.");
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
bool bright = ((x / 4) + (y / 4)) % 2 == 0;
image.SetPixel(x, y, bright ? Color.Gold : Color.DarkSlateBlue);
}
}
var texture = Texture2D.CreateFromImage(
image,
useAlpha: false,
sRgb: true,
mipLevels: 1)
?? throw new InvalidOperationException("Texture upload failed.");
texture.FilterMode = TextureFilterMode.Nearest;
texture.SetAddressMode(TextureCoordinate.U, TextureAddressMode.Wrap);
texture.SetAddressMode(TextureCoordinate.V, TextureAddressMode.Wrap);
#endif上传成功后,纹理拥有独立的 GPU 数据,可以立即释放用于上传的 Image。Texture2D 是运行时资源,使用完毕后仍需由创建方释放;材质、网格或界面正在使用它时不要提前释放。上传失败时工厂返回 null,并自动清理尚未返回的纹理对象。
创建参数与设置顺序
| 参数 | 含义 | 常见选择 |
|---|---|---|
useAlpha | 单通道 Image 是否按 Alpha 纹理解释 | 四通道 RGBA 图片通常保持 false |
sRgb | GPU 纹理是否使用 sRGB 色彩空间 | Albedo/颜色贴图通常为 true;数据贴图通常为 false |
mipLevels | 请求的 mip 层数;0 生成完整链,1 不生成 mip | 像素风 UI/近邻采样常用 1 |
sRgb 和 mipLevels 会影响 GPU 纹理分配,所以由工厂在上传前设置。FilterMode、U/V/W 寻址和各向异性属于采样状态,可在工厂返回后设置。
useAlpha 不会自动把 PBR 材质切换为透明混合或 Alpha 裁剪。材质透明模式、深度和渲染层仍需按实际效果单独选择。
绑定到 PBR 材质
csharp
using GameGraph.MaterialSystem;
var material = new MaterialPBR(texture, useAlphaChannel: false)
{
ColorFactor = Color.White,
MetallicFactor = 0f,
RoughnessFactor = 0.8f,
};这个构造入口会直接把传入纹理绑定为 Albedo,并补齐内置金属度/粗糙度纹理。它不会修改共享的默认白图,也不需要先用无贴图材质再切换 UseAlbedoTexture。
完整可运行代码见 code_sample/src/RuntimeTextureSample/;示例把同一张棋盘纹理同时绑定到 MeshBuilder + StaticMeshComponent 和 CustomGeometryComponent。