/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { OrientationSensor = OrientationSensor.GetDefault(); if (OrientationSensor == null) { SimpleOrientationSensor = SimpleOrientationSensor.GetDefault(); if (SimpleOrientationSensor == null) { throw new Exception("No way of determining orientation"); } } TouchPanel.EnabledGestures = GestureType.Hold | GestureType.Flick | GestureType.HorizontalDrag | GestureType.VerticalDrag | GestureType.DragComplete; vertexBuffer = new DynamicVertexBuffer(graphics.GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.WriteOnly); indexBuffer = new DynamicIndexBuffer(graphics.GraphicsDevice, typeof(ushort), 36, BufferUsage.WriteOnly); basicEffect = new BasicEffect(graphics.GraphicsDevice); //(device, null); basicEffect.LightingEnabled = false; basicEffect.VertexColorEnabled = true; basicEffect.TextureEnabled = false; DepthStencilState depthBufferState = new DepthStencilState(); depthBufferState.DepthBufferEnable = true; GraphicsDevice.DepthStencilState = depthBufferState; TetrisState.Initialize(graphics.GraphicsDevice); Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SuppressSystemOverlays = true; graphics.SupportedOrientations = DisplayOrientation.Portrait; base.Initialize(); }
/// <summary> /// Constructor. /// </summary> protected ParticleSystem(Game game, Tint tint) : base(game) { this.content = game.Content; colorTint = tint; if (colorTint == Tint.Dark) { InitializeSettingsForDark(settings); } else { InitializeSettingsForLight(settings); } particles = new ParticleVertex[settings.MaxParticles]; LoadParticleEffect(); vertexDeclaration = new VertexDeclaration(Game.GraphicsDevice, ParticleVertex.VertexElements); // Create a dynamic vertex buffer. int size = ParticleVertex.SizeInBytes * particles.Length; vertexBuffer = new DynamicVertexBuffer(Game.GraphicsDevice, size, BufferUsage.WriteOnly | BufferUsage.Points); }
public ParticleEmitterPrimitive(Viewer viewer, ParticleEmitterData data, WorldPosition worldPosition) { this.viewer = viewer; this.graphicsDevice = viewer.GraphicsDevice; MaxParticles = (int)(ParticleEmitterViewer.MaxParticlesPerSecond * ParticleEmitterViewer.MaxParticleDuration); Vertices = new ParticleVertex[MaxParticles * VerticiesPerParticle]; VertexDeclaration = new VertexDeclaration(graphicsDevice, ParticleVertex.VertexElements); VertexStride = Marshal.SizeOf(typeof(ParticleVertex)); VertexBuffer = new DynamicVertexBuffer(graphicsDevice, typeof(ParticleVertex), MaxParticles * VerticiesPerParticle, BufferUsage.WriteOnly); VertexBuffer.ContentLost += VertexBuffer_ContentLost; IndexBuffer = InitIndexBuffer(graphicsDevice, MaxParticles * IndiciesPerParticle); EmitterData = data; XNAInitialVelocity = data.XNADirection; XNATargetVelocity = Vector3.Up; ParticlesPerSecond = 0; ParticleDuration = 3; ParticleColor = Color.White; WorldPosition = worldPosition; LastWorldPosition = new WorldPosition(worldPosition); TimeParticlesLastEmitted = (float)viewer.Simulator.GameTime; PerlinStart = new float[] { (float)Viewer.Random.NextDouble() * 30000f, (float)Viewer.Random.NextDouble() * 30000f, (float)Viewer.Random.NextDouble() * 30000f, (float)Viewer.Random.NextDouble() * 30000f, }; }
public void Hook(RTSRenderer renderer, GameState s, int ti, int unit) { // Filter For Unit Types RTSTeam team = s.teams[ti]; Data = team.Race.Units[unit]; // Always Add A Unit To List When Spawned team.OnUnitSpawn += OnUnitSpawn; // Create Instance Buffer visible = new List <RTSUnit>(); instVerts = new VertexRTSAnimInst[Data.MaxCount]; instances = new List <RTSUnit>(Data.MaxCount); dead = new List <RTSUnit>(); for (int i = 0; i < team.Units.Count; i++) { OnUnitSpawn(team.Units[i]); } for (int i = 0; i < instVerts.Length; i++) { instVerts[i] = new VertexRTSAnimInst(Matrix.Identity, 0); } dvbInstances = renderer.CreateDynamicVertexBuffer(VertexRTSAnimInst.Declaration, instVerts.Length, BufferUsage.WriteOnly); dvbInstances.SetData(instVerts); dvbInstances.ContentLost += (sender, args) => { rebuildDVB = true; }; rebuildDVB = false; }
// 頂点をグラボに送信 bool FlushVertexList(List <VertexPositionColorTexture> vertexList, bool vertexColorEnabled, bool textureEnabled, Texture2D texture) { if (vertexList == null || vertexList.Count <= 0) { return(false); } if (textureEnabled && texture == null) { return(false); } if (vertexBuffer == null || vertexBuffer.VertexCount != vertexList.Count) { vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, VertexPositionColorTexture.VertexDeclaration, vertexList.Count, BufferUsage.None); } vertexBuffer.SetData(vertexList.ToArray(), 0, vertexList.Count, SetDataOptions.Discard); GraphicsDevice.BlendState = BlendState.AlphaBlend; GraphicsDevice.DepthStencilState = DepthStencilState.None; GraphicsDevice.SetVertexBuffer(vertexBuffer); GraphicsDevice.RasterizerState = RasterizerState.CullNone; basicEffect.VertexColorEnabled = vertexColorEnabled; basicEffect.TextureEnabled = textureEnabled; if (textureEnabled) { basicEffect.Texture = texture; } return(true); }
public void ContentLostResources() { // https://blogs.msdn.microsoft.com/shawnhar/2007/12/12/virtualizing-the-graphicsdevice-in-xna-game-studio-2-0/ var rt = new RenderTarget2D(gdm.GraphicsDevice, 5, 5); var vb = new DynamicVertexBuffer(gd, VertexPositionColor.VertexDeclaration, 1, BufferUsage.None); var ib = new DynamicIndexBuffer(gd, IndexElementSize.SixteenBits, 1, BufferUsage.None); var rtc = new RenderTargetCube(gd, 1, false, SurfaceFormat.Color, DepthFormat.Depth16); gd.Reset(); Assert.IsTrue(rt.IsContentLost); Assert.IsFalse(rt.IsDisposed); Assert.IsTrue(vb.IsContentLost); Assert.IsFalse(vb.IsDisposed); Assert.IsTrue(ib.IsContentLost); Assert.IsFalse(ib.IsDisposed); Assert.IsTrue(rtc.IsContentLost); Assert.IsFalse(rtc.IsDisposed); rt.Dispose(); vb.Dispose(); ib.Dispose(); rtc.Dispose(); }
protected override void Initialize() { base.Initialize(); // MouseHoverUpdatesOnly = true; representativeGameObject = new GameObject(); representativeGameObject.Sprite.TextureCellsPerRow = 1; c = new SimplexCore.OrthographicCamera(Editor.graphics); cam.Camera = c; cam.Position = Vector2.Zero; cam.TransformSpeed = 0.1f; vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 1000, BufferUsage.WriteOnly); basicEffect = new BasicEffect(GraphicsDevice); msPrev = Mouse.GetState(); GraphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents; m = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1); Sgml.GraphicsDevice = GraphicsDevice; pixel = new Texture2D(GraphicsDevice, 1, 1); pixel.SetData(new[] { Color.White }); Rsize(); UpdateGrid(); previewGrid = Sgml.surface_create(80, 80); }
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); }
/// <summary> /// Loads graphics for the particle system. /// </summary> protected void LoadContent() { LoadParticleEffect(); //_vertexDeclaration = new VertexDeclaration(GameEngine.Device, ParticleVertex.VertexElements); _vertexDeclaration = new VertexDeclaration(ParticleVertex.VertexElements); int size = ParticleVertex.SizeInBytes * particles.Length * 4; //vertexBuffer = new DynamicVertexBuffer(GameEngine.Device, size, BufferUsage.WriteOnly); vertexBuffer = new DynamicVertexBuffer(GameEngine.Device, _vertexDeclaration, size, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(GameEngine.Device, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); }
/// <summary> /// Loads graphics for the particle system. /// </summary> public void LoadContent(GraphicsDevice graphics) { this.graphics = graphics; LoadParticleEffect(); // Create a dynamic vertex buffer. vertexBuffer = new DynamicVertexBuffer(graphics, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(graphics, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); defaultBS = graphics.BlendState; }
private void Allocate() { if (_vertexBuffer == null || _vertexBuffer.IsDisposed) { _vertexBuffer = new DynamicVertexBuffer(_graphicsDevice, typeof(VertexPositionColorTexture), 8192, BufferUsage.WriteOnly); _vertexBufferPosition = 0; //_vertexBuffer.ContentLost += delegate { _vertexBufferPosition = 0; }; } if (_indexBuffer != null && !_indexBuffer.IsDisposed) { return; } if (_fallbackIndexData == null) { _fallbackIndexData = new short[12288]; for (int i = 0; i < 2048; i++) { _fallbackIndexData[i * 6] = (short)(i * 4); _fallbackIndexData[i * 6 + 1] = (short)(i * 4 + 1); _fallbackIndexData[i * 6 + 2] = (short)(i * 4 + 2); _fallbackIndexData[i * 6 + 3] = (short)(i * 4); _fallbackIndexData[i * 6 + 4] = (short)(i * 4 + 2); _fallbackIndexData[i * 6 + 5] = (short)(i * 4 + 3); } } _indexBuffer = new DynamicIndexBuffer(_graphicsDevice, typeof(short), 12288, BufferUsage.WriteOnly); _indexBuffer.SetData(_fallbackIndexData); //_indexBuffer.ContentLost += delegate { _indexBuffer.SetData(_fallbackIndexData); }; }
private void SetUpVertexBuffer() { if (this.mesh == null) { // Per each point we have 2 vertices int verticesNumber = 2 * this.curve.Length; this.vertices = new VertexPositionColorTexture[verticesNumber]; DynamicVertexBuffer vertexBuffer = new DynamicVertexBuffer(VertexPositionColorTexture.VertexFormat); ushort[] indices = new ushort[verticesNumber]; for (ushort i = 0; i < indices.Length; i++) { indices[i] = i; } var indexBuffer = new IndexBuffer(indices); this.mesh = new Mesh( 0, verticesNumber, 0, verticesNumber - 2, vertexBuffer, indexBuffer, PrimitiveType.TriangleStrip); } }
public void CreateDynamicRenderData(List <Microsoft.Xna.Framework.Vector3> positions, List <Color> colors) { vertices = new List <VertexPositionNormalColor>(); for (int count = 0; count < vertexCountWidth - 1; count++) { for (int i = 0; i < vertexCountWidth - 1; i++) { vertices.Add(new VertexPositionNormalColor(positions[i + count * vertexCountWidth], GetAveragedNormal(i, count, positions), colors[i + count * vertexCountWidth])); vertices.Add(new VertexPositionNormalColor(positions[i + (count + 1) * vertexCountWidth], GetAveragedNormal(i, count + 1, positions), colors[i + (count + 1) * vertexCountWidth])); vertices.Add(new VertexPositionNormalColor(positions[i + count * vertexCountWidth + 1], GetAveragedNormal(i + 1, count, positions), colors[i + count * vertexCountWidth + 1])); vertices.Add(new VertexPositionNormalColor(positions[i + count * vertexCountWidth + 1], GetAveragedNormal(i + 1, count, positions), colors[i + count * vertexCountWidth + 1])); vertices.Add(new VertexPositionNormalColor(positions[i + (count + 1) * vertexCountWidth], GetAveragedNormal(i, count + 1, positions), colors[i + (count + 1) * vertexCountWidth])); vertices.Add(new VertexPositionNormalColor(positions[i + (count + 1) * vertexCountWidth + 1], GetAveragedNormal(i + 1, count, positions), colors[i + (count + 1) * vertexCountWidth + 1])); } } effect = new BasicEffect(game.GraphicsDevice, new EffectPool()); effect.VertexColorEnabled = true; effect.TextureEnabled = false; effect.LightingEnabled = true; effect.EnableDefaultLighting(); effect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(0.5f, -1, 0.5f)); dVertexBuffer = new DynamicVertexBuffer(game.GraphicsDevice, typeof(VertexPositionNormalColor), vertexCount, BufferUsage.None); decl = new VertexDeclaration(game.GraphicsDevice, VertexPositionNormalColor.VertexElements); dVertexBuffer.SetData(vertices.ToArray()); }
/// <summary> /// Build the mesh used to draw all trails /// </summary> private void BuildMesh() { if (this.mesh != null) { this.DestroyMesh(); } // Indices this.indices = new ushort[this.nIndices]; DynamicIndexBuffer indexBuffer = new DynamicIndexBuffer(this.indices); this.RenderManager.GraphicsDevice.BindIndexBuffer(indexBuffer); // Vertices this.vertices = new VertexPositionColorTexture[this.nVertices]; DynamicVertexBuffer vertexBuffer = new DynamicVertexBuffer(VertexPositionColorTexture.VertexFormat); vertexBuffer.SetData(this.vertices); this.GraphicsDevice.BindVertexBuffer(vertexBuffer); this.mesh = new Mesh(0, nVertices, 0, nIndices / 3, vertexBuffer, indexBuffer, PrimitiveType.TriangleStrip) { DisableBatch = true }; }
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 ); }
public void Update() { for (int i = 0; i < instances.Count; i++) { instanceTransforms[i] = instances[i].World; } if (instances.Count > 0) { // Make sure our instance data vertex buffer is big enough. (4x4 float matrix) int instanceDataSize = 16 * sizeof(float) * instances.Count; if ((instanceVertexBuffer == null) || (instanceVertexBuffer.VertexCount < instances.Count)) { if (instanceVertexBuffer != null) { instanceVertexBuffer.Dispose(); } instanceVertexBuffer = new DynamicVertexBuffer(vxEngine.GraphicsDevice, instanceVertexDeclaration, instances.Count, BufferUsage.WriteOnly); } // Upload transform matrices to the instance data vertex buffer. instanceVertexBuffer.SetData(instanceTransforms, 0, instances.Count, SetDataOptions.Discard); } }
void InitVertices() { // TriangleStrip 用頂点バッファ作成 this.texVertexBuffer = new DynamicVertexBuffer(this.GraphicsDevice, VertexPositionColorTexture.VertexDeclaration, texVertexSize + 4 * MAX_CPS, BufferUsage.None); for (int y = 0; y < GH; y++) { for (int x = 0; x < GW; x++) { int i = x + y * GW; Vector2 coord = new Vector2(1 - (float)x / GW, (float)y / GH); if (y >= 1) { triangleStripVertices[1 + 2 * x + 2 * GW * (y - 1)] = new VertexPositionColorTexture(Vector3.Zero, Color.White, coord); } if (y <= GH - 2) { triangleStripVertices[2 * x + 2 * GW * y] = new VertexPositionColorTexture(Vector3.Zero, Color.White, coord); } } } for (int i = texVertexSize; i < triangleStripVertices.Length; i++) { triangleStripVertices[i] = new VertexPositionColorTexture(Vector3.Zero, Color.Red, Vector2.Zero); } ResetVertices(); }
private void Allocate() { if (this._vertexBuffer == null || this._vertexBuffer.IsDisposed) { this._vertexBuffer = new DynamicVertexBuffer(this._graphicsDevice, typeof(VertexPositionColorTexture), 8192, BufferUsage.WriteOnly); this._vertexBufferPosition = 0; this._vertexBuffer.ContentLost += (EventHandler <EventArgs>)((_param1, _param2) => this._vertexBufferPosition = 0); } if (this._indexBuffer != null && !this._indexBuffer.IsDisposed) { return; } if (this._fallbackIndexData == null) { this._fallbackIndexData = new short[12288]; for (int index = 0; index < 2048; ++index) { this._fallbackIndexData[index * 6] = (short)(index * 4); this._fallbackIndexData[index * 6 + 1] = (short)(index * 4 + 1); this._fallbackIndexData[index * 6 + 2] = (short)(index * 4 + 2); this._fallbackIndexData[index * 6 + 3] = (short)(index * 4); this._fallbackIndexData[index * 6 + 4] = (short)(index * 4 + 2); this._fallbackIndexData[index * 6 + 5] = (short)(index * 4 + 3); } } this._indexBuffer = new DynamicIndexBuffer(this._graphicsDevice, typeof(short), 12288, BufferUsage.WriteOnly); this._indexBuffer.SetData <short>(this._fallbackIndexData); this._indexBuffer.ContentLost += (EventHandler <EventArgs>)((_param1, _param2) => this._indexBuffer.SetData <short>(this._fallbackIndexData)); }
private void Allocate() { if (this.vertexBuffer == null || this.vertexBuffer.IsDisposed) { this.vertexBuffer = new DynamicVertexBuffer(this.graphicsDevice, typeof(VertexPositionColorTexture), 8192, BufferUsage.WriteOnly); this.vertexBufferPosition = 0; this.vertexBuffer.ContentLost += delegate(object sender, EventArgs e) { this.vertexBufferPosition = 0; }; } if (this.indexBuffer == null || this.indexBuffer.IsDisposed) { if (this.fallbackIndexData == null) { this.fallbackIndexData = new short[12288]; for (int i = 0; i < 2048; i++) { this.fallbackIndexData[i * 6] = (short)(i * 4); this.fallbackIndexData[i * 6 + 1] = (short)(i * 4 + 1); this.fallbackIndexData[i * 6 + 2] = (short)(i * 4 + 2); this.fallbackIndexData[i * 6 + 3] = (short)(i * 4); this.fallbackIndexData[i * 6 + 4] = (short)(i * 4 + 2); this.fallbackIndexData[i * 6 + 5] = (short)(i * 4 + 3); } } this.indexBuffer = new DynamicIndexBuffer(this.graphicsDevice, typeof(short), 12288, BufferUsage.WriteOnly); this.indexBuffer.SetData<short>(this.fallbackIndexData); this.indexBuffer.ContentLost += delegate(object sender, EventArgs e) { this.indexBuffer.SetData<short>(this.fallbackIndexData); }; } }
public ParticleSystem(ParticleSettings settings, Effect effect) { if (settings == null) throw new ArgumentNullException("settings"); if (effect == null) throw new ArgumentNullException("effect"); if (settings.Texture == null) throw new ArgumentException("Texture is null."); Enabled = true; this.settings = settings; //---------------------------------------------------------------- // システム名 Name = settings.Name; //---------------------------------------------------------------- // エフェクト particleEffect = new ParticleEffect(effect); particleEffect.Initialize(settings, settings.Texture); graphicsDevice = particleEffect.GraphicsDevice; //---------------------------------------------------------------- // パーティクル particles = new ParticleVertex[settings.MaxParticles * 4]; for (int i = 0; i < settings.MaxParticles; i++) { particles[i * 4 + 0].Corner = new Short2(-1, -1); particles[i * 4 + 1].Corner = new Short2(1, -1); particles[i * 4 + 2].Corner = new Short2(1, 1); particles[i * 4 + 3].Corner = new Short2(-1, 1); } //---------------------------------------------------------------- // 頂点バッファ vertexBuffer = new DynamicVertexBuffer( graphicsDevice, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); //---------------------------------------------------------------- // インデックス バッファ var indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort) (i * 4 + 0); indices[i * 6 + 1] = (ushort) (i * 4 + 1); indices[i * 6 + 2] = (ushort) (i * 4 + 2); indices[i * 6 + 3] = (ushort) (i * 4 + 0); indices[i * 6 + 4] = (ushort) (i * 4 + 2); indices[i * 6 + 5] = (ushort) (i * 4 + 3); } indexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } if (IndexBuffer != null) { IndexBuffer.Dispose(); } IndexBuffer = null; if (VertexBuffer != null) { VertexBuffer.Dispose(); } VertexBuffer = null; Vertices = null; Indexes = null; disposedValue = true; } }
/// <summary> /// Constructor. /// </summary> /// <param name="graphics"></param> /// <param name="maxSprites">The maximum number of sprites which can be batched.</param> public SpriteRenderer(GraphicsContext graphics, int maxSprites) { if (graphics == null) throw new ArgumentNullException("graphics"); if (maxSprites <= 0) throw new ArgumentOutOfRangeException("maxSprites", "MaxSprites must be >= 1."); this.graphics = graphics; this.vertices = new Vertex[maxSprites * 4]; this.vertexBuffer = new DynamicVertexBuffer<Vertex>(this.graphics); ushort[] indices = new ushort[1024 * 6]; for (ushort i = 0, vertex = 0; i < indices.Length; i += 6, vertex += 4) { indices[i] = vertex; indices[i + 1] = (ushort)(vertex + 1); indices[i + 2] = (ushort)(vertex + 3); indices[i + 3] = (ushort)(vertex + 1); indices[i + 4] = (ushort)(vertex + 2); indices[i + 5] = (ushort)(vertex + 3); } this.indexBuffer = new StaticIndexBuffer<ushort>(this.graphics, indices); this.transform = new Matrix4() { M33 = 1f, M44 = 1f, M41 = -1f, M42 = 1f }; }
/// <summary> /// Resets the vertex buffer object from the verticies. /// <param Name="device">GPU to draw with.</param></summary> public virtual void ResetBuffer(GraphicsDevice device) { //if(DwarfGame.ExitGame) //{ // return; //} //lock (VertexLock) { if (VertexBuffer != null && !VertexBuffer.IsDisposed) { VertexBuffer.Dispose(); } VertexBuffer = null; if (IndexBuffer != null && !IndexBuffer.IsDisposed) { IndexBuffer.Dispose(); } IndexBuffer = null; if (IndexCount <= 0 && Indexes != null) { IndexCount = Indexes.Length; } if (VertexCount <= 0 && Vertices != null) { VertexCount = Vertices.Length; } if (Vertices != null) { try { VertexBuffer = new DynamicVertexBuffer(device, ExtendedVertex.VertexDeclaration, Vertices.Length, BufferUsage.WriteOnly); VertexBuffer.SetData(Vertices, 0, VertexCount); } catch (Exception exception) { Console.Out.WriteLine(exception.ToString()); VertexBuffer = null; } } if (Indexes != null) { try { IndexBuffer = new DynamicIndexBuffer(device, typeof(ushort), Indexes.Length, BufferUsage.None); IndexBuffer.SetData(Indexes, 0, IndexCount); } catch (Exception exception) { Console.Out.WriteLine(exception.ToString()); IndexBuffer = null; } } } }
public override DrawGroup <Sprite> ApplyChanges() { if (!dataModified) { return(this); } int vertexCount = (int)count * 4; transformBuffer?.Dispose(); transformBuffer = new DynamicVertexBuffer(graphicsDevice, typeof(VertexTransform), (int)count, BufferUsage.WriteOnly); transformBuffer.SetData(transforms, 0, (int)count); colorBuffer?.Dispose(); colorBuffer = new DynamicVertexBuffer(graphicsDevice, typeof(VertexColor), (int)count, BufferUsage.WriteOnly); colorBuffer.SetData(colors, 0, (int)count); textureCoordBuffer?.Dispose(); textureCoordBuffer = new DynamicVertexBuffer(graphicsDevice, typeof(VertexTexture), vertexCount, BufferUsage.WriteOnly); textureCoordBuffer.SetData(textureCoords, 0, vertexCount); vertexBufferBindings = new VertexBufferBinding[] { new VertexBufferBinding(sharedGeometry.VertexPositionBuffer), new VertexBufferBinding(transformBuffer, 0, 1), new VertexBufferBinding(colorBuffer, 0, 1), new VertexBufferBinding(textureCoordBuffer) }; dataModified = false; return(this); }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here zNear = 0.001f; zFar = 1000.0f; fov = MathHelper.Pi * 70.0f / 180.0f; eye = new Vector3(0.0f, 0.7f, 1.5f); at = new Vector3(0.0f, 0.0f, 0.0f); up = new Vector3(0.0f, 1.0f, 0.0f); cube = new VertexPositionColor[8]; cube[0] = new VertexPositionColor(new Vector3(-0.5f, -0.5f, -0.5f), new Color(0.0f, 0.0f, 0.0f)); cube[1] = new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f), new Color(0.0f, 0.0f, 1.0f)); cube[2] = new VertexPositionColor(new Vector3(-0.5f, 0.5f, -0.5f), new Color(0.0f, 1.0f, 0.0f)); cube[3] = new VertexPositionColor(new Vector3(-0.5f, 0.5f, 0.5f), new Color(0.0f, 1.0f, 1.0f)); cube[4] = new VertexPositionColor(new Vector3( 0.5f, -0.5f, -0.5f), new Color(1.0f, 0.0f, 0.0f)); cube[5] = new VertexPositionColor(new Vector3( 0.5f, -0.5f, 0.5f), new Color(1.0f, 0.0f, 1.0f)); cube[6] = new VertexPositionColor(new Vector3( 0.5f, 0.5f, -0.5f), new Color(1.0f, 1.0f, 0.0f)); cube[7] = new VertexPositionColor(new Vector3( 0.5f, 0.5f, 0.5f), new Color(1.0f, 1.0f, 1.0f)); vertexBuffer = new DynamicVertexBuffer(graphics.GraphicsDevice, typeof(VertexPositionColor), 8, BufferUsage.WriteOnly); indexBuffer = new DynamicIndexBuffer(graphics.GraphicsDevice, typeof(ushort), 36, BufferUsage.WriteOnly); basicEffect = new BasicEffect(graphics.GraphicsDevice); //(device, null); basicEffect.LightingEnabled = false; basicEffect.VertexColorEnabled = true; basicEffect.TextureEnabled = false; graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight; base.Initialize(); }
int index; // current index in buffer public ParticleManager(GraphicsDevice g, int max) { particleMax = max; particles = new Particle[max]; for (int i = 0; i < max; i++) { particles[i] = new Particle(); } vtx = new VertexInfo[max * 4]; for (int i = 0; i < max; i++) { vtx[i * 4 + 0] = new VertexInfo(new Vector4(-500, -500, 0, 1), new Vector2(0, 1)); vtx[i * 4 + 1] = new VertexInfo(new Vector4(-500, 500, 0, 1), new Vector2(0, 0)); vtx[i * 4 + 2] = new VertexInfo(new Vector4(500, -500, 0, 1), new Vector2(1, 1)); vtx[i * 4 + 3] = new VertexInfo(new Vector4(500, 500, 0, 1), new Vector2(1, 0)); } vertexBuffer = new DynamicVertexBuffer(g, typeof(VertexInfo), max * 4, BufferUsage.WriteOnly); vertexBuffer.SetData(vtx); ushort[] idx = new ushort[max * 6]; for (ushort i = 0; i < max; i++) { idx[i * 6 + 0] = (ushort)(i * 4 + 0); idx[i * 6 + 1] = (ushort)(i * 4 + 1); idx[i * 6 + 2] = (ushort)(i * 4 + 2); idx[i * 6 + 3] = (ushort)(i * 4 + 1); idx[i * 6 + 4] = (ushort)(i * 4 + 3); idx[i * 6 + 5] = (ushort)(i * 4 + 2); } indexBuffer = new IndexBuffer(g, typeof(ushort), idx.Length, BufferUsage.WriteOnly); indexBuffer.SetData(idx); }
public ParticleSystem(Game game, ParticleSettings settings, Texture2D texture, Effect effect, ICamera camera) : base(game) { this.settings = settings; this.particleEffect = effect; this.camera = camera; rand = new Random(settings.Seed); EffectParameterCollection parameters = particleEffect.Parameters; effectViewParameter = parameters["View"]; effectProjectionParameter = parameters["Projection"]; effectViewportScaleParameter = parameters["ViewportScale"]; effectTimeParameter = parameters["CurrentTime"]; parameters["Duration"].SetValue((float)settings.Duration.TotalSeconds); parameters["DurationRandomness"].SetValue(settings.DurationRandomness); parameters["Gravity"].SetValue(settings.Gravity); parameters["EndVelocity"].SetValue(settings.EndVelocity); parameters["MinColor"].SetValue(settings.MinColor.ToVector4()); parameters["MaxColor"].SetValue(settings.MaxColor.ToVector4()); parameters["RotateSpeed"].SetValue(new Vector2(settings.MinRotateSpeed, settings.MaxRotateSpeed)); parameters["StartSize"].SetValue(new Vector2(settings.MinStartSize, settings.MaxStartSize)); parameters["EndSize"].SetValue(new Vector2(settings.MinEndSize, settings.MaxEndSize)); parameters["Texture"].SetValue(texture); particles = new ParticleVertex[settings.MaxParticles * 4]; for (int i = 0; i < settings.MaxParticles; i++) { particles[i * 4 + 0].Corner = new Vector2(-1, -1); particles[i * 4 + 1].Corner = new Vector2(1, -1); particles[i * 4 + 2].Corner = new Vector2(1, 1); particles[i * 4 + 3].Corner = new Vector2(-1, 1); } // Create a dynamic vertex buffer. vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); }
public void GenerateInstanceInfo(GraphicsDevice device) { if (_subMeshes.Count == 0) return; if (_instanceTransforms.Length < _subMeshes.Count) _instanceTransforms = new Matrix[_subMeshes.Count * 2]; for (int index = 0; index < _subMeshes.Count; index++) { Mesh.SubMesh subMesh = _subMeshes[index]; _instanceTransforms[index] = subMesh.GlobalTransform; } // If we have more instances than room in our vertex buffer, grow it to the necessary size. if ((_instanceVertexBuffer == null) || (_instanceTransforms.Length > _instanceVertexBuffer.VertexCount)) { if (_instanceVertexBuffer != null) _instanceVertexBuffer.Dispose(); _instanceVertexBuffer = new DynamicVertexBuffer(device, _instanceVertexDeclaration, _instanceTransforms.Length, BufferUsage.WriteOnly); } // Transfer the latest instance transform matrices into the instanceVertexBuffer. _instanceVertexBuffer.SetData(_instanceTransforms, 0, _subMeshes.Count, SetDataOptions.Discard); }
public unsafe void Append(TextAnalyzer analyzer, FontFace font, string text) { var layout = new TextLayout(); var format = new TextFormat { Font = font, Size = 32.0f }; analyzer.AppendText(text, format); analyzer.PerformLayout(0, 32, 1000, 1000, layout); var memBlock = new MemoryBlock(text.Length * 6 * PosColorTexture.Layout.Stride); var mem = (PosColorTexture*)memBlock.Data; foreach (var thing in layout.Stuff) { var width = thing.Width; var height = thing.Height; var region = new Vector4(thing.SourceX, thing.SourceY, width, height) / 4096; var origin = new Vector2(thing.DestX, thing.DestY); *mem++ = new PosColorTexture(origin + new Vector2(0, height), new Vector2(region.X, region.Y + region.W), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin + new Vector2(width, height), new Vector2(region.X + region.Z, region.Y + region.W), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin + new Vector2(width, 0), new Vector2(region.X + region.Z, region.Y), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin, new Vector2(region.X, region.Y), unchecked((int)0xff000000)); count++; } vertexBuffer = new DynamicVertexBuffer(memBlock, PosColorTexture.Layout); }
public override void Initialize() { base.Initialize(); // Partikel-Vertices und Indices anlegen particles = new ParticleVertex[maxParticles * 4]; indices = new ushort[maxParticles * 6]; // Vertices und Indices initialisieren for (int i = 0; i < maxParticles; i++) { particles[i * 4 + 0] = new ParticleVertex(new Vector2(0, 0)); particles[i * 4 + 1] = new ParticleVertex(new Vector2(1, 0)); particles[i * 4 + 2] = new ParticleVertex(new Vector2(1, 1)); particles[i * 4 + 3] = new ParticleVertex(new Vector2(0, 1)); indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 2); indices[i * 6 + 4] = (ushort)(i * 4 + 3); indices[i * 6 + 5] = (ushort)(i * 4 + 0); } // Vertex- und IndexBuffer anlegen indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, typeof(ParticleVertex), particles.Length, BufferUsage.WriteOnly); // Indices in den Buffer kopieren indexBuffer.SetData(indices); }
private void Allocate() { if (this._vertexBuffer == null || ((GraphicsResource)this._vertexBuffer).get_IsDisposed()) { this._vertexBuffer = new DynamicVertexBuffer(this._graphicsDevice, typeof(VertexPositionColorTexture), 8192, (BufferUsage)1); this._vertexBufferPosition = 0; this._vertexBuffer.add_ContentLost((EventHandler <EventArgs>)((sender, e) => this._vertexBufferPosition = 0)); } if (this._indexBuffer != null && !((GraphicsResource)this._indexBuffer).get_IsDisposed()) { return; } if (this._fallbackIndexData == null) { this._fallbackIndexData = new short[12288]; for (int index = 0; index < 2048; ++index) { this._fallbackIndexData[index * 6] = (short)(index * 4); this._fallbackIndexData[index * 6 + 1] = (short)(index * 4 + 1); this._fallbackIndexData[index * 6 + 2] = (short)(index * 4 + 2); this._fallbackIndexData[index * 6 + 3] = (short)(index * 4); this._fallbackIndexData[index * 6 + 4] = (short)(index * 4 + 2); this._fallbackIndexData[index * 6 + 5] = (short)(index * 4 + 3); } } this._indexBuffer = new DynamicIndexBuffer(this._graphicsDevice, typeof(short), 12288, (BufferUsage)1); ((IndexBuffer)this._indexBuffer).SetData <short>((M0[])this._fallbackIndexData); this._indexBuffer.add_ContentLost((EventHandler <EventArgs>)((sender, e) => ((IndexBuffer)this._indexBuffer).SetData <short>((M0[])this._fallbackIndexData))); }
/// <summary> /// Loads graphics for the particle system. /// </summary> public override void Start() { Load(); // Create a dynamic vertex buffer. _vertexBuffer = new DynamicVertexBuffer(Graphics.gD, Vertex.VertexDeclaration, Settings.MaxParticles * 4, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[Settings.MaxParticles * 6]; for (int i = 0; i < Settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } _indexBuffer = new IndexBuffer(Graphics.gD, typeof(ushort), indices.Length, BufferUsage.WriteOnly); _indexBuffer.SetData(indices); }
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 ); }
public SkidMarkBuffer(Vehicle vehicle, int maxSkids) { _maxSkids = maxSkids; _vehicle = vehicle; _vertices = new VertexPositionTexture[_maxSkids * 6]; _skids = new Texture2D[_maxSkids]; _vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements()); // Create a dynamic vertex buffer. //int size = VertexPositionTexture.SizeInBytes * _vertices.Length; int size = VertexPositionTexture.VertexDeclaration.VertexStride * _vertices.Length; _buffer = new DynamicVertexBuffer(GameEngine.Device, _vertexDeclaration, size, BufferUsage.WriteOnly); if (_defaultTexture == null) { MatFile matfile = new MatFile("skidmark.mat"); matfile.Materials[0].ResolveTexture(); _defaultTexture = matfile.Materials[0].Texture; matfile = new MatFile("gibsmear.mat"); matfile.Materials[0].ResolveTexture(); _bloodTexture = matfile.Materials[0].Texture; } _texture = _defaultTexture; }
/// <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); }
/// <summary> /// Efficiently draws several copies of a piece of geometry using hardware instancing. /// </summary> void DrawModelHardwareInstancing(Model model, Matrix[] modelBones, Matrix[] instances, Matrix view, Matrix projection) { var device = graphics.GraphicsDevice; if (instances.Length == 0) { return; } // If we have more instances than room in our vertex buffer, grow it to the neccessary size. if ((instanceVertexBuffer == null) || (instances.Length > instanceVertexBuffer.VertexCount)) { if (instanceVertexBuffer != null) { instanceVertexBuffer.Dispose(); } instanceVertexBuffer = new DynamicVertexBuffer(device, instanceVertexDeclaration, instances.Length, BufferUsage.WriteOnly); } // Transfer the latest instance transform matrices into the instanceVertexBuffer. instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard); foreach (ModelMesh mesh in model.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer. device.SetVertexBuffers( new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0), new VertexBufferBinding(instanceVertexBuffer, 0, 1) ); device.Indices = meshPart.IndexBuffer; // Set up the instance rendering effect. Effect effect = meshPart.Effect; effect.CurrentTechnique = effect.Techniques["HardwareInstancing"]; effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]); effect.Parameters["View"].SetValue(view); effect.Parameters["Projection"].SetValue(projection); // Draw all the instance copies in a single call. foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); device.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount, instances.Length); } } } }
public void CalcVertexBuffer() { if (instanceVertexBuffer != null) instanceVertexBuffer.Dispose(); instanceVertexBuffer = new DynamicVertexBuffer(BaseClass.Device, instanceVertexDeclaration, instanceTransformMatrices.Count, BufferUsage.WriteOnly); instanceVertexBuffer.SetData(instanceTransformMatrices.Values.ToArray(), 0, instanceTransformMatrices.Count, SetDataOptions.Discard); }
protected override void DisposeData() { if (vertexBuffer == null) return; vertexBuffer.Dispose(); indexBuffer.Dispose(); vertexBuffer = null; }
private void CreateBuffers() { var vertexDeclaration = new VertexDeclaration(Format.Stride, nativeVertexFormat.ConvertFrom(Format)); vertexBuffer = new DynamicVertexBuffer(nativeDevice, vertexDeclaration, NumberOfVertices, BufferUsage.WriteOnly); indexBuffer = new DynamicIndexBuffer(nativeDevice, IndexElementSize.SixteenBits, NumberOfIndices, BufferUsage.WriteOnly); }
public void StoreOnGPU(GraphicsDevice device) { GPUMode = true; GPUBlendVertexBuffer = new DynamicVertexBuffer(device, MeshVertex.SizeInBytes * BlendVertexBuffer.Length, BufferUsage.None); GPUBlendVertexBuffer.SetData(BlendVertexBuffer); GPUIndexBuffer = new IndexBuffer(device, sizeof(short) * IndexBuffer.Length, BufferUsage.None, IndexElementSize.SixteenBits); GPUIndexBuffer.SetData(IndexBuffer); }
public DebugDraw(GraphicsDevice device) { vertexBuffer = new DynamicVertexBuffer(device, typeof(VertexPositionColor), MAX_VERTS, BufferUsage.WriteOnly); indexBuffer = new DynamicIndexBuffer(device, typeof(ushort), MAX_INDICES, BufferUsage.WriteOnly); basicEffect = new BasicEffect(device); //(device, null); basicEffect.LightingEnabled = false; basicEffect.VertexColorEnabled = true; basicEffect.TextureEnabled = false; }
public EditingVoxture(string _name, OutpostColor baseColor, GraphicsDevice graphics) { name = new StringBuilder(_name); vox = new Voxture(baseColor); vBuff = new DynamicVertexBuffer(graphics, typeof(VertexPositionColorNormal), numVerts, BufferUsage.WriteOnly); iBuff = new IndexBuffer(graphics, IndexElementSize.SixteenBits, numInds, BufferUsage.WriteOnly); wfVBuff = new DynamicVertexBuffer(graphics, typeof(VertexPositionColor), numWfVerts, BufferUsage.WriteOnly); wfIBuff = new IndexBuffer(graphics, IndexElementSize.SixteenBits, numWfInds, BufferUsage.WriteOnly); makeIndices(); _rotation = Matrix.Identity; }
protected override void Initialize() { //Создаем буффер индексов и вершин graphics.GraphicsDevice.Flush(); vertexBuffer = new DynamicVertexBuffer(graphics.GraphicsDevice, typeof(VertexPositionNormalTexture), vertex.Length, BufferUsage.WriteOnly); indexBuffer = new IndexBuffer(graphics.GraphicsDevice, typeof(int), indices.Length, BufferUsage.WriteOnly); //Создаем вершины для наших частиц. CreateVertex(); //Переносим данные в буффер для видеокарты. indexBuffer.SetData(indices); vertexBuffer.SetData(vertex); //Вызываем иниталайз для базового класса и всех компоненетов, если они у нас есть. base.Initialize(); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="triangleCount">三角形の個数</param> /// <param name="vertices">頂点配列</param> /// <param name="indexBuffer">インデックスバッファ</param> public MMDCPUModelPartP(int triangleCount, MMDVertex[] vertices,int[] vertMap, IndexBuffer indexBuffer) : base(triangleCount, vertices.Length, vertMap, indexBuffer) { this.vertices = vertices; //GPUリソース作成 gpuVertices = new VertexPosition[vertices.Length]; vertexBuffer = new DynamicVertexBuffer(indexBuffer.GraphicsDevice, typeof(VertexPosition), vertices.Length, BufferUsage.WriteOnly); //初期値代入 for (int i = 0; i < vertices.Length; i++) { gpuVertices[i].Position = vertices[i].Position; } // put the vertices into our vertex buffer vertexBuffer.SetData(gpuVertices, 0, vertexCount, SetDataOptions.Discard); }
public void Setup(InstanceTransforms instanceTransforms) { // 頂点バッファーに必要なインスタンスを保持するための容量が足りない場合、バッファー サイズを増やす。 if ((VertexBuffer == null) || (instanceTransforms.Length > VertexBuffer.VertexCount)) { if (VertexBuffer != null) VertexBuffer.Dispose(); VertexBuffer = new DynamicVertexBuffer(GraphicsDevice, instanceVertexDeclaration, instanceTransforms.Length, BufferUsage.WriteOnly); } // 最新のトランスフォーム行列を InstanceVertexBuffer へコピーする。 VertexBuffer.SetData(instanceTransforms.Matrices, 0, instanceTransforms.Length, SetDataOptions.Discard); }
internal CpuSkinnedModelPart(int triangleCount, CpuVertex[] vertices, IndexBuffer indexBuffer) { this.triangleCount = triangleCount; this.vertexCount = vertices.Length; this.cpuVertices = vertices; this.indexBuffer = indexBuffer; // create our GPU resources gpuVertices = new VertexPositionNormalTexture[cpuVertices.Length]; vertexBuffer = new DynamicVertexBuffer(indexBuffer.GraphicsDevice, typeof(VertexPositionNormalTexture), cpuVertices.Length, BufferUsage.WriteOnly); // copy texture coordinates once since they don't change with skinnning for (int i = 0; i < cpuVertices.Length; i++) { gpuVertices[i].TextureCoordinate = cpuVertices[i].TextureCoordinate; } }
protected override void draw(GameTime time, Matrix parent, Matrix transform) { if (this.Lines.Length == 0) return; if (this.vertexBuffer == null || this.vertexBuffer.IsContentLost || this.Lines.Length * 2 > this.vertexBuffer.VertexCount || this.changed) { this.changed = false; if (this.vertexBuffer != null) this.vertexBuffer.Dispose(); this.vertexBuffer = new DynamicVertexBuffer(this.main.GraphicsDevice, VertexPositionColor.VertexDeclaration, (this.Lines.Length * 2) + 8, BufferUsage.WriteOnly); VertexPositionColor[] data = new VertexPositionColor[this.vertexBuffer.VertexCount]; int i = 0; foreach (Line line in this.Lines) { data[i] = line.A; data[i + 1] = line.B; i += 2; } this.vertexBuffer.SetData<VertexPositionColor>(data, 0, this.Lines.Length * 2, SetDataOptions.Discard); } Viewport viewport = this.main.GraphicsDevice.Viewport; float inverseWidth = (viewport.Width > 0) ? (1f / (float)viewport.Width) : 0f; float inverseHeight = (viewport.Height > 0) ? (-1f / (float)viewport.Height) : 0f; Matrix projection = default(Matrix); projection.M11 = inverseWidth * 2f; projection.M22 = inverseHeight * 2f; projection.M33 = 1f; projection.M44 = 1f; projection.M41 = -1f; projection.M42 = 1f; projection.M41 -= inverseWidth; projection.M42 -= inverseHeight; this.effect.Parameters["Color"].SetValue(this.Color); this.effect.Parameters["Transform"].SetValue(transform * projection); this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, this.Lines.Length); Model.DrawCallCounter++; Model.TriangleCounter += this.Lines.Length; }
public ISurfaceAlgorithm(GraphicsDevice device, int resolution, int size, bool _3d, bool indexed = true, int vertex_size = 262144, int index_size = 4000000) { Device = device; Resolution = resolution; Size = size; Is3D = _3d; IsIndexed = indexed; VertexBuffer = new DynamicVertexBuffer(device, VertexPositionColorNormal.VertexDeclaration, vertex_size, BufferUsage.None); OutlineBuffer = new DynamicVertexBuffer(device, VertexPositionColor.VertexDeclaration, index_size, BufferUsage.None); if (indexed) { IndexBuffer = new DynamicIndexBuffer(device, IndexElementSize.ThirtyTwoBits, index_size, BufferUsage.None); Indices = new List<int>(); } Vertices = new List<VertexPositionColorNormal>(); }
void IDrawableAlphaComponent.DrawAlpha(Microsoft.Xna.Framework.GameTime time, RenderParameters p) { if (this.Lines.Count == 0 || LineDrawer.unsupportedTechniques.Contains(p.Technique)) return; if (this.vertexBuffer == null || this.vertexBuffer.IsContentLost || this.Lines.Count * 2 > this.vertexBuffer.VertexCount || this.changed) { this.changed = false; if (this.vertexBuffer != null) this.vertexBuffer.Dispose(); this.vertexBuffer = new DynamicVertexBuffer(this.main.GraphicsDevice, VertexPositionColor.VertexDeclaration, (this.Lines.Count * 2) + 8, BufferUsage.WriteOnly); VertexPositionColor[] data = new VertexPositionColor[this.vertexBuffer.VertexCount]; int i = 0; foreach (Line line in this.Lines) { data[i] = line.A; data[i + 1] = line.B; i += 2; } this.vertexBuffer.SetData<VertexPositionColor>(data, 0, this.Lines.Count * 2, SetDataOptions.Discard); } p.Camera.SetParameters(this.effect); this.effect.Parameters["Depth" + Model.SamplerPostfix].SetValue(p.DepthBuffer); // Draw lines try { this.effect.CurrentTechnique = this.effect.Techniques[p.Technique.ToString()]; } catch (Exception) { LineDrawer.unsupportedTechniques.Add(p.Technique); return; } this.effect.CurrentTechnique.Passes[0].Apply(); this.main.GraphicsDevice.SetVertexBuffer(this.vertexBuffer); this.main.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, this.Lines.Count); }
public void Build(RTSRenderer renderer, RTSFXEntity fx, string technique, string pass, string texture) { vb = renderer.CreateVertexBuffer(VertexPositionTexture.VertexDeclaration, 4, BufferUsage.WriteOnly); vb.SetData(new VertexPositionTexture[] { new VertexPositionTexture(new Vector3(-1, 0, -1), Vector2.Zero), new VertexPositionTexture(new Vector3(1, 0, -1), Vector2.UnitX), new VertexPositionTexture(new Vector3(-1, 0, 1), Vector2.UnitY), new VertexPositionTexture(new Vector3(1, 0, 1), Vector2.One) }); ib = renderer.CreateIndexBuffer(IndexElementSize.ThirtyTwoBits, 6, BufferUsage.WriteOnly); ib.SetData(new int[] { 0, 1, 2, 2, 1, 3 }); dvb = renderer.CreateDynamicVertexBuffer(VertexHealthInstance.Declaration, MAX_COUNT, BufferUsage.WriteOnly); instances = new VertexHealthInstance[MAX_COUNT]; vbBinds = new VertexBufferBinding[]{ new VertexBufferBinding(vb), new VertexBufferBinding(dvb, 0, 1) }; fxPass = fx.GetEffectPass(technique, pass); }
public CanvasRenderer(GraphicsContext graphics, int bufferSize) { if (graphics == null) throw new ArgumentNullException("graphics"); if (bufferSize < 512) throw new ArgumentOutOfRangeException("bufferSize", "bufferSize should be >= 512"); this.graphics = graphics; this.vertices = new Vertex[1024]; this.vertexBuffer = new DynamicVertexBuffer<Vertex>(this.graphics); this.projection = new Matrix4() { M33 = 1f, M44 = 1f, M41 = -1f, M42 = 1f }; }
/// <summary> /// Creates a new particle system from a ParticleSystemSettings object. /// </summary> /// <param name="_settings">The ParticleSystemSettings object.</param> public ParticleSystem(ParticleSystemSettings _settings) { if (_settings.Initialized) { settings = _settings; } else { settings = RendererAssetPool.ParticleSystemSettings["Sample"]; } texture = settings.Texture; particles = new Particle[settings.Capacity]; random = new Random(); currentTime = 0; vertDeclaration = new VertexDeclaration(GraphicOptions.graphics.GraphicsDevice, Particle.VertexElements); vertBuffer = new DynamicVertexBuffer(GraphicOptions.graphics.GraphicsDevice, settings.Capacity * Particle.SizeInBytes, BufferUsage.WriteOnly | BufferUsage.Points); LoadEffect(); }
public void Build() { if (vertices.Count == 0) return; VertexBuffer = new DynamicVertexBuffer(Game.graphics.GraphicsDevice, VertexPositionNormalColor.VertexDeclaration, vertices.Count, BufferUsage.WriteOnly); VertexBuffer.SetData<VertexPositionNormalColor>(vertices.ToArray()); }
public Grid(float size, int width, int height) { Size = size; Width = width; Height = height; if (Root.Instance.UserInterface == null) return; fieldcount = width * height; vertexcount = fieldcount * 4; data = new VertexP3C4[vertexcount]; int i = 0; material = Material.CreateSimpleMaterial(null); material.DepthTest = true; material.DepthWrite = true; material.Additive = true; //float cy = 1.0f / (float)height * size; //float cy = 1.0f / (float)width * size; indices = new IndexBuffer(); indices.buffer = new int[fieldcount * 6]; for (int y = 0; y < height; ++y) { float yp = (float)y * size -(size * height / 2); for (int x = 0; x < width; ++x) { float xp = (float)x * size -(size * width / 2); Color4f color = new Color4f(VecRandom.Instance.NextFloat(), VecRandom.Instance.NextFloat(), VecRandom.Instance.NextFloat(),1); data[i].Color = color; data[i].Position = new Vector3(xp, 0, yp); data[i + 1].Color = color; data[i + 1].Position = new Vector3(xp + size, 0, yp); data[i + 2].Color = color; data[i + 2].Position = new Vector3(xp, 0, yp + size); data[i + 3].Color = color; data[i + 3].Position = new Vector3(xp+size, 0, yp+size); int idx = i / 4 * 6; indices.buffer[idx] = i; indices.buffer[idx+1] = i+1; indices.buffer[idx+2] = i+2; indices.buffer[idx+3] = i+1; indices.buffer[idx+4] = i+3; indices.buffer[idx+5] = i+2; i += 4; } } buffersize=vertexcount * (3+4) * 4; vertices = Root.Instance.UserInterface.Renderer.CreateDynamicVertexBuffer(buffersize); vertices.Format = VertexFormat.VF_P3C4; vertices.Update(data, buffersize); shader = Root.Instance.ResourceManager.LoadShader("simple3d.shader"); }
/// <summary> /// Loads graphics for the particle system. /// </summary> protected override void LoadContent() { LoadParticleEffect(); // Create a dynamic vertex buffer. vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ParticleVertex.VertexDeclaration, settings.MaxParticles * 4, BufferUsage.WriteOnly); // Create and populate the index buffer. ushort[] indices = new ushort[settings.MaxParticles * 6]; for (int i = 0; i < settings.MaxParticles; i++) { indices[i * 6 + 0] = (ushort)(i * 4 + 0); indices[i * 6 + 1] = (ushort)(i * 4 + 1); indices[i * 6 + 2] = (ushort)(i * 4 + 2); indices[i * 6 + 3] = (ushort)(i * 4 + 0); indices[i * 6 + 4] = (ushort)(i * 4 + 2); indices[i * 6 + 5] = (ushort)(i * 4 + 3); } indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); }
/// <summary> /// Efficiently draws several copies of a piece of geometry using hardware instancing. /// </summary> void DrawModelHardwareInstancing() { if (_matrices.Length == 0) return; // If we have more instances than room in our vertex buffer, grow it to the neccessary size. if ((_instanceVertexBuffer == null) || (_matrices.Length > _instanceVertexBuffer.VertexCount)) { if (_instanceVertexBuffer != null) _instanceVertexBuffer.Dispose(); _instanceVertexBuffer = new DynamicVertexBuffer(MyGame.Device, instanceVertexDeclaration, _matrices.Length, BufferUsage.WriteOnly); } // Transfer the latest instance transform matrices into the instanceVertexBuffer. _instanceVertexBuffer.SetData(_matrices, 0, _matrices.Length, SetDataOptions.Discard); Materials.Material.ObjectRenderEffect.Parameters["World"].SetValue(Matrix.Identity); // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer. MyGame.Device.SetVertexBuffers( new VertexBufferBinding(_model.subsets[0].mesh.VertexBuffer, 0, 0), new VertexBufferBinding(_instanceVertexBuffer, 0, 1) ); MyGame.Device.Indices = _model.subsets[0].mesh.IndexBuffer; // Draw all the instance copies in a single call. foreach (var pass in PhysX_test2.Engine.Render.Materials.Material.ObjectRenderEffect.CurrentTechnique.Passes) { pass.Apply(); MyGame.Device.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, _model.subsets[0].mesh.VertexBuffer.VertexCount, 0, _model.subsets[0].mesh.IndexBuffer.IndexCount / 3, _matrices.Length); } }
protected override void DisposeManagedResources() { this.vertexBuffer.Dispose(); this.vertexBuffer = null; }