Compare commits
39 Commits
sdl-multiw
...
4f386c981c
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f386c981c | |||
| f1a0e84272 | |||
| 1a94cc8bfd | |||
| aeda3ee0d0 | |||
| dd9d5deb92 | |||
| bd58286c98 | |||
| b896a67fd4 | |||
| 1dda9c9d15 | |||
| b30865d105 | |||
| 6ae927c4b7 | |||
| c73d710513 | |||
| 0b287e800d | |||
| b6012f1fc4 | |||
| 85a3bac095 | |||
| bee9513ba0 | |||
| 48824532f1 | |||
| 7dc7069186 | |||
| fd0ba8b583 | |||
| 8532114673 | |||
| df467df5d6 | |||
| 9687d9cab5 | |||
| 716b6fbeea | |||
| e7a0c20353 | |||
| 070c8bad2d | |||
| d640269cad | |||
| 3ac35a5046 | |||
| 6f58967049 | |||
| 8f462cc93b | |||
| 643aaee926 | |||
| b49ee3e46c | |||
| b5d60d67dd | |||
| e22051c1c1 | |||
| 183726aed4 | |||
| 4f0fb09185 | |||
| bb825d0225 | |||
| b852384322 | |||
| d4a2f41a51 | |||
| bca66e3815 | |||
| 7a5f9d62a8 |
7
.vscode/launch.json
vendored
7
.vscode/launch.json
vendored
@@ -10,5 +10,12 @@
|
|||||||
"cwd": "${workspaceFolder}",
|
"cwd": "${workspaceFolder}",
|
||||||
"preLaunchTask": "zig: build"
|
"preLaunchTask": "zig: build"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "Zig: Debug (gdb)",
|
||||||
|
"type": "gdb",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}/zig-out/bin/Zivro",
|
||||||
|
"preLaunchTask": "zig: build"
|
||||||
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
7
.vscode/settings.json
vendored
Normal file
7
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"zig.testArgs": [
|
||||||
|
"build",
|
||||||
|
"test",
|
||||||
|
"-Dtest-filter=${filter}"
|
||||||
|
]
|
||||||
|
}
|
||||||
5
.vscode/tasks.json
vendored
5
.vscode/tasks.json
vendored
@@ -10,11 +10,6 @@
|
|||||||
"isDefault": true
|
"isDefault": true
|
||||||
},
|
},
|
||||||
"problemMatcher": ["$gcc"],
|
"problemMatcher": ["$gcc"],
|
||||||
"presentation": {
|
|
||||||
"reveal": "always",
|
|
||||||
"panel": "shared",
|
|
||||||
"showReuseMessage": true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
11
build.zig
11
build.zig
@@ -34,7 +34,16 @@ pub fn build(b: *std.Build) void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const exe_tests = b.addTest(.{
|
const exe_tests = b.addTest(.{
|
||||||
.root_module = exe.root_module,
|
.root_module = b.createModule(.{
|
||||||
|
.root_source_file = b.path("src/tests.zig"),
|
||||||
|
.target = target,
|
||||||
|
.optimize = optimize,
|
||||||
|
|
||||||
|
.imports = &.{
|
||||||
|
.{ .name = "dvui", .module = dvui_dep.module("dvui_sdl3") },
|
||||||
|
.{ .name = "sdl-backend", .module = dvui_dep.module("sdl3") },
|
||||||
|
},
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const run_exe_tests = b.addRunArtifact(exe_tests);
|
const run_exe_tests = b.addRunArtifact(exe_tests);
|
||||||
|
|||||||
167
src/Canvas.zig
Normal file
167
src/Canvas.zig
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const builtin = @import("builtin");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const Document = @import("models/Document.zig");
|
||||||
|
const RenderEngine = @import("render/RenderEngine.zig").RenderEngine;
|
||||||
|
const ImageRect = @import("models/basic_models.zig").ImageRect;
|
||||||
|
const Point2 = @import("models/basic_models.zig").Point2;
|
||||||
|
const Color = dvui.Color;
|
||||||
|
|
||||||
|
const Canvas = @This();
|
||||||
|
|
||||||
|
allocator: std.mem.Allocator,
|
||||||
|
document: *Document,
|
||||||
|
render_engine: RenderEngine,
|
||||||
|
texture: ?dvui.Texture = null,
|
||||||
|
pos: dvui.Point = dvui.Point{ .x = 400, .y = 400 },
|
||||||
|
scroll: dvui.ScrollInfo = .{
|
||||||
|
.vertical = .auto,
|
||||||
|
.horizontal = .auto,
|
||||||
|
},
|
||||||
|
native_scaling: bool = true,
|
||||||
|
redraw_throttle_ms: u32 = 50,
|
||||||
|
_visible_rect: ?ImageRect = null,
|
||||||
|
_zoom: f32 = 1,
|
||||||
|
_redraw_pending: bool = false,
|
||||||
|
_last_redraw_time_ms: i64 = 0,
|
||||||
|
cursor_document_point: ?Point2 = null,
|
||||||
|
|
||||||
|
pub fn init(allocator: std.mem.Allocator, document: *Document, engine: RenderEngine) Canvas {
|
||||||
|
return .{
|
||||||
|
.allocator = allocator,
|
||||||
|
.document = document,
|
||||||
|
.render_engine = engine,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *Canvas) void {
|
||||||
|
if (self.texture) |texture| {
|
||||||
|
dvui.Texture.destroyLater(texture);
|
||||||
|
self.texture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redrawExample(self: *Canvas) !void {
|
||||||
|
const full = self.getZoomedImageSize();
|
||||||
|
|
||||||
|
const vis: ImageRect = self._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 };
|
||||||
|
|
||||||
|
if (vis.w == 0 or vis.h == 0) {
|
||||||
|
if (self.texture) |tex| {
|
||||||
|
dvui.Texture.destroyLater(tex);
|
||||||
|
self.texture = null;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const new_texture = self.render_engine.example(.{ .w = full.w, .h = full.h }, vis) catch null;
|
||||||
|
|
||||||
|
if (new_texture) |tex| {
|
||||||
|
if (self.texture) |old_tex| {
|
||||||
|
dvui.Texture.destroyLater(old_tex);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.texture = tex;
|
||||||
|
}
|
||||||
|
self._last_redraw_time_ms = std.time.milliTimestamp();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exampleReset(self: *Canvas) !void {
|
||||||
|
self.render_engine.exampleReset();
|
||||||
|
try self.redrawExample();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn setZoom(self: *Canvas, value: f32) void {
|
||||||
|
self._zoom = @max(value, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addZoom(self: *Canvas, value: f32) void {
|
||||||
|
self._zoom += value;
|
||||||
|
self._zoom = @max(self._zoom, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn requestRedraw(self: *Canvas) void {
|
||||||
|
self._redraw_pending = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn processPendingRedraw(self: *Canvas) !void {
|
||||||
|
if (!self._redraw_pending) return;
|
||||||
|
if (self.redraw_throttle_ms == 0) {
|
||||||
|
self._redraw_pending = false;
|
||||||
|
try self.redrawExample();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const now_ms = std.time.milliTimestamp();
|
||||||
|
const elapsed: i64 = if (self._last_redraw_time_ms == 0) self.redraw_throttle_ms else now_ms - self._last_redraw_time_ms;
|
||||||
|
if (elapsed < @as(i64, @intCast(self.redraw_throttle_ms))) return;
|
||||||
|
self._redraw_pending = false;
|
||||||
|
try self.redrawExample();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn getZoomedImageSize(self: Canvas) ImageRect {
|
||||||
|
const doc = self.document;
|
||||||
|
return .{
|
||||||
|
.x = @intFromFloat(self.pos.x),
|
||||||
|
.y = @intFromFloat(self.pos.y),
|
||||||
|
.w = @intFromFloat(doc.size.width * self._zoom),
|
||||||
|
.h = @intFromFloat(doc.size.height * self._zoom),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contentPointToDocument(self: Canvas, content_point: dvui.Point, natural_scale: f32) ?Point2 {
|
||||||
|
const img = self.getZoomedImageSize();
|
||||||
|
const left_n = @as(f32, @floatFromInt(img.x)) / natural_scale;
|
||||||
|
const top_n = @as(f32, @floatFromInt(img.y)) / natural_scale;
|
||||||
|
const right_n = @as(f32, @floatFromInt(img.x + img.w)) / natural_scale;
|
||||||
|
const bottom_n = @as(f32, @floatFromInt(img.y + img.h)) / natural_scale;
|
||||||
|
|
||||||
|
if (content_point.x < left_n or content_point.x >= right_n or
|
||||||
|
content_point.y < top_n or content_point.y >= bottom_n)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
const px_x = content_point.x * natural_scale - @as(f32, @floatFromInt(img.x));
|
||||||
|
const px_y = content_point.y * natural_scale - @as(f32, @floatFromInt(img.y));
|
||||||
|
return Point2{
|
||||||
|
.x = px_x / self._zoom,
|
||||||
|
.y = px_y / self._zoom,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn updateVisibleImageRect(self: *Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) bool {
|
||||||
|
const next = computeVisibleImageRect(self.*, viewport, scroll_offset);
|
||||||
|
var changed = false;
|
||||||
|
if (self._visible_rect) |vis| {
|
||||||
|
changed |= next.x != vis.x or next.y != vis.y or next.w != vis.w or next.h != vis.h;
|
||||||
|
}
|
||||||
|
self._visible_rect = next;
|
||||||
|
if (changed) {
|
||||||
|
std.debug.print("Visible Image Rect: {{ x: {}, y: {}, w: {}, h: {} }}\n", .{ next.x, next.y, next.w, next.h });
|
||||||
|
}
|
||||||
|
if (changed or self.texture == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn computeVisibleImageRect(self: Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) ImageRect {
|
||||||
|
const image_rect = self.getZoomedImageSize();
|
||||||
|
|
||||||
|
const img_w: u32 = image_rect.w;
|
||||||
|
const img_h: u32 = image_rect.h;
|
||||||
|
|
||||||
|
const vis_w: u32 = @min(@as(u32, @intFromFloat(viewport.w)), img_w);
|
||||||
|
const vis_h: u32 = @min(@as(u32, @intFromFloat(viewport.h)), img_h);
|
||||||
|
|
||||||
|
const raw_x: i64 = @intFromFloat(scroll_offset.x - @as(f32, @floatFromInt(image_rect.x)));
|
||||||
|
const raw_y: i64 = @intFromFloat(scroll_offset.y - @as(f32, @floatFromInt(image_rect.y)));
|
||||||
|
|
||||||
|
const vis_x: u32 = @intCast(std.math.clamp(raw_x, 0, @as(i64, img_w) - @as(i64, vis_w)));
|
||||||
|
const vis_y: u32 = @intCast(std.math.clamp(raw_y, 0, @as(i64, img_h) - @as(i64, vis_h)));
|
||||||
|
|
||||||
|
return ImageRect{
|
||||||
|
.x = vis_x,
|
||||||
|
.y = vis_y,
|
||||||
|
.w = vis_w,
|
||||||
|
.h = vis_h,
|
||||||
|
};
|
||||||
|
}
|
||||||
92
src/WindowContext.zig
Normal file
92
src/WindowContext.zig
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Canvas = @import("Canvas.zig");
|
||||||
|
const CpuRenderEngine = @import("render/CpuRenderEngine.zig");
|
||||||
|
const RenderEngine = @import("render/RenderEngine.zig").RenderEngine;
|
||||||
|
const Document = @import("models/Document.zig");
|
||||||
|
const basic_models = @import("models/basic_models.zig");
|
||||||
|
|
||||||
|
const WindowContext = @This();
|
||||||
|
|
||||||
|
pub const OpenDocument = struct {
|
||||||
|
document: Document,
|
||||||
|
cpu_render: CpuRenderEngine,
|
||||||
|
canvas: Canvas,
|
||||||
|
|
||||||
|
pub fn init(allocator: std.mem.Allocator, self: *OpenDocument) void {
|
||||||
|
const default_size = basic_models.Size{ .width = 800, .height = 600 };
|
||||||
|
self.document = Document.init(allocator, default_size);
|
||||||
|
self.cpu_render = CpuRenderEngine.init(allocator, .Squares);
|
||||||
|
self.canvas = Canvas.init(allocator, &self.document, (&self.cpu_render).renderEngine());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *OpenDocument) void {
|
||||||
|
self.document.deinit();
|
||||||
|
self.canvas.deinit();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
allocator: std.mem.Allocator,
|
||||||
|
frame_index: u64,
|
||||||
|
documents: std.ArrayList(*OpenDocument),
|
||||||
|
active_document_index: ?usize,
|
||||||
|
|
||||||
|
pub fn init(allocator: std.mem.Allocator) !WindowContext {
|
||||||
|
const frame_index: u64 = 0;
|
||||||
|
const documents = std.ArrayList(*OpenDocument).empty;
|
||||||
|
const active_document_index: ?usize = null;
|
||||||
|
return .{
|
||||||
|
.allocator = allocator,
|
||||||
|
.frame_index = frame_index,
|
||||||
|
.documents = documents,
|
||||||
|
.active_document_index = active_document_index,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *WindowContext) void {
|
||||||
|
for (self.documents.items) |ptr| {
|
||||||
|
ptr.deinit();
|
||||||
|
self.allocator.destroy(ptr);
|
||||||
|
}
|
||||||
|
self.documents.deinit(self.allocator);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn activeDocument(self: *WindowContext) ?*OpenDocument {
|
||||||
|
const i = self.active_document_index orelse return null;
|
||||||
|
if (i >= self.documents.items.len) return null;
|
||||||
|
return self.documents.items[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addNewDocument(self: *WindowContext) !void {
|
||||||
|
const ptr = try self.allocator.create(OpenDocument);
|
||||||
|
errdefer self.allocator.destroy(ptr);
|
||||||
|
OpenDocument.init(self.allocator, ptr);
|
||||||
|
try ptr.document.addRandomShapes(std.crypto.random);
|
||||||
|
try self.documents.append(self.allocator, ptr);
|
||||||
|
self.active_document_index = self.documents.items.len - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn setActiveDocument(self: *WindowContext, index: usize) void {
|
||||||
|
if (index < self.documents.items.len) {
|
||||||
|
self.active_document_index = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn closeDocument(self: *WindowContext, index: usize) void {
|
||||||
|
if (index >= self.documents.items.len) return;
|
||||||
|
const open_doc = self.documents.items[index];
|
||||||
|
open_doc.deinit();
|
||||||
|
self.allocator.destroy(open_doc);
|
||||||
|
_ = self.documents.orderedRemove(index);
|
||||||
|
|
||||||
|
if (self.active_document_index) |*active| {
|
||||||
|
if (index < active.*) {
|
||||||
|
active.* -= 1;
|
||||||
|
} else if (index == active.*) {
|
||||||
|
if (self.documents.items.len > 0) {
|
||||||
|
active.* = @min(index, self.documents.items.len - 1);
|
||||||
|
} else {
|
||||||
|
self.active_document_index = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
const std = @import("std");
|
|
||||||
|
|
||||||
const WindowData = @This();
|
|
||||||
|
|
||||||
frame: u64,
|
|
||||||
|
|
||||||
pub fn init() WindowData {
|
|
||||||
return WindowData{
|
|
||||||
.frame = 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
242
src/main.zig
242
src/main.zig
@@ -1,227 +1,49 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const builtin = @import("builtin");
|
|
||||||
const dvui = @import("dvui");
|
const dvui = @import("dvui");
|
||||||
const SDLBackend = @import("sdl-backend");
|
const SDLBackend = @import("sdl-backend");
|
||||||
const sdl_c = SDLBackend.c;
|
const WindowContext = @import("WindowContext.zig");
|
||||||
const WindowData = @import("WindowData.zig");
|
const ui = @import("ui/frame.zig");
|
||||||
const dbprint = std.debug.print;
|
|
||||||
|
|
||||||
const WindowContext = struct {
|
|
||||||
backend: SDLBackend,
|
|
||||||
backend_id: u32,
|
|
||||||
window: dvui.Window,
|
|
||||||
title: [:0]u8,
|
|
||||||
id: usize,
|
|
||||||
data: WindowData,
|
|
||||||
|
|
||||||
fn init(allocator: std.mem.Allocator, id: usize) !*WindowContext {
|
|
||||||
var ctx = try allocator.create(WindowContext);
|
|
||||||
errdefer allocator.destroy(ctx);
|
|
||||||
|
|
||||||
ctx.id = id;
|
|
||||||
|
|
||||||
const title_bytes = try std.fmt.allocPrint(allocator, "My DVUI App #{d}", .{id});
|
|
||||||
defer allocator.free(title_bytes);
|
|
||||||
|
|
||||||
ctx.title = try allocator.allocSentinel(u8, title_bytes.len, 0);
|
|
||||||
@memcpy(ctx.title[0..title_bytes.len], title_bytes);
|
|
||||||
|
|
||||||
ctx.backend = try SDLBackend.initWindow(.{
|
|
||||||
.allocator = allocator,
|
|
||||||
.size = .{ .w = 800.0, .h = 600.0 },
|
|
||||||
.title = ctx.title,
|
|
||||||
.vsync = true,
|
|
||||||
});
|
|
||||||
errdefer destroyBackendKeepingSDL(&ctx.backend);
|
|
||||||
|
|
||||||
ctx.backend_id = @intCast(sdl_c.SDL_GetWindowID(ctx.backend.window));
|
|
||||||
|
|
||||||
const theme = switch (ctx.backend.preferredColorScheme() orelse .light) {
|
|
||||||
.light => dvui.Theme.builtin.adwaita_light,
|
|
||||||
.dark => dvui.Theme.builtin.adwaita_dark,
|
|
||||||
};
|
|
||||||
|
|
||||||
ctx.window = try dvui.Window.init(@src(), allocator, ctx.backend.backend(), .{ .theme = theme });
|
|
||||||
errdefer ctx.window.deinit();
|
|
||||||
|
|
||||||
ctx.data = WindowData.init();
|
|
||||||
|
|
||||||
return ctx;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deinit(self: *WindowContext, allocator: std.mem.Allocator, last_backend: bool) void {
|
|
||||||
self.window.deinit();
|
|
||||||
|
|
||||||
if (last_backend) {
|
|
||||||
self.backend.deinit();
|
|
||||||
} else {
|
|
||||||
destroyBackendKeepingSDL(&self.backend);
|
|
||||||
}
|
|
||||||
|
|
||||||
allocator.free(self.title);
|
|
||||||
self.* = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn destroyBackendKeepingSDL(backend: *SDLBackend) void {
|
|
||||||
sdl_c.SDL_DestroyRenderer(backend.renderer);
|
|
||||||
sdl_c.SDL_DestroyWindow(backend.window);
|
|
||||||
backend.we_own_window = false;
|
|
||||||
backend.deinit();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn main() !void {
|
pub fn main() !void {
|
||||||
if (@import("builtin").os.tag == .windows) {
|
|
||||||
// on windows graphical apps have no console, so output goes to nowhere - attach it manually. related: https://github.com/ziglang/zig/issues/4196
|
|
||||||
dvui.Backend.Common.windowsAttachConsole() catch {};
|
|
||||||
}
|
|
||||||
SDLBackend.enableSDLLogging();
|
|
||||||
std.log.info("SDL version: {f}", .{SDLBackend.getSDLVersion()});
|
|
||||||
|
|
||||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||||
defer _ = gpa.deinit();
|
|
||||||
const allocator = gpa.allocator();
|
const allocator = gpa.allocator();
|
||||||
|
|
||||||
var windows = try std.ArrayList(*WindowContext).initCapacity(allocator, 0);
|
var backend = try SDLBackend.initWindow(.{
|
||||||
defer {
|
.allocator = allocator,
|
||||||
for (windows.items, 0..) |ctx, i| {
|
.size = .{ .w = 800.0, .h = 600.0 },
|
||||||
const last = i + 1 == windows.items.len;
|
.title = "My DVUI App",
|
||||||
ctx.deinit(allocator, last);
|
.vsync = true,
|
||||||
allocator.destroy(ctx);
|
});
|
||||||
}
|
defer backend.deinit();
|
||||||
windows.deinit(allocator);
|
|
||||||
}
|
|
||||||
|
|
||||||
var next_window_id: usize = 1;
|
var win = try dvui.Window.init(@src(), allocator, backend.backend(), .{
|
||||||
const first_ctx = try WindowContext.init(allocator, next_window_id);
|
.theme = switch (backend.preferredColorScheme() orelse .light) {
|
||||||
next_window_id += 1;
|
.light => dvui.Theme.builtin.adwaita_light,
|
||||||
try windows.append(allocator, first_ctx);
|
.dark => dvui.Theme.builtin.adwaita_dark,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
defer win.deinit();
|
||||||
|
|
||||||
|
var ctx = try WindowContext.init(allocator);
|
||||||
|
defer ctx.deinit();
|
||||||
|
|
||||||
|
var interrupted = false;
|
||||||
main_loop: while (true) {
|
main_loop: while (true) {
|
||||||
if (windows.items.len == 0) break :main_loop;
|
const nstime = win.beginWait(interrupted);
|
||||||
|
try win.begin(nstime);
|
||||||
|
try backend.addAllEvents(&win);
|
||||||
|
|
||||||
const saw_events = try pumpEvents(&windows);
|
_ = SDLBackend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
|
||||||
|
_ = SDLBackend.c.SDL_RenderClear(backend.renderer);
|
||||||
|
|
||||||
var min_wait_event_micros: u32 = std.math.maxInt(u32);
|
if (!ui.guiFrame(&ctx)) break :main_loop;
|
||||||
var idx: usize = 0;
|
|
||||||
while (saw_events and idx < windows.items.len) {
|
|
||||||
const ctx = windows.items[idx];
|
|
||||||
|
|
||||||
const flags = sdl_c.SDL_GetWindowFlags(ctx.backend.window);
|
const end_micros = try win.end(.{});
|
||||||
const occluded = (flags & (sdl_c.SDL_WINDOW_HIDDEN | sdl_c.SDL_WINDOW_MINIMIZED | sdl_c.SDL_WINDOW_OCCLUDED)) != 0;
|
try backend.setCursor(win.cursorRequested());
|
||||||
if (occluded) {
|
try backend.textInputRect(win.textInputRequested());
|
||||||
idx += 1;
|
try backend.renderPresent();
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const nstime = @max(ctx.window.frame_time_ns, ctx.backend.nanoTime());
|
const wait_event_micros = win.waitTime(end_micros);
|
||||||
|
interrupted = try backend.waitEventTimeout(wait_event_micros);
|
||||||
try ctx.window.begin(nstime);
|
|
||||||
|
|
||||||
_ = sdl_c.SDL_SetRenderDrawColor(ctx.backend.renderer, 0, 0, 0, 255);
|
|
||||||
_ = sdl_c.SDL_RenderClear(ctx.backend.renderer);
|
|
||||||
|
|
||||||
const keep_open = try gui_frame(ctx, allocator, &windows, &next_window_id);
|
|
||||||
if (!keep_open) {
|
|
||||||
closeWindow(&windows, allocator, idx);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const end = try ctx.window.end(.{});
|
|
||||||
|
|
||||||
// cursor management
|
|
||||||
try ctx.backend.setCursor(ctx.window.cursorRequested());
|
|
||||||
try ctx.backend.textInputRect(ctx.window.textInputRequested());
|
|
||||||
|
|
||||||
// render frame to OS
|
|
||||||
try ctx.backend.renderPresent();
|
|
||||||
|
|
||||||
const sleep_time = ctx.window.waitTime(end);
|
|
||||||
min_wait_event_micros = @min(min_wait_event_micros, sleep_time);
|
|
||||||
|
|
||||||
idx += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (min_wait_event_micros != std.math.maxInt(u32)) {
|
|
||||||
min_wait_event_micros = @max(min_wait_event_micros, 1 / 120 * std.time.us_per_s);
|
|
||||||
std.Thread.sleep(min_wait_event_micros * std.time.ns_per_us);
|
|
||||||
} else {
|
|
||||||
std.Thread.sleep(1 / 60 * std.time.ns_per_s);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (windows.items.len == 0) break :main_loop;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn closeWindow(windows: *std.ArrayList(*WindowContext), allocator: std.mem.Allocator, idx: usize) void {
|
|
||||||
const last = windows.items.len == 1;
|
|
||||||
const ctx = windows.swapRemove(idx);
|
|
||||||
ctx.deinit(allocator, last);
|
|
||||||
allocator.destroy(ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn eventWindowId(event: sdl_c.SDL_Event) ?u32 {
|
|
||||||
return switch (event.type) {
|
|
||||||
sdl_c.SDL_EVENT_KEY_DOWN => @intCast(event.key.windowID),
|
|
||||||
sdl_c.SDL_EVENT_KEY_UP => @intCast(event.key.windowID),
|
|
||||||
sdl_c.SDL_EVENT_TEXT_INPUT => @intCast(event.text.windowID),
|
|
||||||
sdl_c.SDL_EVENT_TEXT_EDITING => @intCast(event.edit.windowID),
|
|
||||||
sdl_c.SDL_EVENT_MOUSE_MOTION => @intCast(event.motion.windowID),
|
|
||||||
sdl_c.SDL_EVENT_MOUSE_BUTTON_DOWN => @intCast(event.button.windowID),
|
|
||||||
sdl_c.SDL_EVENT_MOUSE_BUTTON_UP => @intCast(event.button.windowID),
|
|
||||||
sdl_c.SDL_EVENT_MOUSE_WHEEL => @intCast(event.wheel.windowID),
|
|
||||||
sdl_c.SDL_EVENT_WINDOW_FIRST...sdl_c.SDL_EVENT_WINDOW_LAST => @intCast(event.window.windowID),
|
|
||||||
else => null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pumpEvents(windows: *std.ArrayList(*WindowContext)) !bool {
|
|
||||||
var event: sdl_c.SDL_Event = undefined;
|
|
||||||
const poll_got_event = if (SDLBackend.sdl3) true else 1;
|
|
||||||
var saw_event = false;
|
|
||||||
|
|
||||||
while (sdl_c.SDL_PollEvent(&event) == poll_got_event) {
|
|
||||||
saw_event = true;
|
|
||||||
|
|
||||||
if (eventWindowId(event)) |wid| {
|
|
||||||
for (windows.items) |ctx| {
|
|
||||||
if (ctx.backend_id == wid) {
|
|
||||||
_ = try ctx.backend.addEvent(&ctx.window, event);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
//std.debug.print("null with: {any}\n", .{event.type});
|
|
||||||
// broadcast events without a window target (like SDL_QUIT)
|
|
||||||
for (windows.items) |ctx| {
|
|
||||||
_ = try ctx.backend.addEvent(&ctx.window, event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return saw_event;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn gui_frame(ctx: *WindowContext, allocator: std.mem.Allocator, windows: *std.ArrayList(*WindowContext), next_window_id: *usize) !bool {
|
|
||||||
for (ctx.window.events.items) |*e| {
|
|
||||||
if (e.evt == .window and e.evt.window.action == .close) return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var root = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .both, .padding = dvui.Rect.all(12), .background = true, .style = .window });
|
|
||||||
defer root.deinit();
|
|
||||||
|
|
||||||
dvui.label(@src(), "Window #{d}", .{ctx.id}, .{ .font_style = .title_2 });
|
|
||||||
dvui.label(@src(), "Open windows: {d}", .{windows.items.len}, .{});
|
|
||||||
dvui.label(@src(), "Frame {d}, fps: {d}", .{ ctx.data.frame, dvui.FPS() }, .{});
|
|
||||||
|
|
||||||
ctx.data.frame += 1;
|
|
||||||
|
|
||||||
if (dvui.button(@src(), "New window", .{}, .{})) {
|
|
||||||
const id = next_window_id.*;
|
|
||||||
next_window_id.* += 1;
|
|
||||||
const new_ctx = try WindowContext.init(allocator, id);
|
|
||||||
try windows.append(allocator, new_ctx);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|||||||
78
src/models/Document.zig
Normal file
78
src/models/Document.zig
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const basic_models = @import("basic_models.zig");
|
||||||
|
const Size = basic_models.Size;
|
||||||
|
const Document = @This();
|
||||||
|
|
||||||
|
pub const Object = @import("Object.zig");
|
||||||
|
const shape = @import("shape/shape.zig");
|
||||||
|
|
||||||
|
size: Size,
|
||||||
|
allocator: std.mem.Allocator,
|
||||||
|
objects: std.ArrayList(Object),
|
||||||
|
|
||||||
|
pub fn init(allocator: std.mem.Allocator, size: Size) Document {
|
||||||
|
return .{
|
||||||
|
.size = size,
|
||||||
|
.allocator = allocator,
|
||||||
|
.objects = std.ArrayList(Object).empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *Document) void {
|
||||||
|
for (self.objects.items) |*obj| obj.deinit(self.allocator);
|
||||||
|
self.objects.deinit(self.allocator);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addObject(self: *Document, template: Object) !void {
|
||||||
|
const obj = try template.clone(self.allocator);
|
||||||
|
try self.objects.append(self.allocator, obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addShape(self: *Document, parent: ?*Object, shape_kind: Object.ShapeKind) !void {
|
||||||
|
const obj = try shape.createObject(self.allocator, shape_kind);
|
||||||
|
if (parent) |p| {
|
||||||
|
try p.addChild(self.allocator, obj);
|
||||||
|
} else {
|
||||||
|
try self.addObject(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn randomShapeKind(rng: std.Random) Object.ShapeKind {
|
||||||
|
const shapes_implemented = [_]Object.ShapeKind{ .line, .ellipse, .broken };
|
||||||
|
return shapes_implemented[rng.intRangeLessThan(usize, 0, shapes_implemented.len)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Создаёт случайное количество фигур в документе (в т.ч. вложенных).
|
||||||
|
/// Используются только реализованные типы: line, ellipse, broken.
|
||||||
|
/// Ограничение max_total предотвращает экспоненциальный рост и переполнение.
|
||||||
|
pub fn addRandomShapes(self: *Document, rng: std.Random) !void {
|
||||||
|
const max_total: usize = 80;
|
||||||
|
var total_count: usize = 0;
|
||||||
|
|
||||||
|
const n_root = rng.intRangeLessThan(usize, 1, 5);
|
||||||
|
for (0..n_root) |_| {
|
||||||
|
if (total_count >= max_total) break;
|
||||||
|
try self.addShape(null, randomShapeKind(rng));
|
||||||
|
total_count += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var stack = std.ArrayList(*Object).empty;
|
||||||
|
defer stack.deinit(self.allocator);
|
||||||
|
for (self.objects.items) |*obj| {
|
||||||
|
try stack.append(self.allocator, obj);
|
||||||
|
}
|
||||||
|
while (stack.pop()) |obj| {
|
||||||
|
if (total_count >= max_total) continue;
|
||||||
|
const n_children = rng.intRangeLessThan(usize, 0, 2);
|
||||||
|
const base_len = obj.children.items.len;
|
||||||
|
for (0..n_children) |_| {
|
||||||
|
if (total_count >= max_total) break;
|
||||||
|
try self.addShape(obj, randomShapeKind(rng));
|
||||||
|
total_count += 1;
|
||||||
|
}
|
||||||
|
// Пушим в стек только после всех append, чтобы не держать указатели при реаллокации obj.children
|
||||||
|
for (obj.children.items[base_len..]) |*child| {
|
||||||
|
try stack.append(self.allocator, child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
66
src/models/Object.zig
Normal file
66
src/models/Object.zig
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Property = @import("Property.zig").Property;
|
||||||
|
const PropertyData = @import("Property.zig").Data;
|
||||||
|
const Object = @This();
|
||||||
|
|
||||||
|
pub const ShapeKind = enum {
|
||||||
|
line,
|
||||||
|
ellipse,
|
||||||
|
arc,
|
||||||
|
broken,
|
||||||
|
};
|
||||||
|
|
||||||
|
shape: ShapeKind,
|
||||||
|
properties: std.ArrayList(Property),
|
||||||
|
children: std.ArrayList(Object),
|
||||||
|
|
||||||
|
pub fn getProperty(self: Object, tag: std.meta.Tag(PropertyData)) ?*const PropertyData {
|
||||||
|
for (self.properties.items) |*prop| {
|
||||||
|
if (std.meta.activeTag(prop.data) == tag) return &prop.data;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn setProperty(self: *Object, allocator: std.mem.Allocator, prop: Property) !void {
|
||||||
|
for (self.properties.items, 0..) |*p, i| {
|
||||||
|
if (std.meta.activeTag(p.data) == std.meta.activeTag(prop.data)) {
|
||||||
|
if (p.data == .points) p.data.points.deinit(allocator);
|
||||||
|
self.properties.items[i] = prop;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try self.properties.append(allocator, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addChild(self: *Object, allocator: std.mem.Allocator, template: Object) !void {
|
||||||
|
const obj = try template.clone(allocator);
|
||||||
|
try self.children.append(allocator, obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clone(self: Object, allocator: std.mem.Allocator) !Object {
|
||||||
|
var properties_list = std.ArrayList(Property).empty;
|
||||||
|
errdefer properties_list.deinit(allocator);
|
||||||
|
for (self.properties.items) |prop| {
|
||||||
|
try properties_list.append(allocator, try prop.clone(allocator));
|
||||||
|
}
|
||||||
|
|
||||||
|
var children_list = std.ArrayList(Object).empty;
|
||||||
|
errdefer children_list.deinit(allocator);
|
||||||
|
for (self.children.items) |child| {
|
||||||
|
try children_list.append(allocator, try child.clone(allocator));
|
||||||
|
}
|
||||||
|
|
||||||
|
return .{
|
||||||
|
.shape = self.shape,
|
||||||
|
.properties = properties_list,
|
||||||
|
.children = children_list,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *Object, allocator: std.mem.Allocator) void {
|
||||||
|
for (self.children.items) |*child| child.deinit(allocator);
|
||||||
|
self.children.deinit(allocator);
|
||||||
|
for (self.properties.items) |*prop| prop.deinit(allocator);
|
||||||
|
self.properties.deinit(allocator);
|
||||||
|
self.* = undefined;
|
||||||
|
}
|
||||||
77
src/models/Property.zig
Normal file
77
src/models/Property.zig
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const basic_models = @import("basic_models.zig");
|
||||||
|
const Point2 = basic_models.Point2;
|
||||||
|
const Scale2 = basic_models.Scale2;
|
||||||
|
const Size = basic_models.Size;
|
||||||
|
const Radii = basic_models.Radii;
|
||||||
|
|
||||||
|
pub const Data = union(enum) {
|
||||||
|
position: Point2,
|
||||||
|
angle: f32,
|
||||||
|
scale: Scale2,
|
||||||
|
visible: bool,
|
||||||
|
opacity: f32,
|
||||||
|
locked: bool,
|
||||||
|
|
||||||
|
size: Size,
|
||||||
|
radii: Radii,
|
||||||
|
end_point: Point2,
|
||||||
|
|
||||||
|
points: std.ArrayList(Point2),
|
||||||
|
|
||||||
|
fill_rgba: u32,
|
||||||
|
stroke_rgba: u32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Property = struct {
|
||||||
|
data: Data,
|
||||||
|
|
||||||
|
pub fn deinit(self: *Property, allocator: std.mem.Allocator) void {
|
||||||
|
switch (self.data) {
|
||||||
|
.points => |*list| list.deinit(allocator),
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
self.* = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clone(self: Property, allocator: std.mem.Allocator) !Property {
|
||||||
|
return switch (self.data) {
|
||||||
|
.points => |list| .{
|
||||||
|
.data = .{
|
||||||
|
.points = try list.clone(allocator),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
else => .{ .data = self.data },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const default_common_data = [_]Data{
|
||||||
|
.{ .position = .{ .x = 0, .y = 0 } },
|
||||||
|
.{ .angle = 0 },
|
||||||
|
.{ .scale = .{ .scale_x = 1, .scale_y = 1 } },
|
||||||
|
.{ .visible = true },
|
||||||
|
.{ .opacity = 1.0 },
|
||||||
|
.{ .locked = false },
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const defaultCommonProperties: [default_common_data.len]Property = blk: {
|
||||||
|
var result: [default_common_data.len]Property = undefined;
|
||||||
|
for (default_common_data, &result) |d, *p| {
|
||||||
|
p.* = .{ .data = d };
|
||||||
|
}
|
||||||
|
break :blk result;
|
||||||
|
};
|
||||||
|
|
||||||
|
test "Property wrapper and Data" {
|
||||||
|
const p = Property{ .data = .{ .opacity = 0.5 } };
|
||||||
|
try std.testing.expect(p.data == .opacity);
|
||||||
|
try std.testing.expect(p.data.opacity == 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "common properties" {
|
||||||
|
try std.testing.expect(defaultCommonProperties[0].data == .position);
|
||||||
|
try std.testing.expect(defaultCommonProperties[0].data.position.x == 0);
|
||||||
|
try std.testing.expect(defaultCommonProperties[3].data == .visible);
|
||||||
|
try std.testing.expect(defaultCommonProperties[3].data.visible == true);
|
||||||
|
}
|
||||||
39
src/models/basic_models.zig
Normal file
39
src/models/basic_models.zig
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
pub const ImageRect = struct {
|
||||||
|
x: u32,
|
||||||
|
y: u32,
|
||||||
|
w: u32,
|
||||||
|
h: u32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const ImageSize = struct {
|
||||||
|
w: u32,
|
||||||
|
h: u32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Size = struct {
|
||||||
|
width: f32,
|
||||||
|
height: f32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Point2 = struct {
|
||||||
|
x: f32 = 0,
|
||||||
|
y: f32 = 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Radii = struct {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Scale2 = struct {
|
||||||
|
scale_x: f32 = 1,
|
||||||
|
scale_y: f32 = 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Прямоугольник в координатах документа (f32), например локальные границы объекта.
|
||||||
|
pub const Rect = struct {
|
||||||
|
x: f32 = 0,
|
||||||
|
y: f32 = 0,
|
||||||
|
w: f32 = 0,
|
||||||
|
h: f32 = 0,
|
||||||
|
};
|
||||||
23
src/models/shape/arc.zig
Normal file
23
src/models/shape/arc.zig
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Object = @import("../Object.zig");
|
||||||
|
const PropertyData = @import("../Property.zig").Data;
|
||||||
|
const Rect = @import("../basic_models.zig").Rect;
|
||||||
|
const shape_mod = @import("shape.zig");
|
||||||
|
|
||||||
|
/// Теги обязательных свойств (заглушка: arc пока не реализован).
|
||||||
|
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
|
||||||
|
return &[_]std.meta.Tag(PropertyData){};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Добавляет свойства по умолчанию для дуги (заглушка).
|
||||||
|
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
|
||||||
|
_ = allocator;
|
||||||
|
_ = obj;
|
||||||
|
return error.ArcNotImplemented;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Локальные границы дуги (заглушка: пока не реализовано).
|
||||||
|
pub fn getLocalBounds(obj: *const Object) !Rect {
|
||||||
|
try shape_mod.ensure(obj, .arc);
|
||||||
|
return error.ArcNotImplemented;
|
||||||
|
}
|
||||||
49
src/models/shape/broken.zig
Normal file
49
src/models/shape/broken.zig
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Object = @import("../Object.zig");
|
||||||
|
const Property = @import("../Property.zig").Property;
|
||||||
|
const PropertyData = @import("../Property.zig").Data;
|
||||||
|
const Point2 = @import("../basic_models.zig").Point2;
|
||||||
|
const Rect = @import("../basic_models.zig").Rect;
|
||||||
|
const shape_mod = @import("shape.zig");
|
||||||
|
|
||||||
|
/// Точки ломаной по умолчанию (для создания).
|
||||||
|
pub const default_points = [_]Point2{
|
||||||
|
.{ .x = 0, .y = 0 },
|
||||||
|
.{ .x = 80, .y = 0 },
|
||||||
|
.{ .x = 80, .y = 60 },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Теги обязательных свойств (у ломаной нет const default_shape_properties, только default_points).
|
||||||
|
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
|
||||||
|
return &[_]std.meta.Tag(PropertyData){.points};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Добавляет к объекту свойства по умолчанию для ломаной (points из default_points).
|
||||||
|
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
|
||||||
|
var points = std.ArrayList(Point2).empty;
|
||||||
|
try points.appendSlice(allocator, &default_points);
|
||||||
|
try obj.properties.append(allocator, .{ .data = .{ .points = points } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Локальные границы ломаной: AABB по всем точкам.
|
||||||
|
pub fn getLocalBounds(obj: *const Object) !Rect {
|
||||||
|
try shape_mod.ensure(obj, .broken);
|
||||||
|
const p = obj.getProperty(.points).?;
|
||||||
|
if (p.points.items.len == 0) return error.EmptyPoints;
|
||||||
|
var min_x: f32 = p.points.items[0].x;
|
||||||
|
var max_x: f32 = min_x;
|
||||||
|
var min_y: f32 = p.points.items[0].y;
|
||||||
|
var max_y: f32 = min_y;
|
||||||
|
for (p.points.items[1..]) |pt| {
|
||||||
|
min_x = @min(min_x, pt.x);
|
||||||
|
max_x = @max(max_x, pt.x);
|
||||||
|
min_y = @min(min_y, pt.y);
|
||||||
|
max_y = @max(max_y, pt.y);
|
||||||
|
}
|
||||||
|
return .{
|
||||||
|
.x = min_x,
|
||||||
|
.y = min_y,
|
||||||
|
.w = max_x - min_x,
|
||||||
|
.h = max_y - min_y,
|
||||||
|
};
|
||||||
|
}
|
||||||
33
src/models/shape/ellipse.zig
Normal file
33
src/models/shape/ellipse.zig
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Object = @import("../Object.zig");
|
||||||
|
const Property = @import("../Property.zig").Property;
|
||||||
|
const PropertyData = @import("../Property.zig").Data;
|
||||||
|
const Rect = @import("../basic_models.zig").Rect;
|
||||||
|
const shape_mod = @import("shape.zig");
|
||||||
|
|
||||||
|
/// Свойства фигуры по умолчанию (для создания и проверки типа). Теги для ensure выводятся отсюда.
|
||||||
|
pub const default_shape_properties = [_]Property{
|
||||||
|
.{ .data = .{ .radii = .{ .x = 50, .y = 50 } } },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Теги обязательных свойств (выводятся из default_shape_properties).
|
||||||
|
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
|
||||||
|
return &([_]std.meta.Tag(PropertyData){std.meta.activeTag(default_shape_properties[0].data)});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Добавляет к объекту свойства по умолчанию для эллипса.
|
||||||
|
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
|
||||||
|
for (default_shape_properties) |prop| try obj.properties.append(allocator, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Локальные границы эллипса: [-radii.x, -radii.y] .. [radii.x, radii.y].
|
||||||
|
pub fn getLocalBounds(obj: *const Object) !Rect {
|
||||||
|
try shape_mod.ensure(obj, .ellipse);
|
||||||
|
const r = obj.getProperty(.radii).?;
|
||||||
|
return .{
|
||||||
|
.x = -r.radii.x,
|
||||||
|
.y = -r.radii.y,
|
||||||
|
.w = 2 * r.radii.x,
|
||||||
|
.h = 2 * r.radii.y,
|
||||||
|
};
|
||||||
|
}
|
||||||
37
src/models/shape/line.zig
Normal file
37
src/models/shape/line.zig
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Object = @import("../Object.zig");
|
||||||
|
const Property = @import("../Property.zig").Property;
|
||||||
|
const PropertyData = @import("../Property.zig").Data;
|
||||||
|
const Rect = @import("../basic_models.zig").Rect;
|
||||||
|
const shape_mod = @import("shape.zig");
|
||||||
|
|
||||||
|
/// Свойства фигуры по умолчанию (для создания и проверки типа). Теги для ensure выводятся отсюда.
|
||||||
|
pub const default_shape_properties = [_]Property{
|
||||||
|
.{ .data = .{ .end_point = .{ .x = 100, .y = 0 } } },
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Теги обязательных свойств (выводятся из default_shape_properties).
|
||||||
|
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
|
||||||
|
return &([_]std.meta.Tag(PropertyData){std.meta.activeTag(default_shape_properties[0].data)});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Добавляет к объекту свойства по умолчанию для линии.
|
||||||
|
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
|
||||||
|
for (default_shape_properties) |prop| try obj.properties.append(allocator, prop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Локальные границы линии: от (0,0) до end_point.
|
||||||
|
pub fn getLocalBounds(obj: *const Object) !Rect {
|
||||||
|
try shape_mod.ensure(obj, .line);
|
||||||
|
const ep = obj.getProperty(.end_point).?;
|
||||||
|
const min_x = @min(0, ep.end_point.x);
|
||||||
|
const max_x = @max(0, ep.end_point.x);
|
||||||
|
const min_y = @min(0, ep.end_point.y);
|
||||||
|
const max_y = @max(0, ep.end_point.y);
|
||||||
|
return .{
|
||||||
|
.x = min_x,
|
||||||
|
.y = min_y,
|
||||||
|
.w = max_x - min_x,
|
||||||
|
.h = max_y - min_y,
|
||||||
|
};
|
||||||
|
}
|
||||||
95
src/models/shape/shape.zig
Normal file
95
src/models/shape/shape.zig
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const Object = @import("../Object.zig");
|
||||||
|
const Property = @import("../Property.zig").Property;
|
||||||
|
const PropertyData = @import("../Property.zig").Data;
|
||||||
|
const defaultCommonProperties = @import("../Property.zig").defaultCommonProperties;
|
||||||
|
const basic_models = @import("../basic_models.zig");
|
||||||
|
const line = @import("line.zig");
|
||||||
|
const ellipse = @import("ellipse.zig");
|
||||||
|
const broken = @import("broken.zig");
|
||||||
|
const arc = @import("arc.zig");
|
||||||
|
|
||||||
|
pub const Rect = basic_models.Rect;
|
||||||
|
|
||||||
|
/// Создаёт объект с общими свойствами по умолчанию и специфичными для типа фигуры.
|
||||||
|
pub fn createObject(allocator: std.mem.Allocator, shape_kind: Object.ShapeKind) !Object {
|
||||||
|
var obj = try createWithCommonProperties(allocator, shape_kind);
|
||||||
|
errdefer obj.deinit(allocator);
|
||||||
|
switch (shape_kind) {
|
||||||
|
.line => try line.appendDefaultShapeProperties(allocator, &obj),
|
||||||
|
.ellipse => try ellipse.appendDefaultShapeProperties(allocator, &obj),
|
||||||
|
.broken => try broken.appendDefaultShapeProperties(allocator, &obj),
|
||||||
|
.arc => try arc.appendDefaultShapeProperties(allocator, &obj),
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn createWithCommonProperties(allocator: std.mem.Allocator, shape_kind: Object.ShapeKind) !Object {
|
||||||
|
var properties_list = std.ArrayList(Property).empty;
|
||||||
|
errdefer properties_list.deinit(allocator);
|
||||||
|
for (defaultCommonProperties) |prop| try properties_list.append(allocator, prop);
|
||||||
|
return .{
|
||||||
|
.shape = shape_kind,
|
||||||
|
.properties = properties_list,
|
||||||
|
.children = std.ArrayList(Object).empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Проверяет, что объект имеет ожидаемый тип и все требуемые для этого типа свойства.
|
||||||
|
pub fn ensure(obj: *const Object, expected_kind: Object.ShapeKind) !void {
|
||||||
|
if (obj.shape != expected_kind) return error.WrongShapeKind;
|
||||||
|
const tags = requiredTagsFor(expected_kind);
|
||||||
|
for (tags) |tag| {
|
||||||
|
if (obj.getProperty(tag) == null) return error.MissingRequiredProperty;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn requiredTagsFor(kind: Object.ShapeKind) []const std.meta.Tag(PropertyData) {
|
||||||
|
return switch (kind) {
|
||||||
|
.line => line.getRequiredTags(),
|
||||||
|
.ellipse => ellipse.getRequiredTags(),
|
||||||
|
.broken => broken.getRequiredTags(),
|
||||||
|
.arc => arc.getRequiredTags(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Локальные границы объекта (AABB в своих координатах).
|
||||||
|
pub fn getLocalBounds(obj: *const Object) !Rect {
|
||||||
|
return switch (obj.shape) {
|
||||||
|
.line => line.getLocalBounds(obj),
|
||||||
|
.ellipse => ellipse.getLocalBounds(obj),
|
||||||
|
.broken => broken.getLocalBounds(obj),
|
||||||
|
.arc => arc.getLocalBounds(obj),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test "getLocalBounds" {
|
||||||
|
const shape = @This();
|
||||||
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||||
|
defer _ = gpa.deinit();
|
||||||
|
const allocator = gpa.allocator();
|
||||||
|
|
||||||
|
var line_obj = try shape.createObject(allocator, .line);
|
||||||
|
defer line_obj.deinit(allocator);
|
||||||
|
const line_bounds = try getLocalBounds(&line_obj);
|
||||||
|
try std.testing.expect(line_bounds.x == 0);
|
||||||
|
try std.testing.expect(line_bounds.y == 0);
|
||||||
|
try std.testing.expect(line_bounds.w == 100);
|
||||||
|
try std.testing.expect(line_bounds.h == 0);
|
||||||
|
|
||||||
|
var ellipse_obj = try shape.createObject(allocator, .ellipse);
|
||||||
|
defer ellipse_obj.deinit(allocator);
|
||||||
|
const ellipse_bounds = try getLocalBounds(&ellipse_obj);
|
||||||
|
try std.testing.expect(ellipse_bounds.x == -50);
|
||||||
|
try std.testing.expect(ellipse_bounds.y == -50);
|
||||||
|
try std.testing.expect(ellipse_bounds.w == 100);
|
||||||
|
try std.testing.expect(ellipse_bounds.h == 100);
|
||||||
|
|
||||||
|
var broken_obj = try shape.createObject(allocator, .broken);
|
||||||
|
defer broken_obj.deinit(allocator);
|
||||||
|
const broken_bounds = try getLocalBounds(&broken_obj);
|
||||||
|
try std.testing.expect(broken_bounds.x == 0);
|
||||||
|
try std.testing.expect(broken_bounds.y == 0);
|
||||||
|
try std.testing.expect(broken_bounds.w == 80);
|
||||||
|
try std.testing.expect(broken_bounds.h == 60);
|
||||||
|
}
|
||||||
173
src/render/CpuRenderEngine.zig
Normal file
173
src/render/CpuRenderEngine.zig
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const builtin = @import("builtin");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const RenderEngine = @import("RenderEngine.zig").RenderEngine;
|
||||||
|
const basic_models = @import("../models/basic_models.zig");
|
||||||
|
const ImageSize = basic_models.ImageSize;
|
||||||
|
const ImageRect = basic_models.ImageRect;
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
const Color = dvui.Color;
|
||||||
|
|
||||||
|
const CpuRenderEngine = @This();
|
||||||
|
const Type = enum {
|
||||||
|
Gradient,
|
||||||
|
Squares,
|
||||||
|
};
|
||||||
|
|
||||||
|
type: Type,
|
||||||
|
_allocator: Allocator,
|
||||||
|
gradient_start: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 },
|
||||||
|
gradient_end: Color.PMA = .{ .r = 255, .g = 255, .b = 255, .a = 255 },
|
||||||
|
|
||||||
|
pub fn init(allocator: Allocator, render_type: Type) CpuRenderEngine {
|
||||||
|
return .{
|
||||||
|
._allocator = allocator,
|
||||||
|
.type = render_type,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exampleReset(self: *CpuRenderEngine) void {
|
||||||
|
var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));
|
||||||
|
const random = prng.random();
|
||||||
|
self.gradient_start = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 };
|
||||||
|
self.gradient_end = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 };
|
||||||
|
}
|
||||||
|
|
||||||
|
fn renderGradient(self: CpuRenderEngine, pixels: []Color.PMA, width: u32, height: u32, full_w: u32, full_h: u32, visible_rect: ImageRect) void {
|
||||||
|
var y: u32 = 0;
|
||||||
|
while (y < height) : (y += 1) {
|
||||||
|
var x: u32 = 0;
|
||||||
|
while (x < width) : (x += 1) {
|
||||||
|
const gx: u32 = visible_rect.x + x;
|
||||||
|
const gy: u32 = visible_rect.y + y;
|
||||||
|
|
||||||
|
const denom_x: f32 = if (full_w > 1) @as(f32, @floatFromInt(full_w - 1)) else 1;
|
||||||
|
const denom_y: f32 = if (full_h > 1) @as(f32, @floatFromInt(full_h - 1)) else 1;
|
||||||
|
const fx: f32 = @as(f32, @floatFromInt(gx)) / denom_x;
|
||||||
|
const fy: f32 = @as(f32, @floatFromInt(gy)) / denom_y;
|
||||||
|
const factor: f32 = std.math.clamp((fx + fy) / 2, 0, 1);
|
||||||
|
|
||||||
|
const r_f: f32 = @as(f32, @floatFromInt(self.gradient_start.r)) + factor * (@as(f32, @floatFromInt(self.gradient_end.r)) - @as(f32, @floatFromInt(self.gradient_start.r)));
|
||||||
|
const g_f: f32 = @as(f32, @floatFromInt(self.gradient_start.g)) + factor * (@as(f32, @floatFromInt(self.gradient_end.g)) - @as(f32, @floatFromInt(self.gradient_start.g)));
|
||||||
|
const b_f: f32 = @as(f32, @floatFromInt(self.gradient_start.b)) + factor * (@as(f32, @floatFromInt(self.gradient_end.b)) - @as(f32, @floatFromInt(self.gradient_start.b)));
|
||||||
|
|
||||||
|
const r: u8 = @intFromFloat(std.math.clamp(r_f, 0, 255));
|
||||||
|
const g: u8 = @intFromFloat(std.math.clamp(g_f, 0, 255));
|
||||||
|
const b: u8 = @intFromFloat(std.math.clamp(b_f, 0, 255));
|
||||||
|
pixels[y * width + x] = .{ .r = r, .g = g, .b = b, .a = 255 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn renderSquares(self: CpuRenderEngine, pixels: []Color.PMA, canvas_size: ImageSize, visible_rect: ImageRect) void {
|
||||||
|
_ = self;
|
||||||
|
|
||||||
|
const colors = [_]Color.PMA{
|
||||||
|
.{ .r = 255, .g = 0, .b = 0, .a = 255 },
|
||||||
|
.{ .r = 255, .g = 165, .b = 0, .a = 255 },
|
||||||
|
.{ .r = 255, .g = 255, .b = 0, .a = 255 },
|
||||||
|
.{ .r = 0, .g = 255, .b = 0, .a = 255 },
|
||||||
|
.{ .r = 0, .g = 255, .b = 255, .a = 255 },
|
||||||
|
.{ .r = 0, .g = 0, .b = 255, .a = 255 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const squares_num = 5;
|
||||||
|
var thikness: u32 = @intFromFloat(@as(f32, @floatFromInt(canvas_size.w + canvas_size.h)) / 2 * 0.03);
|
||||||
|
if (thikness == 0) thikness = 1;
|
||||||
|
|
||||||
|
const squares_sum_w = canvas_size.w - thikness * (squares_num + 1);
|
||||||
|
const base_w = squares_sum_w / squares_num;
|
||||||
|
const extra_w = squares_sum_w % squares_num;
|
||||||
|
const squares_sum_h = canvas_size.h - thikness * (squares_num + 1);
|
||||||
|
const base_h = squares_sum_h / squares_num;
|
||||||
|
const extra_h = squares_sum_h % squares_num;
|
||||||
|
|
||||||
|
var x_pos: [6]u32 = undefined;
|
||||||
|
x_pos[0] = 0;
|
||||||
|
for (1..squares_num + 1) |i| {
|
||||||
|
const w = base_w + if (i - 1 < extra_w) @as(u32, 1) else 0;
|
||||||
|
x_pos[i] = x_pos[i - 1] + thikness + w;
|
||||||
|
}
|
||||||
|
|
||||||
|
var y_pos: [6]u32 = undefined;
|
||||||
|
y_pos[0] = 0;
|
||||||
|
for (1..squares_num + 1) |i| {
|
||||||
|
const h = base_h + if (i - 1 < extra_h) @as(u32, 1) else 0;
|
||||||
|
y_pos[i] = y_pos[i - 1] + thikness + h;
|
||||||
|
}
|
||||||
|
|
||||||
|
var y: u32 = 0;
|
||||||
|
while (y < visible_rect.h) : (y += 1) {
|
||||||
|
const canvas_y = y + visible_rect.y;
|
||||||
|
if (canvas_y >= canvas_size.h) continue;
|
||||||
|
var x: u32 = 0;
|
||||||
|
while (x < visible_rect.w) : (x += 1) {
|
||||||
|
const canvas_x = x + visible_rect.x;
|
||||||
|
if (canvas_x >= canvas_size.w) continue;
|
||||||
|
|
||||||
|
var vertical_index: ?u32 = null;
|
||||||
|
for (0..x_pos.len) |i| {
|
||||||
|
if (canvas_x >= x_pos[i] and canvas_x < x_pos[i] + thikness) {
|
||||||
|
vertical_index = @intCast(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var horizontal_index: ?u32 = null;
|
||||||
|
for (0..y_pos.len) |i| {
|
||||||
|
if (canvas_y >= y_pos[i] and canvas_y < y_pos[i] + thikness) {
|
||||||
|
horizontal_index = @intCast(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vertical_index) |idx| {
|
||||||
|
pixels[y * visible_rect.w + x] = colors[idx];
|
||||||
|
} else if (horizontal_index) |idx| {
|
||||||
|
pixels[y * visible_rect.w + x] = colors[idx];
|
||||||
|
} else {
|
||||||
|
var square_x: u32 = 0;
|
||||||
|
for (0..squares_num) |i| {
|
||||||
|
if (canvas_x >= x_pos[i] + thikness and canvas_x < x_pos[i + 1]) {
|
||||||
|
square_x = @intCast(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var square_y: u32 = 0;
|
||||||
|
for (0..squares_num) |i| {
|
||||||
|
if (canvas_y >= y_pos[i] + thikness and canvas_y < y_pos[i + 1]) {
|
||||||
|
square_y = @intCast(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (square_x % 2 == square_y % 2) {
|
||||||
|
pixels[y * visible_rect.w + x] = .{ .r = 255, .g = 255, .b = 255, .a = 255 };
|
||||||
|
} else {
|
||||||
|
pixels[y * visible_rect.w + x] = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn example(self: CpuRenderEngine, canvas_size: ImageSize, visible_rect: ImageRect) !?dvui.Texture {
|
||||||
|
const full_w = canvas_size.w;
|
||||||
|
const full_h = canvas_size.h;
|
||||||
|
|
||||||
|
const width = visible_rect.w;
|
||||||
|
const height = visible_rect.h;
|
||||||
|
|
||||||
|
const pixels = try self._allocator.alloc(Color.PMA, @as(usize, width) * height);
|
||||||
|
defer self._allocator.free(pixels);
|
||||||
|
|
||||||
|
switch (self.type) {
|
||||||
|
.Gradient => self.renderGradient(pixels, width, height, full_w, full_h, visible_rect),
|
||||||
|
.Squares => self.renderSquares(pixels, canvas_size, visible_rect),
|
||||||
|
}
|
||||||
|
|
||||||
|
return try dvui.textureCreate(pixels, width, height, .nearest);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn renderEngine(self: *CpuRenderEngine) RenderEngine {
|
||||||
|
return .{ .cpu = self };
|
||||||
|
}
|
||||||
19
src/render/RenderEngine.zig
Normal file
19
src/render/RenderEngine.zig
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const dvui = @import("dvui");
|
||||||
|
const CpuRenderEngine = @import("CpuRenderEngine.zig");
|
||||||
|
const basic_models = @import("../models/basic_models.zig");
|
||||||
|
|
||||||
|
pub const RenderEngine = union(enum) {
|
||||||
|
cpu: *CpuRenderEngine,
|
||||||
|
|
||||||
|
pub fn exampleReset(self: RenderEngine) void {
|
||||||
|
switch (self) {
|
||||||
|
.cpu => |cpu_r| cpu_r.exampleReset(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn example(self: RenderEngine, canvas_size: basic_models.ImageSize, visible_rect: basic_models.ImageRect) !?dvui.Texture {
|
||||||
|
return switch (self) {
|
||||||
|
.cpu => |cpu_r| cpu_r.example(canvas_size, visible_rect),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
14
src/tests.zig
Normal file
14
src/tests.zig
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// Корень для `zig build test`. Тесты из импортированных здесь модулей выполняются (в Zig не подтягиваются из транзитивных импортов).
|
||||||
|
// Добавляй сюда _ = @import("path/to/module.zig"); для каждого модуля с test-блоками.
|
||||||
|
// Чтобы увидеть список всех тестов: после `zig build test` выполни `./zig-out/bin/test`.
|
||||||
|
test "discover tests" {
|
||||||
|
_ = @import("main.zig");
|
||||||
|
_ = @import("models/Property.zig");
|
||||||
|
_ = @import("models/shape/shape.zig");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Убедиться, что выполнились все ожидаемые тесты: этот тест пройдёт только если до него дошли (т.е. все предыдущие прошли).
|
||||||
|
test "all module tests completed" {
|
||||||
|
const std = @import("std");
|
||||||
|
std.debug.print("\n (все тесты модулей выполнены)\n", .{});
|
||||||
|
}
|
||||||
143
src/ui/canvas_view.zig
Normal file
143
src/ui/canvas_view.zig
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const dvui_ext = @import("dvui_ext.zig");
|
||||||
|
const Canvas = @import("../Canvas.zig");
|
||||||
|
const ImageRect = @import("../models/basic_models.zig").ImageRect;
|
||||||
|
|
||||||
|
pub fn canvasView(canvas: *Canvas, content_rect_scale: dvui.RectScale) void {
|
||||||
|
var textured = dvui_ext.texturedBox(content_rect_scale, dvui.Rect.all(20));
|
||||||
|
{
|
||||||
|
var overlay = dvui.overlay(@src(), .{ .expand = .both });
|
||||||
|
{
|
||||||
|
var scroll = dvui.scrollArea(
|
||||||
|
@src(),
|
||||||
|
.{
|
||||||
|
.scroll_info = &canvas.scroll,
|
||||||
|
.vertical_bar = .auto,
|
||||||
|
.horizontal_bar = .auto,
|
||||||
|
},
|
||||||
|
.{ .expand = .both, .background = false },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
drawCanvasContent(canvas, scroll);
|
||||||
|
handleCanvasZoom(canvas, scroll);
|
||||||
|
handleCanvasMouse(canvas, scroll);
|
||||||
|
}
|
||||||
|
scroll.deinit();
|
||||||
|
|
||||||
|
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
|
||||||
|
}
|
||||||
|
overlay.deinit();
|
||||||
|
}
|
||||||
|
textured.deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drawCanvasContent(canvas: *Canvas, scroll: anytype) void {
|
||||||
|
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
|
||||||
|
const img_size = canvas.getZoomedImageSize();
|
||||||
|
const viewport_rect = scroll.data().contentRect();
|
||||||
|
const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y };
|
||||||
|
|
||||||
|
const viewport_px = dvui.Rect{
|
||||||
|
.x = viewport_rect.x * natural_scale,
|
||||||
|
.y = viewport_rect.y * natural_scale,
|
||||||
|
.w = viewport_rect.w * natural_scale,
|
||||||
|
.h = viewport_rect.h * natural_scale,
|
||||||
|
};
|
||||||
|
const scroll_px = dvui.Point{
|
||||||
|
.x = scroll_current.x * natural_scale,
|
||||||
|
.y = scroll_current.y * natural_scale,
|
||||||
|
};
|
||||||
|
|
||||||
|
const changed = canvas.updateVisibleImageRect(viewport_px, scroll_px);
|
||||||
|
if (changed)
|
||||||
|
canvas.requestRedraw();
|
||||||
|
canvas.processPendingRedraw() catch |err| {
|
||||||
|
std.debug.print("processPendingRedraw error: {}\n", .{err});
|
||||||
|
};
|
||||||
|
|
||||||
|
const content_w_px: u32 = img_size.x + img_size.w;
|
||||||
|
const content_h_px: u32 = img_size.y + img_size.h;
|
||||||
|
const content_w = @as(f32, @floatFromInt(content_w_px)) / natural_scale;
|
||||||
|
const content_h = @as(f32, @floatFromInt(content_h_px)) / natural_scale;
|
||||||
|
|
||||||
|
var canvas_layer = dvui.overlay(
|
||||||
|
@src(),
|
||||||
|
.{ .min_size_content = .{ .w = content_w, .h = content_h }, .background = false },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
if (canvas.texture) |tex| {
|
||||||
|
const vis = canvas._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 };
|
||||||
|
const left = @as(f32, @floatFromInt(img_size.x + vis.x)) / natural_scale;
|
||||||
|
const top = @as(f32, @floatFromInt(img_size.y + vis.y)) / natural_scale;
|
||||||
|
|
||||||
|
_ = dvui.image(
|
||||||
|
@src(),
|
||||||
|
.{ .source = .{ .texture = tex } },
|
||||||
|
.{
|
||||||
|
.background = false,
|
||||||
|
.expand = .none,
|
||||||
|
.gravity_x = 0.0,
|
||||||
|
.gravity_y = 0.0,
|
||||||
|
.margin = .{ .x = left, .y = top, .w = canvas.pos.x, .h = canvas.pos.y },
|
||||||
|
.min_size_content = .{
|
||||||
|
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
|
||||||
|
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
|
||||||
|
},
|
||||||
|
.max_size_content = .{
|
||||||
|
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
|
||||||
|
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
canvas_layer.deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handleCanvasZoom(canvas: *Canvas, scroll: anytype) void {
|
||||||
|
const ctrl = dvui.currentWindow().modifiers.control();
|
||||||
|
if (!ctrl) return;
|
||||||
|
|
||||||
|
for (dvui.events()) |*e| {
|
||||||
|
switch (e.evt) {
|
||||||
|
.mouse => |mouse| {
|
||||||
|
const action = mouse.action;
|
||||||
|
if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) {
|
||||||
|
switch (action) {
|
||||||
|
.wheel_y => |y| {
|
||||||
|
canvas.addZoom(y / 1000);
|
||||||
|
canvas.requestRedraw();
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
e.handled = true;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handleCanvasMouse(canvas: *Canvas, scroll: anytype) void {
|
||||||
|
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
|
||||||
|
|
||||||
|
for (dvui.events()) |*e| {
|
||||||
|
switch (e.evt) {
|
||||||
|
.mouse => |*mouse| {
|
||||||
|
if (mouse.action != .press or mouse.button != .left) continue;
|
||||||
|
if (!dvui.eventMatchSimple(e, scroll.data())) continue;
|
||||||
|
|
||||||
|
const viewport_pt = scroll.data().contentRectScale().pointFromPhysical(mouse.p);
|
||||||
|
const content_pt = dvui.Point{
|
||||||
|
.x = viewport_pt.x + canvas.scroll.viewport.x,
|
||||||
|
.y = viewport_pt.y + canvas.scroll.viewport.y,
|
||||||
|
};
|
||||||
|
canvas.cursor_document_point = canvas.contentPointToDocument(content_pt, natural_scale);
|
||||||
|
if (canvas.cursor_document_point) |point|
|
||||||
|
std.debug.print("cursor_document_point: {}\n", .{point});
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
7
src/ui/dvui_ext.zig
Normal file
7
src/ui/dvui_ext.zig
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const TexturedBox = @import("./types/TexturedBox.zig");
|
||||||
|
|
||||||
|
pub fn texturedBox(rs: dvui.RectScale, corner_radius: dvui.Rect) TexturedBox {
|
||||||
|
return TexturedBox.init(rs, corner_radius);
|
||||||
|
}
|
||||||
33
src/ui/frame.zig
Normal file
33
src/ui/frame.zig
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const dvui = @import("dvui");
|
||||||
|
const WindowContext = @import("../WindowContext.zig");
|
||||||
|
const tab_bar = @import("tab_bar.zig");
|
||||||
|
const left_panel = @import("left_panel.zig");
|
||||||
|
const right_panel = @import("right_panel.zig");
|
||||||
|
|
||||||
|
pub fn guiFrame(ctx: *WindowContext) bool {
|
||||||
|
for (dvui.events()) |*e| {
|
||||||
|
if (e.evt == .window and e.evt.window.action == .close) return false;
|
||||||
|
if (e.evt == .app and e.evt.app.action == .quit) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var root = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{ .expand = .both, .background = true, .style = .window },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
tab_bar.tabBar(ctx);
|
||||||
|
|
||||||
|
var content_row = dvui.box(@src(), .{ .dir = .horizontal }, .{ .expand = .both });
|
||||||
|
{
|
||||||
|
left_panel.leftPanel(ctx);
|
||||||
|
|
||||||
|
right_panel.rightPanel(ctx);
|
||||||
|
}
|
||||||
|
content_row.deinit();
|
||||||
|
}
|
||||||
|
root.deinit();
|
||||||
|
|
||||||
|
ctx.frame_index += 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
130
src/ui/left_panel.zig
Normal file
130
src/ui/left_panel.zig
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
const dvui = @import("dvui");
|
||||||
|
const WindowContext = @import("../WindowContext.zig");
|
||||||
|
const Document = @import("../models/Document.zig");
|
||||||
|
const Object = Document.Object;
|
||||||
|
|
||||||
|
const panel_gap: f32 = 12;
|
||||||
|
const panel_padding: f32 = 5;
|
||||||
|
const panel_radius: f32 = 24;
|
||||||
|
const fill_color = dvui.Color.black.opacity(0.2);
|
||||||
|
|
||||||
|
fn shapeLabel(shape: Object.ShapeKind) []const u8 {
|
||||||
|
return switch (shape) {
|
||||||
|
.line => "Line",
|
||||||
|
.ellipse => "Ellipse",
|
||||||
|
.arc => "Arc",
|
||||||
|
.broken => "Broken line",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn objectTreeRow(obj: *const Object, depth: u32, row_id: *usize) void {
|
||||||
|
const id = row_id.*;
|
||||||
|
row_id.* += 1;
|
||||||
|
const indent_px = depth * 18;
|
||||||
|
var row = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .horizontal },
|
||||||
|
.{ .padding = dvui.Rect{ .x = @floatFromInt(indent_px) }, .id_extra = id },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
dvui.labelNoFmt(@src(), shapeLabel(obj.shape), .{}, .{ .id_extra = id });
|
||||||
|
}
|
||||||
|
row.deinit();
|
||||||
|
for (obj.children.items) |*child| {
|
||||||
|
objectTreeRow(child, depth + 1, row_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn objectTree(ctx: *WindowContext) void {
|
||||||
|
const active_doc = ctx.activeDocument();
|
||||||
|
if (active_doc) |open_doc| {
|
||||||
|
const doc = &open_doc.document;
|
||||||
|
if (doc.objects.items.len == 0) {
|
||||||
|
dvui.label(@src(), "No objects", .{}, .{});
|
||||||
|
} else {
|
||||||
|
var row_id: usize = 0;
|
||||||
|
for (doc.objects.items) |*obj| {
|
||||||
|
objectTreeRow(obj, 0, &row_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dvui.label(@src(), "No document", .{}, .{});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn leftPanel(ctx: *WindowContext) void {
|
||||||
|
var padding = dvui.Rect.all(panel_gap);
|
||||||
|
padding.w = 0;
|
||||||
|
var panel = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.expand = .vertical,
|
||||||
|
.min_size_content = .{ .w = 220 },
|
||||||
|
.background = true,
|
||||||
|
.padding = padding,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
// Верхняя часть: дерево объектов
|
||||||
|
var tree_section = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.expand = .both,
|
||||||
|
.padding = dvui.Rect.all(panel_padding),
|
||||||
|
.corner_radius = dvui.Rect.all(panel_radius),
|
||||||
|
.color_fill = fill_color,
|
||||||
|
.background = true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
dvui.label(@src(), "Objects", .{}, .{});
|
||||||
|
var scroll = dvui.scrollArea(
|
||||||
|
@src(),
|
||||||
|
.{ .vertical = .auto },
|
||||||
|
.{ .expand = .vertical, .background = false },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
objectTree(ctx);
|
||||||
|
}
|
||||||
|
scroll.deinit();
|
||||||
|
}
|
||||||
|
tree_section.deinit();
|
||||||
|
|
||||||
|
// Нижняя часть: настройки
|
||||||
|
var settings_section = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.expand = .horizontal,
|
||||||
|
.margin = .{ .y = 5 },
|
||||||
|
.padding = dvui.Rect.all(panel_padding),
|
||||||
|
.corner_radius = dvui.Rect.all(panel_radius),
|
||||||
|
.color_fill = fill_color,
|
||||||
|
.background = true,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
dvui.label(@src(), "Settings", .{}, .{});
|
||||||
|
|
||||||
|
const active_doc = ctx.activeDocument();
|
||||||
|
if (active_doc) |doc| {
|
||||||
|
const canvas = &doc.canvas;
|
||||||
|
if (dvui.checkbox(@src(), &canvas.native_scaling, "Scaling", .{})) {}
|
||||||
|
if (dvui.button(@src(), if (doc.cpu_render.type == .Gradient) "Gradient" else "Squares", .{}, .{})) {
|
||||||
|
if (doc.cpu_render.type == .Gradient) {
|
||||||
|
doc.cpu_render.type = .Squares;
|
||||||
|
} else {
|
||||||
|
doc.cpu_render.type = .Gradient;
|
||||||
|
}
|
||||||
|
canvas.redrawExample() catch {};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dvui.label(@src(), "No document", .{}, .{});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
settings_section.deinit();
|
||||||
|
}
|
||||||
|
panel.deinit();
|
||||||
|
}
|
||||||
68
src/ui/right_panel.zig
Normal file
68
src/ui/right_panel.zig
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const WindowContext = @import("../WindowContext.zig");
|
||||||
|
const canvas_view = @import("canvas_view.zig");
|
||||||
|
|
||||||
|
pub fn rightPanel(ctx: *WindowContext) void {
|
||||||
|
const fill_color = dvui.Color.black.opacity(0.25);
|
||||||
|
var back = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .horizontal },
|
||||||
|
.{ .expand = .both, .padding = dvui.Rect.all(12), .background = true },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
var panel = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.expand = .both,
|
||||||
|
.background = true,
|
||||||
|
.padding = dvui.Rect.all(5),
|
||||||
|
.corner_radius = dvui.Rect.all(24),
|
||||||
|
.color_fill = fill_color,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
const active_doc = ctx.activeDocument();
|
||||||
|
if (active_doc) |doc| {
|
||||||
|
const content_rect_scale = panel.data().contentRectScale();
|
||||||
|
canvas_view.canvasView(&doc.canvas, content_rect_scale);
|
||||||
|
} else {
|
||||||
|
noDocView(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panel.deinit();
|
||||||
|
}
|
||||||
|
back.deinit();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn noDocView(ctx: *WindowContext) void {
|
||||||
|
var center = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.expand = .both,
|
||||||
|
.padding = dvui.Rect.all(20),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
var box = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .vertical },
|
||||||
|
.{
|
||||||
|
.gravity_x = 0.5,
|
||||||
|
.gravity_y = 0.5,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
{
|
||||||
|
dvui.label(@src(), "No document open", .{}, .{});
|
||||||
|
if (dvui.button(@src(), "New document", .{}, .{})) {
|
||||||
|
ctx.addNewDocument() catch |err| {
|
||||||
|
std.debug.print("addNewDocument error: {}\n", .{err});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
box.deinit();
|
||||||
|
}
|
||||||
|
center.deinit();
|
||||||
|
}
|
||||||
26
src/ui/tab_bar.zig
Normal file
26
src/ui/tab_bar.zig
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const WindowContext = @import("../WindowContext.zig");
|
||||||
|
|
||||||
|
pub fn tabBar(ctx: *WindowContext) void {
|
||||||
|
var bar = dvui.box(
|
||||||
|
@src(),
|
||||||
|
.{ .dir = .horizontal },
|
||||||
|
.{ .expand = .horizontal, .min_size_content = .{ .h = 32 }, .background = true, .padding = dvui.Rect.all(4) },
|
||||||
|
);
|
||||||
|
{
|
||||||
|
for (ctx.documents.items, 0..) |_, i| {
|
||||||
|
var buf: [32]u8 = undefined;
|
||||||
|
const label = std.fmt.bufPrint(&buf, "Doc {d}", .{i + 1}) catch "Doc";
|
||||||
|
if (dvui.button(@src(), label, .{}, .{ .id_extra = i })) {
|
||||||
|
ctx.setActiveDocument(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dvui.button(@src(), "+", .{}, .{})) {
|
||||||
|
ctx.addNewDocument() catch |err| {
|
||||||
|
std.debug.print("addNewDocument error: {}\n", .{err});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bar.deinit();
|
||||||
|
}
|
||||||
33
src/ui/types/TexturedBox.zig
Normal file
33
src/ui/types/TexturedBox.zig
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const std = @import("std");
|
||||||
|
const dvui = @import("dvui");
|
||||||
|
const TexturedBox = @This();
|
||||||
|
|
||||||
|
parent: dvui.Widget,
|
||||||
|
rs: dvui.RectScale,
|
||||||
|
pic: ?dvui.Picture,
|
||||||
|
corner_radius: dvui.Rect,
|
||||||
|
|
||||||
|
pub fn init(rs: dvui.RectScale, corner_radius: dvui.Rect) TexturedBox {
|
||||||
|
const parent = dvui.parentGet();
|
||||||
|
const pic = dvui.Picture.start(rs.r);
|
||||||
|
return .{
|
||||||
|
.parent = parent,
|
||||||
|
.corner_radius = corner_radius,
|
||||||
|
.rs = rs,
|
||||||
|
.pic = pic,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *TexturedBox) void {
|
||||||
|
if (self.pic) |*picture| {
|
||||||
|
picture.stop();
|
||||||
|
|
||||||
|
const tex = dvui.textureFromTarget(picture.texture) catch null;
|
||||||
|
if (tex) |t| {
|
||||||
|
dvui.Texture.destroyLater(t);
|
||||||
|
dvui.renderTexture(t, self.rs, .{
|
||||||
|
.corner_radius = self.corner_radius,
|
||||||
|
}) catch {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user