aboutsummaryrefslogtreecommitdiff
path: root/drawing.ha
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2024-03-22 19:38:29 +0000
committerubq323 <ubq323@ubq323.website>2024-03-22 19:38:29 +0000
commitd302628e8665572bc515c254a8d52909cc6db2ae (patch)
treebdff2d6e6213b8bd2f6221ee0798e1f39806b871 /drawing.ha
parent32f8d37ad94a9ea3413c3f9587bb2000f14c61d1 (diff)
refactor
Diffstat (limited to 'drawing.ha')
-rw-r--r--drawing.ha65
1 files changed, 65 insertions, 0 deletions
diff --git a/drawing.ha b/drawing.ha
new file mode 100644
index 0000000..ff2aa71
--- /dev/null
+++ b/drawing.ha
@@ -0,0 +1,65 @@
+use sdl2;
+
+
+// 2d position, x and y
+type pos = (int, int);
+
+type drawing_state = struct {
+ // is the mouse button held down?
+ drawing: bool,
+ pos: pos,
+ picture: picture,
+};
+
+type picture = struct {
+ d: *[*]u32,
+ w: size,
+ h: size,
+};
+// Returns array index of the pixel at position pos.
+// Bounds check happens in here instead of using a slice type, so
+// that it's easier to remove later.
+fn pidx(pic: *picture, pos: pos) size = {
+ const (x,y) = pos;
+ const (xs,ys) = (x:size, y:size);
+ assert(0 <= x, "x position must not be less than 0");
+ assert(0 <= y, "y position must not be less than 0");
+ assert(xs < pic.w, "x position must be less than picture width");
+ assert(ys < pic.h, "y position must be less than picture height");
+
+ return xs + pic.w*ys;
+};
+fn pic_set(pic: *picture, pos: pos, val: u32) void = pic.d[pidx(pic,pos)] = val;
+fn picture_from_surface(surf: *sdl2::SDL_Surface) picture = picture {
+ w = surf.w: size,
+ h = surf.h: size,
+ d = (surf.pixels as *opaque: *[*]u32),
+};
+
+fn min(a: int, b: int) int = if (a<b) a else b;
+fn max(a: int, b: int) int = if (a<b) b else a;
+
+fn circle(dstate: *drawing_state, c: pos, r: int, color: u32) void = {
+ const (cx,cy) = c;
+ const ymin = max(0, cy-r);
+ const ymax = min(dstate.picture.h:int-1, cy+r);
+ const xmin = max(0, cx-r);
+ const xmax = min(dstate.picture.w:int-1, cx+r);
+
+ const r2 = r*r + r;
+
+ for (let y = ymin; y<=ymax; y+=1) {
+ const yd = y-cy;
+ for (let x = xmin; x<=xmax; x+=1) {
+ const xd = x-cx;
+ if (yd*yd + xd*xd <= r2) {
+ pic_set(&dstate.picture, (x,y), color);
+ };
+ };
+ };
+
+};
+
+fn do_drawing(dstate: *drawing_state) void = {
+ if (dstate.drawing) circle(dstate, dstate.pos, 20, 0xff0088);
+};