public override void MouseDown(NSEvent aEvent) { if (iEnabled) { // get current mouse position iMouseDown = MouseLocation(aEvent.LocationInWindow); UpdateState(); if (iMouseDown == EMouse.eLeft || iMouseDown == EMouse.eRight) { // send notification that "rotation" has started if (EventStart != null) { EventStart(this, EventArgs.Empty); } // do a step now and then set a timer for repeat DoStep(); // use a fixed delay of 0.25 for the first delay this.PerformSelectorWithObjectAfterDelay(ObjectiveCRuntime.Selector("timerUpdate"), null, 0.25); } } }
public override void Dispose() { if (!_disposed) { if (RenderPipelineState.NativePtr != IntPtr.Zero) { ObjectiveCRuntime.release(RenderPipelineState.NativePtr); } else { Debug.Assert(ComputePipelineState.NativePtr != IntPtr.Zero); ObjectiveCRuntime.release(ComputePipelineState.NativePtr); } if (_specializedFunctions != null) { foreach (MTLFunction function in _specializedFunctions) { ObjectiveCRuntime.release(function.NativePtr); } _specializedFunctions.Clear(); } _disposed = true; } }
private static bool GetIsSupported() { bool result = false; try { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { if (RuntimeInformation.OSDescription.Contains("Darwin")) { NSArray allDevices = MTLDevice.MTLCopyAllDevices(); result |= (ulong)allDevices.count > 0; ObjectiveCRuntime.release(allDevices.NativePtr); } else { MTLDevice defaultDevice = MTLDevice.MTLCreateSystemDefaultDevice(); if (defaultDevice.NativePtr != IntPtr.Zero) { result = true; ObjectiveCRuntime.release(defaultDevice.NativePtr); } } } } catch { result = false; } return(result); }
internal MTLComputePipelineState GetUnalignedBufferCopyPipeline() { lock (_unalignedBufferCopyPipelineLock) { if (_unalignedBufferCopyPipeline.IsNull) { MTLComputePipelineDescriptor descriptor = MTLUtil.AllocInit <MTLComputePipelineDescriptor>( nameof(MTLComputePipelineDescriptor)); MTLPipelineBufferDescriptor buffer0 = descriptor.buffers[0]; buffer0.mutability = MTLMutability.Mutable; MTLPipelineBufferDescriptor buffer1 = descriptor.buffers[1]; buffer0.mutability = MTLMutability.Mutable; Debug.Assert(_unalignedBufferCopyShader == null); string name = MetalFeatures.IsMacOS ? UnalignedBufferCopyPipelineMacOSName : UnalignedBufferCopyPipelineiOSName; using (Stream resourceStream = typeof(MTLGraphicsDevice).Assembly.GetManifestResourceStream(name)) { byte[] data = new byte[resourceStream.Length]; using (MemoryStream ms = new MemoryStream(data)) { resourceStream.CopyTo(ms); ShaderDescription shaderDesc = new ShaderDescription(ShaderStages.Compute, data, "copy_bytes"); _unalignedBufferCopyShader = new MTLShader(ref shaderDesc, this); } } descriptor.computeFunction = _unalignedBufferCopyShader.Function; _unalignedBufferCopyPipeline = _device.newComputePipelineStateWithDescriptor(descriptor); ObjectiveCRuntime.release(descriptor.NativePtr); } return(_unalignedBufferCopyPipeline); } }
public MTLSampler(ref SamplerDescription description, MTLGraphicsDevice gd) { MTLFormats.GetMinMagMipFilter( description.Filter, out MTLSamplerMinMagFilter min, out MTLSamplerMinMagFilter mag, out MTLSamplerMipFilter mip); MTLSamplerDescriptor mtlDesc = MTLSamplerDescriptor.New(); mtlDesc.sAddressMode = MTLFormats.VdToMTLAddressMode(description.AddressModeU); mtlDesc.tAddressMode = MTLFormats.VdToMTLAddressMode(description.AddressModeV); mtlDesc.rAddressMode = MTLFormats.VdToMTLAddressMode(description.AddressModeW); mtlDesc.minFilter = min; mtlDesc.magFilter = mag; mtlDesc.mipFilter = mip; if (gd.MetalFeatures.IsMacOS) { mtlDesc.borderColor = MTLFormats.VdToMTLBorderColor(description.BorderColor); } if (description.ComparisonKind != null) { mtlDesc.compareFunction = MTLFormats.VdToMTLCompareFunction(description.ComparisonKind.Value); } mtlDesc.lodMinClamp = description.MinimumLod; mtlDesc.lodMaxClamp = description.MaximumLod; mtlDesc.maxAnisotropy = (UIntPtr)(Math.Max(1, description.MaximumAnisotropy)); DeviceSampler = gd.Device.newSamplerStateWithDescriptor(mtlDesc); ObjectiveCRuntime.release(mtlDesc.NativePtr); }
public override void Dispose() { if (!_disposed) { _disposed = true; ObjectiveCRuntime.release(DeviceSampler.NativePtr); } }
public override void Dispose() { if (_hasTextureView && !_disposed) { _disposed = true; ObjectiveCRuntime.release(TargetDeviceTexture.NativePtr); } }
public MTLTexture(ref TextureDescription description, MTLGraphicsDevice _gd) { Width = description.Width; Height = description.Height; Depth = description.Depth; ArrayLayers = description.ArrayLayers; MipLevels = description.MipLevels; Format = description.Format; Usage = description.Usage; Type = description.Type; SampleCount = description.SampleCount; bool isDepth = (Usage & TextureUsage.DepthStencil) == TextureUsage.DepthStencil; MTLPixelFormat = MTLFormats.VdToMTLPixelFormat(Format, isDepth); MTLTextureType = MTLFormats.VdToMTLTextureType( Type, ArrayLayers, SampleCount != TextureSampleCount.Count1, (Usage & TextureUsage.Cubemap) != 0); if (Usage != TextureUsage.Staging) { MTLTextureDescriptor texDescriptor = MTLTextureDescriptor.New(); texDescriptor.width = (UIntPtr)Width; texDescriptor.height = (UIntPtr)Height; texDescriptor.depth = (UIntPtr)Depth; texDescriptor.mipmapLevelCount = (UIntPtr)MipLevels; texDescriptor.arrayLength = (UIntPtr)ArrayLayers; texDescriptor.sampleCount = (UIntPtr)FormatHelpers.GetSampleCountUInt32(SampleCount); texDescriptor.textureType = MTLTextureType; texDescriptor.pixelFormat = MTLPixelFormat; texDescriptor.textureUsage = MTLFormats.VdToMTLTextureUsage(Usage); texDescriptor.storageMode = MTLStorageMode.Private; DeviceTexture = _gd.Device.newTextureWithDescriptor(texDescriptor); ObjectiveCRuntime.release(texDescriptor.NativePtr); } else { uint blockSize = FormatHelpers.IsCompressedFormat(Format) ? 4u : 1u; uint totalStorageSize = 0; for (uint level = 0; level < MipLevels; level++) { Util.GetMipDimensions(this, level, out uint levelWidth, out uint levelHeight, out uint levelDepth); uint storageWidth = Math.Max(levelWidth, blockSize); uint storageHeight = Math.Max(levelHeight, blockSize); totalStorageSize += levelDepth * FormatHelpers.GetDepthPitch( FormatHelpers.GetRowPitch(levelWidth, Format), levelHeight, Format); } totalStorageSize *= ArrayLayers; StagingBuffer = _gd.Device.newBufferWithLengthOptions( (UIntPtr)totalStorageSize, MTLResourceOptions.StorageModeShared); } }
public override void Dispose() { if (!_disposed) { _disposed = true; ObjectiveCRuntime.release(Function.NativePtr); ObjectiveCRuntime.release(Library.NativePtr); } }
public override void Dispose() { if (_drawable.NativePtr != IntPtr.Zero) { ObjectiveCRuntime.objc_msgSend(_drawable.NativePtr, "release"); } _framebuffer.Dispose(); ObjectiveCRuntime.release(_metalLayer.NativePtr); }
public void TimerUpdate() { if (iEnabled && (iMouseDown == EMouse.eLeft || iMouseDown == EMouse.eRight)) { DoStep(); this.PerformSelectorWithObjectAfterDelay(ObjectiveCRuntime.Selector("timerUpdate"), null, iRepeatInterval); } }
public unsafe MTLShader(ref ShaderDescription description, MTLGraphicsDevice gd) : base(description.Stage) { _device = gd; if (description.ShaderBytes.Length > 4 && description.ShaderBytes[0] == 0x4d && description.ShaderBytes[1] == 0x54 && description.ShaderBytes[2] == 0x4c && description.ShaderBytes[3] == 0x42) { DispatchQueue queue = Dispatch.dispatch_get_global_queue(QualityOfServiceLevel.QOS_CLASS_USER_INTERACTIVE, 0); fixed(byte *shaderBytesPtr = description.ShaderBytes) { DispatchData dispatchData = Dispatch.dispatch_data_create( shaderBytesPtr, (UIntPtr)description.ShaderBytes.Length, queue, IntPtr.Zero); try { Library = gd.Device.newLibraryWithData(dispatchData); } finally { Dispatch.dispatch_release(dispatchData.NativePtr); } } } else { string source = Encoding.UTF8.GetString(description.ShaderBytes); MTLCompileOptions compileOptions = MTLCompileOptions.New(); Library = gd.Device.newLibraryWithSource(source, compileOptions); ObjectiveCRuntime.release(compileOptions); } Function = Library.newFunctionWithName(description.EntryPoint); if (Function.NativePtr == IntPtr.Zero) { throw new VeldridException( $"Failed to create Metal {description.Stage} Shader. The given entry point \"{description.EntryPoint}\" was not found."); } if (Function.functionConstantsDictionary.count != UIntPtr.Zero) { // Need to create specialized MTLFunction. ObjectiveCRuntime.release(Function.NativePtr); MTLFunctionConstantValues constantValues = MTLFunctionConstantValues.New(); Function = Library.newFunctionWithNameConstantValues(description.EntryPoint, constantValues); ObjectiveCRuntime.release(constantValues.NativePtr); Debug.Assert(Function.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction"); } }
partial void CheckBoxCustomPort_Action(Id sender) { if (ObjectiveCRuntime.CastTo <NSButton>(sender).State == NSCellStateValue.NSOffState) { textFieldCustomPort.IsEnabled = false; textFieldCustomPort.IntValue = 3389; } else { textFieldCustomPort.IsEnabled = true; } }
/// <summary> /// Used for regression tests. /// </summary> public static void test_regression() { ObjectiveCRuntime.LoadFramework("Cocoa"); ObjectiveCRuntime.Initialize(); var test = new MonobjcTest(); test.OnBeginTest += () => { _pool = new NSAutoreleasePool(); }; test.OnEndTest += () => { _pool.Release(); _pool = null; }; test.TestAll(typeof(ObjectiveCRuntime).Assembly); }
public void GetNextDrawable() { if (_drawable.NativePtr != IntPtr.Zero) { ObjectiveCRuntime.objc_msgSend(_drawable.NativePtr, "release"); } _drawable = _layer.nextDrawable(); if (_drawable.NativePtr == IntPtr.Zero) { Console.WriteLine("Got a null drawable."); } }
public override Id InitConnectionType(RoyalConnection data, NSTabViewItem tabViewItem, NSWindow parentWindow) { Id ret = base.InitConnectionType(data, tabViewItem, parentWindow); m_nativeFrameworkHandle = ApiUtils.LoadPluginFramework(typeof(RdpConnection), "RdpView"); IntPtr funcSymbol = ApiUtils.GetSymbolFromHandle(m_nativeFrameworkHandle, "getRdpViewController"); NativeGetRdpViewController GetRdpViewController = (NativeGetRdpViewController)ApiUtils.GetDelegateFunctionFromFramework <NativeGetRdpViewController>(funcSymbol); m_nativeController = ObjectiveCRuntime.GetInstance <NSObject>(GetRdpViewController(this.NativePointer, parentWindow.NativePointer)); return(ret); }
public void GetNextDrawable() { if (!_drawable.IsNull) { ObjectiveCRuntime.release(_drawable.NativePtr); } using (NSAutoreleasePool.Begin()) { _drawable = _metalLayer.nextDrawable(); ObjectiveCRuntime.retain(_drawable.NativePtr); } }
public override void Dispose() { if (!_disposed) { _disposed = true; if (!StagingBuffer.IsNull) { ObjectiveCRuntime.release(StagingBuffer.NativePtr); } else { ObjectiveCRuntime.release(DeviceTexture.NativePtr); } } }
public override void Dispose() { if (!_disposed) { if (RenderPipelineState.NativePtr != IntPtr.Zero) { ObjectiveCRuntime.release(RenderPipelineState.NativePtr); } else { Debug.Assert(ComputePipelineState.NativePtr != IntPtr.Zero); ObjectiveCRuntime.release(ComputePipelineState.NativePtr); } _disposed = true; } }
public MTLPipeline(ref ComputePipelineDescription description, MTLGraphicsDevice gd) : base(ref description) { IsComputePipeline = true; ResourceLayouts = new MTLResourceLayout[description.ResourceLayouts.Length]; for (int i = 0; i < ResourceLayouts.Length; i++) { ResourceLayouts[i] = Util.AssertSubtype <ResourceLayout, MTLResourceLayout>(description.ResourceLayouts[i]); } ThreadsPerThreadgroup = new MTLSize( description.ThreadGroupSizeX, description.ThreadGroupSizeY, description.ThreadGroupSizeZ); MTLComputePipelineDescriptor mtlDesc = MTLUtil.AllocInit <MTLComputePipelineDescriptor>( nameof(MTLComputePipelineDescriptor)); MTLShader mtlShader = Util.AssertSubtype <Shader, MTLShader>(description.ComputeShader); mtlDesc.computeFunction = mtlShader.Function; MTLPipelineBufferDescriptorArray buffers = mtlDesc.buffers; uint bufferIndex = 0; foreach (MTLResourceLayout layout in ResourceLayouts) { foreach (ResourceKind kind in layout.ResourceKinds) { if (kind == ResourceKind.UniformBuffer || kind == ResourceKind.StructuredBufferReadOnly) { MTLPipelineBufferDescriptor bufferDesc = buffers[bufferIndex]; bufferDesc.mutability = MTLMutability.Immutable; bufferIndex += 1; } else if (kind == ResourceKind.StructuredBufferReadWrite) { MTLPipelineBufferDescriptor bufferDesc = buffers[bufferIndex]; bufferDesc.mutability = MTLMutability.Mutable; bufferIndex += 1; } } } ComputePipelineState = gd.Device.newComputePipelineStateWithDescriptor(mtlDesc); ObjectiveCRuntime.release(mtlDesc.NativePtr); }
private protected override void WaitForIdleCore() { MTLCommandBuffer lastCB = default(MTLCommandBuffer); lock (_submittedCommandsLock) { lastCB = _latestSubmittedCB; ObjectiveCRuntime.retain(lastCB.NativePtr); } if (lastCB.NativePtr != IntPtr.Zero && lastCB.status != MTLCommandBufferStatus.Completed) { lastCB.waitUntilCompleted(); } ObjectiveCRuntime.release(lastCB.NativePtr); }
private void OnCommandBufferCompleted(IntPtr block, MTLCommandBuffer cb) { lock (_submittedCommandsLock) { if (_submittedCBs.TryGetValue(cb, out MTLFence fence)) { fence.Set(); _submittedCBs.Remove(cb); } if (_latestSubmittedCB.NativePtr == cb.NativePtr) { _latestSubmittedCB = default(MTLCommandBuffer); } } ObjectiveCRuntime.release(cb.NativePtr); }
static void Main(string[] aArgs) { // when built with scons, the executing assembly appears in the KinskyDesktop.app/Contents/MacOs folder // whereas under MonoDevelop it is in the KinskyDesktop.app/Contents/Resources folder - this code will handle both string exeFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName); string contentsFolder = Path.GetDirectoryName(exeFolder); string resFolder = Path.Combine(contentsFolder, "Resources"); KinskyDesktop.Properties.Resources.SetBasePath(resFolder); ObjectiveCRuntime.LoadFramework("Cocoa"); ObjectiveCRuntime.LoadFramework("Quartz"); ObjectiveCRuntime.Initialize(); NSApplication.Bootstrap(); NSApplication.LoadNib("MainMenu.nib"); NSApplication.RunApplication(); }
protected override void PlatformDispose() { WaitForIdle(); if (!_unalignedBufferCopyPipeline.IsNull) { _unalignedBufferCopyShader.Dispose(); ObjectiveCRuntime.release(_unalignedBufferCopyPipeline.NativePtr); } _mainSwapchain?.Dispose(); ObjectiveCRuntime.release(_commandQueue.NativePtr); ObjectiveCRuntime.release(_device.NativePtr); lock (s_aotRegisteredBlocks) { s_aotRegisteredBlocks.Remove(_completionBlockLiteral); } _libSystem.Dispose(); Marshal.FreeHGlobal(_completionBlockDescriptor); Marshal.FreeHGlobal(_completionBlockLiteral); }
/// <summary> /// First method called. /// </summary> public static void Main() { try { // // NOTE: refer to monobjc documentation about this code. // load cocoa library ObjectiveCRuntime.LoadFramework("Cocoa"); ObjectiveCRuntime.Initialize(); // NSApplication.Bootstrap(); // load application bundle NSApplication.LoadNib("Window.nib"); NSApplication.RunApplication(); // } catch (Exception exc) { // log errors: if (logger.IsFatalEnabled) { logger.Fatal("An exception at the top level was catched.", exc); } } }
public MTLPipeline(ref ComputePipelineDescription description, MTLGraphicsDevice gd) : base(ref description) { IsComputePipeline = true; ResourceLayouts = new MTLResourceLayout[description.ResourceLayouts.Length]; for (int i = 0; i < ResourceLayouts.Length; i++) { ResourceLayouts[i] = Util.AssertSubtype <ResourceLayout, MTLResourceLayout>(description.ResourceLayouts[i]); } ThreadsPerThreadgroup = new MTLSize( description.ThreadGroupSizeX, description.ThreadGroupSizeY, description.ThreadGroupSizeZ); MTLComputePipelineDescriptor mtlDesc = MTLUtil.AllocInit <MTLComputePipelineDescriptor>( nameof(MTLComputePipelineDescriptor)); MTLShader mtlShader = Util.AssertSubtype <Shader, MTLShader>(description.ComputeShader); MTLFunction specializedFunction; if (mtlShader.HasFunctionConstants) { // Need to create specialized MTLFunction. MTLFunctionConstantValues constantValues = CreateConstantValues(description.Specializations); specializedFunction = mtlShader.Library.newFunctionWithNameConstantValues(mtlShader.EntryPoint, constantValues); AddSpecializedFunction(specializedFunction); ObjectiveCRuntime.release(constantValues.NativePtr); Debug.Assert(specializedFunction.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction"); } else { specializedFunction = mtlShader.Function; } mtlDesc.computeFunction = specializedFunction; MTLPipelineBufferDescriptorArray buffers = mtlDesc.buffers; uint bufferIndex = 0; foreach (MTLResourceLayout layout in ResourceLayouts) { foreach (ResourceKind kind in layout.ResourceKinds) { if (kind == ResourceKind.UniformBuffer || kind == ResourceKind.StructuredBufferReadOnly) { MTLPipelineBufferDescriptor bufferDesc = buffers[bufferIndex]; bufferDesc.mutability = MTLMutability.Immutable; bufferIndex += 1; } else if (kind == ResourceKind.StructuredBufferReadWrite) { MTLPipelineBufferDescriptor bufferDesc = buffers[bufferIndex]; bufferDesc.mutability = MTLMutability.Mutable; bufferIndex += 1; } } } ComputePipelineState = gd.Device.newComputePipelineStateWithDescriptor(mtlDesc); ObjectiveCRuntime.release(mtlDesc.NativePtr); }
public bool ValidateMenuItem(NSMenuItem aItem) { return(aItem.Action == ObjectiveCRuntime.Selector("deleteBookmark:") && ViewTable.ClickedRow >= 0); }
public override void DrawRect(NSRect aRect) { // calculate the number of tick intervals since the hourglass was shown NSDate dateNow = NSDate.DateWithTimeIntervalSinceNow(0); double timeElapsed = dateNow.TimeIntervalSinceReferenceDate - iTimeShown; int numIntervals = (int)(timeElapsed / 0.06); // save graphics state for restoring later NSGraphicsContext context = NSGraphicsContext.CurrentContext; context.SaveGraphicsState(); // apply transforms to rotate the foreground image NSImage bkgd = Properties.Resources.IconHourglass; NSImage frgd = Properties.Resources.IconHourglass2; NSAffineTransform xform1 = new NSAffineTransform(); xform1.TranslateXByYBy(Bounds.Width * 0.5f, Bounds.Height * 0.5f); xform1.Concat(); NSAffineTransform xform2 = new NSAffineTransform(); xform2.RotateByDegrees(-45.0f * (numIntervals % 8)); xform2.Concat(); bool scale = Bounds.Width < frgd.Size.width || Bounds.Height < frgd.Size.height; NSAffineTransform xform3 = null; if (scale) { float scaleX = Bounds.Width / frgd.Size.width; float scaleY = Bounds.Height / frgd.Size.height; float ratio = scaleX > scaleY ? scaleX : scaleY; xform3 = new NSAffineTransform(); xform3.ScaleBy(ratio); xform3.Concat(); } NSAffineTransform xform4 = new NSAffineTransform(); xform4.TranslateXByYBy(-frgd.Size.width * 0.5f, -frgd.Size.height * 0.5f); xform4.Concat(); // draw background and foreground bkgd.DrawAtPointFromRectOperationFraction(Bounds.origin, NSRect.NSZeroRect, NSCompositingOperation.NSCompositeSourceOver, 1.0f); frgd.DrawAtPointFromRectOperationFraction(Bounds.origin, NSRect.NSZeroRect, NSCompositingOperation.NSCompositeSourceOver, 1.0f); // clean up xform1.Release(); xform2.Release(); if (scale) { xform3.Release(); } xform4.Release(); context.RestoreGraphicsState(); // schedule another timer event this.PerformSelectorWithObjectAfterDelay(ObjectiveCRuntime.Selector("timerUpdate"), null, 0.06); }
public MTLPipeline(ref GraphicsPipelineDescription description, MTLGraphicsDevice gd) : base(ref description) { PrimitiveType = MTLFormats.VdToMTLPrimitiveTopology(description.PrimitiveTopology); ResourceLayouts = new MTLResourceLayout[description.ResourceLayouts.Length]; NonVertexBufferCount = 0; for (int i = 0; i < ResourceLayouts.Length; i++) { ResourceLayouts[i] = Util.AssertSubtype <ResourceLayout, MTLResourceLayout>(description.ResourceLayouts[i]); NonVertexBufferCount += ResourceLayouts[i].BufferCount; } ResourceBindingModel = description.ResourceBindingModel ?? gd.ResourceBindingModel; CullMode = MTLFormats.VdToMTLCullMode(description.RasterizerState.CullMode); FrontFace = MTLFormats.VdVoMTLFrontFace(description.RasterizerState.FrontFace); FillMode = MTLFormats.VdToMTLFillMode(description.RasterizerState.FillMode); ScissorTestEnabled = description.RasterizerState.ScissorTestEnabled; MTLRenderPipelineDescriptor mtlDesc = MTLRenderPipelineDescriptor.New(); foreach (Shader shader in description.ShaderSet.Shaders) { MTLShader mtlShader = Util.AssertSubtype <Shader, MTLShader>(shader); MTLFunction specializedFunction; if (mtlShader.HasFunctionConstants) { // Need to create specialized MTLFunction. MTLFunctionConstantValues constantValues = CreateConstantValues(description.ShaderSet.Specializations); specializedFunction = mtlShader.Library.newFunctionWithNameConstantValues(mtlShader.EntryPoint, constantValues); AddSpecializedFunction(specializedFunction); ObjectiveCRuntime.release(constantValues.NativePtr); Debug.Assert(specializedFunction.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction"); } else { specializedFunction = mtlShader.Function; } if (shader.Stage == ShaderStages.Vertex) { mtlDesc.vertexFunction = specializedFunction; } else if (shader.Stage == ShaderStages.Fragment) { mtlDesc.fragmentFunction = specializedFunction; } } // Vertex layouts VertexLayoutDescription[] vdVertexLayouts = description.ShaderSet.VertexLayouts; MTLVertexDescriptor vertexDescriptor = mtlDesc.vertexDescriptor; for (uint i = 0; i < vdVertexLayouts.Length; i++) { uint layoutIndex = ResourceBindingModel == ResourceBindingModel.Improved ? NonVertexBufferCount + i : i; MTLVertexBufferLayoutDescriptor mtlLayout = vertexDescriptor.layouts[layoutIndex]; mtlLayout.stride = (UIntPtr)vdVertexLayouts[i].Stride; uint stepRate = vdVertexLayouts[i].InstanceStepRate; mtlLayout.stepFunction = stepRate == 0 ? MTLVertexStepFunction.PerVertex : MTLVertexStepFunction.PerInstance; mtlLayout.stepRate = (UIntPtr)Math.Max(1, stepRate); } uint element = 0; for (uint i = 0; i < vdVertexLayouts.Length; i++) { uint offset = 0; VertexLayoutDescription vdDesc = vdVertexLayouts[i]; for (uint j = 0; j < vdDesc.Elements.Length; j++) { VertexElementDescription elementDesc = vdDesc.Elements[j]; MTLVertexAttributeDescriptor mtlAttribute = vertexDescriptor.attributes[element]; mtlAttribute.bufferIndex = (UIntPtr)(ResourceBindingModel == ResourceBindingModel.Improved ? NonVertexBufferCount + i : i); mtlAttribute.format = MTLFormats.VdToMTLVertexFormat(elementDesc.Format); mtlAttribute.offset = elementDesc.Offset != 0 ? (UIntPtr)elementDesc.Offset : (UIntPtr)offset; offset += FormatHelpers.GetSizeInBytes(elementDesc.Format); element += 1; } } VertexBufferCount = (uint)vdVertexLayouts.Length; // Outputs OutputDescription outputs = description.Outputs; BlendStateDescription blendStateDesc = description.BlendState; BlendColor = blendStateDesc.BlendFactor; if (outputs.SampleCount != TextureSampleCount.Count1) { mtlDesc.sampleCount = (UIntPtr)FormatHelpers.GetSampleCountUInt32(outputs.SampleCount); } if (outputs.DepthAttachment != null) { PixelFormat depthFormat = outputs.DepthAttachment.Value.Format; MTLPixelFormat mtlDepthFormat = MTLFormats.VdToMTLPixelFormat(depthFormat, true); mtlDesc.depthAttachmentPixelFormat = mtlDepthFormat; if ((FormatHelpers.IsStencilFormat(depthFormat))) { HasStencil = true; mtlDesc.stencilAttachmentPixelFormat = mtlDepthFormat; } } for (uint i = 0; i < outputs.ColorAttachments.Length; i++) { BlendAttachmentDescription attachmentBlendDesc = blendStateDesc.AttachmentStates[i]; MTLRenderPipelineColorAttachmentDescriptor colorDesc = mtlDesc.colorAttachments[i]; colorDesc.pixelFormat = MTLFormats.VdToMTLPixelFormat(outputs.ColorAttachments[i].Format, false); colorDesc.blendingEnabled = attachmentBlendDesc.BlendEnabled; colorDesc.alphaBlendOperation = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.AlphaFunction); colorDesc.sourceAlphaBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceAlphaFactor); colorDesc.destinationAlphaBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationAlphaFactor); colorDesc.rgbBlendOperation = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.ColorFunction); colorDesc.sourceRGBBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceColorFactor); colorDesc.destinationRGBBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationColorFactor); } RenderPipelineState = gd.Device.newRenderPipelineStateWithDescriptor(mtlDesc); ObjectiveCRuntime.release(mtlDesc.NativePtr); if (outputs.DepthAttachment != null) { MTLDepthStencilDescriptor depthDescriptor = MTLUtil.AllocInit <MTLDepthStencilDescriptor>( nameof(MTLDepthStencilDescriptor)); depthDescriptor.depthCompareFunction = MTLFormats.VdToMTLCompareFunction( description.DepthStencilState.DepthComparison); depthDescriptor.depthWriteEnabled = description.DepthStencilState.DepthWriteEnabled; bool stencilEnabled = description.DepthStencilState.StencilTestEnabled; if (stencilEnabled) { StencilReference = description.DepthStencilState.StencilReference; StencilBehaviorDescription vdFrontDesc = description.DepthStencilState.StencilFront; MTLStencilDescriptor front = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor)); front.readMask = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u; front.writeMask = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u; front.depthFailureOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.DepthFail); front.stencilFailureOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Fail); front.depthStencilPassOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Pass); front.stencilCompareFunction = MTLFormats.VdToMTLCompareFunction(vdFrontDesc.Comparison); depthDescriptor.frontFaceStencil = front; StencilBehaviorDescription vdBackDesc = description.DepthStencilState.StencilBack; MTLStencilDescriptor back = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor)); back.readMask = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u; back.writeMask = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u; back.depthFailureOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.DepthFail); back.stencilFailureOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Fail); back.depthStencilPassOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Pass); back.stencilCompareFunction = MTLFormats.VdToMTLCompareFunction(vdBackDesc.Comparison); depthDescriptor.backFaceStencil = back; ObjectiveCRuntime.release(front.NativePtr); ObjectiveCRuntime.release(back.NativePtr); } DepthStencilState = gd.Device.newDepthStencilStateWithDescriptor(depthDescriptor); ObjectiveCRuntime.release(depthDescriptor.NativePtr); } DepthClipMode = description.DepthStencilState.DepthTestEnabled ? MTLDepthClipMode.Clip : MTLDepthClipMode.Clamp; }
public static Process[] GetProcesses() { // spin up the objective-c runtime ObjectiveCRuntime.LoadFramework("Cocoa"); ObjectiveCRuntime.Initialize(); NSAutoreleasePool pool = new NSAutoreleasePool(); // Create our process NSTask getPSTask = new NSTask(); NSPipe getPSStandardOut = new NSPipe(); getPSTask.StandardOutput = getPSStandardOut; getPSTask.LaunchPath = @"/bin/ps"; // add some arguments NSString getPSargumentString = new NSString("-ax"); NSArray getPSarguments = NSArray.ArrayWithObject(getPSargumentString); getPSTask.Arguments = getPSarguments; // We have liftoff getPSTask.Launch(); getPSTask.WaitUntilExit(); // Parse the output NSData getPSoutput = getPSStandardOut.FileHandleForReading.ReadDataToEndOfFile; NSString getPSoutString = new NSString(getPSoutput, NSStringEncoding.NSUTF8StringEncoding); // Split the string of output in to a list of processes string[] getPSsplitString = getPSoutString.ToString().Split(Environment.NewLine.ToCharArray()); // Remove the first and last line of the output string[] processListAsStrings = new string[getPSsplitString.Length - 2]; for (int x = 1; x < getPSsplitString.Length - 1; x++) { processListAsStrings[x - 1] = getPSsplitString[x]; } Process[] processes = new Process[processListAsStrings.Length]; for (int i = 0; i < processes.Length; i++) { string cleanString = RemoveExtraSpaces(processListAsStrings[i]); string[] processDetails = cleanString.Split(' '); Int32 procID = Convert.ToInt32(processDetails[0]); string procName = string.Empty; for (int j = 4; j < processDetails.Length; j++) { if (j == 4) { procName = procName + processDetails[j]; } else { procName = procName + " " + processDetails[j]; } } //Console.WriteLine(procID.ToString() + procName); processes[i] = new Process(procID, procName); } // Dipose our Objective-C objects, gotta love reference counting pool.Release(); return(processes); }