JS.zig 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const std = @import("std");
  2. const utils = @import("utils.zig");
  3. const Imports = struct {
  4. extern fn jsConsoleLogWrite(ptr: [*]const u8, len: usize) void;
  5. extern fn jsConsoleLogFlush() void;
  6. extern fn jsRandom() f32;
  7. extern fn jsClearRectangle(x: f32, y: f32, width: f32, height: f32) void;
  8. extern fn jsDrawCircle(x: f32, y: f32, radius: f32, r: u8, g: u8, b: u8, a: f32) void;
  9. extern fn jsDrawRectangle(x: f32, y: f32, width: f32, height: f32, r: u8, g: u8, b: u8, a: f32) void;
  10. extern fn jsUpdateScore(score: u32) void;
  11. };
  12. const Ball2D = utils.Ball2D;
  13. const RGBColor = utils.RGBColor;
  14. const Vector2D = utils.Vector2D;
  15. pub inline fn random() f32 {
  16. return Imports.jsRandom();
  17. }
  18. pub inline fn clearRectangle(pos: Vector2D, width: f32, height: f32) void {
  19. Imports.jsClearRectangle(pos.x, pos.y, width, height);
  20. }
  21. pub inline fn drawBall2D(ball: Ball2D) void {
  22. const p = ball.pos;
  23. const r = ball.radius;
  24. const c = ball.color;
  25. Imports.jsDrawCircle(p.x, p.y, r, c.r, c.g, c.b, c.a);
  26. }
  27. pub inline fn drawRectangle(pos: Vector2D, width: f32, height: f32, color: RGBColor) void {
  28. Imports.jsDrawRectangle(pos.x, pos.y, width, height, color.r, color.g, color.b, color.a);
  29. }
  30. pub inline fn updateScore(score: u32) void {
  31. Imports.jsUpdateScore(score);
  32. }
  33. pub const Console = struct {
  34. pub const Logger = struct {
  35. pub const Error = error{};
  36. pub const Writer = std.io.Writer(void, Error, write);
  37. fn write(_: void, bytes: []const u8) Error!usize {
  38. Imports.jsConsoleLogWrite(bytes.ptr, bytes.len);
  39. return bytes.len;
  40. }
  41. };
  42. const logger = Logger.Writer{ .context = {} };
  43. pub fn log(comptime format: []const u8, args: anytype) void {
  44. logger.print(format, args) catch return;
  45. Imports.jsConsoleLogFlush();
  46. }
  47. };