Canvas в отдельном файле

This commit is contained in:
2025-12-18 22:24:20 +03:00
parent bb825d0225
commit 4f0fb09185
3 changed files with 94 additions and 72 deletions

View File

@@ -1,88 +1,28 @@
const std = @import("std");
const dvui = @import("dvui");
const Color = dvui.Color;
const Canvas = @import("Canvas.zig");
const WindowContext = @This();
allocator: std.mem.Allocator,
canvas_texture: ?dvui.Texture = null,
canvas_width: u32 = 400,
canvas_height: u32 = 300,
canvas_pos: dvui.Point = dvui.Point{ .x = 0, .y = 0 },
canvas_scroll: dvui.ScrollInfo = .{
.vertical = .given,
.horizontal = .given,
.virtual_size = .{ .w = 2000, .h = 2000 },
},
canvas: Canvas,
pub fn init(allocator: std.mem.Allocator) WindowContext {
return .{
.allocator = allocator,
.canvas = Canvas.init(allocator),
};
}
/// Заполнить canvas случайным цветом на CPU
pub fn fillRandomColor(self: *WindowContext) !void {
var prng = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp()));
const random = prng.random();
// Выделить буфер пиксельных данных
const pixels = try self.allocator.alloc(Color.PMA, @as(usize, self.canvas_width) * self.canvas_height);
defer self.allocator.free(pixels);
// Заполнить случайными цветами
const r = random.int(u8);
const g = random.int(u8);
const b = random.int(u8);
var prev: dvui.Color.PMA = .{
.r = r,
.g = g,
.b = b,
.a = 255,
};
for (pixels) |*pixel| {
const r_delta = random.intRangeAtMost(i16, -1, 1);
const g_delta = random.intRangeAtMost(i16, -1, 1);
const b_delta = random.intRangeAtMost(i16, -1, 1);
const r_new: i16 = @as(i16, prev.r) + r_delta;
const g_new: i16 = @as(i16, prev.g) + g_delta;
const b_new: i16 = @as(i16, prev.b) + b_delta;
pixel.* = .{
.r = @intCast(std.math.clamp(r_new, 0, 255)),
.g = @intCast(std.math.clamp(g_new, 0, 255)),
.b = @intCast(std.math.clamp(b_new, 0, 255)),
.a = 255,
};
prev = pixel.*;
}
// Удалить старую текстуру
if (self.canvas_texture) |tex| {
dvui.Texture.destroyLater(tex);
}
// Создать новую текстуру из пиксельных данных
self.canvas_texture = try dvui.textureCreate(pixels, self.canvas_width, self.canvas_height, .linear);
// Дать скроллам ощутимый диапазон сразу (минимум 2000x2000)
self.canvas_scroll.virtual_size = .{
.w = @max(2000, @as(f32, @floatFromInt(self.canvas_width))),
.h = @max(2000, @as(f32, @floatFromInt(self.canvas_height))),
};
try self.canvas.fillRandomColor();
}
/// Отобразить canvas в UI
pub fn render(self: WindowContext, rect: dvui.Rect.Physical) !void {
if (self.canvas_texture) |texture| {
try dvui.renderTexture(texture, .{ .r = rect }, .{});
}
try self.canvas.render(rect);
}
pub fn deinit(self: *WindowContext) void {
if (self.canvas_texture) |texture| {
dvui.Texture.destroyLater(texture);
}
self.canvas.deinit();
}