本文整理汇总了C#中UnityEngine.ComputeBuffer.GetData方法的典型用法代码示例。如果您正苦于以下问题:C# ComputeBuffer.GetData方法的具体用法?C# ComputeBuffer.GetData怎么用?C# ComputeBuffer.GetData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UnityEngine.ComputeBuffer
的用法示例。
在下文中一共展示了ComputeBuffer.GetData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
void Start()
{
ComputeBuffer buffer = new ComputeBuffer (4 * 4 * 2 * 2, sizeof(int));
int kernel = shader.FindKernel ("CSMain2");
shader.SetBuffer (kernel, "buffer2", buffer);
shader.Dispatch (kernel, 2, 2, 1);
int[] data = new int[4 * 4 * 2 * 2];
buffer.GetData (data);
for(int i = 0; i < 8; i++)
{
string line = "";
for(int j = 0; j < 8; j++)
{
line += " " + data[j+i*8];
}
Debug.Log (line);
}
buffer.Release ();
}
示例2: Start
// Use this for initialization
void Start()
{
Debug.Log("Population size: " + populationSize);
int width = (int)Mathf.Round(Mathf.Sqrt(populationSize));
int height = (int)Mathf.Round(Mathf.Sqrt(populationSize));
testing = new ComputeBuffer(10, Marshal.SizeOf(typeof(Individual)));
Debug.Log("Seed " + DateTime.Now.Millisecond);
// Fill with random genome, and run first fitness test.
int kernel = shader.FindKernel("InitializePopulation");
DebugAux.Assert(kernel >= 0, "Couldn't find kernel: " + "InitializePopulation " + kernel);
shader.SetBuffer(kernel, "Population", testing);
shader.SetFloat("seed", DateTime.Now.Millisecond);
shader.Dispatch(kernel, 32, 32, 1);
Individual[] tes = new Individual[10];
testing.GetData(tes);
for (int i = 0; i < tes.Length; i++)
Debug.Log(tes[i].genome + " " + tes[i].fitness);
// Selection..
/*kernel = shader.FindKernel("AllOnesFitness");
DebugAux.Assert(kernel >= 0, "Couldn't find kernel: " + "AllOnesFitness " + kernel);
shader.SetBuffer(kernel, "Population", testing);
shader.Dispatch(kernel, 32, 32, 1);*/
testing.Dispose();
}
示例3: updateVertices
public void updateVertices(ComputeBuffer verticesBuff)
{
Vector3[] vertices = mesh.vertices;
verticesBuff.GetData (vertices);
/*for (int i = 0; i < vertices.Length; i++) {
vertices[i].y = -1.0f;
}*/
mesh.vertices = vertices;
mesh.RecalculateNormals ();
// UnityEngine.Debug.Log ("updatedVertices");
}
示例4: GetClusters
public static List<Vector4> GetClusters(List<Vector4> atoms, int numCentroids)
{
if (ComputeShaderManager.Instance.KMeansCS == null) throw new Exception("KMeans compute shader not assigned");
if (numCentroids <= 0) throw new Exception("Num centroids too low");
var centroids = new List<Vector4>();
var centroidStep = Mathf.CeilToInt(atoms.Count / (float)numCentroids);
for (int i = 0; i < numCentroids; i++)
{
if (i*centroidStep < atoms.Count)
{
centroids.Add(atoms[i * centroidStep]);
}
else
{
centroids.Add(atoms[UnityEngine.Random.Range(0, atoms.Count)]);
}
}
var centroidBuffer = new ComputeBuffer(numCentroids, 4 * sizeof(float));
centroidBuffer.SetData(centroids.ToArray());
var pointBuffer = new ComputeBuffer(atoms.Count, 4 * sizeof(float));
pointBuffer.SetData(atoms.ToArray());
var membershipBuffer = new ComputeBuffer(atoms.Count, sizeof(int));
ComputeShaderManager.Instance.KMeansCS.SetInt("_NumPoints", atoms.Count);
ComputeShaderManager.Instance.KMeansCS.SetInt("_NumCentroids", numCentroids);
for (int i = 0; i < 5; i++)
{
ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_PointBuffer", pointBuffer);
ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_CentroidBuffer", centroidBuffer);
ComputeShaderManager.Instance.KMeansCS.SetBuffer(0, "_MembershipBuffer", membershipBuffer);
ComputeShaderManager.Instance.KMeansCS.Dispatch(0, Mathf.CeilToInt(atoms.Count / 1), 1, 1);
ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_PointBuffer", pointBuffer);
ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_NewCentroidBuffer", centroidBuffer);
ComputeShaderManager.Instance.KMeansCS.SetBuffer(1, "_NewMembershipBuffer", membershipBuffer);
ComputeShaderManager.Instance.KMeansCS.Dispatch(1, Mathf.CeilToInt(numCentroids / 64.0f), 1, 1);
}
var newCentroids = new Vector4[numCentroids];
centroidBuffer.GetData(newCentroids);
pointBuffer.Release();
centroidBuffer.Release();
membershipBuffer.Release();
return newCentroids.ToList();
}
示例5: Start
// Use this for initialization
void Start () {
ComputeBuffer buffer = new ComputeBuffer(4,sizeof(int));
shader.SetBuffer(0, "buffer1", buffer);
shader.Dispatch(0, 1, 1, 1);
int[] data = new int[4];
buffer.GetData(data);
for(int i = 0; i < 4; i++)
{
buffer.Release();
}
}
示例6: RunMultiplyShader
public void RunMultiplyShader() {
VecMatPair[] data = new VecMatPair[5];
VecMatPair[] output = new VecMatPair[5];
// Init Data here!!!
for (int i = 0; i < data.Length; i++) {
data[i].point = UnityEngine.Random.onUnitSphere;
data[i].matrix = Matrix4x4.TRS(UnityEngine.Random.onUnitSphere, UnityEngine.Random.rotation, UnityEngine.Random.onUnitSphere);
Debug.Log("PreShader! Pos: " + data[i].point.ToString() + ", Matrix: " + data[i].matrix.ToString());
}
ComputeBuffer buffer = new ComputeBuffer(data.Length, 76);
int kernelHandle = shader.FindKernel("Multiply");
buffer.SetData(data);
shader.SetBuffer(kernelHandle, "dataBuffer", buffer);
shader.Dispatch(kernelHandle, data.Length, 1, 1);
buffer.GetData(output);
for (int i = 0; i < output.Length; i++) {
Debug.Log("PostShader! Pos: " + output[i].point.ToString() + ", Matrix: " + output[i].matrix.ToString());
}
buffer.Dispose();
/*public ComputeShader compute;
public ComputeBuffer buffer;
public int[] cols;
void Start () {
var mesh = GetComponent<MeshFilter>().mesh;
int n = mesh.vertexCount;
///
buffer = new ComputeBuffer (n, 16);
///
cols = new int[n];
///
for (int i = 0; i < n; ++i)
cols[i] = 0;
buffer.SetData (cols);
///
compute.SetBuffer(compute.FindKernel ("CSMain"),"bufColors", buffer);
///
compute.Dispatch(0,4,4,1);
///
buffer.GetData(cols);
Debug.Log (cols[0]);
*/
}
示例7: Init
public void Init()
{
_grassShader = Resources.Load<Shader>("Shaders/GrassGeneratorShader");
_grassMaterial = Resources.Load<Material>("GrassGeneratorMat");
_noiseTex = Resources.Load<Texture>("Noise");
if(_noiseTex == null)
{
Debug.LogError("Not found noise");
}
_grassComputeShader = Resources.Load<ComputeShader>("ComputeShaders/GrassComputeShader");
_initGrassKernelId = _grassComputeShader.FindKernel(kInitGrassKernel);
_updateGrassKernelId = _grassComputeShader.FindKernel(kUpdateGrassKernel);
_numGrassItems = _numGroupGrassX*_numGroupGrassY*kThreadsX*kThreadsY;
_grassBuffer = new ComputeBuffer(_numGrassItems, System.Runtime.InteropServices.Marshal.SizeOf(typeof(GrassData)));
_obstaclesBuffer = new ComputeBuffer(kMaxObstacles, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ObstacleData)));
_grassComputeShader.SetFloat("_Width", _numGroupGrassX*kThreadsX);
_grassComputeShader.SetFloat("_Height", _numGroupGrassY*kThreadsY);
_grassComputeShader.SetTexture(_initGrassKernelId, "_NoiseTex", _noiseTex);
_grassMaterial.SetTexture("_NoiseTex", _noiseTex);
_grassMaterial.SetFloat("_Width", _numGroupGrassX*kThreadsX);
_grassMaterial.SetFloat("_Height", _numGroupGrassY*kThreadsY);
_grassComputeShader.SetBuffer(_initGrassKernelId, "_GrassBuffer", _grassBuffer);
_grassComputeShader.SetBuffer(_updateGrassKernelId, "_GrassBuffer", _grassBuffer);
_grassComputeShader.SetBuffer(_updateGrassKernelId, "_ObstaclesBuffer", _obstaclesBuffer);
_grassComputeShader.SetInt("_NumObstacles", 0);
_grassMaterial.SetBuffer("_GrassBuffer", _grassBuffer);
_grassComputeShader.Dispatch(_initGrassKernelId, _numGroupGrassX, _numGroupGrassY, 1);
#if GRASS_CPU
_grassDataTestCPU = new GrassData[_numGrassItems];
_grassBuffer.GetData(_grassDataTestCPU);
#endif
_isInit = true;
}
示例8: BuildMesh
public void BuildMesh() {
float startTime = Time.realtimeSinceStartup;
// NOISE VOLUME!
RenderTexture DensityVolume = new RenderTexture(16, 16, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.sRGB);
DensityVolume.volumeDepth = 16;
DensityVolume.isVolume = true;
DensityVolume.enableRandomWrite = true;
DensityVolume.filterMode = FilterMode.Bilinear;
DensityVolume.wrapMode = TextureWrapMode.Repeat;
DensityVolume.Create();
int mgen_id = CShaderSimplex.FindKernel("FillEmpty");
// uses renderTexture rather than StructuredBuffer?
CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume); // Links RenderTexture to the "Result" RWTexture in the compute shader?
CShaderSimplex.Dispatch(mgen_id, 1, 1, 16); // run computeShader "FillEmpty" with 1 x 1 x 31 threadGroups?
mgen_id = CShaderSimplex.FindKernel("Simplex3d");
CShaderSimplex.SetTexture(mgen_id, "Result", DensityVolume);
CShaderSimplex.Dispatch(mgen_id, 1, 1, 16); // Fill shared RenderTexture with GPU simplex Noise
ComputeBuffer cBufferSegmentTransform = new ComputeBuffer(critterSegmentTransforms.Length, sizeof(float) * (3 + 3 + 4));
cBufferSegmentTransform.SetData(critterSegmentTransforms);
int kernelID = CShaderBuildMC.FindKernel("CSMain");
CShaderBuildMC.SetBuffer(kernelID, "segmentTransformBuffer", cBufferSegmentTransform);
CShaderBuildMC.SetTexture(kernelID, "noise_volume", DensityVolume); // Noise 3D texture
//Debug.Log(DensityVolume.colorBuffer.ToString());
// Figure out how many chunks are needed:
int numChunksX = Mathf.CeilToInt(GlobalBoundingBoxDimensions.x / (cellResolution * 8f));
int numChunksY = Mathf.CeilToInt(GlobalBoundingBoxDimensions.y / (cellResolution * 8f));
int numChunksZ = Mathf.CeilToInt(GlobalBoundingBoxDimensions.z / (cellResolution * 8f));
//Debug.Log("numChunks: (" + numChunksX.ToString() + ", " + numChunksY.ToString() + ", " + numChunksZ.ToString() + ")");
int totalNumChunks = numChunksX * numChunksY * numChunksZ;
Poly[][] PolyArrayArray = new Poly[totalNumChunks][]; // This will hold the mesh data from the chunks calculated on the GPU
int[] numPolysArray = new int[totalNumChunks];
int totalNumPolys = 0;
// Get each chunk!
int chunkIndex = 0;
for(int x = 0; x < numChunksX; x++) {
for(int y = 0; y < numChunksY; y++) {
for(int z = 0; z < numChunksZ; z++) {
// Figure out chunk offset amount:
Vector3 chunkOffset = new Vector3(cellResolution * 8f * x, cellResolution * 8f * y, cellResolution * 8f * z) + GlobalBoundingBoxOffset - (GlobalBoundingBoxDimensions / 2f);
int[] numPolys = new int[1];
ComputeBuffer cBufferNumPoly = new ComputeBuffer(1, sizeof(int));
cBufferNumPoly.SetData(numPolys);
int id = CShaderBuildMC.FindKernel("CSMain");
CShaderBuildMC.SetInt("_CalcNumPolys", 1); // only calculate how many tris so I can correctly size the poly buffer
CShaderBuildMC.SetFloat("_GlobalOffsetX", chunkOffset.x);
CShaderBuildMC.SetFloat("_GlobalOffsetY", chunkOffset.y);
CShaderBuildMC.SetFloat("_GlobalOffsetZ", chunkOffset.z);
CShaderBuildMC.SetFloat("_CellSize", cellResolution);
CShaderBuildMC.SetVector("_ColorPrimary", colorPrimary);
CShaderBuildMC.SetVector("_ColorSecondary", colorSecondary);
CShaderBuildMC.SetFloat("_ColorNoiseScale", colorNoiseScale);
CShaderBuildMC.SetFloat("_ColorSmlAmplitude", colorSmlAmplitude);
CShaderBuildMC.SetFloat("_ColorMedAmplitude", colorMedAmplitude);
CShaderBuildMC.SetFloat("_ColorLrgAmplitude", colorLrgAmplitude);
CShaderBuildMC.SetFloat("_ColorContrast", colorContrast);
CShaderBuildMC.SetFloat("_ColorThreshold", colorThreshold);
CShaderBuildMC.SetVector("_SkinNoiseScale", skinNoiseScale);
CShaderBuildMC.SetFloat("_SkinNoiseAmplitude", skinNoiseAmplitude);
CShaderBuildMC.SetVector("_SkinLocalTaper", skinLocalTaper);
CShaderBuildMC.SetVector("_SkinLocalSinFreq", skinLocalSinFreq);
CShaderBuildMC.SetVector("_SkinLocalSinAmp", skinLocalSinAmp);
// Local Segment-space modifications, sin, taper, etc.
CShaderBuildMC.SetBuffer(id, "numPolyBuffer", cBufferNumPoly);
CShaderBuildMC.Dispatch(id, 1, 1, 1); // calc num polys
cBufferNumPoly.GetData(numPolys); // get numPolys
//Debug.Log("Chunk: " + (z + (numChunksZ * y) + (numChunksZ * numChunksY * x)).ToString() + ", cBufferNumPoly.GetData(numPolys): " + numPolys[0].ToString() + ", chunkOffset: " + chunkOffset.ToString());
totalNumPolys += numPolys[0];
numPolysArray[chunkIndex] = numPolys[0];
if(numPolys[0] > 0) { // only do this if there was at least 1 triangle in the test pass
Poly[] polyArray = new Poly[numPolys[0]];
int cBufferStride = sizeof(float) * (18 + 9 + 6) + sizeof(int) * (6);
ComputeBuffer cBuffer = new ComputeBuffer(numPolys[0], cBufferStride); // 18 floats x 4 bytes/float = 72 + COLORS! 9 x 4 = 36 = 108 + BONES! 6x4 = 24 + 6 xint...
cBuffer.SetData(polyArray);
CShaderBuildMC.SetBuffer(id, "buffer", cBuffer);
CShaderBuildMC.SetInt("_CalcNumPolys", 0); // Actually calc tris
CShaderBuildMC.Dispatch(id, 1, 1, 1);
cBuffer.GetData(polyArray); // return data from GPU
PolyArrayArray[chunkIndex] = polyArray;
cBuffer.Dispose();
}
cBufferNumPoly.Dispose();
chunkIndex++;
}
}
}
//.........这里部分代码省略.........
示例9: PreFilterEnviromentMap
///<summary>
/// Input a cubemap, and then prefilter this cubemap for image-based lighting equation.
///</summary>
public static void PreFilterEnviromentMap(Cubemap cubemap)
{
if (cubemap)
{
int cube_width = cubemap.width;
Vector3 vec3 = new Vector3();
// Create a read buffer to store cubemap direction data.
ComputeBuffer cubeMatrix = new ComputeBuffer(sgFaceInput.Length, Marshal.SizeOf(vec3));
cubeMatrix.SetData(sgFaceInput);
Vector4 vec4 = new Vector4();
// Create a output buffer.
ComputeBuffer dstData = new ComputeBuffer(cube_width * cube_width * 6, Marshal.SizeOf(vec4));
ComputeShader CSEnvFilter;
CSEnvFilter = (ComputeShader)AssetDatabase.LoadAssetAtPath("Assets/EnvironmentMapTool/ComputeShader/FilterCubeMap.compute", typeof(ComputeShader));
// Set cubemap to shader.
CSEnvFilter.SetTexture(0, "gCubemap", cubemap);
// Set read write buffer for data output.
CSEnvFilter.SetBuffer(0, "gOutput", dstData);
// Set cubemap direction data.
CSEnvFilter.SetBuffer(0, "sgFace2DMapping", cubeMatrix);
Color[] outputData = new Color[cube_width * cube_width * 6];
// How many mipmap level?
float mipLevelNum = Mathf.Log(cube_width, 2);
// Loop each mipmap level with different roughness.
for (int i = 0; i < mipLevelNum + 1; i++)
{
// The texel number of a face.
int image_size = cube_width * cube_width;
// The texel number of a cubemap.
int num_threads = image_size * 6;
// Set roughness value (between 0~1).
CSEnvFilter.SetFloat("gRoughness", (i / mipLevelNum));
// The width of a mipmap level of a cube map.
CSEnvFilter.SetInt("gWidth", cube_width);
// The total number of thread groups (the number of my thread group : 64).
num_threads = (int)Mathf.Ceil((float)num_threads / 64.0f);
// Run compute shader.
CSEnvFilter.Dispatch(0, num_threads, 1, 1);
// Get data from the read & write buffer.
dstData.GetData(outputData);
// Copy data to the original cubemap.
SetCubeMipMap(cubemap, outputData, image_size, i);
// Half the size for the next mipmap level.
cube_width = cube_width / 2;
}
// Set false to disable auto-generating mipmap.
cubemap.Apply(false);
// Use trilinear mode to interpolate different mipmap levels.
cubemap.filterMode = FilterMode.Trilinear;
cubemap.wrapMode = TextureWrapMode.Clamp;
cubemap.name = cubemap.name + "(PreFilter)";
// Release data.
dstData.Release();
cubeMatrix.Release();
}
}
示例10: ReadPixelId
public static int ReadPixelId(RenderTexture texture, Vector2 coord)
{
var outBuffer = new ComputeBuffer(1, sizeof(int));
ComputeShaderManager.Instance.ReadPixelCS.SetInts("_Coord", (int)coord.x, Screen.height - (int)coord.y);
ComputeShaderManager.Instance.ReadPixelCS.SetTexture(0, "_IdTexture", texture);
ComputeShaderManager.Instance.ReadPixelCS.SetBuffer(0, "_OutputBuffer", outBuffer);
ComputeShaderManager.Instance.ReadPixelCS.Dispatch(0, 1, 1, 1);
var pixelId = new[] { 0 };
outBuffer.GetData(pixelId);
outBuffer.Release();
return pixelId[0];
}
示例11: InitTerrain
private void InitTerrain() {
int meshGridSize = 16;
int numTerrainMeshVertices = meshGridSize * meshGridSize;
terrainMeshBuffer = new ComputeBuffer(numTerrainMeshVertices, sizeof(float) * (3 + 3 + 2 + 4));
int numStrokesPerVertX = 16;
int numStrokesPerVertZ = 16;
int numTerrainStrokes = meshGridSize * meshGridSize * numStrokesPerVertX * numStrokesPerVertZ;
terrainStrokesBuffer = new ComputeBuffer(numTerrainStrokes, sizeof(float) * (3 + 3 + 3 + 3 + 3 + 2) + sizeof(int) * 1);
//terrainGeneratorCompute = new ComputeShader();
int kernel_id = terrainGeneratorCompute.FindKernel("CSMain");
terrainGeneratorCompute.SetFloat("_GridSideLength", terrainSize);
terrainGeneratorCompute.SetFloat("_NoiseFrequency", terrainNoiseFrequency);
terrainGeneratorCompute.SetFloat("_NoiseAmplitude", terrainNoiseAmplitude);
terrainGeneratorCompute.SetFloat("_GroundHeight", terrainAltitude);
terrainGeneratorCompute.SetInt("_NumGroupsX", numStrokesPerVertX);
terrainGeneratorCompute.SetInt("_NumGroupsZ", numStrokesPerVertZ);
terrainGeneratorCompute.SetBuffer(kernel_id, "buf_StrokeData", terrainStrokesBuffer);
terrainGeneratorCompute.SetBuffer(kernel_id, "buf_MeshData", terrainMeshBuffer);
meshData[] meshDataArray = new meshData[numTerrainMeshVertices]; // memory to receive data from computeshader
terrainGeneratorCompute.Dispatch(kernel_id, numStrokesPerVertX, 1, numStrokesPerVertZ); // fill buffers
terrainMeshBuffer.GetData(meshDataArray); // download mesh Data
// generate Mesh from data:
//Construct mesh using received data
// Why same number of tris as vertices? == // because all triangles have duplicate verts - no shared vertices?
Vector3[] vertices = new Vector3[numTerrainMeshVertices];
Color[] colors = new Color[numTerrainMeshVertices];
int[] tris = new int[2 * (meshGridSize - 1) * (meshGridSize - 1) * 3];
Vector2[] uvs = new Vector2[numTerrainMeshVertices];
Vector3[] normals = new Vector3[numTerrainMeshVertices];
for(int i = 0; i < numTerrainMeshVertices; i++) {
vertices[i] = meshDataArray[i].pos;
normals[i] = meshDataArray[i].normal;
uvs[i] = meshDataArray[i].uv;
colors[i] = meshDataArray[i].color;
}
// Figure out triangles:
int index = 0;
int numSquares = meshGridSize - 1;
for (int y = 0; y < numSquares; y++) {
for(int x = 0; x < numSquares; x++) {
// counterclockwise winding order:
tris[index] = ((y + 1) * meshGridSize) + x;
tris[index + 1] = (y * meshGridSize) + x + 1;
tris[index + 2] = (y * meshGridSize) + x;
tris[index + 3] = ((y + 1) * meshGridSize) + x;
tris[index + 4] = ((y + 1) * meshGridSize) + x + 1;
tris[index + 5] = (y * meshGridSize) + x + 1;
index = index + 6;
}
}
Mesh terrainMesh = new Mesh();
terrainMesh.vertices = vertices;
terrainMesh.uv = uvs; //Unwrapping.GeneratePerTriangleUV(NewMesh);
terrainMesh.triangles = tris;
terrainMesh.normals = normals; //NewMesh.RecalculateNormals();
terrainMesh.colors = colors;
terrainMesh.RecalculateNormals();
terrainMesh.RecalculateBounds();
trainerTerrainManager.GetComponent<MeshFilter>().sharedMesh = terrainMesh;
trainerTerrainManager.GetComponent<MeshCollider>().sharedMesh = terrainMesh;
terrainMeshBuffer.Release();
terrainMeshBuffer.Dispose();
}
示例12: SaveAsRaw
void SaveAsRaw(int size, int channels, string fileName, RenderTexture rtex)
{
ComputeBuffer buffer = new ComputeBuffer(size, sizeof(float)*channels);
CBUtility.ReadFromRenderTexture(rtex, channels, buffer, m_readData);
float[] data = new float[size * channels];
buffer.GetData(data);
byte[] byteArray = new byte[size * 4 * channels];
System.Buffer.BlockCopy(data, 0, byteArray, 0, byteArray.Length);
System.IO.File.WriteAllBytes(Application.dataPath + m_filePath + fileName + ".raw", byteArray);
buffer.Release();
}
示例13: SaveAs8bit
void SaveAs8bit(int width, int height, int channels, string fileName, RenderTexture rtex, float scale = 1.0f)
{
//Only used to get a visible image for debugging.
ComputeBuffer buffer = new ComputeBuffer(width*height, sizeof(float)*channels);
CBUtility.ReadFromRenderTexture(rtex, channels, buffer, m_readData);
float[] data = new float[width*height* channels];
buffer.GetData(data);
Texture2D tex = new Texture2D(width, height);
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
Color col = new Color(0,0,0,1);
col.r = data[(x + y * width) * channels + 0];
if(channels > 1)
col.g = data[(x + y * width) * channels + 1];
if(channels > 2)
col.b = data[(x + y * width) * channels + 2];
tex.SetPixel(x, y, col * scale);
}
}
tex.Apply();
byte[] bytes = tex.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + m_filePath + fileName + ".png", bytes);
buffer.Release();
}
示例14: CreateDistanceField
/*****/
private void CreateDistanceField()
{
var size = 128;
var pdbName = "MA_matrix_G1";
string path = "Assets/Resources/3D Textures/" + pdbName + ".asset";
Texture3D tmp = (Texture3D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture3D));
if (tmp)
{
_volumeTexture = tmp;
}
else
{
RenderTexture _distanceFieldRT;
_distanceFieldRT = new RenderTexture(size, size, 0, RenderTextureFormat.R8);
_distanceFieldRT.volumeDepth = size;
_distanceFieldRT.isVolume = true;
_distanceFieldRT.isPowerOfTwo = true;
_distanceFieldRT.enableRandomWrite = true;
_distanceFieldRT.filterMode = FilterMode.Trilinear;
_distanceFieldRT.name = pdbName;
_distanceFieldRT.hideFlags = HideFlags.HideAndDontSave;
_distanceFieldRT.generateMips = true;
_distanceFieldRT.useMipMap = true;
_distanceFieldRT.Create();
var atomSpheres = PdbLoader.LoadAtomSpheres(pdbName);
var atomSphereGPUBuffer = new ComputeBuffer(atomSpheres.Count, sizeof(float) * 4, ComputeBufferType.Default);
atomSphereGPUBuffer.SetData(atomSpheres.ToArray());
Graphics.SetRenderTarget(_distanceFieldRT);
GL.Clear(true, true, new Color(0, 0, 0));
var createDistanceFieldCS = Resources.Load("Compute Shaders/CreateDistanceField") as ComputeShader;
createDistanceFieldCS.SetInt("_GridSize", size);
createDistanceFieldCS.SetInt("_NumAtoms", atomSpheres.Count);
createDistanceFieldCS.SetBuffer(0, "_SpherePositions", atomSphereGPUBuffer);
createDistanceFieldCS.SetTexture(0, "_VolumeTexture", _distanceFieldRT);
createDistanceFieldCS.Dispatch(0, Mathf.CeilToInt(size / 10.0f), Mathf.CeilToInt(size / 10.0f), Mathf.CeilToInt(size / 10.0f));
atomSphereGPUBuffer.Release();
//****
var flatSize = size * size * size;
var voxelGPUBuffer = new ComputeBuffer(flatSize, sizeof(float));
var readVoxelsCS = Resources.Load("Compute Shaders/ReadVoxels") as ComputeShader;
readVoxelsCS.SetInt("_VolumeSize", size);
readVoxelsCS.SetBuffer(0, "_VoxelBuffer", voxelGPUBuffer);
readVoxelsCS.SetTexture(0, "_VolumeTexture", _distanceFieldRT);
readVoxelsCS.Dispatch(0, size, size, size);
var voxelCPUBuffer = new float[flatSize];
voxelGPUBuffer.GetData(voxelCPUBuffer);
var volumeColors = new Color[flatSize];
for (int i = 0; i < flatSize; i++)
{
volumeColors[i] = new Color(0, 0, 0, voxelCPUBuffer[i]);
}
var texture3D = new Texture3D(size, size, size, TextureFormat.Alpha8, true);
texture3D.SetPixels(volumeColors);
texture3D.wrapMode = TextureWrapMode.Clamp;
texture3D.anisoLevel = 0;
texture3D.Apply();
AssetDatabase.CreateAsset(texture3D, path);
AssetDatabase.SaveAssets();
// Print the path of the created asset
Debug.Log(AssetDatabase.GetAssetPath(texture3D));
voxelGPUBuffer.Release();
_distanceFieldRT.Release();
DestroyImmediate(_distanceFieldRT);
_volumeTexture = texture3D;
}
}
示例15: CubemapToEquirectangular
IEnumerator CubemapToEquirectangular(ComputeBuffer cameraPixelsBuffer, uint[] cameraPixels, ComputeBuffer convertPanoramaResultBuffer, int cameraWidth, int cameraHeight, byte[] pixelValues,
int stride, int panoramaWidth, int panoramaHeight, int ssaaFactor, bool async)
{
if (captureStereoscopic && usingGpuTransform)
{
// Was already done earlier, just grab the result
convertPanoramaResultBuffer.GetData(resultPixels);
if (resultPixels[convertPanoramaResultBuffer.count - 1] != BufferSentinelValue)
ReportOutOfGraphicsMemory();
writeOutputPixels(pixelValues, stride, panoramaWidth, panoramaHeight * 2, panoramaHeight * 2, /*yStart*/0);
}
else if (captureStereoscopic && !usingGpuTransform)
{
// TODO: Factor out into separate method
float startTime = Time.realtimeSinceStartup;
float processingTimePerFrame = cpuMillisecondsPerFrame / 1000.0f;
for (int y = 0; y < panoramaHeight; y++)
for (int x = 0; x < panoramaWidth; x++)
{
float xcoord = (float)x / panoramaWidth;
float ycoord = (float)y / panoramaHeight;
float latitude = (ycoord - 0.5f) * Mathf.PI;
float sinLat = Mathf.Sin(latitude);
float cosLat = Mathf.Cos(latitude);
float longitude = (xcoord * 2.0f - 1.0f) * Mathf.PI;
float sinLong = Mathf.Sin(longitude);
float cosLong = Mathf.Cos(longitude);
// Scale IPD down as latitude moves toward poles to avoid discontinuities
float latitudeNormalized = latitude / (Mathf.PI / 2.0f); // Map to [-1, 1]
float ipdScale = IpdScaleFunction(latitudeNormalized);
float scaledEyeRadius = ipdScale * interpupillaryDistance / 2.0f;
int cameraNum;
float u, v;
float ipdScaleLerp = 1.0f - ipdScale * 5.0f; // Scale [0, 0.2] to [0, 1] and reverse
// Top/bottom cap
Color colorCap = new Color(0.0f, 0.0f, 0.0f, 0.0f);
if (ipdScaleLerp > 0.0f)
{
Vector3 equirectRayDirection = new Vector3(cosLat * sinLong, sinLat, cosLat * cosLong);
float distance = 1.0f / equirectRayDirection.y;
u = equirectRayDirection.x * distance; v = equirectRayDirection.z * distance;
if (u * u <= 1 && v * v <= 1)
{
if (equirectRayDirection.y > 0.0f)
{
cameraNum = 0;
}
else
{
u = -u;
cameraNum = 1;
}
u = (u + 1.0f) * 0.5f;
v = (v + 1.0f) * 0.5f;
colorCap = GetCameraPixelBilinear(cameraPixels, cameraNum, u, v);
}
}
for (int i = 0; i < 2; i++)
{
// The following is equivalent to:
// Quaternion eyesRotation = Quaternion.Euler(0.0f, longitude * 360.0f / (2 * Mathf.PI), 0.0f);
// Vector3 initialEyePosition = (i == 0 ? Vector3.left : Vector3.right) * scaledEyeRadius;
// Vector3 pos = eyesRotation * initialEyePosition; // eye position
// Vector3 dir = eyesRotation * Vector3.forward; // gaze direction
Vector3 dir = new Vector3(sinLong, 0.0f, cosLong);
float angle = (Mathf.PI / 2.0f - Mathf.Acos(scaledEyeRadius / circleRadius));
if (i == 0) angle = -angle;
float circlePointAngle = longitude + angle;
if (circlePointAngle < 0.0f) circlePointAngle += 2 * Mathf.PI;
if (circlePointAngle >= 2 * Mathf.PI) circlePointAngle -= 2 * Mathf.PI;
// Debug.Assert(circlePointAngle >= 0.0f && circlePointAngle < 2 * Mathf.PI);
float circlePointNumber = circlePointAngle / (2 * Mathf.PI) * numCirclePoints;
int circlePoint0 = (int)Mathf.Floor(circlePointNumber) % numCirclePoints;
// Get color from each adjacent circle point
Color color0 = new Color(), color1 = new Color();
for (int j=0; j < 2; j++)
{
int circlePointIdx = (j == 0 ? circlePoint0 : (circlePoint0 + 1) % numCirclePoints);
float cameraPointAngle = 2 * Mathf.PI * circlePointIdx / numCirclePoints;
float sinCameraPointAngle = Mathf.Sin(cameraPointAngle);
float cosCameraPointAngle = Mathf.Cos(cameraPointAngle);
// Equivalent to (using fact that both dir and circlePointNorm are unit vectors):
// Quaternion circlePointRotation = Quaternion.Euler(0.0f, cameraPointAngle * 360.0f / (2 * Mathf.PI), 0.0f);
// Vector3 circlePointNormal = circlePointRotation * Vector3.forward;
// float newLongitude = Mathf.Sign(Vector3.Cross(circlePointNormal, dir).y) * Vector3.Angle(circlePointNormal, dir) * (2 * Mathf.PI) / 360.0f;
//.........这里部分代码省略.........