diff --git a/src/canvas.nim b/src/canvas.nim new file mode 100644 index 0000000..a78b513 --- /dev/null +++ b/src/canvas.nim @@ -0,0 +1,128 @@ +import "./tuple" +import strformat, strutils + +type Colour* = Tuple4 + +proc colour*(red: float, green: float, blue: float): Colour = Colour(x: red, y: green, z: blue, w: 0) +proc red*(c: Colour): float = c.x +proc green*(c: Colour): float = c.y +proc blue*(c: Colour): float = c.z + +proc `*`*(lhs, rhs: Colour): Colour = colour(lhs.red * rhs.red, lhs.green * rhs.green, lhs.blue * rhs.blue) + +type + Canvas* = object + pixels: seq[seq[Colour]] + width*: int + height*: int + +proc canvas*(width, height: int): Canvas = + result.width = width + result.height = height + result.pixels = newSeq[seq[Colour]](height) + for i in 0.. 69): + result[high(result)] = '\n' + length = 0 + result.add(redValue & " ") + length += len(redValue) + 1 + let greenValue = intToStr(toInt(canvas.pixelAt(x, y).green.clamp(0.0, 1.0) * 255)) + if(len(greenValue) + length > 69): + result[high(result)] = '\n' + length = 0 + result.add(greenValue & " ") + length += len(greenValue) + 1 + let blueValue = intToStr(toInt(canvas.pixelAt(x, y).blue.clamp(0.0, 1.0) * 255)) + if(len(blueValue) + length > 69): + result[high(result)] = '\n' + length = 0 + result.add(blueValue & " ") + length += len(blueValue) + 1 + result[high(result)] = '\n' + length = 0 + + + +when isMainModule: + import unittest + suite "canvas": + test "Colour creation": + let t1 = colour(-0.5, 0.4, 1.7) + check(t1.red == -0.5) + check(t1.green == 0.4) + check(t1.blue == 1.7) + + test "Colour addition": + let t1 = colour(0.9, 0.6, 0.75) + let t2 = colour(0.7, 0.1, 0.25) + check(t1 + t2 == colour(1.6, 0.7, 1.0)) + + test "Colour subtraction": + let t1 = colour(0.9, 0.6, 0.75) + let t2 = colour(0.7, 0.1, 0.25) + check(t1 - t2 == colour(0.2, 0.5, 0.5)) + + test "Multiply colour by scalar": + check(colour(0.2, 0.3, 0.4) * 2 == colour(0.4, 0.6, 0.8)) + + test "Multiply colours": + let t1 = colour(1, 0.2, 0.4) + let t2 = colour(0.9, 1, 0.1) + check(t1 * t2 == colour(0.9, 0.2, 0.04)) + + test "Create canvas": + var canvas = canvas(10, 20) + check(canvas.width == 10) + check(canvas.height == 20) + let black = colour(0,0,0) + for i in 0..