Compare commits
1 Commits
main
...
sdl-multiw
| Author | SHA1 | Date | |
|---|---|---|---|
| 03ae8eccb6 |
7
.vscode/launch.json
vendored
7
.vscode/launch.json
vendored
@@ -10,12 +10,5 @@
|
||||
"cwd": "${workspaceFolder}",
|
||||
"preLaunchTask": "zig: build"
|
||||
},
|
||||
{
|
||||
"name": "Zig: Debug (gdb)",
|
||||
"type": "gdb",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/zig-out/bin/Zivro",
|
||||
"preLaunchTask": "zig: build"
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
7
.vscode/settings.json
vendored
7
.vscode/settings.json
vendored
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"zig.testArgs": [
|
||||
"build",
|
||||
"test",
|
||||
"-Dtest-filter=${filter}"
|
||||
]
|
||||
}
|
||||
5
.vscode/tasks.json
vendored
5
.vscode/tasks.json
vendored
@@ -10,6 +10,11 @@
|
||||
"isDefault": true
|
||||
},
|
||||
"problemMatcher": ["$gcc"],
|
||||
"presentation": {
|
||||
"reveal": "always",
|
||||
"panel": "shared",
|
||||
"showReuseMessage": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
11
build.zig
11
build.zig
@@ -34,16 +34,7 @@ pub fn build(b: *std.Build) void {
|
||||
}
|
||||
|
||||
const exe_tests = b.addTest(.{
|
||||
.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") },
|
||||
},
|
||||
}),
|
||||
.root_module = exe.root_module,
|
||||
});
|
||||
|
||||
const run_exe_tests = b.addRunArtifact(exe_tests);
|
||||
|
||||
135
src/Canvas.zig
135
src/Canvas.zig
@@ -1,135 +0,0 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const dvui = @import("dvui");
|
||||
const Document = @import("models/Document.zig");
|
||||
const RenderEngine = @import("render/RenderEngine.zig").RenderEngine;
|
||||
const ImageRect = @import("models/rasterization_models.zig").ImageRect;
|
||||
const Size = dvui.Size;
|
||||
const Color = dvui.Color;
|
||||
|
||||
const Canvas = @This();
|
||||
|
||||
allocator: std.mem.Allocator,
|
||||
texture: ?dvui.Texture = null,
|
||||
size: Size = .{ .w = 800, .h = 600 },
|
||||
pos: dvui.Point = dvui.Point{ .x = 0, .y = 0 },
|
||||
scroll: dvui.ScrollInfo = .{
|
||||
.vertical = .auto,
|
||||
.horizontal = .auto,
|
||||
},
|
||||
native_scaling: bool = true,
|
||||
gradient_start: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 },
|
||||
gradient_end: Color.PMA = .{ .r = 255, .g = 255, .b = 255, .a = 255 },
|
||||
document: ?*Document = null,
|
||||
render_engine: RenderEngine,
|
||||
_visible_rect: ?ImageRect = null,
|
||||
_zoom: f32 = 1,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator, engine: RenderEngine) Canvas {
|
||||
return .{
|
||||
.allocator = allocator,
|
||||
.render_engine = engine,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Canvas) void {
|
||||
if (self.texture) |texture| {
|
||||
dvui.Texture.destroyLater(texture);
|
||||
self.texture = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Заполнить canvas градиентом
|
||||
pub fn redrawExample(self: *Canvas) !void {
|
||||
const full = self.getScaledImageSize();
|
||||
|
||||
const vis: ImageRect = self._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 };
|
||||
|
||||
if (vis.w == 0 or vis.h == 0) {
|
||||
if (self.texture) |tex| {
|
||||
dvui.Texture.destroyLater(tex);
|
||||
self.texture = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const new_texture = self.render_engine.example(.{ .w = full.w, .h = full.h }, vis) catch null;
|
||||
|
||||
if (new_texture) |tex| {
|
||||
// Удалить старую текстуру
|
||||
if (self.texture) |old_tex| {
|
||||
dvui.Texture.destroyLater(old_tex);
|
||||
}
|
||||
|
||||
self.texture = tex;
|
||||
}
|
||||
}
|
||||
|
||||
// Ресетнуть example изображение в renderEngine
|
||||
pub fn exampleReset(self: *Canvas) !void {
|
||||
self.render_engine.exampleReset();
|
||||
try self.redrawExample();
|
||||
}
|
||||
|
||||
pub fn setZoom(self: *Canvas, value: f32) void {
|
||||
self._zoom = @max(value, 0.01);
|
||||
}
|
||||
|
||||
pub fn addZoom(self: *Canvas, value: f32) void {
|
||||
self._zoom += value;
|
||||
self._zoom = @max(self._zoom, 0.01);
|
||||
}
|
||||
|
||||
pub fn getScaledImageSize(self: Canvas) ImageRect {
|
||||
return .{
|
||||
.x = @intFromFloat(self.pos.x),
|
||||
.y = @intFromFloat(self.pos.y),
|
||||
.w = @intFromFloat(self.size.w * self._zoom),
|
||||
.h = @intFromFloat(self.size.h * self._zoom),
|
||||
};
|
||||
}
|
||||
|
||||
/// Обновить видимую часть изображения (в пикселях холста) и сохранить в `visible_rect`.
|
||||
///
|
||||
/// `viewport` и `scroll_offset` ожидаются в *physical* пикселях (т.е. уже умноженные на windowNaturalScale).
|
||||
///
|
||||
/// После обновления (или если текстуры ещё нет) перерисовывает текстуру, чтобы она содержала только видимую часть.
|
||||
pub fn updateVisibleImageRect(self: *Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) !void {
|
||||
const next = computeVisibleImageRect(self.*, viewport, scroll_offset);
|
||||
var changed = false;
|
||||
if (self._visible_rect) |vis| {
|
||||
changed |= next.x != vis.x or next.y != vis.y or next.w != vis.w or next.h != vis.h;
|
||||
}
|
||||
self._visible_rect = next;
|
||||
if (changed) {
|
||||
std.debug.print("Visible Image Rect: {{ x: {}, y: {}, w: {}, h: {} }}\n", .{ next.x, next.y, next.w, next.h });
|
||||
}
|
||||
if (changed or self.texture == null) {
|
||||
try self.redrawExample();
|
||||
}
|
||||
}
|
||||
|
||||
fn computeVisibleImageRect(self: Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) ImageRect {
|
||||
const image_rect = self.getScaledImageSize();
|
||||
|
||||
const img_w: u32 = image_rect.w;
|
||||
const img_h: u32 = image_rect.h;
|
||||
|
||||
// Видимый размер всегда равен размеру viewport, но не больше холста
|
||||
const vis_w: u32 = @min(@as(u32, @intFromFloat(viewport.w)), img_w);
|
||||
const vis_h: u32 = @min(@as(u32, @intFromFloat(viewport.h)), img_h);
|
||||
|
||||
// Вычисляем x и y на основе scroll_offset, clamped чтобы не выходить за границы
|
||||
const raw_x: i64 = @intFromFloat(scroll_offset.x - @as(f32, @floatFromInt(image_rect.x)));
|
||||
const raw_y: i64 = @intFromFloat(scroll_offset.y - @as(f32, @floatFromInt(image_rect.y)));
|
||||
|
||||
const vis_x: u32 = @intCast(std.math.clamp(raw_x, 0, @as(i64, img_w) - @as(i64, vis_w)));
|
||||
const vis_y: u32 = @intCast(std.math.clamp(raw_y, 0, @as(i64, img_h) - @as(i64, vis_h)));
|
||||
|
||||
return ImageRect{
|
||||
.x = vis_x,
|
||||
.y = vis_y,
|
||||
.w = vis_w,
|
||||
.h = vis_h,
|
||||
};
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
const std = @import("std");
|
||||
const Canvas = @import("Canvas.zig");
|
||||
const CpuRenderEngine = @import("render/CpuRenderEngine.zig");
|
||||
|
||||
const WindowContext = @This();
|
||||
|
||||
allocator: std.mem.Allocator,
|
||||
canvas: Canvas,
|
||||
cpu_render: *CpuRenderEngine,
|
||||
frame_index: u64,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) !WindowContext {
|
||||
var self: WindowContext = undefined;
|
||||
self.allocator = allocator;
|
||||
|
||||
self.cpu_render = try allocator.create(CpuRenderEngine);
|
||||
errdefer allocator.destroy(self.cpu_render);
|
||||
self.cpu_render.* = CpuRenderEngine.init(allocator, .Squares);
|
||||
|
||||
self.canvas = Canvas.init(allocator, self.cpu_render.renderEngine());
|
||||
|
||||
self.frame_index = 0;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *WindowContext) void {
|
||||
self.canvas.deinit();
|
||||
self.allocator.destroy(self.cpu_render);
|
||||
}
|
||||
11
src/WindowData.zig
Normal file
11
src/WindowData.zig
Normal file
@@ -0,0 +1,11 @@
|
||||
const std = @import("std");
|
||||
|
||||
const WindowData = @This();
|
||||
|
||||
frame: u64,
|
||||
|
||||
pub fn init() WindowData {
|
||||
return WindowData{
|
||||
.frame = 0,
|
||||
};
|
||||
}
|
||||
414
src/main.zig
414
src/main.zig
@@ -1,253 +1,227 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const dvui = @import("dvui");
|
||||
const dvui_ext = @import("ui/dvui_ext.zig");
|
||||
const SDLBackend = @import("sdl-backend");
|
||||
const Document = @import("models/Document.zig");
|
||||
const ImageRect = @import("models/rasterization_models.zig").ImageRect;
|
||||
const WindowContext = @import("WindowContext.zig");
|
||||
const sdl_c = SDLBackend.c;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Color = dvui.Color;
|
||||
const WindowData = @import("WindowData.zig");
|
||||
const dbprint = std.debug.print;
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const allocator = gpa.allocator();
|
||||
const WindowContext = struct {
|
||||
backend: SDLBackend,
|
||||
backend_id: u32,
|
||||
window: dvui.Window,
|
||||
title: [:0]u8,
|
||||
id: usize,
|
||||
data: WindowData,
|
||||
|
||||
var backend = try SDLBackend.initWindow(.{
|
||||
.allocator = allocator,
|
||||
.size = .{ .w = 800.0, .h = 600.0 },
|
||||
.title = "My DVUI App",
|
||||
.vsync = true,
|
||||
});
|
||||
defer backend.deinit();
|
||||
fn init(allocator: std.mem.Allocator, id: usize) !*WindowContext {
|
||||
var ctx = try allocator.create(WindowContext);
|
||||
errdefer allocator.destroy(ctx);
|
||||
|
||||
var win = try dvui.Window.init(@src(), allocator, backend.backend(), .{
|
||||
.theme = switch (backend.preferredColorScheme() orelse .light) {
|
||||
ctx.id = id;
|
||||
|
||||
const title_bytes = try std.fmt.allocPrint(allocator, "My DVUI App #{d}", .{id});
|
||||
defer allocator.free(title_bytes);
|
||||
|
||||
ctx.title = try allocator.allocSentinel(u8, title_bytes.len, 0);
|
||||
@memcpy(ctx.title[0..title_bytes.len], title_bytes);
|
||||
|
||||
ctx.backend = try SDLBackend.initWindow(.{
|
||||
.allocator = allocator,
|
||||
.size = .{ .w = 800.0, .h = 600.0 },
|
||||
.title = ctx.title,
|
||||
.vsync = true,
|
||||
});
|
||||
errdefer destroyBackendKeepingSDL(&ctx.backend);
|
||||
|
||||
ctx.backend_id = @intCast(sdl_c.SDL_GetWindowID(ctx.backend.window));
|
||||
|
||||
const theme = switch (ctx.backend.preferredColorScheme() orelse .light) {
|
||||
.light => dvui.Theme.builtin.adwaita_light,
|
||||
.dark => dvui.Theme.builtin.adwaita_dark,
|
||||
},
|
||||
});
|
||||
defer win.deinit();
|
||||
};
|
||||
|
||||
var ctx = try WindowContext.init(allocator);
|
||||
defer ctx.deinit();
|
||||
ctx.window = try dvui.Window.init(@src(), allocator, ctx.backend.backend(), .{ .theme = theme });
|
||||
errdefer ctx.window.deinit();
|
||||
|
||||
ctx.data = WindowData.init();
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
fn deinit(self: *WindowContext, allocator: std.mem.Allocator, last_backend: bool) void {
|
||||
self.window.deinit();
|
||||
|
||||
if (last_backend) {
|
||||
self.backend.deinit();
|
||||
} else {
|
||||
destroyBackendKeepingSDL(&self.backend);
|
||||
}
|
||||
|
||||
allocator.free(self.title);
|
||||
self.* = undefined;
|
||||
}
|
||||
|
||||
fn destroyBackendKeepingSDL(backend: *SDLBackend) void {
|
||||
sdl_c.SDL_DestroyRenderer(backend.renderer);
|
||||
sdl_c.SDL_DestroyWindow(backend.window);
|
||||
backend.we_own_window = false;
|
||||
backend.deinit();
|
||||
}
|
||||
};
|
||||
|
||||
pub fn main() !void {
|
||||
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(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const allocator = gpa.allocator();
|
||||
|
||||
var windows = try std.ArrayList(*WindowContext).initCapacity(allocator, 0);
|
||||
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 WindowContext.init(allocator, next_window_id);
|
||||
next_window_id += 1;
|
||||
try windows.append(allocator, first_ctx);
|
||||
|
||||
var interrupted = false;
|
||||
main_loop: while (true) {
|
||||
// beginWait coordinates with waitTime below to run frames only when needed
|
||||
const nstime = win.beginWait(interrupted);
|
||||
if (windows.items.len == 0) break :main_loop;
|
||||
|
||||
// marks the beginning of a frame for dvui, can call dvui functions after this
|
||||
try win.begin(nstime);
|
||||
const saw_events = try pumpEvents(&windows);
|
||||
|
||||
// send all SDL events to dvui for processing
|
||||
try backend.addAllEvents(&win);
|
||||
var min_wait_event_micros: u32 = std.math.maxInt(u32);
|
||||
var idx: usize = 0;
|
||||
while (saw_events and idx < windows.items.len) {
|
||||
const ctx = windows.items[idx];
|
||||
|
||||
// if dvui widgets might not cover the whole window, then need to clear
|
||||
// the previous frame's render
|
||||
_ = SDLBackend.c.SDL_SetRenderDrawColor(backend.renderer, 0, 0, 0, 255);
|
||||
_ = SDLBackend.c.SDL_RenderClear(backend.renderer);
|
||||
const flags = sdl_c.SDL_GetWindowFlags(ctx.backend.window);
|
||||
const occluded = (flags & (sdl_c.SDL_WINDOW_HIDDEN | sdl_c.SDL_WINDOW_MINIMIZED | sdl_c.SDL_WINDOW_OCCLUDED)) != 0;
|
||||
if (occluded) {
|
||||
idx += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const keep_running = gui_frame(&ctx);
|
||||
if (!keep_running) break :main_loop;
|
||||
const nstime = @max(ctx.window.frame_time_ns, ctx.backend.nanoTime());
|
||||
|
||||
// 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 win.end(.{});
|
||||
try ctx.window.begin(nstime);
|
||||
|
||||
// cursor management
|
||||
try backend.setCursor(win.cursorRequested());
|
||||
try backend.textInputRect(win.textInputRequested());
|
||||
_ = sdl_c.SDL_SetRenderDrawColor(ctx.backend.renderer, 0, 0, 0, 255);
|
||||
_ = sdl_c.SDL_RenderClear(ctx.backend.renderer);
|
||||
|
||||
// render frame to OS
|
||||
try backend.renderPresent();
|
||||
const keep_open = try gui_frame(ctx, allocator, &windows, &next_window_id);
|
||||
if (!keep_open) {
|
||||
closeWindow(&windows, allocator, idx);
|
||||
continue;
|
||||
}
|
||||
|
||||
// waitTime and beginWait combine to achieve variable framerates
|
||||
const wait_event_micros = win.waitTime(end_micros);
|
||||
interrupted = try backend.waitEventTimeout(wait_event_micros);
|
||||
const end = try ctx.window.end(.{});
|
||||
|
||||
// cursor management
|
||||
try ctx.backend.setCursor(ctx.window.cursorRequested());
|
||||
try ctx.backend.textInputRect(ctx.window.textInputRequested());
|
||||
|
||||
// render frame to OS
|
||||
try ctx.backend.renderPresent();
|
||||
|
||||
const sleep_time = ctx.window.waitTime(end);
|
||||
min_wait_event_micros = @min(min_wait_event_micros, sleep_time);
|
||||
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
if (min_wait_event_micros != std.math.maxInt(u32)) {
|
||||
min_wait_event_micros = @max(min_wait_event_micros, 1 / 120 * std.time.us_per_s);
|
||||
std.Thread.sleep(min_wait_event_micros * std.time.ns_per_us);
|
||||
} else {
|
||||
std.Thread.sleep(1 / 60 * std.time.ns_per_s);
|
||||
}
|
||||
|
||||
if (windows.items.len == 0) break :main_loop;
|
||||
}
|
||||
}
|
||||
|
||||
fn gui_frame(ctx: *WindowContext) bool {
|
||||
const canvas = &ctx.canvas;
|
||||
const ctrl: bool = dvui.currentWindow().modifiers.control();
|
||||
fn closeWindow(windows: *std.ArrayList(*WindowContext), allocator: std.mem.Allocator, idx: usize) void {
|
||||
const last = windows.items.len == 1;
|
||||
const ctx = windows.swapRemove(idx);
|
||||
ctx.deinit(allocator, last);
|
||||
allocator.destroy(ctx);
|
||||
}
|
||||
|
||||
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;
|
||||
fn eventWindowId(event: sdl_c.SDL_Event) ?u32 {
|
||||
return switch (event.type) {
|
||||
sdl_c.SDL_EVENT_KEY_DOWN => @intCast(event.key.windowID),
|
||||
sdl_c.SDL_EVENT_KEY_UP => @intCast(event.key.windowID),
|
||||
sdl_c.SDL_EVENT_TEXT_INPUT => @intCast(event.text.windowID),
|
||||
sdl_c.SDL_EVENT_TEXT_EDITING => @intCast(event.edit.windowID),
|
||||
sdl_c.SDL_EVENT_MOUSE_MOTION => @intCast(event.motion.windowID),
|
||||
sdl_c.SDL_EVENT_MOUSE_BUTTON_DOWN => @intCast(event.button.windowID),
|
||||
sdl_c.SDL_EVENT_MOUSE_BUTTON_UP => @intCast(event.button.windowID),
|
||||
sdl_c.SDL_EVENT_MOUSE_WHEEL => @intCast(event.wheel.windowID),
|
||||
sdl_c.SDL_EVENT_WINDOW_FIRST...sdl_c.SDL_EVENT_WINDOW_LAST => @intCast(event.window.windowID),
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn pumpEvents(windows: *std.ArrayList(*WindowContext)) !bool {
|
||||
var event: sdl_c.SDL_Event = undefined;
|
||||
const poll_got_event = if (SDLBackend.sdl3) true else 1;
|
||||
var saw_event = false;
|
||||
|
||||
while (sdl_c.SDL_PollEvent(&event) == poll_got_event) {
|
||||
saw_event = true;
|
||||
|
||||
if (eventWindowId(event)) |wid| {
|
||||
for (windows.items) |ctx| {
|
||||
if (ctx.backend_id == wid) {
|
||||
_ = try ctx.backend.addEvent(&ctx.window, event);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//std.debug.print("null with: {any}\n", .{event.type});
|
||||
// broadcast events without a window target (like SDL_QUIT)
|
||||
for (windows.items) |ctx| {
|
||||
_ = try ctx.backend.addEvent(&ctx.window, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const root = dvui.box(
|
||||
@src(),
|
||||
.{ .dir = .horizontal },
|
||||
.{ .expand = .both, .background = true, .style = .window },
|
||||
);
|
||||
return saw_event;
|
||||
}
|
||||
|
||||
fn gui_frame(ctx: *WindowContext, allocator: std.mem.Allocator, windows: *std.ArrayList(*WindowContext), next_window_id: *usize) !bool {
|
||||
for (ctx.window.events.items) |*e| {
|
||||
if (e.evt == .window and e.evt.window.action == .close) return false;
|
||||
}
|
||||
|
||||
var root = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .both, .padding = dvui.Rect.all(12), .background = true, .style = .window });
|
||||
defer root.deinit();
|
||||
|
||||
// Левая панель с фиксированной шириной
|
||||
var left_panel = dvui.box(@src(), .{ .dir = .vertical }, .{ .expand = .vertical, .min_size_content = .{ .w = 200 }, .background = true });
|
||||
{
|
||||
dvui.label(@src(), "Tools", .{}, .{});
|
||||
if (dvui.button(@src(), "Fill Random Color", .{}, .{}) or ctx.frame_index == 0) {
|
||||
canvas.exampleReset() catch |err| {
|
||||
std.debug.print("Error reset example: {}\n", .{err});
|
||||
};
|
||||
canvas.pos = .{ .x = 400, .y = 400 };
|
||||
}
|
||||
if (dvui.checkbox(@src(), &canvas.native_scaling, "Scaling", .{})) {}
|
||||
if (dvui.button(@src(), if (ctx.cpu_render.type == .Gradient) "Gradient" else "Squares", .{}, .{})) {
|
||||
if (ctx.cpu_render.type == .Gradient) {
|
||||
ctx.cpu_render.type = .Squares;
|
||||
} else {
|
||||
ctx.cpu_render.type = .Gradient;
|
||||
}
|
||||
canvas.redrawExample() catch {};
|
||||
}
|
||||
dvui.label(@src(), "Window #{d}", .{ctx.id}, .{ .font_style = .title_2 });
|
||||
dvui.label(@src(), "Open windows: {d}", .{windows.items.len}, .{});
|
||||
dvui.label(@src(), "Frame {d}, fps: {d}", .{ ctx.data.frame, dvui.FPS() }, .{});
|
||||
|
||||
ctx.data.frame += 1;
|
||||
|
||||
if (dvui.button(@src(), "New window", .{}, .{})) {
|
||||
const id = next_window_id.*;
|
||||
next_window_id.* += 1;
|
||||
const new_ctx = try WindowContext.init(allocator, id);
|
||||
try windows.append(allocator, new_ctx);
|
||||
}
|
||||
left_panel.deinit();
|
||||
|
||||
// Правая панель - занимает оставшееся пространство
|
||||
const back = dvui.box(
|
||||
@src(),
|
||||
.{ .dir = .horizontal },
|
||||
.{ .expand = .both, .padding = dvui.Rect.all(12), .background = true },
|
||||
);
|
||||
{
|
||||
const fill_color = Color.black.opacity(0.25);
|
||||
var right_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,
|
||||
},
|
||||
);
|
||||
{
|
||||
var textured = dvui_ext.texturedBox(right_panel.data().contentRectScale(), 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,
|
||||
},
|
||||
);
|
||||
{
|
||||
const natural_scale = if (canvas.native_scaling) 1 else dvui.windowNaturalScale();
|
||||
const img_size = canvas.getScaledImageSize();
|
||||
|
||||
// Получить viewport и scroll offset
|
||||
const viewport_rect = scroll.data().contentRect();
|
||||
const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y };
|
||||
|
||||
// viewport_rect/scroll_current — в natural единицах.
|
||||
// Для расчёта видимой области в пикселях изображения переводим в physical.
|
||||
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,
|
||||
};
|
||||
|
||||
canvas.updateVisibleImageRect(viewport_px, scroll_px) catch |err| {
|
||||
std.debug.print("updateVisibleImageRect error: {}\n", .{err});
|
||||
};
|
||||
|
||||
// `canvas.texture` contains ONLY the visible part.
|
||||
// If we render it inside a widget sized as the full image, dvui will stretch it.
|
||||
// Instead: create a scroll content surface sized like the full image, then place
|
||||
// the visible texture at the correct offset at 1:1.
|
||||
const content_w_px: u32 = img_size.x + img_size.w;
|
||||
const content_h_px: u32 = img_size.y + img_size.h;
|
||||
const content_w = @as(f32, @floatFromInt(content_w_px)) / natural_scale;
|
||||
const content_h = @as(f32, @floatFromInt(content_h_px)) / natural_scale;
|
||||
|
||||
var canvas_layer = dvui.overlay(
|
||||
@src(),
|
||||
.{ .min_size_content = .{ .w = content_w, .h = content_h }, .background = false },
|
||||
);
|
||||
{
|
||||
if (canvas.texture) |tex| {
|
||||
const vis = canvas._visible_rect orelse ImageRect{ .x = 0, .y = 0, .w = 0, .h = 0 };
|
||||
const left = @as(f32, @floatFromInt(img_size.x + vis.x)) / natural_scale;
|
||||
const top = @as(f32, @floatFromInt(img_size.y + vis.y)) / natural_scale;
|
||||
|
||||
_ = dvui.image(
|
||||
@src(),
|
||||
.{ .source = .{ .texture = tex } },
|
||||
.{
|
||||
.background = false,
|
||||
.expand = .none,
|
||||
.gravity_x = 0.0,
|
||||
.gravity_y = 0.0,
|
||||
.margin = .{ .x = left, .y = top, .w = canvas.pos.x, .h = canvas.pos.y },
|
||||
.min_size_content = .{
|
||||
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
|
||||
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
|
||||
},
|
||||
.max_size_content = .{
|
||||
.w = @as(f32, @floatFromInt(vis.w)) / natural_scale,
|
||||
.h = @as(f32, @floatFromInt(vis.h)) / natural_scale,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
canvas_layer.deinit();
|
||||
|
||||
// Заблокировать события скролла, если нажат ctrl
|
||||
if (ctrl) {
|
||||
for (dvui.events()) |*e| {
|
||||
switch (e.evt) {
|
||||
.mouse => |mouse| {
|
||||
const action = mouse.action;
|
||||
if (dvui.eventMatchSimple(e, scroll.data()) and (action == .wheel_x or action == .wheel_y)) {
|
||||
switch (action) {
|
||||
.wheel_y => |y| {
|
||||
canvas.addZoom(y / 1000);
|
||||
canvas.redrawExample() catch {};
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
e.handled = true;
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scroll.deinit();
|
||||
|
||||
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
|
||||
}
|
||||
overlay.deinit();
|
||||
}
|
||||
textured.deinit();
|
||||
}
|
||||
right_panel.deinit();
|
||||
}
|
||||
back.deinit();
|
||||
|
||||
ctx.frame_index += 1;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// Файл векторного документа
|
||||
@@ -1,11 +0,0 @@
|
||||
pub const ImageRect = struct {
|
||||
x: u32,
|
||||
y: u32,
|
||||
w: u32,
|
||||
h: u32,
|
||||
};
|
||||
|
||||
pub const ImageSize = struct {
|
||||
w: u32,
|
||||
h: u32,
|
||||
};
|
||||
@@ -1,180 +0,0 @@
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const dvui = @import("dvui");
|
||||
const RenderEngine = @import("RenderEngine.zig").RenderEngine;
|
||||
const rast_models = @import("../models/rasterization_models.zig");
|
||||
const ImageSize = rast_models.ImageSize;
|
||||
const ImageRect = rast_models.ImageRect;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Color = dvui.Color;
|
||||
|
||||
const CpuRenderEngine = @This();
|
||||
const Type = enum {
|
||||
Gradient,
|
||||
Squares,
|
||||
};
|
||||
|
||||
type: Type,
|
||||
_allocator: Allocator,
|
||||
gradient_start: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 },
|
||||
gradient_end: Color.PMA = .{ .r = 255, .g = 255, .b = 255, .a = 255 },
|
||||
|
||||
pub fn init(allocator: Allocator, render_type: Type) CpuRenderEngine {
|
||||
return .{
|
||||
._allocator = allocator,
|
||||
.type = render_type,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn exampleReset(self: *CpuRenderEngine) void {
|
||||
// Сгенерировать случайные цвета градиента
|
||||
var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));
|
||||
const random = prng.random();
|
||||
self.gradient_start = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 };
|
||||
self.gradient_end = Color.PMA{ .r = random.int(u8), .g = random.int(u8), .b = random.int(u8), .a = 255 };
|
||||
}
|
||||
|
||||
fn renderGradient(self: CpuRenderEngine, pixels: []Color.PMA, width: u32, height: u32, full_w: u32, full_h: u32, visible_rect: ImageRect) void {
|
||||
var y: u32 = 0;
|
||||
while (y < height) : (y += 1) {
|
||||
var x: u32 = 0;
|
||||
while (x < width) : (x += 1) {
|
||||
const gx: u32 = visible_rect.x + x;
|
||||
const gy: u32 = visible_rect.y + y;
|
||||
|
||||
const denom_x: f32 = if (full_w > 1) @as(f32, @floatFromInt(full_w - 1)) else 1;
|
||||
const denom_y: f32 = if (full_h > 1) @as(f32, @floatFromInt(full_h - 1)) else 1;
|
||||
const fx: f32 = @as(f32, @floatFromInt(gx)) / denom_x;
|
||||
const fy: f32 = @as(f32, @floatFromInt(gy)) / denom_y;
|
||||
const factor: f32 = std.math.clamp((fx + fy) / 2, 0, 1);
|
||||
|
||||
const r_f: f32 = @as(f32, @floatFromInt(self.gradient_start.r)) + factor * (@as(f32, @floatFromInt(self.gradient_end.r)) - @as(f32, @floatFromInt(self.gradient_start.r)));
|
||||
const g_f: f32 = @as(f32, @floatFromInt(self.gradient_start.g)) + factor * (@as(f32, @floatFromInt(self.gradient_end.g)) - @as(f32, @floatFromInt(self.gradient_start.g)));
|
||||
const b_f: f32 = @as(f32, @floatFromInt(self.gradient_start.b)) + factor * (@as(f32, @floatFromInt(self.gradient_end.b)) - @as(f32, @floatFromInt(self.gradient_start.b)));
|
||||
|
||||
const r: u8 = @intFromFloat(std.math.clamp(r_f, 0, 255));
|
||||
const g: u8 = @intFromFloat(std.math.clamp(g_f, 0, 255));
|
||||
const b: u8 = @intFromFloat(std.math.clamp(b_f, 0, 255));
|
||||
pixels[y * width + x] = .{ .r = r, .g = g, .b = b, .a = 255 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn renderSquares(self: CpuRenderEngine, pixels: []Color.PMA, canvas_size: ImageSize, visible_rect: ImageRect) void {
|
||||
_ = self;
|
||||
|
||||
const colors = [_]Color.PMA{
|
||||
.{ .r = 255, .g = 0, .b = 0, .a = 255 }, // red
|
||||
.{ .r = 255, .g = 165, .b = 0, .a = 255 }, // orange
|
||||
.{ .r = 255, .g = 255, .b = 0, .a = 255 }, // yellow
|
||||
.{ .r = 0, .g = 255, .b = 0, .a = 255 }, // green
|
||||
.{ .r = 0, .g = 255, .b = 255, .a = 255 }, // cyan
|
||||
.{ .r = 0, .g = 0, .b = 255, .a = 255 }, // blue
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
// Check vertical line index
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// Check horizontal line index
|
||||
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 {
|
||||
// Find square
|
||||
var square_x: u32 = 0;
|
||||
for (0..squares_num) |i| {
|
||||
if (canvas_x >= x_pos[i] + thikness and canvas_x < x_pos[i + 1]) {
|
||||
square_x = @intCast(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
var square_y: u32 = 0;
|
||||
for (0..squares_num) |i| {
|
||||
if (canvas_y >= y_pos[i] + thikness and canvas_y < y_pos[i + 1]) {
|
||||
square_y = @intCast(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (square_x % 2 == square_y % 2) {
|
||||
pixels[y * visible_rect.w + x] = .{ .r = 255, .g = 255, .b = 255, .a = 255 };
|
||||
} else {
|
||||
pixels[y * visible_rect.w + x] = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn example(self: CpuRenderEngine, canvas_size: ImageSize, visible_rect: ImageRect) !?dvui.Texture {
|
||||
const full_w = canvas_size.w;
|
||||
const full_h = canvas_size.h;
|
||||
|
||||
const width = visible_rect.w;
|
||||
const height = visible_rect.h;
|
||||
|
||||
// Выделить буфер пиксельных данных
|
||||
const pixels = try self._allocator.alloc(Color.PMA, @as(usize, width) * height);
|
||||
defer self._allocator.free(pixels);
|
||||
|
||||
// std.debug.print("w={any}, fw={any};\th={any}, fh={any}\n", .{ width, full_w, height, full_h });
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
// Интерфейс для рендеринга документа
|
||||
const dvui = @import("dvui");
|
||||
const CpuRenderEngine = @import("CpuRenderEngine.zig");
|
||||
const rast_models = @import("../models/rasterization_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: rast_models.ImageSize, visible_rect: rast_models.ImageRect) !?dvui.Texture {
|
||||
return switch (self) {
|
||||
.cpu => |cpu_r| cpu_r.example(canvas_size, visible_rect),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
// Test root for `zig build test`.
|
||||
// Import modules here to ensure their `test` blocks are discovered.
|
||||
|
||||
test "module test discovery" {
|
||||
_ = @import("render/CpuRenderEngine.zig");
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Расширения для dvui
|
||||
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);
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Отрисовка дочернего контента как текстуры с параметрами скругления
|
||||
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);
|
||||
// self.rs.r.y -= 2;
|
||||
// self.rs.r.x -= 2;
|
||||
// self.rs.r.h += 2;
|
||||
// self.rs.r.w += 2;
|
||||
dvui.renderTexture(t, self.rs, .{
|
||||
.corner_radius = self.corner_radius,
|
||||
}) catch {};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user