protected override void OnResourceLoad() { vertexBuffer = new VertexBuffer( Context9.Device, 3 * Marshal.SizeOf( typeof( ColoredVertex ) ), Usage.WriteOnly, VertexFormat.None, Pool.Managed ); var stream = vertexBuffer.Lock( 0, 0, LockFlags.None ); stream.WriteRange( new[] { new ColoredVertex( new Vector3(0.0f, 0.5f, 0.5f), Color.Red.ToArgb() ), new ColoredVertex( new Vector3(0.5f, -0.5f, 0.5f), Color.Blue.ToArgb() ), new ColoredVertex( new Vector3(-0.5f, -0.5f, 0.5f), Color.Green.ToArgb() ), } ); vertexBuffer.Unlock(); // Since this sample does not use any lights, disable lighting (otherwise the // triangle will appear flat black). Context9.Device.SetRenderState( RenderState.Lighting, false ); vertexDecl = new VertexDeclaration(Context9.Device, new[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }); }
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; }
protected void AfterDeviceLost() { this.vertDecl = Vertex.CreateDecl(this.d3device); this.lineVB = new VertexBuffer( this.d3device, (this.lines.Length * 2) * Vertex.Bytes, Usage.WriteOnly, VertexFormat.None, Pool.Managed ); this.d3device.SetRenderState(RenderState.Lighting, false); this.d3device.SetRenderState(RenderState.AlphaBlendEnable, true); this.d3device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); this.d3device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); this.d3device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add); // this.d3device.SetTextureStageState(0, TextureStage.AlphaArg0, TextureArgument.a); var cs = this.ClientSize; this.d3device.SetTransform(TransformState.World, Matrix.Identity); this.d3device.SetTransform( TransformState.Projection, Matrix.OrthoOffCenterLH(-cs.Width / 2, cs.Width / 2, cs.Height / 2, -cs.Height / 2, 0, 1) ); this.d3device.SetTransform( TransformState.View, Matrix.LookAtLH( new Vector3(cs.Width / 2, cs.Height / 2, -1), new Vector3(cs.Width / 2, cs.Height / 2, +1), new Vector3(0, 1, 0) ) ); }
public static void Run() { // Initialize scene object Scene scene = new Scene(); // Initialize Node class object Node cubeNode = new Node("box"); // ExStart:ConvertBoxMeshtoTriangleMeshCustomMemoryLayout // Get mesh of the Box Mesh box = (new Box()).ToMesh(); // Create a customized vertex layout VertexDeclaration vd = new VertexDeclaration(); VertexField position = vd.AddField(VertexFieldDataType.FVector4, VertexFieldSemantic.Position); vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Normal); // Get a triangle mesh TriMesh triMesh = TriMesh.FromMesh(box); // ExEnd:ConvertBoxMeshtoTriangleMeshCustomMemoryLayout // Point node to the Mesh geometry cubeNode.Entity = box; // Add Node to a scene scene.RootNode.ChildNodes.Add(cubeNode); // The path to the documents directory. string MyDir = RunExamples.GetDataDir() + RunExamples.GetOutputFilePath("BoxToTriangleMeshCustomMemoryLayoutScene.fbx"); // Save 3D scene in the supported file formats scene.Save(MyDir, FileFormat.FBX7400ASCII); Console.WriteLine("\n Converted a Box mesh to triangle mesh with custom memory layout of the vertex successfully.\nFile saved at " + MyDir); }
public RenderObjectUnity(AnimatorEditor editor, HashSet<string> meshNames) { HighlightSubmesh = new HashSet<int>(); highlightMaterial = new SlimDX.Direct3D9.Material(); highlightMaterial.Ambient = new Color4(1, 1, 1, 1); highlightMaterial.Diffuse = new Color4(1, 0, 1, 0); this.device = Gui.Renderer.Device; this.tweeningVertDec = new VertexDeclaration(this.device, TweeningWithoutNormalsVertexBufferFormat.ThreeStreams); Textures = new Texture[editor.Textures.Count]; Materials = new SlimDX.Direct3D9.Material[editor.Materials.Count]; rootFrame = CreateHierarchy(editor, meshNames, device, out meshFrames); AnimationController = new AnimationController(numFrames, 30, 30, 1); Frame.RegisterNamedMatrices(rootFrame, AnimationController); if (meshFrames.Count > 0) { Bounds = meshFrames[0].Bounds; for (int i = 1; i < meshFrames.Count; i++) { Bounds = BoundingBox.Merge(Bounds, meshFrames[i].Bounds); } } else { Bounds = new BoundingBox(); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var form = new Form1(); var panel = form.SplitContainer.Panel1; var device = new Device(new Direct3D(), 0, DeviceType.Hardware, panel.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = panel.ClientSize.Width, BackBufferHeight = panel.ClientSize.Height }); var vertices = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); vertices.Lock(0, 0, LockFlags.None).WriteRange(new[] { new Vertex() { Color = Color.Red.ToArgb(), Position = new Vector4(400.0f, 100.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Blue.ToArgb(), Position = new Vector4(650.0f, 500.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Green.ToArgb(), Position = new Vector4(150.0f, 500.0f, 0.5f, 1.0f) } }); vertices.Unlock(); var vertices2 = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); vertices2.Lock(0, 0, LockFlags.None).WriteRange(new[] { new Vertex() { Color = Color.Red.ToArgb(), Position = new Vector4(300.0f, 100.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Blue.ToArgb(), Position = new Vector4(550.0f, 500.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Green.ToArgb(), Position = new Vector4(050.0f, 500.0f, 0.5f, 1.0f) } }); vertices2.Unlock(); var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(device, vertexElems); MessagePump.Run(form, () => { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); device.SetStreamSource(0, vertices, 0, 20); device.VertexDeclaration = vertexDecl; device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); device.SetStreamSource(0, vertices2, 0, 20); device.VertexDeclaration = vertexDecl; device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); device.EndScene(); device.Present(); }); foreach (var item in ObjectTable.Objects) item.Dispose(); }
/// <summary> /// Crear un emisor de particulas /// </summary> /// <param name="texturePath">textura a utilizar</param> /// <param name="particlesCount">cantidad maxima de particlas a generar</param> public ParticleEmitter(string texturePath, int particlesCount) { Device device = GuiController.Instance.D3dDevice; //valores default enabled = true; playing = true; random = new Random(0); creationFrecuency = 1.0f; particleTimeToLive = 5.0f; minSizeParticle = 0.25f; maxSizeParticle = 0.5f; dispersion = 100; speed = new Vector3(1, 1, 1); particleVertexArray = new Particle.ParticleVertex[1]; vertexDeclaration = new VertexDeclaration(device, Particle.ParticleVertexElements); position = new Vector3(0, 0, 0); this.particlesCount = particlesCount; this.particles = new Particle[particlesCount]; this.particlesAlive = new ColaDeParticulas(particlesCount); this.particlesDead = new Stack<Particle>(particlesCount); //Creo todas las particulas. Inicialmente estan todas muertas. for (int i = 0; i < particlesCount; i++) { this.particles[i] = new Particle(); this.particlesDead.Push(this.particles[i]); } //Cargo la textura que tendra cada particula this.texture = TgcTexture.createTexture(device, texturePath); }
internal void Draw(VertexDeclaration vertexDeclaration, RenderSettings settings, IEnumerable<IDecorator> decorators) { _device.VertexDeclaration = vertexDeclaration; foreach (IDecorator decorator in decorators) decorator.OnBeginDrawMesh(this, settings); _device.SetStreamSource(0, _vertexBuffer, 0, VertexPositionNormalTexture.SizeInBytes); _device.Indices = _indexBuffer; _effect.LightDirection = settings.Parameters.LightDirection; _effect.View = settings.ViewMatrix; _effect.Projection = settings.ProjectionMatrix; int passes = _effect.Begin(); for (int i = 0; i < passes; i++) { _effect.BeginPass(i); _device.DrawIndexedPrimitives( PrimitiveType.TriangleList, 0, 0, _numVertices, 0, _primitiveCount); _effect.EndPass(); } _effect.End(); foreach (IDecorator decorator in decorators) decorator.OnEndDrawMesh(this, settings); }
/// <summary> /// Creates a new DrawTechnique using the specified <see cref="BlendMode"/> and <see cref="Duality.Resources.ShaderProgram"/>. /// </summary> /// <param name="blendType"></param> /// <param name="shader"></param> /// <param name="formatPref"></param> public DrawTechnique(BlendMode blendType, ContentRef<ShaderProgram> shader, VertexDeclaration formatPref = null) { this.blendType = blendType; this.shader = shader; this.prefFormat = formatPref; this.prefType = formatPref != null ? formatPref.DataType : null; }
public void Initialize() { vertexDeclaration = new VertexDeclaration(new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Color, VertexElementUsage.Color, 0) } ); basicEffect = new BasicEffect(Game.Game.Graphics.GraphicsDevice); basicEffect.VertexColorEnabled = true; world = Matrix.CreateTranslation(0, 0, 0); basicEffect.World = world; view = Matrix.CreateLookAt( new Vector3(0.0f, 0.0f, 1.0f), Vector3.Zero, Vector3.Up ); basicEffect.View = view; projection = Matrix.CreateOrthographicOffCenter( 0, (float)(Game.Game.Graphics.GraphicsDevice.Viewport.Width - 1), 0, (float)(Game.Game.Graphics.GraphicsDevice.Viewport.Height - 1), 1.0f, 1000.0f); basicEffect.Projection = projection; }
public Grid(Renderer renderer, ShaderProgram shader) { // Render state for grid RenderState = renderer.RenderFactory.CreateRenderState(); RenderState.DepthTest = true; RenderState.DepthMask = true; this.Shader = shader; // Define the format of the control point to render the line VertexDeclaration vd = new VertexDeclaration(); vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Position); // and create a vertex buffer for storing this kind of data this.VertexBuffer = renderer.RenderFactory.CreateVertexBuffer(vd); // Draw the primitive as lines this.DrawOperation = DrawOperation.Lines; this.RenderGroup = RenderQueueGroupId.Geometries; List<FVector3> lines = new List<FVector3>(); for (int i = -10; i <= 10; i++) { // Draw - line lines.Add(new FVector3(i, 0, -10)); lines.Add(new FVector3(i,0, 10)); // Draw | line lines.Add(new FVector3(-10, 0, i)); lines.Add(new FVector3(10, 0, i)); } // Put it to vertex buffer VertexBuffer.LoadData(lines.ToArray()); }
void InitGraphicsResource() { vertexBuffer = new VertexBuffer(SlimMMDXCore.Instance.Device, verticesSource.Length * Marshal.SizeOf(typeof(VertexPNmTx)), Usage.Dynamic, VertexFormat.None, Pool.Default); DataStream stream = vertexBuffer.Lock(0, 0, LockFlags.None); stream.WriteRange(verticesSource); vertexBuffer.Unlock(); vertexDec = new VertexDeclaration(SlimMMDXCore.Instance.Device, VertexPNmTx.VertexElements); }
/// <summary> /// ロストデバイス時に呼び出される /// </summary> protected void OnLostDevice() { vertexBuffer.Dispose(); vertexBuffer = null; vertexDec.Dispose(); vertexDec = null; foreach (MMDModelPart part in Parts) part.OnLostDevice(); }
public NormalsDecorator(Device device) { _device = device; _lineVertexDeclaration = new VertexDeclaration(_device, VertexPositionColor.VertexElements); _lineEffect = new LineEffect(device); _normals = new Dictionary<ModelMesh, NormalBuffers>(); }
public VertexDecl(Device device, VertexElement[] elements) { if (elements == null) return; if (elements[elements.Length - 1] != VertexElement.VertexDeclarationEnd) return; d3d9VertexDecl = new VertexDeclaration(device.RawDevice, elements); }
/// <summary> /// Called by Game1. Initializes textures, buffers, etc. /// </summary> public void loadContent(GraphicsDevice device, ContentManager cm) { _vd = new VertexDeclaration(4 * sizeof(float), VertexFormat.VertexElements); _vb = new VertexBuffer(device, _vd, 6, BufferUsage.WriteOnly); VertexFormat[] data = new VertexFormat[6]; data[0].position.X = -1.0f; data[0].position.Y = 1.0f; data[0].texCoord.X = 0.0f; data[0].texCoord.Y = 0.0f; data[1].position.X = 1.0f; data[1].position.Y = 1.0f; data[1].texCoord.X = 1.0f; data[1].texCoord.Y = 0.0f; data[2].position.X = 1.0f; data[2].position.Y = -1.0f; data[2].texCoord.X = 1.0f; data[2].texCoord.Y = 1.0f; data[3].position.X = -1.0f; data[3].position.Y = 1.0f; data[3].texCoord.X = 0.0f; data[3].texCoord.Y = 0.0f; data[4].position.X = 1.0f; data[4].position.Y = -1.0f; data[4].texCoord.X = 1.0f; data[4].texCoord.Y = 1.0f; data[5].position.X = -1.0f; data[5].position.Y = -1.0f; data[5].texCoord.X = 0.0f; data[5].texCoord.Y = 1.0f; _vb.SetData<VertexFormat>(data, 0, 6); _colorTexture = new Texture2D(device, horRes, vertRes, false, SurfaceFormat.Color); _depthTexture = new Texture2D(device, horRes, vertRes, false, SurfaceFormat.Single); cm.RootDirectory = "Content"; _effect = cm.Load<Effect>("simple"); _effect.Parameters["pixelWidth"].SetValue((float)pixelWidth); _effect.Parameters["pixelHeight"].SetValue((float)pixelHeight); _effect.Parameters["fillColor"].SetValue(fillColor.ToVector4()); _effect.Parameters["horRes"].SetValue(horRes); _effect.Parameters["vertRes"].SetValue(vertRes); }
public HeightMap(int m, int n, string filename, float heightScale, float heightOffset) { this.m = m; this.n = n; this.filename = filename; this.scale = heightScale; this.offset = heightOffset; // Create grid if(CreateFromFile()) BuildGridGeometry(); vd = new VertexDeclaration(Renderer.Instance.device, VertexPosTexNormalTanBitan.Elements); }
internal Model(Scene scene, Device device, VertexDeclaration vertexDeclaration) { SourceScene = scene; _device = device; _vertexDeclaration = vertexDeclaration; _decorators = new List<IDecorator> { new FillModeDecorator(device), new NormalsDecorator(device), new ShadowDecorator(device), new RenderOptionsDecorator(device) }; Meshes = new List<ModelMesh>(); }
public XnaHardwareVertexBuffer( HardwareBufferManagerBase manager, VertexDeclaration vertexDeclaration, int numVertices, BufferUsage usage, XFG.GraphicsDevice dev, bool useSystemMemory, bool useShadowBuffer ) : base( manager, vertexDeclaration, numVertices, usage, useSystemMemory, useShadowBuffer ) { _device = dev; if ( !( vertexDeclaration is XnaVertexDeclaration ) ) { throw new AxiomException ("Invalid VertexDeclaration supplied, must be created by HardwareBufferManager.CreateVertexDeclaration()" ); } if (usage == BufferUsage.Dynamic || usage == BufferUsage.DynamicWriteOnly) { _buffer = new XFG.DynamicVertexBuffer(_device, ( (XnaVertexDeclaration)vertexDeclaration ).XFGVertexDeclaration , numVertices, XnaHelper.Convert(usage)); } else _buffer = new XFG.VertexBuffer(_device, ( (XnaVertexDeclaration)vertexDeclaration ).XFGVertexDeclaration, numVertices, XnaHelper.Convert(usage)); _bufferBytes = new byte[ vertexDeclaration.GetVertexSize() * numVertices]; _bufferBytes.Initialize(); }
public C3Sprite(C3Texture texture) { _arrVertex = new SpriteVertex[4]; for (int i = 0; i < 4; i++) { _arrVertex[i].z = 0.5f; _arrVertex[i].rhw = 1.0f; _arrVertex[i].color = new Color4(255, 255, 255, 255).ToArgb(); } _texture = texture; source = new Rectangle( 0, 0, _texture.width, _texture.height ); CalcCoor(); VertexElement[] vertexElems = new VertexElement[]{ new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0 ), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0 ), new VertexElement(0, 20, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0 ), VertexElement.VertexDeclarationEnd }; _vertexDecl = new VertexDeclaration(Core.Device, vertexElems); }
static ADTStaticData() { short[,] indices = new short[64, 12]; for (short i = 0; i < 8; ++i) { for (short j = 0; j < 8; ++j) { short topLeft = (short)(i * 17 + j); short midPoint = (short)(i * 17 + j + 9); short topRight = (short)(i * 17 + j + 1); short bottomRight = (short)(i * 17 + j + 18); short bottomLeft = (short)((i + 1) * 17 + j); indices[i * 8 + j, 0] = topLeft; indices[i * 8 + j, 1] = midPoint; indices[i * 8 + j, 2] = bottomLeft; indices[i * 8 + j, 3] = topLeft; indices[i * 8 + j, 4] = midPoint; indices[i * 8 + j, 5] = topRight; indices[i * 8 + j, 6] = topRight; indices[i * 8 + j, 7] = midPoint; indices[i * 8 + j, 8] = bottomRight; indices[i * 8 + j, 9] = bottomRight; indices[i * 8 + j, 10] = midPoint; indices[i * 8 + j, 11] = bottomLeft; } } for (short i = 0; i < 64; ++i) for (short j = 0; j < 12; ++j) Indices[i * 12 + j] = (short)(indices[i, j]); LoadTexCoords(); LoadAlphaCoords(); VertexDeclaration = new VertexDeclaration(Game.GameManager.GraphicsThread.GraphicsManager.Device, VertexElements); }
public unsafe static void CompactHalf(ref VertexBufferBinding vertexBufferBinding) { var vertexElementsWithOffsets = vertexBufferBinding.Declaration .EnumerateWithOffsets() .OrderBy(x => x.Offset) .ToArray(); var vertexElements = new VertexElementConvertInfo[vertexElementsWithOffsets.Length]; int currentOffset = 0; for (int index = 0; index < vertexElementsWithOffsets.Length; index++) { var vertexElementConvertInfo = new VertexElementConvertInfo(); vertexElementConvertInfo.VertexElementWithOffset = vertexElementsWithOffsets[index]; var vertexElement = vertexElementsWithOffsets[index].VertexElement; var vertexElementFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format; // First iteration? if (index == 0) { currentOffset = vertexElementsWithOffsets[index].Offset; } vertexElements[index] = vertexElementConvertInfo; vertexElementConvertInfo.OldFormat = vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format; int offsetShift = 0; switch (vertexElementFormat) { case PixelFormat.R32G32_Float: vertexElementFormat = PixelFormat.R16G16_Float; // Adjust next offset if current object has been resized offsetShift = Utilities.SizeOf <Half2>() - Utilities.SizeOf <Vector2>(); break; case PixelFormat.R32G32B32_Float: vertexElementFormat = PixelFormat.R16G16B16A16_Float; // Adjust next offset if current object has been resized offsetShift = Utilities.SizeOf <Half4>() - Utilities.SizeOf <Vector3>(); break; case PixelFormat.R32G32B32A32_Float: vertexElementFormat = PixelFormat.R16G16B16A16_Float; // Adjust next offset if current object has been resized offsetShift = Utilities.SizeOf <Half4>() - Utilities.SizeOf <Vector4>(); break; } // Has format changed? vertexElementConvertInfo.NeedConversion = vertexElementFormat != vertexElementConvertInfo.VertexElementWithOffset.VertexElement.Format; // Create new vertex element with adjusted offset, and maybe new vertex format (if modified) vertexElementConvertInfo.VertexElementWithOffset.VertexElement = new VertexElement(vertexElement.semanticName, vertexElement.SemanticIndex, vertexElementFormat, currentOffset); // Increment next offset by the same difference as in original declaration if (index + 1 < vertexElementsWithOffsets.Length) { currentOffset += vertexElementsWithOffsets[index + 1].Offset - vertexElementsWithOffsets[index].Offset; } currentOffset += offsetShift; vertexElements[index] = vertexElementConvertInfo; } var oldVertexStride = vertexBufferBinding.Declaration.VertexStride; var vertexDeclaration = new VertexDeclaration(vertexElements.Select(x => x.VertexElementWithOffset.VertexElement).ToArray()); var newVertexStride = vertexDeclaration.VertexStride; var newBufferData = new byte[vertexBufferBinding.Count * newVertexStride]; fixed(byte *oldBuffer = &vertexBufferBinding.Buffer.GetSerializationData().Content[vertexBufferBinding.Offset]) fixed(byte *newBuffer = &newBufferData[0]) { var oldBufferVertexPtr = (IntPtr)oldBuffer; var newBufferVertexPtr = (IntPtr)newBuffer; for (int i = 0; i < vertexBufferBinding.Count; ++i) { foreach (var element in vertexElements) { var oldBufferElementPtr = oldBufferVertexPtr + element.VertexElementWithOffset.Offset; var newBufferElementPtr = newBufferVertexPtr + element.VertexElementWithOffset.VertexElement.AlignedByteOffset; if (element.NeedConversion) { // Convert floatX => halfX switch (element.OldFormat) { case PixelFormat.R32G32_Float: *((Half2 *)newBufferElementPtr) = (Half2)(*((Vector2 *)oldBufferElementPtr)); break; case PixelFormat.R32G32B32_Float: // Put 1.0f in *((Half4 *)newBufferElementPtr) = (Half4)(new Vector4(*((Vector3 *)oldBufferElementPtr), 1.0f)); break; case PixelFormat.R32G32B32A32_Float: *((Half4 *)newBufferElementPtr) = (Half4)(*((Vector4 *)oldBufferElementPtr)); break; } } else { // Copy as is Utilities.CopyMemory(newBufferElementPtr, oldBufferElementPtr, element.VertexElementWithOffset.Size); } } oldBufferVertexPtr += oldVertexStride; newBufferVertexPtr += newVertexStride; } } vertexBufferBinding = new VertexBufferBinding(new BufferData(BufferFlags.VertexBuffer, newBufferData).ToSerializableVersion(), vertexDeclaration, vertexBufferBinding.Count); }
private static void ExtractData(ref Microsoft.Xna.Framework.Vector3[] vert, ref int[] ind, IModelo model) { List <Microsoft.Xna.Framework.Vector3> vertices = new List <Microsoft.Xna.Framework.Vector3>(); List <int> indices = new List <int>(); for (int i = 0; i < model.MeshNumber; i++) { BatchInformation[] bi = model.GetBatchInformation(i); for (int j = 0; j < bi.Length; j++) { BatchInformation info = bi[j]; int offset = vertices.Count; Microsoft.Xna.Framework.Vector3[] a = new Microsoft.Xna.Framework.Vector3[info.NumVertices]; // Read the format of the vertex buffer VertexDeclaration declaration = bi[j].VertexBuffer.VertexDeclaration; VertexElement[] vertexElements = declaration.GetVertexElements(); // Find the element that holds the position VertexElement vertexPosition = new VertexElement(); foreach (VertexElement elem in vertexElements) { if (elem.VertexElementUsage == VertexElementUsage.Position && elem.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = elem; // There should only be one break; } } // Check the position element found is valid if (vertexPosition == null || vertexPosition.VertexElementUsage != VertexElementUsage.Position || vertexPosition.VertexElementFormat != VertexElementFormat.Vector3) { throw new Exception("Model uses unsupported vertex format!"); } // This where we store the vertices until transformed // Read the vertices from the buffer in to the array bi[j].VertexBuffer.GetData <Microsoft.Xna.Framework.Vector3>( bi[j].BaseVertex * declaration.VertexStride + vertexPosition.Offset, a, 0, bi[j].NumVertices, declaration.VertexStride); for (int k = 0; k != a.Length; ++k) { Microsoft.Xna.Framework.Vector3.Transform(ref a[k], ref info.ModelLocalTransformation, out a[k]); } vertices.AddRange(a); if (info.IndexBuffer.IndexElementSize != IndexElementSize.SixteenBits) { int[] s = new int[info.PrimitiveCount * 3]; info.IndexBuffer.GetData <int>(info.StartIndex * 2, s, 0, info.PrimitiveCount * 3); for (int k = 0; k != info.PrimitiveCount; ++k) { indices.Add(s[k * 3 + 2] + offset); indices.Add(s[k * 3 + 1] + offset); indices.Add(s[k * 3 + 0] + offset); } } else { short[] s = new short[info.PrimitiveCount * 3]; info.IndexBuffer.GetData <short>(info.StartIndex * 2, s, 0, info.PrimitiveCount * 3); for (int k = 0; k != info.PrimitiveCount; ++k) { indices.Add(s[k * 3 + 2] + offset); indices.Add(s[k * 3 + 1] + offset); indices.Add(s[k * 3 + 0] + offset); } } } } ind = indices.ToArray(); vert = vertices.ToArray(); }
/// <summary> /// Libera los recursos de la malla /// </summary> public void Dispose() { enabled = false; if (boundingBox != null) { boundingBox.Dispose(); } //Si es una instancia no liberar nada, lo hace el original. if (parentInstance != null) { parentInstance = null; return; } //hacer dispose de instancias foreach (var meshInstance in meshInstances) { meshInstance.Dispose(); } meshInstances = null; //Dispose de mesh d3dMesh.Dispose(); d3dMesh = null; //Dispose de texturas if (diffuseMaps != null) { for (var i = 0; i < diffuseMaps.Length; i++) { diffuseMaps[i].dispose(); } diffuseMaps = null; } //Dispose de Box de joints if (skeletonRenderJoints != null) { foreach (var jointBox in skeletonRenderJoints) { jointBox.Dispose(); } skeletonRenderJoints = null; } //Dispose de lineas de Bones if (skeletonRenderBones != null) { foreach (var boneLine in skeletonRenderBones) { if (boneLine != null) { boneLine.Dispose(); } } skeletonRenderBones = null; } //Liberar attachments foreach (var attach in attachments) { attach.Mesh.Dispose(); } attachments = null; //VertexDeclaration vertexDeclaration.Dispose(); vertexDeclaration = null; }
/// <summary> /// Get all the triangles from each mesh part (Changed for XNA 4) /// </summary> /// <param name="meshPart">The meshPart from which we want the datas</param> /// <param name="transform">The transform matrix</param> /// <param name="vertices">The list which will contains all the vertices</param> /// <param name="indices">The list which will contains all the triangles to use with vertices</param> public void ExtractModelMeshPartData(ModelMeshPart meshPart, ref Matrix transform, List <Vector3> vertices, List <TriangleVertexIndices> indices) { int offset = vertices.Count; /* Vertices */ VertexDeclaration declaration = meshPart.VertexBuffer.VertexDeclaration; VertexElement[] vertexElements = declaration.GetVertexElements(); VertexElement vertexPosition = new VertexElement(); foreach (VertexElement vert in vertexElements) { if (vert.VertexElementUsage == VertexElementUsage.Position && vert.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = vert; break; } } if (vertexPosition == null || vertexPosition.VertexElementUsage != VertexElementUsage.Position || vertexPosition.VertexElementFormat != VertexElementFormat.Vector3) { throw new Exception("Model uses unsupported vertex format!"); } Vector3[] allVertex = new Vector3[meshPart.NumVertices]; meshPart.VertexBuffer.GetData <Vector3>( meshPart.VertexOffset * declaration.VertexStride + vertexPosition.Offset, allVertex, 0, meshPart.NumVertices, declaration.VertexStride); for (int i = 0; i != allVertex.Length; ++i) { Vector3.Transform(ref allVertex[i], ref transform, out allVertex[i]); } vertices.AddRange(allVertex); /* Indices */ if (meshPart.IndexBuffer.IndexElementSize != IndexElementSize.SixteenBits) { throw new Exception("Model uses 32-bit indices, which are not supported."); } short[] indexElements = new short[meshPart.PrimitiveCount * 3]; meshPart.IndexBuffer.GetData <short>( meshPart.StartIndex * 2, indexElements, 0, meshPart.PrimitiveCount * 3); TriangleVertexIndices[] tvi = new TriangleVertexIndices[meshPart.PrimitiveCount]; for (int i = 0; i != tvi.Length; ++i) { tvi[i].A = indexElements[i * 3 + 0] + offset; tvi[i].B = indexElements[i * 3 + 1] + offset; tvi[i].C = indexElements[i * 3 + 2] + offset; } indices.AddRange(tvi); }
public void Begin(float[] worldToDeviceFloats) { VertexDeclaration.SetAttributePointers(); ShaderProgram.Begin(); ShaderProgram.SetMatrix3("transform", worldToDeviceFloats); }
public void initialize(float size, GraphicsDeviceManager graphics) { this.size = size; float half_size = size / 2.0f; Vector3 topLeftFront = new Vector3(-half_size, half_size, half_size); Vector3 bottomLeftFront = new Vector3(-half_size, -half_size, half_size); Vector3 topRightFront = new Vector3(half_size, half_size, half_size); Vector3 bottomRightFront = new Vector3(half_size, -half_size, half_size); Vector3 topLeftBack = new Vector3(-half_size, half_size, -half_size); Vector3 topRightBack = new Vector3(half_size, half_size, -half_size); Vector3 bottomLeftBack = new Vector3(-half_size, -half_size, -half_size); Vector3 bottomRightBack = new Vector3(half_size, -half_size, -half_size); vertices = new VertexPositionNormal[36]; // Front face vertices[0].Position = topLeftFront; vertices[0].Normal = new Vector3(0, 0, 1); vertices[1].Position = bottomLeftFront; vertices[1].Normal = new Vector3(0, 0, 1); vertices[2].Position = topRightFront; vertices[2].Normal = new Vector3(0, 0, 1); vertices[3].Position = bottomLeftFront; vertices[3].Normal = new Vector3(0, 0, 1); vertices[4].Position = bottomRightFront; vertices[4].Normal = new Vector3(0, 0, 1); vertices[5].Position = topRightFront; vertices[5].Normal = new Vector3(0, 0, 1); // Back face vertices[6].Position = topLeftBack; vertices[6].Normal = new Vector3(0, 0, -1); vertices[7].Position = topRightBack; vertices[7].Normal = new Vector3(0, 0, -1); vertices[8].Position = bottomLeftBack; vertices[8].Normal = new Vector3(0, 0, -1); vertices[9].Position = bottomLeftBack; vertices[9].Normal = new Vector3(0, 0, -1); vertices[10].Position = topRightBack; vertices[10].Normal = new Vector3(0, 0, -1); vertices[11].Position = bottomRightBack; vertices[11].Normal = new Vector3(0, 0, -1); // Top face vertices[12].Position = topLeftFront; vertices[12].Normal = new Vector3(0, 1, 0); vertices[13].Position = topRightBack; vertices[13].Normal = new Vector3(0, 1, 0); vertices[14].Position = topLeftBack; vertices[14].Normal = new Vector3(0, 1, 0); vertices[15].Position = topLeftFront; vertices[15].Normal = new Vector3(0, 1, 0); vertices[16].Position = topRightFront; vertices[16].Normal = new Vector3(0, 1, 0); vertices[17].Position = topRightBack; vertices[17].Normal = new Vector3(0, 1, 0); // Bottom face vertices[18].Position = bottomLeftFront; vertices[18].Normal = new Vector3(0, -1, 0); vertices[19].Position = bottomLeftBack; vertices[19].Normal = new Vector3(0, -1, 0); vertices[20].Position = bottomRightBack; vertices[20].Normal = new Vector3(0, -1, 0); vertices[21].Position = bottomLeftFront; vertices[21].Normal = new Vector3(0, -1, 0); vertices[22].Position = bottomRightBack; vertices[22].Normal = new Vector3(0, -1, 0); vertices[23].Position = bottomRightFront; vertices[23].Normal = new Vector3(0, -1, 0); // Left face vertices[24].Position = topLeftFront; vertices[24].Normal = new Vector3(-1, 0, 0); vertices[25].Position = bottomLeftBack; vertices[25].Normal = new Vector3(-1, 0, 0); vertices[26].Position = bottomLeftFront; vertices[26].Normal = new Vector3(-1, 0, 0); vertices[27].Position = topLeftBack; vertices[27].Normal = new Vector3(-1, 0, 0); vertices[28].Position = bottomLeftBack; vertices[28].Normal = new Vector3(-1, 0, 0); vertices[29].Position = topLeftFront; vertices[29].Normal = new Vector3(-1, 0, 0); // Right face vertices[30].Position = topRightFront; vertices[30].Normal = new Vector3(1, 0, 0); vertices[31].Position = bottomRightFront; vertices[31].Normal = new Vector3(1, 0, 0); vertices[32].Position = bottomRightBack; vertices[32].Normal = new Vector3(1, 0, 0); vertices[33].Position = topRightBack; vertices[33].Normal = new Vector3(1, 0, 0); vertices[34].Position = topRightFront; vertices[34].Normal = new Vector3(1, 0, 0); vertices[35].Position = bottomRightBack; vertices[35].Normal = new Vector3(1, 0, 0); vertex_declaration = new VertexDeclaration(graphics.GraphicsDevice, VertexPositionNormal.vertex_elements); }
/// <summary> /// /// </summary> private unsafe void CreateGeometry() { // Vertex buffers _subMesh.vertexData = new VertexData(); _subMesh.vertexData.vertexStart = 0; _subMesh.vertexData.vertexCount = (uint)_vertexCount; VertexDeclaration vdecl = _subMesh.vertexData.vertexDeclaration; VertexBufferBinding vbind = _subMesh.vertexData.vertexBufferBinding; uint offset = 0; // Position vdecl.AddElement(0, offset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); // 3D coords vdecl.AddElement(0, offset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_TEXTURE_COORDINATES, 0); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); // Noise coords vdecl.AddElement(0, offset, VertexElementType.VET_FLOAT2, VertexElementSemantic.VES_TEXTURE_COORDINATES, 1); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT2); // Opacity vdecl.AddElement(0, offset, VertexElementType.VET_FLOAT1, VertexElementSemantic.VES_TEXTURE_COORDINATES, 2); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT1); _vertexBuffer = HardwareBufferManager.Singleton.CreateVertexBuffer( offset, (uint)_vertexCount, HardwareBuffer.Usage.HBU_DYNAMIC_WRITE_ONLY); vbind.SetBinding(0, _vertexBuffer); int[] indexbuffer = new int[_numberOfTriangles * 3]; int IndexOffset = 0; int VertexOffset = 0; // C for (int k = 0; k < _nc; k++) { // First triangle indexbuffer[IndexOffset] = VertexOffset; indexbuffer[IndexOffset + 1] = VertexOffset + 1; indexbuffer[IndexOffset + 2] = VertexOffset + 3; // Second triangle indexbuffer[IndexOffset + 3] = VertexOffset; indexbuffer[IndexOffset + 4] = VertexOffset + 3; indexbuffer[IndexOffset + 5] = VertexOffset + 2; IndexOffset += 6; VertexOffset += 4; } // B for (int k = 0; k < _nb; k++) { // First triangle indexbuffer[IndexOffset] = VertexOffset; indexbuffer[IndexOffset + 1] = VertexOffset + 1; indexbuffer[IndexOffset + 2] = VertexOffset + 3; // Second triangle indexbuffer[IndexOffset + 3] = VertexOffset; indexbuffer[IndexOffset + 4] = VertexOffset + 3; indexbuffer[IndexOffset + 5] = VertexOffset + 2; // Third triangle indexbuffer[IndexOffset + 6] = VertexOffset + 2; indexbuffer[IndexOffset + 7] = VertexOffset + 3; indexbuffer[IndexOffset + 8] = VertexOffset + 5; // Fourth triangle indexbuffer[IndexOffset + 9] = VertexOffset + 2; indexbuffer[IndexOffset + 10] = VertexOffset + 5; indexbuffer[IndexOffset + 11] = VertexOffset + 4; IndexOffset += 12; VertexOffset += 6; } // A for (int k = 0; k < _na; k++) { // First triangle indexbuffer[IndexOffset] = VertexOffset; indexbuffer[IndexOffset + 1] = VertexOffset + 1; indexbuffer[IndexOffset + 2] = VertexOffset + 3; // Second triangle indexbuffer[IndexOffset + 3] = VertexOffset; indexbuffer[IndexOffset + 4] = VertexOffset + 3; indexbuffer[IndexOffset + 5] = VertexOffset + 2; // Third triangle indexbuffer[IndexOffset + 6] = VertexOffset + 2; indexbuffer[IndexOffset + 7] = VertexOffset + 3; indexbuffer[IndexOffset + 8] = VertexOffset + 5; // Fourth triangle indexbuffer[IndexOffset + 9] = VertexOffset + 2; indexbuffer[IndexOffset + 10] = VertexOffset + 5; indexbuffer[IndexOffset + 11] = VertexOffset + 4; // Fifth triangle indexbuffer[IndexOffset + 12] = VertexOffset + 4; indexbuffer[IndexOffset + 13] = VertexOffset + 5; indexbuffer[IndexOffset + 14] = VertexOffset + 6; IndexOffset += 15; VertexOffset += 7; } // Prepare buffer for indices _indexBuffer = HardwareBufferManager.Singleton.CreateIndexBuffer(Mogre.HardwareIndexBuffer.IndexType.IT_32BIT, (uint)_numberOfTriangles * 3, HardwareBuffer.Usage.HBU_STATIC, true); fixed(int *addr = &indexbuffer[0]) { _indexBuffer.WriteData( 0, _indexBuffer.SizeInBytes, addr, true); } //indexbufferArr = null; // Set index buffer for this submesh _subMesh.indexData.indexBuffer = _indexBuffer; _subMesh.indexData.indexStart = 0; _subMesh.indexData.indexCount = (uint)_numberOfTriangles * 3; // Create our internal buffer for manipulations _vertices = new Vertex[_vertexCount]; // Update geometry UpdateGeometry(); }
/// <summary> /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match /// the vertex declaration as well as the byte sizes of each element and all be of the same length. /// </summary> /// <param name="data">Array of databuffers representing the vertex data.</param> /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the number of buffers do not match the number /// of vertex elements, or if the number of vertices in each buffer does not match the vertex count, /// or if there is a byte size mismatch of any kind.</exception> public override void SetInterleavedData(params DataBuffer[] data) { if (data == null || data.Length == 0) { throw new ArgumentNullException("data", "Data cannot be null."); } VertexDeclaration vertexDecl = base.VertexDeclaration; int vertexCount = base.VertexCount; //Verify if the incoming vertex streams match right with the supplied vertex declaration VertexElement[] elems = vertexDecl.VertexElements; if (elems.Length != data.Length) { throw new ArgumentOutOfRangeException("data", "Number of vertex streams do not match up the number of declared vertex elements."); } int totalSizeInBytes = 0; int vertexStride = 0; for (int i = 0; i < data.Length; i++) { DataBuffer db = data[i]; VertexElement element = elems[i]; int vSizeInBytes = db.ElementSizeInBytes; int vCount = db.SizeInBytes / vSizeInBytes; if (vCount != vertexCount) { throw new ArgumentOutOfRangeException("data", "Vertex count mismatch, buffers must be of same length."); } if (vSizeInBytes != VertexDeclaration.GetVertexElementSize(element.Format)) { throw new ArgumentOutOfRangeException("data", "Supplied vertex buffer element size mismatch with actual vertex element size."); } totalSizeInBytes += db.SizeInBytes; vertexStride += vSizeInBytes; db.Position = 0; } if (totalSizeInBytes != vertexDecl.VertexStride * vertexCount) { throw new ArgumentOutOfRangeException("data", "Vertex data must match the size of the vertex buffer in bytes!"); } DataBuffer <byte> interleaved = new DataBuffer <byte>(vertexCount * vertexDecl.VertexStride); byte[] vertex = new byte[vertexStride]; for (int i = 0; i < vertexCount; i++) { int startIndex = 0; for (int j = 0; j < data.Length; j++) { DataBuffer db = data[j]; int elementSize = db.ElementSizeInBytes; db.Get(vertex, startIndex, elementSize); startIndex += elementSize; } interleaved.Set(vertex, 0, vertexStride); } _vertexBuffer.SetData <byte>(interleaved.Buffer); }
public void BeginNormalMap() { DXMain.device.RenderState.CullMode = Cull.CounterClockwise; //DXMain.device.RenderState.CullMode=Cull.None; DXMain.device.RenderState.Clipping = true; DXMain.device.VertexFormat = CellVertex.Format; DXMain.device.SetStreamSource(0, vBuffer, 0); DXMain.device.SetStreamSource(1, colorBuffer, 0); VertexDeclaration decl = new VertexDeclaration(DXMain.device, NormalElements); //DXMain.device.RenderState.FillMode = FillMode.WireFrame; DXMain.device.Indices = iBuffer; DXMain.device.VertexDeclaration = decl; /*DXMain.device.BeginScene(); effect.Begin(FX.None); effect.BeginPass(1);*/ }
/// <summary> /// Create a mesh for a RoundLine. /// </summary> /// <remarks> /// The RoundLine mesh has 3 sections: /// 1. Two quads, from 0 to 1 (left to right) /// 2. A half-disc, off the left side of the quad /// 3. A half-disc, off the right side of the quad /// /// The X and Y coordinates of the "normal" encode the rho and theta of each vertex /// The "texture" encodes whether to scale and translate the vertex horizontally by length and radius /// </remarks> private void CreateRoundLineMesh() { const int primsPerCap = 12; // A higher primsPerCap produces rounder endcaps at the cost of more vertices const int verticesPerCap = primsPerCap * 2 + 2; const int primsPerCore = 4; const int verticesPerCore = 8; numInstances = 200; numVertices = (verticesPerCore + verticesPerCap + verticesPerCap) * numInstances; numPrimitivesPerInstance = primsPerCore + primsPerCap + primsPerCap; numPrimitives = numPrimitivesPerInstance * numInstances; numIndices = 3 * numPrimitives; short[] indices = new short[numIndices]; bytesPerVertex = RoundLineVertex.SizeInBytes; RoundLineVertex[] tri = new RoundLineVertex[numVertices]; translationData = new float[numInstances * 4]; // Used in Draw() int iv = 0; int ii = 0; int iVertex; int iIndex; for (int instance = 0; instance < numInstances; instance++) { // core vertices const float pi2 = MathHelper.PiOver2; const float threePi2 = 3 * pi2; iVertex = iv; tri[iv++] = new RoundLineVertex(new Vector3(0.0f, -1.0f, 0), new Vector2(1, threePi2), new Vector2(0, 0), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, -1.0f, 0), new Vector2(1, threePi2), new Vector2(0, 1), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 0.0f, 0), new Vector2(0, threePi2), new Vector2(0, 1), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 0.0f, 0), new Vector2(0, threePi2), new Vector2(0, 0), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 0.0f, 0), new Vector2(0, pi2), new Vector2(0, 1), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 0.0f, 0), new Vector2(0, pi2), new Vector2(0, 0), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 1.0f, 0), new Vector2(1, pi2), new Vector2(0, 1), instance); tri[iv++] = new RoundLineVertex(new Vector3(0.0f, 1.0f, 0), new Vector2(1, pi2), new Vector2(0, 0), instance); // core indices indices[ii++] = (short)(iVertex + 0); indices[ii++] = (short)(iVertex + 1); indices[ii++] = (short)(iVertex + 2); indices[ii++] = (short)(iVertex + 2); indices[ii++] = (short)(iVertex + 3); indices[ii++] = (short)(iVertex + 0); indices[ii++] = (short)(iVertex + 4); indices[ii++] = (short)(iVertex + 6); indices[ii++] = (short)(iVertex + 5); indices[ii++] = (short)(iVertex + 6); indices[ii++] = (short)(iVertex + 7); indices[ii++] = (short)(iVertex + 5); // left halfdisc iVertex = iv; iIndex = ii; for (int i = 0; i < primsPerCap + 1; i++) { float deltaTheta = MathHelper.Pi / primsPerCap; float theta0 = MathHelper.PiOver2 + i * deltaTheta; float theta1 = theta0 + deltaTheta / 2; // even-numbered indices are at the center of the halfdisc tri[iVertex + 0] = new RoundLineVertex(new Vector3(0, 0, 0), new Vector2(0, theta1), new Vector2(0, 0), instance); // odd-numbered indices are at the perimeter of the halfdisc float x = (float)Math.Cos(theta0); float y = (float)Math.Sin(theta0); tri[iVertex + 1] = new RoundLineVertex(new Vector3(x, y, 0), new Vector2(1, theta0), new Vector2(1, 0), instance); if (i < primsPerCap) { // indices follow this pattern: (0, 1, 3), (2, 3, 5), (4, 5, 7), ... indices[iIndex + 0] = (short)(iVertex + 0); indices[iIndex + 1] = (short)(iVertex + 1); indices[iIndex + 2] = (short)(iVertex + 3); iIndex += 3; ii += 3; } iVertex += 2; iv += 2; } // right halfdisc for (int i = 0; i < primsPerCap + 1; i++) { float deltaTheta = MathHelper.Pi / primsPerCap; float theta0 = 3 * MathHelper.PiOver2 + i * deltaTheta; float theta1 = theta0 + deltaTheta / 2; float theta2 = theta0 + deltaTheta; // even-numbered indices are at the center of the halfdisc tri[iVertex + 0] = new RoundLineVertex(new Vector3(0, 0, 0), new Vector2(0, theta1), new Vector2(0, 1), instance); // odd-numbered indices are at the perimeter of the halfdisc float x = (float)Math.Cos(theta0); float y = (float)Math.Sin(theta0); tri[iVertex + 1] = new RoundLineVertex(new Vector3(x, y, 0), new Vector2(1, theta0), new Vector2(1, 1), instance); if (i < primsPerCap) { // indices follow this pattern: (0, 1, 3), (2, 3, 5), (4, 5, 7), ... indices[iIndex + 0] = (short)(iVertex + 0); indices[iIndex + 1] = (short)(iVertex + 1); indices[iIndex + 2] = (short)(iVertex + 3); iIndex += 3; ii += 3; } iVertex += 2; iv += 2; } } vb = new VertexBuffer(device, numVertices * bytesPerVertex, BufferUsage.None); vb.SetData <RoundLineVertex>(tri); vdecl = new VertexDeclaration(device, RoundLineVertex.VertexElements); ib = new IndexBuffer(device, numIndices * 2, BufferUsage.None, IndexElementSize.SixteenBits); ib.SetData <short>(indices); }
public LightConePrimitive(LightViewer lightViewer, RenderProcess renderProcess, Light light) : base(light) { Debug.Assert(light.Type == LightType.Cone, "LightConePrimitive is only for LightType.Cone lights."); if (VertexDeclaration == null) { VertexDeclaration = new VertexDeclaration(LightConeVertex.SizeInBytes, LightConeVertex.VertexElements); } if (VertexBuffer == null) { var vertexData = new LightConeVertex[(CircleSegments + 2) * StateCount]; SetUpTransitions((state, stateIndex1, stateIndex2) => { var state1 = Light.States[stateIndex1]; var state2 = Light.States[stateIndex2]; #if DEBUG_LIGHT_TRANSITIONS Console.WriteLine(" Transition {0} is from state {1} to state {2} over {3:F1}s", state, stateIndex1, stateIndex2, state1.Duration); #endif Vector3 position1, position2, direction1, direction2; float angle1, angle2, radius1, radius2, distance1, distance2; Vector4 color1, color2; LightViewer.CalculateLightCone(state1, out position1, out direction1, out angle1, out radius1, out distance1, out color1); LightViewer.CalculateLightCone(state2, out position2, out direction2, out angle2, out radius2, out distance2, out color2); var direction1Right = Vector3.Cross(direction1, Vector3.UnitY); var direction1Up = Vector3.Cross(direction1Right, direction1); var direction2Right = Vector3.Cross(direction2, Vector3.UnitY); var direction2Up = Vector3.Cross(direction2Right, direction2); for (var i = 0; i < CircleSegments; i++) { var a1 = MathHelper.TwoPi * i / CircleSegments; var a2 = MathHelper.TwoPi * (i + 1) / CircleSegments; var v1 = position1 + direction1 * distance1 + direction1Right * (float)(radius1 * Math.Cos(a1)) + direction1Up * (float)(radius1 * Math.Sin(a1)); var v2 = position2 + direction2 * distance2 + direction2Right * (float)(radius2 * Math.Cos(a2)) + direction2Up * (float)(radius2 * Math.Sin(a2)); vertexData[(CircleSegments + 2) * state + i] = new LightConeVertex(v1, v2, color1, color2); } vertexData[(CircleSegments + 2) * state + CircleSegments + 0] = new LightConeVertex(position1, position2, color1, color2); vertexData[(CircleSegments + 2) * state + CircleSegments + 1] = new LightConeVertex(new Vector3(position1.X, position1.Y, position1.Z - distance1), new Vector3(position2.X, position2.Y, position2.Z - distance2), color1, color2); }); VertexBuffer = new VertexBuffer(renderProcess.GraphicsDevice, VertexDeclaration, vertexData.Length, BufferUsage.WriteOnly); VertexBuffer.SetData(vertexData); } if (IndexBuffer == null) { var indexData = new short[6 * CircleSegments]; for (var i = 0; i < CircleSegments; i++) { var i2 = (i + 1) % CircleSegments; indexData[6 * i + 0] = (short)(CircleSegments + 0); indexData[6 * i + 1] = (short)i2; indexData[6 * i + 2] = (short)i; indexData[6 * i + 3] = (short)i; indexData[6 * i + 4] = (short)i2; indexData[6 * i + 5] = (short)(CircleSegments + 1); } IndexBuffer = new IndexBuffer(renderProcess.GraphicsDevice, typeof(short), indexData.Length, BufferUsage.WriteOnly); IndexBuffer.SetData(indexData); } if (BlendState_SourceZeroDestOne == null) { BlendState_SourceZeroDestOne = new BlendState { ColorSourceBlend = Blend.Zero, ColorDestinationBlend = Blend.One, AlphaSourceBlend = Blend.Zero, AlphaDestinationBlend = Blend.One } } ; UpdateState(lightViewer); }
/// <summary> /// Cambiar el mesh interno de DirectX por uno nuevo. /// Se asume que el nuevo mesh es del mismo RenderType que el anterior. /// </summary> /// <param name="newD3dMesh">Nuevo mesh</param> public void changeD3dMesh(Mesh newD3dMesh) { vertexDeclaration = new VertexDeclaration(newD3dMesh.Device, newD3dMesh.Declaration); d3dMesh.Dispose(); d3dMesh = newD3dMesh; }
private unsafe void createCube(string name, Mogre.Vector3 gpose, double d) { MeshPtr msh = MeshManager.Singleton.CreateManual(name, "General"); SubMesh sub1 = msh.CreateSubMesh("1"); const float sqrt13 = 0.577350269f; /* sqrt(1/3) */ const int nVertices = 8; const int vbufCount = 3 * 2 * nVertices; float[] vertices = new float[vbufCount] { (float)(gpose.x - d / 2), (float)(gpose.y + d / 2), (float)(gpose.z - d / 2), //0 position -sqrt13, sqrt13, -sqrt13, //0 normal A (float)(gpose.x + d / 2), (float)(gpose.y + d / 2), (float)(gpose.z - d / 2), //1 position sqrt13, sqrt13, -sqrt13, //1 normal B (float)(gpose.x + d / 2), (float)(gpose.y - d / 2), (float)(gpose.z - d / 2), //2 position sqrt13, -sqrt13, -sqrt13, //2 normal F (float)(gpose.x - d / 2), (float)(gpose.y - d / 2), (float)(gpose.z - d / 2), //3 position -sqrt13, -sqrt13, -sqrt13, //3 normal H (float)(gpose.x - d / 2), (float)(gpose.y + d / 2), (float)(gpose.z + d / 2), -sqrt13, sqrt13, sqrt13, //4 normal C (float)(gpose.x + d / 2), (float)(gpose.y + d / 2), (float)(gpose.z + d / 2), sqrt13, sqrt13, sqrt13, //5 normal D (float)(gpose.x + d / 2), (float)(gpose.y - d / 2), (float)(gpose.z + d / 2), sqrt13, -sqrt13, sqrt13, //6 normal E (float)(gpose.x - d / 2), (float)(gpose.y - d / 2), (float)(gpose.z + d / 2), -sqrt13, -sqrt13, sqrt13, //7 normal G }; const int ibufCount = 36; ushort[] faces = new ushort[ibufCount] { //back 0, 2, 3, 0, 1, 2, //right 1, 6, 2, 1, 5, 6, //front 4, 6, 5, 4, 7, 6, //left 0, 7, 4, 0, 3, 7, //top 0, 5, 1, 0, 4, 5, //bottom 2, 7, 3, 2, 6, 7 }; sub1.vertexData = new VertexData(); sub1.vertexData.vertexCount = nVertices; VertexDeclaration decl = sub1.vertexData.vertexDeclaration; uint offset = 0; //position decl.AddElement(0, offset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_POSITION); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); //normal decl.AddElement(0, offset, VertexElementType.VET_FLOAT3, VertexElementSemantic.VES_NORMAL); offset += VertexElement.GetTypeSize(VertexElementType.VET_FLOAT3); HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager.Singleton.CreateVertexBuffer(offset, sub1.vertexData.vertexCount, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY); VertexBufferBinding bind = sub1.vertexData.vertexBufferBinding; void *pVertices; fixed(float *pFVertice = vertices) { pVertices = (void *)pFVertice; } vbuf.WriteData(0, vbuf.SizeInBytes, pVertices, true); bind.SetBinding(0, vbuf); void *pFaces; fixed(ushort *pUFaces = faces) { pFaces = (void *)pUFaces; } HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager.Singleton.CreateIndexBuffer(HardwareIndexBuffer.IndexType.IT_16BIT, ibufCount, HardwareBuffer.Usage.HBU_STATIC_WRITE_ONLY); ibuf.WriteData(0, ibuf.SizeInBytes, pFaces, true); sub1.useSharedVertices = false; sub1.indexData.indexBuffer = ibuf; sub1.indexData.indexCount = ibufCount; sub1.indexData.indexStart = 0; sub1.SetMaterialName("Examples/10PointBlock"); msh._setBounds(new AxisAlignedBox(-100, -100, -100, 100, 100, 100)); msh._setBoundingSphereRadius(Mogre.Math.Sqrt(3 * 100 * 100)); msh.Load(); }
public SkinnedModel(IXNAGame _game) { game = _game; BaseShader = new SkinnedShader(game, new EffectPool()); vertexDeclaration = AttributeSystem.CreateVertexDeclaration(game.GraphicsDevice, typeof(SkinnedTangentVertex)); }
public OceanWaterData(RenderSystem rs, int size, float lat) { this.Size = size; geoData = new GeomentryData(); ObjectFactory fac = rs.ObjectFactory; vtxDecl = fac.CreateVertexDeclaration(WaterVertex.Elements); int len = size - 1; int vertexCount = size * size; vertexBuffer = fac.CreateVertexBuffer(vertexCount, vtxDecl, BufferUsage.Static); float rad10 = PlanetEarth.DefaultTileSpan; float radtl = MathEx.Degree2Radian(lat); #region 顶点数据 WaterVertex[] vtxArray = new WaterVertex[vertexCount]; float cellAngle = rad10 / (float)len; float invSize = 1 / (float)size; // i为经度方向 for (int i = 0; i < size; i++) { // j为纬度方向 for (int j = 0; j < size; j++) { Vector3 pos = PlanetEarth.GetPosition(j * cellAngle, radtl - i * cellAngle); pos.Normalize(); pos *= PlanetEarth.PlanetRadius; int index = i * size + j; vtxArray[index].Position = pos; vtxArray[index].NormalCoord = new Vector2(i * invSize, j * invSize); // = index; } } vertexBuffer.SetData <WaterVertex>(vtxArray); #endregion #region 索引数据 int indexCount = MathEx.Sqr(len) * 2 * 3; int[] indexArray = new int[indexCount]; indexBuffer = fac.CreateIndexBuffer(IndexBufferType.Bit32, indexCount, BufferUsage.WriteOnly); for (int i = 0, index = 0; i < len; i++) { for (int j = 0; j < len; j++) { int x = i; int y = j; indexArray[index++] = y * size + x; indexArray[index++] = y * size + (x + 1); indexArray[index++] = (y + 1) * size + (x + 1); indexArray[index++] = y * size + x; indexArray[index++] = (y + 1) * size + (x + 1); indexArray[index++] = (y + 1) * size + x; } } indexBuffer.SetData <int>(indexArray); #endregion #region 构造GeomentryData geoData = new GeomentryData(); geoData.VertexDeclaration = vtxDecl; geoData.VertexSize = WaterVertex.Size; geoData.VertexBuffer = vertexBuffer; geoData.IndexBuffer = indexBuffer; geoData.PrimCount = MathEx.Sqr(len) * 2; geoData.VertexCount = MathEx.Sqr(size); geoData.PrimitiveType = RenderPrimitiveType.TriangleList; geoData.BaseVertex = 0; #endregion }
static VertexPositionNormalDualTexture() { // Create a vertex declaration, describing the format of our vertex data. VertexDeclaration = new VertexDeclaration(VertexPositionNormalDualTexture.VertexElements); }
static VertexPositionNormalTextureLight() { VertexDeclaration = new engenious.Graphics.VertexDeclaration(sizeof(uint) * 2, new VertexElement(0, VertexElementFormat.Rgba32, VertexElementUsage.Position, 0), new VertexElement(sizeof(uint), VertexElementFormat.Rgba32, VertexElementUsage.Normal, 0)); }
/// <summary> /// This implements the method in resource, to load the mesh data(vertex buffer, index buffer) /// of this terrain tile. /// </summary> protected override void load() { // 读取地形数据 // This line will load the terrain data in this tile. float[] data = TerrainData.Instance.GetData(tileX, tileY, terrEdgeSize); float radtc = MathEx.Degree2Radian(tileCol); float radtl = MathEx.Degree2Radian(tileLat); float radSpan = MathEx.Degree2Radian(10); int vertexCount = terrEdgeSize * terrEdgeSize; int terrEdgeLen = terrEdgeSize - 1; if (terrEdgeSize == 33) { material.SetEffect(EffectManager.Instance.GetModelEffect(TerrainEffect33Factory.Name)); } else { material.SetEffect(EffectManager.Instance.GetModelEffect(TerrainEffect17Factory.Name)); } #region 顶点数据 vtxDecl = factory.CreateVertexDeclaration(TerrainVertex.Elements); vtxBuffer = factory.CreateVertexBuffer(vertexCount, vtxDecl, BufferUsage.WriteOnly); TerrainVertex[] vtxArray = new TerrainVertex[vertexCount]; float cellAngle = radSpan / (float)terrEdgeLen; #region 计算顶点坐标 // Caluclate the position of each vertex // i为纬度方向 // i is in the latitude direction for (int i = 0; i < terrEdgeSize; i++) { // j为经度方向 // j is in the longitude direction for (int j = 0; j < terrEdgeSize; j++) { Vector3 pos = PlanetEarth.GetPosition(radtc + j * cellAngle, radtl - i * cellAngle); int index = i * terrEdgeSize + j; // 计算海拔高度 // calculate the elevation float height = (data[index] - TerrainMeshManager.PostZeroLevel) * TerrainMeshManager.PostHeightScale; //if (height > 0) //{ // height = (height - 0) * TerrainMeshManager.PostHeightScale; //} //else //{ // height *= TerrainMeshManager.PostHeightScale; // height -= 10; // //if (height < -30) // // height = -30; //} Vector3 normal = pos; normal.Normalize(); vtxArray[index].Position = pos + normal * height; // this index is used to generate detailed texture coordinate in vertex shader vtxArray[index].Index = index; // map the texture coordinate for global texturing float curCol = radtc + j * cellAngle; float curLat = radSpan + radtl - i * cellAngle; curCol += MathEx.PIf; curLat -= MathEx.Degree2Radian(10); vtxArray[index].u = 0.5f * curCol / MathEx.PIf; vtxArray[index].v = (-curLat + MathEx.PiOver2) / MathEx.PIf; } } #endregion #endregion #region 索引数据 SharedIndexData sindexData = TerrainMeshManager.Instance.GetIndexData(terrEdgeSize); indexBuffer = sindexData.Index; #endregion #region 构造GeomentryData defGeometryData = new GeomentryData(); defGeometryData.VertexDeclaration = vtxDecl; defGeometryData.VertexSize = TerrainVertex.Size; defGeometryData.VertexBuffer = vtxBuffer; defGeometryData.IndexBuffer = indexBuffer; defGeometryData.PrimCount = indexBuffer.IndexCount / 3; defGeometryData.VertexCount = terrEdgeSize * terrEdgeSize; defGeometryData.PrimitiveType = RenderPrimitiveType.TriangleList; defGeometryData.BaseVertex = 0; #endregion vtxBuffer.SetData <TerrainVertex>(vtxArray); }
private void PrepareRenderBatch(IDrawBatch renderBatch) { DrawTechnique technique = renderBatch.Material.Technique.Res ?? DrawTechnique.Solid.Res; NativeShaderProgram program = (technique.Shader.Res != null ? technique.Shader.Res.Native : null) as NativeShaderProgram; VertexDeclaration vertexDeclaration = renderBatch.VertexDeclaration; VertexElement[] elements = vertexDeclaration.Elements; for (int elementIndex = 0; elementIndex < elements.Length; elementIndex++) { switch (elements[elementIndex].Role) { case VertexElementRole.Position: { GL.EnableClientState(ArrayCap.VertexArray); GL.VertexPointer( elements[elementIndex].Count, VertexPointerType.Float, vertexDeclaration.Size, elements[elementIndex].Offset); break; } case VertexElementRole.TexCoord: { GL.EnableClientState(ArrayCap.TextureCoordArray); GL.TexCoordPointer( elements[elementIndex].Count, TexCoordPointerType.Float, vertexDeclaration.Size, elements[elementIndex].Offset); break; } case VertexElementRole.Color: { ColorPointerType attribType; switch (elements[elementIndex].Type) { default: case VertexElementType.Float: attribType = ColorPointerType.Float; break; case VertexElementType.Byte: attribType = ColorPointerType.UnsignedByte; break; } GL.EnableClientState(ArrayCap.ColorArray); GL.ColorPointer( elements[elementIndex].Count, attribType, vertexDeclaration.Size, elements[elementIndex].Offset); break; } default: { if (program != null) { ShaderFieldInfo[] varInfo = program.Fields; int[] locations = program.FieldLocations; int selectedVar = -1; for (int varIndex = 0; varIndex < varInfo.Length; varIndex++) { if (locations[varIndex] == -1) { continue; } if (!ShaderVarMatches( ref varInfo[varIndex], elements[elementIndex].Type, elements[elementIndex].Count)) { continue; } selectedVar = varIndex; break; } if (selectedVar == -1) { break; } VertexAttribPointerType attribType; switch (elements[elementIndex].Type) { default: case VertexElementType.Float: attribType = VertexAttribPointerType.Float; break; case VertexElementType.Byte: attribType = VertexAttribPointerType.UnsignedByte; break; } GL.EnableVertexAttribArray(locations[selectedVar]); GL.VertexAttribPointer( locations[selectedVar], elements[elementIndex].Count, attribType, false, vertexDeclaration.Size, elements[elementIndex].Offset); } break; } } } }
/// <summary> /// This implements the method in resource, to load the mesh data(vertex buffer, index buffer) /// of this terrain tile. /// </summary> protected override void load() { // 读取地形数据 // This line will load the terrain data in this tile. float[] data = TerrainData.Instance.GetData(tileX, tileY, terrEdgeSize); float radtc = MathEx.Degree2Radian(tileCol); float radtl = MathEx.Degree2Radian(tileLat); float radSpan = MathEx.Degree2Radian(10); int vertexCount = terrEdgeSize * terrEdgeSize; int terrEdgeLen = terrEdgeSize - 1; if (terrEdgeSize == 33) material.SetEffect(EffectManager.Instance.GetModelEffect(TerrainEffect33Factory.Name)); else material.SetEffect(EffectManager.Instance.GetModelEffect(TerrainEffect17Factory.Name)); #region 顶点数据 vtxDecl = factory.CreateVertexDeclaration(TerrainVertex.Elements); vtxBuffer = factory.CreateVertexBuffer(vertexCount, vtxDecl, BufferUsage.WriteOnly); TerrainVertex[] vtxArray = new TerrainVertex[vertexCount]; float cellAngle = radSpan / (float)terrEdgeLen; #region 计算顶点坐标 // Caluclate the position of each vertex // i为纬度方向 // i is in the latitude direction for (int i = 0; i < terrEdgeSize; i++) { // j为经度方向 // j is in the longitude direction for (int j = 0; j < terrEdgeSize; j++) { Vector3 pos = PlanetEarth.GetPosition(radtc + j * cellAngle, radtl - i * cellAngle); int index = i * terrEdgeSize + j; // 计算海拔高度 // calculate the elevation float height = (data[index] - TerrainMeshManager.PostZeroLevel) * TerrainMeshManager.PostHeightScale; //if (height > 0) //{ // height = (height - 0) * TerrainMeshManager.PostHeightScale; //} //else //{ // height *= TerrainMeshManager.PostHeightScale; // height -= 10; // //if (height < -30) // // height = -30; //} Vector3 normal = pos; normal.Normalize(); vtxArray[index].Position = pos + normal * height; // this index is used to generate detailed texture coordinate in vertex shader vtxArray[index].Index = index; // map the texture coordinate for global texturing float curCol = radtc + j * cellAngle; float curLat = radSpan + radtl - i * cellAngle; curCol += MathEx.PIf; curLat -= MathEx.Degree2Radian(10); vtxArray[index].u = 0.5f * curCol / MathEx.PIf; vtxArray[index].v = (-curLat + MathEx.PiOver2) / MathEx.PIf; } } #endregion #endregion #region 索引数据 SharedIndexData sindexData = TerrainMeshManager.Instance.GetIndexData(terrEdgeSize); indexBuffer = sindexData.Index; #endregion #region 构造GeomentryData defGeometryData = new GeomentryData(); defGeometryData.VertexDeclaration = vtxDecl; defGeometryData.VertexSize = TerrainVertex.Size; defGeometryData.VertexBuffer = vtxBuffer; defGeometryData.IndexBuffer = indexBuffer; defGeometryData.PrimCount = indexBuffer.IndexCount / 3; defGeometryData.VertexCount = terrEdgeSize * terrEdgeSize; defGeometryData.PrimitiveType = RenderPrimitiveType.TriangleList; defGeometryData.BaseVertex = 0; #endregion vtxBuffer.SetData<TerrainVertex>(vtxArray); }
void IVertexUploader.UploadBatchVertices <T>(VertexDeclaration declaration, T[] vertices, int vertexCount) { GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(declaration.Size * vertexCount), IntPtr.Zero, BufferUsageHint.StreamDraw); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(declaration.Size * vertexCount), vertices, BufferUsageHint.StreamDraw); }
public static void ExtractData(List <JVector> vertices, List <TriangleVertexIndices> indices, Model model) { Matrix[] bones_ = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(bones_); foreach (ModelMesh modelmesh in model.Meshes) { JMatrix xform = Conversion.ToJitterMatrix(bones_[modelmesh.ParentBone.Index]); foreach (ModelMeshPart meshPart in modelmesh.MeshParts) { // Before we add any more where are we starting from int offset = vertices.Count; // Read the format of the vertex buffer VertexDeclaration declaration = meshPart.VertexBuffer.VertexDeclaration; VertexElement[] vertexElements = declaration.GetVertexElements(); // Find the element that holds the position VertexElement vertexPosition = new VertexElement(); foreach (VertexElement vert in vertexElements) { if (vert.VertexElementUsage == VertexElementUsage.Position && vert.VertexElementFormat == VertexElementFormat.Vector3) { vertexPosition = vert; // There should only be one break; } } // Check the position element found is valid if (vertexPosition == null || vertexPosition.VertexElementUsage != VertexElementUsage.Position || vertexPosition.VertexElementFormat != VertexElementFormat.Vector3) { throw new Exception("Model uses unsupported vertex format!"); } // This where we store the vertices until transformed JVector[] allVertex = new JVector[meshPart.NumVertices]; // Read the vertices from the buffer in to the array meshPart.VertexBuffer.GetData <JVector>( meshPart.VertexOffset * declaration.VertexStride + vertexPosition.Offset, allVertex, 0, meshPart.NumVertices, declaration.VertexStride); // Transform them based on the relative bone location and the world if provided for (int i = 0; i != allVertex.Length; ++i) { JVector.Transform(ref allVertex[i], ref xform, out allVertex[i]); } // Store the transformed vertices with those from all the other meshes in this model vertices.AddRange(allVertex); // Find out which vertices make up which triangles if (meshPart.IndexBuffer.IndexElementSize != IndexElementSize.SixteenBits) { // This could probably be handled by using int in place of short but is unnecessary throw new Exception("Model uses 32-bit indices, which are not supported."); } // Each primitive is a triangle short[] indexElements = new short[meshPart.PrimitiveCount * 3]; meshPart.IndexBuffer.GetData <short>( meshPart.StartIndex * 2, indexElements, 0, meshPart.PrimitiveCount * 3); // Each TriangleVertexIndices holds the three indexes to each vertex that makes up a triangle TriangleVertexIndices[] tvi = new TriangleVertexIndices[meshPart.PrimitiveCount]; for (int i = 0; i != tvi.Length; ++i) { // The offset is because we are storing them all in the one array and the // vertices were added to the end of the array. tvi[i].I0 = indexElements[i * 3 + 0] + offset; tvi[i].I1 = indexElements[i * 3 + 1] + offset; tvi[i].I2 = indexElements[i * 3 + 2] + offset; } // Store our triangles indices.AddRange(tvi); } } }
/// <summary> /// Create grid screen /// </summary> /// <param name="setGridDimension">Set grid dimension</param> public GridScreen(int setGridWidth, int setGridHeight) { if (setGridWidth < 2 || setGridHeight < 2) { throw new ArgumentException( "setGridWidth=" + setGridWidth + ", setGridHeight=" + setGridHeight, "Grid size must be at least (2, 2)."); } gridWidth = setGridWidth; gridHeight = setGridHeight; // Create vertex buffer // fix //vertexBuffer = new VertexBuffer( // BaseGame.Device, // typeof(VertexPositionTexture), // gridWidth * gridHeight, // ResourceUsage.WriteOnly, // ResourceManagementMode.Automatic); vertexBuffer = new VertexBuffer( BaseGame.Device, typeof(VertexPositionTexture), gridWidth * gridHeight, BufferUsage.WriteOnly); // Create all vertices VertexPositionTexture[] vertices = new VertexPositionTexture[gridWidth * gridHeight]; // Just simply create all vertices of the grid for (int x = 0; x < gridWidth; x++) { for (int y = 0; y < gridHeight; y++) { vertices[x + y * gridWidth] = new VertexPositionTexture(new Vector3( -1.0f + 2.0f * (float)x / (float)(gridWidth - 1), -1.0f + 2.0f * (float)y / (float)(gridHeight - 1), 0.5f), new Vector2((float)x / (float)(gridWidth - 1), // XNA expect bottom up for the screen rendering. 1.0f - ((float)y / (float)(gridHeight - 1)))); } } vertexBuffer.SetData(vertices); // Index buffer // fix //indexBuffer = new IndexBuffer( // BaseGame.Device, // typeof(ushort), // (gridWidth - 1) * (gridHeight - 1) * 2 * 3, // ResourceUsage.WriteOnly, // ResourceManagementMode.Automatic); indexBuffer = new IndexBuffer( BaseGame.Device, typeof(ushort), (gridWidth - 1) * (gridHeight - 1) * 2 * 3, BufferUsage.WriteOnly); ushort[] indices = new ushort[ (gridWidth - 1) * (gridHeight - 1) * 3 * 2]; // Just simply create all indices of the grid int num = 0; for (int x = 0; x < gridWidth - 1; x++) { for (int y = 0; y < gridHeight - 1; y++) { ushort index1 = (ushort)(x + y * gridWidth); ushort index2 = (ushort)((x + 1) + y * gridWidth); ushort index3 = (ushort)((x + 1) + (y + 1) * gridWidth); ushort index4 = (ushort)(x + (y + 1) * gridWidth); indices[num] = index1; indices[num + 1] = index3; indices[num + 2] = index2; indices[num + 3] = index1; indices[num + 4] = index4; indices[num + 5] = index3; num += 6; } } indexBuffer.SetData(indices); decl = new VertexDeclaration( BaseGame.Device, VertexPositionTexture.VertexElements); }
/// <summary> /// /// </summary> protected void Initialize() { // Create geometry int nvertices = this.slices * 4; // n+1 planes int elemsize = 3 * 3; int dsize = elemsize * nvertices; int x; var indexData = new IndexData(); var vertexData = new VertexData(); var vertices = new float[dsize]; var coords = new float[4, 2] { { 0.0f, 0.0f }, { 0.0f, 1.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f } }; for (x = 0; x < this.slices; x++) { for (int y = 0; y < 4; y++) { float xcoord = coords[y, 0] - 0.5f; float ycoord = coords[y, 1] - 0.5f; float zcoord = -((float)x / (float)(this.slices - 1) - 0.5f); // 1.0f .. a/(a+1) // coordinate vertices[x * 4 * elemsize + y * elemsize + 0] = xcoord * (this.size / 2.0f); vertices[x * 4 * elemsize + y * elemsize + 1] = ycoord * (this.size / 2.0f); vertices[x * 4 * elemsize + y * elemsize + 2] = zcoord * (this.size / 2.0f); // normal vertices[x * 4 * elemsize + y * elemsize + 3] = 0.0f; vertices[x * 4 * elemsize + y * elemsize + 4] = 0.0f; vertices[x * 4 * elemsize + y * elemsize + 5] = 1.0f; // tex vertices[x * 4 * elemsize + y * elemsize + 6] = xcoord * Utility.Sqrt(3.0f); vertices[x * 4 * elemsize + y * elemsize + 7] = ycoord * Utility.Sqrt(3.0f); vertices[x * 4 * elemsize + y * elemsize + 8] = zcoord * Utility.Sqrt(3.0f); } } var faces = new short[this.slices * 6]; for (x = 0; x < this.slices; x++) { faces[x * 6 + 0] = (short)(x * 4 + 0); faces[x * 6 + 1] = (short)(x * 4 + 1); faces[x * 6 + 2] = (short)(x * 4 + 2); faces[x * 6 + 3] = (short)(x * 4 + 1); faces[x * 6 + 4] = (short)(x * 4 + 2); faces[x * 6 + 5] = (short)(x * 4 + 3); } //setup buffers vertexData.vertexStart = 0; vertexData.vertexCount = nvertices; VertexDeclaration decl = vertexData.vertexDeclaration; VertexBufferBinding bind = vertexData.vertexBufferBinding; int offset = 0; offset += decl.AddElement(0, 0, VertexElementType.Float3, VertexElementSemantic.Position).Size; offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Normal).Size; offset += decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.TexCoords).Size; HardwareVertexBuffer vertexBuffer = HardwareBufferManager.Instance.CreateVertexBuffer(decl, nvertices, BufferUsage.StaticWriteOnly); bind.SetBinding(0, vertexBuffer); HardwareIndexBuffer indexBuffer = HardwareBufferManager.Instance.CreateIndexBuffer(IndexType.Size16, this.slices * 6, BufferUsage.StaticWriteOnly); indexData.indexBuffer = indexBuffer; indexData.indexCount = this.slices * 6; indexData.indexStart = 0; indexBuffer.WriteData(0, indexBuffer.Size, faces, true); vertexBuffer.WriteData(0, vertexBuffer.Size, vertices); vertices = null; faces = null; // Now make the render operation renderOperation.operationType = OperationType.TriangleList; renderOperation.indexData = indexData; renderOperation.vertexData = vertexData; renderOperation.useIndices = true; // Create a brand new private material if (!ResourceGroupManager.Instance.GetResourceGroups().Contains("VolumeRendable")) { ResourceGroupManager.Instance.CreateResourceGroup("VolumeRendable"); } var material = (Material)MaterialManager.Instance.Create(this.texture, "VolumeRendable"); // Remove pre-created technique from defaults material.RemoveAllTechniques(); // Create a techinique and a pass and a texture unit Technique technique = material.CreateTechnique(); Pass pass = technique.CreatePass(); TextureUnitState textureUnit = pass.CreateTextureUnitState(); // Set pass parameters pass.SetSceneBlending(SceneBlendType.TransparentAlpha); pass.DepthWrite = false; pass.CullingMode = CullingMode.None; pass.LightingEnabled = false; textureUnit.SetTextureAddressingMode(TextureAddressing.Clamp); textureUnit.SetTextureName(this.texture, TextureType.ThreeD); textureUnit.SetTextureFiltering(TextureFiltering.Trilinear); this.unit = textureUnit; base.material = material; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var form = new Form1(); var panel = form.SplitContainer.Panel1; var device = new Device(new Direct3D(), 0, DeviceType.Hardware, panel.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters() { BackBufferWidth = panel.ClientSize.Width, BackBufferHeight = panel.ClientSize.Height }); var vertices = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); vertices.Lock(0, 0, LockFlags.None).WriteRange(new[] { new Vertex() { Color = Color.Red.ToArgb(), Position = new Vector4(400.0f, 100.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Blue.ToArgb(), Position = new Vector4(650.0f, 500.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Green.ToArgb(), Position = new Vector4(150.0f, 500.0f, 0.5f, 1.0f) } }); vertices.Unlock(); var vertices2 = new VertexBuffer(device, 3 * 20, Usage.WriteOnly, VertexFormat.None, Pool.Managed); vertices2.Lock(0, 0, LockFlags.None).WriteRange(new[] { new Vertex() { Color = Color.Red.ToArgb(), Position = new Vector4(300.0f, 100.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Blue.ToArgb(), Position = new Vector4(550.0f, 500.0f, 0.5f, 1.0f) }, new Vertex() { Color = Color.Green.ToArgb(), Position = new Vector4(050.0f, 500.0f, 0.5f, 1.0f) } }); vertices2.Unlock(); var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(device, vertexElems); MessagePump.Run(form, () => { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); device.SetStreamSource(0, vertices, 0, 20); device.VertexDeclaration = vertexDecl; device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); device.SetStreamSource(0, vertices2, 0, 20); device.VertexDeclaration = vertexDecl; device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); device.EndScene(); device.Present(); }); foreach (var item in ObjectTable.Objects) { item.Dispose(); } }
/// <summary> /// </summary> /// <param name="vertexSize"> </param> /// <param name="numVertices"> </param> /// <param name="usage"> </param> public GLES2DefaultHardwareVertexBuffer(VertexDeclaration declaration, int numVertices, BufferUsage usage) : base(null, declaration, numVertices, usage, true, false) { this._data = new byte[declaration.GetVertexSize() * numVertices]; this._dataPtr = BufferBase.Wrap(this._data); }
private void FinishRenderBatch(IDrawBatch renderBatch) { DrawTechnique technique = renderBatch.Material.Technique.Res ?? DrawTechnique.Solid.Res; NativeShaderProgram program = (technique.Shader.Res != null ? technique.Shader.Res.Native : null) as NativeShaderProgram; VertexDeclaration vertexDeclaration = renderBatch.VertexDeclaration; VertexElement[] elements = vertexDeclaration.Elements; for (int elementIndex = 0; elementIndex < elements.Length; elementIndex++) { switch (elements[elementIndex].Role) { case VertexElementRole.Position: { GL.DisableClientState(ArrayCap.VertexArray); break; } case VertexElementRole.TexCoord: { GL.DisableClientState(ArrayCap.TextureCoordArray); break; } case VertexElementRole.Color: { GL.DisableClientState(ArrayCap.ColorArray); break; } default: { if (program != null) { ShaderFieldInfo[] varInfo = program.Fields; int[] locations = program.FieldLocations; int selectedVar = -1; for (int varIndex = 0; varIndex < varInfo.Length; varIndex++) { if (locations[varIndex] == -1) { continue; } if (!ShaderVarMatches( ref varInfo[varIndex], elements[elementIndex].Type, elements[elementIndex].Count)) { continue; } selectedVar = varIndex; break; } if (selectedVar == -1) { break; } GL.DisableVertexAttribArray(locations[selectedVar]); } break; } } } }
public bool DirectX_Init(string background_image) { PresentParameters presentParms = new PresentParameters(); presentParms.Windowed = true; presentParms.SwapEffect = SwapEffect.Discard; presentParms.Multisample = MultisampleType.None; presentParms.EnableAutoDepthStencil = true; presentParms.AutoDepthStencilFormat = Format.D16; presentParms.PresentFlags = PresentFlags.DiscardDepthStencil; presentParms.PresentationInterval = PresentInterval.Default; presentParms.BackBufferFormat = Format.X8R8G8B8; presentParms.BackBufferHeight = gauge_target.Height; presentParms.BackBufferWidth = gauge_target.Width; presentParms.Windowed = true; presentParms.BackBufferCount = 1; switch (directx_render_type) { case RenderType.HARDWARE: try { DX9device = new Device(new Direct3D(), 0, DeviceType.Hardware, gauge_target.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); } catch (Direct3D9Exception ex) { MessageBox.Show("Problem u inicijalizaciji DirectX-a greska 1\n" + ex.ToString()); } break; case RenderType.SOFTWARE: { try { DX9device = new Device(new Direct3D(), 0, DeviceType.Hardware, gauge_target.Handle, CreateFlags.SoftwareVertexProcessing | CreateFlags.FpuPreserve | CreateFlags.Multithreaded, presentParms); } catch (Direct3D9Exception exe) { MessageBox.Show("Problem u inicijalizaciji DirectX-a greska 2\n" + exe.ToString()); return false; } } break; } var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; var vertexDecl = new VertexDeclaration(DX9device, vertexElems); DX9device.VertexDeclaration = vertexDecl; if (File.Exists(background_image)) { BackgroundTexture = Texture.FromFile(DX9device, background_image, this.Width, this.Height, 1, Usage.None, Format.Unknown, Pool.Default, SlimDX.Direct3D9.Filter.Default, SlimDX.Direct3D9.Filter.Default, 0); } texture_size.Width = gauge_target.Width; texture_size.Height = gauge_target.Height; sprite = new Sprite(DX9device); if (render_event == null) render_event = new AutoResetEvent(true); line = new Line(DX9device); line.Antialias = true; line.Width = 3; line.GLLines = true; DX9device.SetRenderState(RenderState.AntialiasedLineEnable, true); return true; }
/// <summary> /// Unpacks a raw buffer of vertex data into proper arrays /// </summary> /// <returns>Returns true if some data was successful in extraction</returns> public static unsafe bool UnpackRawVertData(byte[] data, VertexDeclaration declaration, out Vector3[] positions, out Vector3[] normals, out Vector2[] uvs, out Color4[] colors, out Vector4[] tangents) { positions = null; normals = null; uvs = null; colors = null; tangents = null; if (data == null || declaration == null || data.Length <= 0) { return(false); } VertexElement[] elements = declaration.VertexElements; int totalEntries = data.Length / declaration.VertexStride; positions = new Vector3[totalEntries]; int[] eoffsets = new int[elements.Length]; for (int i = 1; i < elements.Length; i++) { eoffsets[i] = eoffsets[i - 1] + elements[i - 1].Format.SizeInBytes(); fixed(byte *dp = data) { for (int offset = 0; offset < data.Length; offset += declaration.VertexStride) { int vertindex = offset / declaration.VertexStride; for (int i = 0; i < elements.Length; i++) { VertexElement e = elements[i]; switch (e.SemanticName) { case "POSITION": positions[vertindex] = *(Vector3 *)&dp[offset + eoffsets[i]]; break; case "NORMAL": if (normals == null) { normals = new Vector3[totalEntries]; } normals[vertindex] = *(Vector3 *)&dp[offset + eoffsets[i]]; break; case "COLOR": if (colors == null) { colors = new Color4[totalEntries]; } colors[vertindex] = *(Color4 *)&dp[offset + eoffsets[i]]; break; case "TEXCOORD": if (uvs == null) { uvs = new Vector2[totalEntries]; } uvs[vertindex] = *(Vector2 *)&dp[offset + eoffsets[i]]; break; case "TANGENT": if (tangents == null) { tangents = new Vector4[totalEntries]; } tangents[vertindex] = *(Vector4 *)&dp[offset + eoffsets[i]]; break; } } } } return(true); }
static VertexPosition() { VertexElement[] elements = { new VertexElement( 0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0 ) }; VertexDeclaration declaration = new VertexDeclaration( elements ); VertexDeclaration = declaration; }
/// <summary> /// Loads the particle effect from the .fx file, and initializes the vertex and index buffer used for rendering particle clouds. /// This must be called before any particle clouds can be drawn. /// An exception will be thrown if the shader does not conform to the requirements of the particle cloud system /// (ie. if it was missing a parameter). /// </summary> public void Initialize() { // Verify that we have not initialized already. Debug.Assert(!isInitialized, "ParticleCloudSystem is already initialized. Initialize() cannot be called more than once."); // Load the particle cloud effect. particleEffect = content.Load <Effect>(particleEffectPath); // Get all the parameter handles. positionsParam = particleEffect.Parameters["Positions"]; colorsParam = particleEffect.Parameters["Colors"]; orientationsParam = particleEffect.Parameters["Orientations"]; worldParam = particleEffect.Parameters["World"]; projectionParam = particleEffect.Parameters["Projection"]; worldViewParam = particleEffect.Parameters["WorldView"]; billboardRightParam = particleEffect.Parameters["BillboardRight"]; billboardUpParam = particleEffect.Parameters["BillboardUp"]; textureParam = particleEffect.Parameters["Texture"]; // Verify that the parameters we need are indeed there. if (positionsParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float3 Positions[] array is undefined"); } if (colorsParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float4 Colors[] array is undefined"); } if (orientationsParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float4 Orientations[] array is undefined"); } if (worldParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float4x4 World : WORLD, is undefined"); } if (projectionParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float4x4 Projection : PROJECTION, is undefined"); } if (worldViewParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float4x4 WorldView : WORLDVIEW, is undefined"); } if (billboardRightParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float3 BillboardRight, is undefined"); } if (billboardUpParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. float3 BillboardUp, is undefined"); } if (textureParam == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. texture Texture, is undefined"); } // Get the technique handles sortedTechnique = particleEffect.Techniques["SortedParticles"]; unsortedTechnique = particleEffect.Techniques["UnsortedParticles"]; depthTechnique = particleEffect.Techniques["DepthMapStatic"]; // Verify that the required techniques are indeed there. if (sortedTechnique == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. SortedParticles technique is not defined."); } if (unsortedTechnique == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. UnsortedParticles technique is not defined."); } if (depthTechnique == null) { throw new Exception(particleEffectPath + " is not a valid shader for particle clouds. DepthMapStatic technique is not defined."); } // Initialize vertex buffer. ParticleCloudVertex[] vertices = new ParticleCloudVertex[MaxParticlesPerRender * 4]; for (short i = 0; i < MaxParticlesPerRender; i++) { vertices[4 * i] = new ParticleCloudVertex(new Vector2(-1, 1), i); vertices[4 * i + 1] = new ParticleCloudVertex(new Vector2(1, 1), i); vertices[4 * i + 2] = new ParticleCloudVertex(new Vector2(1, -1), i); vertices[4 * i + 3] = new ParticleCloudVertex(new Vector2(-1, -1), i); } vertexBuffer = new VertexBuffer(device, 4 * MaxParticlesPerRender * ParticleCloudVertex.SizeInBytes, BufferUsage.WriteOnly); vertexBuffer.SetData <ParticleCloudVertex>(vertices); // Initialize index buffer int[] indices = new int[MaxParticlesPerRender * 6]; int idx = 0; for (int i = 0; i < MaxParticlesPerRender; i++) { indices[idx++] = 4 * i; indices[idx++] = 4 * i + 1; indices[idx++] = 4 * i + 2; indices[idx++] = 4 * i + 2; indices[idx++] = 4 * i + 3; indices[idx++] = 4 * i; } indexBuffer = new IndexBuffer(device, 6 * MaxParticlesPerRender * sizeof(int), BufferUsage.WriteOnly, IndexElementSize.ThirtyTwoBits); indexBuffer.SetData <int>(indices); // Create the vertex declaration vertexDeclaration = new VertexDeclaration(device, ParticleCloudVertex.VertexElements); // Initialization successful isInitialized = true; }
static VertexPositionColorTexture() { VertexElement[] elements = new VertexElement[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Color, VertexElementUsage.Color, 0), new VertexElement(0x10, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) }; VertexDeclaration declaration = new VertexDeclaration(elements); VertexDeclaration = declaration; }
void IGraphicsBackend.Render(IReadOnlyList <DrawBatch> batches) { if (batches.Count == 0) { return; } this.RetrieveActiveShaders(batches); this.SetupSharedParameters(this.renderOptions.ShaderParameters); int drawCalls = 0; DrawBatch lastRendered = null; for (int i = 0; i < batches.Count; i++) { DrawBatch batch = batches[i]; VertexDeclaration vertexType = batch.VertexBuffer.VertexType; // Bind the vertex buffer we'll use. Note that this needs to be done // before setting up any vertex format state. NativeGraphicsBuffer vertexBuffer = batch.VertexBuffer.NativeVertex as NativeGraphicsBuffer; NativeGraphicsBuffer.Bind(GraphicsBufferType.Vertex, vertexBuffer); bool first = (i == 0); bool sameMaterial = lastRendered != null && lastRendered.Material.Equals(batch.Material); // Setup vertex bindings. Note that the setup differs based on the // materials shader, so material changes can be vertex binding changes. if (lastRendered != null) { this.FinishVertexFormat(lastRendered.Material, lastRendered.VertexBuffer.VertexType); } this.SetupVertexFormat(batch.Material, vertexType); // Setup material when changed. if (!sameMaterial) { this.SetupMaterial( batch.Material, lastRendered != null ? lastRendered.Material : null); } // Draw the current batch this.DrawVertexBatch( batch.VertexBuffer, batch.VertexRanges, batch.VertexMode); drawCalls++; lastRendered = batch; } // Cleanup after rendering NativeGraphicsBuffer.Bind(GraphicsBufferType.Vertex, null); NativeGraphicsBuffer.Bind(GraphicsBufferType.Index, null); if (lastRendered != null) { this.FinishMaterial(lastRendered.Material); this.FinishVertexFormat(lastRendered.Material, lastRendered.VertexBuffer.VertexType); } if (this.renderStats != null) { this.renderStats.DrawCalls += drawCalls; } this.FinishSharedParameters(); }
public RenderObjectXX(xxParser parser, HashSet<string> meshNames) { HighlightSubmesh = new HashSet<int>(); highlightMaterial = new Material(); highlightMaterial.Ambient = new Color4(1, 1, 1, 1); highlightMaterial.Diffuse = new Color4(1, 0, 1, 0); this.device = Gui.Renderer.Device; this.tweeningVertDec = new VertexDeclaration(this.device, TweeningMeshesVertexBufferFormat.ThreeStreams); Textures = new Texture[parser.TextureList.Count]; Materials = new Material[parser.MaterialList.Count]; rootFrame = CreateHierarchy(parser, meshNames, device, out meshFrames); AnimationController = new AnimationController(numFrames, 30, 30, 1); Frame.RegisterNamedMatrices(rootFrame, AnimationController); Bounds = meshFrames[0].Bounds; for (int i = 1; i < meshFrames.Count; i++) { Bounds = BoundingBox.Merge(Bounds, meshFrames[i].Bounds); } }
[Test] public void RentAndClear() { VertexBatchStore memory = new VertexBatchStore(); // Repeatedly rent slices of varying types from memory { VertexSlice <VertexC1P3> slice = memory.Rent <VertexC1P3>(4); slice[0] = new VertexC1P3 { Color = new ColorRgba(0) }; slice[1] = new VertexC1P3 { Color = new ColorRgba(1) }; slice[2] = new VertexC1P3 { Color = new ColorRgba(2) }; slice[3] = new VertexC1P3 { Color = new ColorRgba(3) }; } { VertexSlice <VertexC1P3T2> slice = memory.Rent <VertexC1P3T2>(3); slice[0] = new VertexC1P3T2 { Color = new ColorRgba(4) }; slice[1] = new VertexC1P3T2 { Color = new ColorRgba(5) }; slice[2] = new VertexC1P3T2 { Color = new ColorRgba(6) }; } { VertexSlice <VertexC1P3> slice = memory.Rent <VertexC1P3>(2); slice[0] = new VertexC1P3 { Color = new ColorRgba(7) }; slice[1] = new VertexC1P3 { Color = new ColorRgba(8) }; } { VertexSlice <VertexC1P3> slice = memory.Rent <VertexC1P3>(1); slice[0] = new VertexC1P3 { Color = new ColorRgba(9) }; } // Assert correct storage property values Assert.AreEqual( 1 + Math.Max( VertexDeclaration.Get <VertexC1P3>().TypeIndex, VertexDeclaration.Get <VertexC1P3T2>().TypeIndex), memory.TypeIndexCount); Assert.AreEqual(1, memory.GetBatchCount <VertexC1P3>()); Assert.AreEqual(1, memory.GetBatchCount <VertexC1P3T2>()); // Retrieve specific internal vertex arrays VertexBatch <VertexC1P3> batchA = memory.GetBatch <VertexC1P3>(0); VertexBatch <VertexC1P3T2> batchB = memory.GetBatch <VertexC1P3T2>(0); RawList <VertexC1P3> verticesA = batchA.Vertices; RawList <VertexC1P3T2> verticesB = batchB.Vertices; // Assert that they contain all the data we submitted in the correct order Assert.AreEqual(7, batchA.Count); Assert.AreEqual(3, batchB.Count); Assert.AreEqual(7, verticesA.Count); Assert.AreEqual(3, verticesB.Count); Assert.AreEqual(new ColorRgba(0), verticesA[0].Color); Assert.AreEqual(new ColorRgba(1), verticesA[1].Color); Assert.AreEqual(new ColorRgba(2), verticesA[2].Color); Assert.AreEqual(new ColorRgba(3), verticesA[3].Color); Assert.AreEqual(new ColorRgba(4), verticesB[0].Color); Assert.AreEqual(new ColorRgba(5), verticesB[1].Color); Assert.AreEqual(new ColorRgba(6), verticesB[2].Color); Assert.AreEqual(new ColorRgba(7), verticesA[4].Color); Assert.AreEqual(new ColorRgba(8), verticesA[5].Color); Assert.AreEqual(new ColorRgba(9), verticesA[6].Color); // Clear all vertices memory.Clear(); // Assert correct storage property values Assert.AreEqual(0, memory.TypeIndexCount); Assert.AreEqual(0, memory.GetBatchCount <VertexC1P3>()); Assert.AreEqual(0, memory.GetBatchCount <VertexC1P3T2>()); // Assert that the vertices are gone, but capacity isn't Assert.AreEqual(0, batchA.Count); Assert.AreEqual(0, batchB.Count); Assert.AreEqual(0, verticesA.Count); Assert.AreEqual(0, verticesB.Count); Assert.GreaterOrEqual(verticesA.Capacity, 7); Assert.GreaterOrEqual(verticesB.Capacity, 3); }
protected override void unload() { if (!object.ReferenceEquals(vtxBuffer, null)) { vtxBuffer.Dispose(); vtxBuffer = null; } if (!object.ReferenceEquals(vtxDecl, null)) { vtxDecl.Dispose(); vtxDecl = null; } indexBuffer = null; }
/// <summary> /// Creats a new CubeComponent. /// </summary> /// <param name="game">The game to which this component will be attached.</param> /// <param name="color">The color of the cube.</param> /// <param name="sideLength">The length of one side of the cube.</param> public CubeComponent(Game game, Color color, float sideLength) : base(game) { this.sideLength = sideLength; this.graphics = (IGraphicsDeviceService)game.Services.GetService( typeof(IGraphicsDeviceService)); effect = new BasicEffect(graphics.GraphicsDevice, null); indices = new int[] { 0, 1, 2, // left face 2, 3, 0, 3, 2, 6, // top face 6, 7, 3, 7, 6, 5, // right face 5, 4, 7, 4, 5, 1, // bottom face 1, 0, 4, 5, 6, 2, // back face 2, 1, 5, 7, 4, 0, // front face 0, 3, 7 }; Vector3[] originalVerts = new Vector3[] { new Vector3(-1, -1, 1), // 0 - front bottom left new Vector3(-1, -1, -1), // 1 - back bottom left new Vector3(-1, 1, -1), // 2 - back top left new Vector3(-1, 1, 1), // 3 - front top left new Vector3(1, -1, 1), // 4 - front bottom right new Vector3(1, -1, -1), // 5 - back bottom right new Vector3(1, 1, -1), // 6 - back top right new Vector3(1, 1, 1) // 7 - front top right }; for (int i = 0; i < originalVerts.Length; i++) { originalVerts[i].X *= sideLength / 2; originalVerts[i].Y *= sideLength / 2; originalVerts[i].Z *= sideLength / 2; } vertexDeclaration = new VertexDeclaration( graphics.GraphicsDevice, VertexPositionColor.VertexElements); verts = new VertexPositionColor[8]; buffer = new Vector3[8]; for (int i = 0; i < verts.Length; i++) { verts[i].Position = originalVerts[i]; verts[i].Color = color; } effect.VertexColorEnabled = true; game.Components.Add(this); }
//ExStart:RenderView private void InitRenderer() { // Create a default camera, because it's required during the viewport's creation. camera = new Camera(); Scene.RootNode.CreateChildNode("camera", camera); // Create the renderer and render window from window's native handle renderer = Renderer.CreateRenderer(); // Right now we only support native window handle from Microsoft Windows // We'll support more platform on user's demand. window = renderer.RenderFactory.CreateRenderWindow(new RenderParameters(), Handle); // Create 4 viewports, the viewport's area is meanless here because we'll change it to the right area in the SetViewports later viewports = new[] { window.CreateViewport(camera, Color.Gray, RelativeRectangle.FromScale(0, 0, 1, 1)), window.CreateViewport(camera, Color.Gray, RelativeRectangle.FromScale(0, 0, 1, 1)), window.CreateViewport(camera, Color.Gray, RelativeRectangle.FromScale(0, 0, 1, 1)), window.CreateViewport(camera, Color.Gray, RelativeRectangle.FromScale(0, 0, 1, 1)) }; SetViewports(1); //initialize shader for grid GLSLSource src = new GLSLSource(); src.VertexShader = @"#version 330 core layout (location = 0) in vec3 position; uniform mat4 matWorldViewProj; void main() { gl_Position = matWorldViewProj * vec4(position, 1.0f); }"; src.FragmentShader = @"#version 330 core out vec4 color; void main() { color = vec4(1, 1, 1, 1); }"; // Define the input format used by GLSL vertex shader the format is struct ControlPoint { FVector3 Position;} VertexDeclaration fd = new VertexDeclaration(); fd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Position); // Compile shader from GLSL source code and specify the vertex input format gridShader = renderer.RenderFactory.CreateShaderProgram(src, fd); // Connect GLSL uniform to renderer's internal variable gridShader.Variables = new ShaderVariable[] { new ShaderVariable("matWorldViewProj", VariableSemantic.MatrixWorldViewProj) }; SceneUpdated(""); }
/// <summary>Registers the specified vertex type for particle systems</summary> /// <typeparam name="VertexType">Type of vertex that will be registered</typeparam> /// <param name="vertexDeclaration"> /// Vertex declaration describing the vertex structure to the graphics device /// </param> /// <param name="stride">Offset, in bytes, from one vertex to the next</param> /// <remarks> /// <para> /// Registering a vertex type is only required when the vertex declaration can not /// be automatically extracted from the vertex structure (eg. you didn't use /// VertexElementAttribute to describe your fields). /// </para> /// <para> /// If the vertex type is used by the particle system manager throughout its /// lifespan, it's okay to not call unregister and rely on Dispose() doing /// the clean-up work. Take note that in this variant, the particle system /// manager doesn't take ownership of the vertex declaration; you'll have to /// destroy it yourself after the particle system manager is destroyed. /// </para> /// </remarks> public void RegisterVertex <VertexType>( VertexDeclaration vertexDeclaration, int stride ) where VertexType : struct { RegisterVertex <VertexType>(vertexDeclaration, stride, false); }