Skip to content

Instantly share code, notes, and snippets.

@ochrons
Last active April 25, 2016 20:41
Show Gist options
  • Save ochrons/2b88a446ebc5711462bbad08cacc4d87 to your computer and use it in GitHub Desktop.
Save ochrons/2b88a446ebc5711462bbad08cacc4d87 to your computer and use it in GitHub Desktop.
Hilber curve demonstration in ScalaFiddle
// $FiddleDependency org.scala-js %%% scalajs-dom % 0.9.0
// $FiddleDependency com.lihaoyi %%% scalatags % 0.5.4
import scalatags.JsDom.all._
import org.scalajs.dom
import fiddle.Fiddle, Fiddle.println
import scalajs.js
object ScalaFiddle extends js.JSApp {
def main() = {
// $FiddleStart
import scala.util.Random
case class Point(x: Int, y: Int)
def hilbert(n: Int, d: Int): Point = {
var rx = 0
var ry = 0
var s = 1
var t = d
var p = Point(0, 0)
while(s < n) {
rx = 1 & (t/2)
ry = 1 & (t ^ rx)
p = rot(s, p, rx, ry)
p = Point(p.x + s*rx, p.y + s*ry)
t /= 4
s *= 2
}
p
}
def rot(n: Int, p: Point, rx: Int, ry: Int): Point = {
var np = p
if (ry == 0) {
if (rx == 1) {
np = Point(n-1 - np.x, n-1 - np.y)
}
//Swap x and y
np = Point(np.y, np.x)
}
np
}
def randomColor =
s"rgb(${Random.nextInt(240)}, ${Random.nextInt(240)}, ${Random.nextInt(240)})"
val order = 64
val factor = math.min(Fiddle.canvas.height, Fiddle.canvas.width) / order.toDouble
val maxD = order * order
var d = 0
var p = hilbert(order, d)
Fiddle.draw.strokeStyle = randomColor
Fiddle.draw.lineWidth = 2
Fiddle.draw.lineCap = "square"
Fiddle.schedule(10) {
import Fiddle.draw._
beginPath
moveTo(p.x * factor, p.y * factor)
p = hilbert(order, d)
lineTo(p.x * factor, p.y * factor)
stroke
d += 1
if(d >= maxD) {
d = 1
Fiddle.draw.strokeStyle = randomColor
p = hilbert(order, 0)
}
}
// $FiddleEnd
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment