Exemple #1
0
		public Form1()
		{
			ClientSize = new Size(640, 480);
			Text = "Ijw.Skeletal.Viewer";
			Visible = true;

			device = GraphicsDevice.Create(this, ClientSize.Width, ClientSize.Height, true, true,
				Surfaces.Color | Surfaces.Depth);

			shader = new Shader(device, File.OpenRead("../../../res/shader.fx"));
			wireframe = new Shader(device, File.OpenRead("../../../res/wire.fx"));
			points = new Shader(device, File.OpenRead("../../../res/point.fx"));

			meshes = new Cache<string,CoreMesh>(
				x => new CoreMesh("../../../res/" + x + ".xmf", coreSkeleton ));

			animations = new Cache<string, CoreAnimation>(
				x => new CoreAnimation("../../../res/" + x + ".xaf", coreSkeleton));

			vertices = new FvfVertexBuffer<Vertex>(device, 1024,
				VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture);

			haxVerts = new FvfVertexBuffer<Vector3>(device, 1024,
				VertexFormat.Position);

			indices = new IndexBuffer(device, 1024);

			textures = new Cache<string, Texture>(
				x => Texture.Create(File.OpenRead("../../../res/" + x), device));

			skeleton = new Skeleton(coreSkeleton);

			mixer.Play(animations["walk"]).Looping().WithWeight(0.3f);
			mixer.Play(animations["aim"]).Looping();
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="drawer">パーティクルを描画するためのシェーダー</param>
		/// <param name="device"></param>
		/// <param name="tex">パーティクルのテクスチャ</param>
		/// <param name="number">パーティクル最大数</param>
		public ParticleEngine(Effect drawer, GraphicsDevice device, Texture2D tex, ushort number,
			ParticleMode mode, Matrix projection, Vector2 fieldSize)
			:base(tex, number)
		{
			Device = device;
			
			//int[] x = { -1, -1, 1, 1 };
			//int[] y = { 1, -1, -1, 1 };
			
			VertexDataBuffer = new DynamicVertexBuffer(device, typeof(ParticleVertex), ParticleNum * 1, BufferUsage.WriteOnly);

		
			IndexVertexBuffer = new VertexBuffer(device, typeof(ParticleIndexVertex), indexVertex.Length, BufferUsage.WriteOnly);
			IndexVertexBuffer.SetData(indexVertex);

			short[] index = new short[] { 0, 1, 2, 0, 2, 3 };
			Index = new IndexBuffer(device, IndexElementSize.SixteenBits, index.Length, BufferUsage.WriteOnly);
			Index.SetData(index);
			
			Drawer = drawer;
			InitEffectParam();
			Mode = mode;
			Projection = projection;
			FieldSize = fieldSize;
			BlendColor = Vector4.One;
			Enable = true;

			SetVertex();//初期化
			bind = new VertexBufferBinding(VertexDataBuffer, 0, 1);
		}
Exemple #3
0
 protected virtual void InitBuffers(GraphicsDevice graphics)
 {
     _vertexBuffer = new VertexBuffer(graphics, VertexPositionColorNormal.VertexDeclaration, _vertices.Length, BufferUsage.None);
     _vertexBuffer.SetData<VertexPositionColorNormal>(_vertices);
     _indexBuffer = new IndexBuffer(graphics, IndexElementSize.ThirtyTwoBits, _indices.Length, BufferUsage.None);
     _indexBuffer.SetData<int>(_indices);
 }
        public static void CreateIndices(GraphicsDevice graphicsDevice, int patchWidth, int patchHeight)
        {
            IndexCount = (patchWidth - 1) * (patchHeight - 1) * 6;

              indexData = new short[IndexCount];

              for (int y = 0; y < patchHeight - 1; y++)
            for (int x = 0; x < patchWidth - 1; x++)
            {
              int i = (y * (patchWidth - 1) + x) * 6;

              // lower left triangle
              indexData[i + 0] = (short)((y + 1) * patchWidth + (x + 0));  // top left vertex
              indexData[i + 1] = (short)((y + 1) * patchWidth + (x + 1));  // top right vertex
              indexData[i + 2] = (short)((y + 0) * patchWidth + (x + 0));  // lower left vertex

              // top right triangle
              indexData[i + 3] = (short)((y + 1) * patchWidth + (x + 1));  // top right vertex
              indexData[i + 4] = (short)((y + 0) * patchWidth + (x + 1));  // lower right vertex
              indexData[i + 5] = (short)((y + 0) * patchWidth + (x + 0));  // lower left vertex
            }

              Indices = new IndexBuffer(graphicsDevice, typeof(short), IndexCount, BufferUsage.WriteOnly);
              Indices.SetData<short>(indexData);
        }
        public void Render( ViewRenderArguments args )
        {
            if ( Indicies.Count == 0 ) return;

            var device = args.Device;

            if ( VB==null || VB.Description.SizeInBytes < Vertex.Size * Verticies.Count ) {
                using ( VB ) {}
                using ( IB ) {}
                VB = new VertexBuffer( device, Vertex.Size * Verticies.Count, Usage.None, Vertex.FVF, Pool.Managed );
                IB = new IndexBuffer(  device, sizeof(uint)* Indicies .Count, Usage.None, Pool.Managed, false );
            }

            var vb = VB.Lock(0,0,LockFlags.None);
            vb.WriteRange(Verticies.ToArray());
            VB.Unlock();

            var ib = IB.Lock(0,0,LockFlags.None);
            ib.WriteRange(Indicies.ToArray());
            IB.Unlock();

            device.SetTexture(0,null);
            device.Indices = IB;
            device.VertexFormat = Vertex.FVF;
            device.SetStreamSource(0,VB,0,Vertex.Size);
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList,0,0,Verticies.Count,0,Verticies.Count/2);

            Indicies.Clear();
            Verticies.Clear();
        }
 public IRenderRequest CreateInstancedRequest(IRenderContext renderContext, RasterizerState rasterizerState,
     BlendState blendState, DepthStencilState depthStencilState, IEffect effect, IEffectParameterSet effectParameterSet,
     VertexBuffer meshVertexBuffer, IndexBuffer meshIndexBuffer, PrimitiveType primitiveType,
     Matrix[] instanceWorldTransforms, Action<List<Matrix>, VertexBuffer, IndexBuffer> computeCombinedBuffers)
 {
     throw new NotImplementedException();
 }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this._vertexBuffer != null)
                {
                    if (this._vertexBuffer.IsDisposed == false)
                    {
                        this._vertexBuffer.Dispose();
                        this._vertexBuffer = null;

                    }

                    if (this._indexBuffer != null)
                    {
                        if (this._indexBuffer.IsDisposed == false)
                        {
                            this._indexBuffer.Dispose();
                            this._indexBuffer = null;
                        }
                    }

                    if (this._basicEffect != null)
                    {
                        if (this._basicEffect.IsDisposed == false)
                        {
                            this._basicEffect.Dispose();
                            this._basicEffect = null;
                        }
                    }
                }
            }

            base.Dispose(disposing);
        }
Exemple #8
0
 public void InitializePrimitive(GraphicsDevice graphicsDevice)
 {
     VertexBuffer = new VertexBuffer(graphicsDevice, typeof(Vertex), Vertices.Count, BufferUsage.None);
     VertexBuffer.SetData(Vertices.ToArray());
     IndexBuffer = new IndexBuffer(graphicsDevice, typeof(int), Indices.Count, BufferUsage.None);
     IndexBuffer.SetData(Indices.ToArray());
 }
        public HeightMappedTerrain(Texture2D heightmap, float cellsize, float height, Texture2D basetex, float textile, Vector3 lightdir, GraphicsDevice device, ContentManager content)
        {
            baseTexture = basetex;
            textureTiling = textile;
            lightDirection = lightdir;

            heightMap = heightmap;
            width = heightmap.Width;
            length = heightMap.Height;

            cellSize = cellsize;
            this.height = height;
            GraphicsDevice = device;

            effect = content.Load<Effect>("TerrainEffect");
            nVertices = width * length;
            nIndices = (width - 1) * (length - 1) * 6;

            vertexBuffer = new VertexBuffer(device, typeof(VertexPositionNormalTexture), nVertices, BufferUsage.WriteOnly);
            indexBuffer = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, nIndices, BufferUsage.WriteOnly);

            extractHeightData();
            createVertexData();
            createIndexData();
            createNormalData();

            vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);
            indexBuffer.SetData<int>(indices);
        }
Exemple #10
0
        protected override void LoadContent()
        {
            base.LoadContent();

             effect = new BasicEffect(GraphicsDevice, null);
             effect.VertexColorEnabled = true;
             effect.Projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);

             vertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);

             Color c = Color.Red;

             for (int x = 0; x <= Constants.WIN_X; x += xMax)
             {
            listVertices.Add(new VertexPositionColor(new Vector3(x, Constants.WIN_Y - y, 0), Color.Red));
            listVertices.Add(new VertexPositionColor(new Vector3(x, Constants.WIN_Y, 0), Color.Blue));
             }

             for (int i = 0; i < listVertices.Count - 1; i+=2)
             {
            listIndices.Add((short)(i));
            listIndices.Add((short)(3 + i));
            listIndices.Add((short)(1 + i));
            listIndices.Add((short)(i));
            listIndices.Add((short)(2 + i));
            listIndices.Add((short)(3 + i));
             }

             buffVertex = new VertexBuffer(GraphicsDevice, VertexPositionColor.SizeInBytes * listVertices.Count, BufferUsage.WriteOnly);
             buffVertex.SetData<VertexPositionColor>(listVertices.ToArray());

             buffIndex = new IndexBuffer(GraphicsDevice, typeof(short), listIndices.Count, BufferUsage.WriteOnly);
             buffIndex.SetData<short>(listIndices.ToArray());
        }
        /// <summary>
        /// Performs further custom initialization for this instance.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            VertexPositionColor[] vertices = new VertexPositionColor[3];
            vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
            vertices[0].Color = Color.Red;

            vertices[1].Position = new Vector3(0f, 0.5f, 0f);
            vertices[1].Color = Color.Green;

            vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
            vertices[2].Color = Color.Yellow;

            var vertexBuffer = new VertexBuffer(VertexPositionColor.VertexFormat);
            vertexBuffer.SetData(vertices, 3);
            
            ushort[] indices = new ushort[3];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;

            var indexBuffer = new IndexBuffer(indices);

            this.mesh = new Mesh(0, vertices.Length, 0, 1, vertexBuffer, indexBuffer, PrimitiveType.TriangleList);
        }
        /// <inheritdoc/>
        public override void Attach(IndexBuffer ibuffer)
        {
            Contract.Require(ibuffer, "ibuffer");
            Contract.EnsureNot(HasIndices, UltravioletStrings.GeometryStreamAlreadyHasIndices);
            Contract.EnsureNotDisposed(this, Disposed);

            Ultraviolet.ValidateResource(ibuffer);

            var sdlIndexBuffer = (OpenGLIndexBuffer)ibuffer;
            var sdlIndexBufferName = sdlIndexBuffer.OpenGLName;

            this.ibuffer = sdlIndexBuffer;

            if (IsUsingVertexArrayObject)
            {
                using (OpenGLState.ScopedBindVertexArrayObject(vao, 0, 0, true))
                {
                    gl.BindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, sdlIndexBufferName);
                    gl.ThrowIfError();
                }
            }

            this.glElementArrayBufferBinding = sdlIndexBufferName;
            this.indexBufferElementType      = ibuffer.IndexElementType;
        }
        public void Dispose()
        {
            lock (this)
            {

                if (vbMappedMesh != null)
                {
                    vbMappedMesh.Dispose();
                    vbMappedMesh = null;
                }

                if (vbControlMesh != null)
                {
                    vbControlMesh.Dispose();
                    vbControlMesh = null;
                }

                if (ibMesh != null)
                {
                    ibMesh.Dispose();
                    ibMesh = null;
                }

            }
        }
        public ParticleSystem(GraphicsDevice graphicsDevice, ContentManager content,
            Texture2D tex, int nParticles, Vector2 particleSize, float lifespan,
            Vector3 wind, float FadeInTime)
        {
            this.nParticles = nParticles;
            this.particleSize = particleSize;
            this.lifespan = lifespan;
            this.graphicsDevice = graphicsDevice;
            this.wind = wind;
            this.texture = tex;
            this.fadeInTime = FadeInTime;

            // Create vertex and index buffers to accomodate all particles
            verts = new VertexBuffer(graphicsDevice, typeof(ParticleVertex),
                nParticles * 4, BufferUsage.WriteOnly);

            ints = new IndexBuffer(graphicsDevice, IndexElementSize.ThirtyTwoBits,
                nParticles * 6, BufferUsage.WriteOnly);

            generateParticles();

            effect = content.Load<Effect>("Effects//ParticleEffect");

            start = DateTime.Now;
        }
        protected override void LoadBatchInfo(GraphicFactory factory, out BatchInformation[][] BatchInformations)
        {
            TreeProfile t = factory.GetAsset<TreeProfile>(profileName);
            if (!String.IsNullOrEmpty(LeaftextureName))
            {
                t.LeafTexture = factory.GetAsset<Texture2D>(LeaftextureName);
            }
            if (!String.IsNullOrEmpty(trunktextureName))
            {
                t.TrunkTexture = factory.GetAsset<Texture2D>(trunktextureName);
            }
            tree = t.GenerateSimpleTree(StaticRandom.RandomInstance);

            BatchInformations = new BatchInformation[2][];
            vertexBufferS = new VertexBuffer[2];
            indexBufferS = new IndexBuffer[2];
            indexBufferS[0] = tree.TrunkMesh.IndexBuffer;
            vertexBufferS[0] = tree.TrunkMesh.VertexBuffer;
            BatchInformation bi0 = new BatchInformation(0, tree.TrunkMesh.NumberOfVertices, tree.TrunkMesh.NumberOfTriangles, 0, 0, tree.TrunkMesh.Vdeclaration, TreeVertex.SizeInBytes);
            BatchInformations[0] = new BatchInformation[1];
            BatchInformations[0][0] = bi0;

            indexBufferS[1] = tree.LeafCloud.Ibuffer;
            vertexBufferS[1] = tree.LeafCloud.Vbuffer;
            BatchInformation bi1 = new BatchInformation(0, tree.LeafCloud.Numleaves * 4, tree.LeafCloud.Numleaves * 2, 0, 0, tree.LeafCloud.Vdeclaration, LeafVertex.SizeInBytes);
            BatchInformations[1] = new BatchInformation[1];
            BatchInformations[1][0] = bi1; 
        }
Exemple #16
0
		public Sprite (Stream stream, TextureSettings settings, Vector4 rect, bool relativeRect, Vector4 color, bool flipV = true) {
			var tex = new Texture(stream, settings);
			_material = new SpriteMaterial(new SpriteShader(), tex);
			
			if (rect == Vector4.Zero)
				rect = new Vector4(0, 0, tex.Size.Width, tex.Size.Height);
			else if (relativeRect) {
				rect.X *= tex.Size.Width;
				rect.Y *= tex.Size.Height;
				rect.Z *= tex.Size.Width;
				rect.W *= tex.Size.Height;
			}
			
			_size = new Vector2(rect.Z - rect.X, rect.W - rect.Y);

			_vbuffer = new VertexBuffer(VertexFormat.PositionColorUV);
			_vbuffer.Data = new [] {
				rect.X, rect.Y, 0f, color.X, color.Y, color.Z, color.W, 0f, flipV ? 1f : 0f,
				rect.Z, rect.Y, 0f, color.X, color.Y, color.Z, color.W, 1f, flipV ? 1f : 0f,
				rect.Z, rect.W, 0f, color.X, color.Y, color.Z, color.W, 1f, flipV ? 0f : 1f,
				rect.X, rect.W, 0f, color.X, color.Y, color.Z, color.W, 0f, flipV ? 0f : 1f
			};
			_vbuffer.Commit ();
			
			_ibuffer = new IndexBuffer();
			_ibuffer.Data = new [] { 0, 1, 2, 2, 3, 0 };
			_ibuffer.Commit ();
			
			_ioffset = 0;
			_icount = 6;
			
			_ownResources = true;
		}
Exemple #17
0
 public static void DrawColoredRectangle(Device dev,RectangleF rect,Color color)
 {
     VertexBuffer vb=null;
     IndexBuffer ib=null;
     try{
         int colorArgb=color.ToArgb();
         CustomVertex.PositionColored[] quadVerts=new CustomVertex.PositionColored[] {
                 new CustomVertex.PositionColored(rect.Left,rect.Bottom,0,colorArgb),
                 new CustomVertex.PositionColored(rect.Left,rect.Top,0,colorArgb),
                 new CustomVertex.PositionColored(rect.Right,rect.Top,0,colorArgb),
                 new CustomVertex.PositionColored(rect.Right,rect.Bottom,0,colorArgb),
             };
         vb=new VertexBuffer(typeof(CustomVertex.PositionColored),
             CustomVertex.PositionColored.StrideSize*quadVerts.Length,
             dev,Usage.WriteOnly,CustomVertex.PositionColored.Format,Pool.Managed);
         vb.SetData(quadVerts,0,LockFlags.None);
         int[] indicies=new int[] { 0,1,2,0,2,3 };
         ib=new IndexBuffer(typeof(int),indicies.Length,dev,Usage.None,Pool.Managed);
         ib.SetData(indicies,0,LockFlags.None);
         dev.VertexFormat=CustomVertex.PositionColored.Format;
         dev.SetStreamSource(0,vb,0);
         dev.Indices=ib;
         dev.DrawIndexedPrimitives(PrimitiveType.TriangleList,0,0,quadVerts.Length,0,indicies.Length/3);
     }finally{
         if(vb!=null){
             vb.Dispose();
             vb=null;
         }
         if(ib!=null){
             ib.Dispose();
             ib=null;
         }
     }
 }
Exemple #18
0
        /// <summary>
        /// Tessellate the points into triangles
        /// </summary>
        private void pSetUpIndices()
        {
            Console.WriteLine("Tessellating");
            int xbound = pVertexBuffer.VertexCount / pColHeight;
            int[] indices = new int[((pColHeight - 1) * (xbound - 1)) * 6];

            //Arranges the vertices into squares composed of two triangles.
            int count = 0;
            for (int x = 0; x < (pVertexBuffer.VertexCount - pColHeight); x = x + 1)
            {
                if (((x + 1) % pColHeight) != 0)
                {
                    indices[count] = x;
                    indices[count + 1] = x + pColHeight + 1;
                    indices[count + 2] = x + pColHeight;
                    indices[count + 3] = x;
                    indices[count + 4] = x + 1;
                    indices[count + 5] = x + pColHeight + 1;
                    count += 6;
                }
            }

            pIndexBuffer = new IndexBuffer(pDevice, typeof(int), indices.Length, BufferUsage.WriteOnly);
            pIndexBuffer.SetData(indices);
        }
        public static Model FromScene(Scene scene, Device device)
        {
            VertexDeclaration vertexDeclaration = new VertexDeclaration(device,
                VertexPositionNormalTexture.VertexElements);
            Model result = new Model(scene, device, vertexDeclaration);
            foreach (Mesh mesh in scene.Meshes)
            {
                VertexBuffer vertexBuffer = new VertexBuffer(device,
                    mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes,
                    Usage.WriteOnly, VertexFormat.None, Pool.Default);
                DataStream vertexDataStream = vertexBuffer.Lock(0,
                    mesh.Positions.Count * VertexPositionNormalTexture.SizeInBytes,
                    LockFlags.None);
                VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[mesh.Positions.Count];
                for (int i = 0; i < vertices.Length; ++i)
                    vertices[i] = new VertexPositionNormalTexture(mesh.Positions[i], (mesh.Normals.Count > i) ? mesh.Normals[i] : Vector3D.Zero, Point2D.Zero);
                vertexDataStream.WriteRange(vertices);
                vertexBuffer.Unlock();

                IndexBuffer indexBuffer = new IndexBuffer(device, mesh.Indices.Count * sizeof(int),
                    Usage.WriteOnly, Pool.Default, false);
                DataStream indexDataStream = indexBuffer.Lock(0, mesh.Indices.Count * sizeof(int), LockFlags.None);
                indexDataStream.WriteRange(mesh.Indices.ToArray());
                indexBuffer.Unlock();

                ModelMesh modelMesh = new ModelMesh(mesh, device, vertexBuffer,
                    mesh.Positions.Count, indexBuffer, mesh.PrimitiveCount,
                    Matrix3D.Identity, mesh.Material);
                result.Meshes.Add(modelMesh);
            }
            return result;
        }
Exemple #20
0
        public void Resolve(bool injectHardEdges)
        {
            _vertices = new List<VertexPositionNormalTexture>();
            //ushort indIdx = 0;

            List<UInt16> indices = new List<UInt16>(_vertexPositions.Count);

            foreach (CModel model in _models)
            {
                model.HardEdgesInserted = injectHardEdges;
                model.IndexBufferStart = indices.Count;
                model.Polygons.Sort(delegate(Polygon p1, Polygon p2) { return p1.MaterialIndex.CompareTo(p2.MaterialIndex); });

                model.Resolve(indices, _vertices, _vertexTextureMap, _vertexPositions);
            }

            if (_vertices.Count > 0)
            {
                _vertexBuffer = new VertexBuffer(Engine.Device, VertexPositionNormalTexture.SizeInBytes * _vertices.Count, BufferUsage.WriteOnly);
                _vertexBuffer.SetData<VertexPositionNormalTexture>(_vertices.ToArray());

                if (!injectHardEdges)
                {
                    _indexBuffer = new IndexBuffer(Engine.Device, typeof(UInt16), indices.Count, BufferUsage.WriteOnly);
                    _indexBuffer.SetData<UInt16>(indices.ToArray());
                    _indices = indices;
                }
            }

            _vertexDeclaration = new VertexDeclaration(Engine.Device, VertexPositionNormalTexture.VertexElements);
            _vertexTextureMap = null; //dont need this data anymore
        }
    public Sphere(float Radius, GraphicsDevice graphics, Texture2D tex, Texture2D prograde, Texture2D retrograde,
        Texture2D maneuverPrograde, Texture2D targetPrograde, Texture2D targetRetrograde)
    {
        this.prograde = new Bilboard (prograde, Matrix.CreateScale (1.0f));
        this.retrograde = new Bilboard (retrograde, Matrix.CreateScale (1.0f));
        this.maneuverPrograde = new Bilboard (maneuverPrograde, Matrix.CreateScale (1.0f));
        this.targetPrograde = new Bilboard (targetPrograde, Matrix.CreateScale (1.0f));
        this.targetRetrograde = new Bilboard (targetRetrograde, Matrix.CreateScale (1.0f));

        texture = tex;
        radius = Radius;
        graphicd = graphics;
        effect = new BasicEffect(graphicd);

        nvertices = res * res; // 90 vertices in a circle, 90 circles in a sphere
        nindices = res * res * 6;
        vbuffer = new VertexBuffer(graphics, typeof(VertexPositionNormalTexture), nvertices, BufferUsage.WriteOnly);
        ibuffer = new IndexBuffer(graphics, IndexElementSize.SixteenBits, nindices, BufferUsage.WriteOnly);
        createspherevertices();
        createindices();
        vbuffer.SetData<VertexPositionNormalTexture>(vertices);
        ibuffer.SetData<short>(indices);
        effect.TextureEnabled = true;
        effect.LightingEnabled = true;

        rotQuat = Quaternion.Identity;
    }
Exemple #22
0
        public Doom3Map(Doom3MapData map)
        {
            Surfaces=new List<Surface>();
            int verts = 0;
            int indices = 0;
            foreach(Doom3MapData.Model m in map.Models)
            {
                foreach(Doom3MapData.Surface s in m.Surfaces)
                {
                    VertexBuffer vb = Root.Instance.UserInterface.Renderer.CreateStaticVertexBuffer(
                        s.Vertices,
                        s.Vertices.Length*4*(3+2+3)
                        );
                    vb.Format = VertexFormat.VF_P3T2N3;

                    IndexBuffer ib = new IndexBuffer();
                    ib.buffer = new int[s.Indices.Length];
                    for (int i = 0; i < ib.buffer.Length; ++i)
                        ib.buffer[i] = s.Indices[i];

                    Surface s2 = new Surface();
                    s2.Ibuffer = ib;
                    s2.Vbuffer = vb;
                    verts += s.Vertices.Length;
                    indices += s.Indices.Length;
                    Texture t=null;
                    try
                    {
                        t = Root.Instance.ResourceManager.LoadTexture(s.Name + ".tga");
                    }
                    catch (Exception)
                    {
                        try
                        {
                            t = Root.Instance.ResourceManager.LoadTexture(s.Name + "_add.tga");
                        }
                        catch (Exception)
                        {
                            try
                            {
                                t = Root.Instance.ResourceManager.LoadTexture(s.Name + "_d.tga");
                            }
                            catch (Exception )
                            {
                                System.Console.WriteLine("warning: cant load "+s.Name);
                            }
                        }
                    }
                    s2.Material=Material.CreateSimpleMaterial(t);
                    //s2.Material.Additive = true;
                    Surfaces.Add(s2);
                }
            }
            System.Console.WriteLine("surfaces: "+Surfaces.Count.ToString());
            System.Console.WriteLine("verts: " + verts.ToString());
            System.Console.WriteLine("indices: " + indices.ToString());

            GC.Collect();
            BBox = new BoundingBox(map.BBoxMin, map.BBoxMax);
        }
Exemple #23
0
        public TextureStrip(GraphicsDevice device,Texture2D tex)
        {
            worldMatrix = Matrix.Identity;
            Indices = new int[4];
            effect = new BasicEffect(device);
            float aspectRatio = (float)device.Viewport.Width /
            device.Viewport.Height;
            CamX = 0.0f;
            CamY = 2.0f;
            CamZ = 2.0f;
            effect.View = Matrix.CreateLookAt(new Vector3(CamX, CamY, CamZ),Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10.0f);
            effect.VertexColorEnabled = false;
            textura = tex;
            effect.Texture = this.textura;
            effect.TextureEnabled = true;

            CreateVertices();

            Indices[0]=0;
            Indices[1]=1;
            Indices[2]=2;
            Indices[3]=3;

            effect.LightingEnabled = true;
            effect.DirectionalLight0.DiffuseColor = new Vector3(1, 1, 1);
            effect.DirectionalLight0.Direction = new Vector3(0, -1, 0);
            effect.DirectionalLight0.SpecularColor = new Vector3(0, 0, 0);

            vertexBuffer1 = new VertexBuffer(device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.None);
            vertexBuffer1.SetData<VertexPositionNormalTexture>(vertices);

            indexBuffer1 = new IndexBuffer(device, typeof(int), Indices.Length, BufferUsage.None);
            indexBuffer1.SetData<int>(Indices);
        }
Exemple #24
0
        public IndexBuffer GetIndexBuffer()
        {
            if (this.indexBuffer == null)
            {
                int length = this.SideLength * (this.SideLength - 1) * 2;
                OneIndexBuffer buffer = Buffer.Create(IndexBufferElementType.UInt, length, DrawMode.TriangleStrip, BufferUsage.StaticDraw);
                unsafe
                {
                    IntPtr pointer = buffer.MapBuffer(MapBufferAccess.WriteOnly);
                    var array = (uint*)pointer;
                    for (int k = 0; k < this.SideLength - 1; k++)
                    {
                        for (int i = 0; i < this.SideLength; i++)
                        {
                            if (k % 2 == 0)
                            {
                                array[(i + k * this.SideLength) * 2 + 0] = (uint)(i + (k + 1) * this.SideLength);
                                array[(i + k * this.SideLength) * 2 + 1] = (uint)(i + (k + 0) * this.SideLength);
                            }
                            else
                            {
                                array[(i + k * this.SideLength) * 2 + 0] = (uint)(this.SideLength - 1 - i + (k + 0) * this.SideLength);
                                array[(i + k * this.SideLength) * 2 + 1] = (uint)(this.SideLength - 1 - i + (k + 1) * this.SideLength);
                            }
                        }
                    }
                    buffer.UnmapBuffer();
                }
                this.indexBuffer = buffer;
            }

            return this.indexBuffer;
        }
Exemple #25
0
        public Terrain(Texture2D heightMap,
            Effect effect,
            float cellSize,
            int maxHeight,
            GraphicsDevice device)
        {
            this.HeightMap = heightMap;
            this.Width = heightMap.Width;
            this.Height = maxHeight;
            this.Length = heightMap.Height;
            this.CellSize = cellSize;

            this.Device = device;
            this.Effect = effect;

            this.VerticesCount = Width * Length;
            this.IndexCount = (Width - 1) * (Length - 1) * 6;

            this.VertexBuffer = new VertexBuffer(device,
                typeof(VertexPositionNormalTexture), VerticesCount,
                BufferUsage.WriteOnly);

            this.IndexBuffer = new IndexBuffer(device,
                IndexElementSize.ThirtyTwoBits,
                IndexCount, BufferUsage.WriteOnly);

            ComputeHeights();
            CreateVertices();
            CreateIndices();
            ComputeNormals();

            this.VertexBuffer.SetData<VertexPositionNormalTexture>(Vertices);
            this.IndexBuffer.SetData<int>(Indexes);
        }
Exemple #26
0
			public void Reload()
			{
				Ovr.DistortionMesh meshData = this.main.VRHmd.CreateDistortionMesh(this.eye, this.fov, this.main.VRHmd.GetDesc().DistortionCaps).Value;
				Point textureSize = this.main.ScreenSize;
				Ovr.Vector2f[] scaleAndOffset = this.main.VRHmd.GetRenderScaleAndOffset(this.fov, new Ovr.Sizei(textureSize.X, textureSize.Y), new Ovr.Recti { Size = { w = textureSize.X, h = textureSize.Y } });
				this.uvScale = new Vector2(scaleAndOffset[0].x, scaleAndOffset[0].y);
				this.uvOffset = new Vector2(scaleAndOffset[1].x, scaleAndOffset[1].y);
				Vertex[] vertices = new Vertex[meshData.VertexCount];
				for (int i = 0; i < meshData.VertexCount; i++)
				{
					Ovr.DistortionVertex v = meshData.pVertexData[i];
					vertices[i].ScreenPosNDC = new Vector2(v.ScreenPosNDC.x, v.ScreenPosNDC.y);
					vertices[i].TimeWarpFactor = v.TimeWarpFactor;
					vertices[i].VignetteFactor = v.VignetteFactor;
					vertices[i].TanEyeAnglesR = new Vector2(v.TanEyeAnglesR.x, v.TanEyeAnglesR.y);
					vertices[i].TanEyeAnglesG = new Vector2(v.TanEyeAnglesG.x, v.TanEyeAnglesG.y);
					vertices[i].TanEyeAnglesB = new Vector2(v.TanEyeAnglesB.x, v.TanEyeAnglesB.y);
				}

				this.vb = new VertexBuffer(this.main.GraphicsDevice, typeof(Vertex), (int)meshData.VertexCount, BufferUsage.WriteOnly);
				this.vb.SetData<Vertex>(vertices);

				this.ib = new IndexBuffer(this.main.GraphicsDevice, IndexElementSize.SixteenBits, (int)meshData.IndexCount, BufferUsage.WriteOnly);
				this.ib.SetData<short>(meshData.pIndexData);
			}
        public static void CreateIndexBuffer(Device gDevice, int width, int height, out IndexBuffer iBuffer)
        {
            // create buffer
            iBuffer = new IndexBuffer(typeof(int), (width - 1) * (height - 1) * 6, gDevice, Usage.WriteOnly, Pool.Managed);
            int[] indices = (int[])iBuffer.Lock(0, LockFlags.None);
            
            // fill buffer
            int bufIdx = 0;
            for (int y = 0; y < height - 1; y++)
            {
                for (int x = 0; x < width - 1; x++)
                {
                    // fill quad (2xtri)
                    int pos = (y * width) + x;
                    indices[bufIdx++] = pos;
                    indices[bufIdx++] = pos + width;
                    indices[bufIdx++] = pos + 1;

                    indices[bufIdx++] = pos + 1;
                    indices[bufIdx++] = pos + width;
                    indices[bufIdx++] = pos + 1 + width;
                }
            }
            iBuffer.Unlock();
        }
Exemple #28
0
		public Batcher( GraphicsDevice graphicsDevice )
		{
			Assert.isTrue( graphicsDevice != null );

			this.graphicsDevice = graphicsDevice;

			_vertexInfo = new VertexPositionColorTexture4[MAX_SPRITES];
			_textureInfo = new Texture2D[MAX_SPRITES];
			_vertexBuffer = new DynamicVertexBuffer( graphicsDevice, typeof( VertexPositionColorTexture ), MAX_VERTICES, BufferUsage.WriteOnly );
			_indexBuffer = new IndexBuffer( graphicsDevice, IndexElementSize.SixteenBits, MAX_INDICES, BufferUsage.WriteOnly );
			_indexBuffer.SetData( _indexData );

			_spriteEffect = new SpriteEffect();
			_spriteEffectPass = _spriteEffect.CurrentTechnique.Passes[0];

			_projectionMatrix = new Matrix(
				0f, //(float)( 2.0 / (double)viewport.Width ) is the actual value we will use
				0.0f,
				0.0f,
				0.0f,
				0.0f,
				0f, //(float)( -2.0 / (double)viewport.Height ) is the actual value we will use
				0.0f,
				0.0f,
				0.0f,
				0.0f,
				1.0f,
				0.0f,
				-1.0f,
				1.0f,
				0.0f,
				1.0f
			);
		}
 /// <summary>
 /// Constructor of IndexBufferObject class
 /// </summary>
 /// <param name="device">Graphics device</param>
 /// <param name="type">Type of buffer to use</param>
 /// <param name="buffer">Underlying index buffer</param>
 internal IndexBufferObject(GraphicsDevice device, BufferType type, IndexBuffer buffer)
 {
     _device = device;
     _bufferType = type;
     _elementSize = buffer.IndexElementSize;
     CreateWrapper(buffer);
 }
Exemple #30
0
 public static void Initilize(GraphicsDevice gd)
 {
     ConstructCube();
     vBuffer = new VertexBuffer(gd, VertexPositionNormalTexture.VertexDeclaration, 36, BufferUsage.WriteOnly);
     vBuffer.SetData(verts);
     gd.SetVertexBuffer(vBuffer);
     ib = new IndexBuffer(gd, IndexElementSize.SixteenBits, 14, BufferUsage.WriteOnly);
     ib.SetData(new short[14]
     {
         0,
         1,
         2,
         3,
         4,
         5,
         6,
         7,
         8,
         9,
         10,
         11,
         12,
         13
     });
     gd.Indices = ib;
     wireframeRaster = new RasterizerState();
     wireframeRaster.FillMode = FillMode.WireFrame;
     wireframeRaster.CullMode = CullMode.None;
     wireframeEfect = new BasicEffect(gd);
     wireframeEfect.Projection = Matrix.CreatePerspectiveFieldOfView(0.7853982f,
         wireframeEfect.GraphicsDevice.Viewport.AspectRatio, 0.01f, 3000f);
 }
Exemple #31
0
        /// <summary>
        ///     Vuelve a crear la esfera si hubo cambio en el nivel de detalle, color o coordenadas de textura o si ForceUpdate
        ///     esta en true.
        /// </summary>
        public virtual void updateValues()
        {
            if (!mustUpdate && !ForceUpdate)
            {
                return;
            }

            if (indexBuffer != null && !indexBuffer.Disposed)
            {
                indexBuffer.Dispose();
            }
            if (vertexBuffer != null && !vertexBuffer.Disposed)
            {
                vertexBuffer.Dispose();
            }

            //Obtengo las posiciones de los vertices e indices de la esfera
            List <TGCVector3> positions;

            createSphereSubdividingAPolyhedron(out positions, out indices);

            ///////

            vertices = new List <Vertex.PositionColoredTexturedNormal>();

            var iverticesU1 = new List <int>();

            var polos = new int[2];
            var p     = 0;

            var c = Color.ToArgb();

            var twoPi = FastMath.TWO_PI;

            //Creo la lista de vertices
            for (var i = 0; i < positions.Count; i++)
            {
                var pos = positions[i];
                var u   = 0.5f + FastMath.Atan2(pos.Z, pos.X) / twoPi;
                var v   = 0.5f - 2 * FastMath.Asin(pos.Y) / twoPi;
                vertices.Add(new Vertex.PositionColoredTexturedNormal(pos, c, UVTiling.X * u + UVOffset.X,
                                                                      UVTiling.Y * v + UVOffset.Y, pos));

                if (u == 1 || esPolo(vertices[i]))
                {
                    iverticesU1.Add(i);

                    if (u != 1)
                    {
                        try
                        {
                            polos[p++] = i;
                        }
                        catch (Exception e)
                        {
                            //Arreglar esto... y despues quitar el try catch :(
                            System.Console.WriteLine(e.Message);
                        }
                    }
                }
            }

            //Corrijo los triangulos que tienen mal las coordenadas debido a vertices compartidos
            fixTexcoords(vertices, indices, iverticesU1, polos);

            verticesCount = vertices.Count;
            triangleCount = indices.Count / 3;

            vertexBuffer = new VertexBuffer(typeof(Vertex.PositionColoredTexturedNormal), verticesCount,
                                            D3DDevice.Instance.Device,
                                            Usage.Dynamic | Usage.WriteOnly, Vertex.PositionColoredTexturedNormal.Format, Pool.Default);
            vertexBuffer.SetData(vertices.ToArray(), 0, LockFlags.None);

            indexBuffer = new IndexBuffer(typeof(int), indices.Count, D3DDevice.Instance.Device,
                                          Usage.Dynamic | Usage.WriteOnly,
                                          Pool.Default);
            indexBuffer.SetData(indices.ToArray(), 0, LockFlags.None);

            mustUpdate = false;
        }
Exemple #32
0
        public void GetMesh(byte cubeProfile, out Mesh cubeMesh, out VertexBuffer <VertexMesh> vb, out IndexBuffer <ushort> ib)
        {
            cubeMesh = null;
            vb       = null;
            ib       = null;

            CubePack pack;

            if (!_cache.TryGetValue(cubeProfile, out pack))
            {
                return;
            }

            cubeMesh = pack.Mesh;
            vb       = pack.Vb;
            ib       = pack.Ib;
        }
Exemple #33
0
        IndexBuffer GetIndexBuffer(out int primitiveCount)
        {
            // 16 x 16 squares * 2 triangles per square * 3 indices per triangle
            var indexData = new List <short>(16 * 16 * 2 * 3);

            // For each 8 meter rectangle
            for (var z = 0; z < 16; ++z)
            {
                for (var x = 0; x < 16; ++x)
                {
                    var nw = (short)(z * 17 + x);  // Vertex index in the north west corner
                    var ne = (short)(nw + 1);
                    var sw = (short)(nw + 17);
                    var se = (short)(sw + 1);

                    if ((z & 1) == (x & 1))  // Triangles alternate
                    {
                        if (!IsVertexHidden(x, z) && !IsVertexHidden(x + 1, z + 1) && !IsVertexHidden(x, z + 1))
                        {
                            indexData.Add(nw);
                            indexData.Add(se);
                            indexData.Add(sw);
                        }
                        if (!IsVertexHidden(x, z) && !IsVertexHidden(x + 1, z) && !IsVertexHidden(x + 1, z + 1))
                        {
                            indexData.Add(nw);
                            indexData.Add(ne);
                            indexData.Add(se);
                        }
                    }
                    else
                    {
                        if (!IsVertexHidden(x + 1, z) && !IsVertexHidden(x + 1, z + 1) && !IsVertexHidden(x, z + 1))
                        {
                            indexData.Add(ne);
                            indexData.Add(se);
                            indexData.Add(sw);
                        }
                        if (!IsVertexHidden(x, z) && !IsVertexHidden(x + 1, z) && !IsVertexHidden(x, z + 1))
                        {
                            indexData.Add(nw);
                            indexData.Add(ne);
                            indexData.Add(sw);
                        }
                    }
                }
            }

            primitiveCount = indexData.Count / 3;

            // If this patch has no holes, use the shared IndexBuffer for better performance.
            if (indexData.Count == 16 * 16 * 6)
            {
                return(null);
            }

            var indexBuffer = new IndexBuffer(Viewer.GraphicsDevice, typeof(short), indexData.Count, BufferUsage.WriteOnly);

            indexBuffer.SetData(indexData.ToArray());
            return(indexBuffer);
        }
Exemple #34
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            IsDrawing = true;

            m_objGraphicsDeviceManager.GraphicsDevice.Clear(Color.CornflowerBlue);
            short[] indices = new short[36] {
                0, 1, 2, //face devant
                0, 2, 3,
                3, 2, 4, //face droite
                3, 4, 5,
                5, 4, 7, //face arrière
                5, 7, 6,
                6, 7, 1, //face gauche
                6, 1, 0,
                6, 0, 3, //face bas
                6, 3, 5,
                1, 7, 4, //face haut
                1, 4, 2
            };
            this.indexBuffer = new IndexBuffer(this.m_objGraphicsDeviceManager.GraphicsDevice, typeof(short), 36, BufferUsage.WriteOnly);
            this.indexBuffer.SetData(indices);
            //var vb = new VertexBuffer(this.graphics.GraphicsDevice, typeof (VertexPositionColor), 8, BufferUsage.None);


            vertices             = new VertexPositionColor[8];
            vertices[0].Position = new Vector3(-10f, -10f, 10f);
            vertices[0].Color    = Color.Yellow;
            vertices[1].Position = new Vector3(-10f, 10f, 10f);
            vertices[1].Color    = Color.Green;
            vertices[2].Position = new Vector3(10f, 10f, 10f);
            vertices[2].Color    = Color.Blue;
            vertices[3].Position = new Vector3(10f, -10f, 10f);
            vertices[3].Color    = Color.Black;
            vertices[4].Position = new Vector3(10f, 10f, -10f);
            vertices[4].Color    = Color.Red;
            vertices[5].Position = new Vector3(10f, -10f, -10f);
            vertices[5].Color    = Color.Violet;
            vertices[6].Position = new Vector3(-10f, -10f, -10f);
            vertices[6].Color    = Color.Orange;
            vertices[7].Position = new Vector3(-10f, 10f, -10f);
            vertices[7].Color    = Color.Gray;
            vertexBuffer         = new VertexBuffer(this.m_objGraphicsDeviceManager.GraphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.None);
            //this.vertexBuffer = new VertexBuffer(this.graphics.GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.WriteOnly);
            this.vertexBuffer.SetData(vertices);



            this.m_objGraphicsDeviceManager.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);
            this.m_objGraphicsDeviceManager.GraphicsDevice.Indices = this.indexBuffer;
            //this.graphics.GraphicsDevice.Vertices[0].SetSource(this.vertexBuffer, 0, VertexPositionColor.SizeInBytes);
            //var ib = new IndexBuffer(this.graphics.GraphicsDevice, typeof (short), 36, BufferUsage.None);
            //this.graphics.GraphicsDevice.Indices = ib;
            //this.graphics.GraphicsDevice.VertexDeclaration = new VertexDeclaration(this.graphics.GraphicsDevice, VertexPositionColor.VertexElements);


            // TODO: Add your drawing code here
            //effect.CurrentTechnique.Passes[0].Apply();
            //GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                //GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
                this.m_objGraphicsDeviceManager.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
                //pass.End();
            }

            //effect.End();

            base.Draw(gameTime);

            IsDrawing = false;
        }
Exemple #35
0
        public override void Draw(GameTime gameTime)
        {
            if (!Drawable)
            {
                return;
            }

            VertexBuffer vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.None);

            vertexBuffer.SetData(MeshRenderer.Verticies);

            IndexBuffer triangleIndexBuffer = new IndexBuffer(
                GraphicsDevice,
                IndexElementSize.SixteenBits,
                sizeof(short) * MeshRenderer.TriangleIndices.Length,
                BufferUsage.None);

            triangleIndexBuffer.SetData(MeshRenderer.TriangleIndices);

            GraphicsDevice.Indices = triangleIndexBuffer;
            GraphicsDevice.SetVertexBuffer(vertexBuffer);
            GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, MeshRenderer.TriangleIndices.Length / 3);

            ////////////////////////////////////////////////////////

            var basicEffect = MeshRenderer.Effect;

            // These three lines are required if you use SpriteBatch, to reset the states that it sets
            GraphicsDevice.BlendState        = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.SamplerStates[0]  = SamplerState.LinearWrap;

            // Transform your model to place it somewhere in the world
            basicEffect.World = Matrix.CreateRotationZ(MathHelper.PiOver4) * Matrix.CreateTranslation(0.5f, 0, 0); // for sake of example
                                                                                                                   //basicEffect.World = Matrix.Identity; // Use this to leave your model at the origin
                                                                                                                   // Transform the entire world around (effectively: place the camera)
            basicEffect.View = Matrix.CreateLookAt(new Vector3(0, 0, -3), Vector3.Zero, Vector3.Up);
            // Specify how 3D points are projected/transformed onto the 2D screen
            basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45),
                                                                         (float)GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height, 1.0f, 100.0f);

            // Tell BasicEffect to make use of your vertex colors
            basicEffect.VertexColorEnabled = true;
            // I'm setting this so that *both* sides of your triangle are drawn
            // (so it won't be back-face culled if you move it, or the camera around behind it)
            GraphicsDevice.RasterizerState = RasterizerState.CullNone;

            // Render with a BasicEffect that was created in LoadContent
            // (BasicEffect only has one pass - but effects in general can have many rendering passes)
            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                // This is the all-important line that sets the effect, and all of its settings, on the graphics device
                pass.Apply();

                // Here's your code:
                VertexPositionColor[] vertices = new VertexPositionColor[3];
                vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
                vertices[0].Color    = Color.Red;
                vertices[1].Position = new Vector3(0, 0.5f, 0f);
                vertices[1].Color    = Color.Green;
                vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
                vertices[2].Color    = Color.Yellow;
                GraphicsDevice.DrawUserPrimitives <VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, 1);
            }

            ////////////////////////////////////////////////////////

            base.Draw(gameTime);
        }
Exemple #36
0
        private void BuildVBO()
        {
            vertices = new VertexPositionNormalTexture[36];
            Vector3[] positions = new Vector3[8];

            positions[0] = new Vector3(-1f / 2f, -1f / 2f, -1f / 2f);
            positions[1] = new Vector3(-1f / 2f, -1f / 2f, 1f / 2f);
            positions[2] = new Vector3(-1f / 2f, 1f / 2f, -1f / 2f);
            positions[3] = new Vector3(-1f / 2f, 1f / 2f, 1f / 2f);
            positions[4] = new Vector3(1f / 2f, -1f / 2f, -1f / 2f);
            positions[5] = new Vector3(1f / 2f, -1f / 2f, 1f / 2f);
            positions[6] = new Vector3(1f / 2f, 1f / 2f, -1f / 2f);
            positions[7] = new Vector3(1f / 2f, 1f / 2f, 1f / 2f);


            indices = new int[36];
            for (int i = 0; i < 36; i++)
            {
                indices[i] = i;
            }

            //front face
            vertices[0].Position = positions[6];
            vertices[1].Position = positions[2];
            vertices[2].Position = positions[0];
            vertices[3].Position = positions[0];
            vertices[4].Position = positions[4];
            vertices[5].Position = positions[6];

            vertices[0].TextureCoordinate = new Vector2(1, 1);
            vertices[1].TextureCoordinate = new Vector2(0, 1);
            vertices[2].TextureCoordinate = new Vector2(0, 0);
            vertices[3].TextureCoordinate = new Vector2(0, 0);
            vertices[4].TextureCoordinate = new Vector2(1, 0);
            vertices[5].TextureCoordinate = new Vector2(1, 1);

            for (int i = 0; i < 6; i++)
            {
                vertices[i].Normal = new Vector3(0, 0, -1);
            }


            //right face
            vertices[6].Position  = positions[6];
            vertices[7].Position  = positions[4];
            vertices[8].Position  = positions[5];
            vertices[9].Position  = positions[5];
            vertices[10].Position = positions[7];
            vertices[11].Position = positions[6];

            vertices[6].TextureCoordinate  = new Vector2(1, 1);
            vertices[7].TextureCoordinate  = new Vector2(0, 1);
            vertices[8].TextureCoordinate  = new Vector2(0, 0);
            vertices[9].TextureCoordinate  = new Vector2(0, 0);
            vertices[19].TextureCoordinate = new Vector2(1, 0);
            vertices[11].TextureCoordinate = new Vector2(1, 1);

            for (int i = 6; i < 12; i++)
            {
                vertices[i].Normal = new Vector3(1, 0, 0);
            }

            //top face
            vertices[12].Position = positions[6];
            vertices[13].Position = positions[7];
            vertices[14].Position = positions[3];
            vertices[15].Position = positions[3];
            vertices[16].Position = positions[2];
            vertices[17].Position = positions[6];

            for (int i = 12; i < 18; i++)
            {
                vertices[i].Normal = new Vector3(0, 1, 0);
            }

            vertices[12].TextureCoordinate = new Vector2(1, 1);
            vertices[13].TextureCoordinate = new Vector2(0, 1);
            vertices[14].TextureCoordinate = new Vector2(0, 0);
            vertices[15].TextureCoordinate = new Vector2(0, 0);
            vertices[16].TextureCoordinate = new Vector2(1, 0);
            vertices[17].TextureCoordinate = new Vector2(1, 1);

            //bottom face
            vertices[18].Position = positions[1];
            vertices[19].Position = positions[5];
            vertices[20].Position = positions[4];
            vertices[21].Position = positions[4];
            vertices[22].Position = positions[0];
            vertices[23].Position = positions[1];

            for (int i = 18; i < 24; i++)
            {
                vertices[i].Normal = new Vector3(0, -1, 0);
            }

            vertices[18].TextureCoordinate = new Vector2(1, 1);
            vertices[19].TextureCoordinate = new Vector2(0, 1);
            vertices[20].TextureCoordinate = new Vector2(0, 0);
            vertices[21].TextureCoordinate = new Vector2(0, 0);
            vertices[22].TextureCoordinate = new Vector2(1, 0);
            vertices[23].TextureCoordinate = new Vector2(1, 1);

            //left face
            vertices[24].Position = positions[1];
            vertices[25].Position = positions[0];
            vertices[26].Position = positions[2];
            vertices[27].Position = positions[2];
            vertices[28].Position = positions[3];
            vertices[29].Position = positions[1];

            for (int i = 24; i < 30; i++)
            {
                vertices[i].Normal = new Vector3(-1, 0, 0);
            }

            vertices[24].TextureCoordinate = new Vector2(1, 1);
            vertices[25].TextureCoordinate = new Vector2(0, 1);
            vertices[26].TextureCoordinate = new Vector2(0, 0);
            vertices[27].TextureCoordinate = new Vector2(0, 0);
            vertices[28].TextureCoordinate = new Vector2(1, 0);
            vertices[29].TextureCoordinate = new Vector2(1, 1);

            //back face
            vertices[30].Position = positions[1];
            vertices[31].Position = positions[3];
            vertices[32].Position = positions[7];
            vertices[33].Position = positions[7];
            vertices[34].Position = positions[5];
            vertices[35].Position = positions[1];

            for (int i = 30; i < 36; i++)
            {
                vertices[i].Normal = new Vector3(0, 0, 1);
            }

            vertices[30].TextureCoordinate = new Vector2(1, 1);
            vertices[31].TextureCoordinate = new Vector2(0, 1);
            vertices[32].TextureCoordinate = new Vector2(0, 0);
            vertices[33].TextureCoordinate = new Vector2(0, 0);
            vertices[34].TextureCoordinate = new Vector2(1, 0);
            vertices[35].TextureCoordinate = new Vector2(1, 1);

            //Init buffers
            vertexBuffer = new VertexBuffer(device, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
            vertexBuffer.SetData(vertices);

            indexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly);
            indexBuffer.SetData(indices);
        }
Exemple #37
0
        public void BuildSkyDome(GraphicsDevice GD, float time)
        {
            //generate sky dome geometry
            var subdivs = 65;
            List <VertexPositionTexture> verts = new List <VertexPositionTexture>();
            var indices = new List <int>();
            var skyCol  = new Color(0x00, 0x80, 0xFF, 0xFF);

            float skyPos = OutsideSkyP(time);

            verts.Add(new VertexPositionTexture(new Vector3(0, 1, 0), new Vector2(skyPos, 0f)));
            LastSkyPos = time;
            skyPos    += 1 / 16f;
            int vertLastStart  = 0;
            int vertLastLength = 1;

            for (int y = 1; y < subdivs; y++)
            {
                int start  = verts.Count;
                var angley = (float)Math.PI * y / ((float)subdivs - 1);
                var radius = (float)Math.Sin(angley);
                var height = Math.Cos(angley);
                //var aheight = (height < -0.6f)?((-0.12f) - height):height;
                //var tpos = (0.9f - (float)Math.Sqrt(Math.Abs(aheight)) * 0.9f);
                var tpos = (float)((height > 0) ? (0.9f - Math.Sqrt(height) * 0.9f) : 0.9f + Math.Sqrt(-height) * 0.1f);

                for (int x = 0; x < subdivs + 1; x++)
                {
                    var anglex  = (float)Math.PI * x * 2 / (float)subdivs;
                    var colLerp = Math.Min(1, Math.Abs(((y - 2) / (float)subdivs) - 0.60f) * 4);
                    verts.Add(new VertexPositionTexture(new Vector3((float)Math.Sin(anglex) * radius, (float)height, (float)Math.Cos(anglex) * radius), new Vector2(skyPos, tpos)));
                    if (x < subdivs)
                    {
                        if (y != 1)
                        {
                            indices.Add(vertLastStart + x % vertLastLength);
                            indices.Add(vertLastStart + (x + 1) % vertLastLength);
                            indices.Add(verts.Count - 1);
                        }

                        indices.Add(vertLastStart + (x + 1) % vertLastLength);
                        indices.Add(verts.Count);
                        indices.Add(verts.Count - 1);
                    }
                }
                vertLastStart  = start;
                vertLastLength = subdivs + 1;
            }

            if (Verts == null)
            {
                Verts = new VertexBuffer(GD, typeof(VertexPositionTexture), verts.Count, BufferUsage.None);
            }
            Verts.SetData(verts.ToArray());
            if (Indices == null)
            {
                Indices = new IndexBuffer(GD, IndexElementSize.ThirtyTwoBits, indices.Count, BufferUsage.None);
                Indices.SetData(indices.ToArray());
                PrimCount = indices.Count / 3;
            }
        }
        public void InitializeFromChunk(VoxelChunk chunk, GraphicsDevice graphics)
        {
            if (chunk == null)
            {
                return;
            }

            rebuildMutex.WaitOne();
            if (isRebuilding)
            {
                rebuildMutex.ReleaseMutex();
                return;
            }

            isRebuilding = true;
            rebuildMutex.ReleaseMutex();


            accumulatedVertices.Clear();
            accumulatedIndices.Clear();
            faceExists.Clear();
            drawFace.Clear();

            Voxel v           = chunk.MakeVoxel(0, 0, 0);
            Voxel voxelOnFace = chunk.MakeVoxel(0, 0, 0);

            Voxel[]      manhattanNeighbors = new Voxel[4];
            BoxPrimitive bedrockModel       = VoxelLibrary.GetPrimitive("Bedrock");

            for (int x = 0; x < chunk.SizeX; x++)
            {
                for (int y = 0; y < Math.Min(chunk.Manager.ChunkData.MaxViewingLevel + 1, chunk.SizeY); y++)
                {
                    for (int z = 0; z < chunk.SizeZ; z++)
                    {
                        v.GridPosition = new Vector3(x, y, z);


                        if ((v.IsExplored && v.IsEmpty) || !v.IsVisible)
                        {
                            continue;
                        }

                        BoxPrimitive primitive = VoxelLibrary.GetPrimitive(v.Type);
                        if (v.IsExplored && primitive == null)
                        {
                            continue;
                        }
                        if (!v.IsExplored)
                        {
                            primitive = bedrockModel;
                        }

                        Color tint = v.Type.Tint;
                        BoxPrimitive.BoxTextureCoords uvs = primitive.UVs;

                        if (v.Type.HasTransitionTextures && v.IsExplored)
                        {
                            uvs = v.ComputeTransitionTexture(manhattanNeighbors);
                        }


                        Voxel worldVoxel = new Voxel();
                        for (int i = 0; i < 6; i++)
                        {
                            BoxFace face  = (BoxFace)i;
                            Vector3 delta = FaceDeltas[face];
                            faceExists[face] = chunk.IsCellValid(x + (int)delta.X, y + (int)delta.Y, z + (int)delta.Z);
                            drawFace[face]   = true;

                            if (faceExists[face])
                            {
                                voxelOnFace.GridPosition = new Vector3(x + (int)delta.X, y + (int)delta.Y, z + (int)delta.Z);
                                drawFace[face]           = (voxelOnFace.IsExplored && voxelOnFace.IsEmpty) || !voxelOnFace.IsVisible ||
                                                           (voxelOnFace.Type.CanRamp && voxelOnFace.RampType != RampType.None && IsSideFace(face) &&
                                                            ShouldDrawFace(face, voxelOnFace.RampType, v.RampType));
                            }
                            else
                            {
                                bool success = chunk.Manager.ChunkData.GetNonNullVoxelAtWorldLocation(new Vector3(x + (int)delta.X, y + (int)delta.Y, z + (int)delta.Z) + chunk.Origin, ref worldVoxel);
                                drawFace[face] = !success || (worldVoxel.IsExplored && worldVoxel.IsEmpty) || !worldVoxel.IsVisible ||
                                                 (worldVoxel.Type.CanRamp && worldVoxel.RampType != RampType.None &&
                                                  IsSideFace(face) &&
                                                  ShouldDrawFace(face, worldVoxel.RampType, v.RampType));
                            }
                        }


                        for (int i = 0; i < 6; i++)
                        {
                            BoxFace face = (BoxFace)i;
                            if (!drawFace[face])
                            {
                                continue;
                            }
                            int faceIndex   = 0;
                            int faceCount   = 0;
                            int vertexIndex = 0;
                            int vertexCount = 0;
                            primitive.GetFace(face, uvs, out faceIndex, out faceCount, out vertexIndex, out vertexCount);
                            Vector2 texScale = uvs.Scales[i];

                            int indexOffset = accumulatedVertices.Count;
                            for (int vertOffset = 0; vertOffset < vertexCount; vertOffset++)
                            {
                                ExtendedVertex vert      = primitive.Vertices[vertOffset + vertexIndex];
                                VoxelVertex    bestKey   = primitive.Deltas[vertOffset + vertexIndex];
                                Color          color     = v.Chunk.Data.GetColor(x, y, z, bestKey);
                                Vector3        offset    = Vector3.Zero;
                                Vector2        texOffset = Vector2.Zero;

                                if (v.Type.CanRamp && ShouldRamp(bestKey, v.RampType))
                                {
                                    offset = new Vector3(0, -v.Type.RampSize, 0);

                                    if (face != BoxFace.Top && face != BoxFace.Bottom)
                                    {
                                        texOffset = new Vector2(0, v.Type.RampSize * (texScale.Y));
                                    }
                                }

                                ExtendedVertex newVertex = new ExtendedVertex((vert.Position + v.Position + VertexNoise.GetNoiseVectorFromRepeatingTexture(vert.Position + v.Position) + offset),
                                                                              color,
                                                                              tint,
                                                                              uvs.Uvs[vertOffset + vertexIndex] + texOffset, uvs.Bounds[faceIndex / 6]);
                                accumulatedVertices.Add(newVertex);
                            }

                            for (int idx = faceIndex; idx < faceCount + faceIndex; idx++)
                            {
                                int vertexOffset = primitive.Indices[idx];
                                accumulatedIndices.Add((short)(indexOffset + (vertexOffset - primitive.Indices[faceIndex])));
                            }
                        }
                    }
                }
            }

            if (accumulatedIndices.Count > 0 && accumulatedIndices.Count > 0)
            {
                Vertices = new ExtendedVertex[accumulatedVertices.Count];
                accumulatedVertices.CopyTo(Vertices);
                IndexBuffer = new IndexBuffer(graphics, typeof(short), accumulatedIndices.Count, BufferUsage.WriteOnly);
                IndexBuffer.SetData(accumulatedIndices.ToArray());
            }
            ResetBuffer(graphics);
            isRebuilding = false;

            //chunk.PrimitiveMutex.WaitOne();
            chunk.NewPrimitive         = this;
            chunk.NewPrimitiveReceived = true;
            //chunk.PrimitiveMutex.ReleaseMutex();
        }
Exemple #39
0
        public Doom3Map(Doom3MapData map)
        {
            Surfaces = new List <Surface>();
            int verts   = 0;
            int indices = 0;

            foreach (Doom3MapData.Model m in map.Models)
            {
                foreach (Doom3MapData.Surface s in m.Surfaces)
                {
                    VertexBuffer vb = Root.Instance.UserInterface.Renderer.CreateStaticVertexBuffer(
                        s.Vertices,
                        s.Vertices.Length * 4 * (3 + 2 + 3)
                        );
                    vb.Format = VertexFormat.VF_P3T2N3;

                    IndexBuffer ib = new IndexBuffer();
                    ib.buffer = new int[s.Indices.Length];
                    for (int i = 0; i < ib.buffer.Length; ++i)
                    {
                        ib.buffer[i] = s.Indices[i];
                    }

                    Surface s2 = new Surface();
                    s2.Ibuffer = ib;
                    s2.Vbuffer = vb;
                    verts     += s.Vertices.Length;
                    indices   += s.Indices.Length;
                    Texture t = null;
                    try
                    {
                        t = Root.Instance.ResourceManager.LoadTexture(s.Name + ".tga");
                    }
                    catch (Exception)
                    {
                        try
                        {
                            t = Root.Instance.ResourceManager.LoadTexture(s.Name + "_add.tga");
                        }
                        catch (Exception)
                        {
                            try
                            {
                                t = Root.Instance.ResourceManager.LoadTexture(s.Name + "_d.tga");
                            }
                            catch (Exception)
                            {
                                System.Console.WriteLine("warning: cant load " + s.Name);
                            }
                        }
                    }
                    s2.Material = Material.CreateSimpleMaterial(t);
                    //s2.Material.Additive = true;
                    Surfaces.Add(s2);
                }
            }
            System.Console.WriteLine("surfaces: " + Surfaces.Count.ToString());
            System.Console.WriteLine("verts: " + verts.ToString());
            System.Console.WriteLine("indices: " + indices.ToString());

            GC.Collect();
            BBox = new BoundingBox(map.BBoxMin, map.BBoxMax);
        }
 /// <summary>
 /// Буфер индексов депозитов
 /// </summary>
 public void DepositVertexBuffer(IndexBuffer buffer)
 {
     buffer.Clear();
     EmptyBufferStack.Push(buffer);
 }
        // Create and return the (drawable) bounding box
        private BoundingBoxBuffers CreateBoundingBoxBuffers(BoundingBox boundingBox, GraphicsDevice graphicsDevice)
        {
            BoundingBoxBuffers boundingBoxBuffers = new BoundingBoxBuffers();

            boundingBoxBuffers.PrimitiveCount = 24;
            boundingBoxBuffers.VertexCount    = 48;

            VertexBuffer vertexBuffer = new VertexBuffer(graphicsDevice,
                                                         typeof(VertexPositionColor), boundingBoxBuffers.VertexCount,
                                                         BufferUsage.WriteOnly);
            List <VertexPositionColor> vertices = new List <VertexPositionColor>();

            const float ratio = 5.0f;

            Vector3 xOffset = new Vector3((boundingBox.Max.X - boundingBox.Min.X) / ratio, 0, 0);
            Vector3 yOffset = new Vector3(0, (boundingBox.Max.Y - boundingBox.Min.Y) / ratio, 0);
            Vector3 zOffset = new Vector3(0, 0, (boundingBox.Max.Z - boundingBox.Min.Z) / ratio);

            Vector3[] corners = boundingBox.GetCorners();

            // Corner 1.
            AddVertex(vertices, corners[0]);
            AddVertex(vertices, corners[0] + xOffset);
            AddVertex(vertices, corners[0]);
            AddVertex(vertices, corners[0] - yOffset);
            AddVertex(vertices, corners[0]);
            AddVertex(vertices, corners[0] - zOffset);

            // Corner 2.
            AddVertex(vertices, corners[1]);
            AddVertex(vertices, corners[1] - xOffset);
            AddVertex(vertices, corners[1]);
            AddVertex(vertices, corners[1] - yOffset);
            AddVertex(vertices, corners[1]);
            AddVertex(vertices, corners[1] - zOffset);

            // Corner 3.
            AddVertex(vertices, corners[2]);
            AddVertex(vertices, corners[2] - xOffset);
            AddVertex(vertices, corners[2]);
            AddVertex(vertices, corners[2] + yOffset);
            AddVertex(vertices, corners[2]);
            AddVertex(vertices, corners[2] - zOffset);

            // Corner 4.
            AddVertex(vertices, corners[3]);
            AddVertex(vertices, corners[3] + xOffset);
            AddVertex(vertices, corners[3]);
            AddVertex(vertices, corners[3] + yOffset);
            AddVertex(vertices, corners[3]);
            AddVertex(vertices, corners[3] - zOffset);

            // Corner 5.
            AddVertex(vertices, corners[4]);
            AddVertex(vertices, corners[4] + xOffset);
            AddVertex(vertices, corners[4]);
            AddVertex(vertices, corners[4] - yOffset);
            AddVertex(vertices, corners[4]);
            AddVertex(vertices, corners[4] + zOffset);

            // Corner 6.
            AddVertex(vertices, corners[5]);
            AddVertex(vertices, corners[5] - xOffset);
            AddVertex(vertices, corners[5]);
            AddVertex(vertices, corners[5] - yOffset);
            AddVertex(vertices, corners[5]);
            AddVertex(vertices, corners[5] + zOffset);

            // Corner 7.
            AddVertex(vertices, corners[6]);
            AddVertex(vertices, corners[6] - xOffset);
            AddVertex(vertices, corners[6]);
            AddVertex(vertices, corners[6] + yOffset);
            AddVertex(vertices, corners[6]);
            AddVertex(vertices, corners[6] + zOffset);

            // Corner 8.
            AddVertex(vertices, corners[7]);
            AddVertex(vertices, corners[7] + xOffset);
            AddVertex(vertices, corners[7]);
            AddVertex(vertices, corners[7] + yOffset);
            AddVertex(vertices, corners[7]);
            AddVertex(vertices, corners[7] + zOffset);

            vertexBuffer.SetData(vertices.ToArray());
            boundingBoxBuffers.Vertices = vertexBuffer;

            IndexBuffer indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, boundingBoxBuffers.VertexCount,
                                                      BufferUsage.WriteOnly);

            indexBuffer.SetData(Enumerable.Range(0, boundingBoxBuffers.VertexCount).Select(i => (short)i).ToArray());
            boundingBoxBuffers.Indices = indexBuffer;

            return(boundingBoxBuffers);
        }
Exemple #42
0
        public SceneControl(ScreenComponent manager, string style = "") :
            base(manager, style)
        {
            Mask      = (int)Math.Pow(2, VIEWRANGE) - 1;
            Span      = (int)Math.Pow(2, VIEWRANGE);
            SpanOver2 = Span >> 1;

            player   = manager.Player;
            camera   = manager.Camera;
            assets   = manager.Game.Assets;
            entities = manager.Game.Entity;
            Manager  = manager;

            simpleShader = manager.Game.Content.Load <Effect>("simple");
            sunTexture   = assets.LoadTexture(typeof(ScreenComponent), "sun");

            //List<Bitmap> bitmaps = new List<Bitmap>();
            var definitions  = Manager.Game.DefinitionManager.GetBlockDefinitions();
            int textureCount = 0;

            foreach (var definition in definitions)
            {
                textureCount += definition.Textures.Length;
            }
            int bitmapSize = 128;

            blockTextures = new Texture2DArray(manager.GraphicsDevice, 1, bitmapSize, bitmapSize, textureCount);
            int layer = 0;

            foreach (var definition in definitions)
            {
                foreach (var bitmap in definition.Textures)
                {
                    System.Drawing.Bitmap texture = manager.Game.Assets.LoadBitmap(definition.GetType(), bitmap);

                    var   scaled     = texture;//new Bitmap(bitmap, new System.Drawing.Size(bitmapSize, bitmapSize));
                    int[] data       = new int[scaled.Width * scaled.Height];
                    var   bitmapData = scaled.LockBits(new System.Drawing.Rectangle(0, 0, scaled.Width, scaled.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, data, 0, data.Length);
                    blockTextures.SetData(data, layer);
                    scaled.UnlockBits(bitmapData);
                    layer++;
                }
            }

            planet = Manager.Game.ResourceManager.GetPlanet(player.Position.Position.Planet);

            // TODO: evtl. Cache-Size (Dimensions) VIEWRANGE + 1

            int range = ((int)Math.Pow(2, VIEWRANGE) - 2) / 2;

            localChunkCache = new LocalChunkCache(planet.GlobalChunkCache, VIEWRANGE, range);

            chunkRenderer = new ChunkRenderer[
                (int)Math.Pow(2, VIEWRANGE) * (int)Math.Pow(2, VIEWRANGE),
                planet.Size.Z];
            orderedChunkRenderer = new List <ChunkRenderer>(
                (int)Math.Pow(2, VIEWRANGE) * (int)Math.Pow(2, VIEWRANGE) * planet.Size.Z);

            for (int i = 0; i < chunkRenderer.GetLength(0); i++)
            {
                for (int j = 0; j < chunkRenderer.GetLength(1); j++)
                {
                    ChunkRenderer renderer = new ChunkRenderer(this, Manager.Game.DefinitionManager, simpleShader, manager.GraphicsDevice, camera.Projection, blockTextures);
                    chunkRenderer[i, j] = renderer;
                    orderedChunkRenderer.Add(renderer);
                }
            }

            backgroundThread = new Thread(BackgroundLoop)
            {
                Priority     = ThreadPriority.Lowest,
                IsBackground = true
            };
            backgroundThread.Start();

            backgroundThread2 = new Thread(ForceUpdateBackgroundLoop)
            {
                Priority     = ThreadPriority.Lowest,
                IsBackground = true
            };
            backgroundThread2.Start();

            var additional = Environment.ProcessorCount / 3;

            additional                     = additional == 0 ? 1 : additional;
            _fillIncrement                 = additional + 1;
            additionalFillResetEvents      = new AutoResetEvent[additional];
            _additionalRegenerationThreads = new Thread[additional];
            for (int i = 0; i < additional; i++)
            {
                var t = new Thread(AdditionalFillerBackgroundLoop)
                {
                    Priority     = ThreadPriority.Lowest,
                    IsBackground = true
                };
                var are = new AutoResetEvent(false);
                t.Start(new object[] { are, i });
                additionalFillResetEvents[i]      = are;
                _additionalRegenerationThreads[i] = t;
            }



            var selectionVertices = new[]
            {
                new VertexPositionColor(new Vector3(-0.001f, +1.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, +1.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, -0.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, -0.001f, +1.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, +1.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, +1.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(-0.001f, -0.001f, -0.001f), Color.Black * 0.5f),
                new VertexPositionColor(new Vector3(+1.001f, -0.001f, -0.001f), Color.Black * 0.5f),
            };

            var billboardVertices = new[]
            {
                new VertexPositionTexture(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)),
                new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(0.5f, -0.5f, 0), new Vector2(1, 1)),
                new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)),
            };

            var selectionIndices = new short[]
            {
                0, 1, 0, 2, 1, 3, 2, 3,
                4, 5, 4, 6, 5, 7, 6, 7,
                0, 4, 1, 5, 2, 6, 3, 7
            };

            selectionLines = new VertexBuffer(manager.GraphicsDevice, VertexPositionColor.VertexDeclaration, selectionVertices.Length);
            selectionLines.SetData(selectionVertices);

            selectionIndexBuffer = new IndexBuffer(manager.GraphicsDevice, DrawElementsType.UnsignedShort, selectionIndices.Length);
            selectionIndexBuffer.SetData(selectionIndices);

            billboardVertexbuffer = new VertexBuffer(manager.GraphicsDevice, VertexPositionTexture.VertexDeclaration, billboardVertices.Length);
            billboardVertexbuffer.SetData(billboardVertices);


            sunEffect = new BasicEffect(manager.GraphicsDevice)
            {
                TextureEnabled = true
            };

            selectionEffect = new BasicEffect(manager.GraphicsDevice)
            {
                VertexColorEnabled = true
            };

            MiniMapTexture          = new RenderTarget2D(manager.GraphicsDevice, 128, 128, PixelInternalFormat.Rgb8); // , false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.PreserveContents);
            miniMapProjectionMatrix = Matrix.CreateOrthographic(128, 128, 1, 10000);
        }
        private unsafe DynamicUnstructureGeometry DoCreateMesh(DynamicUnstructuredGridderSource src)
        {
            MatrixPositionBuffer   matrixPositions         = null;
            IndexBuffer            matrixIndicesBuffer     = null;
            FracturePositionBuffer fractionPositionsBuffer = null;

            //生成母体
            if (src.ElementFormat == DynamicUnstructuredGridderSource.MATRIX_FORMAT4_TETRAHEDRON)
            {
                matrixPositions = new TetrahedronMatrixPositionBuffer();
                //matrixPositions.Shape = MatrixPositionBufferData.SHAPE_TETRAHEDRON;

                //int memSize = src.ElementNum * sizeof(TetrahedronPositions);
                //matrixPositions.AllocMem(memSize);
                matrixPositions.AllocMem(src.ElementNum);

                TetrahedronPosition *tets = (TetrahedronPosition *)matrixPositions.Data;
                int[][]  matrixIndices    = src.Elements;
                Vertex[] positions        = src.Nodes;
                for (int i = 0; i < src.ElementNum; i++)
                {
                    tets[i].p1 = src.Transform * positions[matrixIndices[i][0] - 1];
                    tets[i].p2 = src.Transform * positions[matrixIndices[i][1] - 1];
                    tets[i].p3 = src.Transform * positions[matrixIndices[i][2] - 1];
                    tets[i].p4 = src.Transform * positions[matrixIndices[i][3] - 1];
                }

                matrixIndicesBuffer = new TetrahedronMatrixIndexBuffer();
                //int triangleCount = src.ElementNum * 4;
                //matrixIndicesBuffer.AllocMem(triangleCount * sizeof(TriangleIndex));
                matrixIndicesBuffer.AllocMem(src.ElementNum);
                TetrahedronIndex *header = (TetrahedronIndex *)matrixIndicesBuffer.Data;
                for (int i = 0; i < src.ElementNum; i++)
                {
                    header[i].dot0         = (uint)(i * 4 + 0);
                    header[i].dot1         = (uint)(i * 4 + 1);
                    header[i].dot2         = (uint)(i * 4 + 2);
                    header[i].dot3         = (uint)(i * 4 + 3);
                    header[i].dot4         = (uint)(i * 4 + 0);
                    header[i].dot5         = (uint)(i * 4 + 1);
                    header[i].restartIndex = uint.MaxValue;
                }
            }

            if (src.ElementFormat == DynamicUnstructuredGridderSource.MATRIX_FORMAT3_TRIANGLE)
            {
                matrixPositions = new TriangleMatrixPositionBuffer();
                //matrixPositions.Shape = MatrixPositionBufferData.SHAPE_TRIANGLE;
                matrixPositions.AllocMem(src.ElementNum);
                int[][]           matrixIndices = src.Elements;
                Vertex[]          positions     = src.Nodes;
                TrianglePosition *triangles     = (TrianglePosition *)matrixPositions.Data;
                for (int i = 0; i < src.ElementNum; i++)
                {
                    triangles[i].P1 = src.Transform * positions[matrixIndices[i][0] - 1];
                    triangles[i].P2 = src.Transform * positions[matrixIndices[i][1] - 1];
                    triangles[i].P3 = src.Transform * positions[matrixIndices[i][2] - 1];
                }
            }

            if (src.ElementFormat == DynamicUnstructuredGridderSource.MATRIX_FORMAT6_TRIANGULAR_PRISM)
            {
                matrixPositions = new TriangularPrismMatrixPositionBuffer();
                //matrixPositions.Shape = MatrixPositionBufferData.SHAPE_TRIANGLE;
                matrixPositions.AllocMem(src.ElementNum);
                int[][]  matrixIndices         = src.Elements;
                Vertex[] positions             = src.Nodes;
                TriangularPrismPosition *prism = (TriangularPrismPosition *)matrixPositions.Data;
                for (int i = 0; i < src.ElementNum; i++)
                {
                    try
                    {
                        prism[i].P1 = src.Transform * positions[matrixIndices[i][0] - 1];
                        prism[i].P2 = src.Transform * positions[matrixIndices[i][1] - 1];
                        prism[i].P3 = src.Transform * positions[matrixIndices[i][2] - 1];
                        prism[i].P4 = src.Transform * positions[matrixIndices[i][3] - 1];
                        prism[i].P5 = src.Transform * positions[matrixIndices[i][4] - 1];
                        prism[i].P6 = src.Transform * positions[matrixIndices[i][5] - 1];
                    }
                    catch (IndexOutOfRangeException e)
                    {
                        throw new IndexOutOfRangeException(String.Format("Maxtrix positions row:{0},out of range", i + 1));
                    }
                }

                matrixIndicesBuffer = new TetrahedronMatrixTriangularPrismIndexBuffer();
                //int triangleCount = src.ElementNum * 4;
                //matrixIndicesBuffer.AllocMem(triangleCount * sizeof(TriangleIndex));
                matrixIndicesBuffer.AllocMem(src.ElementNum);
                TetrahedronTriangularPrismIndex *indexes = (TetrahedronTriangularPrismIndex *)matrixIndicesBuffer.Data;
                for (int i = 0; i < src.ElementNum; i++)
                {
                    indexes[i].dot0         = (uint)(i * 6 + 0);
                    indexes[i].dot1         = (uint)(i * 6 + 3);
                    indexes[i].dot2         = (uint)(i * 6 + 1);
                    indexes[i].dot3         = (uint)(i * 6 + 4);
                    indexes[i].dot4         = (uint)(i * 6 + 2);
                    indexes[i].dot5         = (uint)(i * 6 + 5);
                    indexes[i].dot6         = (uint)(i * 6 + 0);
                    indexes[i].dot7         = (uint)(i * 6 + 3);
                    indexes[i].restartIndex = uint.MaxValue;
                }
            }

            //生成裂缝
            if (src.FractureFormat == DynamicUnstructuredGridderSource.FRACTURE_FORMAT3_TRIANGLE)
            {
                fractionPositionsBuffer = new TriangleFracturePositionBuffer();

                //fractionPositionsBuffer.Shape = FracturePositionBufferData.SHAPE_TRIANGLE;

                int triangleCount = src.FractureNum;

                //fractionPositionsBuffer.AllocMem(triangleCount * sizeof(TrianglePositions));
                fractionPositionsBuffer.AllocMem(triangleCount);

                int[][]           triangleIndices = src.Fractures;
                Vertex[]          positions       = src.Nodes;
                TrianglePosition *triangles       = (TrianglePosition *)fractionPositionsBuffer.Data;
                for (int i = 0; i < triangleCount; i++)
                {
                    triangles[i].P1 = src.Transform * positions[triangleIndices[i][0] - 1];
                    triangles[i].P2 = src.Transform * positions[triangleIndices[i][1] - 1];
                    triangles[i].P3 = src.Transform * positions[triangleIndices[i][2] - 1];
                }
            }

            if (src.FractureFormat == DynamicUnstructuredGridderSource.FRACTURE_FORMAT2_LINE)
            {
                fractionPositionsBuffer = new LineFracturePositionBuffer();

                //fractionPositionsBuffer.Shape = FracturePositionBufferData.SHAPE_LINE;

                int lineCount = src.FractureNum;

                //fractionPositionsBuffer.AllocMem(lineCount * sizeof(LinePositions));
                fractionPositionsBuffer.AllocMem(lineCount);

                LinePosition *lines       = (LinePosition *)fractionPositionsBuffer.Data;
                Vertex[]      positions   = src.Nodes;
                int[][]       lineIndices = src.Fractures;
                for (int i = 0; i < lineCount; i++)
                {
                    lines[i].P1 = src.Transform * positions[lineIndices[i][0] - 1];
                    lines[i].P2 = src.Transform * positions[lineIndices[i][1] - 1];
                }
            }

            if (src.FractureFormat == DynamicUnstructuredGridderSource.FRACTURE_FORMAT4_QUAD)
            {
                fractionPositionsBuffer = new QuadFracturePositionBuffer();
                int fractureCount = src.FractureNum;
                fractionPositionsBuffer.AllocMem(fractureCount);
                QuadPosition *quad        = (QuadPosition *)fractionPositionsBuffer.Data;
                Vertex[]      positions   = src.Nodes;
                int[][]       quadIndices = src.Fractures;
                for (int i = 0; i < fractureCount; i++)
                {
                    quad[i].P1 = src.Transform * positions[quadIndices[i][0] - 1];
                    quad[i].P2 = src.Transform * positions[quadIndices[i][1] - 1];
                    quad[i].P3 = src.Transform * positions[quadIndices[i][3] - 1];
                    quad[i].P4 = src.Transform * positions[quadIndices[i][2] - 1];
                }
            }

            DynamicUnstructureGeometry geometry = new DynamicUnstructureGeometry(matrixPositions);

            geometry.MatrixIndices     = matrixIndicesBuffer;
            geometry.FracturePositions = fractionPositionsBuffer;
            geometry.Min = src.TransformedActiveBounds.Min;
            geometry.Max = src.TransformedActiveBounds.Max;
            return(geometry);
        }
 private void SetIndexBuffer(GraphicsDevice graphicsDevice)
 {
     indexBuffer = new IndexBuffer(graphicsDevice, sizeof(short) * indices.Length, BufferUsage.None, IndexElementSize.SixteenBits);
     indexBuffer.SetData <short>(indices);
 }
        public void RenderCube(IRenderContext context, IEffect effect, IEffectParameterSet effectParameterSet, Matrix transform, Color color)
        {
            if (!context.IsCurrentRenderPass <I3DRenderPass>())
            {
                throw new InvalidOperationException("Can't use 3D rendering utilities in 2D context.");
            }

            var vertexes = _renderCache.GetOrSet(
                "rendercube3dvb:" + color,
                () =>
            {
                var vb = new VertexBuffer(context.GraphicsDevice, VertexPositionNormalColor.VertexDeclaration, 24, BufferUsage.WriteOnly);
                vb.SetData(new[]
                {
                    new VertexPositionNormalColor(new Vector3(0, 0, 0), new Vector3(-1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 0, 1), new Vector3(-1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 0), new Vector3(-1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 1), new Vector3(-1, 0, 0), color),

                    new VertexPositionNormalColor(new Vector3(1, 0, 0), new Vector3(1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 0, 1), new Vector3(1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 0), new Vector3(1, 0, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 1), new Vector3(1, 0, 0), color),

                    new VertexPositionNormalColor(new Vector3(0, 0, 0), new Vector3(0, -1, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 0, 1), new Vector3(0, -1, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 0), new Vector3(0, 1, 0), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 1), new Vector3(0, 1, 0), color),

                    new VertexPositionNormalColor(new Vector3(1, 0, 0), new Vector3(0, -1, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 0, 1), new Vector3(0, -1, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 0), new Vector3(0, 1, 0), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 1), new Vector3(0, 1, 0), color),

                    new VertexPositionNormalColor(new Vector3(0, 0, 0), new Vector3(0, 0, -1), color),
                    new VertexPositionNormalColor(new Vector3(0, 0, 1), new Vector3(0, 0, 1), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 0), new Vector3(0, 0, -1), color),
                    new VertexPositionNormalColor(new Vector3(0, 1, 1), new Vector3(0, 0, 1), color),

                    new VertexPositionNormalColor(new Vector3(1, 0, 0), new Vector3(0, 0, -1), color),
                    new VertexPositionNormalColor(new Vector3(1, 0, 1), new Vector3(0, 0, 1), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 0), new Vector3(0, 0, -1), color),
                    new VertexPositionNormalColor(new Vector3(1, 1, 1), new Vector3(0, 0, 1), color)
                });
                return(vb);
            });
            var indicies = _renderCache.GetOrSet(
                "rendercube3dib",
                () =>
            {
                var ib = new IndexBuffer(context.GraphicsDevice, IndexElementSize.SixteenBits, 36, BufferUsage.WriteOnly);
                ib.SetData(new short[]
                {
                    0, 2, 1,
                    3, 1, 2,

                    4, 5, 6,
                    7, 6, 5,

                    0 + 8, 1 + 8, 4 + 8,
                    5 + 8, 4 + 8, 1 + 8,

                    2 + 8, 6 + 8, 3 + 8,
                    7 + 8, 3 + 8, 6 + 8,

                    0 + 16, 4 + 16, 2 + 16,
                    6 + 16, 2 + 16, 4 + 16,

                    1 + 16, 3 + 16, 5 + 16,
                    7 + 16, 5 + 16, 3 + 16
                });
                return(ib);
            });

            _renderBatcher.QueueRequest(
                context,
                _renderBatcher.CreateSingleRequestFromState(
                    context,
                    effect,
                    effectParameterSet,
                    vertexes,
                    indicies,
                    PrimitiveType.TriangleList,
                    transform,
                    null));
        }
Exemple #46
0
        bool IDeviceIndexBuffer.AllocateForInstancing(DrawState state)
        {
            if (buffer.instancingCount > 0)
            {
                return(buffer.instancingCount > 1);
            }

            int instances = 128;

            if (this.buffer.Count > 100)
            {
                instances = 64;
            }
            if (this.buffer.Count > 2000)
            {
                instances = 32;
            }
            if (this.buffer.Count > 20000)
            {
                instances = 16;
            }
            if (this.buffer.Count > 175000)
            {
                instances = 8;
            }
            if (this.buffer.Count > 250000)
            {
                instances = 4;
            }
            if (this.buffer.Count > 300000)
            {
                instances = 2;
            }
            if (this.buffer.Count > 400000)
            {
                instances = 1;
            }

            if ((this.ResourceUsage & ResourceUsage.Dynamic) == ResourceUsage.Dynamic)
            {
                instances = 1;
            }

            bool convertToInt = false;

            if (instances > 1)
            {
                if (this.buffer.Stride == 2)
                {
                    if (typeof(IndexType) == typeof(ushort))
                    {
                        if ((this.buffer.i_max + 1) * instances > ushort.MaxValue)
                        {
                            if ((int)ushort.MaxValue / (this.buffer.i_max + 1) >= 16)
                            {
                                instances = (int)ushort.MaxValue / (this.buffer.i_max + 1);
                            }
                            else
                            {
                                convertToInt = true;
                            }
                        }
                    }
                    else
                    {
                        if (this.buffer.i_max * instances > short.MaxValue)
                        {
                            if ((int)short.MaxValue / (this.buffer.i_max + 1) >= 16)
                            {
                                instances = (int)short.MaxValue / (this.buffer.i_max + 1);
                            }
                            else
                            {
                                convertToInt = true;
                            }
                        }
                    }
                }
                else
                {
                    if ((this.buffer.i_max + 1) * 64 > state.graphics.GraphicsDeviceCapabilities.MaxVertexIndex)
                    {
                        instances = Math.Max(1, state.graphics.GraphicsDeviceCapabilities.MaxVertexIndex / (this.buffer.i_max + 1));
                    }
                }
            }

            buffer.instancingCount = 1;

            if (instances > 1)
            {
                IEnumerable <IndexType> data = buffer.Data;

                if (ib != null)
                {
                    if (data == null)
                    {
                        data = new IndexType[buffer.Count];
                        ib.GetData <IndexType>((IndexType[])data);
                    }
                    ib.Dispose();
                    ib = null;
                }
                if (data == null)
                {
                    buffer.instancingCount = 1;
                    return(false);
                }

                buffer.Dispose();

                buffer = new Implementation(data);
                buffer.instancingCount = instances;
                buffer.convertToInt    = convertToInt;
            }
            return(buffer.instancingCount > 1);
        }
Exemple #47
0
        /// <summary>
        /// Loads the static mesh from the compiled binary mesh
        /// </summary>
        public override void Deserialize(BinaryReader reader)
        {
            base.Deserialize(reader);

            // Read mesh data
            int NumTriangles = reader.ReadInt32();
            int vertLen      = reader.ReadInt32();

            objectVertices = new TangentVertex[vertLen];
            for (int i = 0; i < objectVertices.Length; i++)
            {
                objectVertices[i] = new TangentVertex(
                    new Vector3(reader.ReadSingle(), reader.ReadSingle(),
                                reader.ReadSingle()),
                    new Vector2(reader.ReadSingle(), reader.ReadSingle()),
                    new Vector3(reader.ReadSingle(), reader.ReadSingle(),
                                reader.ReadSingle()),
                    new Vector3(reader.ReadSingle(), reader.ReadSingle(),
                                reader.ReadSingle()),
                    new Vector3(reader.ReadSingle(), reader.ReadSingle(),
                                reader.ReadSingle()));
            }

            int indexLen = reader.ReadInt32();

            objectIndices = new uint[indexLen];
            for (int i = 0; i < objectIndices.Length; i++)
            {
                objectIndices[i] = reader.ReadUInt32();
            }

            // Read BoundingSphere
            BoundingSphere = new BoundingSphere(
                new Vector3(reader.ReadSingle(), reader.ReadSingle(),
                            reader.ReadSingle()),
                reader.ReadSingle());

            // Read MeshCameras
            int meshCameraCount = reader.ReadInt32();

            if (meshCameraCount == 0)
            {
                MeshCameras = null;
            }
            else
            {
                MeshCameras = new MeshCamera[meshCameraCount];
                for (int i = 0; i < meshCameraCount; i++)
                {
                    MeshCameras[i]             = new MeshCamera();
                    MeshCameras[i].Translation = new Vector3(
                        reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
                    MeshCameras[i].CameraType = (MeshCameraType)reader.ReadInt32();
                }
            }

            // Create XNA buffers and fill them
            try
            {
                VertexBuffer newVertexBuffer = new VertexBuffer(AlkaronCoreGame.Core.GraphicsDevice,
                                                                TangentVertex.VertexDecl,
                                                                TangentVertex.SizeInBytes * objectVertices.Length,
                                                                BufferUsage.WriteOnly);

                IndexBuffer newIndexBuffer = new IndexBuffer(AlkaronCoreGame.Core.GraphicsDevice,
                                                             IndexElementSize.ThirtyTwoBits,
                                                             objectIndices.Length, BufferUsage.WriteOnly);

                if (newVertexBuffer != null)
                {
                    if (vertexBuffer != null)
                    {
                        vertexBuffer.Dispose();
                        vertexBuffer = null;
                    }

                    vertexBuffer = newVertexBuffer;
                }
                if (newIndexBuffer != null)
                {
                    if (indexBuffer != null)
                    {
                        indexBuffer.Dispose();
                        indexBuffer = null;
                    }

                    indexBuffer = newIndexBuffer;
                }
            }
            catch
            {
                return;
            }

            vertexBuffer.SetData <TangentVertex>(objectVertices);
            indexBuffer.SetData <uint>(objectIndices);

            CreateBoundingSphere();
        }
Exemple #48
0
        public Map(GraphicsDevice device, ContentManager content)
        {
            //matriz identidade do mundo
            worldMatrix = Matrix.Identity;
            effect      = new BasicEffect(device);

            //textura do mapa
            groundTexture         = content.Load <Texture2D>("grassTexture");
            effect.TextureEnabled = true;
            effect.Texture        = groundTexture;

            float aspectRatio = (float)device.Viewport.Width / device.Viewport.Height;

            effect.View = Matrix.CreateLookAt(
                new Vector3(0f, 500, 0f),
                new Vector3(1500, 0, 1500), Vector3.Up);

            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(60f),
                aspectRatio, 1f, 1000f);

            effect.LightingEnabled    = false;
            effect.VertexColorEnabled = true;

            //Indexação dos vertices do mapa, a partir dos valores rgb da textura
            texture = content.Load <Texture2D>("lh3d1");
            texels  = new Color[texture.Height * texture.Width]; // tamanho do array = a autura * a largura da img
            texture.GetData(texels);
            vertex = new VertexPositionColorTexture[texels.Length];

            //Gerar vertices
            int y;

            for (int z = 0; z < texture.Height; z++)
            {
                for (int x = 0; x < texture.Width; x++)
                {
                    y = (texels[z * texture.Width + x].R);
                    vertex[z * texture.Width + x] = new VertexPositionColorTexture(new Vector3(x, y * 0.5f, z), texels[x], new Vector2(x % 2, z % 2));
                }
            }

            //organização dos index
            index = new short[6 * (texture.Height - 1) * (texture.Width - 1)]; // index.Length = texels.Length

            int a = 0;

            for (int z = 0; z < texture.Height - 1; z++)
            {
                int aux = texture.Width - 1;
                for (int x = 0; x < texture.Width; x++)
                {
                    //   if (z % 2 == 0)
                    //{
                    index[2 * a]     = (short)(z * 128 + x + 128);
                    index[2 * a + 1] = (short)(z * 128 + x);
                    a++;

                    /*}
                     * if(z % 2 !=0)
                     * {
                     * index[2 * a] = (short)(z * 128 + aux + 128);
                     * index[2 * a + 1] = (short)(z * 128 + aux);
                     * a++;
                     * aux--;
                     * }*/
                }
            }

            vertexBuffer = new VertexBuffer(device,
                                            typeof(VertexPositionColorTexture),
                                            vertex.Length,
                                            BufferUsage.None);
            vertexBuffer.SetData <VertexPositionColorTexture>(vertex);

            indexBuffer = new IndexBuffer(device,
                                          typeof(short),
                                          index.Length,
                                          BufferUsage.None);
            indexBuffer.SetData(index);
        }
Exemple #49
0
        /// <summary>
        /// Builds a SuperElevation LOD to SuperElevationProfile specifications as one vertex buffer and one index buffer.
        /// The order in which the buffers are built reflects the nesting in the TrProfile.  The nesting order is:
        /// (Polylines (Vertices)).  All vertices and indices are built contiguously for an LOD.
        /// </summary>
        /// <param name="viewer">Viewer.</param>
        /// <param name="worldPosition">WorldPosition.</param>
        /// <param name="iLOD">Index of LOD mesh to be generated from profile.</param>
        /// <param name="iLODItem">Index of LOD mesh to be generated from profile.</param>
        public new ShapePrimitive BuildPrimitive(Viewer viewer, WorldPosition worldPosition, int iLOD, int iLODItem)
        {
            // Call for track section to initialize itself
            if (DTrackData.IsCurved == 0)
            {
                LinearGen();
            }
            else
            {
                CircArcGen();
            }

            // Count vertices and indices
            LOD     lod     = (LOD)TrProfile.LODs[iLOD];
            LODItem lodItem = (LODItem)lod.LODItems[iLODItem];

            NumVertices = (int)(lodItem.NumVertices * (NumSections + 1));
            NumIndices  = (short)(lodItem.NumSegments * NumSections * 6);
            // (Cells x 2 triangles/cell x 3 indices/triangle)

            // Allocate memory for vertices and indices
            VertexList          = new VertexPositionNormalTexture[NumVertices]; // numVertices is now aggregate
            TriangleListIndices = new short[NumIndices];                        // as is NumIndices

            // Build the mesh for lod
            VertexIndex = 0;
            IndexIndex  = 0;
            whichCase   = 0; //0: no elevation (MaxElev=0), 1: start (startE = 0, Max!=end),
            //2: end (end=0, max!=start), 3: middle (start>0, end>0), 4: start and finish in one

            if (StartElev.AlmostEqual(0f, 0.001f) && MaxElev.AlmostEqual(0f, 0.001f) && EndElv.AlmostEqual(0f, 0.001f))
            {
                whichCase = 0;                                                                                                        //no elev
            }
            else if (StartElev.AlmostEqual(0f, 0.001f) && EndElv.AlmostEqual(0f, 0.001f))
            {
                whichCase = 4;                                                                          //finish/start in one
            }
            else if (StartElev.AlmostEqual(0f, 0.001f) && !EndElv.AlmostEqual(0f, 0.001f))
            {
                whichCase = 1;                                                                           //start
            }
            else if (EndElv.AlmostEqual(0f, 0.001f) && !StartElev.AlmostEqual(0f, 0.001f))
            {
                whichCase = 2;                                                                           //finish
            }
            else
            {
                whichCase = 3; //in middle
            }
            Matrix PreRotation = Matrix.Identity;

            elevated = MaxElev;
            if (whichCase == 3 || whichCase == 2)
            {
                PreRotation = Matrix.CreateRotationZ(-elevated * Math.Sign(DTrackData.param1));
            }
            //if section is in the middle of curve, will only rotate the first set of vertex, others will follow the same rotation
            prevRotation = 0f;

            Vector3 tmp;

            // Initial load of baseline cross section polylines for this LOD only:
            foreach (Polyline pl in lodItem.Polylines)
            {
                foreach (Vertex v in pl.Vertices)
                {
                    tmp = new Vector3(v.Position.X, v.Position.Y, v.Position.Z);

                    if (whichCase == 3 || whichCase == 2)
                    {
                        tmp          = Vector3.Transform(tmp, PreRotation);
                        prevRotation = MaxElev;
                    }
                    VertexList[VertexIndex].Position          = tmp;
                    VertexList[VertexIndex].Normal            = v.Normal;
                    VertexList[VertexIndex].TextureCoordinate = v.TexCoord;
                    VertexIndex++;
                }
            }
            // Initial load of base cross section complete

            // Now generate and load subsequent cross sections
            OldRadius = -center;
            uint stride = VertexIndex;

            offSet = 0;

            for (uint i = 0; i < NumSections; i++)
            {
                currentRotation = determineRotation(DTrackData.param1);
                elevated        = currentRotation - prevRotation;
                prevRotation    = currentRotation;
                if (DTrackData.param1 > 0)
                {
                    elevated *= -1;
                }

                foreach (Polyline pl in lodItem.Polylines)
                {
                    uint plv = 0; // Polyline vertex index
                    foreach (Vertex v in pl.Vertices)
                    {
                        if (DTrackData.IsCurved == 0)
                        {
                            LinearGen(stride, pl);                           // Generation call
                        }
                        else
                        {
                            CircArcGen(stride, pl);
                        }

                        if (plv > 0)
                        {
                            // Sense for triangles is clockwise
                            // First triangle:
                            TriangleListIndices[IndexIndex++] = (short)VertexIndex;
                            TriangleListIndices[IndexIndex++] = (short)(VertexIndex - 1 - stride);
                            TriangleListIndices[IndexIndex++] = (short)(VertexIndex - 1);
                            // Second triangle:
                            TriangleListIndices[IndexIndex++] = (short)VertexIndex;
                            TriangleListIndices[IndexIndex++] = (short)(VertexIndex - stride);
                            TriangleListIndices[IndexIndex++] = (short)(VertexIndex - 1 - stride);
                        }
                        VertexIndex++;
                        plv++;
                    }
                }
                OldRadius = radius; // Get ready for next segment
                offSet++;
            }

            // Create and populate a new ShapePrimitive
            var indexBuffer = new IndexBuffer(viewer.GraphicsDevice, typeof(short), NumIndices, BufferUsage.WriteOnly);

            indexBuffer.SetData(TriangleListIndices);
            return(new ShapePrimitive(lodItem.LODMaterial, new SharedShape.VertexBufferSet(VertexList, viewer.GraphicsDevice), indexBuffer, 0, NumVertices, NumIndices / 3, new[] { -1 }, 0));
        }
Exemple #50
0
        protected override void LoadContent()
        {
            base.LoadContent();

            thisMesh = AssetManager.GetAsset <Model>(mesh);

            meshData = (Dictionary <string, object>)thisMesh.Tag;



            transforms = new Matrix[thisMesh.Bones.Count];
            thisMesh.CopyAbsoluteBoneTransformsTo(transforms);

            effect = AssetManager.GetAsset <Effect>("Shaders/Deferred/DeferredInstanceSkinnedShader");
            //effect = AssetManager.GetAsset<Effect>("Shaders/Deferred/DeferredInstanceShader");
            effect.CurrentTechnique = effect.Techniques["BasicTextureH"];

            Dictionary <string, object> TagData = (Dictionary <string, object>)thisMesh.Tag;

            Dictionary <int, List <Vector3> > p    = (Dictionary <int, List <Vector3> >)TagData["Vertices"];
            Dictionary <int, List <Vector3> > n    = (Dictionary <int, List <Vector3> >)TagData["Normals"];
            Dictionary <int, List <Vector2> > t    = (Dictionary <int, List <Vector2> >)TagData["TexCoords"];
            Dictionary <int, List <Vector3> > tang = (Dictionary <int, List <Vector3> >)TagData["Tangents"];
            Dictionary <int, List <Vector3> > bin  = (Dictionary <int, List <Vector3> >)TagData["BiNormals"];
            Dictionary <int, List <int> >     i    = (Dictionary <int, List <int> >)TagData["Inicies"];

            Dictionary <int, List <Vector4> > bi = (Dictionary <int, List <Vector4> >)TagData["BlendIndex"];
            Dictionary <int, List <Vector4> > bw = (Dictionary <int, List <Vector4> >)TagData["BlendWeight"];

            animationPlayer = new AnimationPlayer((SkinningData)meshData["SkinningData"], AnimationOffSet);
            if (!string.IsNullOrEmpty(AnimationClip))
            {
                animationPlayer.StartClip(animationPlayer.skinningDataValue.AnimationClips[AnimationClip]);
            }

            // Build Vert Elemets
            List <VertexPositionNormalTextureInstance> verts = new List <VertexPositionNormalTextureInstance>();
            List <int> indx = new List <int>();

            List <VertexPositionNormalTextureInstance> partVerts = new List <VertexPositionNormalTextureInstance>();
            List <int> partIndx = new List <int>();


            for (int d = 0; d < p.Count; d++)
            {
                partVerts.Clear();
                partIndx.Clear();

                for (int v = 0; v < p[d].Count; v++)
                {
                    verts.Add(new VertexPositionNormalTextureInstance(p[d][v], n[d][v], tang[d][v], t[d][v], bi[d][v], bw[d][v]));
                    indx.Add(i[d][v]);

                    partVerts.Add(new VertexPositionNormalTextureInstance(p[d][v], n[d][v], tang[d][v], t[d][v], bi[d][v], bw[d][v]));
                    partIndx.Add(i[d][v]);
                }

                partVertexBuffer.Add(new VertexBuffer(Game.GraphicsDevice, typeof(VertexPositionNormalTextureInstance), partVerts.Count, BufferUsage.WriteOnly));
                partVertexBuffer[partVertexBuffer.Count - 1].SetData(partVerts.ToArray());

                partIndexBuffer.Add(new IndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, partIndx.Count, BufferUsage.WriteOnly));
                partIndexBuffer[partIndexBuffer.Count - 1].SetData(partIndx.ToArray());
            }



            vertCount         = verts.Count;
            modelVertexBuffer = new VertexBuffer(Game.GraphicsDevice, typeof(VertexPositionNormalTextureInstance), vertCount, BufferUsage.WriteOnly);
            modelVertexBuffer.SetData(verts.ToArray());
            indexBuffer = new IndexBuffer(Game.GraphicsDevice, IndexElementSize.ThirtyTwoBits, indx.Count, BufferUsage.WriteOnly);
            indexBuffer.SetData(indx.ToArray());
        }
Exemple #51
0
        public void CreateGeometry(GraphicsDevice device)
        {
            Color[] texels = new Color[alturas.Height * alturas.Width];
            alturas.GetData <Color>(texels);
            alturasTextura = new float[alturas.Height * alturas.Width];
            vertexCount    = alturas.Width * alturas.Height;
            vertices       = new VertexPositionNormalTexture[vertexCount];

            for (int x = 0; x < alturas.Width; x++)
            {
                for (int z = 0; z < alturas.Height; z++)
                {
                    Color c = texels[z * alturas.Width + x];
                    float y = c.R * escala;
                    v = new VertexPositionNormalTexture(new Vector3(x, y, z), Vector3.Up, new Vector2(x % 2, z % 2));
                    vertices[z * alturas.Width + x]       = v;
                    alturasTextura[z * alturas.Width + x] = y;
                }
            }
            vertexBuffer = new VertexBuffer(device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.None);
            vertexBuffer.SetData <VertexPositionNormalTexture>(vertices);

            //Normais
            vectorNormal = new Vector3[vectorCount];

            //Canto superior esquerdo
            for (int x = 0; x < 1; x++)
            {
                for (int z = 0; z < 1; z++)
                {
                    Vector3 v1 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z + 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v4 = Vector3.Cross(v1, v2);
                    Vector3 v5 = Vector3.Cross(v2, v3);
                    Vector3 v6 = Vector3.Cross(v3, v1);
                    Vector3.Normalize(v4);
                    Vector3.Normalize(v5);
                    Vector3.Normalize(v6);
                    vectorNormal[z * alturas.Width + x] = (v4 + v5 + v6) / 3;
                }
            }

            //Canto superior direito
            for (int x = alturas.Width - 1; x < alturas.Width; x++)
            {
                for (int z = 0; z < 1; z++)
                {
                    Vector3 v1 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z + 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v4 = Vector3.Cross(v1, v2);
                    Vector3 v5 = Vector3.Cross(v2, v3);
                    Vector3 v6 = Vector3.Cross(v3, v1);
                    Vector3.Normalize(v4);
                    Vector3.Normalize(v5);
                    Vector3.Normalize(v6);
                    vectorNormal[z * alturas.Width + x] = (v4 + v5 + v6) / 3;
                }
            }
            //Canto inferior esquerdo
            for (int x = 0; x < 1; x++)
            {
                for (int z = alturas.Height - 1; z < alturas.Height; z++)
                {
                    Vector3 v1 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z - 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v4 = Vector3.Cross(v1, v2);
                    Vector3 v5 = Vector3.Cross(v2, v3);
                    Vector3 v6 = Vector3.Cross(v3, v1);
                    Vector3.Normalize(v4);
                    Vector3.Normalize(v5);
                    Vector3.Normalize(v6);
                    vectorNormal[z * alturas.Width + x] = (v4 + v5 + v6) / 3;
                }
            }

            //Canto inferior direito
            for (int x = alturas.Width - 1; x < alturas.Width; x++)
            {
                for (int z = alturas.Height - 1; z < alturas.Height; z++)
                {
                    Vector3 v1 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z - 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v4 = Vector3.Cross(v1, v2);
                    Vector3 v5 = Vector3.Cross(v2, v3);
                    Vector3 v6 = Vector3.Cross(v3, v1);
                    Vector3.Normalize(v4);
                    Vector3.Normalize(v5);
                    Vector3.Normalize(v6);
                    vectorNormal[z * alturas.Width + x] = (v4 + v5 + v6) / 3;
                }
            }
            //Aresta superior
            for (int x = 1; x < alturas.Width - 1; x++)
            {
                for (int z = 0; z < 1; z++)
                {
                    Vector3 v1 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z + 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v4 = vertices[(z + 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v5 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v6  = Vector3.Cross(v1, v2);
                    Vector3 v7  = Vector3.Cross(v2, v3);
                    Vector3 v8  = Vector3.Cross(v3, v4);
                    Vector3 v9  = Vector3.Cross(v4, v5);
                    Vector3 v10 = Vector3.Cross(v5, v1);

                    Vector3.Normalize(v6);
                    Vector3.Normalize(v7);
                    Vector3.Normalize(v8);
                    Vector3.Normalize(v9);
                    vectorNormal[z * alturas.Width + x] = (v6 + v7 + v8 + v9) / 4;
                }
            }
            //Aresta esquerda
            for (int x = 0; x < 1; x++)
            {
                for (int z = 1; z < alturas.Height - 1; z++)
                {
                    Vector3 v1 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z + 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v4 = vertices[(z - 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v5 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v6  = Vector3.Cross(v1, v2);
                    Vector3 v7  = Vector3.Cross(v2, v3);
                    Vector3 v8  = Vector3.Cross(v3, v4);
                    Vector3 v9  = Vector3.Cross(v4, v5);
                    Vector3 v10 = Vector3.Cross(v5, v1);

                    Vector3.Normalize(v6);
                    Vector3.Normalize(v7);
                    Vector3.Normalize(v8);
                    Vector3.Normalize(v9);
                    vectorNormal[z * alturas.Width + x] = (v6 + v7 + v8 + v9) / 4;
                }
            }
            //Aresta inferior
            for (int x = 1; x < alturas.Width - 1; x++)
            {
                for (int z = alturas.Height - 1; z < alturas.Height; z++)
                {
                    Vector3 v1 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z - 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v4 = vertices[(z - 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v5 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v6  = Vector3.Cross(v1, v2);
                    Vector3 v7  = Vector3.Cross(v2, v3);
                    Vector3 v8  = Vector3.Cross(v3, v4);
                    Vector3 v9  = Vector3.Cross(v4, v5);
                    Vector3 v10 = Vector3.Cross(v5, v1);

                    Vector3.Normalize(v6);
                    Vector3.Normalize(v7);
                    Vector3.Normalize(v8);
                    Vector3.Normalize(v9);
                    vectorNormal[z * alturas.Width + x] = (v6 + v7 + v8 + v9) / 4;
                }
            }
            //Aresta direita
            for (int x = alturas.Width - 1; x < alturas.Width; x++)
            {
                for (int z = 1; z < alturas.Height - 1; z++)
                {
                    Vector3 v1 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z - 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v4 = vertices[(z + 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v5 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v6  = Vector3.Cross(v1, v2);
                    Vector3 v7  = Vector3.Cross(v2, v3);
                    Vector3 v8  = Vector3.Cross(v3, v4);
                    Vector3 v9  = Vector3.Cross(v4, v5);
                    Vector3 v10 = Vector3.Cross(v5, v1);

                    Vector3.Normalize(v6);
                    Vector3.Normalize(v7);
                    Vector3.Normalize(v8);
                    Vector3.Normalize(v9);
                    vectorNormal[z * alturas.Width + x] = (v6 + v7 + v8 + v9) / 4;
                }
            }
            //Miolo
            for (int x = 1; x < alturas.Width - 1; x++)
            {
                for (int z = 1; z < alturas.Height - 1; z++)
                {
                    Vector3 v1 = vertices[(z + 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v2 = vertices[(z + 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v3 = vertices[z * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v4 = vertices[(z - 1) * alturas.Width + (x + 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v5 = vertices[(z - 1) * alturas.Width + x].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v6 = vertices[(z - 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v7 = vertices[z * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;
                    Vector3 v8 = vertices[(z + 1) * alturas.Width + (x - 1)].Position - vertices[(z * alturas.Width + x)].Position;

                    Vector3 v10 = Vector3.Cross(v1, v2);
                    Vector3 v11 = Vector3.Cross(v2, v3);
                    Vector3 v12 = Vector3.Cross(v3, v4);
                    Vector3 v13 = Vector3.Cross(v4, v5);
                    Vector3 v14 = Vector3.Cross(v5, v6);
                    Vector3 v15 = Vector3.Cross(v6, v7);
                    Vector3 v16 = Vector3.Cross(v7, v8);
                    Vector3 v17 = Vector3.Cross(v8, v1);

                    Vector3.Normalize(v10);
                    Vector3.Normalize(v11);
                    Vector3.Normalize(v12);
                    Vector3.Normalize(v13);
                    Vector3.Normalize(v14);
                    Vector3.Normalize(v15);
                    Vector3.Normalize(v16);
                    Vector3.Normalize(v17);
                    vectorNormal[z * alturas.Width + x] = (v10 + v11 + v12 + v13 + v14 + v15 + v16 + v17) / 8;
                }
            }


            for (int x = 0; x < alturas.Width; x++)
            {
                for (int z = 0; z < alturas.Height; z++)
                {
                    Color c = texels[z * alturas.Width + x];
                    float y = c.R * escala;
                    v = new VertexPositionNormalTexture(new Vector3(x, y, z), vectorNormal[z * alturas.Width + x], new Vector2(x % 2, z % 2));
                    vertices[z * alturas.Width + x]       = v;
                    alturasTextura[z * alturas.Width + x] = y;
                }
            }
            vertexBuffer = new VertexBuffer(device, typeof(VertexPositionNormalTexture), vertices.Length, BufferUsage.None);
            vertexBuffer.SetData <VertexPositionNormalTexture>(vertices);


            //Usaremos strips verticais
            indexCount = alturas.Height * 2 * (alturas.Width - 1);
            indices    = new short[indexCount];
            for (int ix = 0; ix < alturas.Width - 1; ix++)
            {
                for (int iz = 0; iz < alturas.Height; iz++)
                {
                    indices[2 * iz + 0 + ix * 2 * alturas.Height] = (short)(iz * alturas.Width + ix);
                    indices[2 * iz + 1 + ix * 2 * alturas.Height] = (short)(iz * alturas.Width + 1 + ix);
                }
            }

            indexBuffer = new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None);
            indexBuffer.SetData <short>(indices);
        }
Exemple #52
0
 public void Draw(IndexBuffer indexbuffer, IAttributeBuffer vertexbuffer, IAttributeBuffer texturebuffer, Texture2D texture, int count, bool alphablending = true)
 {
     Apply(texture.ID, indexbuffer, vertexbuffer, texturebuffer, alphablending);
     GL.DrawElements(BeginMode.Triangles, count, DrawElementsType.UnsignedShort, IntPtr.Zero);
 }
Exemple #53
0
        private void Init(TreeSkeleton skeleton)
        {
            if (skeleton.Leaves.Count == 0)
            {
                return;
            }

            Matrix[] transforms = new Matrix[skeleton.Branches.Count];
            skeleton.CopyAbsoluteBranchTransformsTo(transforms);

            Vector3 center = Vector3.Zero;

            for (int i = 0; i < skeleton.Leaves.Count; i++)
            {
                center += transforms[skeleton.Leaves[i].ParentIndex].Translation;
            }
            center = center / (float)skeleton.Leaves.Count;

            LeafVertex[] vertices = new LeafVertex[skeleton.Leaves.Count * 4];
            short[]      indices  = new short[skeleton.Leaves.Count * 6];

            int vindex = 0;
            int iindex = 0;

            boundingSphere.Center = center;
            boundingSphere.Radius = 0.0f;

            foreach (TreeLeaf leaf in skeleton.Leaves)
            {
                // Get the position of the leaf
                Vector3 position = transforms[leaf.ParentIndex].Translation + transforms[leaf.ParentIndex].Up * skeleton.Branches[leaf.ParentIndex].Length;
                if (skeleton.LeafAxis != null)
                {
                    position += skeleton.LeafAxis.Value * leaf.AxisOffset;
                }

                // Orientation
                Vector2 right = new Vector2((float)Math.Cos(leaf.Rotation), (float)Math.Sin(leaf.Rotation));
                Vector2 up    = new Vector2(-right.Y, right.X);

                // Scale vectors by size
                right = leaf.Size.X * right;
                up    = leaf.Size.Y * up;

                // Choose a normal vector for lighting calculations
                float   distanceFromCenter = Vector3.Distance(position, center);
                Vector3 normal             = (position - center) / distanceFromCenter; // normalize the normal

                //                    0---1
                // Vertex positions:  | \ |
                //                    3---2
                int vidx = vindex;
                vertices[vindex++] = new LeafVertex(position, new Vector2(0, 0), -right + up, leaf.Color, leaf.BoneIndex, normal);
                vertices[vindex++] = new LeafVertex(position, new Vector2(1, 0), right + up, leaf.Color, leaf.BoneIndex, normal);
                vertices[vindex++] = new LeafVertex(position, new Vector2(1, 1), right - up, leaf.Color, leaf.BoneIndex, normal);
                vertices[vindex++] = new LeafVertex(position, new Vector2(0, 1), -right - up, leaf.Color, leaf.BoneIndex, normal);

                // Add indices
                indices[iindex++] = (short)(vidx);
                indices[iindex++] = (short)(vidx + 1);
                indices[iindex++] = (short)(vidx + 2);

                indices[iindex++] = (short)(vidx);
                indices[iindex++] = (short)(vidx + 2);
                indices[iindex++] = (short)(vidx + 3);

                // Update the bounding sphere
                float size = leaf.Size.Length() / 2.0f;
                boundingSphere.Radius = Math.Max(boundingSphere.Radius, distanceFromCenter + size);
            }

            // Create the vertex declaration
            vdeclaration = new VertexDeclaration(LeafVertex.VertexElements);

            // Create the buffers
            vbuffer = new VertexBuffer(device, vdeclaration, vertices.Length, BufferUsage.WriteOnly);
            vbuffer.SetData <LeafVertex>(vertices);

            ibuffer = new IndexBuffer(device, IndexElementSize.SixteenBits, indices.Length, BufferUsage.WriteOnly);
            ibuffer.SetData <short>(indices);

            // Remember the number of leaves
            numleaves = skeleton.Leaves.Count;
        }
Exemple #54
0
        /// <summary>
        /// Removes a display object from the batch.
        /// </summary>
        /// <param name="displayObject">Display object to remove.</param>
        /// <param name="drawer">Instanced model drawer doing the removal.</param>
        public void Remove(ModelDisplayObject displayObject, InstancedModelDrawer drawer)
        {
            //Modify vertex buffer
            var newVertices = new VertexPositionNormalTexture[vertices.Length - displayObject.BatchInformation.VertexCount];

            //Copy the first part back (before the display object)
            Array.Copy(vertices, 0, newVertices, 0, displayObject.BatchInformation.BaseVertexBufferIndex);
            //Copy the second part back (after the display object)
            Array.Copy(vertices, displayObject.BatchInformation.BaseVertexBufferIndex + displayObject.BatchInformation.VertexCount,
                       newVertices, displayObject.BatchInformation.BaseVertexBufferIndex,
                       vertices.Length - (displayObject.BatchInformation.BaseVertexBufferIndex + displayObject.BatchInformation.VertexCount));
            vertices = newVertices;



            //Modify index buffer
            var newIndices = new ushort[indices.Length - displayObject.BatchInformation.IndexCount];

            //Copy the first part back (before the display object)
            Array.Copy(indices, 0, newIndices, 0, displayObject.BatchInformation.BaseIndexBufferIndex);
            //Copy the second part back (after the display object)
            Array.Copy(indices, displayObject.BatchInformation.BaseIndexBufferIndex + displayObject.BatchInformation.IndexCount,
                       newIndices, displayObject.BatchInformation.BaseIndexBufferIndex,
                       indices.Length - (displayObject.BatchInformation.BaseIndexBufferIndex + displayObject.BatchInformation.IndexCount));
            indices = newIndices;
            //The index buffer's data is now wrong though.  We deleted a bunch of vertices.
            //So go through the index buffer starting at the point of deletion and decrease the values appropriately.
            for (int i = displayObject.BatchInformation.BaseIndexBufferIndex; i < indices.Length; i++)
            {
                indices[i] -= (ushort)displayObject.BatchInformation.VertexCount;
            }

            //Modify instancing indices
            var newInstancedVertices = new InstancedVertex[instancedVertices.Length - displayObject.BatchInformation.VertexCount];

            //Copy the first part back (before the display object)
            Array.Copy(instancedVertices, 0, newInstancedVertices, 0, displayObject.BatchInformation.BaseVertexBufferIndex);
            //Copy the second part back (after the display object)
            Array.Copy(instancedVertices, displayObject.BatchInformation.BaseVertexBufferIndex + displayObject.BatchInformation.VertexCount,
                       newInstancedVertices, displayObject.BatchInformation.BaseVertexBufferIndex,
                       instancedVertices.Length - (displayObject.BatchInformation.BaseVertexBufferIndex + displayObject.BatchInformation.VertexCount));
            instancedVertices = newInstancedVertices;
            //Like with the index buffer, go through the buffer starting at the point of deletion and decrease the values appropriately.
            for (int i = displayObject.BatchInformation.BaseVertexBufferIndex; i < instancedVertices.Length; i++)
            {
                instancedVertices[i].InstanceIndex--;
            }

            displayObjects.Remove(displayObject);
            //Move the subsequent display objects list indices and base vertices/indices.
            for (int i = displayObject.BatchInformation.BatchListIndex; i < DisplayObjects.Count; i++)
            {
                DisplayObjects[i].BatchInformation.BatchListIndex--;
                DisplayObjects[i].BatchInformation.BaseVertexBufferIndex -= displayObject.BatchInformation.VertexCount;
                DisplayObjects[i].BatchInformation.BaseIndexBufferIndex  -= displayObject.BatchInformation.IndexCount;
            }
            // Tell ModelDisplayObject that it got removed (batch, indices).
            displayObject.ClearBatchReferences();


            //If there weren't any vertices, this batch is about to die.
            if (displayObjects.Count > 0)
            {
                vertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
                vertexBuffer.SetData(vertices);

                instancingBuffer = new VertexBuffer(graphicsDevice, InstancedVertex.VertexDeclaration, instancedVertices.Length, BufferUsage.WriteOnly);
                instancingBuffer.SetData(instancedVertices);

                indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, indices.Length, BufferUsage.WriteOnly);
                indexBuffer.SetData(indices);

                bindings = new VertexBufferBinding[] { vertexBuffer, instancingBuffer };
            }
        }
Exemple #55
0
        public void VertexDeclaration()
        {
            vb = new VertexBuffer(typeof(CustomVertex.PositionNormalTextured), 18, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionNormalTextured.Format, Pool.Default);

            vertices = new CustomVertex.PositionNormalTextured[18];
            //дно
            float a = -1.5f; //координата Y первой точки
            float b = 3.0f;  //Длина стороны
            float c = 0.0f;  //смещение параллельной стороны относительно начальной стороны по Oy
            float d = 5.0f;  //смещение параллельной стороны относительно начальной стороны по Ox


            vertices[0] = new CustomVertex.PositionNormalTextured(0f, a, 0f, 0f, 0f, 1f, 0f, 0f);
            vertices[1] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, 0f, 0f, 1f, 1f, 0f);
            vertices[2] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 0f, 0f, 1f, 0f, 1f);
            vertices[3] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 0f, 0f, 1f, 0f, 1f);
            vertices[4] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, 0f, 0f, 1f, 1f, 0f);
            vertices[5] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0f, 0f, 0f, 1f, 1f, 1f);

            //передняя левая
            vertices[6] = new CustomVertex.PositionNormalTextured(0f, a, 0f, 1f, 0f, 0f, 1f, 0f);
            vertices[7] = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 1f, 0f, 0f, 0f, 0f);
            vertices[8] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, 1f, 0f, 0f, 0.5f, 0.5f);

            //боковая левая
            float norma1 = (float)Math.Sqrt(25 * c * c + 25 * d * d + d * d * (a + b) * (a + b));

            vertices[9]  = new CustomVertex.PositionNormalTextured(0f, a + b, 0f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 0f, 0f);
            vertices[10] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 1f, 0f);
            vertices[11] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, 5 * c / norma1, -5 * d / norma1, -d * (a + b) / norma1, 0.5f, 0.5f);


            //(5c,-5d,-d(a+b))

            //задняя
            float norma2 = (float)Math.Sqrt(25 * b * b + b * b * d * d);

            vertices[12] = new CustomVertex.PositionNormalTextured(d, c + a + b, 0, -5 * b / norma2, 0f, -b * d / norma2, 1f, 0f);
            vertices[13] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, -5 * b / norma2, 0f, -b * d / norma2, 0f, 0f);
            vertices[14] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, -5 * b / norma2, 0f, -b * d / norma2, 0.5f, 0.5f);

            //(-5b,0,-bd)

            //боковая правая
            float norma3 = (float)Math.Sqrt(25 * c * c + 25 * d * d + a * a * d * d);

            vertices[15] = new CustomVertex.PositionNormalTextured(d, c + a, 0f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 0f, 0f);
            vertices[16] = new CustomVertex.PositionNormalTextured(0f, a, 0f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 1f, 0f);
            vertices[17] = new CustomVertex.PositionNormalTextured(0f, 0f, 5f, -5 * c / norma3, -5 * d / norma3, a * d / norma3, 0.5f, 0.5f);
            //(-5c,5d,ad)
            vb.SetData(vertices, 0, LockFlags.None);

            //индексный буфер показывает, как вершины объединить в треугольники
            ib      = new IndexBuffer(typeof(int), 18, device, Usage.WriteOnly, Pool.Default);
            indices = new int[18];

            //дно - по часовой стрелке
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;
            indices[4] = 4;
            indices[5] = 5;

            indices[6] = 6;
            indices[7] = 7;
            indices[8] = 8;

            indices[9]  = 9;
            indices[10] = 10;
            indices[11] = 11;

            indices[12] = 12;
            indices[13] = 13;
            indices[14] = 14;

            indices[15] = 15;
            indices[16] = 16;
            indices[17] = 17;

            ib.SetData(indices, 0, LockFlags.None);

            ib = new IndexBuffer(typeof(int), indices.Length, device,
                                 Usage.WriteOnly, Pool.Default);

            ib.SetData(indices, 0, LockFlags.None);
        }
Exemple #56
0
 public GeometryData(VertexBuffer vertexBuffer, IndexBuffer indexBuffer, BoundingSphere bounds)
     : this(string.Empty, vertexBuffer, indexBuffer, bounds)
 {
 }
            public void Init()
            {
                // Init the vertex decl.
                if (decl == null)
                {
                    decl = new VertexDeclaration(device, elements);
                }

                // Init the effect.
                if (effect == null)
                {
                    effect = BokuGame.ContentManager.Load <Effect>(BokuGame.Settings.MediaPath + @"Shaders\LightColumn");
                }

                // Load the texture.
                if (texture == null)
                {
                    texture = BokuGame.ContentManager.Load <Texture2D>(BokuGame.Settings.MediaPath + @"Textures\LightColumn");
                }

                //
                // Generate the geometry.
                //

                // Ring
                const int numSegments = 32;

                numTriangles = numSegments * 2 + 2;
                numVertices  = numSegments * 2 + 2;

                const float radius = 1.0f;

                // Init the vertex buffer.
                if (vbuf == null)
                {
                    vbuf = new VertexBuffer(device, typeof(Vertex), numVertices, BufferUsage.WriteOnly);
                }

                // Create local vertices.
                Vertex[] localVerts = new Vertex[numVertices];

                int index = 0;

                for (int i = 0; i < numSegments + 1; i++)
                {
                    float   t      = i * (2.0f * (float)Math.PI) / numSegments;
                    float   s      = (float)Math.Sin(t);
                    float   c      = (float)Math.Cos(t);
                    Vector3 normal = new Vector3(c, s, 0.0f);

                    localVerts[index++] = new Vertex(new Vector3(c * radius, s * radius, 0.0f), normal, new Vector2(t / (2.0f * (float)Math.PI), 1.0f));
                    localVerts[index++] = new Vertex(new Vector3(c * radius, s * radius, 1.0f), normal, new Vector2(t / (2.0f * (float)Math.PI), 0.0f));
                }

                // Copy to vertex buffer.
                vbuf.SetData <Vertex>(localVerts);


                // Create index buffer.
                if (ibuf == null)
                {
                    ibuf = new IndexBuffer(device, numTriangles * 3 * sizeof(ushort), BufferUsage.WriteOnly, IndexElementSize.SixteenBits);
                }

                // Generate the local copy of the data.
                ushort[] localIBuf = new ushort[numTriangles * 3];

                index = 0;
                for (int i = 0; i < numSegments; i++)
                {
                    localIBuf[index++] = (ushort)(0 + i * 2);
                    localIBuf[index++] = (ushort)(1 + i * 2);
                    localIBuf[index++] = (ushort)(2 + i * 2);
                    localIBuf[index++] = (ushort)(2 + i * 2);
                    localIBuf[index++] = (ushort)(1 + i * 2);
                    localIBuf[index++] = (ushort)(3 + i * 2);
                }

                // Copy it to the index buffer.
                ibuf.SetData <ushort>(localIBuf);
            }   // end of RenderObj Init()
Exemple #58
0
 public void SetIndexBuffer(IndexBuffer indexBuffer)
 {
     this.Bind();
     indexBuffer.Bind();
     _indexBuffer = indexBuffer;
 }
Exemple #59
0
        IndexBuffer IDeviceIndexBuffer.GetIndexBuffer(DrawState state)
        {
            GraphicsDevice device = state.graphics;

            ValidateDisposed();

            if (this.ib == null)
            {
                int size = 32;
                if (buffer.CountKnown)
                {
                    size = buffer.Count;
                }

                Type indexType     = BufferIndexType;
                int  instanceCount = 1;

#if XBOX360
                instanceCount = Math.Max(1, this.buffer.instancingCount);
#endif

                if (size == 0)
                {
                    throw new ArgumentException(string.Format("Indices<{0}> data size is zero", typeof(IndexType).Name));
                }
                if ((usage & ResourceUsage.Dynamic) == ResourceUsage.Dynamic)
                {
                    ib = new DynamicIndexBuffer(device, indexType, size * instanceCount, Usage);
                }
                else
                {
                    ib = new IndexBuffer(device, indexType, size * instanceCount, Usage);
                }

                if ((ResourceUsage & ResourceUsage.DynamicSequential) != ResourceUsage.DynamicSequential)
                {
                    int written = buffer.WriteBuffer(state, 0, size * buffer.Stride, ib, this);
                    if (written < buffer.Count)
                    {
                        ib.Dispose();
                        if ((usage & ResourceUsage.Dynamic) == ResourceUsage.Dynamic)
                        {
                            ib = new DynamicIndexBuffer(device, indexType, buffer.Count * instanceCount, Usage);
                        }
                        else
                        {
                            ib = new IndexBuffer(device, indexType, buffer.Count * instanceCount, Usage);
                        }
                        buffer.WriteBuffer(state, 0, buffer.Count * buffer.Stride, ib, this);
                    }
                    this.buffer.ClearDirtyRange();
                }

                if ((usage & ResourceUsage.Dynamic) != ResourceUsage.Dynamic)
                {
                    buffer.ClearBuffer();
                }
            }

            if ((usage & ResourceUsage.Dynamic) == ResourceUsage.Dynamic &&
                ib != null && ((DynamicIndexBuffer)ib).IsContentLost)
            {
                SetDirty();
            }

            if (this.buffer.IsDirty)
            {
                this.buffer.UpdateDirtyRegions(state, this.ib, this);
            }

            return(ib);
        }
Exemple #60
0
        protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container)
        {
            YAMLMappingNode node = base.ExportYAMLRoot(container);

            node.AddSerializedVersion(ToSerializedVersion(container.ExportVersion));
            if (HasLODData(container.ExportVersion))
            {
                node.Add(LODDataName, LODData.ExportYAML(container));
            }
            else
            {
                if (HasUse16bitIndices(container.ExportVersion))
                {
                    node.Add(Use16BitIndicesName, Use16BitIndices);
                }
                if (IsIndexBufferFirst(container.ExportVersion))
                {
                    node.Add(IndexBufferName, IndexBuffer.ExportYAML());
                }
                node.Add(SubMeshesName, SubMeshes.ExportYAML(container));
            }

            if (HasBlendShapes(container.ExportVersion))
            {
                if (HasBlendChannels(container.ExportVersion))
                {
                    node.Add(ShapesName, Shapes.ExportYAML(container));
                }
                else
                {
                    node.Add(ShapesName, BlendShapes.ExportYAML(container));
                    node.Add(ShapeVerticesName, ShapeVertices.ExportYAML(container));
                }
            }
            if (HasBindPose(container.ExportVersion))
            {
                if (IsBindPoseFirst(container.ExportVersion))
                {
                    node.Add(BindPoseName, BindPose.ExportYAML(container));
                }
            }
            if (HasBoneNameHashes(container.ExportVersion))
            {
                node.Add(BoneNameHashesName, BoneNameHashes.ExportYAML(true));
                node.Add(RootBoneNameHashName, RootBoneNameHash);
            }
            if (HasBonesAABB(container.ExportVersion))
            {
                node.Add(BonesAABBName, BonesAABB.ExportYAML(container));
                node.Add(VariableBoneCountWeightsName, VariableBoneCountWeights.ExportYAML(container));
            }

            if (HasMeshCompression(container.ExportVersion))
            {
                node.Add(MeshCompressionName, (byte)MeshCompression);
            }
            if (HasStreamCompression(container.ExportVersion))
            {
                node.Add(StreamCompressionName, StreamCompression);
            }
            if (HasIsReadable(container.ExportVersion))
            {
                node.Add(IsReadableName, IsReadable);
                node.Add(KeepVerticesName, KeepVertices);
                node.Add(KeepIndicesName, KeepIndices);
            }

            if (HasIndexFormat(container.ExportVersion))
            {
                node.Add(IndexFormatName, (int)IndexFormat);
            }

            if (!HasLODData(container.ExportVersion))
            {
                if (!IsIndexBufferFirst(container.ExportVersion))
                {
                    node.Add(IndexBufferName, IndexBuffer.ExportYAML());
                }
            }

            if (HasVertexData(container.ExportVersion))
            {
                if (!IsOnlyVertexData(container.ExportVersion))
                {
                    if (MeshCompression != MeshCompression.Off)
                    {
                        node.Add(VerticesName, Vertices.ExportYAML(container));
                    }
                }
            }
            else
            {
                node.Add(VerticesName, Vertices.ExportYAML(container));
            }

            if (HasSkin(container.ExportVersion))
            {
                node.Add(SkinName, Skin.ExportYAML(container));
            }
            if (HasBindPose(container.ExportVersion))
            {
                if (!IsBindPoseFirst(container.ExportVersion))
                {
                    node.Add(BindPoseName, BindPose.ExportYAML(container));
                }
            }

            if (HasVertexData(container.ExportVersion))
            {
                if (IsOnlyVertexData(container.ExportVersion))
                {
                    node.Add(VertexDataName, VertexData.ExportYAML(container));
                }
                else
                {
                    if (MeshCompression == MeshCompression.Off)
                    {
                        node.Add(VertexDataName, VertexData.ExportYAML(container));
                    }
                    else
                    {
                        node.Add(UVName, UV.ExportYAML(container));
                        node.Add(UV1Name, UV1.ExportYAML(container));
                        node.Add(TangentsName, Tangents.ExportYAML(container));
                        node.Add(NormalsName, Normals.ExportYAML(container));
                        node.Add(ColorsName, Colors.ExportYAML(container));
                    }
                }
            }
            else
            {
                node.Add(UVName, UV.ExportYAML(container));
                if (HasUV1(container.ExportVersion))
                {
                    node.Add(UV1Name, UV1.ExportYAML(container));
                }
                if (HasTangentSpace(container.ExportVersion))
                {
                    node.Add(TangentSpaceName, Tangents.ExportYAML(container));
                }
                else
                {
                    node.Add(TangentsName, Tangents.ExportYAML(container));
                    node.Add(NormalsName, Normals.ExportYAML(container));
                }
            }

            if (HasCompressedMesh(container.ExportVersion))
            {
                node.Add(CompressedMeshName, CompressedMesh.ExportYAML(container));
            }

            node.Add(LocalAABBName, LocalAABB.ExportYAML(container));
            if (!HasVertexData(container.ExportVersion))
            {
                node.Add(ColorsName, Colors.ExportYAML(container));
            }
            if (HasCollisionTriangles(container.ExportVersion))
            {
                node.Add(CollisionTrianglesName, CollisionTriangles.ExportYAML(true));
                node.Add(CollisionVertexCountName, CollisionVertexCount);
            }
            if (HasMeshUsageFlags(container.ExportVersion))
            {
                node.Add(MeshUsageFlagsName, MeshUsageFlags);
            }

            if (HasCollision(container.ExportVersion))
            {
                node.Add(BakedConvexCollisionMeshName, CollisionData.BakedConvexCollisionMesh.ExportYAML());
                node.Add(BakedTriangleCollisionMeshName, CollisionData.BakedTriangleCollisionMesh.ExportYAML());
            }
            if (HasMeshMetrics(container.ExportVersion))
            {
                node.Add(MeshMetricsName + "[0]", MeshMetrics[0]);
                node.Add(MeshMetricsName + "[1]", MeshMetrics[1]);
            }
            if (HasMeshOptimization(container.ExportVersion, container.ExportFlags))
            {
                if (IsMeshOptimizationFlags(container.ExportVersion))
                {
                    node.Add(MeshOptimizationFlagsName, (int)MeshOptimizationFlags);
                }
                else
                {
                    node.Add(MeshOptimizedName, MeshOptimized);
                }
            }
            if (HasStreamData(container.ExportVersion))
            {
                StreamingInfo streamData = new StreamingInfo(true);
                node.Add(StreamDataName, streamData.ExportYAML(container));
            }
            return(node);
        }