我在创建3D纹理并用图像填充它时遇到了问题。我想要做的是使用我的图像的RGBA值创建一个体积/ 3D纹理,并将其按顺序放在纹理中。为此,我创建了一个Cube,并应用了这个着色器和脚本:
脚本
using UnityEditor;
using UnityEngine;
public class Create3DTex : MonoBehaviour
{
private Texture3D tex;
private Texture2D[] slices;
private Texture2D tex2d;
void Start()
{
int n = 91;
slices = new Texture2D[n];
for (int j = 0; j < n; j++)
{
tex2d = (Texture2D)UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/Resources/Textures/texture" + j + ".png", typeof(Texture2D));
SetTextureImporterFormat(tex2d, true);
slices[j] = tex2d;
}
int size = 64;
tex = new Texture3D(size, size, size, TextureFormat.ARGB32, false);
var cols = new Color[size * size * size];
float mul = 1.0f / (size - 1);
int idx = 0;
var c = new Color[size * size * size];
var countOffset = (slices.Length - 1) / (float)size;
var sliceCount = 0;
var sliceCountFloat = 0f;
for (int z = 0; z < size; ++z)
{
sliceCountFloat += countOffset;
sliceCount = Mathf.FloorToInt(sliceCountFloat);
for (int y = 0; y < size; ++y)
{
for (int x = 0; x < size; ++x, ++idx)
{
cols[idx] = slices[sliceCount].GetPixelBilinear(x / (float)size, y / (float)size);
}
}
}
tex.SetPixels(cols);
tex.Apply();
GetComponent<Renderer>().material.SetTexture("_Volume", tex);
}
public static void SetTextureImporterFormat(Texture2D texture, bool isReadable)
{
if (null == texture) return;
string assetPath = AssetDatabase.GetAssetPath(texture);
var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
if (tImporter != null)
{
tImporter.textureType = TextureImporterType.Advanced;
tImporter.isReadable = isReadable;
AssetDatabase.ImportAsset(assetPath);
AssetDatabase.Refresh();
}
}
}
着色
Shader "DX11/Sample 3D Texture" {
Properties {
_Volume ("Texture", 3D) = "" {}
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers flash gles
#include "UnityCG.cginc"
struct vs_input {
float4 vertex : POSITION;
};
struct ps_input {
float4 pos : SV_POSITION;
float3 uv : TEXCOORD0;
};
ps_input vert (vs_input v)
{
ps_input o;
o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
o.uv = v.vertex.xyz;
return o;
}
sampler3D _Volume;
float4 frag (ps_input i) : COLOR
{
return tex3D (_Volume, i.uv);
}
ENDCG
}
}
Fallback "VertexLit"
}
似乎它加载了一些东西,但我不知道如何使立方体透明并且纹理看起来不正确。它显示了这样的事情。有任何想法吗?提前致谢。 Result
答案 0 :(得分:0)
为了正确显示三维数据,您必须在着色器中创建一个包含数据的三维结构,然后集成生成的&#34;体积像素&#34;沿着视线。 为此,您必须执行光线投射。 http://www.alanzucconi.com/2016/07/01/raymarching/