如下内容是对 https://tips.hecomi.com/entry/2018/01/05/192332 进行翻译同时增补得到笔记
体积渲染概述
体积渲染是一种在 2D 屏幕上渲染 3D Texture 的技术,其中 3D Texture 来源有:
- 从 CT 扫描、MRI 等获得的数据;
- 预先准备好或实时计算的 3D 数据(例如云和效果)
3D Texture 的种类
.raw
.pvm
DICOM
NRRD 文件(.nrrd)
NRRD(Nearly Raw Raster Data)是一种轻量级、灵活的科学数据格式,专为多维栅格数据设计。
通常由两个部分组成:
.nrrd 文件:纯文本头文件,包含维度、数据类型、空间方向、原点、间距等元数据。
.raw 文件:二进制体数据(可选,也可内联在 .nrrd 中)。
特点:
开源、跨平台、易于解析。
支持任意维度(2D、3D、4D…)、多种数据类型。
被 3D Slicer、ITK、VTK 等主流科学可视化工具广泛支持。
可压缩(如 gzip)。
生成 3D Texture
运行时候生成
using UnityEngine;
public class Create3DTex : MonoBehaviour
{
[SerializeField]
int size = 16;
void Start()
{
var tex = new Texture3D(size, size, size, TextureFormat.ARGB32, true);
var colors = new Color[size * size * size];
float a = 1f / (size - 1);
int i = 0;
Color c = Color.white;
for (int z = 0; z < size; ++z)
{
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x, ++i)
{
c.r = ((x & 1) != 0) ? x * a : 1 - x * a;
c.g = ((y & 1) != 0) ? y * a : 1 - y * a;
c.b = ((z & 1) != 0) ? z * a : 1 - z * a;
colors[i] = c;
}
}
}
tex.SetPixels(colors);
tex.Apply();
var renderer = GetComponent<Renderer>();
renderer.material.SetTexture("_Volume", tex);
}
}
生成 3D Texture 并序列化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class EditorCreateTexture3DTest : Editor
{
[MenuItem("GameTools/CreateTexture3D")]
static void CreateTexture3D()
{
// Configure the texture
int size = 128;
TextureFormat format = TextureFormat.RGBA32;
TextureWrapMode wrapMode = TextureWrapMode.Clamp;
// Create the texture and apply the configuration
Texture3D texture = new Texture3D(size, size, size, format, false);
texture.wrapMode = wrapMode;
// Create a 3-dimensional array to store color data
Color[] colors = new Color[size * size * size];
// Populate the array so that the x, y, and z values of the texture will map to red, blue, and green colors
float inverseResolution = 1.0f / (size - 1.0f);
for (int z = 0; z < size; z++)
{
int zOffset = z * size * size;
for (int y = 0; y < size; y++)
{
int yOffset = y * size;
for (int x = 0; x < size; x++)
{
colors[x + yOffset + zOffset] = new Color(x * inverseResolution,
y * inverseResolution, z * inverseResolution, 1.0f);
}
}
}
// Copy the color values to the texture
texture.SetPixels(colors);
// Apply the changes to the texture and upload the updated texture to the GPU
texture.Apply();
// Save the texture to your Unity Project
AssetDatabase.CreateAsset(texture, "Assets/Texture3DApply/testtexture3d.asset");
}
}
引用
https://github.com/hecomi/UnityVolumeRendering
https://github.com/mlavik1/UnityVolumeRendering