Первые попытки проверки видимой части

This commit is contained in:
2025-12-20 18:05:28 +03:00
parent e22051c1c1
commit b5d60d67dd
3 changed files with 125 additions and 30 deletions

7
.vscode/launch.json vendored
View File

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

View File

@@ -1,10 +1,18 @@
const std = @import("std");
const builtin = @import("builtin");
const dvui = @import("dvui");
const Size = dvui.Size;
const Color = dvui.Color;
const Canvas = @This();
pub const ImageRect = struct {
x: u32,
y: u32,
w: u32,
h: u32,
};
allocator: std.mem.Allocator,
texture: ?dvui.Texture = null,
size: Size = .{ .w = 800, .h = 600 },
@@ -31,9 +39,9 @@ pub fn deinit(self: *Canvas) void {
/// Заполнить canvas градиентом
pub fn redrawGradient(self: *Canvas) !void {
std.debug.print("Zoom: {any}\n", .{self.zoom});
const width: u32 = @intFromFloat(self.size.w * self.zoom);
const height: u32 = @intFromFloat(self.size.h * self.zoom);
const size = self.getScaledSize();
const width: u32 = @intFromFloat(size.w);
const height: u32 = @intFromFloat(size.h);
// Выделить буфер пиксельных данных
const pixels = try self.allocator.alloc(Color.PMA, @as(usize, width) * height);
@@ -76,6 +84,80 @@ pub fn addZoom(self: *Canvas, value: f32) void {
self.zoom = @max(self.zoom, 0.01);
}
pub fn getScaledSize(self: Canvas) Size {
return .{
.w = self.size.w * self.zoom,
.h = self.size.h * self.zoom,
};
}
/// Видимая часть изображения, которую реально видит пользователь.
///
/// Возвращает прямоугольник в координатах самой картинки (пиксели текстуры):
/// - (0,0) — левый верхний пиксель изображения
/// - размеры ограничены размером текстуры
///
/// Параметры:
/// - `viewport`: размер видимой области scroll-area (x/y игнорируются)
/// - `scroll_offset`: текущий scroll (виртуальные координаты контента)
pub fn getVisibleImageRect(self: Canvas, viewport: dvui.Rect, scroll_offset: dvui.Point) ImageRect {
const tex = self.texture orelse return .{ .x = 0, .y = 0, .w = 0, .h = 0 };
const img_w_f: f32 = @floatFromInt(tex.width);
const img_h_f: f32 = @floatFromInt(tex.height);
const view_left: f32 = scroll_offset.x;
const view_top: f32 = scroll_offset.y;
const view_right: f32 = scroll_offset.x + viewport.w;
const view_bottom: f32 = scroll_offset.y + viewport.h;
const img_left: f32 = self.pos.x;
const img_top: f32 = self.pos.y;
const img_right: f32 = self.pos.x + img_w_f;
const img_bottom: f32 = self.pos.y + img_h_f;
const inter_left: f32 = @max(view_left, img_left);
const inter_top: f32 = @max(view_top, img_top);
const inter_right: f32 = @min(view_right, img_right);
const inter_bottom: f32 = @min(view_bottom, img_bottom);
if (inter_right <= inter_left or inter_bottom <= inter_top) {
if (builtin.mode == .Debug) {
std.debug.print(" -> no intersection, return empty\n", .{});
}
return .{ .x = 0, .y = 0, .w = 0, .h = 0 };
}
// Переводим из координат контента в локальные координаты картинки
const local_x0: f32 = inter_left - img_left;
const local_y0: f32 = inter_top - img_top;
const local_x1: f32 = inter_right - img_left;
const local_y1: f32 = inter_bottom - img_top;
// Консервативно округляем до пикселей: начало вниз (floor), конец вверх (ceil)
const x0_u32: u32 = floatToClampedU32(@floor(local_x0), tex.width);
const y0_u32: u32 = floatToClampedU32(@floor(local_y0), tex.height);
const x1_u32: u32 = floatToClampedU32(@ceil(local_x1), tex.width);
const y1_u32: u32 = floatToClampedU32(@ceil(local_y1), tex.height);
const out: ImageRect = .{
.x = x0_u32,
.y = y0_u32,
.w = if (x1_u32 > x0_u32) x1_u32 - x0_u32 else 0,
.h = if (y1_u32 > y0_u32) y1_u32 - y0_u32 else 0,
};
return out;
}
fn floatToClampedU32(value: f32, max_inclusive: u32) u32 {
if (max_inclusive == 0) return 0;
if (value <= 0) return 0;
const max_f: f32 = @floatFromInt(max_inclusive);
if (value >= max_f) return max_inclusive;
return @intFromFloat(value);
}
/// Отобразить canvas в UI
pub fn render(self: Canvas, rect: dvui.Rect.Physical) !void {
if (self.texture) |texture| {

View File

@@ -93,7 +93,7 @@ fn gui_frame(ctx: *WindowContext) bool {
canvas.fillRandomGradient() catch |err| {
std.debug.print("Error filling canvas: {}\n", .{err});
};
canvas.pos = .{ .x = 400, .y = 400 };
canvas.pos = .{ .x = 800, .y = 400 };
}
}
left_panel.deinit();
@@ -120,14 +120,11 @@ fn gui_frame(ctx: *WindowContext) bool {
{
var textured = dvui_ext.texturedBox(right_panel.data().contentRectScale(), dvui.Rect.all(20));
{
var canvas_box = dvui.box(
var overlay = dvui.overlay(
@src(),
.{ .dir = .vertical },
.{ .expand = .both },
);
{
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
var scroll = dvui.scrollArea(
@src(),
.{
@@ -144,42 +141,51 @@ fn gui_frame(ctx: *WindowContext) bool {
// Отобразить canvas внутри scroll area.
// ScrollArea сам двигает дочерние виджеты, поэтому margin не нужен.
if (canvas.texture) |texture| {
const img_size = canvas.getScaledSize();
_ = dvui.image(@src(), .{
.source = .{ .texture = texture },
}, .{
.margin = .{ .x = canvas.pos.x, .y = canvas.pos.y },
.min_size_content = .{
.w = @floatFromInt(texture.width),
.h = @floatFromInt(texture.height),
.w = img_size.w,
.h = img_size.h,
},
});
}
}
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.redrawGradient() catch {};
},
else => {},
// Получить viewport и scroll offset
const viewport_rect = scroll.data().contentRect();
const scroll_current = dvui.Point{ .x = canvas.scroll.viewport.x, .y = canvas.scroll.viewport.y };
const visible_rect = canvas.getVisibleImageRect(viewport_rect, scroll_current);
std.debug.print("Visible image rect: {any}\n", .{visible_rect});
}
// Заблокировать события скролла, если нажат 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.redrawGradient() catch {};
},
else => {},
}
e.handled = true;
}
e.handled = true;
}
},
else => {},
},
else => {},
}
}
}
}
scroll.deinit();
dvui.label(@src(), "Canvas", .{}, .{ .gravity_x = 0.5, .gravity_y = 0.0 });
}
canvas_box.deinit();
overlay.deinit();
}
textured.deinit();
}