public static int Main(string[] args) { if (args.Length < 3) { Console.Error.WriteLine("Usage: RunUDPipe input_format(tokenize|conllu|horizontal|vertical) output_format(conllu) model"); return 1; } Console.Error.Write("Loading model: "); Model model = Model.load(args[2]); if (model == null) { Console.Error.WriteLine("Cannot load model from file '{0}'", args[2]); return 1; } Console.Error.WriteLine("done"); Pipeline pipeline = new Pipeline(model, args[0], Pipeline.DEFAULT, Pipeline.DEFAULT, args[1]); ProcessingError error = new ProcessingError(); // Read whole input StringBuilder textBuilder = new StringBuilder(); string line; while ((line = Console.In.ReadLine()) != null) textBuilder.Append(line).Append('\n'); // Process data string text = textBuilder.ToString(); string processed = pipeline.process(text, error); if (error.occurred()) { Console.Error.WriteLine("An error occurred in RunUDPipe: {0}", error.message); return 1; } Console.Write(processed); return 0; }
static void Main(string[] args) { var prefilterPump = new OrderSource(); var prefilterSink = new OrderSink(); var prefilter = new Pipeline<Order>(prefilterPump, prefilterSink, "prefiltering") .Register(new CalculateSubtotal() { Name = "Subtotal calculator" }) .Register(new CalculateTax() { Name = "Tax calculator" }) .Register(new CalculateTotal() { Name = "Total calculator" }) ; prefilter.Execute(); Console.WriteLine("".PadRight(50, '=')); foreach (var input in prefilterSink.Orders) { var result = string.Format("{0} {1:C} {2} {3:C} {4:C} {5:C}", input.Name.PadRight(10), input.Price, input.Quantity, input.Subtotal, input.Tax, input.Total ); Console.WriteLine(result); } Console.WriteLine("".PadRight(50, '=')); Console.ReadKey(); }
public void testSelfFilter() { var _List = new List<String>() { "marko", "antonio", "rodriguez", "was", "here", "." }; var _Pipe1 = new AggregatorPipe<String>(new List<String>()); var _Pipe2 = new CollectionFilterPipe<String>(_Pipe1.SideEffect, ComparisonFilter.NOT_EQUAL); var _Pipeline = new Pipeline<String, String>(_Pipe1, _Pipe2); _Pipeline.SetSourceCollection(_List); var _Counter = 0; while (_Pipeline.MoveNext()) _Counter++; Assert.AreEqual(6, _Counter); _Pipe1 = new AggregatorPipe<String>(new List<String>()); _Pipe2 = new CollectionFilterPipe<String>(_Pipe1.SideEffect, ComparisonFilter.EQUAL); _Pipeline = new Pipeline<String, String>(_Pipe1, _Pipe2); _Pipeline.SetSourceCollection(_List); _Counter = 0; while (_Pipeline.MoveNext()) _Counter++; Assert.AreEqual(0, _Counter); }
void ExecuteCommand() { var pipeline = currentPipeline; try { pipeline.Invoke(); foreach (PSObject errorRecord in pipeline.Error.ReadToEnd()) { var errorMessage = "Error executing powershell: " + errorRecord; LogTo.Error(errorMessage); LogError(errorMessage); } } finally { try { if (pipeline != null) { pipeline.Dispose(); } } finally { currentPipeline = null; } } }
public void TestBufferOwnership () { MyTransformIp.Register (); Pipeline pipeline = new Pipeline (); Element src = ElementFactory.Make ("fakesrc"); src["num-buffers"] = 10; Element transform = new MyTransformIp (); Element sink = ElementFactory.Make ("fakesink"); pipeline.Add (src, transform, sink); Element.Link (src, transform, sink); Gst.GLib.MainLoop loop = new Gst.GLib.MainLoop (); pipeline.Bus.AddWatch (delegate (Bus bus, Message message) { switch (message.Type) { case MessageType.Error: Enum err; string msg; message.ParseError (out err, out msg); Assert.Fail (String.Format ("Error message: {0}", msg)); loop.Quit (); break; case MessageType.Eos: loop.Quit (); break; } return true; }); pipeline.SetState (State.Playing); loop.Run (); pipeline.SetState (State.Null); }
static LinkContext GetDefaultContext(Pipeline pipeline) { LinkContext context = new LinkContext (pipeline); context.CoreAction = AssemblyAction.Skip; context.OutputDirectory = "output"; return context; }
public void DefaultCtorSplitsAtDashes() { // Given Engine engine = new Engine(); Metadata metadata = new Metadata(engine); Pipeline pipeline = new Pipeline("Pipeline", engine, null); IExecutionContext context = new ExecutionContext(engine, pipeline); IDocument[] inputs = { new Document(metadata).Clone(@"FM1 FM2 --- Content1 Content2") }; string frontMatterContent = null; FrontMatter frontMatter = new FrontMatter(new Execute(x => { frontMatterContent = x.Content; return new [] {x}; })); // When IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context); // Then Assert.AreEqual(1, documents.Count()); Assert.AreEqual(@"FM1 FM2 ", frontMatterContent); Assert.AreEqual(@"Content1 Content2", documents.First().Content); }
public static void Main (string[] args) { Application.Init(); loop = new MainLoop(); // Construct all the elements pipeline = new Pipeline(); appsrc = new Gst.App.AppSrc ("AppSrcDemo"); Element color = ElementFactory.Make ("ffmpegcolorspace"); Element sink = ElementFactory.Make ("autovideosink"); // Link the elements pipeline.Add (appsrc, color, sink); Element.Link (appsrc, color, sink); // Set the caps on the AppSrc to RGBA, 640x480, 4 fps, square pixels Gst.Video.VideoFormat fmt = (BitConverter.IsLittleEndian) ? Gst.Video.VideoFormat.BGRA : Gst.Video.VideoFormat.ARGB; appsrc.Caps = Gst.Video.VideoUtil.FormatNewCaps (fmt, 640, 480, 4, 1, 1, 1); // Connect the handlers appsrc.NeedData += PushAppData; pipeline.Bus.AddSignalWatch(); pipeline.Bus.Message += MessageHandler; // Run, loop, run! pipeline.SetState (State.Playing); loop.Run(); pipeline.SetState (State.Null); }
public void TestAsyncStateChangeEmpty() { Pipeline pipeline = new Pipeline(); Assert.IsNotNull (pipeline, "Could not create pipeline"); Assert.AreEqual ( ( (Element) pipeline).SetState (State.Playing), StateChangeReturn.Success); }
public void ToLookupOfStringReturnsCorrectLookup() { // Given Engine engine = new Engine(); Pipeline pipeline = new Pipeline("Pipeline", engine, null); IDocument a = new Document(engine, pipeline) .Clone("a", new[] { new KeyValuePair<string, object>("Numbers", new[] { 1, 2, 3 }) }); IDocument b = new Document(engine, pipeline) .Clone("b", new[] { new KeyValuePair<string, object>("Numbers", new[] { 2, 3, 4 }) }); IDocument c = new Document(engine, pipeline) .Clone("c", new[] { new KeyValuePair<string, object>("Numbers", 3) }); IDocument d = new Document(engine, pipeline) .Clone("d", new[] { new KeyValuePair<string, object>("Numbers", "4") }); List<IDocument> documents = new List<IDocument>() { a, b, c, d }; // When ILookup<string, IDocument> lookup = documents.ToLookup<string>("Numbers"); // Then Assert.AreEqual(4, lookup.Count); CollectionAssert.AreEquivalent(new[] { a }, lookup["1"]); CollectionAssert.AreEquivalent(new[] { a, b }, lookup["2"]); CollectionAssert.AreEquivalent(new[] { a, b, c }, lookup["3"]); CollectionAssert.AreEquivalent(new[] { b, d }, lookup["4"]); }
public void TestAsyncStateChangeFake() { bool done = false; Pipeline pipeline = new Pipeline(); Assert.IsNotNull (pipeline, "Could not create pipeline"); Element src = ElementFactory.Make ("fakesrc"); Element sink = ElementFactory.Make ("fakesink"); Bin bin = (Bin) pipeline; bin.Add (src, sink); src.Link (sink); Bus bus = pipeline.Bus; Assert.AreEqual ( ( (Element) pipeline).SetState (State.Playing), StateChangeReturn.Async); while (!done) { State old, newState, pending; Message message = bus.Poll (MessageType.StateChanged, -1); if (message != null) { message.ParseStateChanged (out old, out newState, out pending); if (message.Src == (Gst.Object) pipeline && newState == State.Playing) done = true; } } Assert.AreEqual ( ( (Element) pipeline).SetState (State.Null), StateChangeReturn.Success); }
internal override void Stencil(Pipeline pipeline) { int len = _glyphs.Length; pipeline.BeginCPUTextStenciling(Font.FillRule); for (int i = 0; i < len; i++) pipeline.StencilGlyph(_glyphs[i], ref _offsets[i]); }
internal override void Stencil(Pipeline pipeline) { if (Glyphs == null || _vertices == null) return; pipeline.StencilInstancedGlyphs(Font.FillRule, this); }
static void Main(string[] args) { var pump = new FileDataSource(new StreamReader(@"data\TestData.txt")); var shifter = new CircularShifter(); var alphabetizer = new Alphabetizer(); #region Modifying the requirement - add a 'noise' list to remove words from the index //var noiseWords = new FileDataSource(new StreamReader(@"data\noise.txt")).Begin(); //var noiseRemover = new NoiseRemoval(noiseWords); //pump.Successor = noiseRemover; //noiseRemover.Successor = shifter; #endregion pump.Successor = shifter; shifter.Successor = alphabetizer; var pipeline = new Pipeline<string>(pump: pump, sink: new ConsoleWriter()); Console.WriteLine("Begin Execution At:{0}", DateTime.UtcNow); pipeline.Execute(); Console.WriteLine("Stop Execution At:{0}", DateTime.UtcNow); Console.WriteLine("Press any key to continue"); Console.ReadKey(); }
public void DashStringDoesNotSplitAtNonmatchingDashes() { // Given Engine engine = new Engine(); Metadata metadata = new Metadata(engine); Pipeline pipeline = new Pipeline("Pipeline", engine, null); IExecutionContext context = new ExecutionContext(engine, pipeline); IDocument[] inputs = { new Document(metadata).Clone(@"FM1 FM2 --- Content1 Content2") }; bool executed = false; FrontMatter frontMatter = new FrontMatter("-", new Execute(x => { executed = true; return new[] { x }; })); // When IEnumerable<IDocument> documents = frontMatter.Execute(inputs, context); // Then Assert.AreEqual(1, documents.Count()); Assert.IsFalse(executed); Assert.AreEqual(@"FM1 FM2 --- Content1 Content2", documents.First().Content); }
public void Should_throw_exception_when_chain_goes_too_far() { var pipeline = new Pipeline<int, string>(); pipeline.Add(new AddToInput(3)); Assert.Throws<EndOfChainException>(() => pipeline.Execute(2)); }
public void testMultiProperty() { var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _EVP = new InVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PPipe = new PropertyPipe<String, Object>(Keys: "name"); var _Pipeline = new Pipeline<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, String>(_EVP, _PPipe); _Pipeline.SetSourceCollection(_Marko.OutEdges()); var _Counter = 0; while (_Pipeline.MoveNext()) { var _Name = _Pipeline.Current; Assert.IsTrue(_Name.Equals("vadas") || _Name.Equals("josh") || _Name.Equals("lop")); _Counter++; } Assert.AreEqual(3, _Counter); }
public void Should_load_all_filters_in_assembly() { var pipeline = new Pipeline<int, string>(serviceProvider) .AddAssembly(typeof(AddFiltersInAssemblyTests).Assembly); Assert.That(pipeline.Count, Is.EqualTo(5)); }
public void testListProperty() { var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _Vadas = _Graph.VertexById(2); var _Pipe = new PropertyPipe<String, Object>(Keys: "name"); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, String>(_Pipe); _Pipeline.SetSource(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko, _Vadas }.GetEnumerator()); var _Counter = 0; while (_Pipeline.MoveNext()) { var _Name = _Pipeline.Current; Assert.IsTrue(_Name.Equals("vadas") || _Name.Equals("marko")); _Counter++; } Assert.AreEqual(2, _Counter); }
public static void Main (string [] args) { Application.Init(); if (args.Length != 1) { Console.Error.WriteLine ("usage: mono queueexample.exe <filename>\n"); return; } Element pipeline = new Pipeline ("pipeline"); Element filesrc = ElementFactory.Make ("filesrc", "disk_source"); filesrc.SetProperty ("location", args[0]); Element decode = ElementFactory.Make ("mad", "decode"); Element queue = ElementFactory.Make ("queue", "queue"); Element audiosink = ElementFactory.Make ("alsasink", "play_audio"); Bin bin = (Bin) pipeline; bin.AddMany (filesrc, decode, queue, audiosink); Element.LinkMany (filesrc, decode, queue, audiosink); pipeline.SetState (State.Playing); EventLoop (pipeline); pipeline.SetState (State.Null); }
/// <summary> /// Deletes the pipeline and sets its corresponding property to null. /// </summary> /// <param name="p">The pipeline that will be deleted.</param> public override void ClearPipeline(Pipeline p) { if (this.IncomePipeline == p) { this.IncomePipeline = null; } }
public MessageRegistration(Type messageType, Type handlerType, Pipeline pipeline, IReadOnlyCollection<Type> dependancies, IReadOnlyCollection<Type> scopedDependancies) { if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (handlerType == null) throw new ArgumentNullException(nameof(handlerType)); if (pipeline == null) throw new ArgumentNullException(nameof(pipeline)); if (dependancies == null) throw new ArgumentNullException(nameof(dependancies)); if (scopedDependancies == null) throw new ArgumentNullException(nameof(scopedDependancies)); var messageTypeInfo = messageType.GetTypeInfo(); if (!typeof(IMessage).GetTypeInfo().IsAssignableFrom(messageTypeInfo)) throw new ArgumentException($"Parameter {nameof(messageType)} must implement IMessage", nameof(messageType)); if (typeof(ICommand).GetTypeInfo().IsAssignableFrom(messageTypeInfo)) { GetValue(new[] { messageType }, messageType, handlerType, type => typeof(ICommandHandler<>).MakeGenericType(type)); } else if (typeof(IEvent).GetTypeInfo().IsAssignableFrom(messageTypeInfo)) { GetValue(MessagesHelper.ExpandType(messageType).Where(x => x != typeof(IMessage)), messageType, handlerType, type => typeof(IEventHandler<>).MakeGenericType(type)); } else if (typeof(IQuery).GetTypeInfo().IsAssignableFrom(messageTypeInfo)) { var genericArguments = messageTypeInfo.ImplementedInterfaces.Single(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IQuery<,>)).GenericTypeArguments; GetValue(new[] { messageType }, messageType, handlerType, type => typeof(IQueryHandler<,>).MakeGenericType(genericArguments)); } this.MessageType = messageType; this.Pipeline = pipeline; this.Handler = handlerType; Dependancies = dependancies; ScopedDependancies = scopedDependancies; }
static void Main(string[] args) { // create a set of functions that we want to pipleline together Func<int, double> func1 = (input => Math.Pow(input, 2)); Func<double, double> func2 = (input => input / 2); Func<double, bool> func3 = (input => input % 2 == 0 && input > 100); // define a callback Action<int, bool> callback = (input, output) => { if (output) { Console.WriteLine("Found value {0} with result {1}", input, output); } }; // create the pipeline Pipeline<int, bool> pipe = new Pipeline<int, double>(func1).AddFunction(func2).AddFunction(func3); // start the pipeline pipe.StartProcessing(); // generate values and push them into the pipeline for (int i = 0; i < 1000; i++) { Console.WriteLine("Added value {0}", i); pipe.AddValue(i, callback); } // stop the pipeline pipe.StopProcessing(); // wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine(); }
public static void Main(string [] args) { Application.Init (); Pipeline pipeline = new Pipeline ("pipeline"); Element source = ElementFactory.Make ("filesrc", "source"); typefind = TypeFindElement.Make ("typefind"); Element sink = ElementFactory.Make ("fakesink", "sink"); source.SetProperty ("location", args[0]); typefind.HaveType += OnHaveType; pipeline.AddMany (source, typefind, sink); source.Link (typefind); typefind.Link (sink); pipeline.SetState (State.Paused); pipeline.SetState (State.Null); source.Dispose (); typefind.Dispose (); sink.Dispose (); pipeline.Dispose (); }
public void TestPathPipe() { var _graph = DemoGraphFactory.CreateSimpleGraph(); var Alice = _graph.VertexById("Alice").AsMutable(); var _Pipe1 = new OutEdgesPipe<String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object>(); var _Pipe2 = new InVertexPipe<String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object>(); var _Pipe3 = new PathPipe<IReadOnlyGenericPropertyVertex<String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object>>(); var _Pipeline = new Pipeline<IReadOnlyGenericPropertyVertex<String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object>, IEnumerable<Object>>(_Pipe1, _Pipe2, _Pipe3); _Pipeline.SetSource(new SingleEnumerator<IReadOnlyGenericPropertyVertex<String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object, String, Int64, String, String, Object>>(Alice)); // Via pipeline... var query1 = _Pipeline.Select(path => path.Select(q => ((IIdentifier<String>) q).Id)).ToArray(); Assert.AreEqual(3, query1.Length); Assert.AreEqual(3, query1[0].Count(), "'" + query1[0].AggString() + "' is invalid!"); Assert.AreEqual(3, query1[1].Count(), "'" + query1[1].AggString() + "' is invalid!"); Assert.AreEqual(3, query1[2].Count(), "'" + query1[2].AggString() + "' is invalid!"); Assert.AreEqual("Alice|Alice -loves-> Bob|Bob", query1[0].AggString()); Assert.AreEqual("Alice|0|Bob", query1[1].AggString()); Assert.AreEqual("Alice|2|Carol", query1[2].AggString()); // Via extention methods... var query2 = Alice.OutE().InV().Paths().ToArray(); Assert.AreEqual(3, query2.Length); Assert.AreEqual(3, query2[0].Count(), "'" + query2[0].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); Assert.AreEqual(3, query2[1].Count(), "'" + query2[1].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); Assert.AreEqual(3, query2[2].Count(), "'" + query2[2].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); var query3 = Alice.Out().Paths().ToArray(); Assert.AreEqual(3, query2.Length); Assert.AreEqual(3, query2[0].Count(), "'" + query2[0].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); Assert.AreEqual(3, query2[1].Count(), "'" + query2[1].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); Assert.AreEqual(3, query2[2].Count(), "'" + query2[2].Select(q => ((IIdentifier<String>) q).Id).AggString() + "' is invalid!"); }
public WorkflowProcessor(Step theStep, FilterRegistry<Step> registry, Workflow workflow) { this.step = theStep; this.filterRegistry = registry; this.workflow = workflow; this.pipeline = new Pipeline<Step>(); }
/// <summary> /// Deletes the pipeline and sets its corresponding property to null. /// </summary> /// <param name="p">The pipeline that will be deleted.</param> public override void ClearPipeline(Pipeline p) { if (this.OutcomePipeline == p) { this.OutcomePipeline = null; this.Flow = 0; } }
public void Compare(VarietyPair varietyPair) { _busyService.ShowBusyIndicatorUntilFinishDrawing(); Messenger.Default.Send(new PerformingComparisonMessage(varietyPair)); var pipeline = new Pipeline<VarietyPair>(GetCompareProcessors()); pipeline.Process(varietyPair.ToEnumerable()); Messenger.Default.Send(new ComparisonPerformedMessage(varietyPair)); }
public void testUniquePathFilter() { var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Pipe1 = new OutEdgesPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe2 = new InVertexPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe3 = new InEdgesPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe4 = new OutVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe5 = new UniquePathFilterPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Pipe1, _Pipe2, _Pipe3, _Pipe4, _Pipe5); _Pipeline.SetSource(new SingleEnumerator<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Graph.VertexById(1))); var _Counter = 0; foreach (var _Object in _Pipeline) { _Counter++; Assert.IsTrue(_Object.Equals(_Graph.VertexById(6)) || _Object.Equals(_Graph.VertexById(4))); } Assert.AreEqual(2, _Counter); }
public void StringWith_UpdateBy_ReturnsValue() { var input = "UpdateBy"; Pipeline<string> pipeline = new Pipeline<string>(); string result = pipeline.Register(new UpdateFilter()) .Execute(input); Assert.AreEqual(input, result); }
public TextArrayRenderer(GraphicsDevice gd, FontAtlas charAtlas, BindableResource projectionBuffer) { var factory = gd.ResourceFactory; var surfaceTextureView = factory.CreateTextureView(charAtlas.Texture); // create the vertex buffer _vertexBuffer = factory.CreateBuffer(new BufferDescription( (uint)charAtlas.Count * 4 * VertexPositionColor.SizeInBytes, BufferUsage.VertexBuffer)); var quadVertices = new VertexPositionColor[charAtlas.Count * 4]; for (int i = 0; i < charAtlas.Count; ++i) { var cell = charAtlas[(char)i]; quadVertices[i * 4 + 0].Position.X = 0; quadVertices[i * 4 + 1].Position.X = 1; quadVertices[i * 4 + 2].Position.X = 0; quadVertices[i * 4 + 3].Position.X = 1; quadVertices[i * 4 + 0].Position.Y = 0; quadVertices[i * 4 + 1].Position.Y = 0; quadVertices[i * 4 + 2].Position.Y = 1; quadVertices[i * 4 + 3].Position.Y = 1; quadVertices[i * 4 + 0].Texture = cell.TopLeft; quadVertices[i * 4 + 1].Texture = cell.TopRight; quadVertices[i * 4 + 2].Texture = cell.BottomLeft; quadVertices[i * 4 + 3].Texture = cell.BottomRight; quadVertices[i * 4 + 0].Color = RgbaFloat.White; quadVertices[i * 4 + 1].Color = RgbaFloat.White; quadVertices[i * 4 + 2].Color = RgbaFloat.White; quadVertices[i * 4 + 3].Color = RgbaFloat.White; } gd.UpdateBuffer(_vertexBuffer, 0, quadVertices); // setup the index buffer ushort[] quadIndices = { 0, 1, 2, 3 }; _indexBuffer = factory.CreateBuffer(new BufferDescription((uint)quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); gd.UpdateBuffer(_indexBuffer, 0, quadIndices); // create the world matrix buffer _worldBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer)); // create the color buffer _colorBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer)); // create vertex layout var vertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Texture", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4)); // create vertex and pixel shaders var vertexShaderDesc = new ShaderDescription( ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"); var fragmentShaderDesc = new ShaderDescription( ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main"); var shaders = factory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc); // create resource layout and resource set for projection buffer and texture var projectionTextureResourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("WorldBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment), new ResourceLayoutElementDescription("ColorBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment))); _projectionTextureResourceSet = factory.CreateResourceSet(new ResourceSetDescription( projectionTextureResourceLayout, projectionBuffer, _worldBuffer, surfaceTextureView, factory.CreateSampler(new SamplerDescription { AddressModeU = SamplerAddressMode.Clamp, AddressModeV = SamplerAddressMode.Clamp, AddressModeW = SamplerAddressMode.Clamp, Filter = SamplerFilter.Anisotropic, LodBias = 0, MinimumLod = 0, MaximumLod = uint.MaxValue, MaximumAnisotropy = 4 }), _colorBuffer)); // create pipeline _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false), PrimitiveTopology = PrimitiveTopology.TriangleStrip, ResourceLayouts = new[] { projectionTextureResourceLayout }, ShaderSet = new ShaderSetDescription( vertexLayouts: new[] { vertexLayout }, shaders: shaders), Outputs = gd.SwapchainFramebuffer.OutputDescription }); }
/// <summary> /// Initializes a new instance of the <see cref="RemoteImporter"/> class. /// </summary> /// <param name="pipeline">Pipeline to which to attach.</param> /// <param name="host">Remote host name.</param> /// <param name="port">TCP port on which to connect (default 11411).</param> /// <param name="allowSequenceRestart">Whether to allow sequence ID restarts upon connection loss/reacquire.</param> /// <remarks>In this case the start is a special behavior that is `DateTime.UtcNow` _at the sending `RemoteExporter`_.</remarks> public RemoteImporter(Pipeline pipeline, string host, int port = RemoteExporter.DefaultPort, bool allowSequenceRestart = true) : this(name => PsiStore.Open(pipeline, name, null), new TimeInterval(DateTime.MinValue, DateTime.MaxValue), true, host, port, $"RemoteImporter_{Guid.NewGuid().ToString()}", null, allowSequenceRestart) { }
// Debug function to Visualise video color in command public static void AsciiColor(Pipeline pipeline) { Processing(pipeline, AsciiColorFrame); }
public static void DisplayPoints(Pipeline pipeline) { Processing(pipeline, DisplayPointsFrame); }
public async Task SessionCreateDerivedPartition() { var dataset = new Dataset(); var session = dataset.CreateSession(); // generate a test store GenerateTestStore("OriginalStore", StorePath); // add a partition var partition0 = session.AddStorePartition("OriginalStore", StorePath, "Partition_0"); Assert.AreEqual(1, session.Partitions.Count); Assert.AreEqual("Partition_0", session.Partitions[0].Name); int multiplier = 7; // create a derived partition which contains the values from the original stream multiplied by a multiplier await session.CreateDerivedPartitionAsync( (pipeline, importer, exporter, parameter) => { var inputStream = importer.OpenStream <int>("Root"); var derivedStream = inputStream.Select(x => x *parameter).Write("DerivedStream", exporter); }, multiplier, "Partition_1", false, "DerivedStore", StorePath); // should have created a new store partition Assert.AreEqual(2, session.Partitions.Count); Assert.IsTrue(Store.Exists("OriginalStore", StorePath)); Assert.IsTrue(Store.Exists("DerivedStore", StorePath)); // verify partition metadata var originalPartition = session.Partitions[0] as StorePartition; Assert.AreEqual("Partition_0", originalPartition.Name); Assert.AreEqual("OriginalStore", originalPartition.StoreName); Assert.AreEqual(StorePath, originalPartition.StorePath); var derivedPartition = session.Partitions[1] as StorePartition; Assert.AreEqual("Partition_1", derivedPartition.Name); Assert.AreEqual("DerivedStore", derivedPartition.StoreName); Assert.AreEqual(StorePath, derivedPartition.StorePath); // collections to capture stream values var originalValues = new List <int>(); var originalTimes = new List <DateTime>(); var derivedValues = new List <int>(); var derivedTimes = new List <DateTime>(); // read stream values from the partitions using (var pipeline = Pipeline.Create()) { var originalPartitionImporter = Store.Open(pipeline, originalPartition.StoreName, originalPartition.StorePath); originalPartitionImporter.OpenStream <int>("Root").Do( (i, e) => { originalValues.Add(i); originalTimes.Add(e.OriginatingTime); }); var derivedPartitionImporter = Store.Open(pipeline, derivedPartition.StoreName, derivedPartition.StorePath); derivedPartitionImporter.OpenStream <int>("DerivedStream").Do( (i, e) => { derivedValues.Add(i); derivedTimes.Add(e.OriginatingTime); }); pipeline.Run(); } // verify that we read the data Assert.AreEqual(10, originalValues.Count); Assert.AreEqual(10, originalTimes.Count); Assert.AreEqual(10, derivedValues.Count); Assert.AreEqual(10, derivedTimes.Count); // verify values from both streams are what we expect CollectionAssert.AreEqual(originalValues.Select(x => x * multiplier).ToList(), derivedValues); CollectionAssert.AreEqual(originalTimes, derivedTimes); }
public void StartAudioRx(int recvPort, int codec) { Caps caps; string depayloaderName, decoderName; switch (codec) { case 0: depayloaderName = "rtppcmudepay"; decoderName = "mulawdec"; caps = Caps.FromString("application/x-rtp,clock-rate=8000,payload=0"); break; case 3: depayloaderName = "rtpgsmdepay"; decoderName = "gsmdec"; caps = Caps.FromString("application/x-rtp,clock-rate=8000,payload=3"); break; case 8: depayloaderName = "rtppcmadepay"; decoderName = "alawdec"; caps = Caps.FromString("application/x-rtp,clock-rate=8000,payload=8"); break; case 14: depayloaderName = "rtpmpadepay"; decoderName = "mad"; caps = Caps.FromString("application/x-rtp,media=(string)audio,clock-rate=(int)90000,encoding-name=(string)MPA,payload=(int)96"); break; default: depayloaderName = "rtppcmudepay"; decoderName = "mulawdec"; caps = Caps.FromString("application/x-rtp,clock-rate=8000,payload=0"); break; } _audioRxPipeline = new Pipeline("audiorx-pipeline"); Bin bin = (Bin)_audioRxPipeline; //bin.Bus.AddWatch(new BusFunc(BusCall)); _audioRxPipeline.Bus.AddSignalWatch(); _audioRxPipeline.Bus.Message += (o, args) => BusCall(args.Message); Element udpSrc = ElementFactory.Make("udpsrc", "udp_src"); Element depayloader = ElementFactory.Make(depayloaderName, depayloaderName); Element decoder = ElementFactory.Make(decoderName, decoderName); Element audioconvert = ElementFactory.Make("audioconvert", "audioconvert"); Element audioresample = ElementFactory.Make("audioresample", "audio_resample"); Element directsoundsink = ElementFactory.Make("directsoundsink", "directsoundsink"); if ((udpSrc == null) || (depayloader == null) || (decoder == null) || (audioconvert == null) || (audioresample == null) || (directsoundsink == null)) { MessageBox.Show("Error Creating Gstreamer Elements for Audio Rx pipeline!"); } else { udpSrc["port"] = recvPort; bin.Add(udpSrc, depayloader, decoder, audioconvert, audioresample, directsoundsink); if (!udpSrc.LinkFiltered(depayloader, caps)) { Console.WriteLine("link failed between camera_src and tee"); } if (!Element.Link(depayloader, decoder, audioconvert, audioresample, directsoundsink)) { Console.WriteLine("link failed between udp_src and directsoundsink"); } _audioRxPipeline.SetState(State.Playing); } }
public void SetCancelPipe(Pipeline cancel) { this.cancel = cancel; }
public MonoMacLinkContext(Pipeline pipeline, AssemblyResolver resolver) : base(pipeline, resolver) { }
/// <summary> /// Creates a new multi-stream JSON store and returns an <see cref="JsonExporter"/> instance which can be used to write streams to this store. /// </summary> /// <param name="pipeline">The <see cref="Pipeline"/> that owns the <see cref="JsonExporter"/>.</param> /// <param name="name">The name of the store to create.</param> /// <param name="rootPath">The path to use. If null, an in-memory store is created.</param> /// <param name="createSubdirectory">Indicates whether to create a numbered subdirectory for each execution of the pipeline.</param> /// <returns>An <see cref="JsonExporter"/> instance that can be used to write streams.</returns> public static JsonExporter Create(Pipeline pipeline, string name, string rootPath, bool createSubdirectory = true) { return(new JsonExporter(pipeline, name, rootPath, createSubdirectory)); }
/// <summary> /// Opens a multi-stream JSON store for read and returns an <see cref="JsonGenerator"/> instance which can be used to inspect the store and open the streams. /// </summary> /// <param name="pipeline">The <see cref="Pipeline"/> that owns the <see cref="JsonGenerator"/>.</param> /// <param name="name">The name of the application that generated the persisted files, or the root name of the files.</param> /// <param name="path">The directory in which the main persisted file resides.</param> /// <returns>A <see cref="JsonGenerator"/> instance that can be used to open streams and read messages.</returns> public static JsonGenerator Open(Pipeline pipeline, string name, string path) { return(new JsonGenerator(pipeline, name, path)); }
public void CloneAPipeline(bool revertAfterClone) { Pipeline p = new Pipeline(CatalogueRepository); var source = new PipelineComponent(CatalogueRepository, p, typeof(DelimitedFlatFileAttacher), 0); source.CreateArgumentsForClassIfNotExists <DelimitedFlatFileAttacher>(); var middle = new PipelineComponent(CatalogueRepository, p, typeof(ColumnRenamer), 1); middle.CreateArgumentsForClassIfNotExists <ColumnRenamer>(); var middle2 = new PipelineComponent(CatalogueRepository, p, typeof(ColumnForbidder), 1); middle2.CreateArgumentsForClassIfNotExists <ColumnForbidder>(); var destination = new PipelineComponent(CatalogueRepository, p, typeof(DataTableUploadDestination), 2); destination.CreateArgumentsForClassIfNotExists <DataTableUploadDestination>(); p.SourcePipelineComponent_ID = source.ID; p.DestinationPipelineComponent_ID = destination.ID; p.SaveToDatabase(); int componentsBefore = RepositoryLocator.CatalogueRepository.GetAllObjects <PipelineComponent>().Count(); int argumentsBefore = RepositoryLocator.CatalogueRepository.GetAllObjects <PipelineComponentArgument>().Count(); var arg = p.PipelineComponents.Single(c => c.Class == typeof(ColumnRenamer).ToString()).PipelineComponentArguments.Single(a => a.Name == "ColumnNameToFind"); arg.SetValue("MyMostCoolestColumnEver"); arg.SaveToDatabase(); //Execute the cloning process var p2 = p.Clone(); if (revertAfterClone) { p2.RevertToDatabaseState(); } Assert.AreNotEqual(p2, p); Assert.AreNotEqual(p2.ID, p.ID); Assert.AreEqual(p2.Name, p.Name + " (Clone)"); Assert.AreEqual(componentsBefore * 2, RepositoryLocator.CatalogueRepository.GetAllObjects <PipelineComponent>().Count()); Assert.AreEqual(argumentsBefore * 2, RepositoryLocator.CatalogueRepository.GetAllObjects <PipelineComponentArgument>().Count()); //p the original should have a pipeline component that has the value we set earlier Assert.AreEqual( p.PipelineComponents.Single(c => c.Class == typeof(ColumnRenamer).ToString()).PipelineComponentArguments.Single(a => a.Name == "ColumnNameToFind").Value, "MyMostCoolestColumnEver" ); //p2 the clone should have a pipeline component too since it's a clone Assert.AreEqual( p2.PipelineComponents.Single(c => c.Class == typeof(ColumnRenamer).ToString()).PipelineComponentArguments.Single(a => a.Name == "ColumnNameToFind").Value, "MyMostCoolestColumnEver" ); //both should have source and destination components Assert.NotNull(p2.DestinationPipelineComponent_ID); Assert.NotNull(p2.SourcePipelineComponent_ID); //but with different IDs because they are clones Assert.AreNotEqual(p.DestinationPipelineComponent_ID, p2.DestinationPipelineComponent_ID); Assert.AreNotEqual(p.SourcePipelineComponent_ID, p2.SourcePipelineComponent_ID); p.DeleteInDatabase(); p2.DeleteInDatabase(); }
public void SetPipeline(Pipeline pipeline) { }
protected override void CreateResources(ResourceFactory factory) { _instanceCount = 8000u; _camera.Position = new Vector3(-36f, 20f, 100f); _camera.Pitch = -0.3f; _camera.Yaw = 0.1f; _cameraProjViewBuffer = factory.CreateBuffer( new BufferDescription((uint)(Unsafe.SizeOf <Matrix4x4>() * 2), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightInfoBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _rotationInfoBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _lightDir = Vector3.Normalize(new Vector3(0.3f, -0.75f, -0.3f)); VertexLayoutDescription sharedVertexLayout = new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)); bool etc2Supported = GraphicsDevice.GetPixelFormatSupport( PixelFormat.ETC2_R8_G8_B8_UNorm, TextureType.Texture2D, TextureUsage.Sampled); PixelFormat pixelFormat = etc2Supported ? PixelFormat.ETC2_R8_G8_B8_UNorm : PixelFormat.BC3_UNorm; byte[] rockTextureData = LoadEmbeddedAsset <byte[]>( etc2Supported ? "texturearray_rocks_etc2_unorm.binary" : "texturearray_rocks_bc3_unorm.binary"); Texture rockTexture = KtxFile.LoadTexture( GraphicsDevice, ResourceFactory, rockTextureData, pixelFormat); TextureView rockTextureView = ResourceFactory.CreateTextureView(rockTexture); ResourceLayoutElementDescription[] resourceLayoutElementDescriptions = { new ResourceLayoutElementDescription("LightInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment), new ResourceLayoutElementDescription("ProjView", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("RotationInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex), }; ResourceLayoutDescription resourceLayoutDescription = new ResourceLayoutDescription(resourceLayoutElementDescriptions); ResourceLayout sharedLayout = factory.CreateResourceLayout(resourceLayoutDescription); ResourceLayoutElementDescription[] textureLayoutDescriptions = { new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("Samp", ResourceKind.Sampler, ShaderStages.Fragment) }; ResourceLayout textureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(textureLayoutDescriptions)); BindableResource[] bindableResources = new BindableResource[] { _lightInfoBuffer, _cameraProjViewBuffer, _rotationInfoBuffer }; ResourceSetDescription resourceSetDescription = new ResourceSetDescription(sharedLayout, bindableResources); _sharedResourceSet = factory.CreateResourceSet(resourceSetDescription); BindableResource[] instanceBindableResources = { rockTextureView, GraphicsDevice.LinearSampler }; _instanceTextureSet = factory.CreateResourceSet(new ResourceSetDescription(textureLayout, instanceBindableResources)); ProcessedModel rock = LoadEmbeddedAsset <ProcessedModel>("rock01.binary"); _rockModel = rock.MeshParts[0].CreateDeviceResources(GraphicsDevice, ResourceFactory); VertexLayoutDescription vertexLayoutPerInstance = new VertexLayoutDescription( new VertexElementDescription("InstancePosition", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("InstanceRotation", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("InstanceScale", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("InstanceTexArrayIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Int1)); vertexLayoutPerInstance.InstanceStepRate = 1; _instanceVB = ResourceFactory.CreateBuffer(new BufferDescription(InstanceInfo.Size * _instanceCount, BufferUsage.VertexBuffer)); InstanceInfo[] infos = new InstanceInfo[_instanceCount]; Random r = new Random(); float orbitDistance = 50f; for (uint i = 0; i < _instanceCount / 2; i++) { float angle = (float)(r.NextDouble() * Math.PI * 2); infos[i] = new InstanceInfo( new Vector3( ((float)Math.Cos(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20), (float)(-1.5 + r.NextDouble() * 3), ((float)Math.Sin(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20)), new Vector3( (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2)), new Vector3((float)(0.65 + r.NextDouble() * 0.35)), r.Next(0, (int)rockTexture.ArrayLayers)); } orbitDistance = 100f; for (uint i = _instanceCount / 2; i < _instanceCount; i++) { float angle = (float)(r.NextDouble() * Math.PI * 2); infos[i] = new InstanceInfo( new Vector3( ((float)Math.Cos(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20), (float)(-1.5 + r.NextDouble() * 3), ((float)Math.Sin(angle) * orbitDistance) + (float)(-10 + r.NextDouble() * 20)), new Vector3( (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2), (float)(r.NextDouble() * Math.PI * 2)), new Vector3((float)(0.65 + r.NextDouble() * 0.35)), r.Next(0, (int)rockTexture.ArrayLayers)); } GraphicsDevice.UpdateBuffer(_instanceVB, 0, infos); GraphicsPipelineDescription pipelineDescription = new GraphicsPipelineDescription() { BlendState = BlendStateDescription.SingleOverrideBlend, DepthStencilState = new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false ), PrimitiveTopology = PrimitiveTopology.TriangleList, ResourceLayouts = new ResourceLayout[] { sharedLayout, textureLayout }, ShaderSet = new ShaderSetDescription( // The ordering of layouts directly impacts shader layout schemes vertexLayouts: new VertexLayoutDescription[] { sharedVertexLayout, vertexLayoutPerInstance }, shaders: LoadShaders("Instance") ), Outputs = MainSwapchain.Framebuffer.OutputDescription }; _instancePipeline = factory.CreateGraphicsPipeline(pipelineDescription); // Create planet Pipeline // Almost everything is the same as the rock Pipeline, // except no instance vertex buffer is needed, and different shaders are used. pipelineDescription.ShaderSet = new ShaderSetDescription( new[] { sharedVertexLayout }, LoadShaders("Planet")); _planetPipeline = ResourceFactory.CreateGraphicsPipeline(pipelineDescription); ProcessedModel planet = LoadEmbeddedAsset <ProcessedModel>("sphere.binary"); _planetModel = planet.MeshParts[0].CreateDeviceResources(GraphicsDevice, ResourceFactory); byte[] planetTexData = LoadEmbeddedAsset <byte[]>( etc2Supported ? "lavaplanet_etc2_unorm.binary" : "lavaplanet_bc3_unorm.binary"); Texture planetTexture = KtxFile.LoadTexture(GraphicsDevice, ResourceFactory, planetTexData, pixelFormat); TextureView planetTextureView = ResourceFactory.CreateTextureView(planetTexture); _planetTextureSet = ResourceFactory.CreateResourceSet(new ResourceSetDescription(textureLayout, planetTextureView, GraphicsDevice.Aniso4xSampler)); // Starfield resources ResourceLayout invCameraInfoLayout = ResourceFactory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("InvCameraInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment))); _viewInfoBuffer = ResourceFactory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <MatrixPair>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); _viewInfoSet = ResourceFactory.CreateResourceSet(new ResourceSetDescription(invCameraInfoLayout, _viewInfoBuffer)); ShaderSetDescription starfieldShaders = new ShaderSetDescription( Array.Empty <VertexLayoutDescription>(), LoadShaders("Starfield")); _starfieldPipeline = ResourceFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription( BlendStateDescription.SingleOverrideBlend, DepthStencilStateDescription.Disabled, RasterizerStateDescription.CullNone, PrimitiveTopology.TriangleList, starfieldShaders, new[] { invCameraInfoLayout }, MainSwapchain.Framebuffer.OutputDescription)); _commandList = factory.CreateCommandList(); }
/// <summary> /// Executes a PSCommand against the session's runspace and returns /// a collection of results of the expected type. /// </summary> /// <typeparam name="TResult">The expected result type.</typeparam> /// <param name="psCommand">The PSCommand to be executed.</param> /// <param name="sendOutputToHost"> /// If true, causes any output written during command execution to be written to the host. /// </param> /// <returns> /// An awaitable Task which will provide results once the command /// execution completes. /// </returns> public async Task <IEnumerable <TResult> > ExecuteCommand <TResult>( PSCommand psCommand, bool sendOutputToHost = false) { // If the debugger is active and the caller isn't on the pipeline // thread, send the command over to that thread to be executed. if (Thread.CurrentThread.ManagedThreadId != this.pipelineThreadId && this.pipelineExecutionTask != null) { Logger.Write(LogLevel.Verbose, "Passing command execution to pipeline thread."); PipelineExecutionRequest <TResult> executionRequest = new PipelineExecutionRequest <TResult>( this, psCommand, sendOutputToHost); // Send the pipeline execution request to the pipeline thread this.pipelineResultTask = new TaskCompletionSource <IPipelineExecutionRequest>(); this.pipelineExecutionTask.SetResult(executionRequest); await this.pipelineResultTask.Task; return(executionRequest.Results); } else { try { // Instruct PowerShell to send output and errors to the host if (sendOutputToHost) { psCommand.Commands[0].MergeMyResults( PipelineResultTypes.Error, PipelineResultTypes.Output); psCommand.Commands.Add( this.GetOutputCommand( endOfStatement: false)); } if (this.currentRunspace.RunspaceAvailability == RunspaceAvailability.AvailableForNestedCommand || this.debuggerStoppedTask != null) { Logger.Write( LogLevel.Verbose, string.Format( "Attempting to execute nested pipeline command(s):\r\n\r\n{0}", GetStringForPSCommand(psCommand))); using (Pipeline pipeline = this.currentRunspace.CreateNestedPipeline()) { foreach (var command in psCommand.Commands) { pipeline.Commands.Add(command); } IEnumerable <TResult> result = pipeline .Invoke() .Select(pso => pso.BaseObject) .Cast <TResult>(); return(result); } } else { Logger.Write( LogLevel.Verbose, string.Format( "Attempting to execute command(s):\r\n\r\n{0}", GetStringForPSCommand(psCommand))); // Set the runspace var runspaceHandle = await this.GetRunspaceHandle(); if (runspaceHandle.Runspace.RunspaceAvailability != RunspaceAvailability.AvailableForNestedCommand) { this.powerShell.Runspace = runspaceHandle.Runspace; } // Invoke the pipeline on a background thread // TODO: Use built-in async invocation! var taskResult = await Task.Factory.StartNew <IEnumerable <TResult> >( () => { this.powerShell.Commands = psCommand; Collection <TResult> result = this.powerShell.Invoke <TResult>(); return(result); }, CancellationToken.None, // Might need a cancellation token TaskCreationOptions.None, TaskScheduler.Default ); runspaceHandle.Dispose(); if (this.powerShell.HadErrors) { // TODO: Find a good way to extract errors! Logger.Write( LogLevel.Error, "Execution completed with errors."); } else { Logger.Write( LogLevel.Verbose, "Execution completed successfully."); } bool hadErrors = this.powerShell.HadErrors; return(taskResult); } } catch (RuntimeException e) { // TODO: Return an error Logger.Write( LogLevel.Error, "Exception occurred while attempting to execute command:\r\n\r\n" + e.ToString()); } } // TODO: Better result return(null); }
/// <summary> /// Internal proxy for EnterNestedPrompt /// </summary> /// <param name="callingCommand"></param> internal void EnterNestedPrompt(InternalCommand callingCommand) { // Ensure we are in control of the pipeline LocalRunspace localRunspace = null; // This needs to be in a try / catch, since the LocalRunspace cast // tries to verify that the host supports interactive sessions. // Tests hosts do not. try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException) { } if (localRunspace != null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline != null) && (currentlyRunningPipeline == localRunspace.PulsePipeline)) { throw new InvalidOperationException(); } } // NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it // should include setting a bit that indicates that the initialization is complete, and code should be // added here to throw an exception if this function is called before that bit is set. if (NestedPromptCount < 0) { Dbg.Assert(false, "nested prompt counter should never be negative."); throw PSTraceSource.NewInvalidOperationException( InternalHostStrings.EnterExitNestedPromptOutOfSync); } // Increment our nesting counter. When we set the value of the variable, we will replace any existing variable // of the same name. This is good, as any existing value is either 1) ours, and we have claim to replace it, or // 2) is a squatter, and we have claim to clobber it. ++NestedPromptCount; Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount); // On entering a subshell, save and reset values of certain bits of session state PromptContextData contextData = new PromptContextData(); contextData.SavedContextData = Context.SaveContextData(); contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath); contextData.SavedPSBoundParametersVarValue = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath); contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability; contextData.LanguageMode = Context.LanguageMode; PSPropertyInfo commandInfoProperty = null; PSPropertyInfo stackTraceProperty = null; object oldCommandInfo = null; object oldStackTrace = null; if (callingCommand != null) { Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match"); // Populate $CurrentlyExecutingCommand to facilitate debugging. One of the gotchas is that we are going to want // to expose more and more debug info. We could just populate more and more local variables but that is probably // a lousy approach as it pollutes the namespace. A better way to do it is to add NOTES to the variable value // object. PSObject newValue = PSObject.AsPSObject(callingCommand); commandInfoProperty = newValue.Properties["CommandInfo"]; if (commandInfoProperty == null) { newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo)); } else { oldCommandInfo = commandInfoProperty.Value; commandInfoProperty.Value = callingCommand.CommandInfo; } stackTraceProperty = newValue.Properties["StackTrace"]; if (stackTraceProperty == null) { newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace())); } else { oldStackTrace = stackTraceProperty.Value; stackTraceProperty.Value = new System.Diagnostics.StackTrace(); } Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue); } _contextStack.Push(contextData); Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count"); Context.PSDebugTraceStep = false; Context.PSDebugTraceLevel = 0; Context.ResetShellFunctionErrorOutputPipe(); // Lock down the language in the nested prompt if (Context.HasRunspaceEverUsedConstrainedLanguageMode) { Context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true); try { _externalHostRef.Value.EnterNestedPrompt(); } catch { // So where things really go south is this path; which is possible for hosts (like our ConsoleHost) // that don't return from EnterNestedPrompt immediately. // EnterNestedPrompt() starts // ExitNestedPrompt() called // EnterNestedPrompt throws ExitNestedPromptHelper(); throw; } finally { if (commandInfoProperty != null) { commandInfoProperty.Value = oldCommandInfo; } if (stackTraceProperty != null) { stackTraceProperty.Value = oldStackTrace; } } Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0"); }
/// <summary> /// Generate LogContext structure based on executionContext and invocationInfo passed in. /// /// LogContext structure is used in log provider interface. /// </summary> /// <param name="executionContext"></param> /// <param name="invocationInfo"></param> /// <param name="severity"></param> /// <returns></returns> private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) { if (executionContext == null) { return(null); } LogContext logContext = new LogContext(); string shellId = executionContext.ShellID; logContext.ExecutionContext = executionContext; logContext.ShellId = shellId; logContext.Severity = severity.ToString(); if (executionContext.EngineHostInterface != null) { logContext.HostName = executionContext.EngineHostInterface.Name; logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString(); logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString(); } logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs()); if (executionContext.CurrentRunspace != null) { logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString(); logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString(); Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline(); if (currentPipeline != null) { logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture); } } logContext.SequenceNumber = NextSequenceNumber; try { if (executionContext.LogContextCache.User == null) { logContext.User = Environment.UserDomainName + "\\" + Environment.UserName; executionContext.LogContextCache.User = logContext.User; } else { logContext.User = executionContext.LogContextCache.User; } } catch (InvalidOperationException) { logContext.User = Logging.UnknownUserName; } System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; if (psSenderInfo != null) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture); if (invocationInfo == null) { return(logContext); } logContext.ScriptName = invocationInfo.ScriptName; logContext.CommandLine = invocationInfo.Line; if (invocationInfo.MyCommand != null) { logContext.CommandName = invocationInfo.MyCommand.Name; logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString(); switch (invocationInfo.MyCommand.CommandType) { case CommandTypes.Application: logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path; break; case CommandTypes.ExternalScript: logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path; break; } } return(logContext); }
/// <summary> /// Initializes a new instance of the <see cref="FrequencyDomainEnergy"/> class. /// </summary> /// <param name="pipeline">The pipeline to add the component to.</param> /// <param name="start">The starting frequency of the band.</param> /// <param name="end">The ending frequency of the band.</param> /// <param name="name">An optional name for this component.</param> public FrequencyDomainEnergy(Pipeline pipeline, int start, int end, string name = nameof(FrequencyDomainEnergy)) : base(pipeline, name) { this.start = start; this.end = end; }
static Pipeline CreatePipeline(LinkerOptions options) { var pipeline = new Pipeline(); pipeline.AppendStep(options.LinkMode == LinkMode.None ? new LoadOptionalReferencesStep() : new LoadReferencesStep()); if (options.I18nAssemblies != I18nAssemblies.None) { pipeline.AppendStep(new LoadI18nAssemblies(options.I18nAssemblies)); } // that must be done early since the XML files can "add" new assemblies [#15878] // and some of the assemblies might be (directly or referenced) SDK assemblies foreach (string definition in options.ExtraDefinitions) { pipeline.AppendStep(GetResolveStep(definition)); } if (options.LinkMode != LinkMode.None) { pipeline.AppendStep(new BlacklistStep()); } pipeline.AppendStep(new CustomizeMacActions(options.LinkMode, options.SkippedAssemblies)); // We need to store the Field attribute in annotations, since it may end up removed. pipeline.AppendStep(new ProcessExportedFields()); if (options.LinkMode != LinkMode.None) { pipeline.AppendStep(new CoreTypeMapStep()); var subdispatcher = new SubStepDispatcher { new ApplyPreserveAttribute(), new OptimizeGeneratedCodeSubStep(options), new RemoveUserResourcesSubStep(), new CoreRemoveAttributes(), new CoreHttpMessageHandler(options), new MarkNSObjects(), }; // CoreRemoveSecurity can modify non-linked assemblies // but the conditions for this cannot happen if only the platform assembly is linked if (options.LinkMode != LinkMode.Platform) { subdispatcher.Add(new CoreRemoveSecurity()); } pipeline.AppendStep(subdispatcher); pipeline.AppendStep(new MonoMacPreserveCode(options)); pipeline.AppendStep(new PreserveCrypto()); pipeline.AppendStep(new MonoMacMarkStep()); pipeline.AppendStep(new MacRemoveResources(options)); pipeline.AppendStep(new CoreSweepStep(options.LinkSymbols)); pipeline.AppendStep(new CleanStep()); pipeline.AppendStep(new MonoMacNamespaces()); pipeline.AppendStep(new RemoveSelectors()); pipeline.AppendStep(new RegenerateGuidStep()); } else { SubStepDispatcher sub = new SubStepDispatcher() { new RemoveUserResourcesSubStep() }; pipeline.AppendStep(sub); } pipeline.AppendStep(new ListExportedSymbols(options.MarshalNativeExceptionsState, options.SkipExportedSymbolsInSdkAssemblies)); pipeline.AppendStep(new OutputStep()); return(pipeline); }
public void StartAudioTx(string destIP, int destPort, int codec) { string encoderName, payloaderName; switch (codec) { case 0: encoderName = "mulawenc"; payloaderName = "rtppcmupay"; break; case 3: encoderName = "gsmenc"; payloaderName = "rtpgsmpay"; break; case 8: encoderName = "alawenc"; payloaderName = "rtppcmapay"; break; case 14: encoderName = "ffenc_mp2"; payloaderName = "rtpmpapay"; break; default: encoderName = "mulawenc"; payloaderName = "rtppcmupay"; break; } _audioTxPipeline = new Pipeline("audiotx-pipeline"); Bin bin = (Bin)_audioTxPipeline; //bin.Bus.AddWatch(new BusFunc(BusCall)); _audioTxPipeline.Bus.AddSignalWatch(); _audioTxPipeline.Bus.Message += (o, args) => BusCall(args.Message); //ds_src = ElementFactory.Make("dshowaudiosrc", "dshow-audio-in"); Element dsSrc = ElementFactory.Make("audiotestsrc", "dshow-audio-in"); Element audioConvert = ElementFactory.Make("audioconvert", "audio_convert"); Element audioResample = ElementFactory.Make("audioresample", "audio_resample"); Element encoder = ElementFactory.Make(encoderName, encoderName); Element payloader = ElementFactory.Make(payloaderName, payloaderName); Element udpSink = ElementFactory.Make("udpsink", "udp_sink"); if ((dsSrc == null) || (audioConvert == null) || (audioResample == null) || (encoder == null) || (payloader == null) || (udpSink == null)) { MessageBox.Show("Error Creating Gstreamer Elements for Audio Tx pipeline!"); } else { udpSink["host"] = destIP; udpSink["port"] = destPort; bin.Add(dsSrc, audioConvert, audioResample, encoder, payloader, udpSink); if (!Element.Link(dsSrc, audioConvert, audioResample, encoder, payloader, udpSink)) { Console.WriteLine("link failed between ds_src and udp_sink"); } _audioTxPipeline.SetState(State.Playing); } }
/// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async System.Threading.Tasks.Task ProcessRecordAsync() { using ( NoSynchronizationContext ) { if (this.SkipSSL.ToBool()) { Pipeline = Nutanix.Powershell.Module.Instance.CreatePipelineWithProxy(this.MyInvocation.BoundParameters); } else { Pipeline = Nutanix.Powershell.Module.Instance.CreatePipeline(this.MyInvocation.BoundParameters); } await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletGetPipeline); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested) { return; } Pipeline.Prepend(HttpPipelinePrepend); Pipeline.Append(HttpPipelineAppend); if (Credential == null) { if (Port == null) { Port = System.Environment.GetEnvironmentVariable("NutanixPort") ?? "9440"; } if (Protocol == null) { Protocol = System.Environment.GetEnvironmentVariable("NutanixProtocol") ?? "https"; } if (Server == null) { Server = System.Environment.GetEnvironmentVariable("NutanixServer") ?? "localhost"; } if (Username == null) { Username = System.Environment.GetEnvironmentVariable("NutanixUsername") ?? ""; } if (Password == null) { var psw = System.Environment.GetEnvironmentVariable("NutanixPassword") ?? ""; System.Security.SecureString result = new System.Security.SecureString(); foreach (char c in psw) { result.AppendChar(c); } Password = result; } //build url var url = $"{Protocol}://{Server}:{Port}"; Credential = new Nutanix.Powershell.Models.NutanixCredential(url, Username, Password); } Body.Metadata = new Nutanix.Powershell.Models.VmMetadata(); Body.Metadata.Kind = "vm"; // get the client instance await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletBeforeAPICall); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested) { return; } if (this.Async.ToBool()) { await this.Client.NewVm(Body, onAccepted, onDefault, this, Pipeline, Credential); } else { await this.Client.NewVm_Sync(Body, onAccepted, onDefault, onOK, onNotFound, this, Pipeline, Credential); } await((Microsoft.Rest.ClientRuntime.IEventListener) this).Signal(Microsoft.Rest.ClientRuntime.Events.CmdletAfterAPICall); if (((Microsoft.Rest.ClientRuntime.IEventListener) this).Token.IsCancellationRequested) { return; } } }
static Pipeline CreatePipeline(LinkerOptions options) { var pipeline = new Pipeline(); pipeline.AppendStep(new LoadReferencesStep()); if (options.I18nAssemblies != I18nAssemblies.None) { pipeline.AppendStep(new LoadI18nAssemblies(options.I18nAssemblies)); } // that must be done early since the XML files can "add" new assemblies [#15878] // and some of the assemblies might be (directly or referenced) SDK assemblies foreach (string definition in options.ExtraDefinitions) { pipeline.AppendStep(GetResolveStep(definition)); } if (options.LinkMode != LinkMode.None) { pipeline.AppendStep(new BlacklistStep()); } pipeline.AppendStep(new CustomizeMacActions(options.LinkMode, options.SkippedAssemblies)); // We need to store the Field attribute in annotations, since it may end up removed. pipeline.AppendStep(new ProcessExportedFields()); if (options.LinkMode != LinkMode.None) { pipeline.AppendStep(new TypeMapStep()); pipeline.AppendStep(new SubStepDispatcher { new ApplyPreserveAttribute(), new CoreRemoveSecurity(), new OptimizeGeneratedCodeSubStep(options.EnsureUIThread), new CoreRemoveAttributes(), new CoreHttpMessageHandler(options), new CoreTlsProviderStep(options), new MarkNSObjects(), }); pipeline.AppendStep(new MonoMacPreserveCode(options)); pipeline.AppendStep(new PreserveCrypto()); pipeline.AppendStep(new MonoMacMarkStep()); pipeline.AppendStep(new MacRemoveResources(options)); pipeline.AppendStep(new MobileSweepStep()); pipeline.AppendStep(new CleanStep()); pipeline.AppendStep(new MonoMacNamespaces()); pipeline.AppendStep(new RemoveSelectors()); pipeline.AppendStep(new RegenerateGuidStep()); } pipeline.AppendStep(new ListExportedSymbols()); pipeline.AppendStep(new OutputStep()); return(pipeline); }
public void SingleTask_CanBeRunMultipleTimes() { Pipeline.Run(SingleTaskScript); Pipeline.Run(SingleTaskScript); _mockCalls.Verify(m => m.Call("TestValue"), Times.Exactly(2)); }
// Stream function to Send datas to Unity public static void Stream(Pipeline pipeline) { Processing(pipeline, StreamFrame); }
public SpyExtension(Pipeline builder, Stage stage) { PipelineBuilder = builder; this._stage = stage; }
// Debug function to Visualise video depth as ascii public static void AsciiDepth(Pipeline pipeline) { Processing(pipeline, AsciiDepthFrame); }
/// <summary> /// Initializes a new instance of the <see cref="Timer"/> class. /// The timer fires off messages at the rate specified by timerInterval. /// </summary> /// <param name="pipeline">The pipeline this component will be part of.</param> /// <param name="timerInterval">The timer firing interval, in ms.</param> public Timer(Pipeline pipeline, uint timerInterval) { this.pipeline = pipeline; this.timerInterval = TimeSpan.FromMilliseconds(timerInterval); }
public Pipeline CreatePipeline(VertexLayout vertexLayout, Shader vertexShader, Shader fragmentShader, bool required, string memo) { //if the shaders arent available, the pipeline isn't either if (!vertexShader.Available || !fragmentShader.Available) { string errors = $"Vertex Shader:\r\n {vertexShader.Errors} \r\n-------\r\nFragment Shader:\r\n{fragmentShader.Errors}"; if (required) { throw new InvalidOperationException($"Couldn't build required GL pipeline:\r\n{errors}"); } var pipeline = new Pipeline(this, null, false, null, null, null); pipeline.Errors = errors; return(pipeline); } bool success = true; var vsw = vertexShader.Opaque as ShaderWrapper; var fsw = fragmentShader.Opaque as ShaderWrapper; var sws = new[] { vsw, fsw }; bool mapVariables = vsw.MapCodeToNative != null || fsw.MapCodeToNative != null; ErrorCode errcode; int pid = GL.CreateProgram(); GL.AttachShader(pid, vsw.sid); errcode = GL.GetError(); GL.AttachShader(pid, fsw.sid); errcode = GL.GetError(); //NOT BEING USED NOW: USING SEMANTICS INSTEAD ////bind the attribute locations from the vertex layout ////as we go, look for attribute mappings (CGC will happily reorder and rename our attribute mappings) ////what's more it will _RESIZE_ them but this seems benign..somehow.. ////WELLLLLLL we wish we could do that by names ////but the shaders dont seem to be adequate quality (oddly named attributes.. texCoord vs texCoord1). need to use semantics instead. //foreach (var kvp in vertexLayout.Items) //{ // string name = kvp.Value.Name; // //if (mapVariables) // //{ // // foreach (var sw in sws) // // { // // if (sw.MapNativeToCode.ContainsKey(name)) // // { // // name = sw.MapNativeToCode[name]; // // break; // // } // // } // //} // if(mapVariables) { // ////proxy for came-from-cgc // //switch (kvp.Value.Usage) // //{ // // case AttributeUsage.Position: // //} // } // //GL.BindAttribLocation(pid, kvp.Key, name); //} GL.LinkProgram(pid); errcode = GL.GetError(); string resultLog = GL.GetProgramInfoLog(pid); if (errcode != ErrorCode.NoError) { if (required) { throw new InvalidOperationException($"Error creating pipeline (error returned from glLinkProgram): {errcode}\r\n\r\n{resultLog}"); } else { success = false; } } int linkStatus; GL.GetProgram(pid, GetProgramParameterName.LinkStatus, out linkStatus); if (linkStatus == 0) { if (required) { throw new InvalidOperationException($"Error creating pipeline (link status false returned from glLinkProgram): \r\n\r\n{resultLog}"); } else { success = false; } } //need to work on validation. apparently there are some weird caveats to glValidate which make it complicated and possibly excuses (barely) the intel drivers' dysfunctional operation //"A sampler points to a texture unit used by fixed function with an incompatible target" // //info: //http://www.opengl.org/sdk/docs/man/xhtml/glValidateProgram.xml //This function mimics the validation operation that OpenGL implementations must perform when rendering commands are issued while programmable shaders are part of current state. //glValidateProgram checks to see whether the executables contained in program can execute given the current OpenGL state //This function is typically useful only during application development. // //So, this is no big deal. we shouldnt be calling validate right now anyway. //conclusion: glValidate is very complicated and is of virtually no use unless your draw calls are returning errors and you want to know why //GL.ValidateProgram(pid); //errcode = GL.GetError(); //resultLog = GL.GetProgramInfoLog(pid); //if (errcode != ErrorCode.NoError) // throw new InvalidOperationException($"Error creating pipeline (error returned from glValidateProgram): {errcode}\r\n\r\n{resultLog}"); //int validateStatus; //GL.GetProgram(pid, GetProgramParameterName.ValidateStatus, out validateStatus); //if (validateStatus == 0) // throw new InvalidOperationException($"Error creating pipeline (validateStatus status false returned from glValidateProgram): \r\n\r\n{resultLog}"); //set the program to active, in case we need to set sampler uniforms on it GL.UseProgram(pid); //get all the attributes (not needed) List <AttributeInfo> attributes = new List <AttributeInfo>(); int nAttributes; GL.GetProgram(pid, GetProgramParameterName.ActiveAttributes, out nAttributes); for (int i = 0; i < nAttributes; i++) { int size, length; string name = new System.Text.StringBuilder(1024).ToString(); ActiveAttribType type; GL.GetActiveAttrib(pid, i, 1024, out length, out size, out type, out name); attributes.Add(new AttributeInfo() { Handle = new IntPtr(i), Name = name }); } //get all the uniforms List <UniformInfo> uniforms = new List <UniformInfo>(); int nUniforms; GL.GetProgram(pid, GetProgramParameterName.ActiveUniforms, out nUniforms); List <int> samplers = new List <int>(); for (int i = 0; i < nUniforms; i++) { int size, length; ActiveUniformType type; string name = new System.Text.StringBuilder(1024).ToString(); GL.GetActiveUniform(pid, i, 1024, out length, out size, out type, out name); errcode = GL.GetError(); int loc = GL.GetUniformLocation(pid, name); //translate name if appropriate //not sure how effective this approach will be, due to confusion of vertex and fragment uniforms if (mapVariables) { if (vsw.MapCodeToNative.ContainsKey(name)) { name = vsw.MapCodeToNative[name]; } if (fsw.MapCodeToNative.ContainsKey(name)) { name = fsw.MapCodeToNative[name]; } } var ui = new UniformInfo(); ui.Name = name; ui.Opaque = loc; if (type == ActiveUniformType.Sampler2D) { ui.IsSampler = true; ui.SamplerIndex = samplers.Count; ui.Opaque = loc | (samplers.Count << 24); samplers.Add(loc); } uniforms.Add(ui); } //deactivate the program, so we dont accidentally use it GL.UseProgram(0); if (!vertexShader.Available) { success = false; } if (!fragmentShader.Available) { success = false; } var pw = new PipelineWrapper() { pid = pid, VertexShader = vertexShader, FragmentShader = fragmentShader, SamplerLocs = samplers }; return(new Pipeline(this, pw, success, vertexLayout, uniforms, memo)); }
public void SingleTask_RunsToSuccess_IfConfiguredCorrectly() { Pipeline.Run(SingleTaskScript); _mockCalls.Verify(m => m.Call("TestValue"), Times.Once); }
/// <summary> /// Encodes an instanced draw with all the information needed to batch the calls. For best results, /// draws should be presorted into batches before submission. /// </summary> /// <param name="args">Indexed draw parameters</param> /// <param name="p">The pipeline to use with rendering</param> /// <param name="instanceData">Per instance data resource set</param> /// <param name="indexf">Format of the indices (16 or 32-bit)</param> public void AddDraw(ref IndirectDrawIndexedArgumentsPacked args, int buffer, Pipeline p, ResourceSet instanceData, IndexFormat indexf) { // Encode the draw if (_indirectDrawCount[_stagingSet] >= _indirectStagingBuffer.Length) { throw new Exception("Indirect buffer not large enough for draw"); } if (p == null) { throw new Exception("Pipeline is null"); } if (buffer == -1) { throw new Exception("Invalid buffer index"); } _indirectStagingBuffer[_indirectDrawCount[_stagingSet]] = args; _indirectDrawCount[_stagingSet]++; // Determine if we need a new batch if (_batchCount[_stagingSet] == 0 || _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet] - 1]._pipeline != p || _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet] - 1]._objectRS != instanceData || _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet] - 1]._indexFormat != indexf || _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet] - 1]._bufferIndex != buffer) { if (_batchCount[_stagingSet] >= MAX_BATCH) { //throw new Exception("Batch count is not large enough"); return; // Drop the batch for now } // Add a new batch _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet]]._bufferIndex = buffer; _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet]]._pipeline = p; _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet]]._objectRS = instanceData; _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet]]._indexFormat = indexf; _batches[MAX_BATCH * _stagingSet + _batchCount[_stagingSet]]._batchStart = _indirectDrawCount[_stagingSet] - 1; _batchCount[_stagingSet]++; } }
/// <summary> /// Opens a session importer. /// </summary> /// <param name="pipeline">Pipeline to use for imports.</param> /// <param name="session">Session to import into.</param> /// <returns>The newly created session importer.</returns> public static SessionImporter Open(Pipeline pipeline, Session session) { return(new SessionImporter(pipeline, session)); }