private void CreateIndexBuffer(OpenGL gl)
        {
            const uint vertexCount = slices * stacks;
            const uint indexCount  = vertexCount * 6;

            indices = new ushort[indexCount];
            int count = 0;

            ushort n = 0;

            for (ushort i = 0; i < slices; i++)
            {
                for (ushort j = 0; j < stacks; j++)
                {
                    indices[count++] = (ushort)(n + j);
                    indices[count++] = (ushort)(n + (j + 1) % stacks);
                    indices[count++] = (ushort)((n + j + stacks) % vertexCount);

                    indices[count++] = (ushort)((n + j + stacks) % vertexCount);
                    indices[count++] = (ushort)((n + (j + 1) % stacks) % vertexCount);
                    indices[count++] = (ushort)((n + (j + 1) % stacks + stacks) % vertexCount);
                }

                n += (ushort)stacks;
            }

            var indexBuffer = new IndexBuffer();

            indexBuffer.Create(gl);
            indexBuffer.Bind(gl);
            indexBuffer.SetData(gl, indices);
        }
Exemple #2
0
        /// <summary>
        ///
        /// </summary>
        internal void CreateVertexAndIndexBuffers(GraphicsDevice device)
        {
            indexBuffer = IndexBuffer.Create(device, GetIndices());

            bool skinned = false;

            foreach (var v in Vertices)
            {
                if (v.SkinIndices != Int4.Zero)
                {
                    skinned = true;
                    break;
                }
            }

            IsSkinned = skinned;


            if (skinned)
            {
                vertexBuffer = VertexBuffer.Create(device, Vertices.Select(v => VertexColorTextureTBNSkinned.Convert(v)).ToArray());
            }
            else
            {
                vertexBuffer = VertexBuffer.Create(device, Vertices.Select(v => VertexColorTextureTBNRigid.Convert(v)).ToArray());
            }
        }
Exemple #3
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="SpriteBatch" /> class.
        /// </summary>
        /// <param name="graphicsDevice"> The graphics device. </param>
        /// <param name="center">         (Optional) True to center the coordinate system in the viewport. </param>
        /// <param name="sortAlgorithm">  (Optional) The sort algorithm. </param>
        /// <exception cref="ArgumentException">
        ///     Thrown when one or more arguments have unsupported or
        ///     illegal values.
        /// </exception>
        /// <exception cref="NullReferenceException"> Thrown when a value was unexpectedly null. </exception>
        public SpriteBatch(IGraphicsDevice graphicsDevice,
                           bool center = false,
                           SpriteSortAlgorithm sortAlgorithm = SpriteSortAlgorithm.MergeSort)
        {
            _device  = graphicsDevice.Device;
            _context = graphicsDevice.DeviceContext;

            _center = center;

            _spriteSort = sortAlgorithm switch
            {
                SpriteSortAlgorithm.MergeSort => new SpriteMergeSort(),
                _ => throw new ArgumentException($"invalid sort algorithm ({sortAlgorithm})", nameof(sortAlgorithm))
            };

            _defaultBlendState                    = graphicsDevice.BlendStates.AlphaBlend;
            _defaultSamplerState                  = graphicsDevice.SamplerStates.LinearWrap;
            _defaultDepthStencilState             = graphicsDevice.DepthStencilStates.None;
            _defaultRasterizerState               = graphicsDevice.RasterizerStates.CullBackDepthClipOff;
            _defaultRasterizerScissorEnabledState = graphicsDevice.RasterizerStates.CullBackDepthClipOffScissorEnabled;

            _whiteTexture = graphicsDevice.Textures.White;

            _indexBuffer = IndexBuffer.Create(graphicsDevice, s_indices);

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream stream =
                       assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{Shaders.POSITION_COLOR_TEXTURE}") ??
                       throw new NullReferenceException($"{assembly.GetName().Name}.{Shaders.POSITION_COLOR_TEXTURE}"))
            {
                Shader.Shader.Group group =
                    (_shader = ShaderFileLoader.FromStream(graphicsDevice, stream) ??
                               throw new NullReferenceException(nameof(ShaderFileLoader.FromStream)))["DEFAULT"];
        /// <inheritdoc />
        public void Add(IPolygon data)
        {
            foreach (var layer in RenderLayers)
            {
                layer.Reset(true);
            }

            // Always clear Voronoi layer.
            RenderLayers[4].Reset(true);

            int i = 0;

            // Ensure linear numbering of polygon vertices.
            foreach (var p in data.Points)
            {
                p.ID = i++;
            }

            bounds = data.Bounds();

            zoom.Initialize(bounds);

            RenderLayers[2].SetPoints(VertexBuffer.Create(data.Points, bounds));
            RenderLayers[2].SetIndices(IndexBuffer.Create(data.Segments, 2));

            RenderLayers[3].SetPoints(RenderLayers[2].Points);
        }
        /// <inheritdoc />
        public void Add(IMesh data, bool reset)
        {
            foreach (var layer in RenderLayers)
            {
                layer.Reset(reset);
            }

            // Always clear voronoi layer.
            RenderLayers[4].Reset(true);

            // Save reference to mesh.
            mesh   = data;
            bounds = data.Bounds;

            // Ensure linear numbering of vertices.
            mesh.Renumber();

            zoom.Initialize(bounds);

            RenderLayers[1].SetPoints(VertexBuffer.Create(data.Vertices, bounds));
            RenderLayers[1].SetIndices(IndexBuffer.Create(data.Edges, 2));

            RenderLayers[2].SetPoints(RenderLayers[1].Points);
            RenderLayers[2].SetIndices(IndexBuffer.Create(data.Segments, 2));

            RenderLayers[3].SetPoints(RenderLayers[1].Points, false);
        }
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);
            SafeDispose(ref vertexBuffers);
            SafeDispose(ref indexBuffers);

            surfaceShader = Game.Content.Load <Ubershader>("surface");
            factory       = new StateFactory(surfaceShader, typeof(SurfaceFlags), Primitive.TriangleList, VertexInputElement.FromStructure <VertexColorTextureTBN>());


            scene = Game.Content.Load <Scene>(@"Scenes\testScene");

            vertexBuffers = scene.Meshes
                            .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                            .ToArray();

            indexBuffers = scene.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();


            surfaceProps = scene.Materials
                           .Select(mtrl => new SurfaceProperties()
            {
                Diffuse   = LoadTexture2D(mtrl.TexturePath, "|srgb", defaultDiffuse),
                Specular  = LoadTexture2D(mtrl.TexturePath, "_spec", defaultSpecular),
                NormalMap = LoadTexture2D(mtrl.TexturePath, "_local", defaultNormalMap),
                Emission  = LoadTexture2D(mtrl.TexturePath, "_glow|srgb", defaultEmission),
            })
                           .ToArray();
        }
Exemple #7
0
        /// <summary>
        ///
        /// </summary>
        void LoadContent()
        {
            SafeDispose(ref factory);

            skySphere   = Game.Content.Load <Scene>("skySphere");
            cloudSphere = Game.Content.Load <Scene>("cloudSphere");
            clouds      = Game.Content.Load <Texture2D>("clouds|srgb");
            cirrus      = Game.Content.Load <Texture2D>("cirrus|srgb");
            noise       = Game.Content.Load <Texture2D>("cloudNoise");
            arrows      = Game.Content.Load <Texture2D>("arrowsAll");

            vertexBufferBlur = new VertexBuffer(Game.GraphicsDevice, typeof(VertexColorTextureTBN), 6);
            vertexBuffers    = skySphere.Meshes
                               .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                               .ToArray();

            indexBuffers = skySphere.Meshes
                           .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                           .ToArray();

            cloudVertexBuffers = cloudSphere.Meshes
                                 .Select(mesh => VertexBuffer.Create(Game.GraphicsDevice, mesh.Vertices.Select(v => VertexColorTextureTBN.Convert(v)).ToArray()))
                                 .ToArray();

            cloudIndexBuffers = cloudSphere.Meshes
                                .Select(mesh => IndexBuffer.Create(Game.GraphicsDevice, mesh.GetIndices()))
                                .ToArray();

            sky     = Game.Content.Load <Ubershader>("sky");
            factory = new StateFactory(sky, typeof(SkyFlags), (ps, i) => EnumFunc(ps, (SkyFlags)i));
        }
Exemple #8
0
        protected override void OnLoad(EventArgs e)
        {
            VSync = VSyncMode.On;

            GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
            GL.Enable(EnableCap.DepthTest);

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix);
            modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            shader = new Program(vertexShaderSource, fragmentShaderSource);
            shader.Bind();
            shader.UniformMatrix4("camera", false, ref projectionMatrix);
            shader.UniformMatrix4("model", false, ref modelviewMatrix);
            shader.Unbind();

            positionVbo = VertexBuffer.Create(VertexFormat.PositionTexture, positionVboData);
            //normalVbo = VertexBuffer.Create(new VertexFormat(new List<VertexAttribute>() { new VertexAttribute(VertexUsage.TextureCoordinate, VertexAttribPointerType.Float, 0, 2) }), textureVboData);

            indexVbo = IndexBuffer.Create(indicesVboData);
            vao      = new VertexArray(positionVbo, indexVbo);
            Utilities.CheckGLError();
            vao.AddBinding(shader.VertexAttribute("vert").Slot, VertexUsage.Position);
            vao.AddBinding(shader.VertexAttribute("vertTexCoord").Slot, VertexUsage.TextureCoordinate);
            Utilities.CheckGLError();
            Bitmap bmp = new Bitmap(@"..\..\..\Resources\wooden-crate.jpg");

            texture = Texture2D.Create(bmp, TextureMinFilter.Linear, TextureMagFilter.Linear);
        }
Exemple #9
0
        protected override void OnLoad(EventArgs e)
        {
            VSync = VSyncMode.On;

            GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
            GL.Enable(EnableCap.DepthTest);

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix);
            modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            shader = new Program(vertexShaderSource, fragmentShaderSource);
            shader.Bind();
            shader.UniformMatrix4("projection_matrix", false, ref projectionMatrix);
            shader.UniformMatrix4("modelview_matrix", false, ref modelviewMatrix);
            shader.Unbind();

            positionVbo = VertexBuffer.Create(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Position, VertexAttribPointerType.Float, 0, 3)
            }), positionVboData);
            normalVbo = VertexBuffer.Create(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Normal, VertexAttribPointerType.Float, 0, 3)
            }), positionVboData);
            indexVbo = IndexBuffer.Create(indicesVboData);
            vao      = new VertexArray(positionVbo, indexVbo);
            Utilities.CheckGLError();
            vao.AddBinding(shader.VertexAttribute("in_position").Slot, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
            vao.AddBinding(shader.VertexAttribute("in_normal").Slot, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
            Utilities.CheckGLError();
        }
        /// <inheritdoc />
        public void Add(int[] data)
        {
            // Add partition data for filled mesh.
            RenderLayers[0].SetPoints(RenderLayers[1].Points);
            RenderLayers[0].SetIndices(IndexBuffer.Create(mesh.Triangles, 3));
            RenderLayers[0].AttachLayerData(data);

            RenderLayers[0].IsEnabled = true;
        }
        /// <inheritdoc />
        public void Add(float[] data)
        {
            // Add function values for filled mesh.
            RenderLayers[0].SetPoints(RenderLayers[1].Points);
            RenderLayers[0].SetIndices(IndexBuffer.Create(mesh.Triangles, 3));
            RenderLayers[0].AttachLayerData(data, colorManager.ColorMap);

            RenderLayers[0].IsEnabled = true;
        }
Exemple #12
0
 private void CreateIndexBuffer()
 {
     _indexBuffer?.Dispose();
     _indexBuffer = IndexBuffer.Create <ushort>(ParentContext,
                                                _indexBufferSize,
                                                BufferUsageHint.StreamDraw,
                                                true);
     _indexBuffer.Label = "SpriteBatch IndexBuffer";
 }
Exemple #13
0
        private VertexArray Init()
        {
            var va = VertexArray.Create();
            var vb = VertexBuffer.Create(Vertices);

            vb.BufferLayout = new BufferLayout(BufferLayout);
            va.AddVertexBuffer(vb);
            va.SetIndexBuffer(IndexBuffer.Create(Indices));
            return(va);
        }
Exemple #14
0
    static SkyComponent()
    {
        // 円周方向の分割数
        const int Slices = 16;

        // Y方向の分割数
        const int Stacks = 8;

        List <Vector3> positions = new List <Vector3>();

        for (int i = 0; i < Stacks + 1; i++)
        {
            float y = 1.0f - 2.0f * (float)i / Stacks;
            float r = sqrt(1 - y * y);
            for (int j = 0; j < Slices + 1; j++)
            {
                float   t = (float)j / Slices * 3.14159f * 2;
                float   x = r * cos(t);
                float   z = r * sin(t);
                Vector3 v = new Vector3(x / 2, y / 2, z / 2);
                positions.Add(v);
            }
        }
        VertexBuffer.Create(positions.ToArray(), Accessibility.None);

        List <int> indices = new List <int>();

        for (int i = 0; i < Stacks; i++)
        {
            for (int j = 0; j < Slices; j++)
            {
                int i0 = (Slices + 1) * i + j;
                int i1 = i0 + 1;
                int i2 = (Slices + 1) * (i + 1) + j;
                int i3 = i2 + 1;
                indices.Add(i0);
                indices.Add(i2);
                indices.Add(i1);
                indices.Add(i1);
                indices.Add(i2);
                indices.Add(i3);
            }
        }
        IndexBuffer.Create(indices.ToArray(), Accessibility.None);

        Texture.CreateCubeMap("res/texture/skybox.dds", Accessibility.None);

        VertexShader.CreateFromFile("res/shader/SkyVertexShader.hlsl");
        PixelShader.CreateFromFile("res/shader/SkyPixelShader.hlsl");

        VertexLayout.Create(new VertexElement[]
        {
            new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0),
        }, VertexShader);
    }
Exemple #15
0
        public override void Init()
        {
            Camera.FoV         = 75f;
            Camera.AspectRatio = width / (float)height;
            Camera.Position    = new Vector3(0f, 0f, -2f);
            Camera.zNear       = 0.1f;
            Camera.zFar        = 150f;

            vertexBuffer  = VertexBuffer.Create(BufferUsage.Dynamic);
            indexBuffer   = IndexBuffer.Create(BufferUsage.Dynamic);
            geometryInput = GeometryInput.Create(indexBuffer, new VertexStream(vertexBuffer, vertexFormat));
        }
Exemple #16
0
 private void CreateIndexBuffer()
 {
     CreateIndices();
     indexBuffer = new IndexBuffer();
     indexBuffer.Create(my_OpenGL);
     indexBuffer.Bind(my_OpenGL);
     uint[] indis = new uint[my_Indices.Length];
     for (int I = 0; I < my_Indices.Length; I++)
     {
         indis[I] = (uint)my_Indices[I];
     }
     indexBuffer.SetData(my_OpenGL, indis);
 }
Exemple #17
0
        public void BuildVertexArray()
        {
            foreach (var block in Blocks)
            {
                if (block is IBlockModel)
                {
                    var blockModel = block as IBlockModel;

                    ElementCount  += blockModel.Model.ElementCount;
                    VertecesCount += blockModel.Model.VertexCount;
                }
            }

            Vertices = new Vertex[VertecesCount];
            Elements = new uint[ElementCount];

            uint vertexPos  = 0;
            uint elementPos = 0;

            foreach (var block in Blocks)
            {
                var tempVertexPos = vertexPos;

                if (block is IBlockModel)
                {
                    var blockModel = block as IBlockModel;

                    blockModel.Model.Vertices.CopyTo(Vertices, vertexPos);
                    vertexPos += blockModel.Model.VertexCount;

                    foreach (var element in blockModel.Model.Elements)
                    {
                        Elements[elementPos] = tempVertexPos + element;
                        elementPos++;
                    }
                }
            }

            VertexBuffer = new VertexBuffer();
            IndexBuffer  = new IndexBuffer();

            VertexBuffer.Create();
            VertexBuffer.Bind();
            VertexBuffer.SetData(RawDataCreation.GenRawVertexData(Vertices));

            IndexBuffer.Create();
            IndexBuffer.Bind();
            IndexBuffer.SetData(Elements);
        }
        }                                                                                   // number of points for each line is 2, number of lines for each lightning is 10

        public LightningShot(SceneManager sceneManager, TriangleSelector worldTriangles, float worldInfinity = 5000, float shotSpeed = 0.1f, float shotRadius = 100)
        {
            this.sceneManager   = sceneManager;
            this.worldTriangles = worldTriangles;
            this.worldInfinity  = worldInfinity;
            this.shotSpeed      = shotSpeed;
            this.shotRadius     = shotRadius;

            indexBuffer = IndexBuffer.Create(IndexType._16Bit);
            indexBuffer.Reallocate(64000);
            for (int i = 0; i < indexBuffer.AllocatedCount - 1; i++)
            {
                indexBuffer.Add(i);
            }

            vertexBuffer = VertexBuffer.Create();
        }
Exemple #19
0
        public void GenerateGeometry(OpenGL gl)
        {
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            VertexBuffer vb = new VertexBuffer();

            vb.Create(gl);
            vb.Bind(gl);
            vb.SetData(gl, 0, vertices.SelectMany(v => ((vec3)v).ToArray()).ToArray(), false, 3);

            IndexBuffer ib = new IndexBuffer();

            ib.Create(gl);
            ib.Bind(gl);
            ib.SetData(gl, indices);
        }
Exemple #20
0
        /// <summary>
        /// Load content
        /// </summary>
        public void LoadContent()
        {
            SafeDispose(ref factory);
            SafeDispose(ref vertexBuffers);
            SafeDispose(ref indexBuffers);

            uberShader = Content.Load <Ubershader>("render");

            //factory		=	new StateFactory(
            //					uberShader,
            //					typeof(RenderFlags),
            //					Primitive.PatchList3CP,
            //					VertexColorTextureTBN.Elements,
            //					BlendState.Opaque,
            //					RasterizerState.CullCW,
            //					DepthStencilState.Default
            //				);

            factory = new StateFactory(uberShader, typeof(RenderFlags), (x, i) => EnumFunc(x, (RenderFlags)i));

            scene = Content.Load <Scene>(@"scene");


            vertexBuffers = scene.Meshes
                            .Select(m => VertexBuffer.Create(GraphicsDevice, m.Vertices.Select(VertexColorTextureTBN.Convert).ToArray()))
                            .ToArray();

            indexBuffers = scene.Meshes
                           .Select(m => IndexBuffer.Create(GraphicsDevice, m.GetIndices()))
                           .ToArray();

            textures    = new Texture2D[5];
            textures[0] = Content.Load <Texture2D>("checker");
            textures[1] = Content.Load <Texture2D>(@"Textures\rockA");
            textures[2] = Content.Load <Texture2D>(@"Textures\rockA_local");
            textures[3] = Content.Load <Texture2D>(@"Textures\sandDune");
            textures[4] = Content.Load <Texture2D>(@"Textures\sandDune_local");


            worldMatricies = new Matrix[scene.Nodes.Count];
            scene.CopyAbsoluteTransformsTo(worldMatricies);

            Log.Message("{0}", scene.Nodes.Count(n => n.MeshIndex >= 0));
        }
Exemple #21
0
        public Panel(Color4?borderColor = null, float borderThickness = 0)
        {
            BorderColor     = borderColor ?? Color4.White;
            BorderThickness = borderThickness;
            Margin          = 1f;

            VertexBuffer vbo = new VertexBuffer(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Position, VertexAttribPointerType.Float, 3)
            }), 0, BufferUsageHint.StreamDraw, BeginMode.Triangles);

            _backgroundVao = new VertexArray(vbo, IndexBuffer.Create(new ushort[] { 0, 1, 2, 3, 2, 1 }));

            vbo = new VertexBuffer(new VertexFormat(new List <VertexAttribute>()
            {
                new VertexAttribute(VertexUsage.Position, VertexAttribPointerType.Float, 3)
            }), 0, BufferUsageHint.StreamDraw, BeginMode.Lines);
            _borderVao = new VertexArray(vbo, IndexBuffer.Create(new ushort[] { 0, 1, 1, 2, 2, 3, 3, 0 }));
        }
Exemple #22
0
        protected override void OnLoad(EventArgs e)
        {
            VSync = VSyncMode.On;

            GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f);
            GL.Enable(EnableCap.DepthTest);

            float aspectRatio = ClientSize.Width / (float)(ClientSize.Height);

            Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspectRatio, 1, 100, out projectionMatrix);
            modelviewMatrix = Matrix4.LookAt(new Vector3(0, 3, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            //shader = new Program(vertexShaderSource, fragmentShaderSource);
            //shader.Bind();
            //shader.UniformMatrix4("camera", false, ref projectionMatrix);
            //shader.UniformMatrix4("model", false, ref modelviewMatrix);
            //shader.Unbind();


            ContentManager content = new ContentManager(new ServiceProvider(), "content");

            content.RegisterTypeReader <Texture2D>(new Texture2DReader());
            content.RegisterTypeReader <Program>(new ShaderSourceReader());
            texture = content.Get <Texture2D>("\\wooden-crate.meb").Content as Texture2D;
            shader  = content.Get <Program>("\\simpleTextureShader.meb").Content as Program;
            shader.Bind();
            shader.UniformMatrix4("camera", false, ref projectionMatrix);
            shader.UniformMatrix4("model", false, ref modelviewMatrix);
            shader.Unbind();

            positionVbo = VertexBuffer.Create(VertexFormat.PositionTexture, positionVboData);
            //normalVbo = VertexBuffer.Create(new VertexFormat(new List<VertexAttribute>() { new VertexAttribute(VertexUsage.TextureCoordinate, VertexAttribPointerType.Float, 0, 2) }), textureVboData);

            indexVbo = IndexBuffer.Create(indicesVboData);
            vao      = new VertexArray(positionVbo, indexVbo);
            Utilities.CheckGLError();
            vao.AddBinding(shader.VertexAttribute("vert").Slot, VertexUsage.Position);
            vao.AddBinding(shader.VertexAttribute("vertTexCoord").Slot, VertexUsage.TextureCoordinate);
            Utilities.CheckGLError();
        }
Exemple #23
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="Canvas" /> class.
        /// </summary>
        /// <param name="graphicsDevice"> The graphics device. </param>
        /// <exception cref="NullReferenceException"> Thrown when a value was unexpectedly null. </exception>
        public Canvas(IGraphicsDevice graphicsDevice)
        {
            _context = graphicsDevice.DeviceContext;

            _defaultBlendState        = graphicsDevice.BlendStates.AlphaBlend;
            _defaultSamplerState      = graphicsDevice.SamplerStates.LinearWrap;
            _defaultDepthStencilState = graphicsDevice.DepthStencilStates.None;

            _defaultRasterizerState = graphicsDevice.RasterizerStates.CullBackDepthClipOff;
            _defaultRasterizerScissorEnabledState = graphicsDevice.RasterizerStates.CullBackDepthClipOffScissorEnabled;

            _indexBuffer = IndexBuffer.Create(graphicsDevice, s_indices);

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream stream =
                       assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{Shaders.CANVAS}") ??
                       throw new NullReferenceException($"{assembly.GetName().Name}.{Shaders.CANVAS}"))
            {
                Shader.Shader.Group group =
                    (_shader = ShaderFileLoader.FromStream(graphicsDevice, stream) ??
                               throw new NullReferenceException(nameof(ShaderFileLoader.FromStream)))["DEFAULT"];
Exemple #24
0
        /// <summary>
        /// Load content
        /// </summary>
        public void LoadContent()
        {
            SafeDispose(ref factory);
            SafeDispose(ref vertexBuffers);
            SafeDispose(ref indexBuffers);

            uberShader = Content.Load <Ubershader>("render");

            factory = new StateFactory(
                uberShader,
                typeof(RenderFlags),
                Primitive.TriangleList,
                VertexColorTextureNormal.Elements,
                BlendState.Opaque,
                RasterizerState.CullCW,
                DepthStencilState.Default
                );

            scene = Content.Load <Scene>(@"Scenes\testScene");


            vertexBuffers = scene.Meshes
                            .Select(m => VertexBuffer.Create(GraphicsDevice, m.Vertices.Select(v => VertexColorTextureNormal.Convert(v)).ToArray()))
                            .ToArray();

            indexBuffers = scene.Meshes
                           .Select(m => IndexBuffer.Create(GraphicsDevice, m.GetIndices()))
                           .ToArray();

            textures = scene.Materials
                       .Select(mtrl => Content.Load <Texture2D>(mtrl.TexturePath))
                       .ToArray();

            worldMatricies = new Matrix[scene.Nodes.Count];
            scene.CopyAbsoluteTransformsTo(worldMatricies);

            //Log.Message("{0}", scene.Nodes.Count( n => n.MeshIndex >= 0 ) );
        }
Exemple #25
0
        public override void GenerateGeometry(OpenGL gl)
        {
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            VertexBuffer vb = new VertexBuffer();

            vb.Create(gl);
            vb.Bind(gl);
            vb.SetData(gl, 0, Vertices.SelectMany(v => ((vec3)v).ToArray()).ToArray(), false, 3);

            VertexBuffer nb = new VertexBuffer();

            nb.Create(gl);
            nb.Bind(gl);
            nb.SetData(gl, 1, Vertices.SelectMany(v => ((vec3)v).ToArray()).ToArray(), false, 3);

            IndexBuffer ib = new IndexBuffer();

            ib.Create(gl);
            ib.Bind(gl);
            ib.SetData(gl, Faces.SelectMany(v => v).Select(v => (ushort)v).ToArray());
        }
Exemple #26
0
        public override void GenerateGeometry(OpenGL gl)
        {
            vertexBufferArray = new VertexBufferArray();
            vertexBufferArray.Create(gl);
            vertexBufferArray.Bind(gl);

            VertexBuffer vb = new VertexBuffer();

            vb.Create(gl);
            vb.Bind(gl);
            vb.SetData(gl, 0, vertexTriangles.Select(v => vertices[v]).SelectMany(v => ((vec3)v).ToArray()).ToArray(), false, 3);

            VertexBuffer nb = new VertexBuffer();

            nb.Create(gl);
            nb.Bind(gl);
            nb.SetData(gl, 1, vertexNormals.SelectMany(v => ((vec3)v).ToArray()).ToArray(), false, 3);

            IndexBuffer ib = new IndexBuffer();

            ib.Create(gl);
            ib.Bind(gl);
            ib.SetData(gl, Enumerable.Range(0, 36).Select(v => (ushort)v).ToArray());
        }
Exemple #27
0
    static JetComponent()
    {
        VertexShader.CreateFromFile("res/shader/JetVertexShader.hlsl");
        PixelShader.CreateFromFile("res/shader/JetPixelShader.hlsl");

        VertexLayout.Create(new VertexElement[]
        {
            new VertexElement("POSITION", 0, Format.Float3, 0, 0, VertexElement.Classification.VertexData, 0),
            new VertexElement("TEXCOORD", 0, Format.Float2, 1, 0, VertexElement.Classification.VertexData, 0),
        }, VertexShader);

        const int DIVISIONS = 24;   // 円の三角形の分割数
        const int LENGTH    = 4;    // 円の数

        // 頂点数
        const int VERTICES = (DIVISIONS + 1 + 1) * LENGTH + DIVISIONS * 4 / 2;

        // インデックス数
        const int INDICES = DIVISIONS * LENGTH * 3 + DIVISIONS * 2 * 3 / 2;

        // 頂点バッファを作成する
        {
            Vector3[] positions = new Vector3[VERTICES];
            Vector2[] texcoords = new Vector2[VERTICES];
            int       idx       = 0;

            for (int l = 0; l < LENGTH; l++)
            {
                // 中心の点
                float u = (float)l / (LENGTH - 1);
                float z = -(float)l / (LENGTH - 1);
                positions[idx] = new Vector3(0, 0, z);
                texcoords[idx] = new Vector2(0, 0.5f);
                idx++;

                // 円周上の点
                for (int d = 0; d < DIVISIONS + 1; d++)
                {
                    const float pi2 = (float)Math.PI * 2.0f;
                    float       r   = 0.5f - 0.25f * l / (LENGTH - 1); // 0.25 -> 0.125
                    float       t   = pi2 * (float)d / DIVISIONS;      // 0 -> pie * 2
                    float       x   = r * cos(t);
                    float       y   = r * sin(t);
                    float       v   = 0;
                    positions[idx] = new Vector3(x, y, z);
                    texcoords[idx] = new Vector2(u, v);
                    idx++;
                }
            }

            // 断面の点
            for (int d = 0; d < DIVISIONS / 2; d++)
            {
                const float pi = (float)Math.PI;
                float       t  = pi * d / DIVISIONS * 2;            // 0 -> pie
                float       x  = 0.5f * cos(t);
                float       y  = -0.5f * sin(t);
                var         p0 = new Vector3(-x, -y, 0);
                var         p1 = new Vector3(x, y, 0);
                var         p2 = new Vector3(-0.5f * x, -0.5f * y, -1);
                var         p3 = new Vector3(0.5f * x, 0.5f * y, -1);
                var         t0 = new Vector2(0, 0);
                var         t1 = new Vector2(0, 1);
                var         t2 = new Vector2(1, 0);
                var         t3 = new Vector2(1, 1);
                positions[idx] = p0;
                texcoords[idx] = t0;
                idx++;
                positions[idx] = p1;
                texcoords[idx] = t1;
                idx++;
                positions[idx] = p2;
                texcoords[idx] = t2;
                idx++;
                positions[idx] = p3;
                texcoords[idx] = t3;
                idx++;
            }
            VertexPositionsBuffer.Create(positions, Accessibility.None);
            VertexTexcoordsBuffer.Create(texcoords, Accessibility.None);
        }

        // インデックスバッファを作成する
        {
            int[] indexBufferSource = new int[INDICES];
            int   idx = 0;
            {
                // 円の描画
                for (int l = 0; l < LENGTH; l++)
                {
                    int offset = l * (DIVISIONS + 2);
                    for (int d = 0; d < DIVISIONS; d++)
                    {
                        indexBufferSource[idx++] = offset + 0;
                        indexBufferSource[idx++] = offset + d + 1;
                        indexBufferSource[idx++] = offset + d + 2;
                    }
                }

                // 円柱の描画
                for (int d = 0; d < DIVISIONS / 2; d++)
                {
                    const int offset = (DIVISIONS + 1 + 1) * LENGTH;
                    int       i0     = offset + d * 4;
                    int       i1     = offset + d * 4 + 1;
                    int       i2     = offset + d * 4 + 2;
                    int       i3     = offset + d * 4 + 3;
                    indexBufferSource[idx++] = i0;
                    indexBufferSource[idx++] = i1;
                    indexBufferSource[idx++] = i2;
                    indexBufferSource[idx++] = i2;
                    indexBufferSource[idx++] = i1;
                    indexBufferSource[idx++] = i3;
                }
            }
            IndexBuffer.Create(indexBufferSource, Accessibility.None);
        }

        // テクスチャを作成する
        Texture.Create("res/texture/jet.dds", Accessibility.None);
    }
Exemple #28
0
        public void UltravioletGraphics_CanRenderInstancedTriangles()
        {
            var effect     = default(Effect);
            var vbuffer0   = default(VertexBuffer);
            var vbuffer1   = default(VertexBuffer);
            var ibuffer0   = default(IndexBuffer);
            var geomstream = default(GeometryStream);

            const Int32 InstancesX = 48;
            const Int32 InstancesY = 36;

            const Single TriangleWidth  = 10f;
            const Single TriangleHeight = 10f;

            var result = GivenAnUltravioletApplication()
                         .WithContent(content =>
            {
                effect = content.Load <Effect>("Effects\\InstancedRenderingTestEffect");

                vbuffer0 = VertexBuffer.Create(VertexPosition.VertexDeclaration, 3);
                vbuffer0.SetData(new[]
                {
                    new VertexPosition(new Vector3(0, 0, 0)),
                    new VertexPosition(new Vector3(TriangleWidth, 0, 0)),
                    new VertexPosition(new Vector3(0, TriangleHeight, 0))
                });

                var instanceData = new CanRenderInstancedTrianglesData[InstancesX * InstancesY];
                for (int y = 0; y < InstancesY; y++)
                {
                    for (int x = 0; x < InstancesX; x++)
                    {
                        var transform =
                            Matrix.CreateTranslation(x * TriangleWidth, y * TriangleHeight, 0);

                        var color = new Color(
                            Math.Max(0, 255 - 5 * x),
                            Math.Max(0, 255 - 5 * y), 0);

                        instanceData[(y * InstancesX) + x] = new CanRenderInstancedTrianglesData(transform, color);
                    }
                }

                vbuffer1 = VertexBuffer.Create(CanRenderInstancedTrianglesData.VertexDeclaration, instanceData.Length);
                vbuffer1.SetData(instanceData);

                ibuffer0 = IndexBuffer.Create(IndexBufferElementType.Int16, 3);
                ibuffer0.SetData(new Int16[] { 0, 1, 2 });

                geomstream = GeometryStream.Create();
                geomstream.Attach(vbuffer0);
                geomstream.Attach(vbuffer1, 1);
                geomstream.Attach(ibuffer0);
            })
                         .Render(uv =>
            {
                var gfx      = uv.GetGraphics();
                var viewport = gfx.GetViewport();

                var matrixTransform = Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);
                effect.Parameters["MatrixTransform"].SetValue(matrixTransform);

                foreach (var pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    gfx.SetRasterizerState(RasterizerState.CullNone);
                    gfx.SetGeometryStream(geomstream);
                    gfx.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 1, InstancesX * InstancesY);
                }
            });

            TheResultingImage(result)
            .ShouldMatch(@"Resources/Expected/Graphics/UltravioletGraphics_CanRenderInstancedTriangles.png");
        }
Exemple #29
0
        public override void Init()
        {
            //Window.SetIcon("textures/icon.png");

            Platform.RelativeMouseMode = true;
            //Platform.ShowCursor = false; // Default true

            Camera.FoV         = 75f;
            Camera.AspectRatio = width / (float)height;
            Camera.Position    = new Vector3(0f, 2f, -5f);
            //Camera.Projection = Projection.Orthographic;
            //Camera.Width = Window.Width / 10;
            //Camera.Height = Window.Height / 10;
            Camera.zNear = 0.1f;
            Camera.zFar  = 150f;

            surface = Framebuffer.Create(width, height, 1, TextureFormat.RGB8, TextureFormat.Depth24);

            vertexFormat = new VertexFormat(
                4,                                                                    // Pack
                new VertexAttribute(DataType.Float, 3, false),                        // Position
                new VertexAttribute(DataType.Float, 3, false),                        // Normal
                new VertexAttribute(DataType.UnsignedByte, 4, true),                  // Colour
                new VertexAttribute(DataType.UnsignedShort, 2, true),                 // UV
                new VertexAttribute(DataType.UnsignedByte, 1, true)                   // Textured
                );

            Geometry cubeGeometry = Geometry.Cube();

            cubeVertices = new Vertex[cubeGeometry.Vertices.Length];
            for (int i = 0; i < cubeGeometry.Vertices.Length; i++)
            {
                cubeVertices[i] = new Vertex(cubeGeometry.Vertices[i].Position, cubeGeometry.Vertices[i].Normal, cubeGeometry.Vertices[i].Colour, cubeGeometry.Vertices[i].UV, false);
            }
            cubeIndices = cubeGeometry.Indices16;

            Geometry icosphereGeometry = Geometry.Icosphere(0.5f, 4);

            icosphereVertices = new Vertex[icosphereGeometry.Vertices.Length];
            for (int i = 0; i < icosphereGeometry.Vertices.Length; i++)
            {
                icosphereVertices[i] = new Vertex(icosphereGeometry.Vertices[i].Position, icosphereGeometry.Vertices[i].Normal, icosphereGeometry.Vertices[i].Colour, icosphereGeometry.Vertices[i].UV, false);
            }
            icosphereIndices = icosphereGeometry.Indices16;

            Geometry planeGeometry = Geometry.Plane(1f, Geometry.Orientation.XZ, 10, 10, false);

            planeVertices = new Vertex[planeGeometry.Vertices.Length];
            for (int i = 0; i < planeGeometry.Vertices.Length; i++)
            {
                planeVertices[i] = new Vertex(planeGeometry.Vertices[i].Position, planeGeometry.Vertices[i].Normal, planeGeometry.Vertices[i].Colour, planeGeometry.Vertices[i].UV, false);
            }
            planeIndices = planeGeometry.Indices16;

            cubeVertexBuffer       = VertexBuffer.Create(BufferUsage.Static);
            cubeIndexBuffer        = IndexBuffer.Create(BufferUsage.Static);
            icosphereVertexBuffer  = VertexBuffer.Create(BufferUsage.Static);
            icosphereIndexBuffer   = IndexBuffer.Create(BufferUsage.Static);
            planeVertexBuffer      = VertexBuffer.Create(BufferUsage.Static);
            planeIndexBuffer       = IndexBuffer.Create(BufferUsage.Static);
            cubeGeometryInput      = GeometryInput.Create(cubeIndexBuffer, new VertexStream(cubeVertexBuffer, vertexFormat));
            icosphereGeometryInput = GeometryInput.Create(icosphereIndexBuffer, new VertexStream(icosphereVertexBuffer, vertexFormat));
            planeGeometryInput     = GeometryInput.Create(planeIndexBuffer, new VertexStream(planeVertexBuffer, vertexFormat));
            cubeVertexBuffer.LoadData(cubeVertices);
            cubeIndexBuffer.LoadData(cubeIndices);
            icosphereVertexBuffer.LoadData(icosphereVertices);
            icosphereIndexBuffer.LoadData(icosphereIndices);
            planeVertexBuffer.LoadData(planeVertices);
            planeIndexBuffer.LoadData(planeIndices);

            light1Transform.Parent = light1ParentTransform;
            light2Transform.Parent = light2ParentTransform;
            light3Transform.Parent = light3ParentTransform;
        }
Exemple #30
0
        public unsafe void UpdateBuffers(RenderContext renderContext, ImDrawDataPtr drawData)
        {
            if (drawData.TotalVtxCount == 0)
            {
                return;
            }

            // Expand buffers if we need more room.
            if (drawData.TotalVtxCount > _vertexBufferSize)
            {
                _vertexBuffer?.Dispose();

                _vertexBufferSize = (int)(drawData.TotalVtxCount * 1.5f);
                _vertexBuffer     = VertexBuffer.Create <VertexPosition2TextureColor>(renderContext,
                                                                                      _vertexBufferSize,
                                                                                      BufferUsageHint.StreamDraw,
                                                                                      immutable: true);
                _vertexBuffer.Label = "IMGUI VertexBuffer";
                _vertexData         = new VertexPosition2TextureColor[_vertexBufferSize];
            }

            if (drawData.TotalIdxCount > _indexBufferSize)
            {
                _indexBuffer?.Dispose();

                _indexBufferSize = (int)(drawData.TotalIdxCount * 1.5f);
                _indexBuffer     = IndexBuffer.Create <ushort>(renderContext,
                                                               _indexBufferSize,
                                                               BufferUsageHint.StreamDraw,
                                                               immutable: true);
                _indexBuffer.Label = "IMGUI IndexBuffer";
                _indexData         = new ushort[_indexBufferSize];
            }

            // Copy ImGui's vertices and indices to a set of managed byte arrays
            int vtxOffset = 0;
            int idxOffset = 0;

            for (int n = 0; n < drawData.CmdListsCount; n++)
            {
                ImDrawListPtr cmdList = drawData.CmdListsRange[n];

                fixed(void *vtxDstPtr = &_vertexData[vtxOffset])
                fixed(void *idxDstPtr = &_indexData[idxOffset])
                {
                    System.Buffer.MemoryCopy((void *)cmdList.VtxBuffer.Data,
                                             vtxDstPtr,
                                             _vertexData.Length * sizeof(ImDrawVert),
                                             cmdList.VtxBuffer.Size * sizeof(ImDrawVert));
                    System.Buffer.MemoryCopy((void *)cmdList.IdxBuffer.Data,
                                             idxDstPtr,
                                             _indexData.Length * sizeof(ushort),
                                             cmdList.IdxBuffer.Size * sizeof(ushort));
                }

                vtxOffset += cmdList.VtxBuffer.Size;
                idxOffset += cmdList.IdxBuffer.Size;
            }

            // Copy the managed byte arrays to the gpu vertex and index buffers
            _vertexBuffer.SubData(_vertexData, 0, drawData.TotalVtxCount);
            _indexBuffer.SubData(_indexData, 0, drawData.TotalIdxCount);
        }