public static async Task BeginMonitoring(int interval)
        {
           var _recipients =  System.Configuration.ConfigurationManager.AppSettings["To"].ToString();
            List<Resource> resources = new List<Resource>();

            var urls = System.Configuration.ConfigurationManager.AppSettings["resources"].Split(',').ToList();

            urls.ForEach(s =>
            {
                Resource r = new ResourceFactory().GetResource(s);
                if (r.Exist())
                    resources.Add(r);
                else
                   Console.WriteLine("Unrecognizable resource: {0} . Please verify config file", string.Concat(r.Name,"@",r.GetAbsoluteUri()));
            });
  
            try {
                StateMonitor sm = new StateMonitor(_interval,resources);
                await sm.Init();
            }
            catch(System.AggregateException ex)
            {
                Console.WriteLine("Program Crashed because of " + ex.Data);
                IList<State> st = new List<State>();
                st.Add(new State() { Status = ex.StackTrace });
                StateLogger.SendAlertNotification(st, _recipients);
            }
            


        }
Example #2
0
 /// <summary>Traduz uma ResourceFactory para texto localizado</summary>
 public string translate( ResourceFactory factory )
 {
     return string.Format("<a href='{0}' class='docs'>{1}</a>",
             OrionGlobals.getSectionBaseUrl("docs") + "?category="+factory.Category+"#"+factory.Name,
             info.getContent(factory.Name)
         );
 }
 public static ResourceFactory GetInstance()
 {
     if(instance == null)
     {
         instance = new ResourceFactory();
     }
     return instance;
 }
Example #4
0
        /// <summary>
        /// Default construction
        /// </summary>
        public StaticImage(ResourceFactory resource, VectorInt tileSize)
        {
            if (resource == null) throw new ArgumentNullException("resource");
            this.tileSize = tileSize;
            Resources = resource;

            InitTiles();
        }
        public ResourceString(ResourceFactory factory, ResourceType type, XmlElement xmlConfigData)
            : base(factory, type, xmlConfigData)
        {
            XmlElement xmlString = xmlConfigData["String"];
            if (xmlString == null) throw new Exception("Expected XML String tag");

            dataUnTyped = xmlString.InnerText;
        }
 public ResourceBrush(ResourceFactory factory, ResourceType type, XmlElement xmlConfigData)
     : base(factory, type, xmlConfigData)
 {
     XmlElement xmlSolidBrush = xmlConfigData["SolidBrush"];
     if (xmlSolidBrush != null)
     {
         dataUnTyped = new SolidBrush(ColorFromXML(xmlSolidBrush));
     }
 }
        public ResourceImage(ResourceFactory factory, ResourceType type, XmlElement xmlConfigData)
            : base(factory, type, xmlConfigData)
        {
            XmlElement xmlImage = xmlConfigData["Image"];
            if (xmlImage == null) throw new Exception("Expected XML Image tag");
            if (!xmlImage.HasAttribute("FileName")) throw new Exception("Image Xml Element must have FileName attribute");

            dataUnTyped = Image.FromFile(factory.BuildFullPath(xmlImage.GetAttribute("FileName")));
        }
Example #8
0
        public ResourceFont(ResourceFactory factory, ResourceType type, XmlElement xmlConfigData)
            : base(factory, type, xmlConfigData)
        {
            XmlElement xmlFont = xmlConfigData["Font"];
            if (xmlFont == null) throw new Exception("Expected XML Font tag");

            dataUnTyped = new Font(xmlFont.GetAttribute("Name"),
                float.Parse(xmlFont.GetAttribute("Size")),
                (FontStyle)Enum.Parse(typeof(FontStyle), xmlFont.GetAttribute("Style")));
        }
Example #9
0
        public static void Main(string[] args)
        {
            IBuildingFactory buildingFactory = new BuildingFactory();
            IUnitFactory unitFactory = new UnitFactory();
            IResourceFactory resourceFactory = new ResourceFactory();
            IInputReader reader = new ConsoleReader();
            IOutputWriter writer = new ConsoleWriter();
            IEmpiresData database = new Database();

            IEngine engine = new Engine(unitFactory, resourceFactory, buildingFactory, reader, writer, database);
            engine.Run();
        }
        static void Main()
        {
            var buildingFactory = new BuildingFactory();
            var unitFactory = new UnitFactory();
            var resourceFactory = new ResourceFactory();
            var reader = new ConsoleReader();
            var writer = new ConsoleWriter();
            var data = new EmpiresData();

            var engine = new Engine(buildingFactory,resourceFactory,unitFactory,data,reader,writer);
            engine.Run();
        }
        private void CreateResources(ResourceFactory factory)
        {
            _screenSizeBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            _shiftBuffer      = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            _vertexBuffer     = factory.CreateBuffer(new BufferDescription(16 * 4, BufferUsage.VertexBuffer));
            _indexBuffer      = factory.CreateBuffer(new BufferDescription(2 * 6, BufferUsage.IndexBuffer));

            _computeShader = factory.CreateShader(new ShaderDescription(
                                                      ShaderStages.Compute,
                                                      File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Shaders", $"Compute.{GetExtension(factory.BackendType)}"))));

            _computeLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                              new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadWrite, ShaderStages.Compute),
                                                              new ResourceLayoutElementDescription("ScreenSizeBuffer", ResourceKind.UniformBuffer, ShaderStages.Compute),
                                                              new ResourceLayoutElementDescription("ShiftBuffer", ResourceKind.UniformBuffer, ShaderStages.Compute)));

            ComputePipelineDescription computePipelineDesc = new ComputePipelineDescription(
                new ShaderStageDescription(ShaderStages.Compute, _computeShader, "CS"),
                new[] { _computeLayout });

            _computePipeline = factory.CreateComputePipeline(ref computePipelineDesc);

            _vertexShader = factory.CreateShader(new ShaderDescription(
                                                     ShaderStages.Vertex,
                                                     File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Shaders", $"Vertex.{GetExtension(factory.BackendType)}"))));
            _fragmentShader = factory.CreateShader(new ShaderDescription(
                                                       ShaderStages.Fragment,
                                                       File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "Shaders", $"Fragment.{GetExtension(factory.BackendType)}"))));

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                    new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                new[]
            {
                new ShaderStageDescription(ShaderStages.Vertex, _vertexShader, "VS"),
                new ShaderStageDescription(ShaderStages.Fragment, _fragmentShader, "FS")
            });

            _graphicsLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                               new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                               new ResourceLayoutElementDescription("Tex11", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                               new ResourceLayoutElementDescription("Tex22", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                               new ResourceLayoutElementDescription("SS", ResourceKind.Sampler, ShaderStages.Fragment)));

            GraphicsPipelineDescription fullScreenQuadDesc = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, false, false),
                PrimitiveTopology.TriangleList,
                shaderSet,
                new[] { _graphicsLayout },
                _gd.SwapchainFramebuffer.OutputDescription);

            _graphicsPipeline = factory.CreateGraphicsPipeline(ref fullScreenQuadDesc);

            _cl = factory.CreateCommandList();

            CreateWindowSizedResources();
            InitResources(factory);
        }
Example #12
0
        public Shader LoadShader(ResourceFactory factory, string set, ShaderStages stage, string entryPoint)
        {
            string name = $"{set}-{stage.ToString().ToLower()}.{GetExtension(factory.BackendType)}";

            return(factory.CreateShader(new ShaderDescription(stage, ReadEmbeddedAssetBytes(name), entryPoint)));
        }
Example #13
0
        public unsafe override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc)
        {
            ResourceFactory factory = gd.ResourceFactory;

            _vb = factory.CreateVertexBuffer(new BufferDescription(s_vertices.SizeInBytes()));
            cl.UpdateBuffer(_vb, 0, s_vertices);

            _ib = factory.CreateIndexBuffer(new IndexBufferDescription(s_indices.SizeInBytes(), IndexFormat.UInt16));
            cl.UpdateBuffer(_ib, 0, s_indices);

            _viewMatrixBuffer = factory.CreateUniformBuffer(new BufferDescription((ulong)Unsafe.SizeOf <Matrix4x4>()));

            Texture     textureCube;
            TextureView textureView;

            fixed(Rgba32 *frontPin = &_front.DangerousGetPinnableReferenceToPixelBuffer())
            fixed(Rgba32 * backPin   = &_back.DangerousGetPinnableReferenceToPixelBuffer())
            fixed(Rgba32 * leftPin   = &_left.DangerousGetPinnableReferenceToPixelBuffer())
            fixed(Rgba32 * rightPin  = &_right.DangerousGetPinnableReferenceToPixelBuffer())
            fixed(Rgba32 * topPin    = &_top.DangerousGetPinnableReferenceToPixelBuffer())
            fixed(Rgba32 * bottomPin = &_bottom.DangerousGetPinnableReferenceToPixelBuffer())
            {
                uint width  = (uint)_front.Width;
                uint height = (uint)_front.Height;

                textureCube = factory.CreateTexture(new TextureDescription(
                                                        width,
                                                        height,
                                                        1,
                                                        1,
                                                        1,
                                                        PixelFormat.R8_G8_B8_A8_UNorm,
                                                        TextureUsage.Sampled | TextureUsage.Cubemap));

                uint faceSize = (uint)(_front.Width * _front.Height * Unsafe.SizeOf <Rgba32>());

                cl.UpdateTextureCube(textureCube, (IntPtr)leftPin, faceSize, CubeFace.NegativeX, 0, 0, width, height, 0, 0);
                cl.UpdateTextureCube(textureCube, (IntPtr)rightPin, faceSize, CubeFace.PositiveX, 0, 0, width, height, 0, 0);
                cl.UpdateTextureCube(textureCube, (IntPtr)bottomPin, faceSize, CubeFace.NegativeY, 0, 0, width, height, 0, 0);
                cl.UpdateTextureCube(textureCube, (IntPtr)topPin, faceSize, CubeFace.PositiveY, 0, 0, width, height, 0, 0);
                cl.UpdateTextureCube(textureCube, (IntPtr)backPin, faceSize, CubeFace.NegativeZ, 0, 0, width, height, 0, 0);
                cl.UpdateTextureCube(textureCube, (IntPtr)frontPin, faceSize, CubeFace.PositiveZ, 0, 0, width, height, 0, 0);

                textureView = factory.CreateTextureView(new TextureViewDescription(textureCube));
            }

            VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3))
            };

            Shader vs = ShaderHelper.LoadShader(factory, "Skybox", ShaderStages.Vertex);
            Shader fs = ShaderHelper.LoadShader(factory, "Skybox", ShaderStages.Fragment);

            ShaderStageDescription[] shaderStages = new ShaderStageDescription[]
            {
                new ShaderStageDescription(ShaderStages.Vertex, vs, "VS"),
                new ShaderStageDescription(ShaderStages.Fragment, fs, "VS"),
            };

            _layout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                       new ResourceLayoutElementDescription("Projection", ResourceKind.Uniform, ShaderStages.Vertex),
                                                       new ResourceLayoutElementDescription("View", ResourceKind.Uniform, ShaderStages.Vertex),
                                                       new ResourceLayoutElementDescription("CubeTexture", ResourceKind.Texture, ShaderStages.Fragment),
                                                       new ResourceLayoutElementDescription("CubeSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            PipelineDescription pd = new PipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                DepthStencilStateDescription.LessEqual,
                new RasterizerStateDescription(FaceCullMode.None, TriangleFillMode.Solid, FrontFace.Clockwise, false, true),
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(vertexLayouts, shaderStages),
                new ResourceLayout[] { _layout },
                gd.SwapchainFramebuffer.OutputDescription);

            _pipeline = factory.CreatePipeline(ref pd);

            _resourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                         _layout,
                                                         sc.ProjectionMatrixBuffer,
                                                         _viewMatrixBuffer,
                                                         textureView,
                                                         gd.PointSampler));

            _disposeCollector.Add(_vb, _ib, _viewMatrixBuffer, textureCube, textureView, _layout, _pipeline, _resourceSet, vs, fs);
        }
Example #14
0
 public DisposeCollectorResourceFactory(ResourceFactory factory, DisposeCollector disposeCollector)
     : base(factory.Features)
 {
     Factory          = factory;
     DisposeCollector = disposeCollector;
 }
Example #15
0
 protected abstract void CreateResources(ResourceFactory factory);
Example #16
0
        public void TestPermutation(TypeStruct fieldSet)
        {
            var(shaderInstructions, shaders) = CompileShaderForFieldSet(fieldSet);
            var shaderReflection = new ShaderReflection(shaderInstructions);
            var structure        = shaderReflection.Structures.Where(_ => _.DebugName == fieldSet.DebugName).First();

            CompareStructureLayout(structure, fieldSet);

            var bufferSize = structure.SizeInBytes;

            bufferSize = SpirvUtils.RoundUp(bufferSize, 16);
            var buffer = ResourceFactory.CreateBuffer(new BufferDescription(bufferSize, BufferUsage.UniformBuffer));

            Disposables.Add(buffer);

            var bytes   = new byte[bufferSize];
            var counter = 1;
            var hash    = 0;

            PopulateBuffer(bytes, 0, structure, ref counter, ref hash);
            GraphicsDevice.UpdateBuffer(buffer, 0, bytes);

            //structure.EvaluateLayout();

            //var hlsl = SpirvCompilation.CompileVertexFragment(vertex.SpirvBytes, fragment.SpirvBytes, CrossCompileTarget.HLSL, new CrossCompileOptions());
            //var glsl = SpirvCompilation.CompileVertexFragment(vertex.SpirvBytes, fragment.SpirvBytes, CrossCompileTarget.GLSL, new CrossCompileOptions());
            //var msl = SpirvCompilation.CompileVertexFragment(vertex.SpirvBytes, fragment.SpirvBytes, CrossCompileTarget.MSL, new CrossCompileOptions());
            //var essl = SpirvCompilation.CompileVertexFragment(vertex.SpirvBytes, fragment.SpirvBytes, CrossCompileTarget.ESSL, new CrossCompileOptions());


            var layout = ResourceFactory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                  new ResourceLayoutElementDescription("ModelBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            Disposables.Add(layout);

            var resourceSet = ResourceFactory.CreateResourceSet(new ResourceSetDescription(layout, buffer));

            Disposables.Add(resourceSet);

            var pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                new ShaderSetDescription(new[] { new VertexLayoutDescription(new VertexElementDescription[] { }) },
                                         shaders),
                new[] { layout },
                Framebuffer.OutputDescription);
            var pipeline = ResourceFactory.CreateGraphicsPipeline(pd);

            Disposables.Add(pipeline);

            CommandList.Begin();
            CommandList.SetFramebuffer(Framebuffer);
            CommandList.SetPipeline(pipeline);
            CommandList.SetGraphicsResourceSet(0, resourceSet);
            CommandList.Draw(1);
            CommandList.End();

            GraphicsDevice.SubmitCommands(CommandList);
            GraphicsDevice.WaitForIdle();

            var expected = new RgbaByte((byte)(hash % 256), (byte)(hash / 256 % 256), (byte)(hash / 65536 % 256),
                                        (byte)(hash / 16777216 % 256));
            var actual = ReadRenderTargetPixel();

            Assert.AreEqual(expected, actual);
        }
Example #17
0
        public AssimpMesh(GraphicsDevice gd, OutputDescription outputs, string meshPath, string texturePath)
        {
            _gd = gd;
            ResourceFactory factory = gd.ResourceFactory;

            Shader[] shaders = factory.CreateFromSpirv(
                new ShaderDescription(ShaderStages.Vertex, Encoding.ASCII.GetBytes(vertexGlsl), "main"),
                new ShaderDescription(ShaderStages.Fragment, Encoding.ASCII.GetBytes(fragmentGlsl), "main"));
            _disposables.Add(shaders[0]);
            _disposables.Add(shaders[1]);

            ResourceLayout rl = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                 new ResourceLayoutElementDescription("WVP", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                 new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                 new ResourceLayoutElementDescription("InputSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _disposables.Add(rl);

            VertexLayoutDescription positionLayoutDesc = new VertexLayoutDescription(
                new VertexElementDescription[]
            {
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
            });

            VertexLayoutDescription texCoordLayoutDesc = new VertexLayoutDescription(
                new VertexElementDescription[]
            {
                new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
            });

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           RasterizerStateDescription.CullNone,
                                                           PrimitiveTopology.TriangleList,
                                                           new ShaderSetDescription(new[] { positionLayoutDesc, texCoordLayoutDesc }, new Shader[] { shaders[0], shaders[1] }),
                                                           rl,
                                                           outputs));
            _disposables.Add(_pipeline);

            _wvpBuffer = factory.CreateBuffer(new BufferDescription(64 * 3, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _disposables.Add(_wvpBuffer);

            _texture = new ImageSharpTexture(texturePath, true, true).CreateDeviceTexture(gd, factory);
            _view    = factory.CreateTextureView(_texture);
            _disposables.Add(_texture);
            _disposables.Add(_view);

            _rs = factory.CreateResourceSet(new ResourceSetDescription(rl, _wvpBuffer, _view, gd.Aniso4xSampler));
            _disposables.Add(_rs);

            AssimpContext ac    = new AssimpContext();
            Scene         scene = ac.ImportFile(meshPath);

            foreach (Mesh mesh in scene.Meshes)
            {
                DeviceBuffer positions = CreateDeviceBuffer(mesh.Vertices, BufferUsage.VertexBuffer);
                DeviceBuffer texCoords = CreateDeviceBuffer(
                    mesh.TextureCoordinateChannels[0].Select(v3 => new Vector2(v3.X, v3.Y)).ToArray(),
                    BufferUsage.VertexBuffer);
                DeviceBuffer indices = CreateDeviceBuffer(mesh.GetUnsignedIndices(), BufferUsage.IndexBuffer);

                _meshPieces.Add(new MeshPiece(positions, texCoords, indices));
            }
        }
Example #18
0
 public bool WasSetResourceFactoryCalledWith(ResourceFactory factory)
 {
     return(itsMethodCalls.WasMethodCalledWith("SetResourceFactory", factory));
 }
Example #19
0
 /**
  * Adds a Resource type so that createResourceByType() can be called to create
  * Resource instances.
  *
  * @param type
  *      Type name of the Resource factory to install
  * @param factory
  *      Factory that will create instances of the Resource type
  * @return
  *      True upon success, false upon failure
  */
 public bool addResourceType(string type, ResourceFactory factory)
 {
     string n = normalize(type);
     resource_factories[n] = factory;
     //TODO osgGIS.notify( osg.DEBUG_INFO ) << "osgGIS.Registry: Registered resource type " << type << std.endl;
     return true;
 }
Example #20
0
 /// <summary>Indica se determinado recurso tem determinado filtro</summary>
 private bool hasFilter( ResourceFactory factory )
 {
     if( factory.Keywords == null ) {
         return false;
     }
     return Array.IndexOf(factory.Keywords, filter) >= 0;
 }
        /// <summary>
        /// Obtain a NMS Session that is synchronized with the current transaction, if any.
        /// </summary>
        /// <param name="resourceKey">the TransactionSynchronizationManager key to bind to
        /// (usually the ConnectionFactory)</param>
        /// <param name="resourceFactory">the ResourceFactory to use for extracting or creating
        /// NMS resources</param>
        /// <param name="startConnection">whether the underlying Connection approach should be
	    /// started in order to allow for receiving messages. Note that a reused Connection
	    /// may already have been started before, even if this flag is <code>false</code>.</param>
        /// <returns>
        /// the transactional Session, or <code>null</code> if none found
        /// </returns>
        /// <throws>NMSException in case of NMS failure </throws>
        public static ISession DoGetTransactionalSession(Object resourceKey, ResourceFactory resourceFactory, bool startConnection)
        {
            AssertUtils.ArgumentNotNull(resourceKey, "Resource key must not be null");
            AssertUtils.ArgumentNotNull(resourceKey, "ResourceFactory must not be null");

            NmsResourceHolder resourceHolder =
                (NmsResourceHolder)TransactionSynchronizationManager.GetResource(resourceKey);
            if (resourceHolder != null)
            {
                ISession rhSession = resourceFactory.GetSession(resourceHolder);
                if (rhSession != null)
                {
                    if (startConnection)
                    {
                        IConnection conn = resourceFactory.GetConnection(resourceHolder);
                        if (conn != null)
                        {
                            conn.Start();
                        }
                    }
                    return rhSession;
                }
            }
            if (!TransactionSynchronizationManager.SynchronizationActive)
            {
                return null;
            }
            NmsResourceHolder resourceHolderToUse = resourceHolder;
            if (resourceHolderToUse == null)
            {
                resourceHolderToUse = new NmsResourceHolder();
            }

            IConnection con = resourceFactory.GetConnection(resourceHolderToUse);
            ISession session = null;
            try
            {
                bool isExistingCon = (con != null);
                if (!isExistingCon)
                {
                    con = resourceFactory.CreateConnection();
                    resourceHolderToUse.AddConnection(con);
                }
                session = resourceFactory.CreateSession(con);
                resourceHolderToUse.AddSession(session, con);
                if (startConnection)
                {
                    con.Start();
                }
            }
            catch (NMSException)
            {
                if (session != null)
                {
                    try
                    {
                        session.Close();
                    }
                    catch (Exception)
                    {
                        // ignore
                    }
                }
                if (con != null)
                {
                    try
                    {
                        con.Close();
                    }
                    catch (Exception)
                    {
                        // ignore
                    }
                }
                throw;
            }
            if (resourceHolderToUse != resourceHolder)
            {
                TransactionSynchronizationManager.RegisterSynchronization(
                    new NmsResourceSynchronization(resourceHolderToUse, resourceKey,
                                                   resourceFactory.SynchedLocalTransactionAllowed));
                resourceHolderToUse.SynchronizedWithTransaction = true;
                TransactionSynchronizationManager.BindResource(resourceKey, resourceHolderToUse);
            }
            return session;
        }
Example #22
0
 /// <summary>Escreve atributos numa hash</summary>
 private void writeDuration( HtmlTextWriter writer, ResourceFactory factory )
 {
     writer.WriteLine("<tr>");
     writer.WriteLine("<td class='resource'>{0}</td>", info.getContent("duration"));
     writer.WriteLine("<td class='resourceCell'>{0}</td>", factory.Duration.Value);
     writer.WriteLine("</tr>");
 }
Example #23
0
        private void Init(
            GraphicsDevice gd,
            ResourceFactory factory,
            Stream stream,
            string extension,
            VertexElementSemantic[] elementSemantics,
            ModelCreateInfo?createInfo,
            PostProcessSteps flags = DefaultPostProcessSteps)
        {
            // Load file
            AssimpContext assimpContext = new AssimpContext();
            Scene         pScene        = assimpContext.ImportFileFromStream(stream, DefaultPostProcessSteps, extension);

            parts.Clear();
            parts.Count = (uint)pScene.Meshes.Count;

            Vector3 scale   = new Vector3(1.0f);
            Vector2 uvscale = new Vector2(1.0f);
            Vector3 center  = new Vector3(0.0f);

            if (createInfo != null)
            {
                scale   = createInfo.Value.Scale;
                uvscale = createInfo.Value.UVScale;
                center  = createInfo.Value.Center;
            }

            RawList <float> vertices = new RawList <float>();
            RawList <uint>  indices  = new RawList <uint>();

            VertexCount = 0;
            IndexCount  = 0;

            // Load meshes
            for (int i = 0; i < pScene.Meshes.Count; i++)
            {
                var paiMesh = pScene.Meshes[i];

                parts[i]            = new ModelPart();
                parts[i].vertexBase = VertexCount;
                parts[i].indexBase  = IndexCount;

                VertexCount += (uint)paiMesh.VertexCount;

                var pColor = pScene.Materials[paiMesh.MaterialIndex].ColorDiffuse;

                Vector3D Zero3D = new Vector3D(0.0f, 0.0f, 0.0f);

                for (int j = 0; j < paiMesh.VertexCount; j++)
                {
                    Vector3D pPos       = paiMesh.Vertices[j];
                    Vector3D pNormal    = paiMesh.Normals[j];
                    Vector3D pTexCoord  = paiMesh.HasTextureCoords(0) ? paiMesh.TextureCoordinateChannels[0][j] : Zero3D;
                    Vector3D pTangent   = paiMesh.HasTangentBasis ? paiMesh.Tangents[j] : Zero3D;
                    Vector3D pBiTangent = paiMesh.HasTangentBasis ? paiMesh.BiTangents[j] : Zero3D;

                    foreach (VertexElementSemantic component in elementSemantics)
                    {
                        switch (component)
                        {
                        case VertexElementSemantic.Position:
                            vertices.Add(pPos.X * scale.X + center.X);
                            vertices.Add(-pPos.Y * scale.Y + center.Y);
                            vertices.Add(pPos.Z * scale.Z + center.Z);
                            break;

                        case VertexElementSemantic.Normal:
                            vertices.Add(pNormal.X);
                            vertices.Add(-pNormal.Y);
                            vertices.Add(pNormal.Z);
                            break;

                        case VertexElementSemantic.TextureCoordinate:
                            vertices.Add(pTexCoord.X * uvscale.X);
                            vertices.Add(pTexCoord.Y * uvscale.Y);
                            break;

                        case VertexElementSemantic.Color:
                            vertices.Add(pColor.R);
                            vertices.Add(pColor.G);
                            vertices.Add(pColor.B);
                            break;

                        default: throw new System.NotImplementedException();
                        }
                        ;
                    }

                    dim.Max.X = Math.Max(pPos.X, dim.Max.X);
                    dim.Max.Y = Math.Max(pPos.Y, dim.Max.Y);
                    dim.Max.Z = Math.Max(pPos.Z, dim.Max.Z);

                    dim.Min.X = Math.Min(pPos.X, dim.Min.X);
                    dim.Min.Y = Math.Min(pPos.Y, dim.Min.Y);
                    dim.Min.Z = Math.Min(pPos.Z, dim.Min.Z);
                }

                dim.Size = dim.Max - dim.Min;

                parts[i].vertexCount = (uint)paiMesh.VertexCount;

                uint indexBase = indices.Count;
                for (uint j = 0; j < paiMesh.FaceCount; j++)
                {
                    Face Face = paiMesh.Faces[(int)j];
                    if (Face.IndexCount != 3)
                    {
                        continue;
                    }
                    indices.Add(indexBase + (uint)Face.Indices[0]);
                    indices.Add(indexBase + (uint)Face.Indices[1]);
                    indices.Add(indexBase + (uint)Face.Indices[2]);
                    parts[i].indexCount += 3;
                    IndexCount          += 3;
                }
            }


            uint vBufferSize = (vertices.Count) * sizeof(float);
            uint iBufferSize = (indices.Count) * sizeof(uint);

            VertexBuffer = factory.CreateBuffer(new BufferDescription(vBufferSize, BufferUsage.VertexBuffer));
            IndexBuffer  = factory.CreateBuffer(new BufferDescription(iBufferSize, BufferUsage.IndexBuffer));

            gd.UpdateBuffer(VertexBuffer, 0, ref vertices[0], vBufferSize);
            gd.UpdateBuffer(IndexBuffer, 0, ref indices[0], iBufferSize);
        }
        public virtual void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, GraphicsSystem sc)
        {
            ResourceFactory factory = gd.ResourceFactory;

            ProjectionMatrixBuffer          = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            ViewMatrixBuffer                = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            LightViewProjectionBuffer0      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            LightViewProjectionBuffer0.Name = "LightViewProjectionBuffer0";
            LightViewProjectionBuffer1      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            LightViewProjectionBuffer1.Name = "LightViewProjectionBuffer1";
            LightViewProjectionBuffer2      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            LightViewProjectionBuffer2.Name = "LightViewProjectionBuffer2";
            DepthLimitsBuffer               = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <DepthCascadeLimits>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            LightInfoBuffer  = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <DirectionalLightInfo>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            CameraInfoBuffer = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <CameraInfo>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            if (Camera != null)
            {
                UpdateCameraBuffers(cl);
            }

            PointLightsBuffer = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <PointLightsInfo.Blittable>(), BufferUsage.UniformBuffer));

            PointLightsInfo pli = new PointLightsInfo();

            pli.NumActiveLights = 4;
            pli.PointLights     = new PointLightInfo[4]
            {
                new PointLightInfo {
                    Color = new Vector3(1f, 1f, 1f), Position = new Vector3(-50, 5, 0), Range = 75f
                },
                new PointLightInfo {
                    Color = new Vector3(1f, .75f, .9f), Position = new Vector3(0, 5, 0), Range = 100f
                },
                new PointLightInfo {
                    Color = new Vector3(1f, 1f, 0.6f), Position = new Vector3(50, 5, 0), Range = 40f
                },
                new PointLightInfo {
                    Color = new Vector3(0.75f, 0.75f, 1f), Position = new Vector3(25, 5, 45), Range = 150f
                },
            };

            cl.UpdateBuffer(PointLightsBuffer, 0, pli.GetBlittable());

            TextureSamplerResourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                            new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                            new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            uint ReflectionMapSize = 2048;

            ReflectionColorTexture   = factory.CreateTexture(TextureDescription.Texture2D(ReflectionMapSize, ReflectionMapSize, 12, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.RenderTarget | TextureUsage.Sampled | TextureUsage.GenerateMipmaps));
            ReflectionDepthTexture   = factory.CreateTexture(TextureDescription.Texture2D(ReflectionMapSize, ReflectionMapSize, 1, 1, PixelFormat.R32_Float, TextureUsage.DepthStencil));
            ReflectionColorView      = factory.CreateTextureView(ReflectionColorTexture);
            ReflectionFramebuffer    = factory.CreateFramebuffer(new FramebufferDescription(ReflectionDepthTexture, ReflectionColorTexture));
            ReflectionViewProjBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            MirrorClipPlaneBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer));
            gd.UpdateBuffer(MirrorClipPlaneBuffer, 0, new ClipPlaneInfo(MirrorMesh.Plane, true));
            NoClipPlaneBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer));
            gd.UpdateBuffer(NoClipPlaneBuffer, 0, new ClipPlaneInfo());

            RecreateWindowSizedResources(gd, cl);

            ShadowMaps.CreateDeviceResources(gd);
        }
Example #25
0
 public void SetResourceFactory(ResourceFactory factory)
 {
     itsMethodCalls.RecordMethodCall("SetResourceFactory", factory);
 }
        public void RecreateWindowSizedResources(GraphicsDevice gd, CommandList cl)
        {
            MainSceneColorTexture?.Dispose();
            MainSceneDepthTexture?.Dispose();
            MainSceneResolvedColorTexture?.Dispose();
            MainSceneResolvedColorView?.Dispose();
            MainSceneViewResourceSet?.Dispose();
            MainSceneFramebuffer?.Dispose();
            DuplicatorTarget0?.Dispose();
            DuplicatorTarget1?.Dispose();
            DuplicatorTargetView0?.Dispose();
            DuplicatorTargetView1?.Dispose();
            DuplicatorTargetSet0?.Dispose();
            DuplicatorTargetSet1?.Dispose();
            DuplicatorFramebuffer?.Dispose();

            ResourceFactory factory = gd.ResourceFactory;

            TextureSampleCount mainSceneSampleCountCapped = (TextureSampleCount)Math.Min(
                (int)gd.GetSampleCountLimit(PixelFormat.R8_G8_B8_A8_UNorm, false),
                (int)MainSceneSampleCount);

            TextureDescription mainColorDesc = TextureDescription.Texture2D(
                gd.SwapchainFramebuffer.Width,
                gd.SwapchainFramebuffer.Height,
                1,
                1,
                PixelFormat.R8_G8_B8_A8_UNorm,
                TextureUsage.RenderTarget | TextureUsage.Sampled,
                mainSceneSampleCountCapped);

            MainSceneColorTexture = factory.CreateTexture(ref mainColorDesc);
            if (mainSceneSampleCountCapped != TextureSampleCount.Count1)
            {
                mainColorDesc.SampleCount     = TextureSampleCount.Count1;
                MainSceneResolvedColorTexture = factory.CreateTexture(ref mainColorDesc);
            }
            else
            {
                MainSceneResolvedColorTexture = MainSceneColorTexture;
            }
            MainSceneResolvedColorView = factory.CreateTextureView(MainSceneResolvedColorTexture);
            MainSceneDepthTexture      = factory.CreateTexture(TextureDescription.Texture2D(
                                                                   gd.SwapchainFramebuffer.Width,
                                                                   gd.SwapchainFramebuffer.Height,
                                                                   1,
                                                                   1,
                                                                   PixelFormat.R32_Float,
                                                                   TextureUsage.DepthStencil,
                                                                   mainSceneSampleCountCapped));
            MainSceneFramebuffer     = factory.CreateFramebuffer(new FramebufferDescription(MainSceneDepthTexture, MainSceneColorTexture));
            MainSceneViewResourceSet = factory.CreateResourceSet(new ResourceSetDescription(TextureSamplerResourceLayout, MainSceneResolvedColorView, gd.PointSampler));

            TextureDescription colorTargetDesc = TextureDescription.Texture2D(
                gd.SwapchainFramebuffer.Width,
                gd.SwapchainFramebuffer.Height,
                1,
                1,
                PixelFormat.R8_G8_B8_A8_UNorm,
                TextureUsage.RenderTarget | TextureUsage.Sampled);

            DuplicatorTarget0     = factory.CreateTexture(ref colorTargetDesc);
            DuplicatorTargetView0 = factory.CreateTextureView(DuplicatorTarget0);
            DuplicatorTarget1     = factory.CreateTexture(ref colorTargetDesc);
            DuplicatorTargetView1 = factory.CreateTextureView(DuplicatorTarget1);
            DuplicatorTargetSet0  = factory.CreateResourceSet(new ResourceSetDescription(TextureSamplerResourceLayout, DuplicatorTargetView0, gd.PointSampler));
            DuplicatorTargetSet1  = factory.CreateResourceSet(new ResourceSetDescription(TextureSamplerResourceLayout, DuplicatorTargetView1, gd.PointSampler));

            FramebufferDescription fbDesc = new FramebufferDescription(null, DuplicatorTarget0, DuplicatorTarget1);

            DuplicatorFramebuffer = factory.CreateFramebuffer(ref fbDesc);
        }
Example #27
0
		private void CreateResources()
		{
			// Veldrid.SPIRV is an additional library that complements Veldrid
			// by simplifying the development of cross-backend shaders, and is
			// currently the recommended approach to doing so:
			//
			//   https://veldrid.dev/articles/portable-shaders.html
			//
			// If you decide against using it, you can try out Veldrid developer
			// mellinoe's other project, ShaderGen, or drive yourself crazy by
			// writing and maintaining custom shader code for each platform.
			byte[] vertexShaderSpirvBytes = LoadSpirvBytes(ShaderStages.Vertex);
			byte[] fragmentShaderSpirvBytes = LoadSpirvBytes(ShaderStages.Fragment);

			var options = new CrossCompileOptions();
			switch (Surface.GraphicsDevice.BackendType)
			{
				// InvertVertexOutputY and FixClipSpaceZ address two major
				// differences between Veldrid's various graphics APIs, as
				// discussed here:
				//
				//   https://veldrid.dev/articles/backend-differences.html
				//
				// Note that the only reason those options are useful in this
				// example project is that the vertices being drawn are stored
				// the way Vulkan stores vertex data. The options will therefore
				// properly convert from the Vulkan style to whatever's used by
				// the destination backend. If you store vertices in a different
				// coordinate system, these may not do anything for you, and
				// you'll need to handle the difference in your shader code.
				case GraphicsBackend.Metal:
					options.InvertVertexOutputY = true;
					break;
				case GraphicsBackend.Direct3D11:
					options.InvertVertexOutputY = true;
					break;
				case GraphicsBackend.OpenGL:
					options.FixClipSpaceZ = true;
					options.InvertVertexOutputY = true;
					break;
				default:
					break;
			}

			ResourceFactory factory = Surface.GraphicsDevice.ResourceFactory;

			var vertex = new ShaderDescription(ShaderStages.Vertex, vertexShaderSpirvBytes, "main", true);
			var fragment = new ShaderDescription(ShaderStages.Fragment, fragmentShaderSpirvBytes, "main", true);
			Shader[] shaders = factory.CreateFromSpirv(vertex, fragment, options);

			ResourceLayout modelMatrixLayout = factory.CreateResourceLayout(
				new ResourceLayoutDescription(
					new ResourceLayoutElementDescription(
						"ModelMatrix",
						ResourceKind.UniformBuffer,
						ShaderStages.Vertex)));

			ModelBuffer = factory.CreateBuffer(
				new BufferDescription(64, BufferUsage.UniformBuffer));

			ModelMatrixSet = factory.CreateResourceSet(new ResourceSetDescription(
				modelMatrixLayout, ModelBuffer));

			VertexPositionColor[] quadVertices =
			{
				new VertexPositionColor(new Vector2(-.75f, -.75f), RgbaFloat.Red),
				new VertexPositionColor(new Vector2(.75f, -.75f), RgbaFloat.Green),
				new VertexPositionColor(new Vector2(-.75f, .75f), RgbaFloat.Blue),
				new VertexPositionColor(new Vector2(.75f, .75f), RgbaFloat.Yellow)
			};

			ushort[] quadIndices = { 0, 1, 2, 3 };

			VertexBuffer = factory.CreateBuffer(new BufferDescription(4 * VertexPositionColor.SizeInBytes, BufferUsage.VertexBuffer));
			IndexBuffer = factory.CreateBuffer(new BufferDescription(4 * sizeof(ushort), BufferUsage.IndexBuffer));

			Surface.GraphicsDevice.UpdateBuffer(VertexBuffer, 0, quadVertices);
			Surface.GraphicsDevice.UpdateBuffer(IndexBuffer, 0, quadIndices);

			// Veldrid.SPIRV, when cross-compiling to HLSL, will always produce
			// TEXCOORD semantics; VertexElementSemantic.TextureCoordinate thus
			// becomes necessary to let D3D11 work alongside Vulkan and OpenGL.
			//
			//   https://github.com/mellinoe/veldrid/issues/121
			//
			var vertexLayout = new VertexLayoutDescription(
				new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
				new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4));

			Pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription
			{
				BlendState = BlendStateDescription.SingleOverrideBlend,
				DepthStencilState = new DepthStencilStateDescription(
					depthTestEnabled: true,
					depthWriteEnabled: true,
					comparisonKind: ComparisonKind.LessEqual),
				RasterizerState = new RasterizerStateDescription(
					cullMode: FaceCullMode.Back,
					fillMode: PolygonFillMode.Solid,
					frontFace: FrontFace.Clockwise,
					depthClipEnabled: true,
					scissorTestEnabled: false),
				PrimitiveTopology = PrimitiveTopology.TriangleStrip,
				ResourceLayouts = new[] { modelMatrixLayout },
				ShaderSet = new ShaderSetDescription(
					vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
					shaders: shaders),
				Outputs = Surface.Swapchain.Framebuffer.OutputDescription
			});

			CommandList = factory.CreateCommandList();
		}
Example #28
0
        protected override void CreateResources(ResourceFactory factory)
        {
            _cl = factory.CreateCommandList();
            _cl.Begin();
            _projectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBuffer       = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _worldBuffer      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            VertexPositionTexture[] vertices = GetCubeVertices();
            _vertexBuffer = factory.CreateBuffer(new BufferDescription((uint)(VertexPositionTexture.SizeInBytes * vertices.Length), BufferUsage.VertexBuffer));
            _cl.UpdateBuffer(_vertexBuffer, 0, vertices);

            ushort[] indices = GetCubeIndices();
            _indexBuffer = factory.CreateBuffer(new BufferDescription(sizeof(ushort) * (uint)indices.Length, BufferUsage.IndexBuffer));
            _cl.UpdateBuffer(_indexBuffer, 0, indices);

            ImageSharpTexture stoneImage = new ImageSharpTexture(Path.Combine(AppContext.BaseDirectory, "Textures", "spnza_bricks_a_diff.png"));

            _surfaceTexture     = stoneImage.CreateDeviceTexture(_gd, factory);
            _surfaceTextureView = factory.CreateTextureView(_surfaceTexture);

            _cl.End();
            _gd.SubmitCommands(_cl);
            _gd.WaitForIdle();

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                new[]
            {
                LoadShader(factory, "Cube", ShaderStages.Vertex, "VS"),
                LoadShader(factory, "Cube", ShaderStages.Fragment, "FS")
            });

            ResourceLayout projViewLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldTextureLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           RasterizerStateDescription.Default,
                                                           PrimitiveTopology.TriangleList,
                                                           shaderSet,
                                                           new[] { projViewLayout, worldTextureLayout },
                                                           _gd.SwapchainFramebuffer.OutputDescription));

            _projViewSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                         projViewLayout,
                                                         _projectionBuffer,
                                                         _viewBuffer));

            _worldTextureSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                             worldTextureLayout,
                                                             _worldBuffer,
                                                             _surfaceTextureView,
                                                             _gd.Aniso4xSampler));
        }
Example #29
0
 public static Shader LoadShader(ResourceFactory factory, string setName, string stage, string entryPoint)
 {
     return(LoadShader(factory, setName, (ShaderStages)Enum.Parse(typeof(ShaderStages), stage), entryPoint));
 }
Example #30
0
        private static RenderModePipelines CreatePipelines(
            GraphicsDevice gd,
            SceneContext sc,
            VertexLayoutDescription[] vertexLayouts,
            ResourceLayout sharedLayout,
            ResourceLayout textureLayout,
            ResourceFactory factory,
            bool cullBack,
            bool masked,
            bool additive)
        {
            (var vs, var fs) = sc.MapResourceCache.GetShaders(gd, gd.ResourceFactory, Path.Combine("studio", "StudioGeneric"));

            var rasterizerState = new RasterizerStateDescription(cullBack ? FaceCullMode.Back : FaceCullMode.Front, PolygonFillMode.Solid, FrontFace.Clockwise, true, true);
            const PrimitiveTopology primitiveTopology = PrimitiveTopology.TriangleList;
            var shaderSets        = new ShaderSetDescription(vertexLayouts, new[] { vs, fs });
            var resourceLayouts   = new ResourceLayout[] { sharedLayout, textureLayout };
            var outputDescription = sc.MainSceneFramebuffer.OutputDescription;

            var pipelines = new Pipeline[(int)RenderMode.Last + 1];

            BlendStateDescription        normalBlendState;
            DepthStencilStateDescription normalDepthStencilState;

            if (additive)
            {
                normalBlendState        = BlendStates.SingleAdditiveOneOneBlend;
                normalDepthStencilState = gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead;
            }
            else
            {
                normalBlendState        = BlendStateDescription.SingleDisabled;
                normalDepthStencilState = gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual;
            }

            var pd = new GraphicsPipelineDescription(
                normalBlendState,
                normalDepthStencilState,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.Normal] = factory.CreateGraphicsPipeline(ref pd);

            pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.TransTexture] = factory.CreateGraphicsPipeline(ref pd);

            //These all use the same settings as texture
            pipelines[(int)RenderMode.TransColor] = pipelines[(int)RenderMode.TransTexture];
            pipelines[(int)RenderMode.Glow]       = pipelines[(int)RenderMode.TransTexture];
            pipelines[(int)RenderMode.TransAlpha] = pipelines[(int)RenderMode.TransTexture];

            DepthStencilStateDescription additiveDepthState;

            if (masked)
            {
                additiveDepthState = gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual;
            }
            else
            {
                additiveDepthState = gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead;
            }

            pd = new GraphicsPipelineDescription(
                BlendStates.SingleAdditiveOneOneBlend,
                additiveDepthState,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.TransAdd] = factory.CreateGraphicsPipeline(ref pd);

            return(new RenderModePipelines(pipelines));
        }
Example #31
0
 public DisposeCollectorResourceFactory(ResourceFactory factory)
     : this(factory, new DisposeCollector())
 {
 }
Example #32
0
 public void SetResourceFactory(ResourceFactory factory)
 {
     ++SetResourceFactoryCalled;
 }
Example #33
0
 public unsafe Texture CreateDeviceTexture(GraphicsDevice gd, ResourceFactory factory)
 {
     return(CreateTextureViaUpdate(gd, factory));
 }
Example #34
0
        /// <summary>
        /// 参数化建模
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDriveModel_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (polyline != null)
                {
                    center = polyline.Envelope.Center;
                    IModelPoint mp = new GeometryFactory().CreateGeometry(gviGeometryType.gviGeometryModelPoint, gviVertexAttribute.gviVertexAttributeZ) as IModelPoint;
                    mp.SpatialCRS = datasetCRS;
                    mp.Position   = center;

                    IModel         model     = new ResourceFactory().CreateModel();
                    IDrawGroup     group     = new DrawGroup();
                    IDrawPrimitive primitive = new DrawPrimitive();
                    IDrawMaterial  material  = new DrawMaterial();
                    material.TextureName = (strMediaPath + @"\shp\road\textrure.jpg");
                    material.CullMode    = gviCullFaceMode.gviCullNone;
                    material.WrapModeS   = gviTextureWrapMode.gviTextureWrapRepeat;
                    material.WrapModeT   = gviTextureWrapMode.gviTextureWrapRepeat;
                    IFloatArray va = new FloatArray();
                    IFloatArray ta = new FloatArray();
                    // 逐点外扩
                    for (int i = 0; i < polyline.PointCount; i++)
                    {
                        #region 单独处理最后一个点
                        if (i == polyline.PointCount - 1)
                        {
                            curPoint  = polyline.GetPoint(i);
                            vecCurPos = curPoint.Position;
                            // 最后一个点重用最后的方向向量
                            vecTarget = vecDirect.CrossProduct(vecZ);
                            vecTarget.Normalize();
                            vecTarget.MultiplyByScalar(width / 2);
                            vecP = vecCurPos.Add(vecTarget);
                            vecTarget.MultiplyByScalar(-1);
                            vecQ = vecCurPos.Add(vecTarget);
                            // 设置外扩点
                            P          = curPoint.Clone() as IPoint;
                            P.Position = vecP;
                            Q          = curPoint.Clone() as IPoint;
                            Q.Position = vecQ;
                            // 把点坐标加进顶点数组
                            va.Append((float)(vecP.X - center.X));
                            va.Append((float)(vecP.Y - center.Y));
                            va.Append((float)(vecP.Z - center.Z));
                            va.Append((float)(vecQ.X - center.X));
                            va.Append((float)(vecQ.Y - center.Y));
                            va.Append((float)(vecQ.Z - center.Z));
                            // 加纹理坐标
                            ta.Append(0);  //P点纹理
                            if (i == 0)
                            {
                                lastV = 0.0;
                            }
                            else
                            {
                                lastV = lastV + length / 10;  //v方向上每隔10米重复一次
                            }
                            ta.Append((float)lastV);
                            ta.Append(1);  //Q点纹理
                            ta.Append((float)lastV);

                            {
                                ISimplePointSymbol ps = new SimplePointSymbol();
                                ps.FillColor = System.Drawing.Color.Yellow;
                                ps.Size      = 5;
                                rPointToDelList.Add(this.axRenderControl1.ObjectManager.CreateRenderPoint(P, ps, rootId));
                                rPointToDelList.Add(this.axRenderControl1.ObjectManager.CreateRenderPoint(Q, ps, rootId));
                            }

                            break;
                        }
                        #endregion

                        // 当不是最后一个点时:
                        curPoint   = polyline.GetPoint(i);
                        nextPoint  = polyline.GetPoint(i + 1);
                        vecCurPos  = curPoint.Position;
                        vecNextPos = nextPoint.Position;
                        // 运算
                        vecNextPos.MultiplyByScalar(-1);
                        vecDirect = vecCurPos.Add(vecNextPos);  //方向向量
                        vecZ.Set(0, 0, 1);
                        vecTarget = vecDirect.CrossProduct(vecZ);
                        vecTarget.Normalize();
                        vecTarget.MultiplyByScalar(width / 2);
                        vecP = vecCurPos.Add(vecTarget);
                        vecTarget.MultiplyByScalar(-1);
                        vecQ = vecCurPos.Add(vecTarget);
                        // 设置外扩点
                        P          = curPoint.Clone() as IPoint;
                        P.Position = vecP;
                        Q          = curPoint.Clone() as IPoint;
                        Q.Position = vecQ;
                        // 把点坐标加进顶点数组
                        va.Append((float)(vecP.X - center.X));
                        va.Append((float)(vecP.Y - center.Y));
                        va.Append((float)(vecP.Z - center.Z));
                        va.Append((float)(vecQ.X - center.X));
                        va.Append((float)(vecQ.Y - center.Y));
                        va.Append((float)(vecQ.Z - center.Z));
                        // 加纹理坐标
                        ta.Append(0);  //P点纹理
                        if (i == 0)
                        {
                            lastV = 0.0;
                        }
                        else
                        {
                            lastV = lastV + length / 5; //v方向上每隔10米重复一次
                        }
                        length = vecDirect.Length;      //计算长度给奇数点用
                        ta.Append((float)lastV);
                        ta.Append(1);                   //Q点纹理
                        ta.Append((float)lastV);

                        {
                            ISimplePointSymbol ps = new SimplePointSymbol();
                            ps.FillColor = System.Drawing.Color.Yellow;
                            ps.Size      = 5;
                            rPointToDelList.Add(this.axRenderControl1.ObjectManager.CreateRenderPoint(P, ps, rootId));
                            rPointToDelList.Add(this.axRenderControl1.ObjectManager.CreateRenderPoint(Q, ps, rootId));
                        }
                    }
                    // 计算索引坐标
                    IUInt16Array ia = new UInt16Array();
                    for (int i = 0; i < va.Length / 6 - 1; i++)
                    {
                        ia.Append((ushort)(2 * i));
                        ia.Append((ushort)(2 * i + 1));
                        ia.Append((ushort)(2 * i + 2));
                        ia.Append((ushort)(2 * i + 1));
                        ia.Append((ushort)(2 * i + 3));
                        ia.Append((ushort)(2 * i + 2));
                    }
                    primitive.VertexArray   = va;
                    primitive.TexcoordArray = ta;
                    primitive.IndexArray    = ia;
                    primitive.Material      = material;
                    group.AddPrimitive(primitive);
                    model.AddGroup(group);

                    // 在内存中临时存储模型
                    string modelName = fid.ToString();
                    this.axRenderControl1.ObjectManager.AddModel(modelName, model);
                    mp.ModelName     = modelName;
                    mp.ModelEnvelope = model.Envelope;
                    // 可视化临时模型
                    IRenderModelPoint rmp = this.axRenderControl1.ObjectManager.CreateRenderModelPoint(mp, null, rootId);
                    rmp.MaxVisibleDistance = 100000;
                    rmp.MouseSelectMask    = gviViewportMask.gviViewNone;
                    rModelpointToDelList.Add(rmp);
                }
            }
            catch (System.Exception ex)
            {
                if (ex.GetType().Name.Equals("UnauthorizedAccessException"))
                {
                    MessageBox.Show("需要标准runtime授权");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Example #35
0
 protected virtual void CreateSwapchainResources(ResourceFactory factory)
 {
 }
Example #36
0
 public GShader(Sdl2Window window)
 {
     graphicsDevice = VeldridStartup.CreateGraphicsDevice(window);
     factory        = graphicsDevice.ResourceFactory;
 }
Example #37
0
        public TransformExample(GraphicsDevice gd)
        {
            _gd = gd;
            _resourceFactory = _gd.ResourceFactory;

            _originalQuadVertices = new VertexPositionColor []
            {
                new VertexPositionColor(new Vector2(-1.0f, 1.0f), RgbaFloat.Red),
                new VertexPositionColor(new Vector2(1.0f, 1.0f), RgbaFloat.Green),
                new VertexPositionColor(new Vector2(-1.0f, -1.0f), RgbaFloat.Blue),
                new VertexPositionColor(new Vector2(1.0f, -1.0f), RgbaFloat.Yellow)
            };

            _quadVertices = new VertexPositionColor[4];
            Array.Copy(_originalQuadVertices, 0, _quadVertices, 0, 4);

            ushort[] quadIndices = { 0, 1, 2, 3 };

            _vertexBuffer = _resourceFactory.CreateBuffer(new BufferDescription(4 * VertexPositionColor.SizeInBytes, BufferUsage.VertexBuffer));
            _indexBuffer  = _resourceFactory.CreateBuffer(new BufferDescription(4 * sizeof(ushort), BufferUsage.IndexBuffer));

            _gd.UpdateBuffer(_vertexBuffer, 0, _quadVertices);
            _gd.UpdateBuffer(_indexBuffer, 0, quadIndices);

            VertexLayoutDescription vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4));

            ShaderDescription vertexShaderDesc = new ShaderDescription(
                ShaderStages.Vertex,
                Encoding.UTF8.GetBytes(VertexCode),
                "main",
                true);
            ShaderDescription fragmentShaderDesc = new ShaderDescription(
                ShaderStages.Fragment,
                Encoding.UTF8.GetBytes(FragmentCode),
                "main",
                true);

            _shaders = _resourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription();

            pipelineDescription.BlendState        = BlendStateDescription.SingleOverrideBlend;
            pipelineDescription.DepthStencilState = new DepthStencilStateDescription(
                depthTestEnabled: true,
                depthWriteEnabled: true,
                comparisonKind: ComparisonKind.LessEqual);

            pipelineDescription.RasterizerState = new RasterizerStateDescription(
                cullMode: FaceCullMode.Back,
                fillMode: PolygonFillMode.Solid,
                frontFace: FrontFace.Clockwise,
                depthClipEnabled: true,
                scissorTestEnabled: false);

            pipelineDescription.PrimitiveTopology = PrimitiveTopology.TriangleStrip;
            pipelineDescription.ResourceLayouts   = System.Array.Empty <ResourceLayout>();
            pipelineDescription.ShaderSet         = new ShaderSetDescription(
                vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                shaders: _shaders);

            pipelineDescription.Outputs = _gd.SwapchainFramebuffer.OutputDescription;
            _pipeline = _resourceFactory.CreateGraphicsPipeline(pipelineDescription);
        }
Example #38
0
        public static unsafe Texture LoadTexture(
            GraphicsDevice gd,
            ResourceFactory factory,
            Stream assetStream,
            PixelFormat format)
        {
            KtxFile ktxTex2D = Load(assetStream, false);

            uint width  = ktxTex2D.Header.PixelWidth;
            uint height = ktxTex2D.Header.PixelHeight;

            if (height == 0)
            {
                height = width;
            }

            uint arrayLayers = Math.Max(1, ktxTex2D.Header.NumberOfArrayElements);
            uint mipLevels   = Math.Max(1, ktxTex2D.Header.NumberOfMipmapLevels);

            Texture ret = factory.CreateTexture(TextureDescription.Texture2D(
                                                    width, height, mipLevels, arrayLayers,
                                                    format, TextureUsage.Sampled));

            Texture stagingTex = factory.CreateTexture(TextureDescription.Texture2D(
                                                           width, height, mipLevels, arrayLayers,
                                                           format, TextureUsage.Staging));

            // Copy texture data into staging buffer
            for (uint level = 0; level < mipLevels; level++)
            {
                KtxMipmapLevel mipmap = ktxTex2D.Mipmaps[level];
                for (uint layer = 0; layer < arrayLayers; layer++)
                {
                    KtxArrayElement ktxLayer = mipmap.ArrayElements[layer];
                    Debug.Assert(ktxLayer.Faces.Length == 1);
                    byte[] pixelData = ktxLayer.Faces[0].Data;
                    fixed(byte *pixelDataPtr = &pixelData[0])
                    {
                        gd.UpdateTexture(stagingTex, (IntPtr)pixelDataPtr, (uint)pixelData.Length,
                                         0, 0, 0, mipmap.Width, mipmap.Height, 1, level, layer);
                    }
                }
            }

            CommandList copyCL = factory.CreateCommandList();

            copyCL.Begin();
            for (uint level = 0; level < mipLevels; level++)
            {
                KtxMipmapLevel mipLevel = ktxTex2D.Mipmaps[level];
                for (uint layer = 0; layer < arrayLayers; layer++)
                {
                    copyCL.CopyTexture(
                        stagingTex, 0, 0, 0, level, layer,
                        ret, 0, 0, 0, level, layer,
                        mipLevel.Width, mipLevel.Height, mipLevel.Depth,
                        1);
                }
            }
            copyCL.End();
            gd.SubmitCommands(copyCL);

            gd.DisposeWhenIdle(copyCL);
            gd.DisposeWhenIdle(stagingTex);

            return(ret);
        }
Example #39
0
 public void Init(List<ISimulationCarrier> carrierList)
 {
     this.m_NormalSinrThresh = new Huawei.UNet.LTESimulation.TDDDLSchedule.NormalSinrThresh();
     this.m_ResourceFactory = new ResourceFactory();
     foreach (SimulationCarrier carrier in carrierList)
     {
         this.InitTag(carrier);
         this.CreateQueueFactory(carrier);
         carrier.RbDataRePower = new float[carrier.BandWidthRbNum];
     }
 }
        protected override void CreateResources(ResourceFactory factory)
        {
            _particleBuffer = factory.CreateBuffer(
                new BufferDescription(
                    (uint)Unsafe.SizeOf <ParticleInfo>() * ParticleCount,
                    BufferUsage.StructuredBufferReadWrite,
                    (uint)Unsafe.SizeOf <ParticleInfo>()));

            _screenSizeBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));

            _computeShader = factory.CreateShader(new ShaderDescription(
                                                      ShaderStages.Compute,
                                                      ReadEmbeddedAssetBytes($"Compute.{GetExtension(factory.BackendType)}"),
                                                      "CS"));

            ResourceLayout particleStorageLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                                    new ResourceLayoutElementDescription("ParticlesBuffer", ResourceKind.StructuredBufferReadWrite, ShaderStages.Compute)));

            ResourceLayout screenSizeLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                               new ResourceLayoutElementDescription("ScreenSizeBuffer", ResourceKind.UniformBuffer, ShaderStages.Compute)));

            ComputePipelineDescription computePipelineDesc = new ComputePipelineDescription(
                _computeShader,
                new[] { particleStorageLayout, screenSizeLayout },
                1, 1, 1);

            _computePipeline = factory.CreateComputePipeline(ref computePipelineDesc);

            _computeResourceSet = factory.CreateResourceSet(new ResourceSetDescription(particleStorageLayout, _particleBuffer));

            _computeScreenSizeResourceSet = factory.CreateResourceSet(new ResourceSetDescription(screenSizeLayout, _screenSizeBuffer));

            _vertexShader = factory.CreateShader(new ShaderDescription(
                                                     ShaderStages.Vertex,
                                                     ReadEmbeddedAssetBytes($"Vertex.{GetExtension(factory.BackendType)}"),
                                                     "VS"));
            _fragmentShader = factory.CreateShader(new ShaderDescription(
                                                       ShaderStages.Fragment,
                                                       ReadEmbeddedAssetBytes($"Fragment.{GetExtension(factory.BackendType)}"),
                                                       "FS"));

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                Array.Empty <VertexLayoutDescription>(),
                new[]
            {
                _vertexShader,
                _fragmentShader
            });

            particleStorageLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                     new ResourceLayoutElementDescription("ParticlesBuffer", ResourceKind.StructuredBufferReadOnly, ShaderStages.Vertex)));

            screenSizeLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("ScreenSizeBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            GraphicsPipelineDescription particleDrawPipelineDesc = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                new[] { particleStorageLayout, screenSizeLayout },
                MainSwapchain.Framebuffer.OutputDescription);

            _graphicsPipeline = factory.CreateGraphicsPipeline(ref particleDrawPipelineDesc);

            _graphicsParticleResourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                                         particleStorageLayout,
                                                                         _particleBuffer));

            _screenSizeResourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                                   screenSizeLayout,
                                                                   _screenSizeBuffer));

            _cl = factory.CreateCommandList();

            InitResources(factory);
            _initialized = true;
        }
 private void OnViewCreatedDevice()
 {
     _disposeFactory = _view.GraphicsDevice.ResourceFactory;
     GraphicsDeviceCreated?.Invoke(_view.GraphicsDevice, _disposeFactory, _view.MainSwapchain);
     Resized?.Invoke();
 }
Example #42
0
        private static void GetOrCreateCachedShaders(
            ResourceFactory factory,
            string shaderName,
            bool debug,
            out byte[] vsBytes,
            out byte[] fsBytes)
        {
            const string shaderCacheFolder = "ShaderCache";
            var          backendType       = factory.BackendType;
            var          targetExtension   = backendType.ToString().ToLowerInvariant();

            if (!Directory.Exists(shaderCacheFolder))
            {
                Directory.CreateDirectory(shaderCacheFolder);
            }

            var vsSpvName = $"OpenSage.Assets.Shaders.{shaderName}.vert.spv";
            var fsSpvName = $"OpenSage.Assets.Shaders.{shaderName}.frag.spv";

            var vsSpvBytes = ReadSpvShader(vsSpvName);
            var fsSpvBytes = ReadSpvShader(fsSpvName);

            var vsSpvHash = GetShaderHash(vsSpvBytes);
            var fsSpvHash = GetShaderHash(fsSpvBytes);

            // Check that SPIR-V files on disk match what's in the assembly.
            var vsCacheFilePath = Path.Combine(shaderCacheFolder, $"OpenSage.Assets.Shaders.{shaderName}.vert.{vsSpvHash}.{targetExtension}");
            var fsCacheFilePath = Path.Combine(shaderCacheFolder, $"OpenSage.Assets.Shaders.{shaderName}.frag.{fsSpvHash}.{targetExtension}");

            if (File.Exists(vsCacheFilePath) &&
                File.Exists(fsCacheFilePath))
            {
                // Cache is valid - use it.
                vsBytes = File.ReadAllBytes(vsCacheFilePath);
                fsBytes = File.ReadAllBytes(fsCacheFilePath);
                return;
            }

            // Cache is invalid or doesn't exist - do cross-compilation.

            if (backendType == GraphicsBackend.Vulkan)
            {
                File.WriteAllBytes(vsCacheFilePath, vsSpvBytes);
                File.WriteAllBytes(fsCacheFilePath, fsSpvBytes);
                vsBytes = vsSpvBytes;
                fsBytes = fsSpvBytes;
                return;
            }

            var compilationTarget = GetCompilationTarget(backendType);
            var compilationResult = SpirvCompilation.CompileVertexFragment(
                vsSpvBytes,
                fsSpvBytes,
                compilationTarget,
                new CrossCompileOptions());

            switch (backendType)
            {
            case GraphicsBackend.Direct3D11:
                vsBytes = CompileHlsl(compilationResult.VertexShader, "vs_5_0", debug);
                fsBytes = CompileHlsl(compilationResult.FragmentShader, "ps_5_0", debug);
                break;

            case GraphicsBackend.OpenGL:
            case GraphicsBackend.OpenGLES:
                vsBytes = Encoding.ASCII.GetBytes(compilationResult.VertexShader);
                fsBytes = Encoding.ASCII.GetBytes(compilationResult.FragmentShader);
                break;

            case GraphicsBackend.Metal:
                // TODO: Compile to IR.
                vsBytes = Encoding.UTF8.GetBytes(compilationResult.VertexShader);
                fsBytes = Encoding.UTF8.GetBytes(compilationResult.FragmentShader);
                break;

            default:
                throw new InvalidOperationException();
            }

            File.WriteAllBytes(vsCacheFilePath, vsBytes);
            File.WriteAllBytes(fsCacheFilePath, fsBytes);
        }
Example #43
0
        private void openMenu(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            var dlg = new OpenFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".LIB";
            dlg.Filter     = "LIB Files (*.LIB)|*.LIB|RRM image|*.RRM|VGS image|*.VGS|RIF resource|*.RIF|HPF resource|*.HPF";


            // Display OpenFileDialog by calling ShowDialog method
            bool?result = dlg.ShowDialog();

            if (result == true)
            {
                string filename = dlg.FileName;
                fileName.Text = filename;
                resource      = ResourceFactory.openResource(filename);
                var rootItem = new TreeViewItem();
                rootItem.Header = resource.FileName;
                foreach (FileEntry f in resource.Files)
                {
                    rootItem.Items.Add(f);
                }
                numFilesTextBlock.Text = resource.NFiles.ToString();
                fileTreeView.Items.Add(rootItem);
                rootItem.IsExpanded = true;
            }
            // Get the selected file name and display in a TextBox

            /* if (result == true)
             * {
             *   // Open document
             *   string filename = dlg.FileName;
             *   fileName.Text = filename;
             *   if(Path.GetExtension(filename).Equals(".LIB"))
             *   {
             *       resource = new LibResource(filename);
             *       var rootItem = new TreeViewItem();
             *       rootItem.Header = resource.FileName;
             *       foreach (FileEntry f in resource.Files)
             *       {
             *           //var leafItem = new TreeViewItem() {Header = f.FileName};
             *           //leafItem.Items.Add(new TreeViewItem() {Header = f.FileOffset});
             *
             *           rootItem.Items.Add(f);
             *       }
             *       numFilesTextBlock.Text = resource.NFiles.ToString();
             *       fileTreeView.Items.Add(rootItem);
             *   }
             *   else if (Path.GetExtension(filename).Equals(".RRM"))
             *   {
             *       RRMImage image = new RRMImage(filename);
             *       showImage(image);
             *   }
             *   else if (Path.GetExtension(filename).Equals(".VGS"))
             *   {
             *       VGS2Image image = new VGS2Image(filename);
             *   }
             *   else if (Path.GetExtension(filename).Equals(".RIF"))
             *   {
             *       resource = new RifResource(filename);
             *       var rootItem = new TreeViewItem();
             *       rootItem.Header = resource.FileName;
             *       foreach (FileEntry f in resource.Files)
             *       {
             *           //var leafItem = new TreeViewItem() {Header = f.FileName};
             *           //leafItem.Items.Add(new TreeViewItem() {Header = f.FileOffset});
             *
             *           rootItem.Items.Add(f);
             *       }
             *   }
             *
             *   else if (Path.GetExtension(filename).Equals(".HPF"))
             *   {
             *       resource = new HpfResource(filename);
             *       var rootItem = new TreeViewItem();
             *       rootItem.Header = resource.FileName;
             *       foreach (FileEntry f in resource.Files)
             *       {
             *           //var leafItem = new TreeViewItem() {Header = f.FileName};
             *           //leafItem.Items.Add(new TreeViewItem() {Header = f.FileOffset});
             *
             *           rootItem.Items.Add(f);
             *       }
             *   }
             * }*/
        }
Example #44
0
        /// <summary>
        /// Build from XML based on type
        /// </summary>
        /// <param name="type"></param>
        /// <param name="xmlConfigData"></param>
        protected Resource(ResourceFactory factory, ResourceType type, XmlElement xmlConfigData)
        {
            this.type = type;
            this.xmlConfigData = xmlConfigData;
            this.factory = factory;

            identity = new Identity(int.Parse(xmlConfigData.GetAttribute("ID")));
            name = xmlConfigData.GetAttribute("Name");
            if (xmlConfigData.HasAttribute("Description"))
            {
                description = xmlConfigData.GetAttribute("Description");
            }
        }
        public static Tuple <DeviceBuffer, DeviceBuffer> CreateResource(this BoundingBox bounding, GraphicsDevice gd, ResourceFactory factory)
        {
            var position      = bounding.GetCorners();
            var _vertexBuffer = factory.CreateBuffer(new BufferDescription((uint)(12 * position.Length), BufferUsage.VertexBuffer));

            gd.UpdateBuffer(_vertexBuffer, 0, position);
            //共24个indices,使用line模式绘制
            var indices      = new ushort[] { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 };
            var _indexBuffer = factory.CreateBuffer(new BufferDescription((uint)(sizeof(ushort) * indices.Length), BufferUsage.IndexBuffer));

            gd.UpdateBuffer(_indexBuffer, 0, indices);
            return(new System.Tuple <DeviceBuffer, DeviceBuffer>(_vertexBuffer, _indexBuffer));
        }
Example #46
0
        private static void CreateResources()
        {
            _instanceCount = 5;

            ResourceFactory factory = _graphicsDevice.ResourceFactory;

            _vertexBuffer = factory.CreateBuffer(
                new BufferDescription(IrregularPentagon.VerticesCount * VertexPositionColor.SizeInBytes,
                                      BufferUsage.VertexBuffer));
            _indexBuffer = factory.CreateBuffer(
                new BufferDescription(IrregularPentagon.IndicesCount * sizeof(ushort),
                                      BufferUsage.IndexBuffer));
            _projMatrixBuffer = factory.CreateBuffer(
                new BufferDescription(sizeof(float) * 4 * 4,
                                      BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _projMatrixBuffer.Name = "Projection Buffer";
            _modelMatrixBuffer     = factory.CreateBuffer(
                new BufferDescription(sizeof(float) * 4 * 4,
                                      BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _modelMatrixBuffer.Name = "Model Buffer";


            _graphicsDevice.UpdateBuffer(_vertexBuffer, 0, IrregularPentagon.Vertices);
            _graphicsDevice.UpdateBuffer(_indexBuffer, 0, IrregularPentagon.Indices);

            ViewProjectionUpdate();

            VertexLayoutDescription vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate,
                                             VertexElementFormat.Float2),
                new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate,
                                             VertexElementFormat.Float4));

            _layout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("ViewProjectionMatrix", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("ModelMatrix", ResourceKind.UniformBuffer, ShaderStages.Vertex)));


            ShaderDescription vertexShaderDesc = new ShaderDescription(ShaderStages.Vertex,
                                                                       Resources.VertexShader,
                                                                       "main");
            ShaderDescription fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment,
                                                                         Resources.FragmentShader,
                                                                         "main");

            _shaders = factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc);


            VertexLayoutDescription vertexLayoutPerInstance = new VertexLayoutDescription(
                new VertexElementDescription("InstanceCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float1));

            vertexLayoutPerInstance.InstanceStepRate = 1;

            _instanceVB = factory.CreateBuffer(new BufferDescription(sizeof(float) * _instanceCount, BufferUsage.VertexBuffer));
            float[] infos = new float[_instanceCount];


            for (uint i = 0; i < _instanceCount; i++)
            {
                infos[i] = i / 0.1f;
            }

            _graphicsDevice.UpdateBuffer(_instanceVB, 0, infos);

            GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription
            {
                BlendState        = BlendStateDescription.SingleAlphaBlend,
                DepthStencilState = new DepthStencilStateDescription(
                    true,
                    true,
                    ComparisonKind.LessEqual),
                RasterizerState = new RasterizerStateDescription(
                    FaceCullMode.Back,
                    PolygonFillMode.Solid,
                    FrontFace.Clockwise,
                    true,
                    false),
                PrimitiveTopology = PrimitiveTopology.TriangleStrip,
                ResourceLayouts   = new [] { _layout },
                ShaderSet         = new ShaderSetDescription(new[] { vertexLayout, vertexLayoutPerInstance }, _shaders),
                Outputs           = _graphicsDevice.MainSwapchain.Framebuffer.OutputDescription,
            };

            _pipeline = factory.CreateGraphicsPipeline(pipelineDescription);

            _mainResourceSet = factory.CreateResourceSet(new ResourceSetDescription(_layout,
                                                                                    _projMatrixBuffer, _modelMatrixBuffer));

            _commandList = factory.CreateCommandList();

            var firstPentagon  = new IrregularPentagon();
            var secondPentagon = new IrregularPentagon(firstPentagon, 0);

            _pentagons.Add(firstPentagon);
            _pentagons.Add(secondPentagon);
        }