Example #1
0
        public Renderer()
        {
            // initialize properties
            sampleCount        = 1;
            depthPixelFormat   = MTLPixelFormat.Depth32Float;
            stencilPixelFormat = MTLPixelFormat.Invalid;

            // find a usable Device
            device = MTLDevice.SystemDefault;

            // create a new command queue
            commandQueue = device.CreateCommandQueue();

            NSError error;

            shaderLibrary = device.CreateLibrary("default.metallib", out error);

            // if the shader libary isnt loading, nothing good will happen
            if (shaderLibrary == null)
            {
                throw new Exception("ERROR: Couldnt create a default shader library");
            }

            inflightSemaphore = new Semaphore(maxInflightBuffers, maxInflightBuffers);
        }
        public Renderer()
        {
            sampleCount        = 4;
            depthPixelFormat   = MTLPixelFormat.Depth32Float;
            stencilPixelFormat = MTLPixelFormat.Invalid;

            // find a usable Device
            device = MTLDevice.SystemDefault;

            // create a new command queue
            commandQueue = device.CreateCommandQueue();

            NSError error;

            defaultLibrary = device.CreateLibrary("default.metallib", out error);

            // if the shader libary isnt loading, nothing good will happen
            if (defaultLibrary == null)
            {
                throw new Exception("ERROR: Couldnt create a default shader library");
            }

            constantDataBufferIndex = 0;
            inflightSemaphore       = new Semaphore(max_inflight_buffers, max_inflight_buffers);

            constantBuffer = new Uniforms[2];
            constantBuffer [0].ambientColor = box1AmbientColor;
            constantBuffer [0].diffuseColor = box1DiffuseColor;

            constantBuffer [1].ambientColor = box2AmbientColor;
            constantBuffer [1].diffuseColor = box2DiffuseColor;

            multiplier = 1;
        }
        void SetupMetal()
        {
            // Find a usable device
            device = MTLDevice.SystemDefault;

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            NSError error;

            defaultLibrary = device.CreateLibrary("default.metallib", out error);

            // Setup metal layer and add as sub layer to view
            metalLayer             = new CAMetalLayer();
            metalLayer.Device      = device;
            metalLayer.PixelFormat = MTLPixelFormat.BGRA8Unorm;

            // Change this to NO if the compute encoder is used as the last pass on the drawable texture
            metalLayer.FramebufferOnly = true;

            // Add metal layer to the views layer hierarchy
            metalLayer.Frame = View.Layer.Frame;
            View.Layer.AddSublayer(metalLayer);

            View.Opaque             = true;
            View.BackgroundColor    = null;
            View.ContentScaleFactor = UIScreen.MainScreen.Scale;
        }
Example #4
0
        void ConfigureMetal()
        {
            var library = device.CreateDefaultLibrary();

            if (library == null)
            {
                return;
            }
            MTLRenderPipelineDescriptor pipelineDescriptor = new MTLRenderPipelineDescriptor();

            pipelineDescriptor.SampleCount = 1;
            pipelineDescriptor.ColorAttachments[0].PixelFormat = MTLPixelFormat.BGRA8Unorm;
            pipelineDescriptor.DepthAttachmentPixelFormat      = MTLPixelFormat.Invalid;
            pipelineDescriptor.VertexFunction   = library.CreateFunction("simpleVertex");
            pipelineDescriptor.FragmentFunction = library.CreateFunction("simpleTexture");

            NSError error1 = null;

            renderPipelineState = device.CreateRenderPipelineState(pipelineDescriptor, out error1);

            if (error1 != null)
            {
                return;
            }
            commandQueue = device.CreateCommandQueue();
        }
		void SetupMetal ()
		{
			// Set the view to use the default device.
			metalView.Device = MTLDevice.SystemDefault;

			// Create a new command queue.
			commandQueue = metalView.Device.CreateCommandQueue ();
		}
        void SetupMetal()
        {
            // Set the view to use the default device.
            metalView.Device = MTLDevice.SystemDefault;

            // Create a new command queue.
            commandQueue = metalView.Device.CreateCommandQueue();
        }
Example #7
0
 public void TearDown()
 {
     commandQ?.Dispose();
     commandQ = null;
     commandBuffer?.Dispose();
     commandBuffer = null;
     encoder?.Dispose();
     encoder = null;
 }
        void SetupMetal()
        {
            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();
        }
Example #9
0
        public AmtCommandPool(
            IMTLCommandQueue queue,
            MgCommandPoolCreateInfo pCreateInfo,
            IAmtCmdDepthStencilCache depthCache)
        {
            mQueue = queue;

            CanIndividuallyReset = (pCreateInfo.Flags & MgCommandPoolCreateFlagBits.RESET_COMMAND_BUFFER_BIT)
                                   == MgCommandPoolCreateFlagBits.RESET_COMMAND_BUFFER_BIT;

            mBuffers   = new List <AmtCommandBuffer>();
            DepthCache = depthCache;
        }
Example #10
0
        void SetupMetal()
        {
            // Set the view to use the default device.
                        #if IOS
            device = MTLDevice.SystemDefault;
                        #elif MAC
            // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=32680
            var devicePointer = MTLCreateSystemDefaultDevice();
            device = Runtime.GetINativeObject <IMTLDevice> (devicePointer, false);
                        #endif
            // Create a new command queue.
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project.
            defaultLibrary = device.CreateDefaultLibrary();
        }
Example #11
0
        public override void Init(IntPtr display, IntPtr window, uint samples, bool vsync, bool sRGB)
        {
            _display = display;
            _window  = window;

            while (!_dev.SupportsTextureSampleCount(samples))
            {
                samples >>= 1;
            }
            _samples = samples;

            _layer                 = new CAMetalLayer();
            _layer.Device          = _dev;
            _layer.PixelFormat     = sRGB ? MTLPixelFormat.BGRA8Unorm_sRGB : MTLPixelFormat.BGRA8Unorm;
            _layer.FramebufferOnly = true;

#if __IOS__
            UIView view = (UIView)ObjCRuntime.Runtime.GetNSObject(window);
            view.Layer.AddSublayer(_layer);
#else
            // Mac
            NSView view = (NSView)ObjCRuntime.Runtime.GetNSObject(window);
            view.Layer.AddSublayer(_layer);
#endif
            _cmdQueue = _dev.CreateCommandQueue();

            _descriptor = new MTLRenderPassDescriptor();
            _descriptor.ColorAttachments[0].ClearColor = new MTLClearColor(0.0, 1.0, 0.0, 0.0);

            if (samples > 1)
            {
                _descriptor.ColorAttachments[0].StoreAction = MTLStoreAction.MultisampleResolve;
            }
            else
            {
                _descriptor.ColorAttachments[0].StoreAction = MTLStoreAction.Store;
            }

            _descriptor.StencilAttachment.ClearStencil = 0;
            _descriptor.StencilAttachment.LoadAction   = MTLLoadAction.Clear;
            _descriptor.StencilAttachment.StoreAction  = MTLStoreAction.DontCare;

            _device = new Noesis.RenderDeviceMTL(_dev.Handle, sRGB);
        }
Example #12
0
        public MnistFullLayerNeuralNetwork(IMTLCommandQueue commandQueueIn)
        {
            // CommandQueue to be kept around
            commandQueue = commandQueueIn;
            device       = commandQueueIn.Device;

            // Initialize MPSImage from descriptors
            SrcImage = new MPSImage(device, SID);
            dstImage = new MPSImage(device, DID);

            // setup convolution layer (which is a fully-connected layer)
            // cliprect, offset is automatically set
            layer = SlimMPSCnnFullyConnected.Create(kernelWidth: 28, kernelHeight: 28,
                                                    inputFeatureChannels: 1, outputFeatureChannels: 10,
                                                    neuronFilter: null, device: device,
                                                    kernelParamsBinaryName: "NN");

            // prepare softmax layer to be applied at the end to get a clear label
            softmax = new MPSCnnSoftMax(device);
        }
		public MnistFullLayerNeuralNetwork (IMTLCommandQueue commandQueueIn)
		{
			// CommandQueue to be kept around
			commandQueue = commandQueueIn;
			device = commandQueueIn.Device;

			// Initialize MPSImage from descriptors
			SrcImage = new MPSImage (device, SID);
			dstImage = new MPSImage (device, DID);

			// setup convolution layer (which is a fully-connected layer)
			// cliprect, offset is automatically set
			layer = SlimMPSCnnFullyConnected.Create (kernelWidth: 28, kernelHeight: 28,
													 inputFeatureChannels: 1, outputFeatureChannels: 10,
													 neuronFilter: null, device: device,
													 kernelParamsBinaryName: "NN");

			// prepare softmax layer to be applied at the end to get a clear label
			softmax = new MPSCnnSoftMax (device);
		}
Example #14
0
        void SetupMetal()
        {
            // Set the view to use the default device.
            device = MTLDevice.SystemDefault;
            if (device != null)
            {
                // mark that metal is supported by this device
                isMetalSupported = true;

                // Create a new command queue.
                commandQueue = device.CreateCommandQueue();

                // Load all the shader files with a metal file extension in the project.
                defaultLibrary = device.CreateDefaultLibrary();
            }
            else
            {
                // that mean that device doesn't support Metal
                isMetalSupported = false;
            }
        }
Example #15
0
        public MetalClothSimulator(IMTLDevice device)
        {
            this.device       = device;
            this.commandQueue = this.device.CreateCommandQueue();

            this.defaultLibrary       = this.device.CreateDefaultLibrary();
            this.functionClothSim     = this.defaultLibrary.CreateFunction("updateVertex");
            this.functionNormalUpdate = this.defaultLibrary.CreateFunction("updateNormal");
            this.functionNormalSmooth = this.defaultLibrary.CreateFunction("smoothNormal");

            this.pipelineStateClothSim     = this.device.CreateComputePipelineState(this.functionClothSim, out NSError pipelineStateClothSimError);
            this.pipelineStateNormalUpdate = this.device.CreateComputePipelineState(this.functionNormalUpdate, out NSError pipelineStateNormalUpdateError);
            this.pipelineStateNormalSmooth = this.device.CreateComputePipelineState(this.functionNormalSmooth, out NSError pipelineStateNormalSmoothError);

            if (pipelineStateClothSimError != null ||
                pipelineStateNormalUpdateError != null ||
                pipelineStateNormalSmoothError != null)
            {
                throw new Exception("error");
            }
        }
Example #16
0
		public Renderer ()
		{
			// initialize properties
			sampleCount = 1;
			depthPixelFormat = MTLPixelFormat.Depth32Float;
			stencilPixelFormat = MTLPixelFormat.Invalid;

			// find a usable Device
			device = MTLDevice.SystemDefault;

			// create a new command queue
			commandQueue = device.CreateCommandQueue ();

			NSError error;
			shaderLibrary = device.CreateLibrary ("default.metallib", out error);

			// if the shader libary isnt loading, nothing good will happen
			if (shaderLibrary == null)
				throw new Exception ("ERROR: Couldnt create a default shader library");

			inflightSemaphore = new Semaphore (maxInflightBuffers, maxInflightBuffers);
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Load default device.
			device = MTLDevice.SystemDefault;

			// Make sure the current device supports MetalPerformanceShaders.
			if (!MPSKernel.Supports (device)) {
				Console.WriteLine ("Metal Performance Shaders not Supported on current Device");
				return;
			}

			// Create new command queue.
			commandQueue = device.CreateCommandQueue ();

			// initialize the networks we shall use to detect digits
			neuralNetwork = new MnistFullLayerNeuralNetwork (commandQueue);
			neuralNetworkDeep = new MnistDeepConvNeuralNetwork (commandQueue);

			runningNet = neuralNetwork;
		}
Example #18
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Load default device.
            device = MTLDevice.SystemDefault;

            // Make sure the current device supports MetalPerformanceShaders.
            if (!MPSKernel.Supports(device))
            {
                Console.WriteLine("Metal Performance Shaders not Supported on current Device");
                return;
            }

            // Create new command queue.
            commandQueue = device.CreateCommandQueue();

            // initialize the networks we shall use to detect digits
            neuralNetwork     = new MnistFullLayerNeuralNetwork(commandQueue);
            neuralNetworkDeep = new MnistDeepConvNeuralNetwork(commandQueue);

            runningNet = neuralNetwork;
        }
Example #19
0
        public void SetUp()
        {
            device = MTLDevice.SystemDefault;
            // some older hardware won't have a default
            if (device == null)
            {
                Assert.Inconclusive("Metal is not supported");
            }

            commandQ = device.CreateCommandQueue();
            if (commandQ == null)              // this happens on a simulator
            {
                Assert.Inconclusive("Could not get the functions library for the device.");
            }

            commandBuffer = commandQ.CommandBuffer();
            if (commandBuffer == null)             // happens on sim
            {
                Assert.Inconclusive("Could not get the command buffer for the device.");
            }

            encoder = commandBuffer.ComputeCommandEncoder;
        }
Example #20
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            view          = (MTKView)View;
            view.Delegate = this;
            view.Device   = device;

            view.SampleCount              = 1;
            view.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            view.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            view.PreferredFramesPerSecond = 60;
            view.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("triangle_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("triangle_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 8 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            vertexBuffer = device.CreateBuffer(vertexData, MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = view.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = view.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = view.DepthStencilPixelFormat
            };

            pipelineStateDescriptor.ColorAttachments[0].PixelFormat = view.ColorPixelFormat;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            this.rectangle = new MTLScissorRect(125, 166, 250, 444);
        }
Example #21
0
		public AmtQueueRenderer(IMTLCommandQueue queue)
		{
			mCommandQueue = queue;
		}
		void SetupMetal ()
		{
			// Create a new command queue.
			commandQueue = metalView.Device.CreateCommandQueue ();
		}
Example #23
0
		public Renderer ()
		{
			sampleCount = 4;
			depthPixelFormat = MTLPixelFormat.Depth32Float;
			stencilPixelFormat = MTLPixelFormat.Invalid;

			// find a usable Device
			device = MTLDevice.SystemDefault;

			// create a new command queue
			commandQueue = device.CreateCommandQueue ();

			NSError error;
			defaultLibrary = device.CreateLibrary ("default.metallib", out error);

			// if the shader libary isnt loading, nothing good will happen
			if (defaultLibrary == null)
				throw new Exception ("ERROR: Couldnt create a default shader library");

			constantDataBufferIndex = 0;
			inflightSemaphore = new Semaphore (max_inflight_buffers, max_inflight_buffers);

			constantBuffer = new Uniforms[2];
			constantBuffer [0].ambientColor = box1AmbientColor;
			constantBuffer [0].diffuseColor = box1DiffuseColor;

			constantBuffer [1].ambientColor = box2AmbientColor;
			constantBuffer [1].diffuseColor = box2DiffuseColor;

			multiplier = 1;
		}
Example #24
0
        public MnistDeepConvNeuralNetwork(IMTLCommandQueue commandQueueIn)
            : base(commandQueueIn)
        {
            // use device for a little while to initialize
            var device = commandQueueIn.Device;

            pool = new MPSCnnPoolingMax(device, 2, 2, 2, 2)
            {
                Offset = new MPSOffset {
                    X = 1, Y = 1, Z = 0
                },
                EdgeMode = MPSImageEdgeMode.Clamp
            };
            relu = new MPSCnnNeuronReLU(device, 0);

            // Initialize MPSImage from descriptors
            c1Image  = new MPSImage(device, c1id);
            p1Image  = new MPSImage(device, p1id);
            c2Image  = new MPSImage(device, c2id);
            p2Image  = new MPSImage(device, p2id);
            fc1Image = new MPSImage(device, fc1id);

            // setup convolution layers
            conv1 = SlimMPSCnnConvolution.Create(kernelWidth: 5,
                                                 kernelHeight: 5,
                                                 inputFeatureChannels: 1,
                                                 outputFeatureChannels: 32,
                                                 neuronFilter: relu,
                                                 device: device,
                                                 kernelParamsBinaryName: "conv1",
                                                 padding: true,
                                                 strideX: 1,
                                                 strideY: 1,
                                                 destinationFeatureChannelOffset: 0,
                                                 groupNum: 1);

            conv2 = SlimMPSCnnConvolution.Create(kernelWidth: 5,
                                                 kernelHeight: 5,
                                                 inputFeatureChannels: 32,
                                                 outputFeatureChannels: 64,
                                                 neuronFilter: relu,
                                                 device: device,
                                                 kernelParamsBinaryName: "conv2",
                                                 padding: true,
                                                 strideX: 1,
                                                 strideY: 1,
                                                 destinationFeatureChannelOffset: 0,
                                                 groupNum: 1);

            // same as a 1x1 convolution filter to produce 1x1x10 from 1x1x1024
            fc1 = SlimMPSCnnFullyConnected.Create(kernelWidth: 7,
                                                  kernelHeight: 7,
                                                  inputFeatureChannels: 64,
                                                  outputFeatureChannels: 1024,
                                                  neuronFilter: null,
                                                  device: device,
                                                  kernelParamsBinaryName: "fc1",
                                                  destinationFeatureChannelOffset: 0);

            fc2 = SlimMPSCnnFullyConnected.Create(kernelWidth: 1,
                                                  kernelHeight: 1,
                                                  inputFeatureChannels: 1024,
                                                  outputFeatureChannels: 10,
                                                  neuronFilter: null,
                                                  device: device,
                                                  kernelParamsBinaryName: "fc2");
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("cube_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("cube_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 8 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            vertexBuffer = device.CreateBuffer(vertexData, MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);

            constantBuffer = device.CreateBuffer(64, MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            MTLRenderPipelineColorAttachmentDescriptor renderBufferAttachment = pipelineStateDescriptor.ColorAttachments[0];

            renderBufferAttachment.PixelFormat                 = mtkView.ColorPixelFormat;
            renderBufferAttachment.BlendingEnabled             = true;
            renderBufferAttachment.SourceRgbBlendFactor        = MTLBlendFactor.One;
            renderBufferAttachment.DestinationRgbBlendFactor   = MTLBlendFactor.SourceAlpha;
            renderBufferAttachment.SourceAlphaBlendFactor      = MTLBlendFactor.One;
            renderBufferAttachment.DestinationAlphaBlendFactor = MTLBlendFactor.OneMinusSourceAlpha;
            renderBufferAttachment.RgbBlendOperation           = MTLBlendOperation.Add;
            renderBufferAttachment.AlphaBlendOperation         = MTLBlendOperation.Add;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);
        }
Example #26
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("mesh_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("mesh_fragment");

            // Generate meshes
            MTKMeshBufferAllocator mtkBufferAllocator = new MTKMeshBufferAllocator(device);
            NSUrl     url       = NSBundle.MainBundle.GetUrlForResource("Fighter", "obj");
            MDLAsset  mdlAsset  = new MDLAsset(url, new MDLVertexDescriptor(), mtkBufferAllocator);
            MDLObject mdlObject = mdlAsset.GetObject(0);
            MDLMesh   mdlMesh   = mdlObject as MDLMesh;

            NSError error;

            objMesh = new MTKMesh(mdlMesh, device, out error);

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = MTLVertexDescriptor.FromModelIO(objMesh.VertexDescriptor);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 1, 2), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            this.proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);

            this.constantBuffer = device.CreateBuffer((uint)Marshal.SizeOf(this.param), MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat
            };

            pipelineStateDescriptor.ColorAttachments[0].PixelFormat = mtkView.ColorPixelFormat;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            NSImage          image            = NSImage.ImageNamed("Fighter_Diffuse.jpg");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.texture = mTKTextureLoader.FromCGImage(image.CGImage, new MTKTextureLoaderOptions(), out error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.ClampToEdge,
                TAddressMode = MTLSamplerAddressMode.ClampToEdge,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("cube_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("cube_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float3;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);
            vertexDescriptor.Attributes[2].Format      = MTLVertexFormat.Float2;
            vertexDescriptor.Attributes[2].BufferIndex = 0;
            vertexDescriptor.Attributes[2].Offset      = 7 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 9 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            // Primitive
            Torus(1.0f, 0.3f, 28, out List <PositionNormalTexture> vertexData, out List <ushort> indexData);

            vertexBuffer   = device.CreateBuffer(vertexData.ToArray(), MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);
            indexDataArray = indexData.ToArray();
            indexBuffer    = device.CreateBuffer(indexDataArray, MTLResourceOptions.CpuCacheModeDefault);

            // Use clock
            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            Vector3 cameraPosition = new Vector3(0, 0, 1.5f);

            this.view = CreateLookAt(cameraPosition, new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);


            // Constant Buffer
            this.param = new Parameters()
            {
                CameraPosition      = cameraPosition,
                WorldViewProjection = Matrix4.Identity,
                World = Matrix4.Identity,
                WorldInverseTranspose = Matrix4.Identity,
            };

            this.constantBuffer = device.CreateBuffer((uint)Marshal.SizeOf(this.param), MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            MTLRenderPipelineColorAttachmentDescriptor renderBufferAttachment = pipelineStateDescriptor.ColorAttachments[0];

            renderBufferAttachment.PixelFormat = mtkView.ColorPixelFormat;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);


            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            // Texture
            NSUrl url = NSBundle.MainBundle.GetUrlForResource("cubemap2", "ktx");

            this.texture = mTKTextureLoader.FromUrl(url, new MTKTextureLoaderOptions(), out error);

            Console.WriteLine("Failed to created pipeline state, error {0}", error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                MipFilter    = MTLSamplerMipFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.ClampToEdge,
                TAddressMode = MTLSamplerAddressMode.ClampToEdge,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);
        }
Example #28
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("cube_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("cube_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);
            vertexDescriptor.Attributes[2].Format      = MTLVertexFormat.Float2;
            vertexDescriptor.Attributes[2].BufferIndex = 0;
            vertexDescriptor.Attributes[2].Offset      = 8 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 10 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            vertexBuffer = device.CreateBuffer(vertexData, MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);

            this.constantBuffer1 = device.CreateBuffer((uint)Marshal.SizeOf(this.param), MTLResourceOptions.CpuCacheModeDefault);
            this.constantBuffer2 = device.CreateBuffer((uint)Marshal.SizeOf(this.param), MTLResourceOptions.CpuCacheModeDefault);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            MTLRenderPipelineColorAttachmentDescriptor renderBufferAttachment = pipelineStateDescriptor.ColorAttachments[0];

            renderBufferAttachment.PixelFormat = mtkView.ColorPixelFormat;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStencilState1Description = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true,
                FrontFaceStencil     = new MTLStencilDescriptor()
                {
                    WriteMask = 0xff,
                    StencilCompareFunction    = MTLCompareFunction.Always,
                    DepthStencilPassOperation = MTLStencilOperation.IncrementClamp,
                }
            };

            depthStencilState1 = device.CreateDepthStencilState(depthStencilState1Description);

            var depthStencilState2Description = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true,
                FrontFaceStencil     = new MTLStencilDescriptor()
                {
                    ReadMask  = 0xff,
                    WriteMask = 0x0,
                    StencilCompareFunction = MTLCompareFunction.NotEqual,
                }
            };

            depthStencilState2 = device.CreateDepthStencilState(depthStencilState2Description);

            // Texture
            NSImage          image            = NSImage.ImageNamed("crate.png");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.texture = mTKTextureLoader.FromCGImage(image.CGImage, new MTKTextureLoaderOptions(), out error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.Repeat,
                TAddressMode = MTLSamplerAddressMode.Repeat,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);
        }
Example #29
0
        void SetupMetal()
        {
            // Find a usable device
            device = MTLDevice.SystemDefault;

            // Create a new command queue
            commandQueue = device.CreateCommandQueue ();

            // Load all the shader files with a metal file extension in the project
            NSError error;

            defaultLibrary = device.CreateLibrary ("default.metallib", out error);

            // Setup metal layer and add as sub layer to view
            metalLayer = new CAMetalLayer ();
            metalLayer.Device = device;
            metalLayer.PixelFormat = MTLPixelFormat.BGRA8Unorm;

            // Change this to NO if the compute encoder is used as the last pass on the drawable texture
            metalLayer.FramebufferOnly = true;

            // Add metal layer to the views layer hierarchy
            metalLayer.Frame = View.Layer.Frame;
            View.Layer.AddSublayer (metalLayer);

            View.Opaque = true;
            View.BackgroundColor = null;
            View.ContentScaleFactor = UIScreen.MainScreen.Scale;
        }
Example #30
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            mtkView          = (MTKView)View;
            mtkView.Delegate = this;
            mtkView.Device   = device;

            mtkView.SampleCount              = 1;
            mtkView.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            mtkView.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            mtkView.PreferredFramesPerSecond = 60;
            mtkView.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction triangleVertexProgram = defaultLibrary.CreateFunction("triangle_vertex");
            IMTLFunction cubeVertexProgram     = defaultLibrary.CreateFunction("cube_vertex");

            // Load the fragment program into the library
            IMTLFunction triangleFragmentProgram = defaultLibrary.CreateFunction("triangle_fragment");
            IMTLFunction cubeFragmentProgram     = defaultLibrary.CreateFunction("cube_fragment");

            // Triangle vertex descriptor
            MTLVertexDescriptor triangleVertexDescriptor = new MTLVertexDescriptor();

            triangleVertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            triangleVertexDescriptor.Attributes[0].BufferIndex = 0;
            triangleVertexDescriptor.Attributes[0].Offset      = 0;
            triangleVertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float4;
            triangleVertexDescriptor.Attributes[1].BufferIndex = 0;
            triangleVertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);

            triangleVertexDescriptor.Layouts[0].Stride       = 8 * sizeof(float);
            triangleVertexDescriptor.Layouts[0].StepRate     = 1;
            triangleVertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            // Cube vertex descriptor
            MTLVertexDescriptor cubeVertexDescriptor = new MTLVertexDescriptor();

            cubeVertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            cubeVertexDescriptor.Attributes[0].BufferIndex = 0;
            cubeVertexDescriptor.Attributes[0].Offset      = 0;
            cubeVertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float2;
            cubeVertexDescriptor.Attributes[1].BufferIndex = 0;
            cubeVertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);

            cubeVertexDescriptor.Layouts[0].Stride       = 6 * sizeof(float);
            cubeVertexDescriptor.Layouts[0].StepRate     = 1;
            cubeVertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            // Create buffers
            triangleVertexBuffer = device.CreateBuffer(triangleVertexData, MTLResourceOptions.CpuCacheModeDefault);
            cubeVertexBuffer     = device.CreateBuffer(cubeVertexData, MTLResourceOptions.CpuCacheModeDefault);

            this.clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            this.view = CreateLookAt(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY);
            var aspect = (float)(View.Bounds.Size.Width / View.Bounds.Size.Height);

            this.proj = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, aspect, 0.1f, 100);
            this.cubeParameters.WorldViewProjection = Matrix4.Identity;
            cubeConstantBuffer = device.CreateBuffer((uint)Marshal.SizeOf(this.cubeParameters), MTLResourceOptions.CpuCacheModeDefault);

            // Create Pipeline Descriptor
            var trianglePipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = triangleVertexProgram,
                FragmentFunction             = triangleFragmentProgram,
                VertexDescriptor             = triangleVertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            var cubePipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = mtkView.SampleCount,
                VertexFunction               = cubeVertexProgram,
                FragmentFunction             = cubeFragmentProgram,
                VertexDescriptor             = cubeVertexDescriptor,
                DepthAttachmentPixelFormat   = mtkView.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = mtkView.DepthStencilPixelFormat,
            };

            MTLRenderPipelineColorAttachmentDescriptor triangleRenderBufferAttachment = trianglePipelineStateDescriptor.ColorAttachments[0];

            triangleRenderBufferAttachment.PixelFormat = mtkView.ColorPixelFormat;

            MTLRenderPipelineColorAttachmentDescriptor cubeRenderBufferAttachment = cubePipelineStateDescriptor.ColorAttachments[0];

            cubeRenderBufferAttachment.PixelFormat = mtkView.ColorPixelFormat;

            NSError error;

            trianglePipelineState = device.CreateRenderPipelineState(trianglePipelineStateDescriptor, out error);
            if (trianglePipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            cubePipelineState = device.CreateRenderPipelineState(cubePipelineStateDescriptor, out error);
            if (cubePipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStencilDescriptor = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthStencilState = device.CreateDepthStencilState(depthStencilDescriptor);

            // Texture
            NSImage          image            = NSImage.ImageNamed("crate.png");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.cubeTexture = mTKTextureLoader.FromCGImage(image.CGImage, new MTKTextureLoaderOptions(), out error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.Repeat,
                TAddressMode = MTLSamplerAddressMode.Repeat,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);

            // Create FrameBuffer texture
            IMTLTexture          drawableTexture   = mtkView.CurrentDrawable.Texture;
            MTLTextureDescriptor textureDescriptor = new MTLTextureDescriptor()
            {
                Width            = drawableTexture.Width,
                Height           = drawableTexture.Height,
                PixelFormat      = drawableTexture.PixelFormat,
                TextureType      = drawableTexture.TextureType,
                MipmapLevelCount = drawableTexture.MipmapLevelCount,
                ArrayLength      = drawableTexture.ArrayLength,
                SampleCount      = drawableTexture.SampleCount,
                Depth            = drawableTexture.Depth,
                CpuCacheMode     = drawableTexture.CpuCacheMode,
                Usage            = MTLTextureUsage.RenderTarget,
                StorageMode      = MTLStorageMode.Managed,
            };

            this.colorFrameBufferTexture = device.CreateTexture(textureDescriptor);
        }
Example #31
0
 private void PlatformConstruct(GraphicsDevice graphicsDevice)
 {
     _deviceCommandQueue = AddDisposable(graphicsDevice.Device.CreateCommandQueue());
 }
Example #32
0
 public AmtQueue(IAmtQueueRenderer renderer, IAmtSemaphoreEntrypoint entrypoint, IMTLCommandQueue presentQueue)
 {
     mRenderer     = renderer;
     mSignalModule = entrypoint;
     mPresentQueue = presentQueue;
 }
		void SetupMetal ()
		{
			// Set the view to use the default device.
			#if IOS
			device = MTLDevice.SystemDefault;
			#elif MAC
			// TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=32680
			var devicePointer = MTLCreateSystemDefaultDevice ();
			device = Runtime.GetINativeObject<IMTLDevice> (devicePointer, false);
			#endif
			// Create a new command queue.
			commandQueue = device.CreateCommandQueue ();

			// Load all the shader files with a metal file extension in the project.
			defaultLibrary = device.CreateDefaultLibrary ();
		}
Example #34
0
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (this.commandQueue != null)
                    {
                        this.commandQueue.Dispose();
                        this.commandQueue = null;
                    }

                    if (this.defaultLibrary != null)
                    {
                        this.defaultLibrary.Dispose();
                        this.defaultLibrary = null;
                    }

                    if (this.functionClothSim != null)
                    {
                        this.functionClothSim.Dispose();
                        this.functionClothSim = null;
                    }

                    if (this.functionNormalUpdate != null)
                    {
                        this.functionNormalUpdate.Dispose();
                        this.functionNormalUpdate = null;
                    }

                    if (this.functionNormalSmooth != null)
                    {
                        this.functionNormalSmooth.Dispose();
                        this.functionNormalSmooth = null;
                    }

                    if (this.pipelineStateClothSim != null)
                    {
                        this.pipelineStateClothSim.Dispose();
                        this.pipelineStateClothSim = null;
                    }

                    if (this.pipelineStateNormalUpdate != null)
                    {
                        this.pipelineStateNormalUpdate.Dispose();
                        this.pipelineStateNormalUpdate = null;
                    }

                    if (this.pipelineStateNormalSmooth != null)
                    {
                        this.pipelineStateNormalSmooth.Dispose();
                        this.pipelineStateNormalSmooth = null;
                    }

                    foreach (var item in this.clothData)
                    {
                        item.ClothNode.RemoveFromParentNode();
                        item.Dispose();
                    }

                    this.clothData.Clear();
                }

                this.disposed = true;
            }
        }
 void SetupMetal()
 {
     // Create a new command queue.
     commandQueue = metalView.Device.CreateCommandQueue();
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            // Load all the shader files with a metal file extension in the project
            defaultLibrary = device.CreateDefaultLibrary();

            // Setup view
            view          = (MTKView)View;
            view.Delegate = this;
            view.Device   = device;

            view.SampleCount              = 1;
            view.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            view.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            view.PreferredFramesPerSecond = 60;
            view.ClearColor = new MTLClearColor(0.5f, 0.5f, 0.5f, 1.0f);

            // Load the vertex program into the library
            IMTLFunction vertexProgram = defaultLibrary.CreateFunction("quad_vertex");

            // Load the fragment program into the library
            IMTLFunction fragmentProgram = defaultLibrary.CreateFunction("quad_fragment");

            // Create a vertex descriptor from the MTKMesh
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;
            vertexDescriptor.Attributes[1].Format      = MTLVertexFormat.Float2;
            vertexDescriptor.Attributes[1].BufferIndex = 0;
            vertexDescriptor.Attributes[1].Offset      = 4 * sizeof(float);

            vertexDescriptor.Layouts[0].Stride = 6 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerVertex;

            this.vertexBuffer = device.CreateBuffer(vertexData, MTLResourceOptions.CpuCacheModeDefault);// (MTLResourceOptions)0);

            this.mipmapping     = 0;
            this.constantBuffer = device.CreateBuffer(sizeof(float), MTLResourceOptions.CpuCacheModeDefault);
            SetConstantBuffer(this.mipmapping, constantBuffer);

            // Create a reusable pipeline state
            var pipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = view.SampleCount,
                VertexFunction               = vertexProgram,
                FragmentFunction             = fragmentProgram,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = view.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = view.DepthStencilPixelFormat
            };

            pipelineStateDescriptor.ColorAttachments[0].PixelFormat = view.ColorPixelFormat;

            NSError error;

            pipelineState = device.CreateRenderPipelineState(pipelineStateDescriptor, out error);
            if (pipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            var depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            // Texture KTX
            NSUrl            url = NSBundle.MainBundle.GetUrlForResource("crate", "ktx");
            MTKTextureLoader mTKTextureLoader = new MTKTextureLoader(device);

            this.texture = mTKTextureLoader.FromUrl(url, new MTKTextureLoaderOptions(), out error);

            Console.WriteLine("Failed to created pipeline state, error {0}", error);

            MTLSamplerDescriptor samplerDescriptor = new MTLSamplerDescriptor()
            {
                MinFilter    = MTLSamplerMinMagFilter.Linear,
                MagFilter    = MTLSamplerMinMagFilter.Linear,
                MipFilter    = MTLSamplerMipFilter.Linear,
                SAddressMode = MTLSamplerAddressMode.ClampToEdge,
                TAddressMode = MTLSamplerAddressMode.ClampToEdge,
            };

            this.sampler = device.CreateSamplerState(samplerDescriptor);

            this.clock = new System.Diagnostics.Stopwatch();
            this.clock.Start();
            this.time = 0;
        }
Example #37
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Set the view to use the default device
            device = MTLDevice.SystemDefault;

            if (device == null)
            {
                Console.WriteLine("Metal is not supported on this device");
                View = new NSView(View.Frame);
            }

            // Create a new command queue
            commandQueue = device.CreateCommandQueue();

            NSError error;

            // Setup view
            view          = (MTKView)View;
            view.Delegate = this;
            view.Device   = device;

            view.SampleCount              = 1;
            view.DepthStencilPixelFormat  = MTLPixelFormat.Depth32Float_Stencil8;
            view.ColorPixelFormat         = MTLPixelFormat.BGRA8Unorm;
            view.PreferredFramesPerSecond = 60;
            view.ClearColor = new MTLClearColor(0, 0, 0, 1.0f);

            // Functions
            var source = System.IO.File.ReadAllText("Triangle.metal");
            MTLCompileOptions compileOptions = new MTLCompileOptions()
            {
                LanguageVersion = MTLLanguageVersion.v2_0,
            };

            IMTLLibrary  customLibrary    = device.CreateLibrary(source, compileOptions, out error);
            IMTLFunction kernelFunction   = customLibrary.CreateFunction("tessellation_kernel_triangle");
            IMTLFunction vertexFunction   = customLibrary.CreateFunction("tessellation_vertex_triangle");
            IMTLFunction fragmentFunction = customLibrary.CreateFunction("tessellation_fragment");

            // Create a vertex descriptor
            MTLVertexDescriptor vertexDescriptor = new MTLVertexDescriptor();

            vertexDescriptor.Attributes[0].Format      = MTLVertexFormat.Float4;
            vertexDescriptor.Attributes[0].BufferIndex = 0;
            vertexDescriptor.Attributes[0].Offset      = 0;

            vertexDescriptor.Layouts[0].Stride = 4 * sizeof(float);

            vertexDescriptor.Layouts[0].StepRate     = 1;
            vertexDescriptor.Layouts[0].StepFunction = MTLVertexStepFunction.PerPatchControlPoint;

            // Create RenderPipeline
            var renderPipelineStateDescriptor = new MTLRenderPipelineDescriptor
            {
                SampleCount                  = view.SampleCount,
                VertexFunction               = vertexFunction,
                FragmentFunction             = fragmentFunction,
                VertexDescriptor             = vertexDescriptor,
                DepthAttachmentPixelFormat   = view.DepthStencilPixelFormat,
                StencilAttachmentPixelFormat = view.DepthStencilPixelFormat,

                MaxTessellationFactor             = 16,
                IsTessellationFactorScaleEnabled  = false,
                TessellationFactorFormat          = MTLTessellationFactorFormat.Half,
                TessellationControlPointIndexType = MTLTessellationControlPointIndexType.None,
                TessellationFactorStepFunction    = MTLTessellationFactorStepFunction.Constant,
                TessellationOutputWindingOrder    = MTLWinding.Clockwise,
                TessellationPartitionMode         = MTLTessellationPartitionMode.FractionalEven,
            };

            renderPipelineStateDescriptor.ColorAttachments[0].PixelFormat = view.ColorPixelFormat;

            renderPipelineState = device.CreateRenderPipelineState(renderPipelineStateDescriptor, out error);
            if (renderPipelineState == null)
            {
                Console.WriteLine("Failed to created pipeline state, error {0}", error);
            }

            MTLDepthStencilDescriptor depthStateDesc = new MTLDepthStencilDescriptor
            {
                DepthCompareFunction = MTLCompareFunction.Less,
                DepthWriteEnabled    = true
            };

            depthState = device.CreateDepthStencilState(depthStateDesc);

            computePipelineState = device.CreateComputePipelineState(kernelFunction, out error);

            // Buffers
            tessellationFactorsBuffer       = device.CreateBuffer(256, MTLResourceOptions.StorageModePrivate);
            tessellationFactorsBuffer.Label = "Tessellation Factors";

            controlPointsBuffer       = device.CreateBuffer(controlPointPositionsTriangle, MTLResourceOptions.StorageModeManaged);
            controlPointsBuffer.Label = "Control Points Triangle";
        }