static void Test() { const int length = 17; var array = new UnmanagedArray<float>(length); unsafe { var p = (float*)array.Header.ToPointer(); for (int i = 0; i < length; i++) { p[i] = i + length; } array.Sort(comparer: Comparer<float>.Default); //array.Sort(descending: true); float[] p2 = new float[length]; for (int i = 0; i < length; i++) { p2[i] = p[i]; } Console.WriteLine(); } }
public void Base() { using (var testing = new UnmanagedArray<float>(128)) { for (var i = 0; i < testing.Length; i++) { testing[i] = i; } for (var i = 0; i < testing.Length; i++) { Assert.That(testing[i], Is.EqualTo(i)); testing[i] = -1.0f; } var managedArray = new float[128]; for (var i = 0; i < testing.Length; i++) { managedArray[i] = i; } testing.Write(managedArray); var managedArray2 = new float[128]; testing.Read(managedArray2); for (var i = 0; i < testing.Length; i++) { Assert.That(testing[i], Is.EqualTo(i)); } } }
protected override void DoInitialize() { // Create a vertex array object uint[] vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create and initialize a buffer object uint[] buffers = new uint[NumVertexBuffers]; GL.GenBuffers(NumVertexBuffers, buffers); GL.BindBuffer(GL.GL_ARRAY_BUFFER, buffers[ArrayBuffer]); //GL.BufferData( GL.GL_ARRAY_BUFFER, sizeof(TeapotVertices), TeapotVertices, GL_STATIC_DRAW ); UnmanagedArray<vec3> positions = new UnmanagedArray<vec3>(TeapotExampleHelper.NumTeapotVertices); for (int i = 0; i < positions.Length; i++) { positions[i] = TeapotExampleHelper.TeapotVertices[i]; } GL.BufferData(BufferTarget.ArrayBuffer, positions, BufferUsage.StaticDraw); GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, buffers[ElementBuffer]); //GL.BufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(TeapotIndices), TeapotIndices, GL_STATIC_DRAW ); UnmanagedArray<uint> indexes = new UnmanagedArray<uint>(TeapotExampleHelper.NumTeapotPatches * 4 * 4); for (int i = 0; i < indexes.Length; i++) { indexes[i] = TeapotExampleHelper.TeapotIndices[i]; } GL.BufferData(BufferTarget.ElementArrayBuffer, indexes, BufferUsage.StaticDraw); // Load shaders and use the resulting shader program ShaderInfo[] shaders = new ShaderInfo[] { new ShaderInfo(){ type= ShaderType.VertexShader, shaderSource=ManifestResourceLoader.LoadTextFile("teapot.vert"),}, new ShaderInfo(){ type= ShaderType.TessellationControlShader, shaderSource=ManifestResourceLoader.LoadTextFile("teapot.cont"),}, //new ShaderInfo(){ type= ShaderType.TessellationEvaluationShader, shaderSource=ManifestResourceLoader.LoadTextFile("teapot.eval"),}, new ShaderInfo(){ type= ShaderType.FragmentShader, shaderSource=ManifestResourceLoader.LoadTextFile("teapot.frag"),}, }; //uint program = LoadShaders( shaders ); shaderProgramObject = shaders.LoadShaders(); GL.UseProgram(shaderProgramObject); // set up vertex arrays int vPosition = GL.GetAttribLocation(shaderProgramObject, "vPosition"); GL.EnableVertexAttribArray((uint)vPosition); GL.VertexAttribPointer((uint)vPosition, 3, GL.GL_DOUBLE, false, 0, new IntPtr(0)); PLoc = GL.GetUniformLocation(shaderProgramObject, "P"); InnerLoc = GL.GetUniformLocation(shaderProgramObject, "Inner"); OuterLoc = GL.GetUniformLocation(shaderProgramObject, "Outer"); GL.Uniform1(InnerLoc, Inner); GL.Uniform1(OuterLoc, Outer); mat4 modelview = glm.translate(mat4.identity(), new vec3(-0.2625f, -1.575f, -1.0f)); modelview *= glm.translate(modelview, new vec3(0.0f, 0.0f, -7.5f)); GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramObject, "MV"), 1, true, modelview.to_array()); GL.PatchParameter(PatchParameterName.PatchVertices, TeapotExampleHelper.NumTeapotVerticesPerPatch); }
public HeightfieldColliderShape(int heightStickWidth, int heightStickLength, UnmanagedArray<float> dynamicFieldData, float heightScale, float minHeight, float maxHeight, bool flipQuadEdges) { InternalShape = new BulletSharp.HeightfieldShape(heightStickWidth, heightStickLength, dynamicFieldData.Pointer, heightScale, minHeight, maxHeight, 1, (int)BulletPhyScalarType.PhyFloat, flipQuadEdges) { LocalScaling = Vector3.One }; FloatArray = dynamicFieldData; }
public override void Dispose() { base.Dispose(); ShortArray?.Dispose(); ShortArray = null; ByteArray?.Dispose(); ByteArray = null; FloatArray?.Dispose(); FloatArray = null; }
private void InitTexture3D() { int xSize = 16; int ySize = 16; int zSize = 16; int minSize = Math.Min(xSize, Math.Min(ySize, zSize)); using (var data = new UnmanagedArray<float>(xSize * ySize * zSize)) { int index=0; for (int i = 0; i < xSize; i++) { for (int j = 0; j < ySize; j++) { for (int k = 0; k < zSize; k++) { //data[index++] = new vec3((float)i / xSize, (float)j / ySize, (float)k / zSize); //data[index++] = new vec3((float)i / xSize, (float)j / ySize, (float)k / zSize); data[index++] = (float)random.NextDouble(); } } } GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); GL.GenTextures(1, this.textureName); GL.ActiveTexture(GL.GL_TEXTURE0); GL.BindTexture(GL.GL_TEXTURE_3D, this.textureName[0]); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_BASE_LEVEL, 0); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MAX_LEVEL, (float)Math.Log(minSize, 2)); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE); GL.TexParameterf(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_R, GL.GL_CLAMP_TO_EDGE); GL.TexImage3D(GL.GL_TEXTURE_3D, 0, //(int)GL.GL_R32F, (int)GL.GL_RGB, xSize, ySize, zSize, 0, GL.GL_RGB, GL.GL_FLOAT, data.Header); GL.GenerateMipmapEXT(GL.GL_TEXTURE_3D); GL.PixelStorei(GL.GL_UNPACK_ALIGNMENT, 4); } }
private void InitVAO() { this.mode = DrawMode.Quads; this.vertexCount = 4; // Create a vertex buffer for the vertex data. UnmanagedArray<vec3> in_Position = new UnmanagedArray<vec3>(this.vertexCount); UnmanagedArray<vec2> in_TexCoord = new UnmanagedArray<vec2>(this.vertexCount); Bitmap bigBitmap = this.ttfTexture.BigBitmap; float factor = (float)this.ttfTexture.BigBitmap.Width / (float)this.ttfTexture.BigBitmap.Height; float x1 = -factor; float x2 = factor; float y1 = -1; float y2 = 1; in_Position[0] = new vec3(x1, y1, 0); in_Position[1] = new vec3(x2, y1, 0); in_Position[2] = new vec3(x2, y2, 0); in_Position[3] = new vec3(x1, y2, 0); in_TexCoord[0] = new vec2(0, 0); in_TexCoord[1] = new vec2(1, 0); in_TexCoord[2] = new vec2(1, 1); in_TexCoord[3] = new vec2(0, 1); if (vao[0] != 0) { GL.DeleteBuffers(1, vao); } if (vbo[0] != 0) { GL.DeleteBuffers(vbo.Length, vbo); } GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.GenBuffers(2, vbo); uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]); GL.BufferData(BufferTarget.ArrayBuffer, in_Position, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); uint in_TexCoordLocation = shaderProgram.GetAttributeLocation(strin_TexCoord); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[1]); GL.BufferData(BufferTarget.ArrayBuffer, in_TexCoord, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_TexCoordLocation, 2, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_TexCoordLocation); GL.BindVertexArray(0); in_Position.Dispose(); in_TexCoord.Dispose(); }
static DemoLegacyGLTexture3D() { image = new UnmanagedArray<Texture3DElement>(iDepth * iHeight * iWidth); int s, t, r; for (s = 0; s < 16; s++) for (t = 0; t < 16; t++) for (r = 0; r < 16; r++) { image[r * 16 * 16 + t * 16 + s] = new Texture3DElement() { s = (byte)(s * 17), t = (byte)(t * 17), r = (byte)(r * 17), }; } }
/// <summary> /// Gets stage vertex id by color coded picking machanism. /// Note: left bottom is(0, 0). This is different from Winform's left top being (0, 0). /// </summary> /// <param name="x">target pixel position(Left Down is (0, 0)).</param> /// <param name="y">target pixel position(Left Down is (0, 0)).</param> /// <returns></returns> internal static unsafe uint ReadStageVertexId(int x, int y) { uint stageVertexId = uint.MaxValue; using (var codedColor = new UnmanagedArray<Pixel>(1)) { // get coded color. OpenGL.ReadPixels(x, y, 1, 1, OpenGL.GL_RGBA, OpenGL.GL_UNSIGNED_BYTE, codedColor.Header); var array = (Pixel*)codedColor.Header.ToPointer(); Pixel pixel = array[0]; // This is when (x, y) is not on background and some primitive is picked. if (!pixel.IsWhite()) { stageVertexId = pixel.ToStageVertexId(); } } return stageVertexId; }
protected override void DoInitialize() { base_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(base_prog, ShaderType.VertexShader, quad_shader_vs); ShaderHelper.vglAttachShaderSource(base_prog, ShaderType.FragmentShader, quad_shader_fs); GL.GenBuffers(1, quad_vbo); GL.BindBuffer(BufferTarget.ArrayBuffer, quad_vbo[0]); var quad_data = new UnmanagedArray<vec2>(8); quad_data[0] = new vec2(1.0f, -1.0f); quad_data[1] = new vec2(-1.0f, -1.0f); quad_data[2] = new vec2(-1.0f, 1.0f); quad_data[3] = new vec2(1.0f, 1.0f); quad_data[4] = new vec2(0.0f, 0.0f); quad_data[5] = new vec2(1.0f, 0.0f); quad_data[6] = new vec2(1.0f, 1.0f); quad_data[7] = new vec2(0.0f, 1.0f); GL.BufferData(BufferTarget.ArrayBuffer, quad_data, BufferUsage.StaticDraw); GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.VertexAttribPointer(0, 2, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.VertexAttribPointer(1, 2, GL.GL_FLOAT, false, 0, new IntPtr(8 * sizeof(float))); GL.EnableVertexAttribArray(0); GL.EnableVertexAttribArray(1); GL.LinkProgram(base_prog); StringBuilder buf = new StringBuilder(1024); GL.GetProgramInfoLog(base_prog, 1024, IntPtr.Zero, buf); vglImageData image = new vglImageData(); tex = vgl.vglLoadTexture(@"media\test.dds", 0, ref image); GL.TexParameteri(image.target, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR_MIPMAP_LINEAR); vgl.vglUnloadImage(ref image); }
internal static void TypicalScene() { // 数组较小时可按此方法使用UnmanagedArray,数组较大时请参考UnmanagedArrayHelper。 const int count = 100; // 测试float类型 { var floatArray = new UnmanagedArray <float>(count); for (int i = 0; i < count; i++) { floatArray[i] = i; } for (int i = 0; i < count; i++) { var item = floatArray[i]; if (item != i) { throw new Exception(); } } } // 测试decimal类型 { var decimalArray = new UnmanagedArray <decimal>(count); for (int i = 0; i < count; i++) { decimalArray[i] = i; } for (int i = 0; i < count; i++) { var item = decimalArray[i]; if (item != i) { throw new Exception(); } } } // 测试int类型 { var intArray = new UnmanagedArray <int>(count); for (int i = 0; i < count; i++) { intArray[i] = i; } for (int i = 0; i < count; i++) { var item = intArray[i]; if (item != i) { throw new Exception(); } } } // 测试bool类型 { var boolArray = new UnmanagedArray <bool>(count); for (int i = 0; i < count; i++) { boolArray[i] = i % 2 == 0; } for (int i = 0; i < count; i++) { var item = boolArray[i]; if (item != (i % 2 == 0)) { throw new Exception(); } } } // 测试vec3类型 { var vec3Array = new UnmanagedArray <vec3>(count); for (int i = 0; i < count; i++) { vec3Array[i] = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); } for (int i = 0; i < count; i++) { var item = vec3Array[i]; var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); if (item.x != old.x || item.y != old.y || item.z != old.z) { throw new Exception(); } } // 释放此数组占用的内存,这之后就不能再使用vec3Array了。 vec3Array.Dispose(); } // 速度较慢,不再使用。 //// 测试foreach //foreach (var item in vec3Array.Elements()) //{ // Console.WriteLine(item); //} // 立即释放所有非托管数组占用的内存,任何之前创建的UnmanagedBase数组都不再可用了。 UnmanagedArray <int> .FreeAll(); }
private void InitVAO() { this.axisPrimitiveMode = DrawMode.LineLoop; this.axisVertexCount = 4; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray<vec3> positionArray = new UnmanagedArray<vec3>(4); positionArray[0] = new vec3(-0.5f, -0.5f, 0); positionArray[1] = new vec3(0.5f, -0.5f, 0); positionArray[2] = new vec3(0.5f, 0.5f, 0); positionArray[3] = new vec3(-0.5f, 0.5f, 0); uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { UnmanagedArray<vec3> colorArray = new UnmanagedArray<vec3>(4); vec3 color = this.rectColor; for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = color; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
protected override void DoInitialize() { // Initialize our compute program compute_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(compute_prog, ShaderType.ComputerShader, compute_shader_source); GL.LinkProgram(compute_prog); dt_location = GL.GetUniformLocation(compute_prog, "dt"); GL.GenVertexArrays(1, render_vao); GL.BindVertexArray(render_vao[0]); GL.GenBuffers(2, buffers); { GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[0]);//position buffer UnmanagedArray <vec4> tmp = new UnmanagedArray <vec4>(PARTICLE_COUNT); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicCopy); tmp.Dispose(); IntPtr positions = GL.MapBufferRange(GL.GL_ARRAY_BUFFER, 0, PARTICLE_COUNT * Marshal.SizeOf(typeof(vec4)), GL.GL_MAP_WRITE_BIT | GL.GL_MAP_INVALIDATE_BUFFER_BIT); unsafe { vec4 *array = (vec4 *)positions.ToPointer(); for (int i = 0; i < PARTICLE_COUNT; i++) { array[i] = new vec4(Vec3Helper.GetRandomVec3(), (float)random.NextDouble()); } } GL.UnmapBuffer(BufferTarget.ArrayBuffer); GL.VertexAttribPointer(0, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(0); } { GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[1]);// velocity buffer UnmanagedArray <vec4> tmp = new UnmanagedArray <vec4>(PARTICLE_COUNT); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicCopy); tmp.Dispose(); IntPtr velocities = GL.MapBufferRange(GL.GL_ARRAY_BUFFER, 0, PARTICLE_COUNT * Marshal.SizeOf(typeof(vec4)), GL.GL_MAP_WRITE_BIT | GL.GL_MAP_INVALIDATE_BUFFER_BIT); unsafe { vec4 *array = (vec4 *)velocities.ToPointer(); for (int i = 0; i < PARTICLE_COUNT; i++) { array[i] = new vec4(Vec3Helper.GetRandomVec3(), (float)random.NextDouble()); } } GL.UnmapBuffer(BufferTarget.ArrayBuffer); } { GL.GenTextures(2, tbos); for (int i = 0; i < 2; i++) { GL.BindTexture(GL.GL_TEXTURE_BUFFER, tbos[i]); GL.TexBuffer(GL.GL_TEXTURE_BUFFER, GL.GL_RGBA32F, buffers[i]); } } { GL.GenBuffers(1, attractor_buffer); GL.BindBuffer(BufferTarget.UniformBuffer, attractor_buffer[0]); UnmanagedArray <vec4> tmp = new UnmanagedArray <vec4>(32); GL.BufferData(BufferTarget.UniformBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); for (int i = 0; i < MAX_ATTRACTORS; i++) { attractor_masses[i] = 0.5f + (float)random.NextDouble() * 0.5f; } GL.BindBufferBase(TransformFeedbackBufferTarget.UniformBuffer, 0, attractor_buffer[0]); } { render_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.VertexShader, render_vs); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.FragmentShader, render_fs); GL.LinkProgram(render_prog); } }
public void UnmanagedArray_GetByRef() { var array = new UnmanagedArray <uint>(256); ref uint u = ref array.GetRef(0);
private void InitVAO(string value) { if (value == null) { value = string.Empty; } this.mode = DrawMode.Quads; this.vertexCount = 4 * value.Length; // Create a vertex buffer for the vertex data. UnmanagedArray <vec3> in_Position = new UnmanagedArray <vec3>(this.vertexCount); UnmanagedArray <vec2> in_TexCoord = new UnmanagedArray <vec2>(this.vertexCount); Bitmap bigBitmap = this.ttfTexture.BigBitmap; // step 1: set width for each glyph vec3[] tmpPositions = new vec3[this.vertexCount]; float totalLength = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; CharacterInfo cInfo; if (this.ttfTexture.CharInfoDict.TryGetValue(c, out cInfo)) { float glyphWidth = (float)cInfo.width / (float)this.ttfTexture.FontHeight; if (i == 0) { tmpPositions[i * 4 + 0] = new vec3(0, 0, 0); tmpPositions[i * 4 + 1] = new vec3(glyphWidth, 0, 0); tmpPositions[i * 4 + 2] = new vec3(glyphWidth, 1, 0); tmpPositions[i * 4 + 3] = new vec3(0, 1, 0); } else { tmpPositions[i * 4 + 0] = tmpPositions[i * 4 + 0 - 4 + 1]; tmpPositions[i * 4 + 1] = tmpPositions[i * 4 + 0] + new vec3(glyphWidth, 0, 0); tmpPositions[i * 4 + 3] = tmpPositions[i * 4 + 3 - 4 - 1]; tmpPositions[i * 4 + 2] = tmpPositions[i * 4 + 3] + new vec3(glyphWidth, 0, 0); } totalLength += glyphWidth; } //else //{ throw new Exception(string.Format("Not support for display the char [{0}]", c)); } } for (int i = 0; i < value.Length; i++) { char c = value[i]; CharacterInfo cInfo; float x1 = 0; float x2 = 1; float y1 = 0; float y2 = 1; if (this.ttfTexture.CharInfoDict.TryGetValue(c, out cInfo)) { x1 = (float)cInfo.xoffset / (float)bigBitmap.Width; x2 = (float)(cInfo.xoffset + cInfo.width) / (float)bigBitmap.Width; y1 = (float)cInfo.yoffset / (float)bigBitmap.Height; y2 = (float)(cInfo.yoffset + this.ttfTexture.FontHeight) / (float)bigBitmap.Height; } //else //{ throw new Exception(string.Format("Not support for display the char [{0}]", c)); } in_Position[i * 4 + 0] = tmpPositions[i * 4 + 0] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 1] = tmpPositions[i * 4 + 1] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 2] = tmpPositions[i * 4 + 2] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 3] = tmpPositions[i * 4 + 3] - new vec3(totalLength / 2, 0, 0); //in_TexCoord[i * 4 + 0] = new vec2(x1, y1); //in_TexCoord[i * 4 + 1] = new vec2(x2, y1); //in_TexCoord[i * 4 + 2] = new vec2(x2, y2); //in_TexCoord[i * 4 + 3] = new vec2(x1, y2); in_TexCoord[i * 4 + 0] = new vec2(x1, y2); in_TexCoord[i * 4 + 1] = new vec2(x2, y2); in_TexCoord[i * 4 + 2] = new vec2(x2, y1); in_TexCoord[i * 4 + 3] = new vec2(x1, y1); } if (vao[0] != 0) { GL.DeleteBuffers(1, vao); } if (vbo[0] != 0) { GL.DeleteBuffers(vbo.Length, vbo); } GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.GenBuffers(2, vbo); uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]); GL.BufferData(BufferTarget.ArrayBuffer, in_Position, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); uint in_TexCoordLocation = shaderProgram.GetAttributeLocation(strin_TexCoord); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[1]); GL.BufferData(BufferTarget.ArrayBuffer, in_TexCoord, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_TexCoordLocation, 2, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_TexCoordLocation); GL.BindVertexArray(0); in_Position.Dispose(); in_TexCoord.Dispose(); }
private void InitVAO() { // reserve a vertex array object(VAO) 预约一个VAO this.vertexArrayObject = new uint[1]; GL.GenVertexArrays(1, this.vertexArrayObject); // prepare vertex buffer object(VBO) for vertexes' positions 为顶点位置准备VBO uint[] positionBufferObject = new uint[1]; { // specify position array var positionArray = new UnmanagedArray <vec3>(vertexCount); positionArray[0] = new vec3(0.0f, 1.0f, 0.0f); positionArray[1] = new vec3(-1.0f, -1.0f, 1.0f); positionArray[2] = new vec3(1.0f, -1.0f, 1.0f); positionArray[3] = new vec3(0.0f, 1.0f, 0.0f); positionArray[4] = new vec3(1.0f, -1.0f, 1.0f); positionArray[5] = new vec3(1.0f, -1.0f, -1.0f); positionArray[6] = new vec3(0.0f, 1.0f, 0.0f); positionArray[7] = new vec3(1.0f, -1.0f, -1.0f); positionArray[8] = new vec3(-1.0f, -1.0f, -1.0f); positionArray[9] = new vec3(0.0f, 1.0f, 0.0f); positionArray[10] = new vec3(-1.0f, -1.0f, -1.0f); positionArray[11] = new vec3(-1.0f, -1.0f, 1.0f); // put positions into VBO GL.GenBuffers(1, positionBufferObject); GL.BindBuffer(BufferTarget.ArrayBuffer, positionBufferObject[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); positionArray.Dispose(); } // prepare vertex buffer object(VBO) for vertexes' colors uint[] colorBufferObject = new uint[1]; { // specify color array UnmanagedArray <vec3> colorArray = new UnmanagedArray <vec3>(vertexCount); colorArray[0] = new vec3(1.0f, 0.0f, 0.0f); colorArray[1] = new vec3(0.0f, 1.0f, 0.0f); colorArray[2] = new vec3(0.0f, 0.0f, 1.0f); colorArray[3] = new vec3(1.0f, 0.0f, 0.0f); colorArray[4] = new vec3(0.0f, 0.0f, 1.0f); colorArray[5] = new vec3(0.0f, 1.0f, 0.0f); colorArray[6] = new vec3(1.0f, 0.0f, 0.0f); colorArray[7] = new vec3(0.0f, 1.0f, 0.0f); colorArray[8] = new vec3(0.0f, 0.0f, 1.0f); colorArray[9] = new vec3(1.0f, 0.0f, 0.0f); colorArray[10] = new vec3(0.0f, 0.0f, 1.0f); colorArray[11] = new vec3(0.0f, 1.0f, 0.0f); // put colors into VBO GL.GenBuffers(1, colorBufferObject); GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferObject[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); colorArray.Dispose(); } uint positionLocation = shaderProgram.GetAttributeLocation("in_Position"); uint colorLocation = shaderProgram.GetAttributeLocation("in_Color"); { // bind the vertex array object(VAO), we are going to specify data for it. GL.BindVertexArray(vertexArrayObject[0]); // specify vertexes' positions GL.BindBuffer(BufferTarget.ArrayBuffer, positionBufferObject[0]); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); // specify vertexes' colors GL.BindBuffer(BufferTarget.ArrayBuffer, colorBufferObject[0]); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); // Unbind the vertex array object(VAO), we've finished specifying data for it. GL.BindVertexArray(0); } }
static public void UpdateConditions() { var assembly = new UnmanagedArray <System.Byte>(); assembly.Add(new System.Byte[3] { 0x0F, 0x57, 0xC0 }); // xorps xmm0, xmm0 assembly.Add(new System.Byte[3] { 0x0F, 0x2F, 0xC8 }); // comiss xmm1, xmm0 assembly.Add(new System.Byte[2] { 0x77, 5 + 8 }); // ja D (elapsedTime <= 0.0F) assembly.Add(new System.Byte[8] { 0xF3, 0x0F, 0x11, 0xB7, 0x8C, 0x00, 0x00, 0x00 }); // movss [rdi+8C], xmm6 (padding8C = frameTime) assembly.Add(new System.Byte[5] { 0xE9, 0x6C - ((3 + 3 + 2) + (8 + 5)) + 0x87, 0x00, 0x00, 0x00 }); // jmp DE (Skip) assembly.Add(new System.Byte[8] { 0xF3, 0x0F, 0x10, 0x97, 0x8C, 0x00, 0x00, 0x00 }); // movss xmm2, [rdi+8C] assembly.Add(new System.Byte[3] { 0x0F, 0x2F, 0xD0 }); // comiss xmm2, xmm0 assembly.Add(new System.Byte[2] { 0x76, (5 + 4 + 4 + 3 + 2) + (4 + 8 + 5) }); // jna 23 (padding8C > 0.0F) assembly.Add(new System.Byte[5] { 0xB9, 0x01, 0x00, 0x00, 0x00 }); // mov ecx, 1 assembly.Add(new System.Byte[4] { 0xF3, 0x0F, 0x2A, 0xC1 }); // cvtsi2ss xmm0, ecx assembly.Add(new System.Byte[4] { 0xF3, 0x0F, 0x5E, 0xC3 }); // divss xmm0,xmm3 assembly.Add(new System.Byte[3] { 0x0F, 0x2F, 0xC2 }); // comiss xmm0, xmm2 assembly.Add(new System.Byte[2] { 0x76, (4 + 8 + 5) }); // jna 11 (activeEffectConditionUpdateInterval > padding8C) assembly.Add(new System.Byte[4] { 0xF3, 0x0F, 0x58, 0xD6 }); // addss xmm2, xmm6 assembly.Add(new System.Byte[8] { 0xF3, 0x0F, 0x11, 0x97, 0x8C, 0x00, 0x00, 0x00 }); // movss [rdi+8C], xmm2 (padding8C += frameTime) assembly.Add(new System.Byte[5] { 0xE9, 0x6C - ((3 + 3 + 2) + (8 + 5) + (8 + 3 + 2) + (5 + 4 + 4 + 3 + 2) + (4 + 8 + 5)) + 0x87, 0x00, 0x00, 0x00 }); // jmp AE (Skip) assembly.Add(new System.Byte[8] { 0xF3, 0x0F, 0x11, 0xB7, 0x8C, 0x00, 0x00, 0x00 }); // movss [rdi+8C], xmm6 (padding8C = frameTime) assembly.Add(new System.Byte[2] { 0xEB, 0x6C - ((3 + 3 + 2) + (8 + 5) + (8 + 3 + 2) + (5 + 4 + 4 + 3 + 2) + (4 + 8 + 5) + (8 + 2)) }); // jmp 1D (Update) Memory.SafeFill <System.Byte>(ScrambledBugs.Offsets.Fixes.MagicEffectConditions.UpdateConditions, 0x6C, Assembly.Nop); Memory.SafeWrite <System.Byte>(ScrambledBugs.Offsets.Fixes.MagicEffectConditions.UpdateConditions, assembly); // ecx // eflags // xmm0 // xmm2 // activeEffect != null /* * ActiveEffect* activeEffect; // rdi * System.Single elapsedTime; // xmm1 * System.Single activeEffectConditionUpdateFrequency; // xmm3 * System.Single frameTime; // xmm6 * * if (elapsedTime <= 0.0F) * { * activeEffect->Padding8C(frameTime); * * goto Skip; * } * * System.Single padding8C = activeEffect->Padding8C(); * * if (padding8C > 0.0F) * { * System.Single activeEffectConditionUpdateInterval = 1.0F / activeEffectConditionUpdateFrequency; * * if (padding8C < activeEffectConditionUpdateInterval) * { * activeEffect->Padding8C(padding8C + frameTime); * * goto Skip; * } * } * * activeEffect->Padding8C(frameTime); * * goto Update; */ }
public GuardedByteArray(UnmanagedArray <byte> clearBytes) { _target = new SecureString(); AppendBytes(clearBytes); }
public void Access(UnmanagedArray <char> clearBytes) { _accessor(clearBytes); }
private void InitVAO() { this.axisPrimitiveMode = DrawMode.Lines; this.axisVertexCount = 8 * 3; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray<vec3> positionArray = new UnmanagedArray<vec3>(8 * 3); const float halfLength = 0.5f; // x axis positionArray[0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[1] = new vec3(halfLength, -halfLength, -halfLength); positionArray[2] = new vec3(-halfLength, -halfLength, halfLength); positionArray[3] = new vec3(halfLength, -halfLength, halfLength); positionArray[4] = new vec3(-halfLength, halfLength, halfLength); positionArray[5] = new vec3(halfLength, halfLength, halfLength); positionArray[6] = new vec3(-halfLength, halfLength, -halfLength); positionArray[7] = new vec3(halfLength, halfLength, -halfLength); // y axis positionArray[8 + 0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[8 + 1] = new vec3(-halfLength, halfLength, -halfLength); positionArray[8 + 2] = new vec3(-halfLength, -halfLength, halfLength); positionArray[8 + 3] = new vec3(-halfLength, halfLength, halfLength); positionArray[8 + 4] = new vec3(halfLength, -halfLength, halfLength); positionArray[8 + 5] = new vec3(halfLength, halfLength, halfLength); positionArray[8 + 6] = new vec3(halfLength, -halfLength, -halfLength); positionArray[8 + 7] = new vec3(halfLength, halfLength, -halfLength); // z axis positionArray[16 + 0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[16 + 1] = new vec3(-halfLength, -halfLength, halfLength); positionArray[16 + 2] = new vec3(-halfLength, halfLength, -halfLength); positionArray[16 + 3] = new vec3(-halfLength, halfLength, halfLength); positionArray[16 + 4] = new vec3(halfLength, halfLength, -halfLength); positionArray[16 + 5] = new vec3(halfLength, halfLength, halfLength); positionArray[16 + 6] = new vec3(halfLength, -halfLength, -halfLength); positionArray[16 + 7] = new vec3(halfLength, -halfLength, halfLength); uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { UnmanagedArray<vec3> colorArray = new UnmanagedArray<vec3>(8 * 3); vec3[] colors = new vec3[] { new vec3(1, 0, 0), new vec3(0, 1, 0), new vec3(0, 0, 1), }; for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = colors[i / 8]; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
protected override void DoInitialize() { render_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.VertexShader, render_vs); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.FragmentShader, render_fs); GL.LinkProgram(render_prog); GL.UseProgram(render_prog); view_matrix_loc = GL.GetUniformLocation(render_prog, "view_matrix"); projection_matrix_loc = GL.GetUniformLocation(render_prog, "projection_matrix"); vboObject.LoadFromVBM(@"media\armadillo_low.vbm", 0, 1, 2); // Bind its vertex array object so that we can append the instanced attributes vboObject.BindVertexArray(); // Get the locations of the vertex attributes in 'prog', which is the // (linked) program object that we're going to be rendering with. Note // that this isn't really necessary because we specified locations for // all the attributes in our vertex shader. This code could be made // more concise by assuming the vertex attributes are where we asked // the compiler to put them. int position_loc = GL.GetAttribLocation(render_prog, "position"); int normal_loc = GL.GetAttribLocation(render_prog, "normal"); int color_loc = GL.GetAttribLocation(render_prog, "color"); int matrix_loc = GL.GetAttribLocation(render_prog, "model_matrix"); // Generate the colors of the objects var colors = new UnmanagedArray<vec4>(INSTANCE_COUNT); for (int n = 0; n < INSTANCE_COUNT; n++) { float a = (float)(n) / 4.0f; float b = (float)(n) / 5.0f; float c = (float)(n) / 6.0f; colors[n] = new vec4( (float)(0.5f + 0.25f * (Math.Sin(a + 1.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(b + 2.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(c + 3.0f) + 1.0f)), (float)(1.0f) ); } GL.GenBuffers(1, color_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, colors, BufferUsage.DynamicDraw); colors.Dispose(); // Now we set up the color array. We want each instance of our geometry // to assume a different color, so we'll just pack colors into a buffer // object and make an instanced vertex attribute out of it. GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.VertexAttribPointer((uint)color_loc, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray((uint)color_loc); // This is the important bit... set the divisor for the color array to // 1 to get OpenGL to give us a new value of 'color' per-instance // rather than per-vertex. GL.VertexAttribDivisor((uint)color_loc, 1); // Likewise, we can do the same with the model matrix. Note that a // matrix input to the vertex shader consumes N consecutive input // locations, where N is the number of columns in the matrix. So... // we have four vertex attributes to set up. UnmanagedArray<mat4> tmp = new UnmanagedArray<mat4>(INSTANCE_COUNT); GL.GenBuffers(1, model_matrix_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, model_matrix_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicDraw); tmp.Dispose(); // Loop over each column of the matrix... for (int i = 0; i < 4; i++) { // Set up the vertex attribute GL.VertexAttribPointer((uint)(matrix_loc + i), // Location 4, GL.GL_FLOAT, false, // vec4 Marshal.SizeOf(typeof(mat4)), // Stride new IntPtr(Marshal.SizeOf(typeof(vec4)) * i)); // Start offset // Enable it GL.EnableVertexAttribArray((uint)(matrix_loc + i)); // Make it instanced GL.VertexAttribDivisor((uint)(matrix_loc + i), 1); } // Done (unbind the object's VAO) GL.BindVertexArray(0); }
/// <summary> /// Read pixels in specified rect and get the VertexIds they represent. /// </summary> /// <param name="target"></param> /// <returns></returns> private static unsafe List<Tuple<Point, uint>> ReadPixels(Rectangle target) { var result = new List<Tuple<Point, uint>>(); // get coded color. using (var codedColor = new UnmanagedArray<Pixel>(target.Width * target.Height)) { OpenGL.ReadPixels(target.X, target.Y, target.Width, target.Height, OpenGL.GL_RGBA, OpenGL.GL_UNSIGNED_BYTE, codedColor.Header); var array = (Pixel*)codedColor.Header.ToPointer(); int index = 0; var vertexIdList = new List<uint>(); for (int yOffset = target.Height - 1; yOffset >= 0; yOffset--) { for (int xOffset = 0; xOffset < target.Width; xOffset++) { Pixel pixel = array[index++]; // This is when (x, y) is not on background and some primitive is picked. if (!pixel.IsWhite()) { uint stageVertexId = pixel.ToStageVertexId(); if (!vertexIdList.Contains(stageVertexId)) { result.Add(new Tuple<Point, uint>( new Point(target.X + xOffset, target.Y + yOffset), stageVertexId)); vertexIdList.Add(stageVertexId); } } } } } return result; }
protected override void DoInitialize() { // Initialize our compute program compute_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(compute_prog, ShaderType.ComputerShader, compute_shader_source); GL.LinkProgram(compute_prog); dt_location = GL.GetUniformLocation(compute_prog, "dt"); GL.GenVertexArrays(1, render_vao); GL.BindVertexArray(render_vao[0]); GL.GenBuffers(2, buffers); { GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[0]);//position buffer UnmanagedArray<vec4> tmp = new UnmanagedArray<vec4>(PARTICLE_COUNT); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicCopy); tmp.Dispose(); IntPtr positions = GL.MapBufferRange(GL.GL_ARRAY_BUFFER, 0, PARTICLE_COUNT * Marshal.SizeOf(typeof(vec4)), GL.GL_MAP_WRITE_BIT | GL.GL_MAP_INVALIDATE_BUFFER_BIT); unsafe { vec4* array = (vec4*)positions.ToPointer(); for (int i = 0; i < PARTICLE_COUNT; i++) { array[i] = new vec4(Vec3Helper.GetRandomVec3(), (float)random.NextDouble()); } } GL.UnmapBuffer(BufferTarget.ArrayBuffer); GL.VertexAttribPointer(0, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(0); } { GL.BindBuffer(BufferTarget.ArrayBuffer, buffers[1]);// velocity buffer UnmanagedArray<vec4> tmp = new UnmanagedArray<vec4>(PARTICLE_COUNT); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicCopy); tmp.Dispose(); IntPtr velocities = GL.MapBufferRange(GL.GL_ARRAY_BUFFER, 0, PARTICLE_COUNT * Marshal.SizeOf(typeof(vec4)), GL.GL_MAP_WRITE_BIT | GL.GL_MAP_INVALIDATE_BUFFER_BIT); unsafe { vec4* array = (vec4*)velocities.ToPointer(); for (int i = 0; i < PARTICLE_COUNT; i++) { array[i] = new vec4(Vec3Helper.GetRandomVec3(), (float)random.NextDouble()); } } GL.UnmapBuffer(BufferTarget.ArrayBuffer); } { GL.GenTextures(2, tbos); for (int i = 0; i < 2; i++) { GL.BindTexture(GL.GL_TEXTURE_BUFFER, tbos[i]); GL.TexBuffer(GL.GL_TEXTURE_BUFFER, GL.GL_RGBA32F, buffers[i]); } } { GL.GenBuffers(1, attractor_buffer); GL.BindBuffer(BufferTarget.UniformBuffer, attractor_buffer[0]); UnmanagedArray<vec4> tmp = new UnmanagedArray<vec4>(32); GL.BufferData(BufferTarget.UniformBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); for (int i = 0; i < MAX_ATTRACTORS; i++) { attractor_masses[i] = 0.5f + (float)random.NextDouble() * 0.5f; } GL.BindBufferBase(TransformFeedbackBufferTarget.UniformBuffer, 0, attractor_buffer[0]); } { render_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.VertexShader, render_vs); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.FragmentShader, render_fs); GL.LinkProgram(render_prog); } }
//private void glCanvas1_MouseClick(object sender, MouseEventArgs e) //{ // if (e.Button == System.Windows.Forms.MouseButtons.Right) // { // IPickedGeometry pickedGeometry = this.Pick(e.X, e.Y); // if (pickedGeometry != null) // { // this.txtPickedInfo.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss.ff} {1}", // DateTime.Now, pickedGeometry); // } // else // { // this.txtPickedInfo.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss.ff} {1}", // DateTime.Now, "nothing picked"); // } // } //} private IPickedGeometry Pick(int x, int y) { //this.glCanvas1.MakeCurrent(); // render the scene for color-coded picking. GL.ClearColor(1.0f, 1.0f, 1.0f, 1.0f); GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT); SharedStageInfo info = new SharedStageInfo(); info.Reset(); var arg = new RenderEventArgs(RenderModes.HitTest, this.camera); IColorCodedPicking pickable = this.element; info.RenderForPicking(pickable, arg); GL.Flush(); // get coded color. //byte[] codedColor = new byte[4]; UnmanagedArray<byte> codedColor = new UnmanagedArray<byte>(4); GL.ReadPixels(x, this.glCanvas1.Height - y - 1, 1, 1, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, codedColor.Header); if (codedColor[0] == byte.MaxValue && codedColor[1] == byte.MaxValue && codedColor[2] == byte.MaxValue && codedColor[3] == byte.MaxValue) { // This is when (x, y) is on background and no primitive is picked. return null; } /* // This is how is vertexID coded into color in vertex shader. * int objectID = gl_VertexID; codedColor = vec4( float(objectID & 0xFF), float((objectID >> 8) & 0xFF), float((objectID >> 16) & 0xFF), float((objectID >> 24) & 0xFF)); */ // get vertexID from coded color. // the vertexID is the last vertex that constructs the primitive. // see http://www.cnblogs.com/bitzhuwei/p/modern-opengl-picking-primitive-in-VBO-2.html uint shiftedR = (uint)codedColor[0]; uint shiftedG = (uint)codedColor[1] << 8; uint shiftedB = (uint)codedColor[2] << 16; uint shiftedA = (uint)codedColor[3] << 24; uint stageVertexID = shiftedR + shiftedG + shiftedB + shiftedA; // get picked primitive. IPickedGeometry pickedGeometry = null; pickedGeometry = ((IColorCodedPicking)this.element).Pick(stageVertexID); return pickedGeometry; }
public HeightfieldColliderShape(int heightStickWidth, int heightStickLength, UnmanagedArray <byte> dynamicFieldData, float heightScale, float minHeight, float maxHeight, bool flipQuadEdges) : base(heightStickWidth, heightStickLength, dynamicFieldData, heightScale, minHeight, maxHeight, flipQuadEdges) { }
public static bool VerifyBase64SHA1Hash(UnmanagedArray <char> input, string hash) { string inputHash = ComputeBase64SHA1Hash(input); return(inputHash.Equals(hash)); }
protected override void DoInitialize() { // Now create a simple program to visualize the result basicShaderProgram = new ShaderProgram(); basicShaderProgram.Create(basicVertexShader, basicFragmentShader, null); basicShaderProgram.AssertValid(); base_model_matrix_pos = GL.GetUniformLocation(basicShaderProgram.ShaderProgramObject, "model_matrix"); base_projection_matrix_pos = GL.GetUniformLocation(basicShaderProgram.ShaderProgramObject, "projection_matrix"); fur_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.VertexShader, furVertexShader); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.GeometryShader, furGeometryShader); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.FragmentShader, furFragmentShader); GL.LinkProgram(fur_prog); GL.UseProgram(fur_prog); fur_model_matrix_pos = GL.GetUniformLocation(fur_prog, "model_matrix"); fur_projection_matrix_pos = GL.GetUniformLocation(fur_prog, "projection_matrix"); GL.GenTextures(1, fur_texture); UnmanagedArray<byte> tex = new UnmanagedArray<byte>(1024 * 1024 * 4); Random random = new Random(); for (int n = 0; n < 256; n++) { for (int m = 0; m < 1270; m++) { int x = random.Next() & 0x3FF; int y = random.Next() & 0x3FF; tex[(y * 1024 + x) * 4 + 0] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 1] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 2] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 3] = (byte)(n); //tex[(y * 1024 + x) * 4 + 0] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 1] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 2] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 3] = (byte)(random.Next()); } } GL.BindTexture(GL.GL_TEXTURE_2D, fur_texture[0]); GL.TexImage2D(TexImage2DTargets.Texture2D, 0, TexImage2DFormats.RGBA, 1024, 1024, 0, TexImage2DFormats.RGBA, TexImage2DTypes.UnsignedByte, tex.Header); GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR); GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR); tex.Dispose(); vboObject.LoadFromVBM(@"media\ninja.vbm", 0, 1, 2); base.BeforeRendering += LightingExample_BeforeRendering; base.AfterRendering += LightingExample_AfterRendering; }
//protected void InitializeVAO(out uint[] vao, out DrawMode primitiveMode, out int vertexCount) protected void InitializeVAO() { this.primitiveMode = DrawMode.Triangles; this.vertexCount = positions.Length; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { //uint[] ids = new uint[1]; this.positionBufferObject = new uint[1]; GL.GenBuffers(1, this.positionBufferObject); GL.BindBuffer(BufferTarget.ArrayBuffer, this.positionBufferObject[0]); UnmanagedArray<vec3> positionArray = new UnmanagedArray<vec3>(positions.Length); for (int i = 0; i < positions.Length; i++) { positionArray[i] = positions[i]; } uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { //uint[] ids = new uint[1]; this.colorBufferObject = new uint[1]; GL.GenBuffers(1, this.colorBufferObject); GL.BindBuffer(BufferTarget.ArrayBuffer, this.colorBufferObject[0]); UnmanagedArray<vec3> colorArray = new UnmanagedArray<vec3>(positions.Length); for (int i = 0; i < colors.Length; i++) { colorArray[i] = colors[i]; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
public static void TypicalScene() { const int count = 1000000; long startTick = 0; long interval, interval2; // 测试float类型 { var floatArray = new UnmanagedArray<float>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { floatArray[i] = i; } for (int i = 0; i < count; i++) { var item = floatArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; float* header = (float*)floatArray.FirstElement(); float* last = (float*)floatArray.LastElement(); float* tailAddress = (float*)floatArray.TailAddress(); int value = 0; for (float* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (float* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试decimal类型 { var decimalArray = new UnmanagedArray<decimal>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { decimalArray[i] = i; } for (int i = 0; i < count; i++) { var item = decimalArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; decimal* header = (decimal*)decimalArray.FirstElement(); decimal* last = (decimal*)decimalArray.LastElement(); decimal* tailAddress = (decimal*)decimalArray.TailAddress(); int value = 0; for (decimal* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (decimal* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试int类型 { var intArray = new UnmanagedArray<int>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { intArray[i] = i; } for (int i = 0; i < count; i++) { var item = intArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; int* header = (int*)intArray.FirstElement(); int* last = (int*)intArray.LastElement(); int* tailAddress = (int*)intArray.TailAddress(); int value = 0; for (int* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (int* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试bool类型 { var boolArray = new UnmanagedArray<bool>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { boolArray[i] = i % 2 == 0; } for (int i = 0; i < count; i++) { var item = boolArray[i]; if (item != (i % 2 == 0)) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; bool* header = (bool*)boolArray.FirstElement(); bool* last = (bool*)boolArray.LastElement(); bool* tailAddress = (bool*)boolArray.TailAddress(); int value = 0; for (bool* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = (value % 2 == 0); value++; } int i = 0; for (bool* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != (i % 2 == 0)) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试vec3类型 { var vec3Array = new UnmanagedArray<vec3>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { vec3Array[i] = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); } for (int i = 0; i < count; i++) { var item = vec3Array[i]; var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); if (item.x != old.x || item.y != old.y || item.z != old.z) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; vec3* header = (vec3*)vec3Array.FirstElement(); vec3* last = (vec3*)vec3Array.LastElement(); vec3* tailAddress = (vec3*)vec3Array.TailAddress(); int i = 0; for (vec3* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); i++; } i = 0; for (vec3* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); if (item.x != old.x || item.y != old.y || item.z != old.z) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试mat4类型 { var vec3Array = new UnmanagedArray<mat4>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { vec3Array[i] = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); } for (int i = 0; i < count; i++) { var item = vec3Array[i]; var old = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { if (item[col][row] != old[col][row]) { throw new Exception(); } } } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; mat4* header = (mat4*)vec3Array.FirstElement(); mat4* last = (mat4*)vec3Array.LastElement(); mat4* tailAddress = (mat4*)vec3Array.TailAddress(); int i = 0; for (mat4* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++) { *ptr = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); i++; } i = 0; for (mat4* ptr = header; ptr <= last/*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; var old = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { if (item[col][row] != old[col][row]) { throw new Exception(); } } } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 立即释放所有非托管数组占用的内存,任何之前创建的UnmanagedBase数组都不再可用了。 UnmanagedArray<int>.FreeAll(); }
public bool LoadFromVBM(string filename, int vertexIndex, int normalIndex, int texCoord0Index) { //FILE * f = NULL; FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(f); //f = fopen(filename, "rb"); //if(f == NULL) //return false; //fseek(f, 0, SEEK_END); //size_t filesize = ftell(f); //fseek(f, 0, SEEK_SET); long filesize = f.Length; //f.Seek(0, SeekOrigin.End); //f.Seek(0, SeekOrigin.Begin); byte[] data = new byte[filesize]; UnmanagedArray <byte> raw_data; f.Read(data, 0, (int)filesize); //f.Close(); f.Seek(0, SeekOrigin.Begin); //VBM_HEADER * header = (VBM_HEADER *)data; VBM_HEADER header = br.ReadStruct <VBM_HEADER>(); //raw_data = data + header.size + header->num_attribs * sizeof(VBM_ATTRIB_HEADER) + header->num_frames * sizeof(VBM_FRAME_HEADER); //{ // long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); // raw_data = new UnmanagedArray<byte>((int)(data.Length - offset)); // for (int i = 0; i < raw_data.Length; i++) // { // raw_data[i] = data[offset+i]; // } //} //VBM_ATTRIB_HEADER * attrib_header = (VBM_ATTRIB_HEADER *)(data + header.size); VBM_ATTRIB_HEADER attrib_header = br.ReadStruct <VBM_ATTRIB_HEADER>(); //VBM_FRAME_HEADER * frame_header = (VBM_FRAME_HEADER *)(data + header.size + header.num_attribs * sizeof(VBM_ATTRIB_HEADER)); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } VBM_FRAME_HEADER frame_header = br.ReadStruct <VBM_FRAME_HEADER>(); uint total_data_size = 0; //memcpy(&m_header, header, header.size < Marshal.SizeOf(typeof(VBM_HEADER)) ? header.size : Marshal.SizeOf(typeof(VBM_HEADER))); this.m_header = header; //memcpy(m_attrib, attrib_header, header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER))); { long offset = header.size;// +header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_attrib = new VBM_ATTRIB_HEADER[header.num_attribs]; for (int i = 0; i < header.num_attribs; i++) { this.m_attrib[i] = br.ReadStruct <VBM_ATTRIB_HEADER>(); } //memcpy(m_frame, frame_header, header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER))); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER));// +header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_frame = new VBM_FRAME_HEADER[header.num_frames]; for (int i = 0; i < header.num_frames; i++) { this.m_frame[i] = br.ReadStruct <VBM_FRAME_HEADER>(); } GL.GenVertexArrays(1, m_vao); GL.BindVertexArray(m_vao[0]); GL.GenBuffers(1, m_attribute_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, m_attribute_buffer[0]); //uint i; for (uint i = 0; i < header.num_attribs; i++) { total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); raw_data = new UnmanagedArray <byte>((int)total_data_size); for (int i = 0; i < raw_data.Length; i++) { raw_data[i] = data[offset + i]; } } //GL.BufferData(GL_ARRAY_BUFFER, total_data_size, raw_data, GL_STATIC_DRAW); GL.BufferData(BufferTarget.ArrayBuffer, raw_data, BufferUsage.StaticDraw); total_data_size = 0; for (uint i = 0; i < header.num_attribs; i++) { uint attribIndex = i; if (attribIndex == 0) { attribIndex = (uint)vertexIndex; } else if (attribIndex == 1) { attribIndex = (uint)normalIndex; } else if (attribIndex == 2) { attribIndex = (uint)texCoord0Index; } GL.VertexAttribPointer(attribIndex, (int)m_attrib[i].components, m_attrib[i].type, false, 0, new IntPtr(total_data_size)); GL.EnableVertexAttribArray(attribIndex); total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } if (header.num_indices > 0) { GL.GenBuffers(1, m_index_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, m_index_buffer[0]); uint element_size; if (header.indexype == 0x1403) { element_size = sizeof(ushort); } else { element_size = sizeof(uint); } //GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, header.num_indices * element_size, raw_data + total_data_size, GL_STATIC_DRAW); UnmanagedArray <byte> tmp = new UnmanagedArray <byte>((int)(header.num_indices * element_size)); for (int t = 0; t < tmp.Length; t++) { tmp[t] = raw_data[(int)(t + total_data_size)]; } GL.BufferData(BufferTarget.ElementArrayBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); } GL.BindVertexArray(0); if (m_header.num_materials != 0) { m_material = new VBM_MATERIAL[m_header.num_materials]; //memcpy(m_material, raw_data + total_data_size, m_header.num_materials * sizeof(VBM_MATERIAL)); { var offset = header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material[t] = br.ReadStruct <VBM_MATERIAL>(); } total_data_size += (uint)(m_header.num_materials * Marshal.SizeOf(typeof(VBM_MATERIAL))); m_material_textures = new material_texture[m_header.num_materials]; //memset(m_material_textures, 0, m_header.num_materials * sizeof(*m_material_textures)); { var offset = 0; f.Seek(0, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material_textures[t] = br.ReadStruct <material_texture>(); } } if (m_header.num_chunks != 0) { m_chunks = new VBM_RENDER_CHUNK[m_header.num_chunks]; //memcpy(m_chunks, raw_data + total_data_size, m_header.num_chunks * sizeof(VBM_RENDER_CHUNK)); { var offset = m_header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_chunks; t++) { m_chunks[t] = br.ReadStruct <VBM_RENDER_CHUNK>(); } //total_data_size += m_header.num_chunks * sizeof(VBM_RENDER_CHUNK); } raw_data.Dispose(); return(true); }
private void InitVAO() { int size = this.size; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // prepare positions { var positionArray = new UnmanagedArray <vec3>(size * size * size * 14); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { positionArray[index++] = unitCubePos[cubeIndex] + new vec3((i - size / 2) * unitSpace, (j - size / 2) * unitSpace, (k - size / 2) * unitSpace); } } } } uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // prepare colors { var colorArray = new UnmanagedArray <vec3>(size * size * size * 14); Random random = new Random(); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { //vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); colorArray[index++] = color; } } } } uint in_ColorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); // prepare firsts and counts { // todo: rename 'size' this.firsts = new int[size * size * size]; for (int i = 0; i < this.firsts.Length; i++) { this.firsts[i] = i * 14; } this.counts = new int[size * size * size]; for (int i = 0; i < this.counts.Length; i++) { this.counts[i] = 14; } } }
protected void InitializeVAO(out uint[] vao, out DrawMode primitiveMode, out int vertexCount) { primitiveMode = DrawMode.QuadStrip;// PrimitiveModes.QuadStrip; vertexCount = faceCount * 2; vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); UnmanagedArray<vec3> positionArray = new UnmanagedArray<vec3>(faceCount * 2); for (int i = 0; i < faceCount * 2; i++) { int face = i / 2; positionArray[i] = new vec3( (float)(this.radius * Math.Cos(face * (Math.PI * 2) / faceCount)), (i % 2 == 1 ? -1 : 1) * this.height / 2, (float)(this.radius * Math.Sin(face * (Math.PI * 2) / faceCount)) ); } uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); UnmanagedArray<vec3> colorArray = new UnmanagedArray<vec3>(faceCount * 2); for (int i = 0; i < colorArray.Length; i++) { if (i % 2 == 0) { colorArray[i] = new vec3(1, 0, 0); //new vec3((i % 3) / 3.0f, (i + 1) % 3 / 3.0f, (i + 2) % 3 / 3.0f); } else { colorArray[i] = new vec3(0, 1, 0); //new vec3((i % 3) / 3.0f, (i + 1) % 3 / 3.0f, (i + 2) % 3 / 3.0f); } } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); } { uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ids[0]); UnmanagedArray<uint> cylinderIndex = new UnmanagedArray<uint>(faceCount * 2 + 2); for (int i = 0; i < cylinderIndex.Length - 2; i++) { cylinderIndex[i] = (uint)i; } cylinderIndex[cylinderIndex.Length - 2] = 0; cylinderIndex[cylinderIndex.Length - 1] = 1; GL.BufferData(BufferTarget.ElementArrayBuffer, cylinderIndex, BufferUsage.StaticDraw); cylinderIndex.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
private void InitVAO() { primitiveMode = PrimitiveModes.Points; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray<vec3> in_Position = new UnmanagedArray<vec3>(1); in_Position[0] = this.position; uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, in_Position, BufferUsage.StaticDraw); GL.VertexAttribPointer(attributeIndexPosition, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(attributeIndexPosition); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
public bool LoadFromVBM(string filename, int vertexIndex, int normalIndex, int texCoord0Index) { FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(f); long filesize = f.Length; byte[] data = new byte[filesize]; UnmanagedArray <byte> raw_data; f.Read(data, 0, (int)filesize); f.Seek(0, SeekOrigin.Begin); VBM_HEADER header = br.ReadStruct <VBM_HEADER>(); VBM_ATTRIB_HEADER attrib_header = br.ReadStruct <VBM_ATTRIB_HEADER>(); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } VBM_FRAME_HEADER frame_header = br.ReadStruct <VBM_FRAME_HEADER>(); uint total_data_size = 0; this.m_header = header; { long offset = header.size;// +header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_attrib = new VBM_ATTRIB_HEADER[header.num_attribs]; for (int i = 0; i < header.num_attribs; i++) { this.m_attrib[i] = br.ReadStruct <VBM_ATTRIB_HEADER>(); } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER));// +header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_frame = new VBM_FRAME_HEADER[header.num_frames]; for (int i = 0; i < header.num_frames; i++) { this.m_frame[i] = br.ReadStruct <VBM_FRAME_HEADER>(); } GL.GenVertexArrays(1, m_vao); GL.BindVertexArray(m_vao[0]); GL.GenBuffers(1, m_attribute_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, m_attribute_buffer[0]); //uint i; for (uint i = 0; i < header.num_attribs; i++) { total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); raw_data = new UnmanagedArray <byte>((int)total_data_size); for (int i = 0; i < raw_data.Length; i++) { raw_data[i] = data[offset + i]; } } //GL.BufferData(GL_ARRAY_BUFFER, total_data_size, raw_data, GL_STATIC_DRAW); GL.BufferData(BufferTarget.ArrayBuffer, raw_data, BufferUsage.StaticDraw); total_data_size = 0; for (uint i = 0; i < header.num_attribs; i++) { uint attribIndex = i; if (attribIndex == 0) { attribIndex = (uint)vertexIndex; } else if (attribIndex == 1) { attribIndex = (uint)normalIndex; } else if (attribIndex == 2) { attribIndex = (uint)texCoord0Index; } GL.VertexAttribPointer(attribIndex, (int)m_attrib[i].components, m_attrib[i].type, false, 0, new IntPtr(total_data_size)); GL.EnableVertexAttribArray(attribIndex); total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } if (header.num_indices > 0) { GL.GenBuffers(1, m_index_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, m_index_buffer[0]); uint element_size; if (header.indexype == 0x1403) { element_size = sizeof(ushort); } else { element_size = sizeof(uint); } //GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, header.num_indices * element_size, raw_data + total_data_size, GL_STATIC_DRAW); UnmanagedArray <byte> tmp = new UnmanagedArray <byte>((int)(header.num_indices * element_size)); for (int t = 0; t < tmp.Length; t++) { tmp[t] = raw_data[(int)(t + total_data_size)]; } GL.BufferData(BufferTarget.ElementArrayBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); } GL.BindVertexArray(0); raw_data.Dispose(); return(true); }
private void InitVAO() { this.axisPrimitiveMode = DrawMode.QuadStrip; GLColor[] colors = this.ColorPalette.Colors; float[] coords = this.ColorPalette.Coords; this.numbers = new PointSpriteStringElement[coords.Length]; this.vertexCount = coords.Length * 2; this.vao = new uint[1]; float coordLength = coords[coords.Length - 1] - coords[0]; { GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray <vec3> positionArray = new UnmanagedArray <vec3>(this.vertexCount); positionArray[0] = new vec3(-0.5f, -0.5f, 0); positionArray[1] = new vec3(-0.5f, 0.5f, 0); for (int i = 1; i < coords.Length; i++) { float x = (coords[i] - coords[0]) / coordLength - 0.5f; positionArray[i * 2 + 0] = new vec3(x, -0.5f, 0); positionArray[i * 2 + 1] = new vec3(x, 0.5f, 0); } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { var colorArray = new UnmanagedArray <vec4>(this.vertexCount); for (int i = 0; i < colors.Length; i++) { GLColor color = colors[i]; colorArray[i * 2 + 0] = new vec4(color.R, color.G, color.B, color.A); colorArray[i * 2 + 1] = new vec4(color.R, color.G, color.B, color.A); } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); } // prepare numbers { const float numberPosY = -0.6f; this.numbers[0] = new PointSpriteStringElement( this.Min.ToShortString(), new vec3(-0.5f, numberPosY, 0)); this.numbers[0].Initialize(); for (int i = 1; i < coords.Length; i++) { float x = (coords[i] - coords[0]) / coordLength - 0.5f; if (i + 1 == coords.Length) { this.numbers[i] = new PointSpriteStringElement( (this.Min + i * this.Step).ToShortString(), new vec3(x, numberPosY, 0)); } else { this.numbers[i] = new PointSpriteStringElement( this.Max.ToShortString(), new vec3(x, numberPosY, 0)); } this.numbers[i].Initialize(); } } }
protected void InitializeVAO(OpenGL gl, out uint[] vao, out BeginMode primitiveMode, out int vertexCount) { primitiveMode = BeginMode.QuadStrip; vertexCount = (faceCount * 2 + 2) * (this.pipe.Count - 1); UnmanagedArray <Vertex> positionArray = new UnmanagedArray <Vertex>(vertexCount); { int index = 0; for (int i = 1; i < this.pipe.Count; i++) { Vertex p1 = this.pipe[i - 1]; Vertex p2 = this.pipe[i]; Vertex vector = p2 - p1;// 从p1到p2的向量 // 找到互相垂直的三个向量:vector, orthogontalVector1和orthogontalVector2 Vertex orthogontalVector1 = new Vertex(vector.Y - vector.Z, vector.Z - vector.X, vector.X - vector.Y); Vertex orthogontalVector2 = vector.VectorProduct(orthogontalVector1); orthogontalVector1.Normalize(); orthogontalVector2.Normalize(); orthogontalVector1 *= (float)Math.Sqrt(this.radius); orthogontalVector2 *= (float)Math.Sqrt(this.radius); for (int faceIndex = 0; faceIndex < faceCount + 1; faceIndex++) { double angle = (Math.PI * 2 * faceIndex) / faceCount; Vertex point = orthogontalVector1 * (float)Math.Cos(angle) + orthogontalVector2 * (float)Math.Sin(angle); positionArray[index++] = p2 + point; positionArray[index++] = p1 + point; } //positionArray[index++] = new vec3();//用于分割圆柱体 } } UnmanagedArray <Vertex> colorArray = new UnmanagedArray <Vertex>(vertexCount); { Vertex vColor = new Vertex(this.color.R, this.color.G, this.color.B); for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = vColor; // 测试时用此代码区分各个圆柱 //if ((i / (faceCount * 2 + 2)) % 3 == 0) //{ // colorArray[i] = new vec3(1, 0, 0); //} //else if ((i / (faceCount * 2 + 2)) % 3 == 1) //{ // colorArray[i] = new vec3(0, 1, 0); //} //else //{ // colorArray[i] = new vec3(0, 0, 1); //} } } UnmanagedArray <uint> indexArray = new UnmanagedArray <uint>(vertexCount + (this.pipe.Count - 1)); { uint positionIndex = 0; for (int i = 0; i < indexArray.Length; i++) { if (i % (faceCount * 2 + 2 + 1) == (faceCount * 2 + 2)) { indexArray[i] = uint.MaxValue;//分割各个圆柱体 } else { indexArray[i] = positionIndex++; } } } vao = new uint[1]; gl.GenVertexArrays(1, vao); gl.BindVertexArray(vao[0]); { uint[] ids = new uint[1]; gl.GenBuffers(1, ids); gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, ids[0]); int location = gl.GetAttribLocation(shaderProgram.ShaderProgramObject, strin_Position); if (location < 0) { throw new Exception(); } uint positionLocation = (uint)location; gl.BufferData(OpenGL.GL_ARRAY_BUFFER, positionArray.ByteLength, positionArray.Header, OpenGL.GL_STATIC_DRAW); gl.VertexAttribPointer(positionLocation, 3, OpenGL.GL_FLOAT, false, 0, IntPtr.Zero); gl.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); this.positionBufferObject = ids[0]; } { uint[] ids = new uint[1]; gl.GenBuffers(1, ids); gl.BindBuffer(OpenGL.GL_ARRAY_BUFFER, ids[0]); int location = gl.GetAttribLocation(shaderProgram.ShaderProgramObject, strin_Color); if (location < 0) { throw new Exception(); } uint colorLocation = (uint)location; gl.BufferData(OpenGL.GL_ARRAY_BUFFER, colorArray.ByteLength, colorArray.Header, OpenGL.GL_STATIC_DRAW); gl.VertexAttribPointer(colorLocation, 3, OpenGL.GL_FLOAT, false, 0, IntPtr.Zero); gl.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); this.colorBufferObject = ids[0]; } { uint[] ids = new uint[1]; gl.GenBuffers(1, ids); gl.BindBuffer(OpenGL.GL_ELEMENT_ARRAY_BUFFER, ids[0]); gl.BufferData(OpenGL.GL_ELEMENT_ARRAY_BUFFER, indexArray.ByteLength, indexArray.Header, OpenGL.GL_STATIC_DRAW); indexArray.Dispose(); this.indexBufferObject = ids[0]; } // Unbind the vertex array, we've finished specifying data for it. gl.BindVertexArray(0); }
private void InitVAO() { this.axisPrimitiveMode = DrawMode.Lines; this.axisVertexCount = 8 * 3; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray <vec3> positionArray = new UnmanagedArray <vec3>(8 * 3); const float halfLength = 0.5f; // x axis positionArray[0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[1] = new vec3(halfLength, -halfLength, -halfLength); positionArray[2] = new vec3(-halfLength, -halfLength, halfLength); positionArray[3] = new vec3(halfLength, -halfLength, halfLength); positionArray[4] = new vec3(-halfLength, halfLength, halfLength); positionArray[5] = new vec3(halfLength, halfLength, halfLength); positionArray[6] = new vec3(-halfLength, halfLength, -halfLength); positionArray[7] = new vec3(halfLength, halfLength, -halfLength); // y axis positionArray[8 + 0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[8 + 1] = new vec3(-halfLength, halfLength, -halfLength); positionArray[8 + 2] = new vec3(-halfLength, -halfLength, halfLength); positionArray[8 + 3] = new vec3(-halfLength, halfLength, halfLength); positionArray[8 + 4] = new vec3(halfLength, -halfLength, halfLength); positionArray[8 + 5] = new vec3(halfLength, halfLength, halfLength); positionArray[8 + 6] = new vec3(halfLength, -halfLength, -halfLength); positionArray[8 + 7] = new vec3(halfLength, halfLength, -halfLength); // z axis positionArray[16 + 0] = new vec3(-halfLength, -halfLength, -halfLength); positionArray[16 + 1] = new vec3(-halfLength, -halfLength, halfLength); positionArray[16 + 2] = new vec3(-halfLength, halfLength, -halfLength); positionArray[16 + 3] = new vec3(-halfLength, halfLength, halfLength); positionArray[16 + 4] = new vec3(halfLength, halfLength, -halfLength); positionArray[16 + 5] = new vec3(halfLength, halfLength, halfLength); positionArray[16 + 6] = new vec3(halfLength, -halfLength, -halfLength); positionArray[16 + 7] = new vec3(halfLength, -halfLength, halfLength); uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { UnmanagedArray <vec3> colorArray = new UnmanagedArray <vec3>(8 * 3); vec3[] colors = new vec3[] { new vec3(1, 0, 0), new vec3(0, 1, 0), new vec3(0, 0, 1), }; for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = colors[i / 8]; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
} // end sub #endregion protected override void DoInitialize() { skybox_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(skybox_prog, ShaderType.VertexShader, skybox_shader_vs); ShaderHelper.vglAttachShaderSource(skybox_prog, ShaderType.FragmentShader, skybox_shader_fs); GL.LinkProgram(skybox_prog); object_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(object_prog, ShaderType.VertexShader, object_shader_vs); ShaderHelper.vglAttachShaderSource(object_prog, ShaderType.FragmentShader, object_shader_fs); GL.LinkProgram(object_prog); GL.GenBuffers(1, cube_vbo); GL.BindBuffer(BufferTarget.ArrayBuffer, cube_vbo[0]); var cube_vertices = new UnmanagedArray <vec3>(8); cube_vertices[0] = new vec3(-1.0f, -1.0f, -1.0f); cube_vertices[1] = new vec3(-1.0f, -1.0f, 1.0f); cube_vertices[2] = new vec3(-1.0f, 1.0f, -1.0f); cube_vertices[3] = new vec3(-1.0f, 1.0f, 1.0f); cube_vertices[4] = new vec3(1.0f, -1.0f, -1.0f); cube_vertices[5] = new vec3(1.0f, -1.0f, 1.0f); cube_vertices[6] = new vec3(1.0f, 1.0f, -1.0f); cube_vertices[7] = new vec3(1.0f, 1.0f, 1.0f); var cube_indices = new UnmanagedArray <ushort>(16); // First strip cube_indices[0] = 0; cube_indices[1] = 1; cube_indices[2] = 2; cube_indices[3] = 3; cube_indices[4] = 6; cube_indices[5] = 7; cube_indices[6] = 4; cube_indices[7] = 5; // Second strip cube_indices[8] = 2; cube_indices[9] = 6; cube_indices[10] = 0; cube_indices[11] = 4; cube_indices[12] = 1; cube_indices[13] = 5; cube_indices[14] = 3; cube_indices[15] = 7; GL.BufferData(BufferTarget.ArrayBuffer, cube_vertices, BufferUsage.StaticDraw); cube_vertices.Dispose(); GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.VertexAttribPointer(0, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(0); GL.GenBuffers(1, cube_element_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, cube_element_buffer[0]); GL.BufferData(BufferTarget.ElementArrayBuffer, cube_indices, BufferUsage.StaticDraw); cube_indices.Dispose(); skybox_rotate_loc = GL.GetUniformLocation(skybox_prog, "tc_rotate"); object_mat_mvp_loc = GL.GetUniformLocation(object_prog, "mat_mvp"); object_mat_mv_loc = GL.GetUniformLocation(object_prog, "mat_mv"); skyboxTexLocation = GL.GetUniformLocation(skybox_prog, "tex"); objectTexLocation = GL.GetUniformLocation(object_prog, "tex"); //tex = new Texture2D(); //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"media\TantolundenCube.png"); //tex.Initialize(bmp); vglImageData data = new vglImageData(); tex = vgl.vglLoadTexture(@"media\TantolundenCube.dds", 0, ref data); uint e = GL.GetError(); vgl.vglUnloadImage(ref data); vboObject.LoadFromVBM(@"media\unit_torus.vbm", 0, 1, 2); }
public void CopyTo <T>(UnmanagedArray <T> heightStickArray, int index) where T : struct { if (Heightmap is null) { throw new InvalidOperationException($"{ nameof(Heightmap) } is a null"); } if (heightStickArray is null) { throw new ArgumentNullException(nameof(heightStickArray)); } var heightStickArrayLength = heightStickArray.Length - index; if (heightStickArrayLength <= 0) { throw new IndexOutOfRangeException(nameof(index)); } var typeOfT = typeof(T); T[] heights; if (typeOfT == typeof(float)) { if (Heightmap.Floats is null) { throw new InvalidOperationException($"{ nameof(Heightmap.Floats) } is a null."); } heights = (T[])(object)Heightmap.Floats; } else if (typeOfT == typeof(short)) { if (Heightmap.Shorts is null) { throw new InvalidOperationException($"{ nameof(Heightmap.Shorts) } is a null."); } heights = (T[])(object)Heightmap.Shorts; } else if (typeOfT == typeof(byte)) { if (Heightmap.Bytes is null) { throw new InvalidOperationException($"{ nameof(Heightmap.Bytes) } is a null."); } heights = (T[])(object)Heightmap.Bytes; } else { throw new NotSupportedException($"{ typeof(UnmanagedArray<T>) } type is not supported."); } var heightsLength = heights.Length; if (heightStickArrayLength < heightsLength) { throw new ArgumentException($"{ nameof(heightStickArray) }.{ nameof(heightStickArray.Length) } is not enough to copy."); } heightStickArray.Write(heights, index * Utilities.SizeOf <T>(), 0, heightsLength); }
private void InitBuffer() { BufferName = new uint[2]; GL.GenBuffers(BufferName.Length, BufferName); int[] UniformBufferOffset = new int[1]; GL.GetInteger(GetTarget.UniformBufferOffsetAlignment, UniformBufferOffset); int mat4Size = Marshal.SizeOf(typeof(mat4)); int UniformBlockSize = Math.Max(mat4Size, UniformBufferOffset[0]); GL.BindBuffer(BufferTarget.UniformBuffer, BufferName[1]); var buffer = new UnmanagedArray<byte>(UniformBlockSize); GL.BufferData(BufferTarget.UniformBuffer, buffer, BufferUsage.DynamicDraw); GL.BindBuffer(BufferTarget.UniformBuffer, 0); transformBuffer = new uint[1]; GL.GenBuffers(transformBuffer.Length, transformBuffer); GL.BindBuffer(BufferTarget.ArrayBuffer, transformBuffer[0]); UnmanagedArray<vec4> positionData = new UnmanagedArray<vec4>(6); positionData[0] = new vec4(-1.0f, -1.0f, 0.0f, 1.0f); positionData[1] = new vec4(1.0f, -1.0f, 0.0f, 1.0f); positionData[2] = new vec4(1.0f, 1.0f, 0.0f, 1.0f); positionData[3] = new vec4(1.0f, 1.0f, 0.0f, 1.0f); positionData[4] = new vec4(-1.0f, 1.0f, 0.0f, 1.0f); positionData[5] = new vec4(-1.0f, -1.0f, 0.0f, 1.0f); GL.BufferData(BufferTarget.ArrayBuffer, positionData, BufferUsage.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); feedBackBuffer = new uint[1]; GL.GenBuffers(feedBackBuffer.Length, feedBackBuffer); GL.BindBuffer(BufferTarget.ArrayBuffer, feedBackBuffer[0]); UnmanagedArray<vec4> tmp = new UnmanagedArray<vec4>(2 * 6); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); }
} // end sub #endregion protected override void DoInitialize() { render_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.VertexShader, render_vs); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.FragmentShader, render_fs); GL.LinkProgram(render_prog); GL.UseProgram(render_prog); view_matrix_loc = GL.GetUniformLocation(render_prog, "view_matrix"); projection_matrix_loc = GL.GetUniformLocation(render_prog, "projection_matrix"); vboObject.LoadFromVBM(@"media\armadillo_low.vbm", 0, 1, 2); // Bind its vertex array object so that we can append the instanced attributes vboObject.BindVertexArray(); // Get the locations of the vertex attributes in 'prog', which is the // (linked) program object that we're going to be rendering with. Note // that this isn't really necessary because we specified locations for // all the attributes in our vertex shader. This code could be made // more concise by assuming the vertex attributes are where we asked // the compiler to put them. int position_loc = GL.GetAttribLocation(render_prog, "position"); int normal_loc = GL.GetAttribLocation(render_prog, "normal"); int color_loc = GL.GetAttribLocation(render_prog, "color"); int matrix_loc = GL.GetAttribLocation(render_prog, "model_matrix"); // Generate the colors of the objects var colors = new UnmanagedArray <vec4>(INSTANCE_COUNT); for (int n = 0; n < INSTANCE_COUNT; n++) { float a = (float)(n) / 4.0f; float b = (float)(n) / 5.0f; float c = (float)(n) / 6.0f; colors[n] = new vec4( (float)(0.5f + 0.25f * (Math.Sin(a + 1.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(b + 2.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(c + 3.0f) + 1.0f)), (float)(1.0f) ); } GL.GenBuffers(1, color_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, colors, BufferUsage.DynamicDraw); colors.Dispose(); // Now we set up the color array. We want each instance of our geometry // to assume a different color, so we'll just pack colors into a buffer // object and make an instanced vertex attribute out of it. GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.VertexAttribPointer((uint)color_loc, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray((uint)color_loc); // This is the important bit... set the divisor for the color array to // 1 to get OpenGL to give us a new value of 'color' per-instance // rather than per-vertex. GL.VertexAttribDivisor((uint)color_loc, 1); // Likewise, we can do the same with the model matrix. Note that a // matrix input to the vertex shader consumes N consecutive input // locations, where N is the number of columns in the matrix. So... // we have four vertex attributes to set up. UnmanagedArray <mat4> tmp = new UnmanagedArray <mat4>(INSTANCE_COUNT); GL.GenBuffers(1, model_matrix_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, model_matrix_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicDraw); tmp.Dispose(); // Loop over each column of the matrix... for (int i = 0; i < 4; i++) { // Set up the vertex attribute GL.VertexAttribPointer((uint)(matrix_loc + i), // Location 4, GL.GL_FLOAT, false, // vec4 Marshal.SizeOf(typeof(mat4)), // Stride new IntPtr(Marshal.SizeOf(typeof(vec4)) * i)); // Start offset // Enable it GL.EnableVertexAttribArray((uint)(matrix_loc + i)); // Make it instanced GL.VertexAttribDivisor((uint)(matrix_loc + i), 1); } // Done (unbind the object's VAO) GL.BindVertexArray(0); }
private void DoRender(object sender, PaintEventArgs e) { // Compute the MVP (Model View Projection matrix) { GL.BindBuffer(BufferTarget.UniformBuffer, BufferName[1]);//BufferName[TRANSFORM] var mvpPointer = GL.MapBufferRange(GL.GL_UNIFORM_BUFFER, 0, 64, (uint)(GL.GL_MAP_WRITE_BIT | GL.GL_MAP_INVALIDATE_BUFFER_BIT)); var tmp = new UnmanagedArray<mat4>(1); mat4 projection = this.camera.GetProjectionMat4(); mat4 view = this.camera.GetViewMat4(); //tmp[0] = projection * view; //tmp.CopyTo(Pointer); unsafe { mat4* array = (mat4*)mvpPointer.ToPointer(); array[0] = projection * view; } GL.UnmapBuffer(GL.GL_UNIFORM_BUFFER); tmp.Dispose(); } // Clear color buffer //GL.ClearBufferfv(GL_COLOR, 0, &GL.m.vec4(0.0f, 0.0f, 0.0f, 1.0f)[0]); GL.ClearBuffer(GL.GL_COLOR, 0, new float[] { 0.0f, 0.0f, 0.0f, 1.0f }); // First draw, capture the attributes // Disable rasterisation, vertices processing only! GL.Enable(GL.GL_RASTERIZER_DISCARD); transformProgram.Bind(); GL.BindVertexArray(transformArray[0]); //GL.BindBufferBase(GL.GL_UNIFORM_BUFFER, semantic.uniform.TRANSFORM0, BufferName[buffer.TRANSFORM]); GL.BindBufferBase(GL.GL_UNIFORM_BUFFER, 1, BufferName[1]); GL.BindTransformFeedback(GL.GL_TRANSFORM_FEEDBACK, feedbackObj[0]); GL.BeginTransformFeedback(GL.GL_TRIANGLES); GL.DrawArraysInstanced(GL.GL_TRIANGLES, 0, 6, 1);//VertexCount: 6 GL.EndTransformFeedback(); GL.BindTransformFeedback(GL.GL_TRANSFORM_FEEDBACK, 0); GL.Disable(GL.GL_RASTERIZER_DISCARD); // Second draw, reuse the captured attributes feedbackProgram.Bind(); GL.BindVertexArray(feedbackArray[0]); GL.DrawTransformFeedback(GL.GL_TRIANGLES, feedbackObj[0]); }
public HeightfieldColliderShape(int heightStickWidth, int heightStickLength, UnmanagedArray <float> dynamicFieldData, float heightScale, float minHeight, float maxHeight, bool flipQuadEdges) : this(heightStickWidth, heightStickLength, HeightfieldTypes.Float, dynamicFieldData, heightScale, minHeight, maxHeight, flipQuadEdges) { }
protected override void DoInitialize() { // Create a vertex array object uint[] vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create and initialize a buffer object uint[] buffers = new uint[NumVertexBuffers]; GL.GenBuffers(NumVertexBuffers, buffers); GL.BindBuffer(GL.GL_ARRAY_BUFFER, buffers[ArrayBuffer]); //GL.BufferData( GL.GL_ARRAY_BUFFER, sizeof(TeapotVertices), TeapotVertices, GL_STATIC_DRAW ); UnmanagedArray <vec3> positions = new UnmanagedArray <vec3>(TeapotExampleHelper.NumTeapotVertices); for (int i = 0; i < positions.Length; i++) { positions[i] = TeapotExampleHelper.TeapotVertices[i]; } GL.BufferData(BufferTarget.ArrayBuffer, positions, BufferUsage.StaticDraw); GL.BindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, buffers[ElementBuffer]); //GL.BufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(TeapotIndices), TeapotIndices, GL_STATIC_DRAW ); UnmanagedArray <uint> indexes = new UnmanagedArray <uint>(TeapotExampleHelper.NumTeapotPatches * 4 * 4); for (int i = 0; i < indexes.Length; i++) { indexes[i] = TeapotExampleHelper.TeapotIndices[i]; } GL.BufferData(BufferTarget.ElementArrayBuffer, indexes, BufferUsage.StaticDraw); // Load shaders and use the resulting shader program ShaderInfo[] shaders = new ShaderInfo[] { new ShaderInfo() { type = ShaderType.VertexShader, shaderSource = ManifestResourceLoader.LoadTextFile("teapot.vert"), }, new ShaderInfo() { type = ShaderType.TessellationControlShader, shaderSource = ManifestResourceLoader.LoadTextFile("teapot.cont"), }, //new ShaderInfo(){ type= ShaderType.TessellationEvaluationShader, shaderSource=ManifestResourceLoader.LoadTextFile("teapot.eval"),}, new ShaderInfo() { type = ShaderType.FragmentShader, shaderSource = ManifestResourceLoader.LoadTextFile("teapot.frag"), }, }; //uint program = LoadShaders( shaders ); shaderProgramObject = shaders.LoadShaders(); GL.UseProgram(shaderProgramObject); // set up vertex arrays int vPosition = GL.GetAttribLocation(shaderProgramObject, "vPosition"); GL.EnableVertexAttribArray((uint)vPosition); GL.VertexAttribPointer((uint)vPosition, 3, GL.GL_DOUBLE, false, 0, new IntPtr(0)); PLoc = GL.GetUniformLocation(shaderProgramObject, "P"); InnerLoc = GL.GetUniformLocation(shaderProgramObject, "Inner"); OuterLoc = GL.GetUniformLocation(shaderProgramObject, "Outer"); GL.Uniform1(InnerLoc, Inner); GL.Uniform1(OuterLoc, Outer); mat4 modelview = glm.translate(mat4.identity(), new vec3(-0.2625f, -1.575f, -1.0f)); modelview *= glm.translate(modelview, new vec3(0.0f, 0.0f, -7.5f)); GL.UniformMatrix4(GL.GetUniformLocation(shaderProgramObject, "MV"), 1, true, modelview.to_array()); GL.PatchParameter(PatchParameterName.PatchVertices, TeapotExampleHelper.NumTeapotVerticesPerPatch); }
private void InitVAO() { this.axisPrimitiveMode = DrawMode.QuadStrip; GLColor[] colors = this.ColorPalette.Colors; float[] coords = this.ColorPalette.Coords; this.numbers = new PointSpriteStringElement[coords.Length]; this.vertexCount = coords.Length * 2; this.vao = new uint[1]; float coordLength = coords[coords.Length - 1] - coords[0]; { GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // Create a vertex buffer for the vertex data. { UnmanagedArray<vec3> positionArray = new UnmanagedArray<vec3>(this.vertexCount); positionArray[0] = new vec3(-0.5f, -0.5f, 0); positionArray[1] = new vec3(-0.5f, 0.5f, 0); for (int i = 1; i < coords.Length; i++) { float x = (coords[i] - coords[0]) / coordLength - 0.5f; positionArray[i * 2 + 0] = new vec3(x, -0.5f, 0); positionArray[i * 2 + 1] = new vec3(x, 0.5f, 0); } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // Now do the same for the colour data. { var colorArray = new UnmanagedArray<vec4>(this.vertexCount); for (int i = 0; i < colors.Length; i++) { GLColor color = colors[i]; colorArray[i * 2 + 0] = new vec4(color.R, color.G, color.B, color.A); colorArray[i * 2 + 1] = new vec4(color.R, color.G, color.B, color.A); } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); } // prepare numbers { const float numberPosY = -0.6f; this.numbers[0] = new PointSpriteStringElement( this.Min.ToShortString(), new vec3(-0.5f, numberPosY, 0)); this.numbers[0].Initialize(); for (int i = 1; i < coords.Length; i++) { float x = (coords[i] - coords[0]) / coordLength - 0.5f; if (i + 1 == coords.Length) { this.numbers[i] = new PointSpriteStringElement( (this.Min + i * this.Step).ToShortString(), new vec3(x, numberPosY, 0)); } else { this.numbers[i] = new PointSpriteStringElement( this.Max.ToShortString(), new vec3(x, numberPosY, 0)); } this.numbers[i].Initialize(); } } }
public bool LoadFromVBM(string filename, int vertexIndex, int normalIndex, int texCoord0Index) { //FILE * f = NULL; FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(f); //f = fopen(filename, "rb"); //if(f == NULL) //return false; //fseek(f, 0, SEEK_END); //size_t filesize = ftell(f); //fseek(f, 0, SEEK_SET); long filesize = f.Length; //f.Seek(0, SeekOrigin.End); //f.Seek(0, SeekOrigin.Begin); byte[] data = new byte[filesize]; UnmanagedArray<byte> raw_data; f.Read(data, 0, (int)filesize); //f.Close(); f.Seek(0, SeekOrigin.Begin); //VBM_HEADER * header = (VBM_HEADER *)data; VBM_HEADER header = br.ReadStruct<VBM_HEADER>(); //raw_data = data + header.size + header->num_attribs * sizeof(VBM_ATTRIB_HEADER) + header->num_frames * sizeof(VBM_FRAME_HEADER); //{ // long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); // raw_data = new UnmanagedArray<byte>((int)(data.Length - offset)); // for (int i = 0; i < raw_data.Length; i++) // { // raw_data[i] = data[offset+i]; // } //} //VBM_ATTRIB_HEADER * attrib_header = (VBM_ATTRIB_HEADER *)(data + header.size); VBM_ATTRIB_HEADER attrib_header = br.ReadStruct<VBM_ATTRIB_HEADER>(); //VBM_FRAME_HEADER * frame_header = (VBM_FRAME_HEADER *)(data + header.size + header.num_attribs * sizeof(VBM_ATTRIB_HEADER)); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } VBM_FRAME_HEADER frame_header = br.ReadStruct<VBM_FRAME_HEADER>(); uint total_data_size = 0; //memcpy(&m_header, header, header.size < Marshal.SizeOf(typeof(VBM_HEADER)) ? header.size : Marshal.SizeOf(typeof(VBM_HEADER))); this.m_header = header; //memcpy(m_attrib, attrib_header, header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER))); { long offset = header.size;// +header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_attrib = new VBM_ATTRIB_HEADER[header.num_attribs]; for (int i = 0; i < header.num_attribs; i++) { this.m_attrib[i] = br.ReadStruct<VBM_ATTRIB_HEADER>(); } //memcpy(m_frame, frame_header, header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER))); { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER));// +header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); f.Seek(offset, SeekOrigin.Begin); } this.m_frame = new VBM_FRAME_HEADER[header.num_frames]; for (int i = 0; i < header.num_frames; i++) { this.m_frame[i] = br.ReadStruct<VBM_FRAME_HEADER>(); } GL.GenVertexArrays(1, m_vao); GL.BindVertexArray(m_vao[0]); GL.GenBuffers(1, m_attribute_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, m_attribute_buffer[0]); //uint i; for (uint i = 0; i < header.num_attribs; i++) { total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } { long offset = header.size + header.num_attribs * Marshal.SizeOf(typeof(VBM_ATTRIB_HEADER)) + header.num_frames * Marshal.SizeOf(typeof(VBM_FRAME_HEADER)); raw_data = new UnmanagedArray<byte>((int)total_data_size); for (int i = 0; i < raw_data.Length; i++) { raw_data[i] = data[offset + i]; } } //GL.BufferData(GL_ARRAY_BUFFER, total_data_size, raw_data, GL_STATIC_DRAW); GL.BufferData(BufferTarget.ArrayBuffer, raw_data, BufferUsage.StaticDraw); total_data_size = 0; for (uint i = 0; i < header.num_attribs; i++) { uint attribIndex = i; if (attribIndex == 0) attribIndex = (uint)vertexIndex; else if (attribIndex == 1) attribIndex = (uint)normalIndex; else if (attribIndex == 2) attribIndex = (uint)texCoord0Index; GL.VertexAttribPointer(attribIndex, (int)m_attrib[i].components, m_attrib[i].type, false, 0, new IntPtr(total_data_size)); GL.EnableVertexAttribArray(attribIndex); total_data_size += m_attrib[i].components * sizeof(float) * header.num_vertices; } if (header.num_indices > 0) { GL.GenBuffers(1, m_index_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, m_index_buffer[0]); uint element_size; if (header.indexype == 0x1403) { element_size = sizeof(ushort); } else { element_size = sizeof(uint); } //GL.BufferData(GL_ELEMENT_ARRAY_BUFFER, header.num_indices * element_size, raw_data + total_data_size, GL_STATIC_DRAW); UnmanagedArray<byte> tmp = new UnmanagedArray<byte>((int)(header.num_indices * element_size)); for (int t = 0; t < tmp.Length; t++) { tmp[t] = raw_data[(int)(t + total_data_size)]; } GL.BufferData(BufferTarget.ElementArrayBuffer, tmp, BufferUsage.StaticDraw); tmp.Dispose(); } GL.BindVertexArray(0); if (m_header.num_materials != 0) { m_material = new VBM_MATERIAL[m_header.num_materials]; //memcpy(m_material, raw_data + total_data_size, m_header.num_materials * sizeof(VBM_MATERIAL)); { var offset = header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material[t] = br.ReadStruct<VBM_MATERIAL>(); } total_data_size += (uint)(m_header.num_materials * Marshal.SizeOf(typeof(VBM_MATERIAL))); m_material_textures = new material_texture[m_header.num_materials]; //memset(m_material_textures, 0, m_header.num_materials * sizeof(*m_material_textures)); { var offset = 0; f.Seek(0, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_materials; t++) { m_material_textures[t] = br.ReadStruct<material_texture>(); } } if (m_header.num_chunks != 0) { m_chunks = new VBM_RENDER_CHUNK[m_header.num_chunks]; //memcpy(m_chunks, raw_data + total_data_size, m_header.num_chunks * sizeof(VBM_RENDER_CHUNK)); { var offset = m_header.size + total_data_size; f.Seek(offset, SeekOrigin.Begin); } for (int t = 0; t < m_header.num_chunks; t++) { m_chunks[t] = br.ReadStruct<VBM_RENDER_CHUNK>(); } //total_data_size += m_header.num_chunks * sizeof(VBM_RENDER_CHUNK); } raw_data.Dispose(); return true; }
public static void TypicalScene() { const int count = 1000000; long startTick = 0; long interval, interval2; // 测试float类型 { var floatArray = new UnmanagedArray <float>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { floatArray[i] = i; } for (int i = 0; i < count; i++) { var item = floatArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; float *header = (float *)floatArray.FirstElement(); float *last = (float *)floatArray.LastElement(); float *tailAddress = (float *)floatArray.TailAddress(); int value = 0; for (float *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (float *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试decimal类型 { var decimalArray = new UnmanagedArray <decimal>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { decimalArray[i] = i; } for (int i = 0; i < count; i++) { var item = decimalArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; decimal *header = (decimal *)decimalArray.FirstElement(); decimal *last = (decimal *)decimalArray.LastElement(); decimal *tailAddress = (decimal *)decimalArray.TailAddress(); int value = 0; for (decimal *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (decimal *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试int类型 { var intArray = new UnmanagedArray <int>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { intArray[i] = i; } for (int i = 0; i < count; i++) { var item = intArray[i]; if (item != i) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; int *header = (int *)intArray.FirstElement(); int *last = (int *)intArray.LastElement(); int *tailAddress = (int *)intArray.TailAddress(); int value = 0; for (int *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = value++; } int i = 0; for (int *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != i) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试bool类型 { var boolArray = new UnmanagedArray <bool>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { boolArray[i] = i % 2 == 0; } for (int i = 0; i < count; i++) { var item = boolArray[i]; if (item != (i % 2 == 0)) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; bool *header = (bool *)boolArray.FirstElement(); bool *last = (bool *)boolArray.LastElement(); bool *tailAddress = (bool *)boolArray.TailAddress(); int value = 0; for (bool *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = (value % 2 == 0); value++; } int i = 0; for (bool *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; if (item != (i % 2 == 0)) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试vec3类型 { var vec3Array = new UnmanagedArray <vec3>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { vec3Array[i] = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); } for (int i = 0; i < count; i++) { var item = vec3Array[i]; var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); if (item.x != old.x || item.y != old.y || item.z != old.z) { throw new Exception(); } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; vec3 *header = (vec3 *)vec3Array.FirstElement(); vec3 *last = (vec3 *)vec3Array.LastElement(); vec3 *tailAddress = (vec3 *)vec3Array.TailAddress(); int i = 0; for (vec3 *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); i++; } i = 0; for (vec3 *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; var old = new vec3(i * 3 + 0, i * 3 + 1, i * 3 + 2); if (item.x != old.x || item.y != old.y || item.z != old.z) { throw new Exception(); } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 测试mat4类型 { var vec3Array = new UnmanagedArray <mat4>(count); startTick = DateTime.Now.Ticks; for (int i = 0; i < count; i++) { vec3Array[i] = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); } for (int i = 0; i < count; i++) { var item = vec3Array[i]; var old = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { if (item[col][row] != old[col][row]) { throw new Exception(); } } } } interval = DateTime.Now.Ticks - startTick; unsafe { startTick = DateTime.Now.Ticks; mat4 *header = (mat4 *)vec3Array.FirstElement(); mat4 *last = (mat4 *)vec3Array.LastElement(); mat4 *tailAddress = (mat4 *)vec3Array.TailAddress(); int i = 0; for (mat4 *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++) { *ptr = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); i++; } i = 0; for (mat4 *ptr = header; ptr <= last /*or: ptr < tailAddress*/; ptr++, i++) { var item = *ptr; var old = new mat4(new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3), new vec4(i, i + 1, i + 2, i + 3)); for (int col = 0; col < 4; col++) { for (int row = 0; row < 4; row++) { if (item[col][row] != old[col][row]) { throw new Exception(); } } } } interval2 = DateTime.Now.Ticks - startTick; } Console.WriteLine("Ticks: safe: {0} vs unsafe: {1}", interval, interval2); } // 立即释放所有非托管数组占用的内存,任何之前创建的UnmanagedBase数组都不再可用了。 UnmanagedArray <int> .FreeAll(); }
protected override void DoInitialize() { skybox_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(skybox_prog, ShaderType.VertexShader, skybox_shader_vs); ShaderHelper.vglAttachShaderSource(skybox_prog, ShaderType.FragmentShader, skybox_shader_fs); GL.LinkProgram(skybox_prog); object_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(object_prog, ShaderType.VertexShader, object_shader_vs); ShaderHelper.vglAttachShaderSource(object_prog, ShaderType.FragmentShader, object_shader_fs); GL.LinkProgram(object_prog); GL.GenBuffers(1, cube_vbo); GL.BindBuffer(BufferTarget.ArrayBuffer, cube_vbo[0]); var cube_vertices = new UnmanagedArray<vec3>(8); cube_vertices[0] = new vec3(-1.0f, -1.0f, -1.0f); cube_vertices[1] = new vec3(-1.0f, -1.0f, 1.0f); cube_vertices[2] = new vec3(-1.0f, 1.0f, -1.0f); cube_vertices[3] = new vec3(-1.0f, 1.0f, 1.0f); cube_vertices[4] = new vec3(1.0f, -1.0f, -1.0f); cube_vertices[5] = new vec3(1.0f, -1.0f, 1.0f); cube_vertices[6] = new vec3(1.0f, 1.0f, -1.0f); cube_vertices[7] = new vec3(1.0f, 1.0f, 1.0f); var cube_indices = new UnmanagedArray<ushort>(16); // First strip cube_indices[0] = 0; cube_indices[1] = 1; cube_indices[2] = 2; cube_indices[3] = 3; cube_indices[4] = 6; cube_indices[5] = 7; cube_indices[6] = 4; cube_indices[7] = 5; // Second strip cube_indices[8] = 2; cube_indices[9] = 6; cube_indices[10] = 0; cube_indices[11] = 4; cube_indices[12] = 1; cube_indices[13] = 5; cube_indices[14] = 3; cube_indices[15] = 7; GL.BufferData(BufferTarget.ArrayBuffer, cube_vertices, BufferUsage.StaticDraw); cube_vertices.Dispose(); GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.VertexAttribPointer(0, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(0); GL.GenBuffers(1, cube_element_buffer); GL.BindBuffer(BufferTarget.ElementArrayBuffer, cube_element_buffer[0]); GL.BufferData(BufferTarget.ElementArrayBuffer, cube_indices, BufferUsage.StaticDraw); cube_indices.Dispose(); skybox_rotate_loc = GL.GetUniformLocation(skybox_prog, "tc_rotate"); object_mat_mvp_loc = GL.GetUniformLocation(object_prog, "mat_mvp"); object_mat_mv_loc = GL.GetUniformLocation(object_prog, "mat_mv"); skyboxTexLocation = GL.GetUniformLocation(skybox_prog, "tex"); objectTexLocation = GL.GetUniformLocation(object_prog, "tex"); //tex = new Texture2D(); //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"media\TantolundenCube.png"); //tex.Initialize(bmp); vglImageData data = new vglImageData(); tex = vgl.vglLoadTexture(@"media\TantolundenCube.dds", 0, ref data); uint e = GL.GetError(); vgl.vglUnloadImage(ref data); vboObject.LoadFromVBM(@"media\unit_torus.vbm", 0, 1, 2); }
private void scientificVisual3DControl_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 'r') { // 随机显示某些hexahedron foreach (var item in this.scientificVisual3DControl.ModelContainer.Children) { { HexahedronGridderElement element = item as HexahedronGridderElement; if (element != null) { YieldingGeometryModel.Builder.HexahedronGridderElementHelper.RandomVisibility(element, this.scientificVisual3DControl.OpenGL, 0.2); } } { PointSpriteGridderElement element = item as PointSpriteGridderElement; if (element != null) { YieldingGeometryModel.Builder.PointSpriteGridderElementHelper.RandomVisibility(element, this.scientificVisual3DControl.OpenGL, 0.2); } } } this.scientificVisual3DControl.Invalidate(); } if (e.KeyChar == 'c') { OpenGL gl = this.scientificVisual3DControl.OpenGL; List <HexahedronGridderElement> elements = this.scientificVisual3DControl.ModelContainer.Traverse <HexahedronGridderElement>().ToList <HexahedronGridderElement>(); if (elements.Count > 0) { HexahedronGridderElement gridder = elements[0]; HexahedronGridderSource source = gridder.Source; UnmanagedArray <float> visibles = HexahedronGridderHelper.GridVisibleFromActive(source); //随机生成不完整网格的属性。 int propCount = source.DimenSize / 2; if (propCount <= 0) { return; } int minValue = 5000; int maxValue = 10000; int[] gridIndexes; float[] gridValues; HexahedronGridderHelper.RandomValue(propCount, minValue, maxValue, out gridIndexes, out gridValues); float step = (maxValue - minValue) / 10.0f; this.scientificVisual3DControl.SetColorIndicator(minValue, maxValue, step); ColorF[] colors = new ColorF[propCount]; for (int i = 0; i < colors.Length; i++) { colors[i] = (ColorF)this.scientificVisual3DControl.MapToColor(gridValues[i]); } UnmanagedArray <ColorF> colorArray = HexahedronGridderHelper.FromColors(source, gridIndexes, colors, visibles); gridder.UpdateColorBuffer(gl, colorArray, visibles); colorArray.Dispose(); visibles.Dispose(); this.scientificVisual3DControl.Invalidate(); } } }
public static void CtorUnmanagedReadOnlySpanNUIntTest() { using var array = new UnmanagedArray <int>(3); array[0] = 1; array[1] = 2; array[2] = 3; using (var valueList = new UnmanagedValueList <int>(array.AsSpan())) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)3) .And.Count.EqualTo((nuint)3) ); } using (var valueList = new UnmanagedValueList <int>(array.AsSpan(), 2)) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)3) .And.Count.EqualTo((nuint)3) ); } Assert.That(() => new UnmanagedValueList <int>(array.AsSpan(), 3), Throws.InstanceOf <ArgumentOutOfRangeException>() .And.Property("ActualValue").EqualTo((nuint)3) .And.Property("ParamName").EqualTo("alignment") ); using (var valueList = new UnmanagedValueList <int>(UnmanagedArray <int> .Empty.AsSpan())) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)0) .And.Count.EqualTo((nuint)0) ); } using (var valueList = new UnmanagedValueList <int>(UnmanagedArray <int> .Empty.AsSpan(), 2)) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)0) .And.Count.EqualTo((nuint)0) ); } Assert.That(() => new UnmanagedValueList <int>(UnmanagedArray <int> .Empty.AsSpan(), 3), Throws.InstanceOf <ArgumentOutOfRangeException>() .And.Property("ActualValue").EqualTo((nuint)3) .And.Property("ParamName").EqualTo("alignment") ); using (var valueList = new UnmanagedValueList <int>(new UnmanagedArray <int>().AsSpan())) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)0) .And.Count.EqualTo((nuint)0) ); } using (var valueList = new UnmanagedValueList <int>(new UnmanagedArray <int>().AsSpan(), 2)) { Assert.That(() => valueList, Has.Property("Capacity").EqualTo((nuint)0) .And.Count.EqualTo((nuint)0) ); } Assert.That(() => new UnmanagedValueList <int>(new UnmanagedArray <int>().AsSpan(), 3), Throws.InstanceOf <ArgumentOutOfRangeException>() .And.Property("ActualValue").EqualTo((nuint)3) .And.Property("ParamName").EqualTo("alignment") ); }
private void InitVAO() { int size = this.size; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // prepare positions { var positionArray = new UnmanagedArray<vec3>(size * size * size * 14); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { positionArray[index++] = unitCubePos[cubeIndex] + new vec3((i - size / 2) * unitSpace, (j - size / 2) * unitSpace, (k - size / 2) * unitSpace); } } } } uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // prepare colors { var colorArray = new UnmanagedArray<vec3>(size * size * size * 14); Random random = new Random(); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { //vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); colorArray[index++] = color; } } } } uint in_ColorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); // prepare firsts and counts { // todo: rename 'size' this.firsts = new int[size * size * size]; for (int i = 0; i < this.firsts.Length; i++) { this.firsts[i] = i * 14; } this.counts = new int[size * size * size]; for (int i = 0; i < this.counts.Length; i++) { this.counts[i] = 14; } } }
public DebugView(UnmanagedArray <T> array) { _array = array; }
private void InitVAO() { int size = this.size; this.vao = new uint[1]; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // prepare positions { var positionArray = new UnmanagedArray <vec3>(size * size * size * 8); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 8; cubeIndex++) { positionArray[index++] = unitCubePos[cubeIndex] + new vec3((i - size / 2) * unitSpace, (j - size / 2) * unitSpace, (k - size / 2) * unitSpace); } } } } uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // prepare colors { var colorArray = new UnmanagedArray <vec3>(size * size * size * 8); Random random = new Random(); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { //vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); for (int cubeIndex = 0; cubeIndex < 8; cubeIndex++) { vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); colorArray[index++] = color; } } } } uint in_ColorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // prepare index { var indexArray = new UnmanagedArray <uint>(size * size * size * (14 + 1)); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { long posIndex = unitCubeIndex[cubeIndex] + (i * size * size + j * size + k) * 8; indexArray[index++] = (uint)posIndex; } indexArray[index++] = uint.MaxValue; } } } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ElementArrayBuffer, indexArray, BufferUsage.StaticDraw); indexArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
private void InitVAO(string value) { if (value == null) { value = string.Empty; } this.mode = DrawMode.Quads; this.vertexCount = 4 * value.Length; // Create a vertex buffer for the vertex data. UnmanagedArray<vec3> in_Position = new UnmanagedArray<vec3>(this.vertexCount); UnmanagedArray<vec2> in_TexCoord = new UnmanagedArray<vec2>(this.vertexCount); Bitmap bigBitmap = this.ttfTexture.BigBitmap; // step 1: set width for each glyph vec3[] tmpPositions = new vec3[this.vertexCount]; float totalLength = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; CharacterInfo cInfo; if (this.ttfTexture.CharInfoDict.TryGetValue(c, out cInfo)) { float glyphWidth = (float)cInfo.width / (float)this.ttfTexture.FontHeight; if (i == 0) { tmpPositions[i * 4 + 0] = new vec3(0, 0, 0); tmpPositions[i * 4 + 1] = new vec3(glyphWidth, 0, 0); tmpPositions[i * 4 + 2] = new vec3(glyphWidth, 1, 0); tmpPositions[i * 4 + 3] = new vec3(0, 1, 0); } else { tmpPositions[i * 4 + 0] = tmpPositions[i * 4 + 0 - 4 + 1]; tmpPositions[i * 4 + 1] = tmpPositions[i * 4 + 0] + new vec3(glyphWidth, 0, 0); tmpPositions[i * 4 + 3] = tmpPositions[i * 4 + 3 - 4 - 1]; tmpPositions[i * 4 + 2] = tmpPositions[i * 4 + 3] + new vec3(glyphWidth, 0, 0); } totalLength += glyphWidth; } //else //{ throw new Exception(string.Format("Not support for display the char [{0}]", c)); } } for (int i = 0; i < value.Length; i++) { char c = value[i]; CharacterInfo cInfo; float x1 = 0; float x2 = 1; float y1 = 0; float y2 = 1; if (this.ttfTexture.CharInfoDict.TryGetValue(c, out cInfo)) { x1 = (float)cInfo.xoffset / (float)bigBitmap.Width; x2 = (float)(cInfo.xoffset + cInfo.width) / (float)bigBitmap.Width; y1 = (float)cInfo.yoffset / (float)bigBitmap.Height; y2 = (float)(cInfo.yoffset + this.ttfTexture.FontHeight) / (float)bigBitmap.Height; } //else //{ throw new Exception(string.Format("Not support for display the char [{0}]", c)); } in_Position[i * 4 + 0] = tmpPositions[i * 4 + 0] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 1] = tmpPositions[i * 4 + 1] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 2] = tmpPositions[i * 4 + 2] - new vec3(totalLength / 2, 0, 0); in_Position[i * 4 + 3] = tmpPositions[i * 4 + 3] - new vec3(totalLength / 2, 0, 0); //in_TexCoord[i * 4 + 0] = new vec2(x1, y1); //in_TexCoord[i * 4 + 1] = new vec2(x2, y1); //in_TexCoord[i * 4 + 2] = new vec2(x2, y2); //in_TexCoord[i * 4 + 3] = new vec2(x1, y2); in_TexCoord[i * 4 + 0] = new vec2(x1, y2); in_TexCoord[i * 4 + 1] = new vec2(x2, y2); in_TexCoord[i * 4 + 2] = new vec2(x2, y1); in_TexCoord[i * 4 + 3] = new vec2(x1, y1); } if (vao[0] != 0) { GL.DeleteBuffers(1, vao); } if (vbo[0] != 0) { GL.DeleteBuffers(vbo.Length, vbo); } GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.GenBuffers(2, vbo); uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[0]); GL.BufferData(BufferTarget.ArrayBuffer, in_Position, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); uint in_TexCoordLocation = shaderProgram.GetAttributeLocation(strin_TexCoord); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo[1]); GL.BufferData(BufferTarget.ArrayBuffer, in_TexCoord, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_TexCoordLocation, 2, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_TexCoordLocation); GL.BindVertexArray(0); in_Position.Dispose(); in_TexCoord.Dispose(); }
protected void InitializeVAO() { this.axisPrimitiveMode = DrawMode.QuadStrip;// PrimitiveModes.QuadStrip; this.axisVertexCount = faceCount * 2; this.vao = new uint[4]; GL.GenVertexArrays(4, vao); vec3[] colors = new vec3[] { new vec3(1, 0, 0), new vec3(0, 1, 0), new vec3(0, 0, 1) }; // 计算三个坐标轴 for (int axisIndex = 0; axisIndex < 3; axisIndex++) { GL.BindVertexArray(vao[axisIndex]); // Create a vertex buffer for the vertex data. using (var positionArray = new UnmanagedArray <vec3>(faceCount * 2)) { for (int i = 0; i < faceCount * 2; i++) { int face = i / 2; float[] components = new float[] { i % 2 == 1 ? 0 : this.axisLength, (float)(this.radius * Math.Cos(face * (Math.PI * 2) / faceCount)), (float)(this.radius * Math.Sin(face * (Math.PI * 2) / faceCount)) }; positionArray[i] = new vec3( components[(0 + axisIndex) % 3], components[(2 + axisIndex) % 3], components[(4 + axisIndex) % 3]); } uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); } // Now do the same for the colour data. using (var colorArray = new UnmanagedArray <vec3>(faceCount * 2)) { for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = colors[axisIndex]; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); } using (var cylinderIndex = new UnmanagedArray <uint>(faceCount * 2 + 2)) { for (int i = 0; i < cylinderIndex.Length - 2; i++) { cylinderIndex[i] = (uint)i; } cylinderIndex[cylinderIndex.Length - 2] = 0; cylinderIndex[cylinderIndex.Length - 1] = 1; uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ElementArrayBuffer, cylinderIndex, BufferUsage.StaticDraw); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); } // 计算XZ平面 { this.planPrimitveMode = DrawMode.LineLoop; this.planVertexCount = 4; GL.BindVertexArray(vao[3]); // Create a vertex buffer for the vertex data. using (var plan = new UnmanagedArray <vec3>(4)) { float length = this.axisLength; plan[0] = new vec3(-length, 0, -length); plan[1] = new vec3(-length, 0, length); plan[2] = new vec3(length, 0, length); plan[3] = new vec3(length, 0, -length); uint positionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, plan, BufferUsage.StaticDraw); GL.VertexAttribPointer(positionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(positionLocation); } // Now do the same for the colour data. using (var colorArray = new UnmanagedArray <vec3>(4)) { for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = this.planColor; } uint colorLocation = shaderProgram.GetAttributeLocation(strin_Color); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(colorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(colorLocation); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); } }
internal Enumerator(UnmanagedArray <T> array) { _array = array; _index = nuint.MaxValue; }
private void InitVAO() { int size = this.size; GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); // prepare positions { var positionArray = new UnmanagedArray<vec3>(size * size * size * 8); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 8; cubeIndex++) { positionArray[index++] = unitCubePos[cubeIndex] + new vec3((i - size / 2) * unitSpace, (j - size / 2) * unitSpace, (k - size / 2) * unitSpace); } } } } uint in_PositionLocation = shaderProgram.GetAttributeLocation(strin_Position); uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ArrayBuffer, positionArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_PositionLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_PositionLocation); positionArray.Dispose(); } // prepare colors { var colorArray = new UnmanagedArray<vec3>(size * size * size * 8); Random random = new Random(); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { //vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); for (int cubeIndex = 0; cubeIndex < 8; cubeIndex++) { vec3 color = new vec3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); colorArray[index++] = color; } } } } uint in_ColorLocation = shaderProgram.GetAttributeLocation(strin_Color); GL.GenBuffers(1, this.colorBuffer); GL.BindBuffer(BufferTarget.ArrayBuffer, this.colorBuffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, colorArray, BufferUsage.StaticDraw); GL.VertexAttribPointer(in_ColorLocation, 3, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray(in_ColorLocation); colorArray.Dispose(); } // prepare index { var indexArray = new UnmanagedArray<uint>(size * size * size * (14 + 1)); int index = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { for (int cubeIndex = 0; cubeIndex < 14; cubeIndex++) { long posIndex = unitCubeIndex[cubeIndex] + (i * size * size + j * size + k) * 8; indexArray[index++] = (uint)posIndex; } indexArray[index++] = uint.MaxValue; } } } uint[] ids = new uint[1]; GL.GenBuffers(1, ids); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ids[0]); GL.BufferData(BufferTarget.ElementArrayBuffer, indexArray, BufferUsage.StaticDraw); indexArray.Dispose(); } // Unbind the vertex array, we've finished specifying data for it. GL.BindVertexArray(0); }
// Call this only after the open gl is initialized. public bool ReadFile(string lpDataFile_i, int nWidth_i, int nHeight_i, int nSlices_i) { FileStream file = new FileStream(lpDataFile_i, FileMode.Open, FileAccess.Read); // File has only image data. The dimension of the data should be known. m_uImageCount = nSlices_i; m_uImageWidth = nWidth_i; m_uImageHeight = nHeight_i; // Holds the luminance buffer //byte[] chBuffer = new byte[m_uImageWidth * m_uImageHeight * m_uImageCount]; //UnmanagedArray<byte> chBuffer = new UnmanagedArray<byte>(m_uImageWidth * m_uImageHeight * m_uImageCount); byte[] chBuffer = new byte[m_uImageWidth * m_uImageHeight * m_uImageCount]; // Holds the RGBA buffer UnmanagedArray <byte> pRGBABuffer = new UnmanagedArray <byte>(m_uImageWidth * m_uImageHeight * m_uImageCount * 4); file.Read(chBuffer, 0, chBuffer.Length); // Convert the data to RGBA data. // Here we are simply putting the same value to R, G, B and A channels. // Usually for raw data, the alpha value will be constructed by a threshold value given by the user unsafe { byte *rgbBuffer = (byte *)pRGBABuffer.FirstElement(); for (int nIndx = 0; nIndx < m_uImageWidth * m_uImageHeight * m_uImageCount; ++nIndx) { byte value = chBuffer[nIndx]; //if (value < 20) //{ value = 0; } rgbBuffer[nIndx * 4] = value; rgbBuffer[nIndx * 4 + 1] = value; rgbBuffer[nIndx * 4 + 2] = value; rgbBuffer[nIndx * 4 + 3] = value; } } // If this function is getting called again for another data file. // Deleting and creating texture is not a good idea, // we can use the glTexSubImage3D for better performance for such scenario. // I am not using that now :-) if (0 != m_nTexId[0]) { GL.DeleteTextures(1, m_nTexId); } GL.GenTextures(1, m_nTexId); GL.BindTexture(GL.GL_TEXTURE_3D, m_nTexId[0]); GL.TexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, (int)GL.GL_REPLACE); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, (int)GL.GL_CLAMP_TO_BORDER); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, (int)GL.GL_CLAMP_TO_BORDER); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_R, (int)GL.GL_CLAMP_TO_BORDER); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR); GL.TexParameteri(GL.GL_TEXTURE_3D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR); //uint target, int level, int internalformat, int width, int height, int depth, int border, uint format, uint type, IntPtr pixels) GL.TexImage3D(GL.GL_TEXTURE_3D, 0, (int)GL.GL_RGBA, m_uImageWidth, m_uImageHeight, m_uImageCount, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pRGBABuffer.Header); GL.BindTexture(GL.GL_TEXTURE_3D, 0); return(true); }
public static void vglLoadDDS(string filename, ref vglImageData image) { System.IO.FileStream f = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(f); //DDS_FILE_HEADER file_header = { 0, }; DDS_FILE_HEADER file_header = new DDS_FILE_HEADER(); //fread(&file_header, sizeof(file_header.magic) + sizeof(file_header.std_header), 1, f); file_header = br.ReadStruct<DDS_FILE_HEADER>(); file_header.dxt10_header.format = 0; file_header.dxt10_header.array_size = 0; f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header); if (file_header.magic != DDSSignal.DDS_MAGIC) { goto done_close_file; } if (file_header.std_header.ddspf.dwFourCC == DDSSignal.DDS_FOURCC_DX10) { //fread(&file_header.dxt10_header, sizeof(file_header.dxt10_header), 1, f); f.Position = Marshal.SizeOf(file_header.magic) + Marshal.SizeOf(file_header.std_header); file_header.dxt10_header = br.ReadStruct<DDS_HEADER_DXT10>(); } if (!vgl_DDSHeaderToImageDataHeader(ref file_header, ref image)) goto done_close_file; image.target = vgl_GetTargetFromDDSHeader(ref file_header); if (image.target == GL.GL_NONE) goto done_close_file; //int current_pos = ftell(f); long current_pos = f.Position; long file_size = f.Length; image.totalDataSize = (int)(file_size - current_pos); var data = new UnmanagedArray<byte>(image.totalDataSize); if (image.mip == null) { image.mip = new vglImageMipData[vermilion.MAX_TEXTURE_MIPS]; } image.mip[0].data = data.Header; //image.mip[0].data = new byte[image.totalDataSize]; //fread(image.mip[0].data, file_size - current_pos, 1, f); for (int i = 0; i < image.totalDataSize; i++) { data[i] = br.ReadByte(); } int level; IntPtr ptr = image.mip[0].data; uint width = file_header.std_header.width; uint height = file_header.std_header.height; uint depth = file_header.std_header.depth; image.sliceStride = 0; if (image.mipLevels == 0) { image.mipLevels = 1; } for (level = 0; level < image.mipLevels; ++level) { image.mip[level].data = ptr; image.mip[level].width = (int)width; image.mip[level].height = (int)height; image.mip[level].depth = (int)depth; image.mip[level].mipStride = (int)(vgl_GetDDSStride(ref file_header, (int)width) * height); image.sliceStride += image.mip[level].mipStride; ptr += image.mip[level].mipStride; width >>= 1; height >>= 1; depth >>= 1; } done_close_file: f.Close(); }
public static void CopyToUnmanagedSpanTest() { var array = new UnmanagedArray <int>(3); array[0] = 1; array[1] = 2; array[2] = 3; using (var valueList = new UnmanagedValueList <int>(array, takeOwnership: true)) { using (var destination = new UnmanagedArray <int>(3)) { valueList.CopyTo(destination); Assert.That(() => destination[0], Is.EqualTo(1) ); Assert.That(() => destination[1], Is.EqualTo(2) ); Assert.That(() => destination[2], Is.EqualTo(3) ); } using (var destination = new UnmanagedArray <int>(6)) { valueList.CopyTo(destination); Assert.That(() => destination[0], Is.EqualTo(1) ); Assert.That(() => destination[1], Is.EqualTo(2) ); Assert.That(() => destination[2], Is.EqualTo(3) ); Assert.That(() => destination[3], Is.EqualTo(0) ); Assert.That(() => destination[4], Is.EqualTo(0) ); Assert.That(() => destination[5], Is.EqualTo(0) ); } Assert.That(() => valueList.CopyTo(UnmanagedArray <int> .Empty), Throws.InstanceOf <ArgumentOutOfRangeException>() .And.Property("ActualValue").EqualTo((nuint)3) .And.Property("ParamName").EqualTo("Count") ); } using (var valueList = new UnmanagedValueList <int>()) { Assert.That(() => valueList.CopyTo(UnmanagedArray <int> .Empty), Throws.Nothing ); } }