Skip to content

Commit

Permalink
added memory
Browse files Browse the repository at this point in the history
  • Loading branch information
mhorga authored May 1, 2017
1 parent 048dc00 commit 307e7e6
Show file tree
Hide file tree
Showing 8 changed files with 40,314 additions and 0 deletions.
50 changes: 50 additions & 0 deletions memory/memory.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@

import MetalKit

let device = MTLCreateSystemDefaultDevice()!
let queue = device.makeCommandQueue()
let count = 1500
var myVector = [Float](repeating: 0, count: count)
var length = count * MemoryLayout<Float>.size
//print(length)
var outBuffer = device.makeBuffer(bytes: myVector, length: length, options: [])
for (index, value) in myVector.enumerated() { myVector[index] = Float(index) }
var inBuffer = device.makeBuffer(bytes: myVector, length: length, options: [])

let path = Bundle.main.path(forResource: "memory", ofType: "metal")
let input = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
let library = try device.makeLibrary(source: input, options: nil)
let function = library.makeFunction(name: "compute")!
let computePipelineState = try! device.makeComputePipelineState(function: function)

let commandBuffer = queue.makeCommandBuffer()
let encoder = commandBuffer.makeComputeCommandEncoder()
encoder.setComputePipelineState(computePipelineState)
encoder.setBuffer(inBuffer, offset: 0, at: 0)
encoder.setBuffer(outBuffer, offset: 0, at: 1)
let size = MTLSize(width: count, height: 1, depth: 1)
encoder.dispatchThreadgroups(size, threadsPerThreadgroup: size)
encoder.endEncoding()
commandBuffer.commit()

let result = outBuffer.contents().bindMemory(to: Float.self, capacity: count)
var data = [Float](repeating:0, count: count)
for i in 0 ..< count { data[i] = result[i] }
data.map { $0 }

import ModelIO

guard let url = Bundle.main.url(forResource: "teapot", withExtension: "obj") else { fatalError() }
let asset = MDLAsset(url: url)
let voxelArray = MDLVoxelArray(asset: asset, divisions: 10, patchRadius: 0)
if let data = voxelArray.voxelIndices() {
data.withUnsafeBytes { (voxels: UnsafePointer<MDLVoxelIndex>) -> Void in
let count = data.count / MemoryLayout<MDLVoxelIndex>.size
var voxelIndex = voxels
for _ in 0..<count {
let position = voxelArray.spatialLocation(ofIndex: voxelIndex.pointee)
print(position)
voxelIndex = voxelIndex.successor()
}
}
}
10 changes: 10 additions & 0 deletions memory/memory.playground/Resources/memory.metal
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

#include <metal_stdlib>
using namespace metal;

kernel void compute(const device float *inVector [[ buffer(0) ]],
device float *outVector [[ buffer(1) ]],
uint id [[ thread_position_in_grid ]])
{
outVector[id] = 1.0 / (1.0 + exp(-inVector[id]));
}
Loading

0 comments on commit 307e7e6

Please sign in to comment.