Compare commits

...

64 Commits

Author SHA1 Message Date
bf63729124 убраны круги из линий 2026-02-26 18:49:15 +03:00
40b3b0ad10 Правильная толщина 2026-02-26 18:16:33 +03:00
d070c1660f Улучшайки 2026-02-26 15:58:26 +03:00
6212d8d6aa Дерево объектов хорошее 2026-02-26 15:45:54 +03:00
93f7f3d814 начало дерева объектов 2026-02-26 15:16:43 +03:00
05f5481a42 Дополнительный буфер для отрисовки broken line 2026-02-26 13:48:42 +03:00
0eee436150 llvm 2026-02-26 12:42:45 +03:00
01b76ede64 Оптимизация круга 2026-02-26 00:39:11 +03:00
faf79367f6 Толщина круга 2026-02-26 00:32:59 +03:00
f8731bde87 Толщина линии 2026-02-26 00:23:10 +03:00
563c2a7535 Кнопка для добавления случайных фигур 2026-02-26 00:03:22 +03:00
b6e14cd74d Теперь сквозь тулбар не кликается на холст 2026-02-25 23:59:46 +03:00
790200be2a Добавлены остальные инструменты 2026-02-25 23:20:30 +03:00
65ca468bfb Убраны лишние комментарии 2026-02-25 22:46:45 +03:00
317ebb958b Убрано лишнее умножение на Alpha 2026-02-25 22:37:52 +03:00
31ba2c57cb Поправлены цвета 2026-02-25 22:31:50 +03:00
5c9ec3167a рефакторинг небольшой 2026-02-25 21:27:02 +03:00
9202b527e4 Первая версия тулбара 2026-02-25 21:13:38 +03:00
0d546782bb Поправлена панель настроек 2026-02-25 19:14:06 +03:00
0ee7be2002 Зум к курсору 2026-02-25 18:26:08 +03:00
23111172d8 правка 2026-02-25 01:22:42 +03:00
0114db1f48 feat: Добавил толщину линий, унифицировал геометрию
Переименовал основные геометрические модели (Point, Size, Rect, Scale, Radii), явно разделив их на типы с плавающей точкой (_f) и целочисленные (_i). Обновил использование этих типов во всем проекте для улучшения типобезопасности и ясности.

Ввел новое свойство thickness для объектов и реализовал его применение при отрисовке линий и ломаных. Добавил Point2_i для целочисленных координат буфера в конвейере отрисовки.
2026-02-25 00:57:55 +03:00
1d995995e7 Рефакторинг ещё... 2026-02-24 23:52:13 +03:00
e5dd455d14 Первая растеризация 2026-02-24 21:56:15 +03:00
ef768e9fe7 Первые попытки рисовать 2026-02-24 20:51:40 +03:00
4f386c981c Refactor: Переместил модуль shape
Я переместил модуль shape в подкаталог shape/ для лучшей организации кода.

Изменил пути импорта в связанных файлах, чтобы соответствовать новому местоположению модуля.

Удалил возвраты null из `getLocalBounds` и заменил их на обработку ошибок для улучшения надежности.
2026-02-24 20:34:14 +03:00
f1a0e84272 Refactor: Перенёс логику создания фигур
Я перенёс логику создания объектов фигур из `Document.zig` и `Object.zig` в новый модуль `shape.zig`. Это упрощает добавление новых фигур и улучшает организацию кода.
2026-02-24 19:59:57 +03:00
1a94cc8bfd Случайное дерево объектов 2026-02-24 00:39:40 +03:00
aeda3ee0d0 Возможность добавлять объекты в документ 2026-02-23 23:52:47 +03:00
dd9d5deb92 Базовая модель готова 2026-02-23 23:37:02 +03:00
bd58286c98 Убраны комментарии лишние и улучшены модели 2026-02-23 23:01:49 +03:00
b896a67fd4 Позиция мыши в координатах документа 2026-02-23 22:21:59 +03:00
1dda9c9d15 Улучшение 2026-02-23 20:05:24 +03:00
b30865d105 Refactor: Разделил UI на модули
Разделил главный фрейм UI на отдельные модули: tab_bar, left_panel, right_panel и canvas_view. Это улучшает читаемость и поддерживает принцип единственной ответственности.
Также изменил функцию `updateVisibleImageRect`, чтобы она возвращала `bool`, указывающий на необходимость перерисовки.
2026-02-23 19:58:49 +03:00
6ae927c4b7 Удалил слои, добавил древовидность объектов
Удалил структуру слоев. Теперь объекты хранятся непосредственно в документе, а вложенность реализуется через поле children структуры Object. Это упростило структуру документа и позволило создавать иерархические объекты.
2026-02-23 19:33:51 +03:00
c73d710513 Объекты в документе 2026-02-23 19:29:21 +03:00
0b287e800d 20 фпс 2026-02-22 22:25:53 +03:00
b6012f1fc4 Ограничение частоты перерисовки до 20 фпс 2026-02-22 22:25:49 +03:00
85a3bac095 Документ в канвасе 2026-02-22 22:09:40 +03:00
bee9513ba0 Вкладки документов 2026-02-22 22:01:41 +03:00
48824532f1 Дополнительные базовые модели 2026-02-22 20:38:03 +03:00
7dc7069186 Окно хранит документы 2026-02-22 00:55:08 +03:00
fd0ba8b583 Оживление проекта 2026-02-22 00:42:18 +03:00
8532114673 Прикольные цвета для сетки 2026-01-22 19:12:42 +03:00
df467df5d6 Убрана текстура для проверки 2026-01-22 18:17:08 +03:00
9687d9cab5 renderTexture example 2026-01-22 17:31:59 +03:00
716b6fbeea ПРавильные прямоугольники 2025-12-24 22:24:48 +03:00
e7a0c20353 кнопка для переключения сэмпла 2025-12-21 19:27:45 +03:00
070c8bad2d правильное определение видимой области 2025-12-21 19:22:38 +03:00
d640269cad Переход на CpuRenderEngine 2025-12-21 17:37:43 +03:00
3ac35a5046 Переход к RenderEngine 2025-12-21 17:26:19 +03:00
6f58967049 микроправки 2025-12-20 21:57:10 +03:00
8f462cc93b Миничистка 2025-12-20 21:16:52 +03:00
643aaee926 Скейлинг 2025-12-20 20:47:37 +03:00
b49ee3e46c Убрано масштабирование от системы 2025-12-20 19:07:59 +03:00
b5d60d67dd Первые попытки проверки видимой части 2025-12-20 18:05:28 +03:00
e22051c1c1 Рабочий зум 2025-12-19 21:57:51 +03:00
183726aed4 Градиент вместо фигни какой то 2025-12-18 22:24:30 +03:00
4f0fb09185 Canvas в отдельном файле 2025-12-18 22:24:20 +03:00
bb825d0225 какое то скроллирование 2025-12-18 21:49:01 +03:00
b852384322 скругление 2025-12-18 21:41:21 +03:00
d4a2f41a51 Вывод текстуры 2025-12-18 19:35:47 +03:00
bca66e3815 Наброски UI 2025-12-10 00:28:10 +03:00
7a5f9d62a8 Revert "Окна открываются и закрываются"
This reverts commit 68a4647e3f.
2025-12-07 18:00:18 +03:00
42 changed files with 2553 additions and 202 deletions

9
.vscode/launch.json vendored
View File

@@ -10,5 +10,14 @@
"cwd": "${workspaceFolder}", "cwd": "${workspaceFolder}",
"preLaunchTask": "zig: build" "preLaunchTask": "zig: build"
}, },
{
"name": "Zig: Debug (gdb)",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/Zivro",
"cwd": "${workspaceFolder}",
"MIMode": "gdb",
"preLaunchTask": "zig: build"
},
] ]
} }

7
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"zig.testArgs": [
"build",
"test",
"-Dtest-filter=${filter}"
]
}

6
.vscode/tasks.json vendored
View File

@@ -9,12 +9,6 @@
"kind": "build", "kind": "build",
"isDefault": true "isDefault": true
}, },
"problemMatcher": ["$gcc"],
"presentation": {
"reveal": "always",
"panel": "shared",
"showReuseMessage": true
}
} }
] ]
} }

0
assets/icons/.gitkeep Normal file
View File

View File

@@ -8,11 +8,11 @@ pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ const exe = b.addExecutable(.{
.name = "Zivro", .name = "Zivro",
.use_llvm = optimize == .Debug,
.root_module = b.createModule(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"), .root_source_file = b.path("src/main.zig"),
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
.imports = &.{ .imports = &.{
.{ .name = "dvui", .module = dvui_dep.module("dvui_sdl3") }, .{ .name = "dvui", .module = dvui_dep.module("dvui_sdl3") },
.{ .name = "sdl-backend", .module = dvui_dep.module("sdl3") }, .{ .name = "sdl-backend", .module = dvui_dep.module("sdl3") },
@@ -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);

190
src/Canvas.zig Normal file
View File

@@ -0,0 +1,190 @@
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 basic_models = @import("models/basic_models.zig");
const Rect_i = basic_models.Rect_i;
const Size_i = basic_models.Size_i;
const Point2_f = @import("models/basic_models.zig").Point2_f;
const Color = dvui.Color;
const tools = @import("tools.zig");
const Toolbar = @import("Toolbar.zig");
const random_document = @import("random_document.zig");
const Canvas = @This();
allocator: std.mem.Allocator,
document: *Document,
render_engine: RenderEngine,
toolbar: Toolbar,
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: ?Rect_i = null,
_zoom: f32 = 1,
_redraw_pending: bool = false,
_last_redraw_time_ms: i64 = 0,
cursor_document_point: ?Point2_f = null,
draw_document: bool = true,
/// Rect тулбара (из предыдущего кадра) для исключения кликов по нему из handleCanvasMouse.
toolbar_rect_scale: ?dvui.RectScale = null,
pub fn init(allocator: std.mem.Allocator, document: *Document, engine: RenderEngine) Canvas {
return .{
.allocator = allocator,
.document = document,
.render_engine = engine,
.toolbar = Toolbar.init(&tools.default_tools),
};
}
pub fn deinit(self: *Canvas) void {
self.toolbar.deinit();
if (self.texture) |texture| {
dvui.Texture.destroyLater(texture);
self.texture = null;
}
}
fn redraw(self: *Canvas) !void {
const full = self.getZoomedImageSize();
const vis: Rect_i = self._visible_rect orelse Rect_i{ .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 canvas_size: Size_i = .{ .w = full.w, .h = full.h };
const new_texture = if (self.draw_document)
self.render_engine.render(self.document, canvas_size, vis) catch null
else
self.render_engine.example(canvas_size, 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.redraw();
}
pub fn addRandomShapes(self: *Canvas) !void {
try random_document.addRandomShapes(self.document, std.crypto.random);
self.requestRedraw();
}
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 getZoom(self: Canvas) f32 {
return self._zoom;
}
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.redraw();
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.redraw();
}
pub fn getZoomedImageSize(self: Canvas) Rect_i {
const doc = self.document;
return .{
.x = @intFromFloat(self.pos.x),
.y = @intFromFloat(self.pos.y),
.w = @intFromFloat(doc.size.w * self._zoom),
.h = @intFromFloat(doc.size.h * self._zoom),
};
}
/// Точка контента -> координаты документа.
pub fn contentPointToDocument(self: Canvas, content_point: dvui.Point, natural_scale: f32) Point2_f {
const img = self.getZoomedImageSize();
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 .{
.x = px_x / self._zoom,
.y = px_y / self._zoom,
};
}
/// Точка контента внутри холста.
pub fn isContentPointOnDocument(self: Canvas, content_point: dvui.Point, natural_scale: f32) bool {
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;
return content_point.x >= left_n and content_point.x < right_n and
content_point.y >= top_n and content_point.y < bottom_n;
}
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 or self.texture == null) {
return true;
}
return false;
}
fn computeVisibleImageRect(self: Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) Rect_i {
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 Rect_i{
.x = vis_x,
.y = vis_y,
.w = vis_w,
.h = vis_h,
};
}

11
src/Tool.zig Normal file
View File

@@ -0,0 +1,11 @@
const Point2_f = @import("models/basic_models.zig").Point2_f;
const Canvas = @import("Canvas.zig");
pub const ToolContext = struct {
canvas: *Canvas,
document_point: Point2_f,
};
pub const Tool = struct {
onCanvasClick: *const fn (*const ToolContext) anyerror!void,
};

43
src/Toolbar.zig Normal file
View File

@@ -0,0 +1,43 @@
const Tool = @import("Tool.zig");
const Toolbar = @This();
pub const ToolDescriptor = struct {
name: []const u8,
icon_tvg: []const u8,
implementation: *const Tool.Tool,
};
tools: []const ToolDescriptor,
selected_index: ?usize,
pub fn init(tools_list: []const ToolDescriptor) Toolbar {
return .{
.tools = tools_list,
.selected_index = null,
};
}
pub fn deinit(_: *Toolbar) void {}
pub fn currentDescriptor(self: *const Toolbar) ?*const ToolDescriptor {
if (self.tools.len == 0) return null;
if (self.selected_index) |index| {
return &self.tools[index];
}
return null;
}
pub fn select(self: *Toolbar, index: ?usize) void {
if (index == self.selected_index) {
self.selected_index = null;
return;
}
if (index) |i| {
if (i < self.tools.len) {
self.selected_index = i;
}
} else {
self.selected_index = null;
}
}

99
src/WindowContext.zig Normal file
View File

@@ -0,0 +1,99 @@
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 random_document = @import("random_document.zig");
const basic_models = @import("models/basic_models.zig");
const WindowContext = @This();
pub const OpenDocument = struct {
document: Document,
cpu_render: CpuRenderEngine,
canvas: Canvas,
/// Выбранный объект в дереве (указатель, не индекс).
selected_object: ?*Document.Object = null,
pub fn init(allocator: std.mem.Allocator, self: *OpenDocument) void {
const default_size = basic_models.Size_f{ .w = 800, .h = 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 random_document.addRandomShapes(&ptr.document, 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;
}
}
}
}

7
src/icons.zig Normal file
View File

@@ -0,0 +1,7 @@
const dvui = @import("dvui");
pub const line = dvui.entypo.line_graph;
pub const ellipse = dvui.entypo.circle;
pub const arc = dvui.entypo.loop;
pub const broken = dvui.entypo.flow_line;
pub const trash = dvui.entypo.trash;

View File

@@ -1,215 +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 WindowContext = @import("WindowContext.zig");
const WindowContext = struct { const ui = @import("ui/frame.zig");
backend: SDLBackend,
window: dvui.Window,
title: [:0]u8,
id: usize,
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;
}
};
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 {
for (windows.items, 0..) |ctx, i| {
const last = i + 1 == windows.items.len;
ctx.deinit(allocator, last);
allocator.destroy(ctx);
}
windows.deinit(allocator);
}
var next_window_id: usize = 1;
const first_ctx = try createWindow(allocator, next_window_id);
next_window_id += 1;
try windows.append(allocator, first_ctx);
var interrupted = false;
main_loop: while (true) {
if (windows.items.len == 0) break :main_loop;
const saw_events = try pumpEvents(&windows);
var min_wait_event_micros: u32 = std.math.maxInt(u32);
var idx: usize = 0;
while (idx < windows.items.len) {
const ctx = windows.items[idx];
// beginWait coordinates with waitTime below to run frames only when needed
const nstime = ctx.window.beginWait(interrupted);
// marks the beginning of a frame for dvui, can call dvui functions after this
try ctx.window.begin(nstime);
// if dvui widgets might not cover the whole window, then need to clear
// the previous frame's render
_ = SDLBackend.c.SDL_SetRenderDrawColor(ctx.backend.renderer, 0, 0, 0, 255);
_ = SDLBackend.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;
}
// marks end of dvui frame, don't call dvui functions after this
// - sends all dvui stuff to backend for rendering, must be called before renderPresent()
const end_micros = 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();
// waitTime and beginWait combine to achieve variable framerates
const wait_event_micros = ctx.window.waitTime(end_micros);
min_wait_event_micros = @min(min_wait_event_micros, wait_event_micros);
idx += 1;
}
if (windows.items.len == 0) break :main_loop;
interrupted = saw_events or try windows.items[0].backend.waitEventTimeout(min_wait_event_micros);
}
}
fn createWindow(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, .allocator = allocator,
.size = .{ .w = 800.0, .h = 600.0 }, .size = .{ .w = 800.0, .h = 600.0 },
.title = ctx.title, .title = "My DVUI App",
.vsync = true, .vsync = true,
}); });
errdefer destroyBackendKeepingSDL(&ctx.backend); defer backend.deinit();
const theme = switch (ctx.backend.preferredColorScheme() orelse .light) { var win = try dvui.Window.init(@src(), allocator, backend.backend(), .{
.theme = switch (backend.preferredColorScheme() orelse .light) {
.light => dvui.Theme.builtin.adwaita_light, .light => dvui.Theme.builtin.adwaita_light,
.dark => dvui.Theme.builtin.adwaita_dark, .dark => dvui.Theme.builtin.adwaita_dark,
}; },
});
defer win.deinit();
ctx.window = try dvui.Window.init(@src(), allocator, ctx.backend.backend(), .{ .theme = theme }); var ctx = try WindowContext.init(allocator);
errdefer ctx.window.deinit(); defer ctx.deinit();
return ctx; var interrupted = false;
} main_loop: while (true) {
const nstime = win.beginWait(interrupted);
try win.begin(nstime);
try backend.addAllEvents(&win);
fn closeWindow(windows: *std.ArrayList(*WindowContext), allocator: std.mem.Allocator, idx: usize) void { _ = SDLBackend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
const last = windows.items.len == 1; _ = SDLBackend.c.SDL_RenderClear(backend.renderer);
const ctx = windows.swapRemove(idx);
ctx.deinit(allocator, last);
allocator.destroy(ctx);
}
fn destroyBackendKeepingSDL(backend: *SDLBackend) void { if (!ui.guiFrame(&ctx)) break :main_loop;
SDLBackend.c.SDL_DestroyRenderer(backend.renderer);
SDLBackend.c.SDL_DestroyWindow(backend.window);
backend.we_own_window = false;
backend.deinit();
}
fn windowId(ctx: *WindowContext) u32 { const end_micros = try win.end(.{});
return @intCast(SDLBackend.c.SDL_GetWindowID(ctx.backend.window)); try backend.setCursor(win.cursorRequested());
} try backend.textInputRect(win.textInputRequested());
try backend.renderPresent();
fn eventWindowId(event: SDLBackend.c.SDL_Event) ?u32 { const wait_event_micros = win.waitTime(end_micros);
return switch (event.type) { interrupted = try backend.waitEventTimeout(wait_event_micros);
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_KEY_DOWN else SDLBackend.c.SDL_KEYDOWN => @intCast(event.key.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_KEY_UP else SDLBackend.c.SDL_KEYUP => @intCast(event.key.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_TEXT_INPUT else SDLBackend.c.SDL_TEXTINPUT => @intCast(event.text.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_TEXT_EDITING else SDLBackend.c.SDL_TEXTEDITING => @intCast(event.edit.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_MOTION else SDLBackend.c.SDL_MOUSEMOTION => @intCast(event.motion.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_BUTTON_DOWN else SDLBackend.c.SDL_MOUSEBUTTONDOWN => @intCast(event.button.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_BUTTON_UP else SDLBackend.c.SDL_MOUSEBUTTONUP => @intCast(event.button.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_MOUSE_WHEEL else SDLBackend.c.SDL_MOUSEWHEEL => @intCast(event.wheel.windowID),
if (SDLBackend.sdl3) SDLBackend.c.SDL_EVENT_WINDOW_CLOSE_REQUESTED else SDLBackend.c.SDL_WINDOWEVENT => @intCast(event.window.windowID),
else => null,
};
}
fn pumpEvents(windows: *std.ArrayList(*WindowContext)) !bool {
var event: SDLBackend.c.SDL_Event = undefined;
const poll_got_event = if (SDLBackend.sdl3) true else 1;
var saw_event = false;
while (SDLBackend.c.SDL_PollEvent(&event) == poll_got_event) {
saw_event = true;
if (eventWindowId(event)) |wid| {
for (windows.items) |ctx| {
if (windowId(ctx) == wid) {
_ = try ctx.backend.addEvent(&ctx.window, event);
break;
} }
}
} else {
// 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;
// Treat SDL_QUIT as a global request; ignore here so other windows keep running.
}
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}, .{});
if (dvui.button(@src(), "New window", .{}, .{})) {
const id = next_window_id.*;
next_window_id.* += 1;
const new_ctx = try createWindow(allocator, id);
try windows.append(allocator, new_ctx);
}
return true;
} }

63
src/models/Document.zig Normal file
View File

@@ -0,0 +1,63 @@
const std = @import("std");
const basic_models = @import("basic_models.zig");
const Size_f = basic_models.Size_f;
const Document = @This();
pub const Object = @import("Object.zig");
const shape = @import("shape/shape.zig");
size: Size_f,
allocator: std.mem.Allocator,
objects: std.ArrayList(Object),
pub fn init(allocator: std.mem.Allocator, size: Size_f) 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);
}
}
/// Удаляет объект из документа (из корня или из детей родителя). Возвращает true, если объект был найден и удалён.
pub fn removeObject(self: *Document, obj: *Object) bool {
for (self.objects.items, 0..) |*item, i| {
if (item == obj) {
var removed = self.objects.orderedRemove(i);
removed.deinit(self.allocator);
return true;
}
if (removeFromChildren(self.allocator, &item.children, obj)) return true;
}
return false;
}
fn removeFromChildren(allocator: std.mem.Allocator, children: *std.ArrayList(Object), obj: *Object) bool {
for (children.items, 0..) |*item, i| {
if (item == obj) {
var removed = children.orderedRemove(i);
removed.deinit(allocator);
return true;
}
if (removeFromChildren(allocator, &item.children, obj)) return true;
}
return false;
}

85
src/models/Object.zig Normal file
View File

@@ -0,0 +1,85 @@
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,
};
const default_common_data = [_]PropertyData{
.{ .position = .{ .x = 0, .y = 0 } },
.{ .angle = 0 },
.{ .scale = .{ .scale_x = 1, .scale_y = 1 } },
.{ .visible = true },
.{ .opacity = 1.0 },
.{ .locked = false },
.{ .stroke_rgba = 0x000000FF }, // чёрный, полная непрозрачность
.{ .thickness = 2.0 },
};
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;
};
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;
}
}
return error.PropertyNotFound;
}
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;
}

51
src/models/Property.zig Normal file
View File

@@ -0,0 +1,51 @@
const std = @import("std");
const basic_models = @import("basic_models.zig");
const Point2_f = basic_models.Point2_f;
const Scale2_f = basic_models.Scale2_f;
const Size_f = basic_models.Size_f;
const Radii_f = basic_models.Radii_f;
pub const Data = union(enum) {
position: Point2_f,
angle: f32,
scale: Scale2_f,
visible: bool,
opacity: f32,
locked: bool,
size: Size_f,
radii: Radii_f,
end_point: Point2_f,
points: std.ArrayList(Point2_f),
/// Цвет заливки, 0xRRGGBBAA.
fill_rgba: u32,
/// Цвет обводки, 0xRRGGBBAA.
stroke_rgba: u32,
thickness: f32,
};
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 },
};
}
};

View File

@@ -0,0 +1,43 @@
pub const Rect_i = struct {
x: u32,
y: u32,
w: u32,
h: u32,
};
pub const Size_i = struct {
w: u32,
h: u32,
};
pub const Size_f = struct {
w: f32,
h: f32,
};
pub const Point2_f = struct {
x: f32 = 0,
y: f32 = 0,
};
pub const Point2_i = struct {
x: i32 = 0,
y: i32 = 0,
};
pub const Radii_f = struct {
x: f32,
y: f32,
};
pub const Scale2_f = struct {
scale_x: f32 = 1,
scale_y: f32 = 1,
};
pub const Rect_f = struct {
x: f32 = 0,
y: f32 = 0,
w: f32 = 0,
h: f32 = 0,
};

23
src/models/shape/arc.zig Normal file
View File

@@ -0,0 +1,23 @@
const std = @import("std");
const Object = @import("../Object.zig");
const PropertyData = @import("../Property.zig").Data;
const Rect_f = @import("../basic_models.zig").Rect_f;
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_f {
try shape_mod.ensure(obj, .arc);
return error.ArcNotImplemented;
}

View File

@@ -0,0 +1,51 @@
const std = @import("std");
const Object = @import("../Object.zig");
const Property = @import("../Property.zig").Property;
const PropertyData = @import("../Property.zig").Data;
const Point2_f = @import("../basic_models.zig").Point2_f;
const Rect_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Точки ломаной по умолчанию.
pub const default_points = [_]Point2_f{
.{ .x = 0, .y = 0 },
.{ .x = 80, .y = 0 },
.{ .x = 80, .y = 60 },
};
/// Теги обязательных свойств.
pub fn getRequiredTags() []const std.meta.Tag(PropertyData) {
return &[_]std.meta.Tag(PropertyData){
.points,
};
}
/// Добавляет к объекту свойства по умолчанию для ломаной.
pub fn appendDefaultShapeProperties(allocator: std.mem.Allocator, obj: *Object) !void {
var points = std.ArrayList(Point2_f).empty;
try points.appendSlice(allocator, &default_points);
try obj.properties.append(allocator, .{ .data = .{ .points = points } });
}
/// Локальные границы: AABB по точкам.
pub fn getLocalBounds(obj: *const Object) !Rect_f {
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,
};
}

View 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_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Свойства фигуры по умолчанию.
pub const default_shape_properties = [_]Property{
.{ .data = .{ .radii = .{ .x = 50, .y = 50 } } },
};
/// Теги обязательных свойств.
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_f {
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
View 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_f = @import("../basic_models.zig").Rect_f;
const shape_mod = @import("shape.zig");
/// Свойства фигуры по умолчанию.
pub const default_shape_properties = [_]Property{
.{ .data = .{ .end_point = .{ .x = 100, .y = 200 } } },
};
/// Теги обязательных свойств.
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_f {
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,
};
}

View 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 = Object.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.Rectf;
/// Создаёт объект с дефолтными общими и фигурными свойствами.
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);
}

127
src/random_document.zig Normal file
View File

@@ -0,0 +1,127 @@
const std = @import("std");
const Document = @import("models/Document.zig");
const Object = Document.Object;
const shape = @import("models/shape/shape.zig");
const basic_models = @import("models/basic_models.zig");
const Size_f = basic_models.Size_f;
const Point2_f = basic_models.Point2_f;
const Scale2_f = basic_models.Scale2_f;
const Radii_f = basic_models.Radii_f;
fn randFloat(rng: std.Random, min: f32, max: f32) f32 {
return min + (max - min) * rng.float(f32);
}
fn randRgba(rng: std.Random) u32 {
const r = rng.int(u8);
const g = rng.int(u8);
const b = rng.int(u8);
const a: u8 = @intCast(rng.intRangeLessThan(usize, 128, 256));
return (@as(u32, r) << 24) | (@as(u32, g) << 16) | (@as(u32, b) << 8) | a;
}
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)];
}
fn randomizeObjectProperties(allocator: std.mem.Allocator, doc_size: *const Size_f, obj: *Object, rng: std.Random) !void {
const margin: f32 = 8;
const max_x = @max(0, doc_size.w - margin);
const max_y = @max(0, doc_size.h - margin);
try obj.setProperty(allocator, .{ .data = .{
.position = .{
.x = randFloat(rng, margin, if (max_x > margin) max_x else margin),
.y = randFloat(rng, margin, if (max_y > margin) max_y else margin),
},
} });
try obj.setProperty(allocator, .{ .data = .{ .angle = randFloat(rng, 0, 2 * std.math.pi) } });
try obj.setProperty(allocator, .{ .data = .{
.scale = .{
.scale_x = randFloat(rng, 0.25, 2.0),
.scale_y = randFloat(rng, 0.25, 2.0),
},
} });
try obj.setProperty(allocator, .{ .data = .{ .visible = true } });
try obj.setProperty(allocator, .{ .data = .{ .opacity = randFloat(rng, 0.3, 1.0) } });
try obj.setProperty(allocator, .{ .data = .{ .locked = rng.boolean() } });
const stroke = randRgba(rng);
try obj.setProperty(allocator, .{ .data = .{ .stroke_rgba = stroke } });
obj.setProperty(allocator, .{ .data = .{ .fill_rgba = randRgba(rng) } }) catch {};
const thickness = randFloat(rng, max_x * 0.001, max_x * 0.01);
try obj.setProperty(allocator, .{ .data = .{ .thickness = thickness } });
switch (obj.shape) {
.line => {
const len = randFloat(rng, 20, @min(doc_size.w, doc_size.h) * 0.5);
const angle = randFloat(rng, 0, 2 * std.math.pi);
try obj.setProperty(allocator, .{ .data = .{
.end_point = .{
.x = std.math.cos(angle) * len,
.y = std.math.sin(angle) * len,
},
} });
},
.ellipse => {
const max_r = @min(120, @min(doc_size.w / 4, doc_size.h / 4));
try obj.setProperty(allocator, .{ .data = .{
.radii = .{
.x = randFloat(rng, 8, @max(8, max_r)),
.y = randFloat(rng, 8, @max(8, max_r)),
},
} });
},
.broken => {
var points = std.ArrayList(Point2_f).empty;
const n = rng.intRangeLessThan(usize, 2, 9);
var x: f32 = 0;
var y: f32 = 0;
for (0..n) |_| {
try points.append(allocator, .{ .x = x, .y = y });
x += randFloat(rng, -40, 80);
y += randFloat(rng, -30, 60);
}
try obj.setProperty(allocator, .{ .data = .{ .points = points } });
},
.arc => {},
}
}
/// Создаёт в документе случайные фигуры (line, ellipse, broken).
pub fn addRandomShapes(doc: *Document, rng: std.Random) !void {
const max_total: usize = 80;
var total_count: usize = 0;
const allocator = doc.allocator;
const n_root = rng.intRangeLessThan(usize, 6, 15);
for (0..n_root) |_| {
if (total_count >= max_total) break;
var obj = try shape.createObject(allocator, randomShapeKind(rng));
try randomizeObjectProperties(allocator, &doc.size, &obj, rng);
try doc.addObject(obj);
total_count += 1;
}
var stack = std.ArrayList(*Object).empty;
defer stack.deinit(allocator);
for (doc.objects.items) |*obj| {
try stack.append(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;
var child = try shape.createObject(allocator, randomShapeKind(rng));
try randomizeObjectProperties(allocator, &doc.size, &child, rng);
try obj.addChild(allocator, child);
total_count += 1;
}
for (obj.children.items[base_len..]) |*child| {
try stack.append(allocator, child);
}
}
}

View File

@@ -0,0 +1,188 @@
const std = @import("std");
const builtin = @import("builtin");
const dvui = @import("dvui");
const RenderEngine = @import("RenderEngine.zig").RenderEngine;
const Document = @import("../models/Document.zig");
const basic_models = @import("../models/basic_models.zig");
const cpu_draw = @import("cpu/draw.zig");
const Size_i = basic_models.Size_i;
const Rect_i = basic_models.Rect_i;
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: Rect_i) 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: Size_i, visible_rect: Rect_i) 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: Size_i, visible_rect: Rect_i) !?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 };
}
/// Растеризует документ в текстуру (фон + фигуры через конвейер).
pub fn renderDocument(self: *CpuRenderEngine, document: *const Document, canvas_size: Size_i, visible_rect: Rect_i) !?dvui.Texture {
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);
for (pixels) |*p| p.* = .{ .r = 255, .g = 255, .b = 255, .a = 255 };
try cpu_draw.drawDocument(pixels, width, height, visible_rect, document, canvas_size, self._allocator);
return try dvui.textureCreate(pixels, width, height, .nearest);
}

View File

@@ -0,0 +1,27 @@
const dvui = @import("dvui");
const CpuRenderEngine = @import("CpuRenderEngine.zig");
const Document = @import("../models/Document.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.Size_i, visible_rect: basic_models.Rect_i) !?dvui.Texture {
return switch (self) {
.cpu => |cpu_r| cpu_r.example(canvas_size, visible_rect),
};
}
/// Растеризует документ в текстуру.
pub fn render(self: RenderEngine, document: *const Document, canvas_size: basic_models.Size_i, visible_rect: basic_models.Rect_i) !?dvui.Texture {
return switch (self) {
.cpu => |cpu_r| cpu_r.renderDocument(document, canvas_size, visible_rect),
};
}
};

8
src/render/cpu/arc.zig Normal file
View File

@@ -0,0 +1,8 @@
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const DrawContext = pipeline.DrawContext;
const Object = Document.Object;
/// Дуга (не реализовано).
pub fn draw(_: *DrawContext, _: *const Object) void {}

38
src/render/cpu/broken.zig Normal file
View File

@@ -0,0 +1,38 @@
const std = @import("std");
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const line = @import("line.zig");
const DrawContext = pipeline.DrawContext;
const Color = @import("dvui").Color;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_thickness: f32 = 2.0;
/// Ломаная по точкам, обводка stroke_rgba
pub fn draw(
ctx: *DrawContext,
obj: *const Object,
allocator: std.mem.Allocator,
) !void {
const p_prop = obj.getProperty(.points) orelse return;
const pts = p_prop.points.items;
if (pts.len < 2) return;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
const buffer = try allocator.alloc(Color.PMA, ctx.buf_width * ctx.buf_height);
@memset(buffer, .{ .r = 0, .g = 0, .b = 0, .a = 0 });
defer allocator.free(buffer);
var copy_ctx = ctx.*;
copy_ctx.pixels = buffer;
copy_ctx.replace_mode = true;
var i: usize = 0;
while (i + 1 < pts.len) : (i += 1) {
line.drawLine(&copy_ctx, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, stroke, thickness);
}
ctx.compositeDrawerContext(&copy_ctx, copy_ctx.transform.opacity);
}

82
src/render/cpu/draw.zig Normal file
View File

@@ -0,0 +1,82 @@
const std = @import("std");
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const line = @import("line.zig");
const ellipse = @import("ellipse.zig");
const broken = @import("broken.zig");
const arc = @import("arc.zig");
const basic_models = @import("../../models/basic_models.zig");
const Rect_i = basic_models.Rect_i;
const Size_i = basic_models.Size_i;
const Object = Document.Object;
const DrawContext = pipeline.DrawContext;
const Transform = pipeline.Transform;
fn getLocalTransform(obj: *const Object) Transform {
const pos = if (obj.getProperty(.position)) |p| p.position else basic_models.Point2_f{ .x = 0, .y = 0 };
const angle = if (obj.getProperty(.angle)) |p| p.angle else 0;
const scale = if (obj.getProperty(.scale)) |p| p.scale else basic_models.Scale2_f{ .scale_x = 1, .scale_y = 1 };
const opacity = if (obj.getProperty(.opacity)) |p| p.opacity else 1.0;
return .{
.position = pos,
.angle = angle,
.scale = scale,
.opacity = opacity,
};
}
fn isVisible(obj: *const Object) bool {
return if (obj.getProperty(.visible)) |p| p.visible else true;
}
fn drawObject(
ctx: *DrawContext,
obj: *const Object,
parent_transform: Transform,
allocator: std.mem.Allocator,
) !void {
if (!isVisible(obj)) return;
const local = getLocalTransform(obj);
const world = Transform.compose(parent_transform, local);
ctx.setTransform(world);
switch (obj.shape) {
.line => line.draw(ctx, obj),
.ellipse => ellipse.draw(ctx, obj),
.broken => try broken.draw(ctx, obj, allocator),
.arc => arc.draw(ctx, obj),
}
for (obj.children.items) |*child| {
try drawObject(ctx, child, world, allocator);
}
}
/// Рекурсивно рисует документ в буфер (объекты и потомки по порядку).
/// allocator опционален; если передан, ломаные рисуются через слой (без двойного наложения при alpha < 1).
pub fn drawDocument(
pixels: []@import("dvui").Color.PMA,
buf_width: u32,
buf_height: u32,
visible_rect: Rect_i,
document: *const Document,
canvas_size: Size_i,
allocator: std.mem.Allocator,
) !void {
const scale_x: f32 = if (document.size.w > 0) @as(f32, @floatFromInt(canvas_size.w)) / document.size.w else 0;
const scale_y: f32 = if (document.size.h > 0) @as(f32, @floatFromInt(canvas_size.h)) / document.size.h else 0;
var ctx = DrawContext{
.pixels = pixels,
.buf_width = buf_width,
.buf_height = buf_height,
.visible_rect = visible_rect,
.scale_x = scale_x,
.scale_y = scale_y,
};
const identity = Transform{};
for (document.objects.items) |*obj| {
try drawObject(&ctx, obj, identity, allocator);
}
}

View File

@@ -0,0 +1,96 @@
const std = @import("std");
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const DrawContext = pipeline.DrawContext;
const Color = @import("dvui").Color;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_thickness: f32 = 2.0;
/// Эллипс с центром (0,0) и полуосями radii (обводка с учётом thickness).
pub fn draw(ctx: *DrawContext, obj: *const Object) void {
const r_prop = obj.getProperty(.radii) orelse return;
const rx = r_prop.radii.x;
const ry = r_prop.radii.y;
if (rx <= 0 or ry <= 0) return;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
// Полуширина обводки в нормализованных единицах (d = (x/rx)² + (y/ry)², граница при d=1).
const min_r = @min(rx, ry);
const half_norm = thickness / (2.0 * min_r);
const inner = @max(0.0, 1.0 - half_norm);
const outer = 1.0 + half_norm;
const d_inner_sq = inner * inner;
const d_outer_sq = outer * outer;
const corners = [_]struct { x: f32, y: f32 }{
.{ .x = -rx, .y = -ry },
.{ .x = rx, .y = -ry },
.{ .x = rx, .y = ry },
.{ .x = -rx, .y = ry },
};
const w0 = ctx.localToWorld(corners[0].x, corners[0].y);
const b0 = ctx.worldToBufferF(w0.x, w0.y);
var min_bx: f32 = b0.x;
var min_by: f32 = b0.y;
var max_bx: f32 = b0.x;
var max_by: f32 = b0.y;
for (corners[1..]) |c| {
const w = ctx.localToWorld(c.x, c.y);
const b = ctx.worldToBufferF(w.x, w.y);
min_bx = @min(min_bx, b.x);
min_by = @min(min_by, b.y);
max_bx = @max(max_bx, b.x);
max_by = @max(max_by, b.y);
}
const buf_w: i32 = @intCast(ctx.buf_width);
const buf_h: i32 = @intCast(ctx.buf_height);
const x0: i32 = @max(0, @as(i32, @intFromFloat(std.math.floor(min_bx))));
const y0: i32 = @max(0, @as(i32, @intFromFloat(std.math.floor(min_by))));
const x1: i32 = @min(buf_w, @as(i32, @intFromFloat(std.math.ceil(max_bx))) + 1);
const y1: i32 = @min(buf_h, @as(i32, @intFromFloat(std.math.ceil(max_by))) + 1);
// Один раз считаем аффин buffer -> local, чтобы в цикле не вызывать cos/sin и лишние функции.
const t = &ctx.transform;
const ctx_sx = if (ctx.scale_x != 0) ctx.scale_x else 1.0;
const ctx_sy = if (ctx.scale_y != 0) ctx.scale_y else 1.0;
const inv_ctx_sx = 1.0 / ctx_sx;
const inv_ctx_sy = 1.0 / ctx_sy;
const vx = @as(f32, @floatFromInt(ctx.visible_rect.x));
const vy = @as(f32, @floatFromInt(ctx.visible_rect.y));
const t_sx = if (t.scale.scale_x != 0) t.scale.scale_x else 1.0;
const t_sy = if (t.scale.scale_y != 0) t.scale.scale_y else 1.0;
const ca = std.math.cos(-t.angle);
const sa = std.math.sin(-t.angle);
const dx_off = vx * inv_ctx_sx - t.position.x;
const dy_off = vy * inv_ctx_sy - t.position.y;
const loc_x_off = (dx_off * ca - dy_off * sa) / t_sx;
const loc_y_off = (dx_off * sa + dy_off * ca) / t_sy;
const m00 = inv_ctx_sx * ca / t_sx;
const m01 = -inv_ctx_sy * sa / t_sx;
const m10 = inv_ctx_sx * sa / t_sy;
const m11 = inv_ctx_sy * ca / t_sy;
const inv_rx = 1.0 / rx;
const inv_ry = 1.0 / ry;
var by: i32 = y0;
while (by < y1) : (by += 1) {
const buf_y = @as(f32, @floatFromInt(by)) + 0.5;
const row_loc_x_off = buf_y * m01 + loc_x_off;
const row_loc_y_off = buf_y * m11 + loc_y_off;
var bx: i32 = x0;
while (bx < x1) : (bx += 1) {
const buf_x = @as(f32, @floatFromInt(bx)) + 0.5;
const loc_x = buf_x * m00 + row_loc_x_off;
const loc_y = buf_x * m10 + row_loc_y_off;
const nx = loc_x * inv_rx;
const ny = loc_y * inv_ry;
const d = nx * nx + ny * ny;
if (d >= d_inner_sq and d <= d_outer_sq) {
ctx.blendPixelAtBuffer(@intCast(bx), @intCast(by), stroke);
}
}
}
}

188
src/render/cpu/line.zig Normal file
View File

@@ -0,0 +1,188 @@
const std = @import("std");
const Document = @import("../../models/Document.zig");
const pipeline = @import("pipeline.zig");
const DrawContext = pipeline.DrawContext;
const Color = @import("dvui").Color;
const base_models = @import("../../models/basic_models.zig");
const Point2_i = base_models.Point2_i;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_thickness: f32 = 2.0;
/// Линия от (0,0) до end_point.
pub fn draw(ctx: *DrawContext, obj: *const Object) void {
const ep_prop = obj.getProperty(.end_point) orelse return;
const end_x = ep_prop.end_point.x;
const end_y = ep_prop.end_point.y;
const stroke = if (obj.getProperty(.stroke_rgba)) |s| pipeline.rgbaToPma(s.stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |t| t.thickness else default_thickness;
drawLine(ctx, 0, 0, end_x, end_y, stroke, thickness);
}
/// Рисует отрезок по локальным концам (перевод в буфер внутри).
pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Color.PMA, thickness: f32) void {
const w0 = ctx.localToWorld(x0, y0);
const w1 = ctx.localToWorld(x1, y1);
const b0 = ctx.worldToBuffer(w0.x, w0.y);
const b1 = ctx.worldToBuffer(w1.x, w1.y);
const t = &ctx.transform;
const scale = @sqrt(t.scale.scale_x * ctx.scale_x * t.scale.scale_y * ctx.scale_y);
const thickness_px: u32 = @max(@as(u32, 1), @as(u32, @intFromFloat(std.math.round(thickness * scale))));
drawLineInBuffer(ctx, b0.x, b0.y, b1.x, b1.y, color, thickness_px);
}
inline fn clip(p: f32, q: f32, t0: *f32, t1: *f32) bool {
if (p == 0) {
return q >= 0;
}
const r = q / p;
if (p < 0) {
if (r > t1.*) return false;
if (r > t0.*) t0.* = r;
} else {
if (r < t0.*) return false;
if (r < t1.*) t1.* = r;
}
return true;
}
/// LiangBarsky отсечение отрезка (x0,y0)-(x1,y1) прямоугольником [left,right]x[top,bottom].
/// Координаты концов модифицируются по месту. Возвращает false, если отрезок целиком вне прямоугольника.
fn liangBarskyClip(
x0: *i32,
y0: *i32,
x1: *i32,
y1: *i32,
left: i32,
top: i32,
right: i32,
bottom: i32,
) bool {
const fx0: f32 = @floatFromInt(x0.*);
const fy0: f32 = @floatFromInt(y0.*);
const fx1: f32 = @floatFromInt(x1.*);
const fy1: f32 = @floatFromInt(y1.*);
const dx = fx1 - fx0;
const dy = fy1 - fy0;
var t0: f32 = 0.0;
var t1: f32 = 1.0;
const fl: f32 = @floatFromInt(left);
const ft: f32 = @floatFromInt(top);
const fr: f32 = @floatFromInt(right);
const fb: f32 = @floatFromInt(bottom);
if (!clip(-dx, fx0 - fl, &t0, &t1)) return false; // x >= left
if (!clip(dx, fr - fx0, &t0, &t1)) return false; // x <= right
if (!clip(-dy, fy0 - ft, &t0, &t1)) return false; // y >= top
if (!clip(dy, fb - fy0, &t0, &t1)) return false; // y <= bottom
const nx0 = fx0 + dx * t0;
const ny0 = fy0 + dy * t0;
const nx1 = fx0 + dx * t1;
const ny1 = fy0 + dy * t1;
x0.* = @intFromFloat(std.math.round(nx0));
y0.* = @intFromFloat(std.math.round(ny0));
x1.* = @intFromFloat(std.math.round(nx1));
y1.* = @intFromFloat(std.math.round(ny1));
return true;
}
/// Отсекает отрезок буфером ctx (0..buf_width-1, 0..buf_height-1).
fn clipLineToBuffer(ctx: *DrawContext, a: *Point2_i, b: *Point2_i, thickness: i32) bool {
var x0 = a.x;
var y0 = a.y;
var x1 = b.x;
var y1 = b.y;
const left: i32 = -thickness;
const top: i32 = -thickness;
const right: i32 = @as(i32, @intCast(ctx.buf_width - 1)) + thickness;
const bottom: i32 = @as(i32, @intCast(ctx.buf_height - 1)) + thickness;
if (!liangBarskyClip(&x0, &y0, &x1, &y1, left, top, right, bottom)) {
return false;
}
a.* = .{ .x = x0, .y = y0 };
b.* = .{ .x = x1, .y = y1 };
return true;
}
fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, color: Color.PMA, thickness_px: u32) void {
// Коррекция толщины в зависимости от угла линии.
var thickness_corrected: u32 = thickness_px;
var use_vertical: bool = undefined;
const dx_f: f32 = @floatFromInt(bx1 - bx0);
const dy_f: f32 = @floatFromInt(by1 - by0);
const len: f32 = @sqrt(dx_f * dx_f + dy_f * dy_f);
if (len > 0) {
const cos_theta = @abs(dx_f) / len;
const sin_theta = @abs(dy_f) / len;
const desired: f32 = @floatFromInt(thickness_px);
const eps: f32 = 1e-3;
// Если будем рисовать «вертикальными» полосами (смещение по X),
// перпендикулярное смещение на 1 пиксель X равно |sin(theta)|.
const vertical_based = desired / @max(sin_theta, eps);
// Если будем рисовать «горизонтальными» полосами (смещение по Y),
// перпендикулярное смещение на 1 пиксель Y равно |cos(theta)|.
const horizontal_based = desired / @max(cos_theta, eps);
// Предпочитаем тот вариант, где проекция больше (меньше разброс по пикселям).
use_vertical = sin_theta >= cos_theta;
const corrected_f = if (use_vertical) vertical_based else horizontal_based;
thickness_corrected = @max(@as(u32, 1), @as(u32, @intFromFloat(std.math.round(corrected_f))));
}
const half_thickness: i32 = @intCast(thickness_corrected / 2);
var p0 = Point2_i{ .x = bx0, .y = by0 };
var p1 = Point2_i{ .x = bx1, .y = by1 };
// Отсечение отрезка буфером. Если он целиком вне — рисовать нечего.
if (!clipLineToBuffer(ctx, &p0, &p1, @as(i32, @intCast(thickness_corrected)))) return;
var x0 = p0.x;
var y0 = p0.y;
const ex = p1.x;
const ey = p1.y;
const dx: i32 = @intCast(@abs(ex - x0));
const sx: i32 = if (x0 < ex) 1 else -1;
const dy_abs: i32 = @intCast(@abs(ey - y0));
const dy: i32 = -dy_abs;
const sy: i32 = if (y0 < ey) 1 else -1;
var err: i32 = dx + dy;
while (true) {
var thick: i32 = -half_thickness;
while (thick <= half_thickness) {
const x = if (use_vertical) x0 + thick else x0;
const y = if (use_vertical) y0 else y0 + thick;
if (x >= 0 and y >= 0) {
ctx.blendPixelAtBuffer(@intCast(x), @intCast(y), color);
}
thick += 1;
}
if (x0 == ex and y0 == ey) break;
const e2: i32 = 2 * err;
if (e2 >= dy) {
err += dy;
x0 += sx;
}
if (e2 <= dx) {
err += dx;
y0 += sy;
}
}
}

184
src/render/cpu/pipeline.zig Normal file
View File

@@ -0,0 +1,184 @@
const std = @import("std");
const dvui = @import("dvui");
const basic_models = @import("../../models/basic_models.zig");
const Point2_f = basic_models.Point2_f;
const Point2_i = basic_models.Point2_i;
const Scale2_f = basic_models.Scale2_f;
const Rect_i = basic_models.Rect_i;
const Color = dvui.Color;
/// Трансформ объекта: позиция, угол, масштаб, непрозрачность.
pub const Transform = struct {
position: Point2_f = .{},
angle: f32 = 0,
scale: Scale2_f = .{},
opacity: f32 = 1.0,
/// Композиция: world = parent * local.
pub fn compose(parent: Transform, local: Transform) Transform {
const cos_a = std.math.cos(parent.angle);
const sin_a = std.math.sin(parent.angle);
const sx = parent.scale.scale_x * local.scale.scale_x;
const sy = parent.scale.scale_y * local.scale.scale_y;
const local_px = local.position.x * parent.scale.scale_x;
const local_py = local.position.y * parent.scale.scale_y;
const rx = cos_a * local_px - sin_a * local_py;
const ry = sin_a * local_px + cos_a * local_py;
return .{
.position = .{
.x = parent.position.x + rx,
.y = parent.position.y + ry,
},
.angle = parent.angle + local.angle,
.scale = .{ .scale_x = sx, .scale_y = sy },
.opacity = parent.opacity * local.opacity,
};
}
};
/// Конвейер отрисовки: локальные координаты -> трансформ -> буфер.
pub const DrawContext = struct {
pixels: []Color.PMA,
buf_width: u32,
buf_height: u32,
visible_rect: Rect_i,
scale_x: f32,
scale_y: f32,
transform: Transform = .{},
/// Если true, blendPixelAtBuffer перезаписывает пиксель без бленда
replace_mode: bool = false,
pub fn setTransform(self: *DrawContext, t: Transform) void {
self.transform = t;
}
/// Локальные -> мировые.
pub fn localToWorld(self: *const DrawContext, local_x: f32, local_y: f32) Point2_f {
const t = &self.transform;
const cos_a = std.math.cos(t.angle);
const sin_a = std.math.sin(t.angle);
return .{
.x = t.position.x + (local_x * t.scale.scale_x) * cos_a - (local_y * t.scale.scale_y) * sin_a,
.y = t.position.y + (local_x * t.scale.scale_x) * sin_a + (local_y * t.scale.scale_y) * cos_a,
};
}
/// Мировые -> буфер (float).
pub fn worldToBufferF(self: *const DrawContext, wx: f32, wy: f32) Point2_f {
const canvas_x = wx * self.scale_x;
const canvas_y = wy * self.scale_y;
const vx = @as(f32, @floatFromInt(self.visible_rect.x));
const vy = @as(f32, @floatFromInt(self.visible_rect.y));
return .{
.x = canvas_x - vx,
.y = canvas_y - vy,
};
}
/// Мировые -> буфер (целые).
pub fn worldToBuffer(self: *const DrawContext, wx: f32, wy: f32) Point2_i {
const b = self.worldToBufferF(wx, wy);
return .{
.x = @intFromFloat(std.math.round(b.x)),
.y = @intFromFloat(std.math.round(b.y)),
};
}
/// Буфер -> мировые.
pub fn bufferToWorld(self: *const DrawContext, buf_x: f32, buf_y: f32) Point2_f {
const vx = @as(f32, @floatFromInt(self.visible_rect.x));
const vy = @as(f32, @floatFromInt(self.visible_rect.y));
const canvas_x = buf_x + vx;
const canvas_y = buf_y + vy;
const sx = if (self.scale_x != 0) self.scale_x else 1.0;
const sy = if (self.scale_y != 0) self.scale_y else 1.0;
return .{
.x = canvas_x / sx,
.y = canvas_y / sy,
};
}
/// Мировые -> локальные.
pub fn worldToLocal(self: *const DrawContext, wx: f32, wy: f32) Point2_f {
const t = &self.transform;
const dx = wx - t.position.x;
const dy = wy - t.position.y;
const cos_a = std.math.cos(-t.angle);
const sin_a = std.math.sin(-t.angle);
const sx = if (t.scale.scale_x != 0) t.scale.scale_x else 1.0;
const sy = if (t.scale.scale_y != 0) t.scale.scale_y else 1.0;
return .{
.x = (dx * cos_a - dy * sin_a) / sx,
.y = (dx * sin_a + dy * cos_a) / sy,
};
}
/// Смешивает цвет в пикселе буфера с учётом opacity трансформа. В replace_mode просто перезаписывает пиксель.
pub fn blendPixelAtBuffer(self: *DrawContext, bx: u32, by: u32, color: Color.PMA) void {
if (bx >= self.buf_width or by >= self.buf_height) return;
const idx = by * self.buf_width + bx;
const dst = &self.pixels[idx];
if (self.replace_mode) {
dst.* = color;
return;
}
const t = &self.transform;
const a = @as(f32, @floatFromInt(color.a)) / 255.0 * t.opacity;
const src_r = @as(f32, @floatFromInt(color.r)) * t.opacity;
const src_g = @as(f32, @floatFromInt(color.g)) * t.opacity;
const src_b = @as(f32, @floatFromInt(color.b)) * t.opacity;
const inv_a = 1.0 - a;
dst.r = @intFromFloat(std.math.clamp(src_r + inv_a * @as(f32, @floatFromInt(dst.r)), 0, 255));
dst.g = @intFromFloat(std.math.clamp(src_g + inv_a * @as(f32, @floatFromInt(dst.g)), 0, 255));
dst.b = @intFromFloat(std.math.clamp(src_b + inv_a * @as(f32, @floatFromInt(dst.b)), 0, 255));
dst.a = @intFromFloat(std.math.clamp(a * 255 + inv_a * @as(f32, @floatFromInt(dst.a)), 0, 255));
}
/// Накладывает буфер другого контекста на этот с заданной прозрачностью (один бленд на пиксель). Размеры буферов должны совпадать.
pub fn compositeDrawerContext(self: *DrawContext, other: *const DrawContext, opacity: f32) void {
if (self.buf_width != other.buf_width or self.buf_height != other.buf_height) return;
const n = self.buf_width * self.buf_height;
for (0..n) |i| {
const src = other.pixels[i];
if (src.a == 0) continue;
const dst = &self.pixels[i];
const a = @as(f32, @floatFromInt(src.a)) / 255.0 * opacity;
const src_r = @as(f32, @floatFromInt(src.r)) * opacity;
const src_g = @as(f32, @floatFromInt(src.g)) * opacity;
const src_b = @as(f32, @floatFromInt(src.b)) * opacity;
const inv_a = 1.0 - a;
dst.r = @intFromFloat(std.math.clamp(src_r + inv_a * @as(f32, @floatFromInt(dst.r)), 0, 255));
dst.g = @intFromFloat(std.math.clamp(src_g + inv_a * @as(f32, @floatFromInt(dst.g)), 0, 255));
dst.b = @intFromFloat(std.math.clamp(src_b + inv_a * @as(f32, @floatFromInt(dst.b)), 0, 255));
dst.a = @intFromFloat(std.math.clamp(a * 255 + inv_a * @as(f32, @floatFromInt(dst.a)), 0, 255));
}
}
/// Пиксель в локальных координатах (трансформ + PMA).
pub fn blendPixelLocal(self: *DrawContext, local_x: f32, local_y: f32, color: Color.PMA) void {
const w = self.localToWorld(local_x, local_y);
const b = self.worldToBufferF(w.x, w.y);
const bx: i32 = @intFromFloat(b.x);
const by: i32 = @intFromFloat(b.y);
const vw = @as(i32, @intCast(self.visible_rect.w));
const vh = @as(i32, @intCast(self.visible_rect.h));
if (bx < 0 or bx >= vw or by < 0 or by >= vh) return;
self.blendPixelAtBuffer(@intCast(bx), @intCast(by), color);
}
};
/// Конвертирует u32 0xRRGGBBAA в Color.PMA.
pub fn rgbaToPma(rgba: u32) Color.PMA {
const r: u8 = @intCast((rgba >> 24) & 0xFF);
const g: u8 = @intCast((rgba >> 16) & 0xFF);
const b: u8 = @intCast((rgba >> 8) & 0xFF);
const a: u8 = @intCast((rgba >> 0) & 0xFF);
if (a == 0) return .{ .r = 0, .g = 0, .b = 0, .a = 0 };
const af: f32 = @as(f32, @floatFromInt(a)) / 255.0;
return .{
.r = @intFromFloat(@as(f32, @floatFromInt(r)) * af),
.g = @intFromFloat(@as(f32, @floatFromInt(g)) * af),
.b = @intFromFloat(@as(f32, @floatFromInt(b)) * af),
.a = a,
};
}

14
src/tests.zig Normal file
View 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", .{});
}

29
src/tools.zig Normal file
View File

@@ -0,0 +1,29 @@
const Toolbar = @import("Toolbar.zig");
const line = @import("tools/line.zig");
const ellipse = @import("tools/ellipse.zig");
const arc = @import("tools/arc.zig");
const broken = @import("tools/broken.zig");
const icons = @import("icons.zig");
pub const default_tools = [_]Toolbar.ToolDescriptor{
.{
.name = "Line",
.icon_tvg = icons.line,
.implementation = &line.tool,
},
.{
.name = "Ellipse",
.icon_tvg = icons.ellipse,
.implementation = &ellipse.tool,
},
.{
.name = "Arc",
.icon_tvg = icons.arc,
.implementation = &arc.tool,
},
.{
.name = "Broken line",
.icon_tvg = icons.broken,
.implementation = &broken.tool,
},
};

12
src/tools/arc.zig Normal file
View File

@@ -0,0 +1,12 @@
const Tool = @import("../Tool.zig");
const shape = @import("../models/shape/shape.zig");
fn onCanvasClick(ctx: *const Tool.ToolContext) !void {
const canvas = ctx.canvas;
var obj = shape.createObject(canvas.document.allocator, .arc) catch return;
defer obj.deinit(canvas.allocator);
try obj.setProperty(canvas.document.allocator, .{ .data = .{ .position = ctx.document_point } });
try canvas.document.addObject(obj);
canvas.requestRedraw();
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

12
src/tools/broken.zig Normal file
View File

@@ -0,0 +1,12 @@
const Tool = @import("../Tool.zig");
const shape = @import("../models/shape/shape.zig");
fn onCanvasClick(ctx: *const Tool.ToolContext) !void {
const canvas = ctx.canvas;
var obj = shape.createObject(canvas.document.allocator, .broken) catch return;
defer obj.deinit(canvas.allocator);
try obj.setProperty(canvas.document.allocator, .{ .data = .{ .position = ctx.document_point } });
try canvas.document.addObject(obj);
canvas.requestRedraw();
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

12
src/tools/ellipse.zig Normal file
View File

@@ -0,0 +1,12 @@
const Tool = @import("../Tool.zig");
const shape = @import("../models/shape/shape.zig");
fn onCanvasClick(ctx: *const Tool.ToolContext) !void {
const canvas = ctx.canvas;
var obj = shape.createObject(canvas.document.allocator, .ellipse) catch return;
defer obj.deinit(canvas.allocator);
try obj.setProperty(canvas.document.allocator, .{ .data = .{ .position = ctx.document_point } });
try canvas.document.addObject(obj);
canvas.requestRedraw();
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

14
src/tools/line.zig Normal file
View File

@@ -0,0 +1,14 @@
const std = @import("std");
const Canvas = @import("../Canvas.zig");
const Tool = @import("../Tool.zig");
const shape = @import("../models/shape/shape.zig");
fn onCanvasClick(ctx: *const Tool.ToolContext) !void {
const canvas = ctx.canvas;
var obj = shape.createObject(canvas.document.allocator, .line) catch return;
defer obj.deinit(canvas.allocator);
try obj.setProperty(canvas.document.allocator, .{ .data = .{ .position = ctx.document_point } });
try canvas.document.addObject(obj);
canvas.requestRedraw();
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

243
src/ui/canvas_view.zig Normal file
View File

@@ -0,0 +1,243 @@
const std = @import("std");
const dvui = @import("dvui");
const dvui_ext = @import("dvui_ext.zig");
const Canvas = @import("../Canvas.zig");
const Rect_i = @import("../models/basic_models.zig").Rect_i;
const Tool = @import("../Tool.zig");
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();
// Тулбар поверх scroll
var toolbar_box = dvui.box(
@src(),
.{ .dir = .horizontal },
.{
.expand = .none,
.background = false,
.gravity_x = 0.0,
.gravity_y = 0.0,
.margin = dvui.Rect{ .x = 8, .y = 8 },
},
);
{
drawToolbar(canvas);
}
// Сохраняем rect тулбара для следующего кадра — в handleCanvasMouse исключаем из него клики
canvas.toolbar_rect_scale = toolbar_box.data().contentRectScale();
toolbar_box.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 Rect_i{ .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;
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
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| {
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,
};
const doc_pt = canvas.contentPointToDocument(content_pt, natural_scale);
canvas.addZoom(y / 1000);
canvas.requestRedraw();
// Сдвигаем viewport так, чтобы точка под курсором (даже вне холста) не уезжала
const new_zoom = canvas.getZoom();
const img = canvas.getZoomedImageSize();
const new_content_x = (@as(f32, @floatFromInt(img.x)) + doc_pt.x * new_zoom) / natural_scale;
const new_content_y = (@as(f32, @floatFromInt(img.y)) + doc_pt.y * new_zoom) / natural_scale;
canvas.scroll.viewport.x = new_content_x - viewport_pt.x;
canvas.scroll.viewport.y = new_content_y - viewport_pt.y;
const viewport_rect = scroll.data().contentRect();
const content_w = @as(f32, @floatFromInt(img.x + img.w)) / natural_scale;
const content_h = @as(f32, @floatFromInt(img.y + img.h)) / natural_scale;
const max_x = @max(0, content_w - viewport_rect.w + canvas.pos.x);
const max_y = @max(0, content_h - viewport_rect.h + canvas.pos.y);
canvas.scroll.viewport.x = std.math.clamp(canvas.scroll.viewport.x, 0, max_x);
canvas.scroll.viewport.y = std.math.clamp(canvas.scroll.viewport.y, 0, max_y);
},
else => {},
}
e.handled = true;
}
},
else => {},
}
}
}
fn handleCanvasMouse(canvas: *Canvas, scroll: *dvui.ScrollAreaWidget) void {
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
const scroll_data = scroll.data();
for (dvui.events()) |*e| {
switch (e.evt) {
.mouse => |*mouse| {
if (mouse.action != .press or mouse.button != .left) continue;
if (e.handled) continue;
if (!dvui.eventMatchSimple(e, scroll_data)) continue;
// Не обрабатывать клик, если он попал в область тулбара (rect с предыдущего кадра).
if (canvas.toolbar_rect_scale) |trs| {
const pt = trs.pointFromPhysical(mouse.p);
const r = trs.r;
if (pt.x >= 0 and pt.x * trs.s < r.w and pt.y >= 0 and pt.y * trs.s < r.h) 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,
};
const doc_pt = canvas.contentPointToDocument(content_pt, natural_scale);
canvas.cursor_document_point = if (canvas.isContentPointOnDocument(content_pt, natural_scale)) doc_pt else null;
if (canvas.cursor_document_point) |point| {
if (canvas.toolbar.currentDescriptor()) |desc| {
var ctx = Tool.ToolContext{
.canvas = canvas,
.document_point = point,
};
desc.implementation.onCanvasClick(&ctx) catch |err| {
std.debug.print("onCanvasClick error: {}\n", .{err});
};
}
}
},
else => {},
}
}
}
fn drawToolbar(canvas: *Canvas) void {
const tools_list = canvas.toolbar.tools;
if (tools_list.len == 0) return;
var bar = dvui.box(
@src(),
.{ .dir = .vertical },
.{
.gravity_x = 0.0,
.gravity_y = 0.0,
.margin = dvui.Rect{ .x = 8, .y = 8 },
.padding = dvui.Rect.all(6),
.corner_radius = dvui.Rect.all(8),
.background = true,
.color_fill = dvui.Color.black.opacity(0.2),
},
);
{
var to_select: ?usize = null;
for (tools_list, 0..) |*tool_desc, i| {
const is_selected = canvas.toolbar.selected_index == i;
const selected_fill = dvui.themeGet().focus;
const opts: dvui.Options = .{
.id_extra = i,
.color_fill = if (is_selected) selected_fill else null,
};
if (dvui.buttonIcon(@src(), tool_desc.name, tool_desc.icon_tvg, .{}, .{}, opts)) {
to_select = i;
}
}
if (to_select) |index| {
canvas.toolbar.select(index);
}
}
bar.deinit();
}

7
src/ui/dvui_ext.zig Normal file
View 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
View 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;
}

226
src/ui/left_panel.zig Normal file
View File

@@ -0,0 +1,226 @@
const std = @import("std");
const dvui = @import("dvui");
const WindowContext = @import("../WindowContext.zig");
const Document = @import("../models/Document.zig");
const icons = @import("../icons.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);
const ObjectTreeCallback = union(enum) {
select: *Object,
delete: *Object,
};
fn shapeLabel(shape: Object.ShapeKind) []const u8 {
return switch (shape) {
.line => "Line",
.ellipse => "Ellipse",
.arc => "Arc",
.broken => "Broken line",
};
}
fn objectTreeRow(open_doc: *WindowContext.OpenDocument, obj: *Object, depth: u32, object_callback: *?ObjectTreeCallback) void {
const indent_px = depth * 18;
const is_selected: bool = open_doc.selected_object == obj;
const row_id = @intFromPtr(obj);
const focus_color = dvui.themeGet().focus;
var row = dvui.box(
@src(),
.{ .dir = .horizontal },
.{
.id_extra = row_id,
.expand = .horizontal,
},
);
{
var hovered: bool = false;
const row_data = row.data();
var select_row: bool = false;
// Ручная обработка hover/click по строке без пометки события как handled,
// чтобы кнопка удаления могла нормально получать свои события.
for (dvui.events()) |*e| {
switch (e.evt) {
.mouse => |*mouse| {
if (!dvui.eventMatchSimple(e, row_data)) continue;
hovered = true;
if (mouse.action == .press and mouse.button == .left) {
select_row = true;
}
},
else => {},
}
}
const background = is_selected or hovered;
var content = dvui.box(@src(), .{ .dir = .horizontal }, .{
.expand = .horizontal,
.margin = dvui.Rect{ .x = @floatFromInt(indent_px) },
.background = background,
.color_fill = if (is_selected) focus_color.opacity(0.35) else if (hovered) focus_color.opacity(0.18) else null,
});
{
dvui.labelNoFmt(
@src(),
shapeLabel(obj.shape),
.{},
.{ .id_extra = row_id, .expand = .horizontal },
);
if (hovered) {
const delete_opts: dvui.Options = .{
.id_extra = row_id +% 1,
.margin = dvui.Rect{ .x = 4 },
.padding = dvui.Rect.all(2),
.gravity_y = 0.5,
.gravity_x = 1.0,
};
if (dvui.buttonIcon(@src(), "Delete object", icons.trash, .{}, .{}, delete_opts)) {
object_callback.* = .{ .delete = obj };
}
}
}
content.deinit();
if (select_row) {
object_callback.* = .{ .select = obj };
}
}
row.deinit();
for (obj.children.items) |*child| {
objectTreeRow(open_doc, child, depth + 1, object_callback);
}
}
fn objectTree(ctx: *WindowContext) void {
const active_doc = ctx.activeDocument();
var object_callback: ?ObjectTreeCallback = null;
if (active_doc) |open_doc| {
const doc = &open_doc.document;
if (doc.objects.items.len == 0) {
dvui.label(@src(), "No objects", .{}, .{});
} else {
for (doc.objects.items) |*obj| {
objectTreeRow(open_doc, obj, 0, &object_callback);
}
}
if (object_callback) |callback| {
switch (callback) {
.select => |obj| {
if (open_doc.selected_object == obj) {
open_doc.selected_object = null;
} else {
open_doc.selected_object = obj;
}
},
.delete => |obj| {
_ = doc.removeObject(obj);
open_doc.selected_object = null;
open_doc.canvas.requestRedraw();
},
}
}
} 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 },
.max_size_content = .{ .h = undefined, .w = 220 },
.background = true,
.padding = padding,
},
);
{
// Нижняя часть: настройки
var settings_section = dvui.box(
@src(),
.{ .dir = .vertical },
.{
.expand = .horizontal,
.gravity_y = 1.0,
.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.checkbox(@src(), &canvas.draw_document, "Draw document", .{})) {
canvas.requestRedraw();
}
if (!canvas.draw_document) {
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.requestRedraw();
}
}
if (dvui.button(@src(), "Add random shapes", .{}, .{})) {
canvas.addRandomShapes() catch {};
}
} else {
dvui.label(@src(), "No document", .{}, .{});
}
}
settings_section.deinit();
// Верхняя часть: дерево объектов
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", .{}, .{ .font = .{
.id = dvui.themeGet().font_heading.id,
.line_height_factor = dvui.themeGet().font_heading.line_height_factor,
.size = dvui.themeGet().font_heading.size + 8,
}, .gravity_x = 0.5 });
var scroll = dvui.scrollArea(
@src(),
.{ .vertical = .auto, .horizontal = .auto },
.{ .expand = .both, .background = false },
);
{
objectTree(ctx);
}
scroll.deinit();
}
tree_section.deinit();
}
panel.deinit();
}

68
src/ui/right_panel.zig Normal file
View 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
View 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();
}

View 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 {};
}
}
}