summaryrefslogtreecommitdiff
path: root/src/main/smp/sys/draw
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-08-10 11:11:18 -0700
committerCliff Click <cliffc@acm.org>2026-11-15 11:20:40 -0800
commit658289861e8d971cd9e449e66a749c9c2d65f623 (patch)
tree209a32ef7fab1d27222121bc8b53a968ff4b6796 /src/main/smp/sys/draw
parent77ae05305a5653a2353709564705819f201e587f (diff)
downloadSimple-658289861e8d971cd9e449e66a749c9c2d65f623.tar.gz
Simple-658289861e8d971cd9e449e66a749c9c2d65f623.zip
Chapter 31: Software Drawing, Time, and Graphical Gameslinear
Co-authored-by: Hsiang-Ying Fu <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: fuhsnn <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: Symious <14933944+symious@users.noreply.github.com> Co-authored-by: Jun Kawasaki <jun784@gmail.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Diffstat (limited to 'src/main/smp/sys/draw')
-rw-r--r--src/main/smp/sys/draw/Button.smp41
-rw-r--r--src/main/smp/sys/draw/Canvas.smp201
-rw-r--r--src/main/smp/sys/draw/README.md124
3 files changed, 366 insertions, 0 deletions
diff --git a/src/main/smp/sys/draw/Button.smp b/src/main/smp/sys/draw/Button.smp
new file mode 100644
index 00000000..c90ed2d3
--- /dev/null
+++ b/src/main/smp/sys/draw/Button.smp
@@ -0,0 +1,41 @@
+// Feed pointer state once per event-loop iteration. Activate on release inside,
+// only after a press that began inside. No native/window dependency.
+struct Button {
+ int x, y, width, height;
+ u8[~] !label;
+ bool !enabled = true, !hovered = false, !pressed = false;
+ bool !_held = false, !_armed = false;
+ new Button = { int px, int py, int w, int h, u8[~] text ->
+ x = px; y = py; width = w; height = h; label = text;
+ };
+ val contains = { i64 px, i64 py ->
+ if( width <= 0 || height <= 0 ) return false;
+ i64 right = x, bottom = y; right += width; bottom += height;
+ if( px < x || py < y || px >= right || py >= bottom ) return false;
+ return true;
+ };
+ val update = { i64 px, i64 py, bool down ->
+ hovered = false;
+ if( enabled ) hovered = contains(px,py);
+ if( !enabled ) _armed = false;
+ if( down && !_held ) _armed = hovered;
+ var clicked = false;
+ if( !down ) if( _held ) if( _armed ) if( hovered ) clicked = true;
+ if( !down ) _armed = false;
+ _held = down;
+ pressed = false;
+ if( down ) if( _armed ) if( hovered ) pressed = true;
+ return clicked;
+ };
+ val draw = { !sys.draw.Canvas screen, int scale, u32 foreground, u32 background, u32 active ->
+ screen.fillRect(x,y,width,height,enabled && (hovered || pressed) ? active : background);
+ screen.rect(x,y,width,height,2,enabled ? foreground : active);
+ if( scale > 0 ) {
+ i64 textWidth = label#; textWidth = (textWidth*4-1)*scale;
+ if( textWidth <= width-8 && 5*scale <= height-8 )
+ screen.text(x+(width-textWidth)/2,y+(height-5*scale)/2+(pressed ? 1 : 0),
+ label,scale,enabled ? foreground : active);
+ }
+ return self;
+ };
+};
diff --git a/src/main/smp/sys/draw/Canvas.smp b/src/main/smp/sys/draw/Canvas.smp
new file mode 100644
index 00000000..5ec7c9ef
--- /dev/null
+++ b/src/main/smp/sys/draw/Canvas.smp
@@ -0,0 +1,201 @@
+struct Canvas {
+ u32 !width;
+ u32 !height;
+ u32[] !pixels;
+ // Layout coordinates are relative to the constructor's base size.
+ // A single float scale preserves circles and game geometry on resize.
+ u32 baseWidth, baseHeight;
+ f64 scale = 1.0;
+ int offsetX = 0, offsetY = 0;
+
+ new Canvas = { u32 w, u32 h ->
+ if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1);
+ i64 count = w;
+ count *= h;
+ if( w <= 0 || h <= 0 || count > sys.integer.MAX_I32 ) libc._exit(1);
+ width = w;
+ height = h;
+ baseWidth = w;
+ baseHeight = h;
+ pixels = new u32[count];
+ };
+
+ // Ignore minimized windows. Return true only when a redraw is needed.
+ val resize = { u32 w, u32 h ->
+ if( w == 0 || h == 0 || (w == width && h == height) ) return false;
+ if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1);
+ i64 count = w; count *= h;
+ if( count > sys.integer.MAX_I32 ) libc._exit(1);
+ // Reuse storage while dragging. Geometric growth bounds total allocation
+ // even in the current runtime, which does not yet collect old arrays.
+ if( count > pixels# ) {
+ i64 capacity = pixels#*2;
+ if( capacity < count ) capacity = count;
+ if( capacity > sys.integer.MAX_I32 ) capacity = sys.integer.MAX_I32;
+ pixels = new u32[capacity];
+ }
+ width = w; height = h;
+ f64 sx = w*1.0/baseWidth, sy = h*1.0/baseHeight;
+ scale = sx < sy ? sx : sy;
+ offsetX = (w-baseWidth*scale)/2;
+ offsetY = (h-baseHeight*scale)/2;
+ return true;
+ };
+
+ // Inverse of the drawing transform. Margins are outside the layout;
+ // reject them before integer truncation can turn a small negative into 0.
+ val localX = { int x ->
+ if( x < offsetX || x >= offsetX+baseWidth*scale ) return -1;
+ int local = (x-offsetX)/scale;
+ return local;
+ };
+ val localY = { int y ->
+ if( y < offsetY || y >= offsetY+baseHeight*scale ) return -1;
+ int local = (y-offsetY)/scale;
+ return local;
+ };
+
+ val clear = { u32 color ->
+ i64 count = width; count *= height;
+ for( int i = 0; i < count; i++ ) pixels[i] = color;
+ return self;
+ };
+
+ val pixel = { i64 x, i64 y, u32 color ->
+ return fillRect(x,y,1,1,color);
+ };
+
+ // Integer coordinates, top-left origin. Rectangle extents are half-open.
+ val fillRect = { i64 x, i64 y, i64 w, i64 h, u32 color ->
+ if( w <= 0 || h <= 0 ) return self;
+ i64 right = offsetX+(x+w)*scale;
+ i64 bottom = offsetY+(y+h)*scale;
+ x = offsetX+x*scale; y = offsetY+y*scale;
+ if( right <= 0 || bottom <= 0 || x >= width || y >= height ) return self;
+ int x0 = x < 0 ? 0 : x, y0 = y < 0 ? 0 : y;
+ int x1 = right > width ? width : right, y1 = bottom > height ? height : bottom;
+ for( int py = y0; py < y1; py++ )
+ for( int px = x0; px < x1; px++ ) pixels[py*width+px] = color;
+ return self;
+ };
+
+ // Outline stays inside the rectangle. Wide borders become a filled rect.
+ val rect = { i64 x, i64 y, i64 w, i64 h, i64 thickness, u32 color ->
+ if( w <= 0 || h <= 0 || thickness <= 0 ) return self;
+ if( thickness >= w || thickness >= h || thickness >= w-thickness || thickness >= h-thickness )
+ return fillRect(x,y,w,h,color);
+ fillRect(x,y,w,thickness,color);
+ fillRect(x,y+h-thickness,w,thickness,color);
+ fillRect(x,y+thickness,thickness,h-2*thickness,color);
+ return fillRect(x+w-thickness,y+thickness,thickness,h-2*thickness,color);
+ };
+
+ // Integer centers are pixel centers. Circle outlines extend inward.
+ val fillCircle = { i64 cx, i64 cy, int radius, u32 color ->
+ return _circle(cx,cy,radius,0,true,color);
+ };
+ val circle = { i64 cx, i64 cy, int radius, int thickness, u32 color ->
+ return _circle(cx,cy,radius,thickness,false,color);
+ };
+ val _circle = { i64 cx, i64 cy, int radius, int thickness, bool filled, u32 color ->
+ if( radius < 0 || (!filled && thickness <= 0) ) return self;
+ cx = offsetX+cx*scale; cy = offsetY+cy*scale;
+ radius *= scale;
+ thickness *= scale;
+ if( !filled && thickness < 1 ) thickness = 1;
+ i64 left = cx; left -= radius;
+ i64 top = cy; top -= radius;
+ i64 right = cx; right += radius;
+ i64 bottom = cy; bottom += radius;
+ if( right < 0 || bottom < 0 || left >= width || top >= height ) return self;
+ int x0 = left < 0 ? 0 : left, y0 = top < 0 ? 0 : top;
+ int x1 = right >= width ? width-1 : right, y1 = bottom >= height ? height-1 : bottom;
+ i64 outer2 = radius;
+ outer2 *= radius;
+ i64 inner = filled ? -1 : radius-thickness;
+ for( int py = y0; py <= y1; py++ )
+ for( int px = x0; px <= x1; px++ ) {
+ i64 dx = px; dx -= cx;
+ i64 dy = py; dy -= cy;
+ i64 d2 = dx*dx+dy*dy;
+ if( d2 <= outer2 && (inner <= 0 || d2 > inner*inner) ) pixels[py*width+px] = color;
+ }
+ return self;
+ };
+
+ // Round caps; a zero-length segment is a dot. Only the clipped bounding
+ // box is scanned. Floating distances avoid overflowing coordinate squares.
+ val line = { i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness, u32 color ->
+ if( thickness <= 0 ) return self;
+ x0 = offsetX+x0*scale; y0 = offsetY+y0*scale;
+ x1 = offsetX+x1*scale; y1 = offsetY+y1*scale;
+ thickness *= scale;
+ if( thickness < 1 ) thickness = 1;
+ i64 pad = thickness/2+1;
+ i64 left = x0 < x1 ? x0 : x1; left -= pad;
+ i64 top = y0 < y1 ? y0 : y1; top -= pad;
+ i64 right = x0 > x1 ? x0 : x1; right += pad;
+ i64 bottom = y0 > y1 ? y0 : y1; bottom += pad;
+ if( right < 0 || bottom < 0 || left >= width || top >= height ) return self;
+ int bx0 = left < 0 ? 0 : left, by0 = top < 0 ? 0 : top;
+ int bx1 = right >= width ? width-1 : right, by1 = bottom >= height ? height-1 : bottom;
+ for( int py = by0; py <= by1; py++ )
+ for( int px = bx0; px <= bx1; px++ )
+ if( _onLine(px,py,x0,y0,x1,y1,thickness) ) pixels[py*width+px] = color;
+ return self;
+ };
+
+ // Small 3x5 bitmap font for game labels. Lowercase maps to uppercase.
+ // Newline returns to x; unsupported characters draw a question mark.
+ val text = { i64 x, i64 y, u8[~] str, int scale, u32 color ->
+ if( scale <= 0 ) return self;
+ i64 px = x, py = y;
+ for( int i = 0; i < str#; i++ ) {
+ u8 c = str[i];
+ if( c == '\n' ) { px = x; py += 6*scale; continue; }
+ int bits = _glyph(c);
+ for( int row = 0; row < 5; row++ )
+ for( int col = 0; col < 3; col++ )
+ if( (bits >> (14-row*3-col)) & 1 )
+ fillRect(px+col*scale,py+row*scale,scale,scale,color);
+ px += 4*scale;
+ }
+ return self;
+ };
+};
+
+// An old-school 3x5 font, ASCII 32..127. Five octal row digits need u16.
+// Lowercase uses uppercase shapes; unsupported characters use '?'.
+val _glyphs = new u16[~96]{
+ 000000,022202,055000,057575,061202,051245,061202,022000, // space..'
+ 012221,042224,005250,002720,000024,000700,000002,011244, // (../
+ 075557,026227,061247,061216,055711,074616,034757,071222, // 0..7
+ 075757,075716,002020,002024,012421,007070,042124,061202, // 8..?
+ 061202,025755,065656,034443,065556,074647,074644,034553, // @..G
+ 055755,072227,011152,055655,044447,057755,057775,025552, // H..O
+ 065644,025573,065655,034216,072222,055557,055552,055775, // P..W
+ 055255,055222,071247,032223,044211,062226,025000,000007, // X.._
+ 042000,025755,065656,034443,065556,074647,074644,034553, // `..g
+ 055755,072227,011152,055655,044447,057755,057775,025552, // h..o
+ 065644,025573,065655,034216,072222,055557,055552,055775, // p..w
+ 055255,055222,071247,032423,022222,062126,003600,061202, // x..DEL
+};
+
+val _glyph = { u8 c ->
+ return 32 <= c < 128 ? _glyphs[c-32] : 061202;
+};
+
+// Pixel coverage for a round-ended segment, separate from traversal.
+val _onLine = { i64 px, i64 py, i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness ->
+ f64 dx = x1; dx -= x0;
+ f64 dy = y1; dy -= y0;
+ f64 vx = px; vx -= x0;
+ f64 vy = py; vy -= y0;
+ f64 length2 = dx*dx+dy*dy;
+ bool point = x0 == x1 && y0 == y1;
+ f64 t = point ? 0.0 : (vx*dx+vy*dy)/length2;
+ t = t < 0 ? 0.0 : t > 1 ? 1.0 : t;
+ f64 ex = vx-t*dx, ey = vy-t*dy;
+ f64 half = thickness/2.0;
+ return ex*ex+ey*ey <= half*half;
+};
diff --git a/src/main/smp/sys/draw/README.md b/src/main/smp/sys/draw/README.md
new file mode 100644
index 00000000..7d3bf6c8
--- /dev/null
+++ b/src/main/smp/sys/draw/README.md
@@ -0,0 +1,124 @@
+# Drawing in Simple
+
+[Chapter 31](../../../../../README.md#graphics-and-sound) introduces the library.
+The implementation is in [Canvas.smp](Canvas.smp), [Button.smp](Button.smp),
+and the [draw module](../draw.smp).
+
+`sys.draw` draws into an ordinary `u32[]`. It has no native dependencies and
+does not open a window. `sys.gfx` presents the resulting pixels using the
+optional [MiniFB backend](../gfx.md).
+
+```simple
+val canvas = new sys.draw.Canvas(600,780);
+u32 orange = 0xe47b57;
+canvas.clear(sys.draw.WHITE);
+canvas.fillRect(20,20,180,80,orange);
+canvas.rect(20,20,180,80,3,sys.draw.BLACK);
+canvas.circle(300,200,48,8,sys.draw.BLUE);
+canvas.fillCircle(420,200,20,sys.draw.GREEN);
+canvas.line(40,320,250,440,12,orange);
+canvas.text(40,500,"YOUR TURN",4,sys.draw.BLACK);
+// After sys.gfx.open succeeds:
+sys.gfx.presentSize(canvas.pixels,canvas.width,canvas.height);
+```
+
+## Small raster API
+
+Coordinates start at the upper left; x increases rightward and y downward.
+Drawing methods return the canvas for chaining. Everything is opaque RGB;
+there is no blending, antialiasing, transform stack, or native drawing state.
+Coordinates accept `i64` so ordinary widened arithmetic can be passed directly.
+Circle radii and circle stroke widths are `int`. Use screen-sized coordinates,
+extents, and stroke widths.
+
+| Operation | Behavior |
+| --- | --- |
+| `rgb(r,g,b)` | Clamp components to 0–255 and pack RGB. `BLACK`, `WHITE`, `RED`, `GREEN`, and `BLUE` are available too. |
+| `new Canvas(width,height)` | Allocate a zero-filled pixel array. Dimensions must be positive and their product must fit a signed 32-bit index; invalid sizes exit with status 1. Allocation can still fail for lack of memory. |
+| `resize(width,height)` | Fit the original layout into new drawable dimensions; return whether they changed. Ignore zero dimensions. |
+| `localX(x)`, `localY(y)` | Convert drawable pixels to base coordinates for input; return -1 in the margins. |
+| `clear(color)` | Fill the entire canvas. |
+| `pixel(x,y,color)` | Set one pixel; ignore points outside the canvas. |
+| `fillRect(x,y,w,h,color)` | Fill a half-open rectangle: x through x+w-1, y through y+h-1. |
+| `rect(x,y,w,h,thickness,color)` | Draw an inward outline. A sufficiently wide outline fills the rectangle. |
+| `fillCircle(cx,cy,radius,color)` | Fill a circle; radius zero draws its center pixel. |
+| `circle(cx,cy,radius,thickness,color)` | Draw an inward circular outline. |
+| `line(x0,y0,x1,y1,thickness,color)` | Draw a round-ended segment. A zero-length segment draws a round dot. Thickness is its geometric diameter, sampled at integer pixel centers. |
+| `text(x,y,string,scale,color)` | Draw a 3×5 bitmap font, with one column between characters. Upper/lowercase ASCII letters, digits, spaces, and basic punctuation are supported. Newline advances six scaled pixels. Unknown characters use `?`. |
+
+Shapes clip to the canvas. Nonpositive rectangle extents, stroke widths, or
+text scale do nothing; negative circle radii do nothing. Line and circle
+coverage scans only the clipped bounding box, which is sufficient for small
+turn-based games. This is a starting raster library rather than a fast animated
+renderer. The pixel array remains available for direct drawing and inspection.
+
+The constructor sets the layout's `baseWidth` and `baseHeight`. Resizing uses
+`scale = min(width/baseWidth, height/baseHeight)` in floating point and centers
+the result with `offsetX` and `offsetY`. Sizes, offsets, glyph cells, and stroke
+widths all use this transform; circles stay circular. Positive line and circle
+strokes retain at least one drawable pixel. Existing drawing coordinates remain
+in base units, while `width`, `height`, and direct pixel indexing use the actual
+framebuffer dimensions. `clear` fills the whole framebuffer, including margins.
+At very small sizes, details smaller than a pixel naturally disappear.
+
+Canvas reuses its pixel storage and grows its capacity geometrically when needed.
+Only the first `width*height` elements are active; use `gfx.presentSize` after
+resizing. This avoids allocating on every drag event, including repeated shrink
+and grow cycles. Use `localX`/`localY` before button or game hit tests so drawing
+and input share the same scale and centering.
+
+Packed colors use hexadecimal literals (`0xRRGGBB`); `rgb(r,g,b)` remains handy
+for computed components. The font masks use leading-zero octal, with five
+digits after the prefix: each digit is one three-pixel row, top to bottom.
+For example, `A` is `025755`: rows `010`, `101`, `111`, `101`, `101`.
+The font includes all printable ASCII punctuation except `@`, `&`, and `$`,
+which use the question-mark fallback. Colons and slashes support clock and date
+labels; quotes, brackets, arithmetic signs, and other small symbols fit in 3×5.
+
+## Button widget
+
+`new sys.draw.Button(x,y,width,height,label)` creates a rectangular software
+button. It owns no window or native resources. Feed pointer coordinates and
+the held mouse-button state to `update(x,y,down)` once per event-loop iteration.
+It returns true once on release inside, provided the press began inside.
+Dragging in from outside does not activate it; releasing outside cancels.
+
+`hovered` and `pressed` expose visual state. Set `enabled=false` to cancel a
+pending press and disable activation; `label` can be changed at any time.
+`contains(x,y)` uses half-open bounds. `draw(canvas,scale,foreground,background,active)`
+paints the button and centers its 3x5 label when it fits. Colors belong to the
+caller. Keyboard shortcuts belong to the application; this small widget has
+no focus system. The [clock example](../../../../../docs/examples/Clock.smp) shows mouse activation
+and a Space shortcut in the same single-threaded loop.
+
+## Graphical tic-tac-toe
+
+From `chapter31`:
+
+```sh
+make run-graphical-tictactoe
+```
+
+Click an empty square or press **1–9**, numbered left-to-right, top-to-bottom.
+You are X; the CPU is O. It wins when possible, blocks your immediate win,
+then prefers the center, corners, and edges. The result stays visible with
+the winning line highlighted. Press **R** or **Space** to start a new game,
+or **Q**/**Escape** to quit. Restart is also available during a game.
+
+Held buttons and keys do not take repeated turns. Moving the pointer highlights
+empty cells. The canvas is redrawn after a move, restart, hover change, or resize;
+polling still processes window events and waits between polls.
+
+`make graphical-tictactoe` builds without opening a window or requiring
+MiniFB. Its output is `build/examples/x86_64_v2_win64/TicTacToeGraphical.exe`
+on Windows or `build/examples/x86_64_v2_SystemV/TicTacToeGraphical` on Linux.
+Backend discovery and explicit overrides follow [the pixel-window instructions](../gfx.md).
+Passing any argument performs a five-poll, self-closing smoke test.
+
+The original `make tictactoe` still builds the terminal game.
+The graphical game also uses optional [background audio](../audio.md): a soft
+boop for accepted moves, rising tones for a player win, and falling tones for
+a CPU win. Bad input is silent. The run target builds/configures both backends.
+`make test CLASS=DrawTest` checks raster pixels and complete game turns
+without a display. `make tests_nographics` runs the ordinary suite with
+the backend disabled.