コード例 #1
0
        private void CheckForAndSetDisconnectedState(PipelineState pipelineState)
        {
            bool flag;
            lock (base.SyncObject)
            {
                if (this.IsTerminalState())
                {
                    return;
                }
                switch (pipelineState)
                {
                    case PipelineState.Stopped:
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                        this.pipelineFinishedCount++;
                        break;

                    case PipelineState.Disconnected:
                        this.pipelineDisconnectedCount++;
                        break;
                }
                flag = ((this.pipelineFinishedCount + this.pipelineDisconnectedCount) == this.helpers.Count) && (this.pipelineDisconnectedCount > 0);
            }
            if (flag)
            {
                base.SetJobState(JobState.Disconnected);
            }
        }
コード例 #2
0
		public PipelineExecutionResult(Collection<PSObject> output, Collection<Object> errors, Exception failure,
									   PipelineState state)
		{
			_failure = failure;
			_errors = errors ?? new Collection<Object>();
			_output = output ?? new Collection<PSObject>();
			_state = state;
		}
コード例 #3
0
ファイル: History.cs プロジェクト: dfinke/powershell
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="pipelineId">Id of pipeline in which command associated 
 /// with this history entry is executed</param>
 /// <param name="cmdline">command string</param>
 /// <param name="status">status of pipeline execution</param>
 /// <param name="startTime">startTime of execution</param>
 /// <param name="endTime">endTime of execution</param>
 internal HistoryInfo(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime)
 {
     Dbg.Assert(cmdline != null, "caller should validate the parameter");
     _pipelineId = pipelineId;
     _cmdline = cmdline;
     _status = status;
     _startTime = startTime;
     _endTime = endTime;
     _cleared = false;
 }
コード例 #4
0
ファイル: SaveNodeOutputViewModel.cs プロジェクト: Kha/YUV.KA
		public SaveNodeOutputViewModel(Node.Output output, Stream stream, PipelineState model)
		{
			this.model = model;
			IEnumerable<Frame> frames = model.Driver.RenderTicks(new[] { output.Node }, 0, TickCount, cts.Token)
				.Do(_ => { CurrentTick++; NotifyOfPropertyChange(() => CurrentTick); })
				.Select(dic => dic[output])
				.ToEnumerable();

			Task.Factory.StartNew(() => {
				using (stream)
					YuvEncoder.Encode(stream, frames);
				TryClose();
			});
		}
コード例 #5
0
 /// <summary>
 /// Right before a prompt we want to insert a new paragraph...
 /// But we want to trim any whitespace off the end of the output first 
 /// because the paragraph mark makes plenty of whitespace
 /// </summary>
 internal void OnCommandFinished(IEnumerable<Command> command, PipelineState results)
 {
     _id++;
      //// NOTE: we are only using the dispatcher, to make sure this doesn't complete before the command output
      Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)delegate
      {
     Current.Tag = _id;
     if (results != PipelineState.Completed && results != PipelineState.NotStarted)
     {
         Write(ConsoleBrushes.VerboseForeground, ConsoleBrushes.VerboseBackground, $"VERBOSE: PowerShell Pipeline was: {results}\n");
     }
      Finished?.Invoke(this, new FinishedEventArgs { Commands = command, Results = results });
      });
 }
コード例 #6
0
 protected void SetPipelineState(PipelineState state, Exception reason)
 {
     using (PipelineBase._trace.TraceMethod("{0} to {1} {2}", (object)this.PipelineState, (object)state, reason != null ? (object)reason.Message : (object)""))
     {
         lock (this.SyncRoot)
         {
             if (state == this.PipelineState)
             {
                 return;
             }
             this._pipelineStateInfo = new PipelineStateInfo(state, reason);
             RunspaceAvailability runspaceAvailability = this._runspace.RunspaceAvailability;
             this._runspace.UpdateRunspaceAvailability(this._pipelineStateInfo.State, false);
             this._executionEventQueue.Enqueue(new PipelineBase.ExecutionEventQueueItem(this._pipelineStateInfo.Clone(), runspaceAvailability, this._runspace.RunspaceAvailability));
         }
     }
 }
コード例 #7
0
ファイル: Game.cs プロジェクト: PinedaRP/Zeckoxe-Engine
        public void Initialize()
        {
            Instance = new GraphicsInstance(Parameters);

            Adapter = new GraphicsAdapter(Instance);

            Device = new GraphicsDevice(Adapter);

            Texture = new Texture(Device);

            Framebuffer = new Framebuffer(Device);

            Context = new GraphicsContext(Device);


            PipelineState = new PipelineState(new string[] { "Shaders/VertexShader.hlsl", "Shaders/PixelShader.hlsl" }, Framebuffer);
        }
コード例 #8
0
        public GraphicsCommandList GetObject(PipelineState initialState = null)
        {
            GraphicsCommandList item;

            // Try to take object
            if (spareObjects.TryTake(out item))
            {
                // Reset the object
                item.Reset(allocator, initialState);
                graphicsHost.BeginFrame(item);
                return(item);
            }

            // Create new object
            this.Add(item = CreateNew(initialState));
            return(item);
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="flags"></param>
        void Enum(PipelineState ps, RenderFlags flags)
        {
            ps.Primitive           = Primitive.LineList;
            ps.VertexInputElements = VertexInputElement.FromStructure(typeof(LineVertex));
            ps.RasterizerState     = RasterizerState.CullNone;

            if (flags.HasFlag(RenderFlags.SOLID))
            {
                ps.BlendState        = BlendState.Opaque;
                ps.DepthStencilState = DepthStencilState.Default;
            }

            if (flags.HasFlag(RenderFlags.GHOST))
            {
                ps.BlendState        = BlendState.AlphaBlend;
                ps.DepthStencilState = DepthStencilState.None;
            }
        }
コード例 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="flags"></param>
        void Enum(PipelineState ps, ShaderFlags flags)
        {
            ps.Primitive           = Primitive.TriangleList;
            ps.VertexInputElements = VertexInputElement.Empty;
            ps.BlendState          = BlendState.Opaque;
            ps.RasterizerState     = RasterizerState.CullNone;
            ps.DepthStencilState   = DepthStencilState.None;

            if (flags == ShaderFlags.OVERLAY_ADDITIVE)
            {
                ps.BlendState = BlendState.Additive;
            }

            if (flags == ShaderFlags.FILL_ALPHA_ONE)
            {
                ps.BlendState = BlendState.AlphaMaskWrite;
            }
        }
コード例 #11
0
        public IPipelineState CreatePipelineState()
        {
            var pso = PipelineState.Create();

            var vtxShader =
                new ShaderDescription(ShaderStages.Vertex, ReadEmbeddedAssetBytes(@"Veldrid.SceneGraph.Assets.Shaders.Phong-vertex.glsl"), "main");

            var frgShader =
                new ShaderDescription(ShaderStages.Fragment, ReadEmbeddedAssetBytes(@"Veldrid.SceneGraph.Assets.Shaders.Phong-fragment.glsl"), "main");

            pso.VertexShaderDescription   = vtxShader;
            pso.FragmentShaderDescription = frgShader;

            pso.AddUniform(CreateLightSourceUniform());
            pso.AddUniform(CreateMaterialUniform());

            return(pso);
        }
コード例 #12
0
        public void ErrorInput()
        {
            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(TestHelpers.BuildGraphNode(0, "input", inputPlugin.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(1, "input", ErrorPlugin.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(2, "process"));
            nodes.Add(TestHelpers.BuildGraphNode(3, "output"));

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(TestHelpers.MatchSlots(nodes[0], nodes[2], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[2], 0, 1));
            links.Add(TestHelpers.MatchSlots(nodes[2], nodes[3], 0, 0));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());
            Assert.Throws <NodeException>(() => PipelineState.BuildPipesTestOnly());
        }
コード例 #13
0
        public void BasicBuild()
        {
            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(TestHelpers.BuildGraphNode(0, "input", inputPlugin.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(1, "process"));
            nodes.Add(TestHelpers.BuildGraphNode(2, "output"));

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(TestHelpers.MatchSlots(nodes[0], nodes[1], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[2], 0, 0));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());
            PipelineExecutor[] results = PipelineState.BuildPipesTestOnly();

            Assert.AreEqual(DataSize, results.Length);
        }
コード例 #14
0
        public void PrematureInputEnd()
        {
            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(TestHelpers.BuildGraphNode(0, "input", EarlyData.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(1, "input", LateData.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(2, "process"));
            nodes.Add(TestHelpers.BuildGraphNode(3, "output"));

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(TestHelpers.MatchSlots(nodes[0], nodes[2], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[2], 0, 1));
            links.Add(TestHelpers.MatchSlots(nodes[2], nodes[3], 0, 0));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());
            Assert.Throws <InvalidDataException>(() => PipelineState.BuildPipesTestOnly());
        }
コード例 #15
0
        public virtual bool TransitAtStoppedSingleTrip(PipelineSyncCommand command, out PipelineState currentState)
        {
            bool transitSucceeded = false;

            currentState = PipelineState.Default;
            switch (command)
            {
            case PipelineSyncCommand.FINISH:
                transitSucceeded = true;
                currentState     = PipelineState.Stopping;
                break;

            case PipelineSyncCommand.PAUSE:
                transitSucceeded = true;
                currentState     = PipelineState.Pausing;
                break;

            case PipelineSyncCommand.RESUME:
                break;

            case PipelineSyncCommand.START:
                break;

            case PipelineSyncCommand.START_NEW_TRIP:
                currentState     = PipelineState.Starting;
                transitSucceeded = true;
                break;

            case PipelineSyncCommand.STOP:
                transitSucceeded = true;
                currentState     = PipelineState.Stopping;
                break;

            case PipelineSyncCommand.STOP_CURRENT_TRIP:
                transitSucceeded = true;
                currentState     = PipelineState.StoppedSingleTrip;
                break;

            case PipelineSyncCommand.DEFAULT:
            default:
                break;
            }
            return(transitSucceeded);
        }
コード例 #16
0
        private void SetPipelineState(PipelineState state, Exception reason)
        {
            PipelineState stopped = state;

            System.Management.Automation.Runspaces.PipelineStateInfo info = null;
            lock (this._syncRoot)
            {
                switch (this._pipelineStateInfo.State)
                {
                case PipelineState.Running:
                    if (state != PipelineState.Running)
                    {
                        goto Label_005F;
                    }
                    return;

                case PipelineState.Stopping:
                    if ((state != PipelineState.Running) && (state != PipelineState.Stopping))
                    {
                        break;
                    }
                    return;

                case PipelineState.Stopped:
                case PipelineState.Completed:
                case PipelineState.Failed:
                    return;

                default:
                    goto Label_005F;
                }
                stopped = PipelineState.Stopped;
Label_005F:
                this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(stopped, reason);
                info = this._pipelineStateInfo;
                RunspaceAvailability runspaceAvailability = this._runspace.RunspaceAvailability;
                this._runspace.UpdateRunspaceAvailability(this._pipelineStateInfo.State, false);
                this._executionEventQueue.Enqueue(new ExecutionEventQueueItem(this._pipelineStateInfo.Clone(), runspaceAvailability, this._runspace.RunspaceAvailability));
            }
            if (((info.State == PipelineState.Completed) || (info.State == PipelineState.Failed)) || (info.State == PipelineState.Stopped))
            {
                this.Cleanup();
            }
        }
コード例 #17
0
ファイル: Test1.cs プロジェクト: wyq1153/DirectX12GameEngine
        private static async Task ExecuteOnGpu(GraphicsDevice device, StructuredBuffer <float> sourceBufferView, WriteableStructuredBuffer <float> destinationBufferView)
        {
            bool generateWithDelegate = false;

            DescriptorSet descriptorSet = new DescriptorSet(device, 2);

            descriptorSet.AddResourceViews(destinationBufferView);
            descriptorSet.AddResourceViews(sourceBufferView);

            // Generate computer shader
            ShaderGenerator shaderGenerator = generateWithDelegate
                ? CreateShaderGeneratorWithDelegate(sourceBufferView, destinationBufferView)
                : CreateShaderGeneratorWithClass();

            ShaderGeneratorResult result = shaderGenerator.GenerateShader();

            // Compile shader

            byte[] shaderBytecode = ShaderCompiler.Compile(ShaderStage.ComputeShader, result.ShaderSource, result.EntryPoints["compute"]);

            DescriptorRange[] descriptorRanges = new DescriptorRange[]
            {
                new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, 0),
                new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, 0)
            };

            RootParameter rootParameter = new RootParameter(new RootDescriptorTable(descriptorRanges), ShaderVisibility.All);

            RootSignatureDescription rootSignatureDescription = new RootSignatureDescription(RootSignatureFlags.None, new[] { rootParameter });
            RootSignature            rootSignature            = new RootSignature(device, rootSignatureDescription);
            PipelineState            pipelineState            = new PipelineState(device, rootSignature, shaderBytecode);

            // Execute computer shader

            using (CommandList commandList = new CommandList(device, CommandListType.Compute))
            {
                commandList.SetPipelineState(pipelineState);
                commandList.SetComputeRootDescriptorTable(0, descriptorSet);

                commandList.Dispatch(1, 1, 1);
                await commandList.FlushAsync();
            }
        }
コード例 #18
0
ファイル: ParticleSystem.cs プロジェクト: ttou73/IronStar
        /// <summary>
        ///
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="flag"></param>
        void EnumAction(PipelineState ps, Flags flag)
        {
            ps.BlendState        = BlendState.AlphaBlendPremul;
            ps.DepthStencilState = DepthStencilState.Readonly;
            ps.Primitive         = Primitive.PointList;

            if (flag == Flags.DRAW_SHADOW)
            {
                var bs = new BlendState();
                bs.DstAlpha = Blend.One;
                bs.SrcAlpha = Blend.One;
                bs.SrcColor = Blend.DstColor;
                bs.DstColor = Blend.Zero;
                bs.AlphaOp  = BlendOp.Add;

                ps.BlendState        = bs;
                ps.DepthStencilState = DepthStencilState.Readonly;
            }
        }
コード例 #19
0
ファイル: History.cs プロジェクト: modulexcite/pash-1
 internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool skipIfLocked)
 {
     if (Monitor.TryEnter(this._syncRoot, skipIfLocked ? 0 : -1))
     {
         try
         {
             HistoryInfo info = this.CoreGetEntry(id);
             if (info != null)
             {
                 info.SetStatus(status);
                 info.SetEndTime(endTime);
             }
         }
         finally
         {
             Monitor.Exit(this._syncRoot);
         }
     }
 }
コード例 #20
0
ファイル: SceneRenderer.cs プロジェクト: ttou73/IronStar
        /// <summary>
        ///
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="flags"></param>
        void Enum(PipelineState ps, SurfaceFlags flags)
        {
            ps.RasterizerState = RasterizerState.CullCW;

            if (flags.HasFlag(SurfaceFlags.SKINNED))
            {
                ps.VertexInputElements = VertexColorTextureTBNSkinned.Elements;
            }

            if (flags.HasFlag(SurfaceFlags.RIGID))
            {
                ps.VertexInputElements = VertexColorTextureTBNRigid.Elements;
            }

            if (flags.HasFlag(SurfaceFlags.SHADOW))
            {
                ps.RasterizerState = RasterizerState.CullNone;
            }
        }
コード例 #21
0
        public void Execute(GraphicsCommandList cmdList, RootSignature rootSig, PipelineState pso, GpuDescriptorHandle input)
        {
            cmdList.SetComputeRootSignature(rootSig);
            cmdList.PipelineState = pso;

            cmdList.SetComputeRootDescriptorTable(0, input);
            cmdList.SetComputeRootDescriptorTable(2, _gpuUav);

            cmdList.ResourceBarrierTransition(_output, ResourceStates.GenericRead, ResourceStates.UnorderedAccess);

            // How many groups do we need to dispatch to cover image, where each
            // group covers 16x16 pixels.
            int numGroupsX = (int)Math.Ceiling(_width / 16.0);
            int numGroupsY = (int)Math.Ceiling(_height / 16.0);

            cmdList.Dispatch(numGroupsX, numGroupsY, 1);

            cmdList.ResourceBarrierTransition(_output, ResourceStates.UnorderedAccess, ResourceStates.GenericRead);
        }
コード例 #22
0
ファイル: History.cs プロジェクト: nickchal/pash
 internal long AddEntry(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime, bool skipIfLocked)
 {
     long num;
     if (!Monitor.TryEnter(this._syncRoot, skipIfLocked ? 0 : -1))
     {
         return -1L;
     }
     try
     {
         this.ReallocateBufferIfNeeded();
         HistoryInfo entry = new HistoryInfo(pipelineId, cmdline, status, startTime, endTime);
         num = this.Add(entry);
     }
     finally
     {
         Monitor.Exit(this._syncRoot);
     }
     return num;
 }
コード例 #23
0
        public ForwardRenderer(GraphicsDevice device)
        {
            //Scene.Processors.Add(renderableProcessor);
            samplerState = SamplerState.Create(device, null);

            descriptorPool     = new DisposableObjectPool <DescriptorSet>(() => new DescriptorSet(device, geometryShader.Layout));
            constantBufferPool = new DisposableObjectPool <GraphicsBuffer>(() => GraphicsBuffer.Create(device, constants, false));

            geometryShader = new GeometryShader(device);
            geometryShader.Initialize();
            pipelineStateDescription = new PipelineStateDescription()
            {
                InputLayout   = PositionColorTexture.Layout,
                RootSignature = geometryShader.RootSignature,
                VertexShader  = geometryShader.VertexShader,
                PixelShader   = geometryShader.PixelShader,
            };
            pipelineState = PipelineState.Create(device, pipelineStateDescription);
        }
コード例 #24
0
        /// <summary>
        /// Pauses the SessionGroup defined by the current DataModel.
        /// </summary>
        public virtual void Pause()
        {
            if (DataModel != null && DataModel.Configuration != null)
            {
                CanStart = false;
                CanStop  = false;
                CanPause = false;
                m_currentPipelineState = PipelineState.Pausing;
                RaisePropertyChangedEvent("CurrentPipelineState");
                NotificationBarViewModel.SetState(NotificationState.Info, DataModel.Configuration.SessionGroup.FriendlyName,
                                                  Properties.Resources.PausingString);


                Guid sessionGroupUniqueId = DataModel.Configuration.SessionGroupUniqueId;
                m_backgroundWorker.RunWorkerAsync(new BackgroundWorkerArgs(sessionGroupUniqueId, BackgroundWorkerTask.Pause));

                RuntimeManager.EnableAutoRefresh();
            }
        }
コード例 #25
0
        // Called by the underlying PowerShell pipeline object on state changes.
        private void OnStateChanged(object sender, PipelineStateEventArgs args)
        {
            try
            {
                PipelineState state    = args.PipelineStateInfo.State;
                Pipeline      pipeline = sender as Pipeline;

                if (state == PipelineState.Completed)
                {
                    var result = pipeline.Output.ReadToEnd();
                    if (result != null)
                    {
                        this.Output = new Collection <object>();
                        foreach (var res in result)
                        {
                            Output.Add(res.BaseObject);
                        }
                    }
                    ReadErrorRecords(pipeline);
                    Complete();
                }
                else if (state == PipelineState.Failed)
                {
                    this.Exception = new AggregateException(args.PipelineStateInfo.Reason);
                    ReadErrorRecords(pipeline);
                    Complete();
                }
                else if (state == PipelineState.Stopped)
                {
                    Complete();
                }
                else
                {
                    return; // nothing to do
                }
            }
            catch (Exception e)
            {
                this.Exception = new AggregateException(e);
                Complete();
            }
        }
コード例 #26
0
        public void OverrideInput()
        {
            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(TestHelpers.BuildGraphNode(0, "input", oneInput.TypeName, "Override"));
            nodes.Add(TestHelpers.BuildGraphNode(1, "process"));
            nodes.Add(TestHelpers.BuildGraphNode(2, "output"));

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(TestHelpers.MatchSlots(nodes[0], nodes[1], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[2], 0, 0));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());
            PipelineExecutor[] results = PipelineState.BuildPipesTestOnly();

            Assert.AreEqual(1, results.Length);
            Assert.AreEqual("Override", oneInput.InputDataQuantityPath);
            Assert.AreEqual("Override", oneInput.InputRetrieveDataPath);
        }
コード例 #27
0
        public ParallelPipeline(IReadOnlyList <PipelineStage> pipelineStages)
        {
            this.PipelineStages      = pipelineStages;
            this.MaxConcurrency      = this.PipelineStages.Max(stage => stage.Systems.Count);
            this.ExternalThreadIndex = this.MaxConcurrency;

            this.StartFramePrimitive = new ThreadingPrimitive(this.MaxConcurrency + 1, 10000);
            this.EndFramePrimitive   = new ThreadingPrimitive(this.MaxConcurrency + 1, 10000);

            this.StagePrimitive = new ThreadingPrimitive(this.MaxConcurrency);

            this.Threads = new Thread[this.MaxConcurrency];
            for (var i = 0; i < this.MaxConcurrency; i++)
            {
                this.Threads[i] = new Thread(threadIndex => this.ThreadStart(threadIndex));
                this.Threads[i].Start(i);
            }

            this.pipelineState = PipelineState.ReadyForNextRun;
        }
コード例 #28
0
ファイル: History.cs プロジェクト: modulexcite/pash-1
        internal long AddEntry(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime, bool skipIfLocked)
        {
            long num;

            if (!Monitor.TryEnter(this._syncRoot, skipIfLocked ? 0 : -1))
            {
                return(-1L);
            }
            try
            {
                this.ReallocateBufferIfNeeded();
                HistoryInfo entry = new HistoryInfo(pipelineId, cmdline, status, startTime, endTime);
                num = this.Add(entry);
            }
            finally
            {
                Monitor.Exit(this._syncRoot);
            }
            return(num);
        }
コード例 #29
0
        public void OneLinkToMany()
        {
            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(new GraphNode {
                id = 0, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 1, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 2, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 3, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 4, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 5, title = "used"
            });
            nodes.Add(new GraphNode {
                id = 6, title = "used"
            });

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(new NodeLinkInfo(0, 0, 0, 1, 0));
            links.Add(new NodeLinkInfo(0, 0, 0, 2, 0));
            links.Add(new NodeLinkInfo(0, 0, 0, 3, 1));
            links.Add(new NodeLinkInfo(0, 0, 0, 4, 1));
            links.Add(new NodeLinkInfo(0, 0, 0, 5, 1));
            links.Add(new NodeLinkInfo(0, 0, 0, 6, 1));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());

            GraphNode[] result = PipelineState.ActiveNodes;
            Assert.AreEqual(nodes.ToArray(), result);
            Assert.AreEqual(links.ToArray(), PipelineState.ActiveLinks);
        }
コード例 #30
0
        public virtual bool TransitAtPausedByConflict(PipelineSyncCommand command, out PipelineState currentState)
        {
            bool transitSucceeded = false;

            currentState = PipelineState.Default;
            switch (command)
            {
            case PipelineSyncCommand.FINISH:
                break;

            case PipelineSyncCommand.PAUSE:
                break;

            case PipelineSyncCommand.PAUSE_FOR_CONFLICT:
                currentState     = PipelineState.PausedByConflict;
                transitSucceeded = true;
                break;

            case PipelineSyncCommand.RESUME:
                break;

            case PipelineSyncCommand.START:
                break;

            case PipelineSyncCommand.START_NEW_TRIP:
                currentState     = PipelineState.Starting;
                transitSucceeded = true;
                break;

            case PipelineSyncCommand.STOP:
                break;

            case PipelineSyncCommand.STOP_CURRENT_TRIP:
                break;

            case PipelineSyncCommand.DEFAULT:
            default:
                break;
            }
            return(transitSucceeded);
        }
コード例 #31
0
        public void Stop()
        {
            if (this.pipelineState == PipelineState.Running)
            {
                this.pipelineState = PipelineState.Stopped;
                this.EndFramePrimitive.DecrementAndWait(this.ExternalThreadIndex);

                this.JoinWorkers();
            }
            else if (this.pipelineState == PipelineState.ReadyForNextRun)
            {
                this.pipelineState = PipelineState.Stopped;
                this.StartFramePrimitive.DecrementAndWait(this.ExternalThreadIndex);

                this.JoinWorkers();
            }
            else
            {
                throw new InvalidOperationException($"Cannot call {nameof(Stop)} while the {nameof(ParallelPipeline)} is in the {this.pipelineState} state");
            }
        }
コード例 #32
0
        public GuiPass(RenderTarget target)
            : base("UI", "ui")
        {
            renderTarget = target;

            PipelineState ps = new PipelineState();

            ps.blending.enabled          = true;
            ps.shaderState.shaderProgram = UI.Canvas.theShader;
            ps.blending.enabled          = true;
            ps.culling.enabled           = false;
            ps.depthTest.enabled         = false;

            ps.vaoState.vao = new VertexArrayObject();
            ps.vaoState.vao.bindVertexFormat <V2T2B4>(ps.shaderState.shaderProgram);
            ps.generateId();

            myRenderQueue      = Renderer.device.createRenderQueue(ps);
            myRenderQueue.name = "UI";
            registerQueue(myRenderQueue);
        }
コード例 #33
0
        public void Disturb(GraphicsCommandList cmdList, RootSignature rootSig, PipelineState pso, int i, int j, float magnitude)
        {
            cmdList.PipelineState = pso;
            cmdList.SetComputeRootSignature(rootSig);

            // Set the disturb constants.
            int[] disturbIndex = { j, i };
            Utilities.Pin(ref magnitude, ptr => cmdList.SetComputeRoot32BitConstants(0, 1, ptr, 3));
            Utilities.Pin(disturbIndex, ptr => cmdList.SetComputeRoot32BitConstants(0, 2, ptr, 4));

            cmdList.SetComputeRootDescriptorTable(3, _currSolUav);

            // The current solution is in the GENERIC_READ state so it can be read by the vertex shader.
            // Change it to UNORDERED_ACCESS for the compute shader. Note that a UAV can still be
            // read in a compute shader.
            cmdList.ResourceBarrierTransition(_currSol, ResourceStates.GenericRead, ResourceStates.UnorderedAccess);

            // One thread group kicks off one thread, which displaces the height of one
            // vertex and its neighbors.
            cmdList.Dispatch(1, 1, 1);
        }
コード例 #34
0
        public RenderSystem(PresentationParameters parameters)
        {
            Adapters = GraphicsAdapter.EnumerateGraphicsAdapter();

            Device = new GraphicsDevice(Adapters[0]);

            SwapChain = new GraphicsSwapChain(parameters, Device);

            CommandList = new CommandList(Device);

            Texture = new Texture(Device, SwapChain);

            Shaders = new Shaders(Device, "Shaders/VertexShader.hlsl", "Shaders/PixelShader.hlsl");

            StateWireframe = new PipelineState(Device, FillMode.Wireframe, CullMode.None);

            StateSolid = new PipelineState(Device, FillMode.Solid, CullMode.None);

            Grid = new Grid(1, 1, 8, 8);

            VertexBuffer = new Buffer(Grid.SizeInBytes, Grid.Size, Device, ResourceInfo.VertexBuffer);

            IndexBuffer = new Buffer(Grid.IndexSizeInBytes, Grid.IndexSize, Device, ResourceInfo.IndexBuffer);

            ConstantBuffer = new Buffer(Utilities.SizeOf <Transform>(), Utilities.SizeOf <Transform>(), Device, ResourceInfo.ConstantBuffer);

            TextureAddressMode Wrap = TextureAddressMode.Wrap;

            SamplerState = new SamplerState(Device, Wrap, Wrap, Wrap, Filter.MinMagMipLinear);

            Camera = new Camera(CameraType.Static);

            Camera.Position = new Vector3(0.0f, 0.0f, -2.5f);

            Camera.SetLens((float)Math.PI / 4, 1.2f, 1.0f, 1000.0f);

            World = new Matrix[2];

            CubesTexture1 = Texture.LoadFromFile(Device, "UV_Grid_Lrg.jpg");
        }
コード例 #35
0
        public void Linked()
        {
            // Multi            | Multi
            // S -> Process -> Sync -> Process -> End
            //         v-----------------ᴧ

            List <GraphNode> nodes = new List <GraphNode>();

            nodes.Add(TestHelpers.BuildGraphNode(0, "in", inputPlugin3.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(1, "pro"));
            nodes.Add(TestHelpers.BuildGraphNode(2, "sync", SyncNode.TypeName));
            nodes.Add(TestHelpers.BuildGraphNode(3, "pro"));
            nodes.Add(TestHelpers.BuildGraphNode(4, "end"));

            List <NodeLinkInfo> links = new List <NodeLinkInfo>();

            links.Add(TestHelpers.MatchSlots(nodes[0], nodes[1], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[2], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[1], nodes[3], 0, 1));
            links.Add(TestHelpers.MatchSlots(nodes[2], nodes[3], 0, 0));
            links.Add(TestHelpers.MatchSlots(nodes[3], nodes[4], 0, 0));

            PipelineState.UpdateActiveGraph(nodes.ToArray(), links.ToArray());
            PipelineExecutor[] executor = PipelineState.BuildPipesTestOnly();
            SpecialNodeData    data     = PipelineState.SpecialNodeDataTestOnly;

            Assert.AreEqual(2, data.SyncInformation.NodeGroups.Count);
            Assert.AreEqual(3, data.SyncInformation.NodeGroups[0].pipes.Length);
            Assert.AreEqual(3, data.SyncInformation.NodeGroups[0].RequiredPipes);
            Assert.IsTrue(data.SyncInformation.NodeGroups[0].Input);
            Assert.AreEqual(3, data.SyncInformation.NodeGroups[1].pipes.Length);
            Assert.AreEqual(3, data.SyncInformation.NodeGroups[1].RequiredPipes);
            Assert.AreEqual(3, data.SyncInformation.SyncNodes[0].TriggeredPipelines.Length);
            Assert.AreEqual(3, data.SyncInformation.SyncNodes[0].ParallelismTestOnly);
            Assert.IsFalse(data.SyncInformation.NodeGroups[1].Input);

            Assert.AreSame(data.SyncInformation.NodeGroups[0].pipes, data.SyncInformation.NodeGroups[1].pipes);
            Assert.AreSame(data.SyncInformation.SyncNodes[0].TriggeredPipelines, data.SyncInformation.NodeGroups[1].pipes);
        }
コード例 #36
0
        public static bool IsIntermittentState(PipelineState state)
        {
            switch (state)
            {
            case PipelineState.Default:
            case PipelineState.Paused:
            case PipelineState.Running:
            case PipelineState.Stopped:
            case PipelineState.StoppedSingleTrip:
                return(false);

            case PipelineState.Pausing:
            case PipelineState.Starting:
            case PipelineState.Stopping:
            case PipelineState.StoppingSingleTrip:
                return(true);

            default:
                Debug.Assert(false, "must never reach here");
                return(false);
            }
        }
コード例 #37
0
ファイル: PipelineStateInfo.cs プロジェクト: nickchal/pash
 internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo)
 {
     this._state = pipelineStateInfo.State;
     this._reason = pipelineStateInfo.Reason;
 }
コード例 #38
0
ファイル: RemotePipeline.cs プロジェクト: nickchal/pash
        private void SetPipelineState(PipelineState state, Exception reason)
        {
            PipelineState stopped = state;
            System.Management.Automation.Runspaces.PipelineStateInfo info = null;
            lock (this._syncRoot)
            {
                switch (this._pipelineStateInfo.State)
                {
                    case PipelineState.Running:
                        if (state != PipelineState.Running)
                        {
                            goto Label_005F;
                        }
                        return;

                    case PipelineState.Stopping:
                        if ((state != PipelineState.Running) && (state != PipelineState.Stopping))
                        {
                            break;
                        }
                        return;

                    case PipelineState.Stopped:
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                        return;

                    default:
                        goto Label_005F;
                }
                stopped = PipelineState.Stopped;
            Label_005F:
                this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(stopped, reason);
                info = this._pipelineStateInfo;
                RunspaceAvailability runspaceAvailability = this._runspace.RunspaceAvailability;
                this._runspace.UpdateRunspaceAvailability(this._pipelineStateInfo.State, false);
                this._executionEventQueue.Enqueue(new ExecutionEventQueueItem(this._pipelineStateInfo.Clone(), runspaceAvailability, this._runspace.RunspaceAvailability));
            }
            if (((info.State == PipelineState.Completed) || (info.State == PipelineState.Failed)) || (info.State == PipelineState.Stopped))
            {
                this.Cleanup();
            }
        }
コード例 #39
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),color=new Vector4(1.0f, 0.0f, 0.0f, 1.0f ) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 0.0f, 1.0f, 1.0f ) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBuffer>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
コード例 #40
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } };

            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter = Filter.MinimumMinMagMipPoint,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                MipLODBias = 0,
                MaxAnisotropy = 0,
                ComparisonFunc = Comparison.Never,
                BorderColor = StaticBorderColor.TransparentBlack,
                MinLOD = 0.0f,
                MaxLOD = float.MaxValue,
                ShaderRegister = 0,
                RegisterSpace = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) };

            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });
            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),uv=new Vector2(0.5f, 0.0f) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(1.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(0.0f, 1.0f) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(),
                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            commandQueue.ExecuteCommandList(commandList);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);

            WaitForPreviousFrame();

            //release temp texture
            textureUploadHeap.Dispose();
        }
コード例 #41
0
        private void LoadAssets()
        {
            // Create an empty root signature.
            var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout);
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new []
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            var triangleVertices = new []
            {
                    new Vertex() {Position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),Color=new Vector4(1.0f, 0.0f, 0.0f, 1.0f ) },
                    new Vertex() {Position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),Color=new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
                    new Vertex() {Position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),Color=new Vector4(0.0f, 0.0f, 1.0f, 1.0f ) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // Create and record the bundle.
            bundle = device.CreateCommandList(0, CommandListType.Bundle, bundleAllocator, pipelineState);
            bundle.SetGraphicsRootSignature(rootSignature);
            bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            bundle.SetVertexBuffer(0, vertexBufferView);
            bundle.DrawInstanced(3, 1, 0, 0);
            bundle.Close();

            // Create synchronization objects.
            {
                fence = device.CreateFence(0, FenceFlags.None);
                fenceValue = 1;

                // Create an event handle to use for frame synchronization.
                fenceEvent = new AutoResetEvent(false);
            }
        }
コード例 #42
0
ファイル: History.cs プロジェクト: dfinke/powershell
        /// <summary>
        /// Update the history entry corresponding to id.
        /// </summary>
        /// <param name="id">id of history entry to be updated</param>
        /// <param name="status">status to be updated</param>
        /// <param name="endTime">endTime to be updated</param>
        /// <param name="skipIfLocked">If true, the entry will not be added when the history is locked</param>
        /// <returns></returns>
        internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool skipIfLocked)
        {
            if (!System.Threading.Monitor.TryEnter(_syncRoot, skipIfLocked ? 0 : System.Threading.Timeout.Infinite))
            {
                return;
            }

            try
            {
                HistoryInfo entry = CoreGetEntry(id);
                if (entry != null)
                {
                    entry.SetStatus(status);
                    entry.SetEndTime(endTime);
                }
            }
            finally
            {
                System.Threading.Monitor.Exit(_syncRoot);
            }
        }
コード例 #43
0
ファイル: Connection.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Used to raise the AvailabilityChanged event when the state of the currently executing pipeline changes
        /// </summary>
        /// <remarks>
        /// The possible pipeline states are
        ///     NotStarted
        ///     Running
        ///     Disconnected
        ///     Stopping
        ///     Stopped
        ///     Completed
        ///     Failed
        /// </remarks>
        internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raiseEvent, Guid? cmdInstanceId = null)
        {
            RunspaceAvailability oldAvailability = this.RunspaceAvailability;

            switch (oldAvailability)
            {
                // Because of disconnect/connect support runspace availability can now transition
                // in and out of "None" state.
                case RunspaceAvailability.None:
                    switch (pipelineState)
                    {
                        case PipelineState.Running:
                            this.RunspaceAvailability = RunspaceAvailability.Busy;
                            break;

                            // Otherwise no change.
                    }
                    break;

                case RunspaceAvailability.Available:
                    switch (pipelineState)
                    {
                        case PipelineState.Running:
                            this.RunspaceAvailability = RunspaceAvailability.Busy;
                            break;

                        case PipelineState.Disconnected:
                            this.RunspaceAvailability = Runspaces.RunspaceAvailability.None;
                            break;
                    }
                    break;

                case RunspaceAvailability.AvailableForNestedCommand:
                    switch (pipelineState)
                    {
                        case PipelineState.Running:
                            this.RunspaceAvailability = RunspaceAvailability.Busy;
                            break;

                        case PipelineState.Completed: // a nested pipeline caused the host to exit nested prompt
                            this.RunspaceAvailability = (this.InNestedPrompt || (_runningPowerShells.Count > 1)) ?
                                RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available;
                            break;

                        default:
                            break; // no change in the availability
                    }
                    break;

                case RunspaceAvailability.Busy:
                case RunspaceAvailability.RemoteDebug:
                    switch (pipelineState)
                    {
                        case PipelineState.Disconnected:
                            if (oldAvailability == Runspaces.RunspaceAvailability.RemoteDebug)
                            {
                                this.RunspaceAvailability = RunspaceAvailability.RemoteDebug;
                            }
                            else
                            {
                                this.RunspaceAvailability = RunspaceAvailability.None;
                            }
                            break;

                        case PipelineState.Stopping:
                            break; // no change in the availability

                        case PipelineState.Completed:
                        case PipelineState.Stopped:
                        case PipelineState.Failed:
                            if (this.InNestedPrompt || !(this is RemoteRunspace) && this.Debugger.InBreakpoint)
                            {
                                this.RunspaceAvailability = RunspaceAvailability.AvailableForNestedCommand;
                            }
                            else
                            {
                                RemoteRunspace remoteRunspace = this as RemoteRunspace;
                                RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null;
                                Internal.ConnectCommandInfo remoteCommand = (remoteRunspace != null) ? remoteRunspace.RemoteCommand : null;
                                if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) ||
                                    ((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened)))
                                    && (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId))
                                {
                                    // Completed, Failed, and Stopped with Runspace.Opened states are command finish states and we know 
                                    // that the command is finished on the server.
                                    // Setting ConnectCommands to null indicates that the runspace is free to run other
                                    // commands.
                                    remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ConnectCommands = null;
                                    remoteCommand = null;

                                    if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
                                    {
                                        // Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
                                        remoteDebugger.OnCommandStopped();
                                    }
                                }

                                Pipeline currentPipeline = this.GetCurrentlyRunningPipeline();
                                RemotePipeline remotePipeline = currentPipeline as RemotePipeline;
                                Guid? pipeLineCmdInstance = (remotePipeline != null && remotePipeline.PowerShell != null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null;
                                if (currentPipeline == null)
                                {
                                    // A runspace is available:
                                    //  - if there is no currently running pipeline
                                    //    and for remote runspaces:
                                    //    - if there is no remote command associated with it.
                                    //    - if the remote runspace pool is marked as available for connection.
                                    if (remoteCommand == null)
                                    {
                                        if (remoteRunspace != null)
                                        {
                                            if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
                                            {
                                                // Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
                                                remoteDebugger.OnCommandStopped();
                                            }

                                            this.RunspaceAvailability =
                                                remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.AvailableForConnection ?
                                                RunspaceAvailability.Available : Runspaces.RunspaceAvailability.Busy;
                                        }
                                        else
                                        {
                                            this.RunspaceAvailability = RunspaceAvailability.Available;
                                        }
                                    }
                                }
                                else if ((cmdInstanceId != null) && (pipeLineCmdInstance != null) && (cmdInstanceId == pipeLineCmdInstance))
                                {
                                    if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped))
                                    {
                                        // Notify remote debugger of a stop in case the stop occurred while command was in debug stop.
                                        remoteDebugger.OnCommandStopped();
                                    }

                                    this.RunspaceAvailability = RunspaceAvailability.Available;
                                }
                                else // a nested pipeline completed, but the parent pipeline is still running
                                {
                                    if (oldAvailability == Runspaces.RunspaceAvailability.RemoteDebug)
                                    {
                                        this.RunspaceAvailability = Runspaces.RunspaceAvailability.RemoteDebug;
                                    }
                                    else if ((currentPipeline.PipelineStateInfo.State == PipelineState.Running) || (_runningPowerShells.Count > 1))
                                    {
                                        // Either the current pipeline is running or there are other nested commands to run in the Runspace.
                                        this.RunspaceAvailability = RunspaceAvailability.Busy;
                                    }
                                    else
                                    {
                                        this.RunspaceAvailability = RunspaceAvailability.Available;
                                    }
                                }
                            }
                            break;

                        case PipelineState.Running: // this can happen if a nested pipeline is created without entering a nested prompt
                            break; // no change in the availability

                        default:
                            break; // no change in the availability
                    }
                    break;

                default:
                    Diagnostics.Assert(false, "Invalid RunspaceAvailability");
                    break;
            }

            if (raiseEvent && this.RunspaceAvailability != oldAvailability)
            {
                OnAvailabilityChanged(new RunspaceAvailabilityEventArgs(this.RunspaceAvailability));
            }
        }
コード例 #44
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create a root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = DepthStencilStateDescription.Default(),
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a cube.

            Vertex[] vertices = new[]
            {
                ////TOP
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,1,0,0)),
                //BOTTOM
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,1,1)),
                //LEFT
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,0,1)),
                //RIGHT
                new Vertex(new Vector3(5,-5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,1,0,1)),
                //FRONT
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(-5,-5,5),new Vector4(0,1,1,1)),
                //BACK
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(0,0,1,1))
            };

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            //Indices
            int[] indices = new int[]
            {
                0,1,2,0,2,3,
                4,6,5,4,7,6,
                8,9,10,8,10,11,
                12,14,13,12,15,14,
                16,18,17,16,19,18,
                20,21,22,20,22,23
            };
            int indexBufferSize = Utilities.SizeOf(indices);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;

            //constant Buffer for each cubes
            constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = NumCubes,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            int constantBufferSize = (Utilities.SizeOf<Transform>() + 255) & ~255;
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize * NumCubes), ResourceStates.GenericRead);
            constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            //First cube
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = constantBufferSize
            };

            CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart;

            for (int i = 0; i < NumCubes; i++)
            {
                device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart);
                cbvDesc.BufferLocation += Utilities.SizeOf<Transform>();
                cbHandleHeapStart += constantBufferDescriptorSize;
            }

            InitBundles();
        }
コード例 #45
0
ファイル: PipelineStateInfo.cs プロジェクト: mauve/Pash
 internal PipelineStateInfo(PipelineState state)
 {
     State = state;
 }
コード例 #46
0
ファイル: PipelineStateInfo.cs プロジェクト: mauve/Pash
 internal PipelineStateInfo(PipelineState state, Exception reason)
 {
     State = state;
 }
コード例 #47
0
ファイル: PipelineStateInfo.cs プロジェクト: mauve/Pash
 internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo)
 {
     Reason = pipelineStateInfo.Reason;
     State = pipelineStateInfo.State;
 }
コード例 #48
0
        private void CreateTerrainBind()
        {
            var rootSignatureDesc = new RootSignatureDescription(
               RootSignatureFlags.AllowInputAssemblerInputLayout,
               // Root Parameters
               new[]
               {
                   new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = 0,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 2,
                                OffsetInDescriptorsFromTableStart = 0,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = 0,
                            BaseShaderRegister = 0
                        }),
               });

            terrainRootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());
            var inputElementDescs = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0),
                    new InputElement("BITANGENT", 0, Format.R32G32B32_Float, 36, 0),
                    new InputElement("DIFFUSE", 0, Format.R32G32B32_Float, 48, 0),
                    new InputElement("EMISSIVE", 0, Format.R32G32B32_Float, 64, 0),
                    new InputElement("SPECULAR", 0, Format.R32G32B32_Float, 80, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 96, 0)
            };
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = terrainRootSignature,
                VertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../Terrain.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)),
                PixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../Terrain.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)),
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState2 = device.CreateGraphicsPipelineState(psoDesc);
        }
コード例 #49
0
        private void CreatePSO(InputElement[] inputElementDescs,ShaderBytecode vertexShader,ShaderBytecode pixelShader)
        {
            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();
        }
コード例 #50
0
ファイル: PipelineStateInfo.cs プロジェクト: nickchal/pash
 internal PipelineStateInfo(PipelineState state, Exception reason)
 {
     this._state = state;
     this._reason = reason;
 }
コード例 #51
0
ファイル: PipelineStateInfo.cs プロジェクト: nickchal/pash
 internal PipelineStateInfo(PipelineState state) : this(state, null)
 {
 }
コード例 #52
0
ファイル: Pipeline.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// Initializes a new instance of the InvalidPipelineStateException and defines value of 
 /// CurrentState and ExpectedState
 /// </summary>
 /// <param name="message">The error message that explains the reason for the exception. 
 /// </param>
 /// <param name="currentState">Current state of pipeline</param>
 /// <param name="expectedState">Expected state of pipeline</param>
 internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState)
 : base(message)
 {
     _expectedState = expectedState;
     _currentState = currentState;
 }
コード例 #53
0
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue,
                                BaseShaderRegister = 0
                            },
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = int.MinValue,
                            BaseShaderRegister = 0
                        }),
                });
                //// Samplers
                //new[]
                //{
                //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                //    {
                //        Filter = Filter.MinimumMinMagMipPoint,
                //        AddressUVW = TextureAddressMode.Border,
                //    }
                //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            #if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                GeometryShader = geometryShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //BOTTOM
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //LEFT
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                //RIGHT
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)} ,
                //FRONT
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                //BACK
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)}
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0,1,2,
                0,2,3,

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

                8,9,10,
                8,10,11,

                12,14,13,
                12,15,14,

                16,18,17,
                16,19,18,

                20,21,22,
                20,22,23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes = indexBufferSize;
            indexBufferView.Format = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) |(((1) & 0x7) << 3) |(((2) & 0x7) << (3 * 2)) |(((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels = 1,
                    MostDetailedMip = 0,
                    PlaneSlice = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
コード例 #54
0
ファイル: LocalPipeline.cs プロジェクト: Ventero/Pash
        private void SetPipelineState(PipelineState state, Exception reason)
        {
            _pipelineStateInfo = new PipelineStateInfo(state, reason);

            if (StateChanged != null)
                StateChanged(this, new PipelineStateEventArgs(_pipelineStateInfo));
        }
コード例 #55
0
ファイル: LocalPipeline.cs プロジェクト: Ventero/Pash
 private void SetPipelineState(PipelineState state)
 {
     SetPipelineState(state, null);
 }
コード例 #56
0
ファイル: History.cs プロジェクト: nickchal/pash
 internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool skipIfLocked)
 {
     if (Monitor.TryEnter(this._syncRoot, skipIfLocked ? 0 : -1))
     {
         try
         {
             HistoryInfo info = this.CoreGetEntry(id);
             if (info != null)
             {
                 info.SetStatus(status);
                 info.SetEndTime(endTime);
             }
         }
         finally
         {
             Monitor.Exit(this._syncRoot);
         }
     }
 }
コード例 #57
0
ファイル: PoshHost.cs プロジェクト: ForNeVeR/PoshConsole
		//void Execute(string cmd)
		//{
		//    try
		//    {
		//        // execute the command with no Input...
		//        ExecuteHelper(cmd, null, true);
		//    }
		//    catch (RuntimeException rte)
		//    {
		//        // An exception occurred that we want to display ...
		//        // We have to run another pipeline, and pass in the error record.
		//        // The runtime will bind the Input to the $Input variable
		//        ExecuteHelper("write-host ($Input | out-string) -fore darkyellow", rte.ErrorRecord, false);
		//    }
		//}
		///// <summary>
		///// Invoke's the user's PROMPT function to display a prompt.
		///// Called after each command completes
		///// </summary>
		//internal void Prompt()
		//{
		//    StringBuilder sb = new StringBuilder();
		//    try
		//    {
		//        Collection<PSObject> output = InvokePipeline("prompt");

		//        foreach (PSObject thing in output)
		//        {
		//            sb.Append(thing.ToString());
		//        }
		//        //sb.Append(PromptPadding);
		//    }
		//    catch (RuntimeException rte)
		//    {
		//        // An exception occurred that we want to display ...
		//        // We have to run another pipeline, and pass in the error record.
		//        // The runtime will bind the Input to the $Input variable
		//        ExecuteHelper("write-host \"ERROR: Your prompt function crashed!\n\" -fore darkyellow", null, false);
		//        ExecuteHelper("write-host ($Input | out-string) -fore darkyellow", rte.ErrorRecord, false);
		//        sb.Append("\n> ");
		//    }
		//    finally
		//    {
		//        _buffer.Prompt(sb.ToString());
		//    }
		//}
		private void ExecutePromptFunction(String command, PipelineState lastState)
		{
			_buffer.OnCommandFinished(command, lastState);
			// It is IMPERATIVE that we call "New-Paragraph" before Prompt
			_runner.Enqueue(new InputBoundCommand(new[] {"New-Paragraph", "Prompt"}, EmptyArray, result =>
				{
					StringBuilder str = new StringBuilder();

					foreach (PSObject obj in result.Output)
					{
						str.Append(obj);
					}
					// ToDo: write errors from PROMPT the same as we would for a regular command...
					//if(result.State == PipelineState.Failed ) {
					//   str.Append(result.Failure.Message);
					//   str.Append(result.Failure.Message);

					_buffer.Prompt(str.ToString());
				}) {AddToHistory = false, RunAsScript = false, DefaultOutput = false});
		}
コード例 #58
0
        private void LoadAssets()
        {
            RootParameter parameter1 = new RootParameter(ShaderVisibility.All, new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 });
            RootParameter parameter2 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, BaseShaderRegister = 0, DescriptorCount = 1 });
            RootParameter parameter3 = new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.Sampler, BaseShaderRegister = 0, DescriptorCount = 1 });

            // Create a root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter1, parameter2, parameter3 });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("NORMAL",0,Format.R32G32B32_Float,12,0),
                    new InputElement("TEXCOORD",0,Format.R32G32B32_Float,24,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = DepthStencilStateDescription.Default(),
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            //constant Buffer
            int constantBufferSize = (Utilities.SizeOf<Transform>() + 255) & ~255;
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize), ResourceStates.GenericRead);
            constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            //constant buffer
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = constantBufferSize
            };

            CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart;
            device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart);
            cbvDesc.BufferLocation += Utilities.SizeOf<Transform>();

            cbHandleHeapStart += constantBufferDescriptorSize;
            LoadMesh(cbHandleHeapStart);

            // Create synchronization objects.
            {
                fence = device.CreateFence(0, FenceFlags.None);
                fenceValue = 1;

                // Create an event handle to use for frame synchronization.
                fenceEvent = new AutoResetEvent(false);
            }

            InitBundles();
        }
コード例 #59
0
ファイル: remotepipeline.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Sets the new execution state.
        /// </summary>
        /// <param name="state">the new state</param>
        /// <param name="reason">
        /// An exception indicating that state change is the result of an error, 
        /// otherwise; null.
        /// </param>
        /// <remarks>
        /// Sets the internal execution state information member variable. It
        /// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents
        /// raises event for each item in this queue.  
        /// </remarks>
        private void SetPipelineState(PipelineState state, Exception reason)
        {
            PipelineState copyState = state;
            PipelineStateInfo copyStateInfo = null;

            lock (_syncRoot)
            {
                switch (_pipelineStateInfo.State)
                {
                    case PipelineState.Completed:
                    case PipelineState.Failed:
                    case PipelineState.Stopped:
                        return;

                    case PipelineState.Running:
                        {
                            if (state == PipelineState.Running)
                            {
                                return;
                            }
                        }
                        break;
                    case PipelineState.Stopping:
                        {
                            if (state == PipelineState.Running || state == PipelineState.Stopping)
                            {
                                return;
                            }
                            else
                            {
                                copyState = PipelineState.Stopped;
                            }
                        }
                        break;
                }
                _pipelineStateInfo = new PipelineStateInfo(copyState, reason);
                copyStateInfo = _pipelineStateInfo;

                //Add _pipelineStateInfo to _executionEventQueue. 
                //RaisePipelineStateEvents will raise event for each item
                //in this queue.
                //Note:We are doing clone here instead of passing the member 
                //_pipelineStateInfo because we donot want outside
                //to change pipeline state.
                RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability;

                Guid? cmdInstanceId = (_powershell != null) ? _powershell.InstanceId : (Guid?)null;
                _runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false, cmdInstanceId);

                _executionEventQueue.Enqueue(
                    new ExecutionEventQueueItem(
                        _pipelineStateInfo.Clone(),
                        previousAvailability,
                        _runspace.RunspaceAvailability));
            } // lock...

            // using the copyStateInfo here as this piece of code is 
            // outside of lock and _pipelineStateInfo might get changed
            // by two threads running concurrently..so its value is 
            // not guaranteed to be the same for this entire method call.
            // copyStateInfo is a local variable.
            if (copyStateInfo.State == PipelineState.Completed ||
                copyStateInfo.State == PipelineState.Failed ||
                copyStateInfo.State == PipelineState.Stopped)
            {
                Cleanup();
            }
        }
コード例 #60
0
 internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState)
 {
     CurrentState = currentState;
     ExpectedState = expectedState;
 }