Instead of using map(), try just modifying the Points directly for diamond corners

This commit is contained in:
Eryn Wells 2018-11-11 22:13:52 -05:00
parent 50d895afa1
commit ebfe3b5d57

View file

@ -137,8 +137,8 @@ class RandomAlgorithm: Kernel, TerrainGenerator {
/// - https://en.wikipedia.org/wiki/Diamond-square_algorithm /// - https://en.wikipedia.org/wiki/Diamond-square_algorithm
public class DiamondSquareGenerator: TerrainGenerator { public class DiamondSquareGenerator: TerrainGenerator {
public struct Point { public struct Point {
let x: Int var x: Int
let y: Int var y: Int
init() { init() {
self.init(x: 0, y: 0) self.init(x: 0, y: 0)
@ -151,8 +151,8 @@ public class DiamondSquareGenerator: TerrainGenerator {
} }
public struct Size { public struct Size {
let w: Int var w: Int
let h: Int var h: Int
var half: Size { var half: Size {
return Size(w: w / 2, h: h / 2) return Size(w: w / 2, h: h / 2)
@ -160,8 +160,8 @@ public class DiamondSquareGenerator: TerrainGenerator {
} }
public struct Box { public struct Box {
let origin: Point var origin: Point
let size: Size var size: Size
var corners: [Point] { var corners: [Point] {
return [northwest, southwest, northeast, northwest] return [northwest, southwest, northeast, northwest]
@ -294,23 +294,22 @@ public class DiamondSquareGenerator: TerrainGenerator {
/// Find our diamond's corners, wrapping around the grid if needed. /// Find our diamond's corners, wrapping around the grid if needed.
func diamondCorners(forPoint pt: Point, diamondSize: Size) -> [Point] { func diamondCorners(forPoint pt: Point, diamondSize: Size) -> [Point] {
let halfSize = diamondSize.half let halfSize = diamondSize.half
let n = Point(x: pt.x, y: pt.y - halfSize.h) var corners = [Point(x: pt.x, y: pt.y - halfSize.h),
let w = Point(x: pt.x - halfSize.w, y: pt.y) Point(x: pt.x - halfSize.w, y: pt.y),
let s = Point(x: pt.x, y: pt.y + halfSize.h) Point(x: pt.x, y: pt.y + halfSize.h),
let e = Point(x: pt.x + halfSize.w, y: pt.y) Point(x: pt.x + halfSize.w, y: pt.y)]
return [n, w, s, e].map { (p: Point) -> Point in for i in 0..<corners.count {
if p.x < 0 { if corners[i].x < 0 {
return Point(x: p.x + grid.size.w - 1, y: p.y) corners[i].x += grid.size.w - 1
} else if p.x >= grid.size.w { } else if corners[i].x >= grid.size.w {
return Point(x: p.x - grid.size.w + 1, y: p.y) corners[i].x -= grid.size.w - 1
} else if p.y < 0 { } else if corners[i].y < 0 {
return Point(x: p.x, y: p.y + grid.size.h - 1) corners[i].y += grid.size.h - 1
} else if p.y >= grid.size.h { } else if corners[i].y >= grid.size.h {
return Point(x: p.x, y: p.y - grid.size.h + 1) corners[i].y -= grid.size.h - 1
} else {
return p
} }
} }
return corners
} }
func average(ofPoints pts: [Float]) -> Float { func average(ofPoints pts: [Float]) -> Float {