Skip to content

Commit

Permalink
Solidify a bit for StackOverflow help
Browse files Browse the repository at this point in the history
  • Loading branch information
SaganRitual committed May 12, 2020
1 parent 402379c commit 1e78735
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 259 deletions.
10 changes: 1 addition & 9 deletions Foil.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

/* Begin PBXBuildFile section */
D42B958B24648E2900F4B5B0 /* FoilShaders.metal in Sources */ = {isa = PBXBuildFile; fileRef = D42B958A24648E2900F4B5B0 /* FoilShaders.metal */; };
D462CC9D2466652400D79B48 /* LikeObjcSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = D462CC9C2466652400D79B48 /* LikeObjcSync.swift */; };
D475693E2469259D000F87AE /* OFoilRenderer.m in Sources */ = {isa = PBXBuildFile; fileRef = D475693D2469259D000F87AE /* OFoilRenderer.m */; };
D4AC68B8245CF43F00917569 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4AC68B7245CF43F00917569 /* AppDelegate.swift */; };
D4AC68BA245CF43F00917569 /* FoilViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4AC68B9245CF43F00917569 /* FoilViewController.swift */; };
D4AC68BC245CF44000917569 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D4AC68BB245CF44000917569 /* Assets.xcassets */; };
Expand All @@ -23,9 +21,7 @@

/* Begin PBXFileReference section */
D42B958A24648E2900F4B5B0 /* FoilShaders.metal */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.metal; path = FoilShaders.metal; sourceTree = "<group>"; };
D462CC9C2466652400D79B48 /* LikeObjcSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LikeObjcSync.swift; sourceTree = "<group>"; };
D475693C2469259D000F87AE /* Foil-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Foil-Bridging-Header.h"; sourceTree = "<group>"; };
D475693D2469259D000F87AE /* OFoilRenderer.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = OFoilRenderer.m; sourceTree = "<group>"; };
D475693F24692638000F87AE /* FoilShaderTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FoilShaderTypes.h; sourceTree = "<group>"; };
D47569402469267E000F87AE /* FoilKernelTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FoilKernelTypes.h; sourceTree = "<group>"; };
D4AC68B4245CF43F00917569 /* Foil.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Foil.app; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -79,12 +75,10 @@
D4AC68BB245CF44000917569 /* Assets.xcassets */,
D4AC68B7245CF43F00917569 /* AppDelegate.swift */,
D4AC68C1245CF44000917569 /* Foil.entitlements */,
D475693C2469259D000F87AE /* Foil-Bridging-Header.h */,
D4AC68B9245CF43F00917569 /* FoilViewController.swift */,
D4AC68C0245CF44000917569 /* Info.plist */,
D462CC9C2466652400D79B48 /* LikeObjcSync.swift */,
D4AC68BD245CF44000917569 /* Main.storyboard */,
D475693D2469259D000F87AE /* OFoilRenderer.m */,
D475693C2469259D000F87AE /* Foil-Bridging-Header.h */,
);
path = Foil;
sourceTree = "<group>";
Expand Down Expand Up @@ -191,12 +185,10 @@
files = (
D4BE16FE2463F0E10085FD3C /* FoilKernels.metal in Sources */,
D4AC68C9245CF57A00917569 /* FoilRenderer.swift in Sources */,
D462CC9D2466652400D79B48 /* LikeObjcSync.swift in Sources */,
D4AC68BA245CF43F00917569 /* FoilViewController.swift in Sources */,
D42B958B24648E2900F4B5B0 /* FoilShaders.metal in Sources */,
D4F680AC245FACB3000B8EF2 /* FoilSimulation.swift in Sources */,
D4F680BE24639638000B8EF2 /* FoilMathUtilities.swift in Sources */,
D475693E2469259D000F87AE /* OFoilRenderer.m in Sources */,
D4AC68B8245CF43F00917569 /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
146 changes: 22 additions & 124 deletions Foil/FoilViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@
import Cocoa
import MetalKit

class FoilViewController: NSViewController, MTKViewDelegate {
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
assert(false)
}

class FoilViewController: NSViewController {
let IntelGPUInMetalDevicesArray = 0
let RadeonGPUInMetalDevicesArray = 1

Expand All @@ -36,8 +32,6 @@ class FoilViewController: NSViewController, MTKViewDelegate {

static let FoilNumSimulationConfigs = FoilSimulationConfigTable.count

// var _view: MTKView { guard let v = self.view as? MTKView else { fatalError() }; return v }
var _view: MTKView { (self.view as? MTKView)! }
var renderer: FoilRenderer!
var simulation: FoilSimulation!

Expand Down Expand Up @@ -88,18 +82,18 @@ class FoilViewController: NSViewController, MTKViewDelegate {
super.viewDidLoad()
selectDevices()

_view.delegate = self
// _view.delegate = self
}

override func viewDidAppear() { beginSimulation() }

override func viewDidDisappear() {
viewControllerispatchQueue.sync {
// Stop simulation if on another thread
self.simulation.halt = true;
self.simulation.halt = true

// Indicate that simulation should not continue and results will not be needed
self.terminateAllSimulations = true;
self.terminateAllSimulations = true
}
}

Expand All @@ -108,140 +102,43 @@ class FoilViewController: NSViewController, MTKViewDelegate {

precondition(!availableDevices.isEmpty, "Metal is not supported on this Mac")

computeDevice = availableDevices[IntelGPUInMetalDevicesArray]
computeDevice = availableDevices[RadeonGPUInMetalDevicesArray]
NSLog("Selected compute device: \(computeDevice.name)")

// Select renderer device
let rendererDevice = availableDevices[IntelGPUInMetalDevicesArray]

if rendererDevice !== _view.device {
_view.device = rendererDevice;
let rendererDevice = availableDevices[RadeonGPUInMetalDevicesArray]

NSLog("New render device: '\(rendererDevice.name)', drawableSize \(_view.drawableSize)")
renderer = FoilRenderer(self, rendererDevice)

renderer = FoilRenderer(_view)
renderer.drawableSizeWillChange(size: _view.drawableSize)
}
NSLog("New render device: \"\(rendererDevice.name)\"")
}

func beginSimulation() {
simulationTime = 0;
simulationTime = 0

_simulationName.stringValue = "Simulation \(configNum)"
config = FoilViewController.FoilSimulationConfigTable[configNum]

simulation = FoilSimulation(computeDevice: computeDevice, config: config)

renderer.setRenderScale(renderScale: config.renderScale, drawableSize: _view.drawableSize)
renderer.setRenderScale(renderScale: config.renderScale)

NSLog("Starting Simulation Config: \(configNum)");
commandQueue = renderer.device.makeCommandQueue()

if computeDevice === renderer.device {
// If the device used for rendering and compute are the same, create a command queue shared
// by both components
commandQueue = renderer.device.makeCommandQueue()
} else {
// If the device used for rendering is different than that used for compute, run the
// the simulation asynchronously on the compute device
runSimulationOnAlternateDevice()
}
NSLog("Starting Simulation Config: \(configNum)")
}

// Asynchronously begins or continues a simulation on a different than the device used for rendering
func runSimulationOnAlternateDevice() {
assert(computeDevice !== renderer.device)

commandQueue = nil;

let updateHandler: (NSData, CFAbsoluteTime) -> () = {
// Update the renderer's position data so that it can show forward progress
self.updateWithNewPositionData(updateData: $0, forSimulationTime: $1)
}

let dataProvider: (NSData, NSData, CFAbsoluteTime) -> () = {
self.handleFullyProvidedSetOfPositionData(positionData: $0, velocityData: $1, forSimulationTime: $2)
}

simulation.runAsyncWithUpdateHandler(updateHandler: updateHandler, dataProvider: dataProvider)
}

/// Receive and update of new positions for the simulation time given.
func updateWithNewPositionData(updateData: NSData, forSimulationTime simulationTime: CFAbsoluteTime) {
// Lock with updateData so thus thread does not update data during an update on another thread
dataUpdateDispatchQueue.sync {
// Update the renderer's position data so that it can show forward progress
self.renderer.providePositionData(data: updateData)
}

viewControllerispatchQueue.sync {
// Lock around _simulation time since it will be accessed on another thread
self.simulationTime = simulationTime;
}
}

// Handle the passing of full data set from asynchronous simulation executed on device different
// the the device used for rendering
func handleFullyProvidedSetOfPositionData(
positionData: NSData, velocityData: NSData,
forSimulationTime simulationTime: CFAbsoluteTime
) {
viewControllerispatchQueue.sync {
if self.terminateAllSimulations {
NSLog("Terminating all simulations")
return
}

self.simulationTime = simulationTime;

if simulationTime >= config.simDuration {
NSLog("Simulation Config \(configNum) Complete")

// If the simulation is complete, provide all the final positions to render
renderer.providePositionData(data: positionData)
} else {
NSLog("Simulation Config \(configNum) Cannot complete with current simulation object")

// If the simulation is not complete, this indicates that compute device cannot complete
// the simulation, so data has been transferred from that device so the app can continue
// the simulation on another device

// Reselect a new device to continue the simulation
selectDevices()

// Create a new simulation object with the data provided
self.simulation = FoilSimulation(
computeDevice: computeDevice, config: config,
positionData: positionData, velocityData: velocityData,
simulationTime: simulationTime
)

if computeDevice === renderer.device {
// If the device used for rendering and compute are the same, create a command queue shared
// by both components
commandQueue = renderer.device.makeCommandQueue()
} else {
// If the device used for rendering is different than that used for compute, run the
// the simulation asynchronously on the compute device
runSimulationOnAlternateDevice()
}
}
}
}

/// Called whenever view changes orientation or layout is changed
func drawableSizeWillChange(size: CGSize) { renderer.drawableSizeWillChange(size: size) }

static let FoilSecondsToPresentSimulationResults = CFTimeInterval(4.0)

/// Called whenever the view needs to render
func draw(in view: MTKView) {
// Number of bodies to render this frame
var numBodies = config.renderBodies;
var numBodies = config.renderBodies

// Handle simulations completion
if(simulationTime >= config.simDuration) {
// If the simulation is over, render all the bodies in the simulation to show final results
numBodies = config.numBodies;
numBodies = config.numBodies

if(continuationTime == 0) {
continuationTime = CACurrentMediaTime() + FoilViewController.FoilSecondsToPresentSimulationResults
Expand All @@ -256,8 +153,8 @@ class FoilViewController: NSViewController, MTKViewDelegate {
}

let animationCompletion: () -> () = {
self._simulationName.alphaValue = 1.0;
self._simulationPercentage.alphaValue = 1.0;
self._simulationName.alphaValue = 1.0
self._simulationPercentage.alphaValue = 1.0
}

let blinkyBlock: (Timer) -> () = { timer in
Expand All @@ -270,9 +167,9 @@ class FoilViewController: NSViewController, MTKViewDelegate {

} else if(CACurrentMediaTime() >= continuationTime) {
// If the continuation time has been reached, select a new simulation and begin execution
configNum = (configNum + 1) % FoilViewController.FoilNumSimulationConfigs;
configNum = (configNum + 1) % FoilViewController.FoilNumSimulationConfigs

continuationTime = 0;
continuationTime = 0

blinker.invalidate()
blinker = nil
Expand All @@ -297,8 +194,9 @@ class FoilViewController: NSViewController, MTKViewDelegate {

// Render the updated positions (or all positions in the case that the simulation is complete)
renderer.drawWithCommandBuffer(
commandBuffer: commandBuffer, positionsBuffer: positionBuffer,
numBodies: numBodies, view: _view
commandBuffer: commandBuffer,
positionsBuffer: positionBuffer,
numBodies: numBodies
)

commandBuffer.commit()
Expand All @@ -307,7 +205,7 @@ class FoilViewController: NSViewController, MTKViewDelegate {

simulationTime += Double(config.simInterval)
} else {
renderer.drawProvidedPositionDataWithNumBodies(numParticles: numBodies, inView: _view)
renderer.drawProvidedPositionDataWithNumBodies(numParticles: numBodies)
}

var percentComplete = 0
Expand Down
15 changes: 0 additions & 15 deletions Foil/LikeObjcSync.swift

This file was deleted.

9 changes: 0 additions & 9 deletions Foil/OFoilRenderer.m

This file was deleted.

12 changes: 6 additions & 6 deletions Renderer/FoilMathUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ enum FoilMath {
var rand = vector_float3()

repeat {
rand = generateRandomVector(min, max);
rand = generateRandomVector(min, max)
} while(simd_length(rand) > maxlength)

return simd_normalize(rand)
}

static func generateRandomVector(_ min: Float, _ max: Float) -> vector_float3 {
let range = max - min;
let range = max - min

let x = Float.random(in: 0..<1) * range + min;
let y = Float.random(in: 0..<1) * range + min;
let z = Float.random(in: 0..<1) * range + min;
let x = Float.random(in: 0..<1) * range + min
let y = Float.random(in: 0..<1) * range + min
let z = Float.random(in: 0..<1) * range + min

return vector_float3(x, y, z)
}
Expand All @@ -28,7 +28,7 @@ enum FoilMath {
2 / (right - left), 0, 0, (left + right) / (left - right),
0, 2 / (top - bottom), 0, (top + bottom) / (bottom - top),
0, 0, 1 / (farZ - nearZ), nearZ / (nearZ - farZ),
0, 0, 0, 1 );
0, 0, 0, 1 )
}

static func matriMakeRows(
Expand Down
Loading

0 comments on commit 1e78735

Please sign in to comment.