private void VertexArrayBufferValues(VertexArrayObject vertexArray, string attributeSemantic, ArrayBufferObjectBase arrayBuffer, uint arraySectionIndex) { VertexArrayObject.VertexArray vertexArrayBuffer = vertexArray.GetVertexArray(attributeSemantic); Assert.IsFalse(arrayBuffer.IsDisposed); Assert.IsNotNull(vertexArrayBuffer); Assert.AreSame(arrayBuffer, vertexArrayBuffer.ArrayBuffer); Assert.AreEqual(arraySectionIndex, vertexArrayBuffer.ArraySectionIndex); }
private void UpdateVertexArrayObject() { if (vertexArrayObject) { vertexArrayObject.DisposeAndKeepBuffers(); } vertexArrayObject = null; if (!mesh || !material) { return; } vertexArrayObject = new VertexArrayObject(mesh.vertexArrayObject); vertexArrayObject.ApplyWithShader(material.shader); }
public void SetArraySectionByBlock() { ArrayBufferObjectBase arrayBuffer1 = null, arrayBuffer2 = null, arrayBuffer3 = null; try { arrayBuffer1 = new ArrayBufferObject(VertexBaseType.Float, 3, BufferObjectHint.StaticCpuDraw); arrayBuffer1.Create(16); arrayBuffer2 = new ArrayBufferObjectInterleaved(typeof(ComplexVertexElement), BufferObjectHint.StaticCpuDraw); arrayBuffer2.Create(16); arrayBuffer3 = new ArrayBufferObjectPacked(typeof(ComplexVertexElement), BufferObjectHint.StaticCpuDraw); arrayBuffer3.Create(16); using (VertexArrayObject vertexArray = new VertexArrayObject()) { // Set array buffers to different attributes Assert.DoesNotThrow(delegate () { vertexArray.SetArray(arrayBuffer1, 0, "attribute1", null); }); VertexArrayBufferValues(vertexArray, "attribute1", null, arrayBuffer1, 0); Assert.DoesNotThrow(delegate () { vertexArray.SetArray(arrayBuffer2, 0, "attribute2", null); }); VertexArrayBufferValues(vertexArray, "attribute2", null, arrayBuffer2, 0); Assert.DoesNotThrow(delegate () { vertexArray.SetArray(arrayBuffer2, 1, "attribute3", null); }); VertexArrayBufferValues(vertexArray, "attribute3", null, arrayBuffer2, 1); Assert.DoesNotThrow(delegate () { vertexArray.SetArray(arrayBuffer3, 2, "attribute4", null); }); VertexArrayBufferValues(vertexArray, "attribute4", null, arrayBuffer3, 2); } Assert.IsTrue(arrayBuffer1.IsDisposed); Assert.IsTrue(arrayBuffer2.IsDisposed); Assert.IsTrue(arrayBuffer3.IsDisposed); } finally { if (arrayBuffer1 != null && !arrayBuffer1.IsDisposed) arrayBuffer1.Dispose(); if (arrayBuffer2 != null && !arrayBuffer2.IsDisposed) arrayBuffer2.Dispose(); if (arrayBuffer3 != null && !arrayBuffer3.IsDisposed) arrayBuffer3.Dispose(); } }
/// <summary>Renders a static frustrum based background</summary> /// <param name="data">The background to render</param> /// <param name="alpha">The alpha level</param> /// <param name="scale">The scale</param> private void RenderStaticBackgroundRetained(StaticBackground data, float alpha, float scale) { if (data.Texture != null && renderer.currentHost.LoadTexture(data.Texture, OpenGlTextureWrapMode.RepeatClamp)) { renderer.LastBoundTexture = data.Texture.OpenGlTextures[(int)OpenGlTextureWrapMode.RepeatClamp]; GL.Enable(EnableCap.Texture2D); if (alpha == 1.0f) { GL.Disable(EnableCap.Blend); } else { GL.Enable(EnableCap.Blend); } if (data.VAO == null) { data.CreateVAO(renderer.DefaultShader.VertexLayout, renderer); } renderer.DefaultShader.Activate(); renderer.ResetShader(renderer.DefaultShader); // matrix renderer.DefaultShader.SetCurrentProjectionMatrix(renderer.CurrentProjectionMatrix); renderer.DefaultShader.SetCurrentModelViewMatrix(Matrix4D.Scale(scale) * renderer.CurrentViewMatrix); // fog if (renderer.OptionFog) { renderer.DefaultShader.SetIsFog(true); renderer.DefaultShader.SetFog(renderer.Fog); } // texture renderer.DefaultShader.SetIsTexture(true); GL.BindTexture(TextureTarget.Texture2D, data.Texture.OpenGlTextures[(int)OpenGlTextureWrapMode.RepeatClamp].Name); renderer.LastBoundTexture = null; // alpha test renderer.SetAlphaFunc(AlphaFunction.Greater, 0.0f); // blend mode renderer.DefaultShader.SetOpacity(alpha); // render polygon VertexArrayObject VAO = (VertexArrayObject)data.VAO; VAO.Bind(); renderer.lastVAO = VAO.handle; for (int i = 0; i + 9 < 32 * 10; i += 10) { VAO.Draw(PrimitiveType.Quads, i, 4); VAO.Draw(PrimitiveType.Triangles, i + 4, 3); VAO.Draw(PrimitiveType.Triangles, i + 7, 3); } renderer.DefaultShader.Deactivate(); GL.Disable(EnableCap.Texture2D); renderer.RestoreBlendFunc(); } }
public void TestLineShaderRender() { using (ShaderProgram shaderProgram = ShadersLibrary.Instance.CreateProgram("OpenGL.Line")) { Assert.DoesNotThrow(delegate() { shaderProgram.Create(_Context); }); using (VertexArrayObject vao = new VertexArrayObject()) { List <Vertex2f> vertices = new List <Vertex2f>(); for (float y = 0.375f; y < _Framebuffer.Height; y += 2.0f) { vertices.Add(new Vertex2f(0.0f, y)); vertices.Add(new Vertex2f(_Framebuffer.Width, y)); } // Setup ABO (Position) ArrayBufferObject abo = new ArrayBufferObject(VertexBaseType.Float, 2, BufferObjectHint.StaticCpuDraw); abo.Create(vertices.ToArray()); // Setup VAO vao.SetArray(abo, VertexArraySemantic.Position); vao.SetElementArray(PrimitiveType.Lines); vao.Create(_Context); // Draw test Image feedbackImageFixed = null, feedbackImageShader = null; try { Gl.Viewport(0, 0, (int)_Framebuffer.Width, (int)_Framebuffer.Height); #region Fixed pipeline _Framebuffer.SetClearColor(new ColorRGBAF(0.0f, 0.0f, 0.0f)); _Framebuffer.Clear(_Context); Gl.MatrixMode(MatrixMode.Projection); Gl.LoadMatrix(new OrthoProjectionMatrix(0.0f, _Framebuffer.Width, 0.0f, _Framebuffer.Height).ToArray()); Gl.MatrixMode(MatrixMode.Modelview); Gl.LoadIdentity(); Gl.Color3(1.0f, 1.0f, 1.0f); Gl.LineWidth(1.0f); vao.Draw(_Context); feedbackImageFixed = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8); ImageCodec.Instance.Save( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LineProgram.Fixed.png"), feedbackImageFixed, ImageFormat.Png, null ); #endregion #region Shader pipeline _Framebuffer.SetClearColor(new ColorRGBAF(0.0f, 0.0f, 0.0f)); _Framebuffer.Clear(_Context); _Context.Bind(shaderProgram); shaderProgram.SetUniform(_Context, "hal_ModelViewProjection", RenderProjectionMatrix); shaderProgram.SetUniform(_Context, "hal_UniformColor", new ColorRGBA(1.0f, 1.0f, 1.0f)); shaderProgram.SetUniform(_Context, "hal_LineWidth", 1.0f); shaderProgram.SetUniform(_Context, "hal_ViewportSize", new Vertex2f(_Framebuffer.Width, _Framebuffer.Height)); vao.Draw(_Context, shaderProgram); feedbackImageShader = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8); ImageCodec.Instance.Save( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LineProgram.Shader.png"), feedbackImageShader, ImageFormat.Png, null ); #endregion // Compare results } finally { if (feedbackImageFixed != null) { feedbackImageFixed.Dispose(); } if (feedbackImageShader != null) { feedbackImageShader.Dispose(); } } } //// Get rendering feedback //using (Image feedbackImage = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8)) { // // Drawn only even lines // for (uint y = 0; y < _Framebuffer.Height; y++) { // for (uint x = 0; x < _Framebuffer.Width; x++) { // ColorGRAY8 fragment = (ColorGRAY8)feedbackImage[x, y]; // Assert.AreEqual((y % 2) == 0 ? 255 : 0, fragment.Level, String.Format("Color mismatch at {0}x{1}", x, y)); // } // } //} } }
void initScene() { heolBones[5] = 10f; pawnBones [2] = 0.299f; pawnBones [5] = 0.90812f; int nbHeol = 5; terrain = new Terrain(ClientRectangle.Size); terrain.gridShader.ShadowMap = shadowMap; vaoDeformables = new VertexArrayObject <WeightedMeshData, WeightedInstancedData> (); vaoObjects = new VertexArrayObject <MeshData, InstancedData> (); car = (VAOItem <InstancedData>)vaoObjects.Add(OBJMeshLoader.Load("Meshes/car.obj")); car.DiffuseTexture = Tetra.Texture.Load("Meshes/0000.png"); car.InstancedDatas = new InstancedData[nbHeol]; for (int i = 0; i < nbHeol; i++) { Vector2 pos = new Vector2((float)rnd.Next(0, terrain.GridSize), (float)rnd.Next(0, terrain.GridSize)); car.InstancedDatas[i].modelMats = Matrix4.CreateScale(0.2f) * Matrix4.CreateTranslation(pos.X - (pos.X % 4f) + 0.5f, pos.Y - (pos.Y % 4f) + 0.5f, 0.1f); } car.UpdateInstancesData(); nbHeol = 50; // trees = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/trees/treesTrunk.obj")); // treesLeave = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/trees/treesLeaves.obj")); // trees.DiffuseTexture = Tetra.Texture.Load ("Meshes/trees/treeTrunk.jpg"); // treesLeave.DiffuseTexture = Tetra.Texture.Load ("Meshes/trees/treeLeaves.png"); // trees.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // treesLeave.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // float angle = (float)(rnd.NextDouble() * Math.PI); // trees.InstancedDatas[i].modelMats = Matrix4.CreateRotationZ(angle) * Matrix4.CreateScale(4f) * Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // treesLeave.InstancedDatas [i].modelMats = trees.InstancedDatas [i].modelMats; // } // trees.UpdateInstancesData(); // // treesLeave.UpdateInstancesData(); //HEOLIENNES nbHeol = 5; // heoliennes = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/heolienne.obj")); // heoliennes.DiffuseTexture = Tetra.Texture.Load ("Meshes/heolienne.png"); // heoliennes.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // heoliennes.InstancedDatas[i].modelMats = Matrix4.CreateScale(0.1f) * Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // heoliennes.InstancedDatas [i].quat0 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat1 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat2 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat3 = Quaternion.Identity; //// heoliennes.InstancedDatas [i].bpos0 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos1 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos2 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos3 = new Vector4 (0f, 0f, 0f, 0f); // } // heoliennes.UpdateInstancesData(); nbHeol = 5; heollow = (VAOItem <WeightedInstancedData>)vaoDeformables.Add(OBJMeshLoader.Load("Meshes/heolienne_lod0.obj")); heollow.DiffuseTexture = Tetra.Texture.Load("Meshes/heollow.png"); heollow.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; for (int i = 0; i < nbHeol; i++) { Vector2 pos = new Vector2((float)rnd.Next(0, terrain.GridSize), (float)rnd.Next(0, terrain.GridSize)); heollow.InstancedDatas[i].modelMats = Matrix4.CreateTranslation(pos.X - (pos.X % 4f) + 0.5f, pos.Y - (pos.Y % 4f) + 0.5f, 0f); heollow.InstancedDatas [i].quat0 = Quaternion.Identity; heollow.InstancedDatas [i].quat1 = Quaternion.Identity; heollow.InstancedDatas [i].quat2 = Quaternion.Identity; heollow.InstancedDatas [i].quat3 = Quaternion.Identity; // heollow.InstancedDatas [i].bpos0 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos1 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos2 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos3 = new Vector4 (0f, 0f, 0f, 0f); } heollow.UpdateInstancesData(); // pawn = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/pawn.obj")); // pawn.DiffuseTexture = Tetra.Texture.Load ("Meshes/pawn.png"); // pawn.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // pawn.InstancedDatas[i].modelMats = Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // pawn.InstancedDatas [i].quat0 = Quaternion.Identity; // pawn.InstancedDatas [i].quat1 = Quaternion.Identity; // pawn.InstancedDatas [i].quat2 = Quaternion.Identity; // pawn.InstancedDatas [i].quat3 = Quaternion.Identity; // } // pawn.UpdateInstancesData(); //landItemsVao.ComputeTangents(); vaoDeformables.BuildBuffers(); vaoObjects.BuildBuffers(); // const float treezone = 32; // const int treeCount = 50; // transparentItemsVao = new VertexArrayObject<MeshData, VAOInstancedData> (); // // //====TREE1==== // // vaoi = transparentItemsVao.Add (Tetra.OBJMeshLoader.Load ("#Ottd3D.images.trees.obj__pinet1.obj")); // // vaoi.DiffuseTexture = Tetra.Texture.Load("#Ottd3D.images.trees.pinet1.png"); // // vaoi.modelMats = new Matrix4[treeCount]; // // for (int i = 0; i < treeCount; i++) { // // Vector2 pos = new Vector2 ((float)rnd.NextDouble() * treezone, (float)rnd.NextDouble() * treezone); // // float scale = (float)rnd.NextDouble () * 0.002f + 0.004f; // // vaoi.modelMats[i] =treeRot * Matrix4.CreateScale (scale)* Matrix4.CreateTranslation(pos.X, pos.Y, 0f); // // } // // vaoi.UpdateInstancesData (); // // //====TREE2==== // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.simple.obj", // // "#Ottd3D.images.trees.birch_tree_small_20131230_2041956203.png",400f); // // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__pinet1.obj", // // "#Ottd3D.images.trees.pinet1.png",5f); // addRandomTrees (transparentItemsVao, treeCount, // "images/trees/obj__pinet2.obj", // "images/trees/pinet2.png",3f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree1.obj", // // "#Ottd3D.images.trees.tree1.png",5f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree2.obj", // // "#Ottd3D.images.trees.tree2.png", 5f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree3.obj", // // "#Ottd3D.images.trees.tree3.png", 5f); // // //transparentItemsVao.ComputeTangents (); // transparentItemsVao.BuildBuffers (); }
public Graphics(UserControl control, SceneTime time, ShadingTechnique technique) { Assert.NotNull(control); Assert.NotNull(time); IsDisposed = false; CurrentShadingTechnique = technique; if (GL.GetCurrent(false) != null || GetCurrent(false) != null) { var error = "Only one NetGL view per thread is now supported. Try launching 3D view in different thread."; Log.Error(error); throw new InvalidOperationException(error); } _control = control; _time = time; try { _glContext = new GL(_control.Handle); } catch { Dispose(); throw; } _currentContext.Value = this; _glContext.Enable(EnableCap.DepthTest); _glContext.Enable(EnableCap.Texture2D); _glContext.Enable(EnableCap.CullFace); _glContext.Enable(EnableCap.ProgramPointSize); _glContext.Enable(EnableCap.PointSprite); _glContext.CullFace(MaterialFace.Back); _glContext.FrontFace(FrontFaceDirection.CounterClockwise); _glContext.BlendEquation(BlendEquations.FuncAdd); _glContext.BlendFunc(BlendMode.SrcAlpha, BlendMode.OneMinusSrcAlpha); _glContext.SwapInterval(_swapInterval); _globalUniforms = new GlobalUniformsBufferObject(); _standartUniforms = new StandardUniformsBufferObject(); _defaultMaterial = new Material(MaterialType.DiffuseColor); _blankTexture = new Texture2(); _blankTexture.SetImage(new byte[4] { 255, 0, 255, 255 }, new Size(1, 1), Core.PixelFormat.Rgba, Core.PixelInternalFormat.Rgba8); _quadShader = new QuadShader(); _displayQuadVao = CreateDisplayQuadVao(); switch (CurrentShadingTechnique) { case ShadingTechnique.Forward: _renderTechnique = new ForwardRender(); break; case ShadingTechnique.Deferred: _renderTechnique = new DeferredRender(); break; default: throw new NotSupportedException(CurrentShadingTechnique.ToString()); } ScreenSize = _control.ClientSize; }
public static void Initialize(GL_ControlModern control, float scale) { if (DefaultShaderProgram != null && DefaultShaderProgram.programs.ContainsKey(control)) { return; } if (DefaultShaderProgram == null) { var solidColorFrag = new FragmentShader( @"#version 330 uniform vec4 color; out vec4 fragColor; void main(){ fragColor = color; }"); var solidColorVert = new VertexShader( @"#version 330 layout(location = 0) in vec4 position; uniform mat4 mtxMdl; uniform mat4 mtxCam; void main(){ gl_Position = mtxCam*mtxMdl*position; }"); var defaultFrag = new FragmentShader( @"#version 330 uniform vec4 highlight_color; uniform sampler2D texture0; in vec3 viewPosition; in vec3 normal; in vec2 f_texcoord0; out vec4 fragColor; void main(){ vec4 color = texture(texture0,f_texcoord0); float hc_a = highlight_color.w; vec4 colorComb = vec4(color.rgb * (1-hc_a) + highlight_color.rgb * hc_a, color.a); vec3 displayNormal = (normal.xyz * 0.5) + 0.5; float halfLambert = max(displayNormal.y,0.5); vec4 colorOutput = vec4(colorComb.rgb * halfLambert, colorComb.a); fragColor = colorOutput; }"); var defaultVert = new VertexShader( @"#version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec3 vNormal; layout(location = 2) in vec2 vTexCoord; uniform mat4 mtxMdl; uniform mat4 mtxCam; out vec3 normal; out vec3 viewPosition; out vec2 f_texcoord0; void main(){ normal = vNormal; viewPosition = position; f_texcoord0 = vTexCoord; gl_Position = mtxCam*mtxMdl*vec4(position, 1); }"); DefaultShaderProgram = new ShaderProgram(defaultFrag, defaultVert, control); SolidColorShaderProgram = new ShaderProgram(solidColorFrag, solidColorVert, control); int buffer = GL.GenBuffer(); sphereVao = new VertexArrayObject(buffer); sphereVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, 32, 0); sphereVao.AddAttribute(1, 3, VertexAttribPointerType.Float, false, 32, 12); sphereVao.AddAttribute(2, 2, VertexAttribPointerType.Float, false, 32, 24); sphereVao.Initialize(control); List <float> list = new List <float>(); Vertices = GetVertices(scale); for (int i = 0; i < Vertices.Length; i++) { list.Add(Vertices[i].Position.X); list.Add(Vertices[i].Position.Y); list.Add(Vertices[i].Position.Z); list.Add(Vertices[i].Normal.X); list.Add(Vertices[i].Normal.Y); list.Add(Vertices[i].Normal.Z); list.Add(Vertices[i].TexCoord.X); list.Add(Vertices[i].TexCoord.Y); } float[] data = list.ToArray(); GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw); } else { sphereVao.Initialize(control); DefaultShaderProgram.Link(control); SolidColorShaderProgram.Link(control); } }
protected override void DoRender(RenderEventArgs e) { GL.BindTexture(GL.GL_TEXTURE_3D, this.NoiseTextureID); ShaderProgram program = this.shaderProgram; // 绑定shader program.Bind(); program.SetUniformMatrix4(strprojectionMatrix, projectionMatrix.to_array()); program.SetUniformMatrix4(strviewMatrix, viewMatrix.to_array()); program.SetUniformMatrix4(strmodelMatrix, modelMatrix.to_array()); program.SetUniform(strLightPos, LightPos.x, LightPos.y, LightPos.z); program.SetUniform(strScale, this.Scale); program.SetUniform(strTimeFromInit, this.TIME_FROM_INIT); this.TIME_FROM_INIT += 0.0001f; program.SetUniform(strNoise, this.NoiseTextureID); program.SetUniform(strSkyColor, this.SkyColor.x, SkyColor.y, SkyColor.z); program.SetUniform(strCloudColor, CloudColor.x, CloudColor.y, CloudColor.z); int[] originalPolygonMode = new int[1]; GL.GetInteger(GetTarget.PolygonMode, originalPolygonMode); GL.PolygonMode(PolygonModeFaces.FrontAndBack, this.polygonMode); if (this.vertexArrayObject == null) { var vertexArrayObject = new VertexArrayObject( this.positionBufferRenderer, //this.colorBufferRenderer, this.normalBufferRenderer, this.indexBufferRenderer); vertexArrayObject.Create(e, this.shaderProgram); this.vertexArrayObject = vertexArrayObject; } else { this.vertexArrayObject.Render(e, this.shaderProgram); } GL.PolygonMode(PolygonModeFaces.FrontAndBack, (PolygonModes)(originalPolygonMode[0])); // 解绑shader program.Unbind(); GL.BindTexture(GL.GL_TEXTURE_3D, 0); }
public FencedBufferObjects(VertexBuffer vbo, VertexArrayObject vao) { VBO = vbo; VAO = vao; }
public void SetArraySectionBySemantic_Exception2() { using (VertexArrayObject vertexArray = new VertexArrayObject()) { using (ArrayBufferObject arrayBuffer = new ArrayBufferObject(VertexBaseType.Float, 3, BufferObjectHint.StaticCpuDraw)) { // arrayBuffer is empty Assert.Throws(Is.InstanceOf(typeof(ArgumentException)), delegate () { vertexArray.SetArray(arrayBuffer, 1, VertexArraySemantic.Position); }); } } }
public void Draw() { Vertex2f[] vertices = new Vertex2f[] { new Vertex2f(0.0f, 0.0f), new Vertex2f(1.0f, 0.0f), new Vertex2f(1.0f, 1.0f), new Vertex2f(0.0f, 1.0f), }; using (VertexArrayObject vao = new VertexArrayObject()) { // Setup ABO (Position) ArrayBufferObject abo = new ArrayBufferObject(VertexBaseType.Float, 2, BufferObjectHint.StaticCpuDraw); abo.Create(vertices); // Setup VAO vao.SetArray(abo, VertexArraySemantic.Position); vao.SetElementArray(PrimitiveType.TriangleStrip); vao.Create(_Context); using (State.GraphicsStateSet currentState = State.GraphicsStateSet.GetDefaultSet()) { // Set transform state State.TransformStateBase stateTransform = (State.TransformStateBase)currentState[State.TransformStateBase.StateId]; // Set normalized orthogonal projection stateTransform.LocalProjection = new OrthoProjectionMatrix(0.0f, 1.0f, 0.0f, 1.0f); // Apply state currentState.Apply(_Context); // Draw Assert.DoesNotThrow(delegate () { vao.Draw(_Context); }); } } }
public void SetArrayByBlock_Exception2() { using (VertexArrayObject vertexArray = new VertexArrayObject()) { using (ArrayBufferObject arrayBuffer = new ArrayBufferObject(VertexBaseType.Float, 3, BufferObjectHint.StaticCpuDraw)) { // arrayBuffer is empty Assert.Throws(Is.InstanceOf(typeof(ArgumentException)), delegate () { vertexArray.SetArray(arrayBuffer, "attributeName", null); }); } } }
public void SetArraySectionBySemantic_Exception1() { using (VertexArrayObject vertexArray = new VertexArrayObject()) { // attributeName is null Assert.Throws(Is.InstanceOf(typeof(ArgumentException)), delegate () { vertexArray.SetArray(null, 0, null); }); // attributeName is empty Assert.Throws(Is.InstanceOf(typeof(ArgumentException)), delegate () { vertexArray.SetArray(null, 0, String.Empty); }); } }
public void SetArraySectionByBlock_Exception3() { using (VertexArrayObject vertexArray = new VertexArrayObject()) { using (ArrayBufferObject arrayBuffer = new ArrayBufferObject(VertexBaseType.Float, 3, BufferObjectHint.StaticCpuDraw)) { // Create the array buffer arrayBuffer.Create(16); // sectionIndex is out of range Assert.Throws(Is.InstanceOf(typeof(ArgumentOutOfRangeException)), delegate () { vertexArray.SetArray(arrayBuffer, 1, "attributeName", null); }); } } }
public static void Initialize() { if (!Initialized) { var defaultFrag = new FragmentShader( @"#version 330 uniform sampler2D tex; in vec4 fragColor; in vec3 fragPosition; in vec2 uv; void main(){ gl_FragColor = fragColor*((fragPosition.y+2)/3)*texture(tex, uv, 100); }"); var defaultVert = new VertexShader( @"#version 330 layout(location = 0) in vec4 position; uniform vec4 color; uniform mat4 mtxMdl; uniform mat4 mtxCam; out vec4 fragColor; out vec3 fragPosition; out vec2 uv; vec2 map(vec2 value, vec2 min1, vec2 max1, vec2 min2, vec2 max2) { return min2 + (value - min1) * (max2 - min2) / (max1 - min1); } void main(){ fragPosition = position.xyz; uv = map(fragPosition.xz,vec2(-1.0625,-1.0625),vec2(1.0625,1.0625), vec2(0.5,0.5), vec2(0.75,1.0)); gl_Position = mtxCam*mtxMdl*position; fragColor = color; }"); DefaultShaderProgram = new ShaderProgram(defaultFrag, defaultVert); int buffer; #region block buffer = GL.GenBuffer(); blockVao = new VertexArrayObject(buffer); blockVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, sizeof(float) * 3, 0); blockVao.Submit(); List <float> list = new List <float>(); Face(ref points, ref list, 0, 1, 2, 3); FaceInv(ref points, ref list, 4, 5, 6, 7); FaceInv(ref points, ref list, 0, 1, 4, 5); Face(ref points, ref list, 2, 3, 6, 7); Face(ref points, ref list, 0, 2, 4, 6); FaceInv(ref points, ref list, 1, 3, 5, 7); float[] data = list.ToArray(); GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw); #endregion #region lines buffer = GL.GenBuffer(); linesVao = new VertexArrayObject(buffer); linesVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, sizeof(float) * 3, 0); linesVao.Submit(); list = new List <float>(); LineFace(ref points, ref list, 0, 1, 2, 3); LineFace(ref points, ref list, 4, 5, 6, 7); Line(ref points, ref list, 0, 4); Line(ref points, ref list, 1, 5); Line(ref points, ref list, 2, 6); Line(ref points, ref list, 3, 7); data = list.ToArray(); GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw); #endregion #region legacy lines lineDrawList = GL.GenLists(1); GL.NewList(lineDrawList, ListMode.Compile); GL.Begin(PrimitiveType.LineStrip); GL.Vertex3(points[6]); GL.Vertex3(points[2]); GL.Vertex3(points[3]); GL.Vertex3(points[7]); GL.Vertex3(points[6]); GL.Vertex3(points[4]); GL.Vertex3(points[5]); GL.Vertex3(points[1]); GL.Vertex3(points[0]); GL.Vertex3(points[4]); GL.End(); GL.Begin(PrimitiveType.Lines); GL.Vertex3(points[2]); GL.Vertex3(points[0]); GL.Vertex3(points[3]); GL.Vertex3(points[1]); GL.Vertex3(points[7]); GL.Vertex3(points[5]); GL.End(); GL.EndList(); #endregion Initialized = true; } }
public void VertexArrayObject() { VertexArrayObject glObject = new VertexArrayObject(); Assert.AreEqual($"VertexArrayObject ID: {glObject.Id}", glObject.ToString()); }
public void TestLineShaderRender() { using (ShaderProgram shaderProgram = ShadersLibrary.Instance.CreateProgram("OpenGL.Line")) { Assert.DoesNotThrow(delegate () { shaderProgram.Create(_Context); }); using (VertexArrayObject vao = new VertexArrayObject()) { List<Vertex2f> vertices = new List<Vertex2f>(); for (float y = 0.375f; y < _Framebuffer.Height; y += 2.0f) { vertices.Add(new Vertex2f(0.0f, y)); vertices.Add(new Vertex2f(_Framebuffer.Width, y)); } // Setup ABO (Position) ArrayBufferObject abo = new ArrayBufferObject(VertexBaseType.Float, 2, BufferObjectHint.StaticCpuDraw); abo.Create(vertices.ToArray()); // Setup VAO vao.SetArray(abo, VertexArraySemantic.Position); vao.SetElementArray(PrimitiveType.Lines); vao.Create(_Context); // Draw test Image feedbackImageFixed = null, feedbackImageShader = null; try { Gl.Viewport(0, 0, (int)_Framebuffer.Width, (int)_Framebuffer.Height); #region Fixed pipeline _Framebuffer.SetClearColor(new ColorRGBAF(0.0f, 0.0f, 0.0f)); _Framebuffer.Clear(_Context); Gl.MatrixMode(MatrixMode.Projection); Gl.LoadMatrix(new OrthoProjectionMatrix(0.0f, _Framebuffer.Width, 0.0f, _Framebuffer.Height).ToArray()); Gl.MatrixMode(MatrixMode.Modelview); Gl.LoadIdentity(); Gl.Color3(1.0f, 1.0f, 1.0f); Gl.LineWidth(1.0f); vao.Draw(_Context); feedbackImageFixed = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8); ImageCodec.Instance.Save( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LineProgram.Fixed.png"), feedbackImageFixed, ImageFormat.Png, null ); #endregion #region Shader pipeline _Framebuffer.SetClearColor(new ColorRGBAF(0.0f, 0.0f, 0.0f)); _Framebuffer.Clear(_Context); shaderProgram.Bind(_Context); shaderProgram.SetUniform(_Context, "hal_ModelViewProjection", RenderProjectionMatrix); shaderProgram.SetUniform(_Context, "hal_UniformColor", new ColorRGBA(1.0f, 1.0f, 1.0f)); shaderProgram.SetUniform(_Context, "hal_LineWidth", 1.0f); shaderProgram.SetUniform(_Context, "hal_ViewportSize", new Vertex2f(_Framebuffer.Width, _Framebuffer.Height)); vao.Draw(_Context, shaderProgram); feedbackImageShader = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8); ImageCodec.Instance.Save( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "LineProgram.Shader.png"), feedbackImageShader, ImageFormat.Png, null ); #endregion // Compare results } finally { if (feedbackImageFixed != null) feedbackImageFixed.Dispose(); if (feedbackImageShader != null) feedbackImageShader.Dispose(); } } //// Get rendering feedback //using (Image feedbackImage = _Framebuffer.ReadColorBuffer(_Context, 0, 0, 0, _Framebuffer.Width, _Framebuffer.Height, PixelLayout.GRAY8)) { // // Drawn only even lines // for (uint y = 0; y < _Framebuffer.Height; y++) { // for (uint x = 0; x < _Framebuffer.Width; x++) { // ColorGRAY8 fragment = (ColorGRAY8)feedbackImage[x, y]; // Assert.AreEqual((y % 2) == 0 ? 255 : 0, fragment.Level, String.Format("Color mismatch at {0}x{1}", x, y)); // } // } //} } }
/// <summary> /// Test for default values after construction. /// </summary> /// <param name="vertexArray"></param> private void ConstructionDefaulValues(VertexArrayObject vertexArray) { Assert.AreEqual(0, vertexArray.ArrayLength); }
protected override void DoRender(RenderEventArgs e) { ShaderProgram program = this.shaderProgram; // 绑定shader program.Bind(); program.SetUniformMatrix4(strprojectionMatrix, projectionMatrix.to_array()); program.SetUniformMatrix4(strviewMatrix, viewMatrix.to_array()); program.SetUniformMatrix4(strmodelMatrix, modelMatrix.to_array()); program.SetUniform(strSpecularContribution, SpecularContribution); program.SetUniform(strLightPosition, LightPosition.x, LightPosition.y, LightPosition.z); program.SetUniform(strSpacing, Spacing.x, Spacing.y, Spacing.z); program.SetUniform(strDotSize, DotSize); program.SetUniform(strModelColor, ModelColor.x, ModelColor.y, ModelColor.z); program.SetUniform(strPolkaDotColor, PolkaDotColor.x, PolkaDotColor.y, PolkaDotColor.z); int[] originalPolygonMode = new int[1]; GL.GetInteger(GetTarget.PolygonMode, originalPolygonMode); GL.Enable(GL.GL_PRIMITIVE_RESTART); GL.PrimitiveRestartIndex(uint.MaxValue); GL.PolygonMode(PolygonModeFaces.FrontAndBack, this.polygonMode); GL.Enable(GL.GL_BLEND); GL.BlendFunc(CSharpGL.Enumerations.BlendingSourceFactor.SourceAlpha, CSharpGL.Enumerations.BlendingDestinationFactor.OneMinusSourceAlpha); if (this.vertexArrayObject == null) { var vao = new VertexArrayObject( this.positionBufferRenderer, //this.colorBufferRenderer, this.normalBufferRenderer, this.indexBufferRenderer); vao.Create(e, this.shaderProgram); this.vertexArrayObject = vao; } else { this.vertexArrayObject.Render(e, this.shaderProgram); } GL.Disable(GL.GL_BLEND); GL.PolygonMode(PolygonModeFaces.FrontAndBack, (PolygonModes)(originalPolygonMode[0])); GL.Disable(GL.GL_PRIMITIVE_RESTART); // 解绑shader program.Unbind(); }
/// <summary> /// Test for default values after construction. /// </summary> /// <param name="vertexArray"></param> private void DispositionDefaulValues(VertexArrayObject vertexArray) { }
public static void DrawNudMaterialSphere(Shader shader, NUD.Material material, VertexArrayObject screenVao, Dictionary <NUD.DummyTextures, Texture> dummyTextures) { if (!shader.ProgramCreatedSuccessfully) { return; } shader.UseProgram(); // Use the same uniforms as the NUD shader. NUD.SetMaterialPropertyUniforms(shader, material); NUD.SetStageLightingUniforms(shader, 0); ModelContainer.SetRenderSettingsUniforms(shader); nudSphereCamera.UpdateMatrices(); ModelContainer.SetLightingUniforms(shader, nudSphereCamera); ModelContainer.SetCameraMatrixUniforms(nudSphereCamera, shader); // Use default textures rather than textures from the NUT. NUD.SetTextureUniformsNudMatSphere(shader, material, dummyTextures); // These values aren't needed in the shader currently. shader.SetVector3("cameraPosition", 0, 0, 0); shader.SetFloat("zBufferOffset", 0); shader.SetFloat("bloomThreshold", Runtime.bloomThreshold); bool isTransparent = (material.srcFactor > 0) || (material.dstFactor > 0) || (material.alphaFunction > 0) || (material.alphaTest > 0); shader.SetBoolToInt("isTransparent", isTransparent); // Set texture uniforms for the mesh attributes. shader.SetTexture("normalTex", sphereNrmTex.Id, TextureTarget.Texture2D, 15); shader.SetTexture("uvTex", sphereUvTex.Id, TextureTarget.Texture2D, 16); shader.SetTexture("tanTex", sphereTanTex.Id, TextureTarget.Texture2D, 17); shader.SetTexture("bitanTex", sphereBitanTex.Id, TextureTarget.Texture2D, 18); // Draw full screen "quad" (big triangle) ScreenDrawing.DrawScreenTriangle(shader, screenVao); }
/// <summary>Creates a new colored cube</summary> public Cube(BaseRenderer renderer, Color128 color) { this.renderer = renderer; LibRenderVertex[] vertexData = { // back new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = color }, // right new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.Down, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.Null, Color = color }, // top new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.One, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Down, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = color }, // front new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.Down, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Null, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.Right, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.One, Color = color }, // left new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.One, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Right, Color = color }, // bottom new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.Null, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.Right, Color = color }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = color }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = color } }; if (!renderer.ForceLegacyOpenGL) { defaultVAO = new VertexArrayObject(); defaultVAO.Bind(); defaultVAO.SetVBO(new VertexBufferObject(vertexData, BufferUsageHint.StaticDraw)); defaultVAO.SetIBO(new IndexBufferObjectUS(Enumerable.Range(0, vertexData.Length).Select(x => (ushort)x).ToArray(), BufferUsageHint.StaticDraw)); defaultVAO.SetAttributes(renderer.DefaultShader.VertexLayout); defaultVAO.UnBind(); } }
public static void Initialize(GL_ControlModern control) { if (DefaultShaderProgram != null && DefaultShaderProgram.programs.ContainsKey(control)) { return; } if (DefaultShaderProgram == null) { var solidColorFrag = new FragmentShader( @"#version 330 uniform vec4 color; in vec3 normal; in vec3 viewPosition; void main(){ vec3 xTangent = dFdx( viewPosition ); vec3 yTangent = dFdy( viewPosition ); vec3 faceNormal = normalize( cross( xTangent, yTangent ) ); vec3 displayNormal = (faceNormal.xyz * 0.5) + 0.5; float shading = max(displayNormal.y,0.5); gl_FragColor = color; }"); var solidColorVert = new VertexShader( @"#version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec3 vNormal; uniform mat4 mtxMdl; uniform mat4 mtxCam; out vec3 normal; out vec3 viewPosition; void main(){ normal = vNormal; viewPosition = position; gl_Position = mtxCam*mtxMdl*vec4(position, 1); }"); DefaultShaderProgram = new ShaderProgram(solidColorFrag, solidColorVert, control); int buffer = GL.GenBuffer(); sphereVao = new VertexArrayObject(buffer); sphereVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, 24, 0); sphereVao.AddAttribute(1, 3, VertexAttribPointerType.Float, false, 24, 12); sphereVao.Initialize(control); List <float> list = new List <float>(); Vertices = GetVertices(10, 2, 15, 32); for (int i = 0; i < Vertices.Length; i++) { var mat = Matrix4.CreateRotationX(MathHelper.DegreesToRadians(90)); Vertices[i].Position = Vector3.TransformPosition(Vertices[i].Position, mat); Vertices[i].Normal = Vector3.TransformNormal(Vertices[i].Normal, mat); list.Add(Vertices[i].Position.X); list.Add(Vertices[i].Position.Y); list.Add(Vertices[i].Position.Z); list.Add(Vertices[i].Normal.X); list.Add(Vertices[i].Normal.Y); list.Add(Vertices[i].Normal.Z); } float[] data = list.ToArray(); GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw); } else { sphereVao.Initialize(control); DefaultShaderProgram.Link(control); } }
public AnimatedSkin(VertexArrayObject vao, ParentBone rootBone) : base(vao) { m_rootBone = rootBone; }
public static void Initialize() { if (!Initialized) { var defaultFrag = new FragmentShader( @"#version 330 uniform sampler2D tex; uniform vec4 color; in vec2 uv; void main(){ gl_FragColor = color * texture(tex,uv); }"); var defaultVert = new VertexShader( @"#version 330 layout(location = 0) in vec4 position; uniform vec2 uvTopLeft; uniform mat4 mtxMdl; uniform mat4 mtxCam; out vec2 uv; vec2 map(vec2 value, vec2 min1, vec2 max1, vec2 min2, vec2 max2) { return min2 + (value - min1) * (max2 - min2) / (max1 - min1); } void main(){ uv = map(position.xy,vec2(-0.5,0.5),vec2(0.5,-0.5), uvTopLeft, uvTopLeft+vec2(0.25,0.25)); gl_Position = mtxCam*mtxMdl*position; }"); DefaultShaderProgram = new ShaderProgram(defaultFrag, defaultVert); int buffer; #region block buffer = GL.GenBuffer(); planeVao = new VertexArrayObject(buffer); planeVao.AddAttribute(0, 3, VertexAttribPointerType.Float, false, sizeof(float) * 3, 0); planeVao.Submit(); float[] data = new float[] { -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, 0.5f, 0.5f, 0, -0.5f, 0.5f, 0, }; GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, BufferUsageHint.StaticDraw); #endregion //texture sheet TextureSheet = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, TextureSheet); var bmp = Properties.Resources.Gizmos; var bmpData = bmp.LockBits( new Rectangle(0, 0, 128 * 4, 128 * 4), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, 128 * 4, 128 * 4, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.GenerateMipmap(GenerateMipmapTarget.Texture2D); bmp.UnlockBits(bmpData); Initialized = true; } }
private Skin SendDataToGpu(string modelPath) { Skin resultSkin = null; // Get mesh data using (AssimpModelLoader loader = new AssimpModelLoader(modelPath)) { VertexArrayObject vao = new VertexArrayObject(); MeshVertexData meshData = loader.GetMeshData(); // explicit null assignment if there is no some of mesh data var vertices = meshData.Verts; var normals = meshData.bHasNormals ? meshData.N_Verts : null; var texCoords = meshData.T_Verts; var tangents = meshData.bHasTangentVertices ? meshData.Tangent_Verts : meshData.bHasTextureCoordinates ? VectorMath.AdditionalVertexInfoCreator.CreateTangentVertices(vertices, texCoords) : null; var bitangents = meshData.bHasTangentVertices ? meshData.Bitanget_Verts : meshData.bHasTextureCoordinates ? VectorMath.AdditionalVertexInfoCreator.CreateBitangentVertices(vertices, texCoords) : null; var blendWeights = meshData.bHasAnimation ? meshData.BlendWeights : null; var blendIndices = meshData.bHasAnimation ? meshData.BlendIndices : null; UInt32[] indices = meshData.bHasIndices ? meshData.Indices.ToArray() : null; IndexBufferObject ibo = null; VertexBufferObjectTwoDimension <float> normalsVBO = null, texCoordsVBO = null, tangentsVBO = null, bitangentsVBO = null, blendWeightsVBO = null; VertexBufferObjectTwoDimension <Int32> blendIndicesVBO = null; if (meshData.bHasIndices) { ibo = new IndexBufferObject(indices); } VertexBufferObjectTwoDimension <float> vertexVBO = new VertexBufferObjectTwoDimension <float>(vertices, BufferTarget.ArrayBuffer, 0, 3, VertexBufferObjectBase.DataCarryFlag.Invalidate); if (meshData.bHasNormals) { normalsVBO = new VertexBufferObjectTwoDimension <float>(normals, BufferTarget.ArrayBuffer, 1, 3, VertexBufferObjectBase.DataCarryFlag.Invalidate); } if (meshData.bHasTextureCoordinates) { texCoordsVBO = new VertexBufferObjectTwoDimension <float>(texCoords, BufferTarget.ArrayBuffer, 2, 2, VertexBufferObjectBase.DataCarryFlag.Invalidate); } if (meshData.bHasTangentVertices) { tangentsVBO = new VertexBufferObjectTwoDimension <float>(tangents, BufferTarget.ArrayBuffer, 4, 3, VertexBufferObjectBase.DataCarryFlag.Invalidate); } if (meshData.bHasTangentVertices) { bitangentsVBO = new VertexBufferObjectTwoDimension <float>(bitangents, BufferTarget.ArrayBuffer, 5, 3, VertexBufferObjectBase.DataCarryFlag.Invalidate); } if (meshData.bHasAnimation) { Int32 skeletonWeightsPerVertexCount = (Int32)loader.m_skeletonType; if (skeletonWeightsPerVertexCount > 4) { throw new NotImplementedException("There is no implementation yet for cases when there are more than four weights influencing on vertex."); } Int32 vectorSize = skeletonWeightsPerVertexCount; blendWeightsVBO = new VertexBufferObjectTwoDimension <float>(blendWeights, BufferTarget.ArrayBuffer, 6, vectorSize, VertexBufferObjectBase.DataCarryFlag.Invalidate); blendIndicesVBO = new VertexBufferObjectTwoDimension <int>(blendIndices, BufferTarget.ArrayBuffer, 7, vectorSize, VertexBufferObjectBase.DataCarryFlag.Invalidate); } vao.AddVBO(vertexVBO, normalsVBO, texCoordsVBO, tangentsVBO, bitangentsVBO, blendWeightsVBO, blendIndicesVBO); vao.AddIndexBuffer(ibo); vao.BindBuffersToVao(); if (meshData.bHasAnimation) { ParentBone rootBone = AssimpConverter.Converter.ConvertAssimpBoneToEngineBone(meshData.SkeletonRoot); resultSkin = new AnimatedSkin(vao, rootBone); } else { resultSkin = new Skin(vao); } } return(resultSkin); }
internal void Initialize(GraphicsDevice device) { vertexArrayObject = VertexArrayObject.New(device, Effect.InputSignature, Mesh.Draw.IndexBuffer, Mesh.Draw.VertexBuffers); }
private unsafe void InitVertexBuffers() { // http://images.cnblogs.com/cnblogs_com/bitzhuwei/482613/o_Cube-small.jpg { VR03PositionBuffer positionBuffer = new VR03PositionBuffer(strin_Position); positionBuffer.Alloc(xFrameCount * yFrameCount * zFrameCount); HexahedronPosition *array = (HexahedronPosition *)positionBuffer.FirstElement(); int index = 0; for (int i = 0; i < xFrameCount; i++) { for (int j = 0; j < yFrameCount; j++) { for (int k = 0; k < zFrameCount; k++) { var x = ((float)i / (float)xFrameCount - 0.5f) * factor; var y = ((float)j / (float)yFrameCount - 0.5f) * factor; var z = (((float)k / (float)zFrameCount - 0.5f) * 109.0f / 256.0f) * factor; var hexahedron = new HexahedronPosition(); hexahedron.v0 = new vec3(x + hexahedronHalfLength, y + hexahedronHalfLength, z + hexahedronHalfLength); hexahedron.v1 = new vec3(x - hexahedronHalfLength, y + hexahedronHalfLength, z + hexahedronHalfLength); hexahedron.v2 = new vec3(x + hexahedronHalfLength, y - hexahedronHalfLength, z + hexahedronHalfLength); hexahedron.v3 = new vec3(x - hexahedronHalfLength, y - hexahedronHalfLength, z + hexahedronHalfLength); hexahedron.v4 = new vec3(x + hexahedronHalfLength, y + hexahedronHalfLength, z - hexahedronHalfLength); hexahedron.v5 = new vec3(x - hexahedronHalfLength, y + hexahedronHalfLength, z - hexahedronHalfLength); hexahedron.v6 = new vec3(x + hexahedronHalfLength, y - hexahedronHalfLength, z - hexahedronHalfLength); hexahedron.v7 = new vec3(x - hexahedronHalfLength, y - hexahedronHalfLength, z - hexahedronHalfLength); array[index++] = hexahedron; } } } this.positionBufferRenderer = positionBuffer.GetRenderer(); positionBuffer.Dispose(); } { VR03UVBuffer uvBuffer = new VR03UVBuffer(strin_uv); uvBuffer.Alloc(xFrameCount * yFrameCount * zFrameCount); HexahedronUV *array = (HexahedronUV *)uvBuffer.FirstElement(); int index = 0; for (int i = 0; i < xFrameCount; i++) { for (int j = 0; j < yFrameCount; j++) { for (int k = 0; k < zFrameCount; k++) { var x = (float)i / (float)xFrameCount; var y = (float)j / (float)yFrameCount; var z = (float)k / (float)zFrameCount; var color = new vec3(x, y, z); var uv = new HexahedronUV(); uv.v0 = color; uv.v1 = color; uv.v2 = color; uv.v3 = color; uv.v4 = color; uv.v5 = color; uv.v6 = color; uv.v7 = color; array[index++] = uv; } } } this.uvBufferRenderer = uvBuffer.GetRenderer(); uvBuffer.Dispose(); } { var indexBuffer = new VR03IndexBuffer(); indexBuffer.Alloc(xFrameCount * yFrameCount * zFrameCount); HexahedronIndex *array = (HexahedronIndex *)indexBuffer.FirstElement(); int index = 0; for (int i = 0; i < xFrameCount; i++) { for (int j = 0; j < yFrameCount; j++) { for (int k = 0; k < zFrameCount; k++) { uint centerIndex = (uint)((i * yFrameCount * zFrameCount + j * zFrameCount + k) * 8); array[index++] = new HexahedronIndex(centerIndex); } } } this.indexBufferRenderer = indexBuffer.GetRenderer() as IndexBufferPointerBase; indexBuffer.Dispose(); } this.vao = new VertexArrayObject( this.indexBufferRenderer, this.positionBufferRenderer, this.uvBufferRenderer); }
private unsafe void InitVertexBuffers() { { VR04PositionBuffer positionBuffer = new VR04PositionBuffer(strin_Position); positionBuffer.Alloc(zFrameCount); QuadPosition *array = (QuadPosition *)positionBuffer.FirstElement(); for (int i = 0; i < zFrameCount; i++) { array[i] = new QuadPosition( new vec3(-xLength, -yLength, (float)i / (float)zFrameCount - 0.5f), new vec3(xLength, -yLength, (float)i / (float)zFrameCount - 0.5f), new vec3(xLength, yLength, (float)i / (float)zFrameCount - 0.5f), new vec3(-xLength, yLength, (float)i / (float)zFrameCount - 0.5f) ); } this.positionBufferRenderer = positionBuffer.GetRenderer(); positionBuffer.Dispose(); } { VR04UVBuffer uvBuffer = new VR04UVBuffer(strin_uv); uvBuffer.Alloc(zFrameCount); QuadUV *array = (QuadUV *)uvBuffer.FirstElement(); for (int i = 0; i < zFrameCount; i++) { array[i] = new QuadUV( new vec3(0, 0, (float)i / (float)zFrameCount), new vec3(1, 0, (float)i / (float)zFrameCount), new vec3(1, 1, (float)i / (float)zFrameCount), new vec3(0, 1, (float)i / (float)zFrameCount) ); } this.uvBufferRenderer = uvBuffer.GetRenderer(); uvBuffer.Dispose(); } { var indexBuffer = new VR04IndexBuffer(); indexBuffer.Alloc(zFrameCount); QuadIndex *array = (QuadIndex *)indexBuffer.FirstElement(); for (uint i = 0; i < zFrameCount; i++) { if (this.reverSide) { array[i] = new QuadIndex((zFrameCount - i - 1) * 4 + 0, (zFrameCount - i - 1) * 4 + 1, (zFrameCount - i - 1) * 4 + 2, (zFrameCount - i - 1) * 4 + 3 ); } else { array[i] = new QuadIndex(i * 4 + 0, i * 4 + 1, i * 4 + 2, i * 4 + 3); } } this.indexBufferRenderer = indexBuffer.GetRenderer(); indexBuffer.Dispose(); } //if (!this.reverSide) //{ // var indexBuffer = new ZeroIndexBuffer(DrawMode.Quads, zFrameCount * 4); // indexBuffer.Alloc(zFrameCount);// this actually does nothing. // this.indexBufferRenderer = indexBuffer.GetRenderer(); // indexBuffer.Dispose(); //} //else //{ // var indexBuffer = new VR04IndexBuffer(); // indexBuffer.Alloc(zFrameCount); // QuadIndex* array = (QuadIndex*)indexBuffer.FirstElement(); // for (uint i = 0; i < zFrameCount; i++) // { // //array[i] = new QuadIndex(i * 4 + 0, i * 4 + 1, i * 4 + 2, i * 4 + 3); // array[i] = new QuadIndex((zFrameCount - i - 1) * 4 + 0, // (zFrameCount - i - 1) * 4 + 1, // (zFrameCount - i - 1) * 4 + 2, // (zFrameCount - i - 1) * 4 + 3 // ); // } // this.indexBufferRenderer = indexBuffer.GetRenderer(); // indexBuffer.Dispose(); //} this.vao = new VertexArrayObject(this.positionBufferRenderer, this.uvBufferRenderer, this.indexBufferRenderer); }
static RenderCubemapSphere() { theOrientation = Matrix4.CreateFromQuaternion(new Quaternion(0f, 0f, 0f)); List <ShaderDescriptor> shadersDesc = new List <ShaderDescriptor>(); shadersDesc.Add(new ShaderDescriptor(ShaderType.VertexShader, "GpuNoise.shaders.cube-vs.glsl")); shadersDesc.Add(new ShaderDescriptor(ShaderType.FragmentShader, "GpuNoise.shaders.cube-ps.glsl")); ShaderProgramDescriptor sd = new ShaderProgramDescriptor(shadersDesc); theShader = Renderer.resourceManager.getResource(sd) as ShaderProgram; theVBO = new VertexBufferObject(BufferUsageHint.StaticDraw); theIBO = new IndexBufferObject(BufferUsageHint.StaticDraw); int lats = 25; int longs = 25; int vertIdx = 0; V3[] verts = new V3[(lats + 1) * (longs + 1)]; ushort[] index = new ushort[lats * longs * 6]; for (int i = 0; i <= lats; i++) { float theta = (float)i * (float)Math.PI / lats; float sinTheta = (float)Math.Sin(theta); float cosTheta = (float)Math.Cos(theta); for (int j = 0; j <= longs; j++) { float phi = (float)j * (float)(Math.PI * 2) / longs; float sinPhi = (float)Math.Sin(phi); float cosPhi = (float)Math.Cos(phi); float x = cosPhi * sinTheta; float y = sinPhi * sinTheta; float z = cosTheta; // float u = 1 - (j / longs); // float v = 1- (i / lats); V3 temp = new V3(); temp.Position = new Vector3(x, y, z); verts[vertIdx++] = temp; } } int indexIdx = 0; for (int i = 0; i < lats; i++) { for (int j = 0; j < longs; j++) { ushort first = (ushort)((i * (longs + 1)) + j); ushort second = (ushort)(first + longs + 1); index[indexIdx++] = first; index[indexIdx++] = second; index[indexIdx++] = (ushort)(first + 1); index[indexIdx++] = second; index[indexIdx++] = (ushort)(second + 1); index[indexIdx++] = (ushort)(first + 1); } } theVBO.setData(verts); theIBO.setData(index); theVAO = new VertexArrayObject(); theVAO.bindVertexFormat(theShader, V3.bindings()); thePipeline = new PipelineState(); thePipeline.shaderState.shaderProgram = theShader; thePipeline.vaoState.vao = theVAO; thePipeline.generateId(); }
private SceneObjectGeometry CreateCubeGeometry() { SceneObjectGeometry cubeGeometry = new SceneObjectGeometry("Cube"); #region State cubeGeometry.ObjectState.DefineState(new DepthTestState(DepthFunction.Less)); cubeGeometry.ObjectState.DefineState(new CullFaceState(FrontFaceDirection.Ccw, CullFaceMode.Back)); cubeGeometry.ObjectState.DefineState(new TransformState()); MaterialState cubeMaterialState = new MaterialState(); cubeMaterialState.FrontMaterial = new MaterialState.Material(ColorRGBAF.ColorWhite * 0.5f); cubeMaterialState.FrontMaterial.Ambient = ColorRGBAF.ColorBlack; cubeMaterialState.FrontMaterial.Diffuse = ColorRGBAF.ColorWhite * 0.5f; cubeMaterialState.FrontMaterial.Specular = ColorRGBAF.ColorWhite * 0.5f; cubeMaterialState.FrontMaterial.Shininess = 10.0f; cubeGeometry.ObjectState.DefineState(cubeMaterialState); #endregion #region Vertex Arrays if (_CubeArrayPosition == null) { _CubeArrayPosition = new ArrayBufferObject <Vertex3f>(BufferObjectHint.StaticCpuDraw); _CubeArrayPosition.Create(ArrayPosition); } if (_CubeArrayColor == null) { _CubeArrayColor = new ArrayBufferObject <ColorRGBF>(BufferObjectHint.StaticCpuDraw); _CubeArrayColor.Create(ArrayColors); } if (_CubeArrayNormal == null) { _CubeArrayNormal = new ArrayBufferObject <Vertex3f>(BufferObjectHint.StaticCpuDraw); _CubeArrayNormal.Create(ArrayNormals); } if (_CubeArrays == null) { _CubeArrays = new VertexArrayObject(); _CubeArrays.SetArray(_CubeArrayPosition, VertexArraySemantic.Position); _CubeArrays.SetArray(_CubeArrayColor, VertexArraySemantic.Color); _CubeArrays.SetArray(_CubeArrayNormal, VertexArraySemantic.Normal); _CubeArrays.SetElementArray(PrimitiveType.Triangles); } cubeGeometry.VertexArray = _CubeArrays; #endregion #region Program cubeGeometry.BoundingVolume = new BoundingBox(-Vertex3f.One * _CubeSize, Vertex3f.One * _CubeSize); #endregion return(cubeGeometry); }
public static void AddFaceToVao(WorldServer world, Vector3i blockPos, int x, int y, int z, Block block, BlockFace face, BlockModel.FaceData data, VertexArrayObject vao, Matrix4 transform) { var faceId = (int)face - 1; var indicesOffset = vao.VertexCount; //var transform = Matrix4.CreateScale()//Matrix4.Identity;//block.GetTransform(world, blockPos, face); var texture = data.LoadedTexture; //block.GetTexture(world, blockPos, face); //var overlayTexture = block.GetOverlayTexture(world, blockPos, face); var texCoords = data.GetTexCoords(); //block.GetTexCoords(world, blockPos, face) ?? FaceTexCoords; //var overlayTexCoords = block.GetOverlayTexCoords(world, blockPos, face) ?? FaceTexCoords; var color = data.TintIndex == -1 ? new Vector4(1) : block.GetTintColor(world, blockPos, data.TintIndex).ToVector4(); var normal = face.GetNormal(); if (texCoords.Length != 4) { throw new Exception($"\"{block}\" invalid texture coords array length!"); } var vPositions = new Vector3[4]; var vTexCoords = new Vector4[4]; var vOverlayTexCoords = new Vector4[4]; //TODO: Remove var vBrightness = new Vector3[4]; for (var j = 0; j < 4; j++) { var vertexPosition = FacePositions[faceId * 4 + j]; var position = (new Vector4(vertexPosition, 1) * transform).Xyz + new Vector3(x, y, z); //tex coords are -1 if texture is null var texCoord = texture == null ? new Vector4(-1) : new Vector4(texCoords[j]) { //texCoord z = texId, w = textureArrayId Z = texture.TextureId, W = texture.ArrayId }; //per vertex light value interpolation (smooth lighting + free ambient occlusion) var brightness = CalculateBrightness(world, block, blockPos, face, vertexPosition); //TODO: transform normals vPositions[j] = position; vTexCoords[j] = texCoord; vOverlayTexCoords[j] = new Vector4(-1); vBrightness[j] = brightness; } //Flip faces to fix ambient occlusion anisotrophy //https://0fps.net/2013/07/03/ambient-occlusion-for-minecraft-like-worlds/ for (var j = 0; j < 4; j++) { vao.Add(vPositions[j], vTexCoords[j], new Vector4(normal), color.Xyz, vBrightness[j]); } var newIndices = new uint[FaceIndices.Length]; if ((vBrightness[0] + vBrightness[3]).LengthSquared > (vBrightness[1] + vBrightness[2]).LengthSquared) { for (var j = 0; j < newIndices.Length; j++) { newIndices[j] = (uint)(FlippedFaceIndices[j] + indicesOffset); } } else { for (var j = 0; j < newIndices.Length; j++) { newIndices[j] = (uint)(FaceIndices[j] + indicesOffset); } } //Calculate face middle for transparency sorting var faceMiddle = Vector3.Zero; if (vao is SortedVertexArrayObject) { faceMiddle = vPositions.Aggregate(faceMiddle, (current, pos) => current + pos); faceMiddle = faceMiddle / vPositions.Length + blockPos.ToVector3() - new Vector3(x, y, z); } vao.AddFace(newIndices, faceMiddle); }
protected override async Task LoadContent() { await base.LoadContent(); var vertices = new Vertex[4]; vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) }; vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) }; vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) }; vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) }; var indices = new short[] { 0, 1, 2, 0, 2, 3 }; var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default); var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default); var meshDraw = new MeshDraw { DrawCount = 4, PrimitiveType = PrimitiveType.TriangleList, VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position <Vector3>(), VertexElement.TextureCoordinate <Vector2>()), 4) }, IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length), }; var mesh = new Mesh { Draw = meshDraw, }; simpleEffect = new Effect(GraphicsDevice, SpriteEffect.Bytecode); parameterCollection = new ParameterCollection(); parameterCollectionGroup = new EffectParameterCollectionGroup(GraphicsDevice, simpleEffect, new[] { parameterCollection }); parameterCollection.Set(TexturingKeys.Texture0, UVTexture); vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers); myDraws = new DrawOptions[3]; myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) }; myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) }; myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) }; //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple }; //var border = SamplerState.New(GraphicsDevice, borderDescription); //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) }; }
public Geometry(VertexArrayObject vertexArray) : base(vertexArray) { }
internal Cube(BaseRenderer renderer) { this.renderer = renderer; LibRenderVertex[] vertexData = { // back new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = Color128.White }, // right new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.Down, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.Null, Color = Color128.White }, // top new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, 1.0f), UV = Vector2f.Right, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.One, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Down, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = Color128.White }, // front new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.Down, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Null, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, 1.0f, -1.0f), UV = Vector2f.Right, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.One, Color = Color128.White }, // left new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.One, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, 1.0f), UV = Vector2f.Null, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, 1.0f, -1.0f), UV = Vector2f.Right, Color = Color128.White }, // bottom new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, -1.0f), UV = Vector2f.Null, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, -1.0f), UV = Vector2f.Right, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(1.0f, -1.0f, 1.0f), UV = Vector2f.One, Color = Color128.White }, new LibRenderVertex { Position = new Vector3f(-1.0f, -1.0f, 1.0f), UV = Vector2f.Down, Color = Color128.White } }; if (renderer.currentOptions.IsUseNewRenderer) { defaultVAO = new VertexArrayObject(); defaultVAO.Bind(); defaultVAO.SetVBO(new VertexBufferObject(vertexData, BufferUsageHint.StaticDraw)); defaultVAO.SetIBO(new IndexBufferObject(Enumerable.Range(0, vertexData.Length).Select(x => (ushort)x).ToArray(), BufferUsageHint.StaticDraw)); defaultVAO.UnBind(); } }
/// <summary> /// Construct an Geometry. /// </summary> /// <param name="vertexArray"> /// /// </param> /// <param name="state"></param> /// <param name="program"></param> public Geometry(VertexArrayObject vertexArray, State.GraphicsStateSet state, ShaderProgram program) : base(vertexArray, state, program) { }
protected override void DoRender(RenderEventArgs e) { ShaderProgram program = this.shaderProgram; // 绑定shader program.Bind(); program.SetUniformMatrix4(strprojectionMatrix, projectionMatrix.to_array()); program.SetUniformMatrix4(strviewMatrix, viewMatrix.to_array()); program.SetUniformMatrix4(strmodelMatrix, modelMatrix.to_array()); int[] originalPolygonMode = new int[1]; GL.GetInteger(GetTarget.PolygonMode, originalPolygonMode); GL.PolygonMode(PolygonModeFaces.FrontAndBack, this.polygonMode); if (this.vertexArrayObject == null) { var vertexArrayObject = new VertexArrayObject( this.positionBufferRenderer, this.colorBufferRenderer, this.normalBufferRenderer, this.indexBufferRenderer); vertexArrayObject.Create(e, this.shaderProgram); this.vertexArrayObject = vertexArrayObject; } else { this.vertexArrayObject.Render(e, this.shaderProgram); } GL.PolygonMode(PolygonModeFaces.FrontAndBack, (PolygonModes)(originalPolygonMode[0])); // 解绑shader program.Unbind(); }
public void AddGeometry(VertexArrayObject vertexArray) { _GeometryInstances.Add(new Geometry(vertexArray)); }
public void AddGeometry(VertexArrayObject vertexArray, State.GraphicsStateSet state) { _GeometryInstances.Add(new Geometry(vertexArray, state, null)); }
void initScene(){ heolBones[5] = 10f; pawnBones [2] = 0.299f; pawnBones [5] = 0.90812f; int nbHeol = 5; terrain = new Terrain (ClientRectangle.Size); terrain.gridShader.ShadowMap = shadowMap; vaoDeformables = new VertexArrayObject<WeightedMeshData, WeightedInstancedData> (); vaoObjects = new VertexArrayObject<MeshData, InstancedData> (); car = (VAOItem<InstancedData>)vaoObjects.Add (OBJMeshLoader.Load ("Meshes/car.obj")); car.DiffuseTexture = Tetra.Texture.Load ("Meshes/0000.png"); car.InstancedDatas = new InstancedData[nbHeol]; for (int i = 0; i < nbHeol; i++) { Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); car.InstancedDatas[i].modelMats = Matrix4.CreateScale(0.2f) * Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0.1f); } car.UpdateInstancesData(); nbHeol = 50; // trees = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/trees/treesTrunk.obj")); // treesLeave = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/trees/treesLeaves.obj")); // trees.DiffuseTexture = Tetra.Texture.Load ("Meshes/trees/treeTrunk.jpg"); // treesLeave.DiffuseTexture = Tetra.Texture.Load ("Meshes/trees/treeLeaves.png"); // trees.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // treesLeave.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // float angle = (float)(rnd.NextDouble() * Math.PI); // trees.InstancedDatas[i].modelMats = Matrix4.CreateRotationZ(angle) * Matrix4.CreateScale(4f) * Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // treesLeave.InstancedDatas [i].modelMats = trees.InstancedDatas [i].modelMats; // } // trees.UpdateInstancesData(); // // treesLeave.UpdateInstancesData(); //HEOLIENNES nbHeol = 5; // heoliennes = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/heolienne.obj")); // heoliennes.DiffuseTexture = Tetra.Texture.Load ("Meshes/heolienne.png"); // heoliennes.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // heoliennes.InstancedDatas[i].modelMats = Matrix4.CreateScale(0.1f) * Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // heoliennes.InstancedDatas [i].quat0 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat1 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat2 = Quaternion.Identity; // heoliennes.InstancedDatas [i].quat3 = Quaternion.Identity; //// heoliennes.InstancedDatas [i].bpos0 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos1 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos2 = new Vector4 (0f, 0f, 0f, 0f); //// heoliennes.InstancedDatas [i].bpos3 = new Vector4 (0f, 0f, 0f, 0f); // } // heoliennes.UpdateInstancesData(); nbHeol = 5; heollow = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/heolienne_lod0.obj")); heollow.DiffuseTexture = Tetra.Texture.Load ("Meshes/heollow.png"); heollow.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; for (int i = 0; i < nbHeol; i++) { Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); heollow.InstancedDatas[i].modelMats = Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); heollow.InstancedDatas [i].quat0 = Quaternion.Identity; heollow.InstancedDatas [i].quat1 = Quaternion.Identity; heollow.InstancedDatas [i].quat2 = Quaternion.Identity; heollow.InstancedDatas [i].quat3 = Quaternion.Identity; // heollow.InstancedDatas [i].bpos0 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos1 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos2 = new Vector4 (0f, 0f, 0f, 0f); // heollow.InstancedDatas [i].bpos3 = new Vector4 (0f, 0f, 0f, 0f); } heollow.UpdateInstancesData(); // pawn = (VAOItem<WeightedInstancedData>)vaoDeformables.Add (OBJMeshLoader.Load ("Meshes/pawn.obj")); // pawn.DiffuseTexture = Tetra.Texture.Load ("Meshes/pawn.png"); // pawn.InstancedDatas = new Tetra.WeightedInstancedData[nbHeol]; // for (int i = 0; i < nbHeol; i++) { // Vector2 pos = new Vector2 ((float)rnd.Next(0,terrain.GridSize), (float)rnd.Next(0,terrain.GridSize)); // pawn.InstancedDatas[i].modelMats = Matrix4.CreateTranslation (pos.X-(pos.X % 4f) + 0.5f, pos.Y-(pos.Y % 4f) + 0.5f, 0f); // pawn.InstancedDatas [i].quat0 = Quaternion.Identity; // pawn.InstancedDatas [i].quat1 = Quaternion.Identity; // pawn.InstancedDatas [i].quat2 = Quaternion.Identity; // pawn.InstancedDatas [i].quat3 = Quaternion.Identity; // } // pawn.UpdateInstancesData(); //landItemsVao.ComputeTangents(); vaoDeformables.BuildBuffers (); vaoObjects.BuildBuffers (); // const float treezone = 32; // const int treeCount = 50; // transparentItemsVao = new VertexArrayObject<MeshData, VAOInstancedData> (); // // //====TREE1==== // // vaoi = transparentItemsVao.Add (Tetra.OBJMeshLoader.Load ("#Ottd3D.images.trees.obj__pinet1.obj")); // // vaoi.DiffuseTexture = Tetra.Texture.Load("#Ottd3D.images.trees.pinet1.png"); // // vaoi.modelMats = new Matrix4[treeCount]; // // for (int i = 0; i < treeCount; i++) { // // Vector2 pos = new Vector2 ((float)rnd.NextDouble() * treezone, (float)rnd.NextDouble() * treezone); // // float scale = (float)rnd.NextDouble () * 0.002f + 0.004f; // // vaoi.modelMats[i] =treeRot * Matrix4.CreateScale (scale)* Matrix4.CreateTranslation(pos.X, pos.Y, 0f); // // } // // vaoi.UpdateInstancesData (); // // //====TREE2==== // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.simple.obj", // // "#Ottd3D.images.trees.birch_tree_small_20131230_2041956203.png",400f); // // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__pinet1.obj", // // "#Ottd3D.images.trees.pinet1.png",5f); // addRandomTrees (transparentItemsVao, treeCount, // "images/trees/obj__pinet2.obj", // "images/trees/pinet2.png",3f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree1.obj", // // "#Ottd3D.images.trees.tree1.png",5f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree2.obj", // // "#Ottd3D.images.trees.tree2.png", 5f); // // addRandomTrees (transparentItemsVao, treeCount, // // "#Ottd3D.images.trees.obj__tree3.obj", // // "#Ottd3D.images.trees.tree3.png", 5f); // // //transparentItemsVao.ComputeTangents (); // transparentItemsVao.BuildBuffers (); }
protected override async Task LoadContent() { await base.LoadContent(); var vertices = new Vertex[4]; vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) }; vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) }; vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) }; vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) }; var indices = new short[] { 0, 1, 2, 0, 2, 3 }; var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default); var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default); var meshDraw = new MeshDraw { DrawCount = 4, PrimitiveType = PrimitiveType.TriangleList, VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position<Vector3>(), VertexElement.TextureCoordinate<Vector2>()), 4) }, IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length), }; var mesh = new Mesh { Draw = meshDraw, }; simpleEffect = new Effect(GraphicsDevice, SpriteEffect.Bytecode); parameterCollection = new ParameterCollection(); parameterCollectionGroup = new EffectParameterCollectionGroup(GraphicsDevice, simpleEffect, new[] { parameterCollection }); parameterCollection.Set(TexturingKeys.Texture0, UVTexture); vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers); myDraws = new DrawOptions[3]; myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) }; myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) }; myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) }; //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple }; //var border = SamplerState.New(GraphicsDevice, borderDescription); //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) }; }
void addRandomTrees(VertexArrayObject<MeshData, InstancedData> vao, int count, string objPath, string diffTexPath, float _scale=1f) { VAOItem<InstancedData> vaoi = (VAOItem<InstancedData>)vao.Add (OBJMeshLoader.Load (objPath)); vaoi.DiffuseTexture = Tetra.Texture.Load(diffTexPath); vaoi.InstancedDatas = new Tetra.InstancedData[count]; for (int i = 0; i < count; i++) { Vector2 pos = new Vector2 ((float)rnd.NextDouble() * terrain.GridSize, (float)rnd.NextDouble() * terrain.GridSize); float scale = (float)(rnd.NextDouble () * 0.002f + 0.004f)*_scale; vaoi.InstancedDatas[i].modelMats =Matrix4.CreateRotationX (MathHelper.PiOver2) * Matrix4.CreateScale (scale)* Matrix4.CreateTranslation(pos.X, pos.Y, 0f); } vaoi.UpdateInstancesData (); }
protected override void DoRender(RenderEventArgs e) { // 绑定shader this.shaderProgram.Bind(); this.shaderProgram.SetUniformMatrix4(strprojectionMatrix, projectionMatrix.to_array()); this.shaderProgram.SetUniformMatrix4(strviewMatrix, viewMatrix.to_array()); this.shaderProgram.SetUniformMatrix4(strmodelMatrix, modelMatrix.to_array()); this.shaderProgram.SetUniform(strlightPosition, this.lightPosition.x, this.lightPosition.y, this.lightPosition.z); this.shaderProgram.SetUniform(strSurfaceColor, this.surfaceColor.x, this.surfaceColor.y, this.surfaceColor.z); this.shaderProgram.SetUniform(strWarmColor, this.warmColor.x, this.warmColor.y, this.warmColor.z); this.shaderProgram.SetUniform(strCoolColor, this.coolColor.x, this.coolColor.y, this.coolColor.z); this.shaderProgram.SetUniform(strDiffuseWarm, this.diffuseWarm); this.shaderProgram.SetUniform(strDiffuseCool, this.diffuseCool); int[] originalPolygonMode = new int[1]; GL.GetInteger(GetTarget.PolygonMode, originalPolygonMode); GL.Enable(GL.GL_PRIMITIVE_RESTART); GL.PrimitiveRestartIndex(uint.MaxValue); GL.PolygonMode(PolygonModeFaces.FrontAndBack, this.polygonMode); if (this.vertexArrayObject == null) { var vao = new VertexArrayObject( this.positionBufferRenderer, //colorBufferRenderer, this.normalBufferRenderer, this.indexBufferRenderer); vao.Create(e, this.shaderProgram); this.vertexArrayObject = vao; } else { this.vertexArrayObject.Render(e, this.shaderProgram); } GL.PolygonMode(PolygonModeFaces.FrontAndBack, (PolygonModes)(originalPolygonMode[0])); GL.Disable(GL.GL_PRIMITIVE_RESTART); // 解绑shader this.shaderProgram.Unbind(); }
public RenderableMesh(VertexBufferObject <Vertex3V3N> vertexBuffer, VertexBufferObject <uint> elementBuffer, VertexArrayObject vertexArrayObject, int length, ResourceAllocator resourceAllocator) { _resourceAllocator = resourceAllocator; Faces = length; _vertexArrayObject = vertexArrayObject; _elementBuffer = elementBuffer; _vertexBuffer = vertexBuffer; }