Compare commits

28 Commits

Author SHA1 Message Date
6fc311139f Перегенерирован отчёт 2026-03-19 19:35:23 +03:00
97c19381d9 Фикс цветов 2026-03-19 19:26:08 +03:00
d73d378194 обозначения в отчёте 2026-03-19 18:08:18 +03:00
aea57a1901 мелкие правки в отчёте 2026-03-19 17:57:45 +03:00
d09ab72a38 более верный отчёт 2026-03-19 16:25:20 +03:00
d6825592b1 скрипт генерации pdf 2026-03-19 15:43:14 +03:00
37036f8f75 Report 2026-03-19 14:54:09 +03:00
7145b66e0e Merge remote-tracking branch 'codeberg/review' 2026-03-18 23:39:28 +03:00
andrew.kraevskii
d6c8a062cd Fix memory leaks found by DebugAllocator. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
045624beac Use leak detection of DebugAllocator.
When allocating memory it remebers where memory was allocated but it only
for leaks in .deinit(). So not calling it is a sure way to miss a bunch of leaks.

deinit() returns if it found leaks but we don't really care. Its usefull for tests but not here.
2026-03-04 02:00:40 +03:00
andrew.kraevskii
b0259c5788 Stuff. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
0a47ea1e43 If function doesn't do anything related to object just don't pass object to it 2026-03-04 02:00:40 +03:00
andrew.kraevskii
cc10d806fe Return type of field of property instead of property. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
e3a4506194 Use std.mem.Allocator.dupe instead of @memcpy. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
3348b2e91c Update to latest dvui. 2026-03-04 02:00:40 +03:00
andrew.kraevskii
9ca360c6b3 Im trying not to die of old age waiting on llvm :( 2026-03-04 02:00:21 +03:00
2e2c140d5b applyPropertyPatch 2026-03-03 20:46:23 +03:00
129206ce4f Очистка 2026-03-03 20:39:01 +03:00
446cd80616 points теперь слайс 2026-03-03 20:38:57 +03:00
9a795c22f1 Изменён лимит частоты перерисовки 2026-03-03 20:10:30 +03:00
84c9a55ee5 refactor: Удалена нереализованная фигура "Дуга"
Полностью удалены модель, инструменты, рендеринг и связанные UI-элементы для фигуры "Дуга", поскольку она не была реализована в системе.
Также обновлены иконки для инструментов "Линия" и "Ломаная линия".
2026-03-03 20:07:03 +03:00
4bb98f1f41 заливка круга и closed 2026-03-03 19:59:50 +03:00
d6d41388b3 Небольшое упрощение 2026-03-03 19:46:50 +03:00
4bf92356af Первый крутой круг 2026-03-03 19:07:53 +03:00
b1177265ea Универсальная растровая заливка 2026-03-03 18:30:24 +03:00
5b1b3a8c5e Переход на i32 2026-03-03 15:26:01 +03:00
7aa9673b44 Более красивая панель 2026-03-03 14:32:20 +03:00
32cffb757d Заливка и замкнутая фигура 2026-03-03 14:21:55 +03:00
54 changed files with 6029 additions and 370 deletions

View File

@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""
Append source files to a markdown report and save as a new file.
Example:
python3 Report/append_sources_to_report.py \
--input Report/zivro-open-project-report.md \
--output Report/zivro-open-project-report-with-code.md \
--base .
"""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Iterable
DEFAULT_EXTENSIONS = {
".zig",
".zon",
".json",
".toml",
".yaml",
".yml",
".md",
".txt",
".py",
".puml",
}
DEFAULT_EXCLUDE_DIRS = {
".git",
"zig-out",
"zig-cache",
".zig-cache",
".cursor",
"mcps",
}
DEFAULT_EXCLUDE_FILES = {
".DS_Store",
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Adds source code listings to the end of a markdown report and writes "
"the result to a new markdown file."
)
)
parser.add_argument("--input", required=True, help="Path to source markdown report")
parser.add_argument("--output", required=True, help="Path to output markdown report")
parser.add_argument(
"--base",
default=".",
help="Project root to scan for source files (default: current directory)",
)
parser.add_argument(
"--include",
nargs="*",
default=["src", "build.zig", "build.zig.zon"],
help=(
"Files/directories (relative to --base) to include in appendix scan. "
"Default: src build.zig build.zig.zon"
),
)
parser.add_argument(
"--extensions",
nargs="*",
default=sorted(DEFAULT_EXTENSIONS),
help=(
"Allowed file extensions (e.g. .zig .md). "
"If empty, all file extensions are allowed."
),
)
parser.add_argument(
"--exclude-dir",
nargs="*",
default=sorted(DEFAULT_EXCLUDE_DIRS),
help="Directory names to exclude recursively",
)
parser.add_argument(
"--max-bytes",
type=int,
default=1_000_000,
help="Skip files larger than this size in bytes (default: 1_000_000)",
)
return parser.parse_args()
def is_text_file(path: Path) -> bool:
try:
data = path.read_bytes()
except OSError:
return False
if b"\x00" in data:
return False
return True
def iter_files(
base: Path,
include_paths: Iterable[str],
extensions: set[str],
exclude_dirs: set[str],
max_bytes: int,
) -> list[Path]:
files: list[Path] = []
def add_file(path: Path) -> None:
if not path.is_file():
return
if path.name in DEFAULT_EXCLUDE_FILES:
return
if extensions and path.suffix.lower() not in extensions:
return
try:
size = path.stat().st_size
except OSError:
return
if size > max_bytes:
return
if not is_text_file(path):
return
files.append(path)
for rel in include_paths:
item = (base / rel).resolve()
if not item.exists():
continue
if item.is_file():
add_file(item)
continue
for path in item.rglob("*"):
if any(part in exclude_dirs for part in path.parts):
continue
add_file(path)
return sorted(set(files), key=lambda p: p.relative_to(base).as_posix())
def language_for(path: Path) -> str:
ext = path.suffix.lower()
if ext == ".zig":
return "zig"
if ext == ".py":
return "python"
if ext in {".yaml", ".yml"}:
return "yaml"
if ext == ".json":
return "json"
if ext == ".toml":
return "toml"
if ext == ".md":
return "markdown"
return ""
def main() -> int:
args = parse_args()
input_path = Path(args.input).resolve()
output_path = Path(args.output).resolve()
base_path = Path(args.base).resolve()
if not input_path.exists():
raise FileNotFoundError(f"Input report not found: {input_path}")
if input_path == output_path:
raise ValueError("--input and --output must be different files")
report_text = input_path.read_text(encoding="utf-8")
extensions = {e.lower() if e.startswith(".") else f".{e.lower()}" for e in args.extensions}
exclude_dirs = set(args.exclude_dir)
files = iter_files(
base=base_path,
include_paths=args.include,
extensions=extensions,
exclude_dirs=exclude_dirs,
max_bytes=args.max_bytes,
)
appendix_lines: list[str] = []
appendix_lines.append("")
appendix_lines.append("---")
appendix_lines.append("")
appendix_lines.append("## Приложение A. Исходные тексты")
appendix_lines.append("")
appendix_lines.append(
f"Сформировано автоматически скриптом `Report/append_sources_to_report.py` "
f"(файлов: {len(files)})."
)
appendix_lines.append("")
for idx, path in enumerate(files, start=1):
rel = path.relative_to(base_path).as_posix()
lang = language_for(path)
code = path.read_text(encoding="utf-8", errors="replace")
appendix_lines.append(f"### A.{idx}. `{rel}`")
appendix_lines.append("")
appendix_lines.append(f"```{lang}")
appendix_lines.append(code.rstrip("\n"))
appendix_lines.append("```")
appendix_lines.append("")
output_text = report_text.rstrip() + "\n" + "\n".join(appendix_lines)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(output_text, encoding="utf-8")
print(f"Created: {output_path}")
print(f"Input report preserved: {input_path}")
print(f"Attached files: {len(files)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

11
Report/generate-pdf.sh Executable file
View File

@@ -0,0 +1,11 @@
#!/bin/bash
pandoc zivro-open-project-report-with-code.md \
-f markdown+implicit_figures+link_attributes+tex_math_dollars \
-o sample_1.pdf \
--pdf-engine=xelatex \
-V geometry:left=1.2cm,right=1.2cm,top=1.2cm,bottom=1.2cm \
-V mainfont="DejaVu Serif" \
-V monofont="DejaVu Sans Mono" \
-H header.tex

16
Report/header.tex Normal file
View File

@@ -0,0 +1,16 @@
\usepackage{fvextra}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{
breaklines,
breakanywhere,
commandchars=\\\{\},
fontsize=\small
}
\usepackage{xurl}
\urlstyle{same}
\setlength{\emergencystretch}{3em}
\usepackage{graphicx}
\setkeys{Gin}{width=\linewidth,height=0.80\textheight,keepaspectratio}
\usepackage{float}
\floatplacement{figure}{H}

182
Report/render_uml_png.py Normal file
View File

@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""
Render PlantUML diagrams (.puml) to high-resolution PNG files via Kroki.
Why this script:
- local `plantuml` may require X11 in some environments;
- this script uses Kroki HTTP API and can raise output quality via `skinparam dpi`.
Examples:
python3 Report/render_uml_png.py
python3 Report/render_uml_png.py --dpi 360 --glob "*.puml"
python3 Report/render_uml_png.py --input-dir Report/uml --timeout 120
"""
from __future__ import annotations
import argparse
import io
from pathlib import Path
import re
from typing import Iterable
import requests
from PIL import Image
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Render .puml diagrams to PNG with configurable DPI."
)
parser.add_argument(
"--input-dir",
default="Report/uml",
help="Directory with .puml files (default: Report/uml)",
)
parser.add_argument(
"--glob",
default="*.puml",
help="Glob pattern inside input-dir (default: *.puml)",
)
parser.add_argument(
"--dpi",
type=int,
default=300,
help="Output DPI via PlantUML skinparam (default: 300)",
)
parser.add_argument(
"--timeout",
type=int,
default=120,
help="HTTP timeout in seconds (default: 120)",
)
parser.add_argument(
"--kroki-url",
default="https://kroki.io/plantuml/png",
help="Kroki PlantUML PNG endpoint",
)
parser.add_argument(
"--min-dpi",
type=int,
default=96,
help="Lower bound for auto DPI fallback (default: 96)",
)
parser.add_argument(
"--max-dim",
type=int,
default=3900,
help=(
"Target max PNG dimension during auto-fit. "
"Keep below backend hard limits (default: 3900)"
),
)
return parser.parse_args()
def iter_puml_files(input_dir: Path, pattern: str) -> Iterable[Path]:
return sorted(p for p in input_dir.glob(pattern) if p.is_file())
def inject_or_replace_skinparam(plantuml_text: str, key: str, value: int) -> str:
"""
Ensure diagram has the requested `skinparam <key>`.
- If skinparam exists, replace it.
- Otherwise insert after @startuml line.
"""
line_value = f"skinparam {key} {value}"
pattern = rf"(?im)^\s*skinparam\s+{re.escape(key)}\s+\d+\s*$"
if re.search(pattern, plantuml_text):
return re.sub(pattern, line_value, plantuml_text)
lines = plantuml_text.splitlines()
for i, line in enumerate(lines):
if line.strip().lower().startswith("@startuml"):
lines.insert(i + 1, line_value)
return "\n".join(lines) + ("\n" if plantuml_text.endswith("\n") else "")
# Fallback: if @startuml is missing, prepend anyway.
return line_value + "\n" + plantuml_text
def render_one(
puml_file: Path,
kroki_url: str,
dpi: int,
min_dpi: int,
max_dim: int,
timeout: int,
) -> Path:
source = puml_file.read_text(encoding="utf-8")
source = inject_or_replace_skinparam(source, "padding", 24)
current_dpi = dpi
png_bytes: bytes | None = None
while True:
payload = inject_or_replace_skinparam(source, "dpi", current_dpi)
response = requests.post(
kroki_url,
data=payload.encode("utf-8"),
timeout=timeout,
)
response.raise_for_status()
candidate = response.content
with Image.open(io.BytesIO(candidate)) as im:
width, height = im.size
# Kroki/PlantUML PNG responses may hit hard canvas limits.
# If we are close to that ceiling, lower DPI and retry.
if (width > max_dim or height > max_dim) and current_dpi > min_dpi:
next_dpi = max(min_dpi, int(current_dpi * 0.82))
if next_dpi == current_dpi:
next_dpi = current_dpi - 1
current_dpi = max(min_dpi, next_dpi)
continue
png_bytes = candidate
break
if png_bytes is None:
raise RuntimeError(f"Failed to render diagram: {puml_file}")
out_file = puml_file.with_suffix(".png")
out_file.write_bytes(png_bytes)
return out_file
def main() -> int:
args = parse_args()
input_dir = Path(args.input_dir).resolve()
if not input_dir.exists():
raise FileNotFoundError(f"Input directory not found: {input_dir}")
files = list(iter_puml_files(input_dir, args.glob))
if not files:
print(f"No files matched in {input_dir} with pattern {args.glob}")
return 0
print(f"Rendering {len(files)} diagrams from: {input_dir}")
print(f"DPI: {args.dpi}")
success = 0
for puml in files:
out = render_one(
puml_file=puml,
kroki_url=args.kroki_url,
dpi=args.dpi,
min_dpi=args.min_dpi,
max_dim=args.max_dim,
timeout=args.timeout,
)
print(f"created {out}")
success += 1
print(f"Done: {success}/{len(files)} PNG files generated.")
return 0
if __name__ == "__main__":
raise SystemExit(main())

BIN
Report/sample_1.pdf Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

View File

@@ -0,0 +1,35 @@
@startuml
title Canvas/ViewPort: алгоритм вычисления видимой области и редроу
start
:Get zoomed document rect\n(getZoomedImageSize);
:Read viewport rect + scroll offset;
:Compute visible width/height\nmin(viewport, image size);
:Compute raw visible x/y\nfrom scroll - image offset;
:Clamp x/y into image bounds;
:Store Rect_i{x,y,w,h} as _visible_rect;
if (visible rect changed\nOR texture is null?) then (yes)
:request redraw;
else (no)
:no redraw needed;
endif
if (redraw pending?) then (yes)
:Read render quality %;
:Convert area-quality to side-scale\nscale = sqrt(q/100);
:Scale full canvas size;
:Scale visible rect;
:Clamp scaled rect to scaled canvas;
if (scaled visible rect valid?) then (yes)
:Render only scaled visible area\nthrough RenderEngine;
:Update texture + stats + throttle;
else (no)
:Drop texture / skip rendering;
endif
else (no)
:Keep previous frame;
endif
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

View File

@@ -0,0 +1,28 @@
@startuml
title Конвейер координат: Local -> World -> Canvas -> Buffer
skinparam rectangle {
RoundCorner 10
}
rectangle "Local coords\n(object space)" as L
rectangle "World coords\n(document space)" as W
rectangle "Canvas coords\n(scaled document)" as C
rectangle "Buffer coords\n(visible rect origin)" as B
L --> W : localToWorld()\nrotate + scale + translate
W --> C : world * scale_x/scale_y
C --> B : subtract visible_rect.(x,y)
B --> C : + visible_rect.(x,y)
C --> W : divide by scale_x/scale_y
W --> L : worldToLocal()\ntranslate^-1 + rotate^-1 + scale^-1
note right of B
All raster tests are done
in buffer coords (integer pixels).
Shape analytics often done
in local coords after inverse map.
end note
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

@@ -0,0 +1,43 @@
@startuml
title Эллипс/дуга: алгоритм растризации
start
:Read rx, ry, thickness,\narc_percent, closed, filled;
if (rx<=0 or ry<=0?) then (yes)
stop
endif
:Build local bbox corners with margin;
:Transform corners to buffer\nand compute pixel scan bounds;
:Create temporary transparent buffer;
if (do_fill?) then (yes)
:startFill() collect border pixels;
endif
while (for each pixel in bbox)
:Map pixel center Buffer -> World -> Local;
:nx = x/rx, ny = y/ry,\nd = nx^2 + ny^2;
if (d in stroke ring?) then (yes)
if (arc_percent < 100?) then (yes)
:Compute angular position\nvia atan2 and normalized diff;
if (inside arc sector?) then (yes)
:plot stroke pixel;
endif
else (full ellipse)
:plot stroke pixel;
endif
endif
endwhile
if (closed and arc_percent<100?) then (yes)
:Draw two radial segments\n(center->start and center->end);
endif
if (do_fill?) then (yes)
:stopFill(fill_color);
endif
:Composite temp buffer to target\nonce with object opacity;
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

View File

@@ -0,0 +1,34 @@
@startuml
title Liang-Barsky: отсечение отрезка прямоугольником
start
:Input segment P0,P1 and clip rect;
:dx = x1-x0, dy = y1-y0;
:t0 = 0, t1 = 1;
:Process boundary x >= left\np=-dx, q=x0-left;
if (clip test fails?) then (yes)
stop
endif
:Process boundary x <= right\np=dx, q=right-x0;
if (clip test fails?) then (yes)
stop
endif
:Process boundary y >= top\np=-dy, q=y0-top;
if (clip test fails?) then (yes)
stop
endif
:Process boundary y <= bottom\np=dy, q=bottom-y0;
if (clip test fails?) then (yes)
stop
endif
:Compute clipped points:\nP0' = P0 + t0*(P1-P0)\nP1' = P0 + t1*(P1-P0);
:Round to integer pixels;
:Return accepted clipped segment;
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View File

@@ -0,0 +1,30 @@
@startuml
title Линия: полная схема растризации
start
:Input local endpoints (x0,y0),(x1,y1)\n+ color + thickness;
:Map endpoints Local -> World -> Buffer;
:Compute pixel thickness from transform scale;
if (thickness_px <= 0?) then (yes)
stop
endif
if (draw_when_outside == false?) then (yes)
:Clip segment to expanded buffer bounds\n(Liang-Barsky);
if (segment rejected?) then (yes)
stop
endif
endif
:Compute angle-based thickness correction\n(using |dx|/len and |dy|/len);
:Initialize Bresenham state\ndx,dy,sx,sy,err;
while (not reached end point?)
:Choose effective half-thickness:\nfull in viewport, 0 outside if draw_when_outside;
:Draw stripe around center pixel\n(along normal axis);
:Advance Bresenham step by error update;
endwhile
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -0,0 +1,27 @@
@startuml
title PMA alpha blending в blendPixelAtBuffer
start
:Input dst pixel, src PMA pixel,\ntransform opacity;
if (pixel outside buffer?) then (yes)
stop
endif
if (replace_mode?) then (yes)
:dst = src;
stop
endif
:a = (src.a / 255) * opacity;
:inv_a = 1 - a;
:src_rgb = src.rgb * opacity;
:dst.r = clamp(src_r + inv_a * dst.r);
:dst.g = clamp(src_g + inv_a * dst.g);
:dst.b = clamp(src_b + inv_a * dst.b);
:dst.a = clamp(a*255 + inv_a * dst.a);
:Store dst pixel;
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

@@ -0,0 +1,29 @@
@startuml
title Ломаная + заливка: 3-фазный алгоритм
start
:Input points[], closed, filled;
if (points < 2?) then (yes)
stop
endif
:Create temporary buffer + copy context;
if (closed and filled?) then (yes)
:Enable FillCanvas (startFill);
endif
:Draw all segments Pi->Pi+1;
if (closed?) then (yes)
:Draw segment Pn->P0;
endif
if (fill enabled?) then (yes)
:Phase 1:\nBorder pixels already collected in hash-set;
:Phase 2:\nSort border keys by (y,x),\nfind row segments,\nchoose interior seeds;
:Phase 3:\nStack flood fill (4-neighbors),\nskip border/visited,\npaint fill color;
endif
:Composite temporary buffer to target once;
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View File

@@ -0,0 +1,19 @@
@startuml
title Алгоритм композиции трансформаций (parent * local)
start
:Input parent transform:\nP(tx,ty,angle,sx,sy,opacity);
:Input local transform:\nL(tx,ty,angle,sx,sy,opacity);
:Scale local position by parent scale:\nlx' = L.tx * P.sx\nly' = L.ty * P.sy;
:Rotate by parent angle:\nrx = cos(P.a)*lx' - sin(P.a)*ly'\nry = sin(P.a)*lx' + cos(P.a)*ly';
:Translate by parent position:\nW.tx = P.tx + rx\nW.ty = P.ty + ry;
:Compose angle:\nW.angle = P.angle + L.angle;
:Compose scale:\nW.sx = P.sx * L.sx\nW.sy = P.sy * L.sy;
:Compose opacity:\nW.opacity = P.opacity * L.opacity;
:Return world transform W;
stop
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

View File

@@ -0,0 +1,49 @@
@startuml
title Zivro: компонентная архитектура
skinparam componentStyle rectangle
skinparam shadowing false
package "UI Layer" {
[main.zig\nEvent Loop]
[ui/*\nMenu/Tab/Panels]
[Canvas.zig\nViewport + Redraw]
}
package "Application State" {
[WindowContext.zig\nOpenDocument tabs]
[models/Document.zig\nObject tree]
[models/Object.zig\nProperties + Children]
}
package "Render Layer" {
[RenderEngine.zig\nInterface]
[CpuRenderEngine.zig\nCPU backend]
[cpu/draw.zig\nRecursive draw]
[cpu/pipeline.zig\nTransforms + blend]
[cpu/line.zig]
[cpu/ellipse.zig]
[cpu/broken.zig]
}
package "Persistence" {
[persistence/json_io.zig]
}
[main.zig\nEvent Loop] --> [WindowContext.zig\nOpenDocument tabs]
[ui/*\nMenu/Tab/Panels] --> [WindowContext.zig\nOpenDocument tabs]
[Canvas.zig\nViewport + Redraw] --> [RenderEngine.zig\nInterface]
[Canvas.zig\nViewport + Redraw] --> [models/Document.zig\nObject tree]
[WindowContext.zig\nOpenDocument tabs] --> [Canvas.zig\nViewport + Redraw]
[WindowContext.zig\nOpenDocument tabs] --> [CpuRenderEngine.zig\nCPU backend]
[RenderEngine.zig\nInterface] <|.. [CpuRenderEngine.zig\nCPU backend]
[CpuRenderEngine.zig\nCPU backend] --> [cpu/draw.zig\nRecursive draw]
[cpu/draw.zig\nRecursive draw] --> [cpu/pipeline.zig\nTransforms + blend]
[cpu/draw.zig\nRecursive draw] --> [cpu/line.zig]
[cpu/draw.zig\nRecursive draw] --> [cpu/ellipse.zig]
[cpu/draw.zig\nRecursive draw] --> [cpu/broken.zig]
[models/Document.zig\nObject tree] --> [models/Object.zig\nProperties + Children]
[persistence/json_io.zig] ..> [models/Document.zig\nObject tree] : save/load
@enduml

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

View File

@@ -0,0 +1,33 @@
@startuml
title Zivro: последовательность рендера кадра (CPU)
actor User
participant "UI Frame\n(frame.zig)" as UI
participant "Canvas\n(Canvas.zig)" as Canvas
participant "RenderEngine" as RE
participant "CpuRenderEngine" as CPU
participant "drawDocument\n(cpu/draw.zig)" as Draw
participant "Shape modules\nline/ellipse/broken" as Shapes
User -> UI : input/events
UI -> Canvas : processPendingRedraw()
alt redraw pending and throttle passed
Canvas -> Canvas : computeVisibleImageRect()\ncompute quality scale
Canvas -> RE : render(document, canvas_size, visible_rect)
RE -> CPU : renderDocument(...)
CPU -> Draw : drawDocument(pixels,...)
loop for each root object
Draw -> Draw : Transform.compose(parent, local)
Draw -> Shapes : draw shape by object.kind
loop for each child
Draw -> Draw : recursive drawObject(child, world_transform)
end
end
Draw --> CPU : pixels rendered
CPU --> Canvas : texture
Canvas -> UI : texture for draw
else no redraw
Canvas -> UI : keep previous texture
end
@enduml

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,490 @@
# Лабораторная работа 3
## Векторный редактор `Zivro`
## 1. Цель работы
### 1.1. Дидактическая цель
Овладеть навыками разработки программных модулей, реализующих алгоритмы растровой развёртки (растеризации) контуров фигур и сплошных областей на плоскости, а также получить опыт эмпирического анализа вычислительной трудоёмкости и точности алгоритмов растеризации.
### 1.2. Практическая цель
Разработать и исследовать программный модуль, выполняющий:
- растеризацию контура фигуры;
- растеризацию (закраску) сплошной области;
- формирование и отображение растрового изображения;
- сбор эмпирических данных по времени выполнения и различию результатов алгоритмов.
В рамках данной работы в качестве программной базы используется проект `Zivro`, разработанный автором специально для выполнения лабораторной работы, в который интегрированы и исследуются соответствующие алгоритмы.
## 2. Постановка задачи
В рамках лабораторной работы требуется реализовать и проверить функционал, соответствующий методическим указаниям ЛР №3:
1. Реализовать программный модуль растеризации контура и внутренней области фигуры на растровом изображении.
2. Обеспечить вывод результата в окне/холсте приложения с попиксельной визуализацией.
3. Реализовать не менее двух алгоритмов построения контура и не менее двух алгоритмов закраски (в соответствии с вариантом).
4. Добавить эталонный контурный алгоритм (например, Брезенхейм) для сравнения.
5. Реализовать сбор эмпирических данных:
- время выполнения алгоритмов;
- различие получаемых растровых развёрток (по отличающимся пикселям).
6. Подготовить и оформить отчёт по выполненной работе.
7. Сформировать приложение с исходными текстами автоматически в отдельный `.md` без изменения исходного файла отчёта.
## 3. Краткое описание проекта
Для выполнения ЛР в качестве основы используется проект `Zivro` - настольное графическое приложение для работы с векторными объектами (линия, эллипс, ломаная), с собственной моделью документа, иерархией объектов и CPU-рендерингом.
В контексте ЛР проект используется не как объект абстрактного обзора, а как программная платформа, где реализуются и исследуются алгоритмы растеризации контура и закраски.
Приложение использует:
- язык `Zig`;
- UI-библиотеку `dvui` с SDL3-бэкендом;
- модульную архитектуру (UI, модель данных, рендер, сериализация, инструменты).
Точка входа находится в `src/main.zig`: создаётся окно, инициализируется `WindowContext`, далее выполняется event/render loop и отрисовка растрового результата алгоритмов.
## 4. Структура проекта
Основные каталоги и файлы:
- `build.zig` - сценарий сборки и шагов `run`/`test`;
- `src/main.zig` - запуск приложения и главный цикл;
- `src/WindowContext.zig` - управление открытыми документами и активным документом;
- `src/Canvas.zig` - логика холста, масштабирование, вычисление видимой области, запуск рендера;
- `src/models/*` - модель документа, объектов и их свойств;
- `src/render/*` - CPU-рендер и конвейер отрисовки;
- `src/persistence/json_io.zig` - сохранение/загрузка документов в JSON;
- `src/ui/*` - интерфейсные панели и компоновка экрана;
- `src/tests.zig` - entry-point тестов.
## 5. Архитектура приложения
### 5.1. Высокоуровневая схема
Архитектурно проект разделён на три уровня:
1. **UI-уровень** (`src/ui`, `src/Canvas.zig`)
Обрабатывает пользовательские события, отображает панели и холст, передаёт действия в модель и рендер.
2. **Модель данных** (`src/models`)
Хранит документ, дерево объектов и свойства (позиция, угол, масштаб, цвет, точки, радиусы и др.).
3. **Рендер-уровень** (`src/render`)
Преобразует модель объектов в набор пикселей видимой области и формирует текстуру.
### 5.2. Управление документами
`WindowContext` хранит массив открытых документов (`OpenDocument`) и индекс активного документа.
Каждый `OpenDocument` содержит:
- `Document`;
- экземпляр `CpuRenderEngine`;
- `Canvas`;
- идентификатор выбранного объекта.
Это позволяет одновременно работать с несколькими документами во вкладках.
### 5.3. Рендер-конвейер
Ключевой путь рендера:
1. `Canvas.redraw()` вычисляет масштаб качества и видимую часть документа;
2. вызывается `RenderEngine.render(...)` (в текущей конфигурации CPU-вариант);
3. `CpuRenderEngine.renderDocument(...)` подготавливает пиксельный буфер;
4. `cpu/draw.zig` рекурсивно обходит объекты документа;
5. для каждого объекта применяется `Transform.compose(parent, local)`;
6. shape-специфичные модули рисуют примитивы в буфер;
7. буфер превращается в текстуру UI.
## 6. Математические алгоритмы проекта (подробное текстовое описание)
В данном разделе подробно рассмотрены алгоритмы, которые формируют геометрию и цвет в CPU-рендере.
### 6.1. Иерархические трансформации объектов
В основе рендера лежит сцена-дерево: каждый объект может иметь дочерние элементы.
Следовательно, координаты дочернего объекта заданы не в мировой системе, а в системе координат родителя.
В `Transform` хранятся:
- `position = (tx, ty)` - перенос;
- `angle = a` - поворот;
- `scale = (sx, sy)` - независимый масштаб по осям;
- `opacity = o` - накопленная непрозрачность.
Для перехода из локальных координат объекта к мировым используется аффинное преобразование:
$$
\begin{aligned}
x_w &= t_x + (x_l \cdot s_x)\cos a - (y_l \cdot s_y)\sin a, \\
y_w &= t_y + (x_l \cdot s_x)\sin a + (y_l \cdot s_y)\cos a.
\end{aligned}
$$
Обозначения:
- `x_l, y_l` - локальные координаты точки объекта;
- `x_w, y_w` - мировые координаты точки в документе;
- `t_x, t_y` - перенос (`position`) текущего transform;
- `s_x, s_y` - масштаб по осям (`scale_x`, `scale_y`);
- `a` - угол поворота объекта (в радианах).
При композиции `parent * local``Transform.compose`) выполняются шаги:
1. локальная позиция сначала масштабируется масштабом родителя;
2. результат поворачивается на угол родителя;
3. добавляется перенос родителя;
4. углы складываются: `a_world = a_parent + a_local`;
5. масштабы перемножаются покомпонентно: `sx_world = sx_parent * sx_local`, `sy_world = sy_parent * sy_local`;
6. прозрачности перемножаются: `o_world = o_parent * o_local`.
Почему это важно: такой порядок гарантирует, что при повороте/масштабе группы объектов дочерние элементы ведут себя как единая связанная конструкция.
### 6.2. Цепочка преобразований координат в рендере
Рендер использует 4 системы координат:
1. **локальная** (внутри shape);
2. **мировая** (внутри документа);
3. **координаты канвы** (после масштабирования документа под текущий размер);
4. **координаты буфера viewport** (видимая часть, начинающаяся с `(0,0)`).
Основные формулы:
- `canvas_x = world_x * scale_x`, `canvas_y = world_y * scale_y`;
- `buffer_x = canvas_x - visible_rect.x`, `buffer_y = canvas_y - visible_rect.y`.
Обратное преобразование также используется (например, в эллипсе):
- `canvas_x = buffer_x + visible_rect.x`, `canvas_y = buffer_y + visible_rect.y`;
- `world_x = canvas_x / scale_x`, `world_y = canvas_y / scale_y`.
Для вычисления локальных координат из мировых применяется обратный поворот и обратный масштаб:
$$
\begin{aligned}
dx &= x_w - t_x,\quad dy = y_w - t_y, \\
x_l &= \frac{dx\cos(-a)-dy\sin(-a)}{s_x}, \\
y_l &= \frac{dx\sin(-a)+dy\cos(-a)}{s_y}.
\end{aligned}
$$
Обозначения:
- `x_w, y_w` - мировые координаты точки;
- `x_l, y_l` - локальные координаты точки после обратного преобразования;
- `t_x, t_y` - перенос transform;
- `a` - угол поворота transform;
- `s_x, s_y` - масштаб transform;
- `dx, dy` - координаты точки после вычитания переноса.
Практический смысл: shape можно тестировать аналитически (по формулам) в "своей" удобной локальной системе, независимо от того, как он повернут и где расположен в документе.
### 6.3. Рисование линии: отсечение + дискретизация + толщина
Алгоритм в `line.zig` состоит из трёх частей.
#### 6.3.1. Отсечение Liang-Barsky
Перед рисованием линия отсекается расширенным прямоугольником буфера.
Параметрическая форма отрезка:
$$
P(t)=P_0+t(P_1-P_0),\quad t\in[0,1].
$$
Обозначения:
- `P_0, P_1` - начальная и конечная точки исходного отрезка;
- `P(t)` - точка на отрезке при параметре `t`;
- `t` - параметр интерполяции (`0` - начало, `1` - конец);
- `[t0, t1]` - допустимый интервал параметра после отсечения.
Для каждого ограничения (`x >= left`, `x <= right`, `y >= top`, `y <= bottom`) обновляется допустимый интервал `[t0, t1]`.
Если после обработки ограничений `t0 > t1`, отрезок полностью вне экрана и пропускается.
Преимущество: вместо "шагать по пикселям и каждый проверять границы" рендер сразу работает только с видимым отрезком.
#### 6.3.2. Дискретизация линии (Bresenham-подобный проход)
После отсечения используются целочисленные приращения:
- `dx = abs(x1 - x0)`, `dy = -abs(y1 - y0)`;
- `sx = sign(x1 - x0)`, `sy = sign(y1 - y0)`;
- ошибка `err = dx + dy`.
На каждом шаге:
- вычисляется `e2 = 2*err`;
- если `e2 >= dy`, двигаемся по `x`;
- если `e2 <= dx`, двигаемся по `y`.
Это классическая идея целочисленного интегрирования ошибки для аппроксимации идеального непрерывного отрезка на пиксельной сетке.
#### 6.3.3. Толщина и коррекция по углу
Если просто расширять линию равномерно, визуальная толщина может "плыть" при разных углах.
В проекте вычисляется поправка по длине проекций:
- `cos(theta) = |dx| / len`;
- `sin(theta) = |dy| / len`;
- выбирается базис (по X или Y), где ошибка толщины минимальна;
- итоговая толщина пересчитывается через деление на `max(sin, eps)` или `max(cos, eps)`.
Далее вокруг центрального пикселя проводится полоса ширины `thickness_corrected`.
Дополнительно есть режим `draw_when_outside`:
- внутри viewport рисуется полная толщина;
- за пределами viewport — только 1px, чтобы контур не "взрывался" по ширине за экраном.
### 6.4. Растрирование эллипса и дуги
Алгоритм `ellipse.zig` не использует инкрементальные midpoint-формулы, а работает через аналитическую проверку каждого пикселя в ограничивающем прямоугольнике.
#### 6.4.1. Нормализация координат
Для пикселя вычисляются локальные координаты `loc = (x_l, y_l)` и нормализуются:
$$
n_x = \frac{x_l}{r_x},\quad n_y = \frac{y_l}{r_y},\quad d=n_x^2+n_y^2.
$$
Обозначения:
- `x_l, y_l` - локальные координаты текущего пикселя (центра пикселя после обратного преобразования);
- `r_x, r_y` - полуоси эллипса по `x` и `y`;
- `n_x, n_y` - нормализованные координаты в системе эллипса;
- `d` - значение функции эллипса в нормализованной форме.
- `d = 1` соответствует идеальному контуру эллипса;
- `d < 1` внутри;
- `d > 1` снаружи.
#### 6.4.2. Полоса обводки заданной толщины
Толщина `thickness` переводится в нормированное пространство через меньшую полуось:
- `half_norm = thickness / (2*min(rx, ry))`;
- внутренний радиус: `inner = max(0, 1 - half_norm)`;
- внешний радиус: `outer = 1 + half_norm`.
Пиксель принадлежит обводке, если:
$$
inner^2 \le d \le outer^2.
$$
Обозначения:
- `d` - нормализованная квадратичная дистанция из предыдущей формулы;
- `inner` - внутренний радиус полосы обводки в нормализованном пространстве;
- `outer` - внешний радиус полосы обводки в нормализованном пространстве.
Это даёт геометрически корректную полосу вокруг эллипса при произвольном повороте/масштабе объекта.
#### 6.4.3. Дуга через угловой фильтр
Если `arc_percent < 100`, из полного эллипса берётся только часть:
- вычисляется длина дуги в радианах: `arc_len = 2*pi*arc_percent/100`;
- для пикселя находится угол через `atan2(ny, nx)` (с поправкой на экранную систему);
- точка принимается только если её угловая позиция не превышает `arc_len`.
Если `closed = true`, концы дуги соединяются с центром двумя радиальными отрезками (используется общий алгоритм линии).
### 6.5. Ломаная, выделение границы и заливка
В `broken.zig` ломаная строится как цепочка сегментов `P0->P1->...->Pn`, а при `closed` добавляется `Pn->P0`.
Для корректной заливки применяется трёхфазный алгоритм.
#### 6.5.1. Фаза 1: сбор пикселей границы
Во временном `FillCanvas` при каждом `blendPixelAtBuffer` сохраняется координата пикселя как граничная точка (`border_set`).
Смысл: сначала зафиксировать "жёсткий" контур, затем независимо заполнить внутренность.
#### 6.5.2. Фаза 2: поиск внутренних сегментов по строкам
Граничные пиксели сортируются по `(y, x)`. Для каждой строки:
1. выделяются последовательности рёбер;
2. строятся интервалы между соседними рёбрами;
3. из подходящих интервалов выбираются seed-точки (середина интервала).
Это снижает риск старта flood fill с внешней стороны фигуры.
#### 6.5.3. Фаза 3: flood fill (4-связность)
От каждого seed выполняется стековый обход соседей:
- влево, вправо, вверх, вниз;
- граничные пиксели не пересекаются;
- уже посещённые пиксели пропускаются.
Каждый найденный внутренний пиксель окрашивается в `fill_color`.
Почему используется отдельный буфер: при полупрозрачности иначе одна и та же область может смешаться несколько раз из-за пересечения сегментов.
### 6.6. Альфа-смешивание в Premultiplied Alpha (PMA)
Для каждого канала цвета применяется модель:
$$
C_{out} = C_{src} + (1-\alpha_{src})C_{dst},
\quad
\alpha_{out} = \alpha_{src} + (1-\alpha_{src})\alpha_{dst}.
$$
Обозначения:
- `C_src` - цвет источника в PMA (`r,g,b` уже домножены на альфу);
- `C_dst` - текущий цвет пикселя в буфере до смешивания;
- `C_out` - результат смешивания;
- `\alpha_src` - альфа источника (с учётом `transform.opacity`);
- `\alpha_dst` - альфа пикселя назначения;
- `\alpha_out` - итоговая альфа после композиции.
В коде `C_src` уже premultiplied (или домножается на opacity трансформа в момент смешивания).
Пошагово:
1. берётся альфа источника `a = src_a/255 * transform.opacity`;
2. вычисляется `inv_a = 1 - a`;
3. каналы `r,g,b` источника масштабируются на `transform.opacity`;
4. формируется новый `dst` по PMA-формуле.
`replace_mode = true` отключает смешивание и просто заменяет пиксель.
Этот режим используется во временных буферах shape-рендера, а затем результат один раз композится в целевой буфер.
### 6.7. Численная устойчивость и ограничения
В алгоритмах предусмотрены защиты от деградации вычислений:
- защита от деления на ноль в обратных преобразованиях (`scale == 0 -> 1.0`);
- использование `eps` в коррекции толщины линий;
- ограничение минимальных размеров рендер-буфера (`>= 1 px`);
- отсечение слишком больших выходов за viewport до начала растрирования;
- явное округление float->int в точках, где нужна стабильная пиксельная привязка.
Это снижает число визуальных артефактов при малых масштабах, сильных поворотах и частичной видимости объектов.
## 7. Работа с данными и сериализация
Модуль `src/persistence/json_io.zig` поддерживает:
- `saveToFile(...)` - сериализация в JSON (pretty-print);
- `loadFromFile(...)` - чтение JSON и восстановление структуры.
Для `Document` после парсинга выполняется клонирование, чтобы избежать проблем владения памятью (парсер выделяет память из арены).
## 8. Сборка, запуск и тестирование
### 8.1. Сборка и запуск
```bash
zig build
zig build run
```
### 8.2. Запуск тестов
```bash
zig build test
```
Файл `src/tests.zig` подключает модули с `test`-блоками, чтобы они выполнялись в составе общего тестового шага.
## 9. Автоматическое формирование приложения с исходным кодом
Чтобы не вставлять исходники вручную в конец отчёта, используется скрипт `Report/append_sources_to_report.py`.
Скрипт:
- читает исходный `.md` отчёт;
- добавляет раздел с кодом файлов проекта;
- перед каждым листингом вставляет путь файла;
- сохраняет результат в новый `.md` файл;
- исходный отчёт не изменяет.
Пример запуска:
```bash
python3 Report/append_sources_to_report.py \
--input Report/zivro-open-project-report.md \
--output Report/zivro-open-project-report-with-code.md \
--base .
```
## 10. PlantUML-диаграммы
Для отчёта подготовлены диаграммы в формате PlantUML (`.puml`) и сгенерированы их PNG-версии для прямой вставки в документ.
### 10.1. Архитектура проекта
`Report/uml/zivro-architecture-components.puml` - компонентная архитектура приложения.
![Компонентная архитектура Zivro](uml/zivro-architecture-components.png)
`Report/uml/zivro-render-sequence.puml` - последовательность рендера кадра.
![Последовательность рендера кадра](uml/zivro-render-sequence.png)
### 10.2. Управление холстом и viewport
`Report/uml/canvas-viewport-algorithm.puml` - вычисление видимой области, масштабирование по качеству, условия редроу.
![Алгоритм управления viewport и redraw](uml/canvas-viewport-algorithm.png)
### 10.3. Алгоритмы обработки данных и растризации
`Report/uml/transform-compose-algorithm.puml` - композиция трансформаций в иерархии объектов.
![Композиция трансформаций](uml/transform-compose-algorithm.png)
`Report/uml/coordinate-pipeline.puml` - конвейер преобразований координат.
![Конвейер преобразований координат](uml/coordinate-pipeline.png)
`Report/uml/line-rasterization-flow.puml` - полный алгоритм отрисовки линии.
![Полный алгоритм растрирования линии](uml/line-rasterization-flow.png)
`Report/uml/liang-barsky-clip.puml` - шаги отсечения отрезка методом Liang-Barsky.
![Алгоритм Liang-Barsky](uml/liang-barsky-clip.png)
`Report/uml/ellipse-arc-rasterization.puml` - растрирование эллипса/дуги.
![Алгоритм растрирования эллипса и дуги](uml/ellipse-arc-rasterization.png)
`Report/uml/polyline-fill-algorithm.puml` - построение и заливка замкнутой ломаной.
![Алгоритм ломаной и заливки](uml/polyline-fill-algorithm.png)
`Report/uml/pma-alpha-blending.puml` - PMA alpha-композиция пикселей.
![PMA alpha-композиция пикселя](uml/pma-alpha-blending.png)
### 10.4. Скрипт генерации PNG-диаграмм
Для повторной генерации PNG сохранён отдельный скрипт:
- `Report/render_uml_png.py`
Пример запуска в высоком качестве:
```bash
python3 Report/render_uml_png.py --input-dir Report/uml --dpi 360
```
## 11. Выводы
В ходе работы разработан и исследован проект `Zivro`, подготовлено структурированное описание его архитектуры. Проект реализует модульный подход: модель документа, иерархию объектов, CPU-рендер с преобразованиями координат и отдельные алгоритмы растеризации геометрии.
Ключевые математические части - композиция трансформаций, отсечение и растеризация линий, рендер эллипсов/дуг, а также алгоритм заливки замкнутых контуров.
Текстовый отчёт подготовлен без встроенных листингов кода; для генерации версии с приложением исходников создан отдельный автоматизированный скрипт.

View File

@@ -8,8 +8,8 @@ pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{
.name = "Zivro",
.use_llvm = true,
.use_lld = true,
// .use_llvm = true,
// .use_lld = true,
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,

View File

@@ -33,8 +33,8 @@
// internet connectivity.
.dependencies = .{
.dvui = .{
.url = "https://github.com/david-vanderson/dvui/archive/main.tar.gz",
.hash = "dvui-0.4.0-dev-AQFJmev72QC6e0ojhnW8a_wRhZDgzWWLgeyoNuIPZc2m",
.url = "git+https://github.com/david-vanderson/dvui#edb2d5a4cd2981fca74ee5f096277b91333c1316",
.hash = "dvui-0.4.0-dev-AQFJmeGB3QAwun9qF76CDE5IopA4nUVRgD-IwwTsOo4H",
},
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.

0
review.txt Normal file
View File

View File

@@ -116,6 +116,7 @@ fn redraw(self: *Canvas) !void {
}
self._last_redraw_time_ms = std.time.milliTimestamp();
self.frame_index += 1;
self.redraw_throttle_ms = @max(1, @as(u32, @intCast(self.render_engine.getStats().render_time_ns / std.time.ns_per_ms / 3)));
}
pub fn exampleReset(self: *Canvas) !void {

View File

@@ -16,15 +16,10 @@ pub const OpenDocument = struct {
selected_object_id: ?u64 = 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(default_size);
self.cpu_render = CpuRenderEngine.init(allocator, .Squares);
self.canvas = Canvas.init(
allocator,
&self.document,
(&self.cpu_render).renderEngine(),
);
self.selected_object_id = null;
initWithDocument(allocator, self, .init(.{
.w = 800,
.h = 600,
}));
}
pub fn initWithDocument(allocator: std.mem.Allocator, self: *OpenDocument, doc: Document) void {

View File

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

View File

@@ -5,7 +5,10 @@ const WindowContext = @import("WindowContext.zig");
const ui = @import("ui/frame.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// std.heap.GeneralPurposeAllocator was renamed to DebugAllocator recently.
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var backend = try SDLBackend.initWindow(.{

View File

@@ -6,7 +6,6 @@ const Object = @This();
pub const ShapeKind = enum {
line,
ellipse,
arc,
broken,
};
@@ -34,9 +33,9 @@ shape: ShapeKind,
properties: std.ArrayList(Property),
children: std.ArrayList(Object),
pub fn getProperty(self: Object, tag: std.meta.Tag(PropertyData)) ?*const PropertyData {
pub fn getProperty(self: Object, comptime tag: std.meta.Tag(PropertyData)) ?@FieldType(PropertyData, @tagName(tag)) {
for (self.properties.items) |*prop| {
if (std.meta.activeTag(prop.data) == tag) return &prop.data;
if (std.meta.activeTag(prop.data) == tag) return @field(prop.data, @tagName(tag));
}
return null;
}
@@ -45,7 +44,7 @@ pub fn getProperty(self: Object, tag: std.meta.Tag(PropertyData)) ?*const Proper
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);
if (p.data == .points) allocator.free(p.data.points);
self.properties.items[i] = prop;
return;
}

View File

@@ -15,9 +15,17 @@ pub const Data = union(enum) {
size: Size_f,
radii: Radii_f,
/// Процент дуги эллипса: 100 — полный эллипс, 50 — полуэллипс (0..100).
arc_percent: f32,
end_point: Point2_f,
points: std.ArrayList(Point2_f),
/// Владеет памятью; при deinit/clone — free/duplicate.
points: []const Point2_f,
/// Замкнутый контур (для ломаной: отрезок последняя–первая точка + заливка).
closed: bool,
/// Включена ли заливка.
filled: bool,
/// Цвет заливки, 0xRRGGBBAA.
fill_rgba: u32,
@@ -32,7 +40,7 @@ pub const Property = struct {
pub fn deinit(self: *Property, allocator: std.mem.Allocator) void {
switch (self.data) {
.points => |*list| list.deinit(allocator),
.points => |slice| allocator.free(slice),
else => {},
}
self.* = undefined;
@@ -40,9 +48,12 @@ pub const Property = struct {
pub fn clone(self: Property, allocator: std.mem.Allocator) !Property {
return switch (self.data) {
.points => |list| .{
.points => |slice| .{
.data = .{
.points = try list.clone(allocator),
.points = blk: {
const copy = try allocator.dupe(Point2_f, slice);
break :blk copy;
},
},
},
else => .{ .data = self.data },

View File

@@ -1,23 +0,0 @@
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

@@ -6,46 +6,15 @@ 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{
/// Свойства фигуры по умолчанию (добавляются к общим). points — слайс на статический массив.
pub const default_shape_properties_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 const default_shape_properties = [_]Property{
.{ .data = .{ .points = &default_shape_properties_points } },
.{ .data = .{ .closed = false } },
.{ .data = .{ .filled = true } },
.{ .data = .{ .fill_rgba = 0x000000FF } },
};
}
/// Добавляет к объекту свойства по умолчанию для ломаной.
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

@@ -1,33 +1,14 @@
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 } } },
.{ .data = .{ .arc_percent = 100.0 } },
.{ .data = .{ .closed = true } },
.{ .data = .{ .filled = false } },
.{ .data = .{ .fill_rgba = 0x000000FF } },
};
/// Теги обязательных свойств.
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,
};
}

View File

@@ -1,37 +1,10 @@
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

@@ -4,22 +4,36 @@ const Property = @import("../Property.zig").Property;
const PropertyData = @import("../Property.zig").Data;
const defaultCommonProperties = Object.defaultCommonProperties;
const basic_models = @import("../basic_models.zig");
const Point2_f = basic_models.Point2_f;
const line = @import("line.zig");
const ellipse = @import("ellipse.zig");
const broken = @import("broken.zig");
const arc = @import("arc.zig");
pub const Rect = basic_models.Rect_f;
pub const Rect = basic_models.Rectf;
/// Добавляет к объекту список свойств фигуры. Для .points дублирует слайс (объект владеет).
fn appendShapeProperties(allocator: std.mem.Allocator, obj: *Object, props: []const Property) !void {
for (props) |prop| {
if (prop.data == .points) {
const pts = prop.data.points;
const copy = try allocator.dupe(Point2_f, pts);
try obj.properties.append(allocator, .{ .data = .{ .points = copy } });
} else {
try obj.properties.append(allocator, prop);
}
}
}
/// Создаёт объект с дефолтными общими и фигурными свойствами.
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),
.line => try appendShapeProperties(allocator, &obj, &line.default_shape_properties),
.ellipse => try appendShapeProperties(allocator, &obj, &ellipse.default_shape_properties),
.broken => {
try appendShapeProperties(allocator, &obj, &broken.default_shape_properties);
try obj.setProperty(allocator, .{ .data = .{ .fill_rgba = obj.getProperty(.stroke_rgba).? } });
},
}
return obj;
}
@@ -35,62 +49,3 @@ fn createWithCommonProperties(allocator: std.mem.Allocator, shape_kind: Object.S
.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);
}

View File

@@ -74,18 +74,20 @@ fn randomizeObjectProperties(allocator: std.mem.Allocator, doc_size: *const Size
} });
},
.broken => {
var points = std.ArrayList(Point2_f).empty;
var list = std.ArrayList(Point2_f).empty;
defer list.deinit(allocator);
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 });
try list.append(allocator, .{ .x = x, .y = y });
x += randFloat(rng, -40, 80);
y += randFloat(rng, -30, 60);
}
try obj.setProperty(allocator, .{ .data = .{ .points = points } });
const slice = try allocator.dupe(Point2_f, list.items);
errdefer allocator.free(slice);
try obj.setProperty(allocator, .{ .data = .{ .points = slice } });
},
.arc => {},
}
}
@@ -98,6 +100,7 @@ pub fn addRandomShapes(doc: *Document, allocator: std.mem.Allocator, rng: std.Ra
for (0..n_root) |_| {
if (total_count >= max_total) break;
var obj = try shape.createObject(allocator, randomShapeKind(rng));
defer obj.deinit(allocator);
try randomizeObjectProperties(allocator, &doc.size, &obj, rng);
try doc.addObject(allocator, obj);
total_count += 1;
@@ -115,6 +118,7 @@ pub fn addRandomShapes(doc: *Document, allocator: std.mem.Allocator, rng: std.Ra
for (0..n_children) |_| {
if (total_count >= max_total) break;
var child = try shape.createObject(allocator, randomShapeKind(rng));
defer child.deinit(allocator);
try randomizeObjectProperties(allocator, &doc.size, &child, rng);
try obj.addChild(allocator, child, &doc.next_object_id);
total_count += 1;

View File

@@ -66,9 +66,7 @@ fn renderGradient(self: CpuRenderEngine, pixels: []Color.PMA, width: u32, height
}
}
fn renderSquares(self: CpuRenderEngine, pixels: []Color.PMA, canvas_size: Size_i, visible_rect: Rect_i) void {
_ = self;
fn renderSquares(pixels: []Color.PMA, canvas_size: Size_i, visible_rect: Rect_i) void {
const colors = [_]Color.PMA{
.{ .r = 255, .g = 0, .b = 0, .a = 255 },
.{ .r = 255, .g = 165, .b = 0, .a = 255 },
@@ -169,10 +167,10 @@ pub fn example(self: CpuRenderEngine, canvas_size: Size_i, visible_rect: Rect_i)
switch (self.type) {
.Gradient => self.renderGradient(pixels, width, height, full_w, full_h, visible_rect),
.Squares => self.renderSquares(pixels, canvas_size, visible_rect),
.Squares => renderSquares(pixels, canvas_size, visible_rect),
}
return try dvui.textureCreate(pixels, width, height, .nearest);
return try dvui.textureCreate(pixels, width, height, .nearest, .abgr_8_8_8_8);
}
pub fn renderEngine(self: *CpuRenderEngine) RenderEngine {
@@ -191,7 +189,7 @@ pub fn renderDocument(self: *CpuRenderEngine, document: *const Document, canvas_
try cpu_draw.drawDocument(pixels, width, height, visible_rect, document, canvas_size, self._allocator);
self._renderStats.render_time_ns = t.read();
return try dvui.textureCreate(pixels, width, height, .nearest);
return try dvui.textureCreate(pixels, width, height, .nearest, .abgr_8_8_8_8);
}
pub fn getStats(self: CpuRenderEngine) RenderStats {

View File

@@ -1,3 +1,3 @@
const RenderStats = @This();
render_time_ns: u64, // Время рендера кадра в микросекундах
render_time_ns: u64, // Время рендера кадра в наносекундах

View File

@@ -1,8 +0,0 @@
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 {}

View File

@@ -7,19 +7,22 @@ const Color = @import("dvui").Color;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_fill: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 0 };
const default_thickness: f32 = 2.0;
/// Ломаная по точкам, обводка stroke_rgba
/// Ломаная по точкам, обводка stroke_rgba. При closed — отрезок последняя–первая точка и заливка fill_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;
const pts = obj.getProperty(.points) orelse return;
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 stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = obj.getProperty(.thickness) orelse default_thickness;
const closed = obj.getProperty(.closed) orelse false;
const filled = obj.getProperty(.filled) orelse true;
const fill_color = if (obj.getProperty(.fill_rgba)) |fill_rgba| pipeline.rgbaToPma(fill_rgba) else default_fill;
const buffer = try allocator.alloc(Color.PMA, ctx.buf_width * ctx.buf_height);
@memset(buffer, .{ .r = 0, .g = 0, .b = 0, .a = 0 });
@@ -29,9 +32,23 @@ pub fn draw(
copy_ctx.pixels = buffer;
copy_ctx.replace_mode = true;
const do_fill = closed and filled;
if (do_fill) {
copy_ctx.startFill(allocator) catch return;
}
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);
line.drawLine(&copy_ctx, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y, stroke, thickness, true);
}
if (closed and pts.len >= 2) {
const last = pts.len - 1;
line.drawLine(&copy_ctx, pts[last].x, pts[last].y, pts[0].x, pts[0].y, stroke, thickness, true);
}
if (do_fill) {
copy_ctx.stopFill(allocator, fill_color);
}
ctx.compositeDrawerContext(&copy_ctx, copy_ctx.transform.opacity);

View File

@@ -4,7 +4,6 @@ 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;
@@ -14,7 +13,7 @@ const DrawContext = pipeline.DrawContext;
const Transform = pipeline.Transform;
fn isVisible(obj: *const Object) bool {
return if (obj.getProperty(.visible)) |p| p.visible else true;
return obj.getProperty(.visible) orelse true;
}
fn drawObject(
@@ -30,9 +29,8 @@ fn drawObject(
switch (obj.shape) {
.line => line.draw(ctx, obj),
.ellipse => ellipse.draw(ctx, obj),
.ellipse => try ellipse.draw(ctx, obj, allocator),
.broken => try broken.draw(ctx, obj, allocator),
.arc => arc.draw(ctx, obj),
}
for (obj.children.items) |*child| {

View File

@@ -1,23 +1,36 @@
const std = @import("std");
const std_math = std.math;
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 basic_models = @import("../../models/basic_models.zig");
const Point2_f = basic_models.Point2_f;
const Object = Document.Object;
const default_stroke: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 255 };
const default_fill: Color.PMA = .{ .r = 0, .g = 0, .b = 0, .a = 0 };
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;
/// Эллипс с центром (0,0) и полуосями radii. Обводка — полоса расстояния до контура (чёткая линия, не круги).
/// arc_percent: 100 — полный эллипс, иначе одна дуга; обход в коде от (0,ry) по квадрантам (визуально может казаться от низа против часовой из‑за экранной Y).
/// Отрисовка в отдельный буфер и один composite, чтобы при alpha<255 пиксели не накладывались несколько раз.
pub fn draw(ctx: *DrawContext, obj: *const Object, allocator: std.mem.Allocator) !void {
const radii = obj.getProperty(.radii) orelse return;
const rx = radii.x;
const ry = 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 stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = if (obj.getProperty(.thickness)) |thickness| thickness else default_thickness;
const arc_percent = std_math.clamp(if (obj.getProperty(.arc_percent)) |arc_percent| arc_percent else 100.0, 0.0, 100.0);
const closed = obj.getProperty(.closed) orelse true;
const filled = obj.getProperty(.filled) orelse false;
const fill_color = if (obj.getProperty(.fill_rgba)) |fill_rgba| pipeline.rgbaToPma(fill_rgba) else default_fill;
const do_fill = filled and (closed or arc_percent >= 100.0);
const t = &ctx.transform;
const min_r = @min(rx, ry);
const half_norm = thickness / (2.0 * min_r);
const inner = @max(0.0, 1.0 - half_norm);
@@ -25,19 +38,18 @@ pub fn draw(ctx: *DrawContext, obj: *const Object) void {
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 margin = 1.0 + half_norm;
const corners = [_]Point2_f{
.{ .x = -rx * margin, .y = -ry * margin },
.{ .x = rx * margin, .y = -ry * margin },
.{ .x = rx * margin, .y = ry * margin },
.{ .x = -rx * margin, .y = ry * margin },
};
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| {
var min_bx: f32 = std_math.inf(f32);
var min_by: f32 = std_math.inf(f32);
var max_bx: f32 = -std_math.inf(f32);
var max_by: f32 = -std_math.inf(f32);
for (corners) |c| {
const w = ctx.localToWorld(c.x, c.y);
const b = ctx.worldToBufferF(w.x, w.y);
min_bx = @min(min_bx, b.x);
@@ -47,50 +59,58 @@ pub fn draw(ctx: *DrawContext, obj: *const Object) void {
}
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);
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);
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 stroke_ctx = ctx.*;
stroke_ctx.pixels = buffer;
stroke_ctx.replace_mode = true;
if (do_fill) {
stroke_ctx.startFill(allocator) catch return;
}
// Один раз считаем аффин 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;
const arc_len = 2.0 * std_math.pi * arc_percent / 100.0;
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 w = stroke_ctx.bufferToWorld(buf_x, buf_y);
const loc = stroke_ctx.worldToLocal(w.x, w.y);
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);
if (d < d_inner_sq or d > d_outer_sq) continue;
if (arc_percent < 100.0) {
var diff = std_math.pi / 2.0 - std_math.atan2(ny, nx);
if (diff < 0) diff += 2.0 * std_math.pi;
if (diff > arc_len) continue;
}
stroke_ctx.blendPixelAtBuffer(bx, by, stroke);
}
}
if (closed and arc_percent < 100.0) {
const end_x = rx * std_math.sin(arc_len);
const end_y = ry * std_math.cos(arc_len);
line.drawLine(&stroke_ctx, 0, 0, 0, ry, stroke, thickness, false);
line.drawLine(&stroke_ctx, 0, 0, end_x, end_y, stroke, thickness, false);
}
if (do_fill) {
stroke_ctx.stopFill(allocator, fill_color);
}
ctx.compositeDrawerContext(&stroke_ctx, t.opacity);
}

View File

@@ -12,16 +12,17 @@ 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);
const end_point = obj.getProperty(.end_point) orelse return;
const end_x = end_point.x;
const end_y = end_point.y;
const stroke = if (obj.getProperty(.stroke_rgba)) |stroke_rgba| pipeline.rgbaToPma(stroke_rgba) else default_stroke;
const thickness = obj.getProperty(.thickness) orelse default_thickness;
drawLine(ctx, 0, 0, end_x, end_y, stroke, thickness, false);
}
/// Рисует отрезок по локальным концам (перевод в буфер внутри).
pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Color.PMA, thickness: f32) void {
/// draw_when_outside: если true, участки линии за экраном тоже рисуются (толщиной 1 px); в буфере — обычная толщина.
pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Color.PMA, thickness: f32, draw_when_outside: bool) void {
const w0 = ctx.localToWorld(x0, y0);
const w1 = ctx.localToWorld(x1, y1);
const b0 = ctx.worldToBuffer(w0.x, w0.y);
@@ -30,7 +31,7 @@ pub fn drawLine(ctx: *DrawContext, x0: f32, y0: f32, x1: f32, y1: f32, color: Co
const scale = @sqrt(t.scale.scale_x * ctx.scale_x * t.scale.scale_y * ctx.scale_y);
const thickness_px: u32 = @as(u32, @intFromFloat(std.math.round(thickness * scale)));
if (thickness_px > 0)
drawLineInBuffer(ctx, b0.x, b0.y, b1.x, b1.y, color, thickness_px);
drawLineInBuffer(ctx, b0.x, b0.y, b1.x, b1.y, color, thickness_px, draw_when_outside);
}
inline fn clip(p: f32, q: f32, t0: *f32, t1: *f32) bool {
@@ -115,7 +116,7 @@ fn clipLineToBuffer(ctx: *DrawContext, a: *Point2_i, b: *Point2_i, thickness: i3
return true;
}
fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, color: Color.PMA, thickness_px: u32) void {
fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, color: Color.PMA, thickness_px: u32, draw_when_outside: bool) void {
// Коррекция толщины в зависимости от угла линии.
var thickness_corrected: u32 = thickness_px;
var use_vertical: bool = undefined;
@@ -137,12 +138,15 @@ fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, c
thickness_corrected = @max(@as(u32, 1), @as(u32, @intFromFloat(std.math.round(corrected_f))));
}
const half_thickness: i32 = @intCast(thickness_corrected / 2);
const thickness_corrected_i: i32 = @as(i32, @intCast(thickness_corrected));
var p0 = Point2_i{ .x = bx0, .y = by0 };
var p1 = Point2_i{ .x = bx1, .y = by1 };
// Отсечение отрезка буфером. Если он целиком вне — рисовать нечего.
// Отсечение только когда не рисуем вне viewport: иначе линия идёт целиком, толщина 1 px снаружи.
if (!draw_when_outside) {
if (!clipLineToBuffer(ctx, &p0, &p1, @as(i32, @intCast(thickness_corrected)))) return;
}
var x0 = p0.x;
var y0 = p0.y;
@@ -156,15 +160,20 @@ fn drawLineInBuffer(ctx: *DrawContext, bx0: i32, by0: i32, bx1: i32, by1: i32, c
const sy: i32 = if (y0 < ey) 1 else -1;
var err: i32 = dx + dy;
const buf_w_i: i32 = @intCast(ctx.buf_width);
const buf_h_i: i32 = @intCast(ctx.buf_height);
while (true) {
var thick: i32 = -half_thickness;
while (thick <= half_thickness) {
// Внутри viewport — полная толщина; снаружи при draw_when_outside — только 1 пиксель.
const in_viewport = x0 >= -thickness_corrected_i and x0 < buf_w_i + thickness_corrected_i and y0 >= -thickness_corrected_i and y0 < buf_h_i + thickness_corrected_i;
const effective_half: i32 = if (draw_when_outside and !in_viewport) 0 else half_thickness;
var thick: i32 = -effective_half;
while (thick <= effective_half) {
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);
}
ctx.blendPixelAtBuffer(x, y, color);
thick += 1;
}

View File

@@ -16,10 +16,10 @@ pub const Transform = struct {
opacity: f32 = 1.0,
pub fn init(obj: *const Document.Object) Transform {
const pos = if (obj.getProperty(.position)) |p| p.position else 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 Scale2_f{ .scale_x = 1, .scale_y = 1 };
const opacity = if (obj.getProperty(.opacity)) |p| p.opacity else 1.0;
const pos = obj.getProperty(.position) orelse Point2_f{ .x = 0, .y = 0 };
const angle = obj.getProperty(.angle) orelse 0;
const scale = obj.getProperty(.scale) orelse Scale2_f{ .scale_x = 1, .scale_y = 1 };
const opacity = obj.getProperty(.opacity) orelse 1.0;
return .{
.position = pos,
.angle = angle,
@@ -75,6 +75,7 @@ pub const DrawContext = struct {
transform: Transform = .{},
/// Если true, blendPixelAtBuffer перезаписывает пиксель без бленда
replace_mode: bool = false,
_fill_canvas: ?*FillCanvas = null,
pub fn setTransform(self: *DrawContext, t: Transform) void {
self.transform = t;
@@ -132,8 +133,13 @@ pub const DrawContext = struct {
}
/// Смешивает цвет в пикселе буфера с учётом 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;
/// Если активен fill canvas, каждый записанный пиксель помечается как граница для заливки.
pub fn blendPixelAtBuffer(self: *DrawContext, bx_i32: i32, by_i32: i32, color: Color.PMA) void {
if (self._fill_canvas) |fc| fc.setBorder(bx_i32, by_i32);
if (bx_i32 < 0 or by_i32 < 0 or bx_i32 >= self.buf_width or by_i32 >= self.buf_height) return;
const bx: u32 = @intCast(bx_i32);
const by: u32 = @intCast(by_i32);
const idx = by * self.buf_width + bx;
const dst = &self.pixels[idx];
if (self.replace_mode) {
@@ -181,7 +187,24 @@ pub const DrawContext = struct {
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);
self.blendPixelAtBuffer(bx, by, color);
}
/// Начинает сбор границ для заливки: создаёт FillCanvas и при последующих вызовах blendPixelAtBuffer помечает пиксели как границу.
pub fn startFill(self: *DrawContext, allocator: std.mem.Allocator) !void {
const fc = try FillCanvas.init(allocator, self.buf_width, self.buf_height);
const ptr = try allocator.create(FillCanvas);
ptr.* = fc;
self._fill_canvas = ptr;
}
/// Рисует заливку по собранным границам цветом color, освобождает FillCanvas и сбрасывает режим.
pub fn stopFill(self: *DrawContext, allocator: std.mem.Allocator, color: Color.PMA) void {
const fc = self._fill_canvas orelse return;
self._fill_canvas = null;
fc.fillColor(self, allocator, color);
fc.deinit();
allocator.destroy(fc);
}
};
@@ -200,3 +223,127 @@ pub fn rgbaToPma(rgba: u32) Color.PMA {
.a = a,
};
}
/// Контекст для заполнения фигур цветом. Границы хранятся в set — по x и y можно добавлять произвольные точки.
const FillCanvas = struct {
/// Множество пикселей границы (x, y) — без ограничения по размеру буфера.
border_set: std.AutoHashMap(Point2_i, void),
buf_width: u32,
buf_height: u32,
pub fn init(allocator: std.mem.Allocator, width: u32, height: u32) !FillCanvas {
const border_set = std.AutoHashMap(Point2_i, void).init(allocator);
return .{
.border_set = border_set,
.buf_width = width,
.buf_height = height,
};
}
pub fn deinit(self: *FillCanvas) void {
self.border_set.deinit();
}
/// Добавляет точку границы; координаты x, y могут быть любыми (условно бесконечное поле).
pub fn setBorder(self: *FillCanvas, x: i32, y: i32) void {
self.border_set.put(.{ .x = x, .y = y }, {}) catch {};
}
/// Заливка четырёхсвязным стековым алгоритмом от первой найденной внутренней точки.
pub fn fillColor(self: *FillCanvas, draw_ctx: *DrawContext, allocator: std.mem.Allocator, color: Color.PMA) void {
const n = self.border_set.count();
if (n == 0) return;
const buf_w_i: i32 = @intCast(self.buf_width);
const buf_h_i: i32 = @intCast(self.buf_height);
// Ключи один раз по (y, x) — по строкам x уже будут отсортированы.
var keys_buf = std.ArrayList(Point2_i).empty;
defer keys_buf.deinit(allocator);
keys_buf.ensureTotalCapacity(allocator, n) catch return;
var iter = self.border_set.keyIterator();
while (iter.next()) |k| {
keys_buf.appendAssumeCapacity(k.*);
}
std.mem.sort(Point2_i, keys_buf.items, {}, struct {
fn lessThan(_: void, a: Point2_i, b: Point2_i) bool {
if (a.y != b.y) return a.y < b.y;
return a.x < b.x;
}
}.lessThan);
// Семена: по строкам находим сегменты (пары x), пересекаем с окном буфера, берём середину сегмента.
var seeds = findFillSeeds(keys_buf.items, buf_w_i, buf_h_i, allocator) catch return;
defer seeds.deinit(allocator);
var stack = std.ArrayList(Point2_i).empty;
defer stack.deinit(allocator);
var filled = std.AutoHashMap(Point2_i, void).init(allocator);
defer filled.deinit();
for (seeds.items) |s| {
if (self.border_set.contains(s)) continue;
if (filled.contains(s)) continue;
stack.clearRetainingCapacity();
stack.append(allocator, s) catch return;
while (stack.pop()) |cell| {
if (self.border_set.contains(cell)) continue;
const gop = filled.getOrPut(cell) catch return;
if (gop.found_existing) continue;
if (cell.x >= 0 and cell.x < buf_w_i and cell.y >= 0 and cell.y < buf_h_i) {
draw_ctx.blendPixelAtBuffer(cell.x, cell.y, color);
}
if (cell.x > 0) stack.append(allocator, .{ .x = cell.x - 1, .y = cell.y }) catch return;
if (cell.x < buf_w_i - 1) stack.append(allocator, .{ .x = cell.x + 1, .y = cell.y }) catch return;
if (cell.y > 0) stack.append(allocator, .{ .x = cell.x, .y = cell.y - 1 }) catch return;
if (cell.y < buf_h_i - 1) stack.append(allocator, .{ .x = cell.x, .y = cell.y + 1 }) catch return;
}
}
}
/// По строкам: рёбра (подряд идущие x) → сегменты между ними. Семена — середины чётных сегментов (при чётном числе границ).
fn findFillSeeds(
keys: []const Point2_i,
buf_w_i: i32,
buf_h_i: i32,
allocator: std.mem.Allocator,
) !std.ArrayList(Point2_i) {
var list = std.ArrayList(Point2_i).empty;
errdefer list.deinit(allocator);
var segments = std.ArrayList(struct { left: i32, right: i32 }).empty;
defer segments.deinit(allocator);
var i: usize = 0;
while (i < keys.len) {
const y = keys[i].y;
const row_start = i;
while (i < keys.len and keys[i].y == y) : (i += 1) {}
const row = keys[row_start..i];
if (row.len < 2 or y < 0 or y >= buf_h_i) continue;
segments.clearRetainingCapacity();
var run_end_x: i32 = row[0].x;
for (row[1..]) |p| {
if (p.x != run_end_x + 1) {
try segments.append(allocator, .{ .left = run_end_x + 1, .right = p.x - 1 });
run_end_x = p.x;
} else {
run_end_x = p.x;
}
}
// Семена только при чётном числе границ
if ((segments.items.len + 1) % 2 != 0) continue;
for (segments.items, 0..) |seg, gi| {
if (gi % 2 != 0 or seg.left > seg.right) continue;
const left = @max(seg.left, 0);
const right = @min(seg.right, buf_w_i - 1);
if (left <= right) {
try list.append(allocator, .{ .x = left + @divTrunc(right - left, 2), .y = y });
}
}
}
return list;
}
};

View File

@@ -1,7 +1,6 @@
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");
@@ -16,11 +15,6 @@ pub const default_tools = [_]Toolbar.ToolDescriptor{
.icon_tvg = icons.ellipse,
.implementation = &ellipse.tool,
},
.{
.name = "Arc",
.icon_tvg = icons.arc,
.implementation = &arc.tool,
},
.{
.name = "Broken line",
.icon_tvg = icons.broken,

View File

@@ -1,10 +0,0 @@
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.allocator, .arc) catch return;
defer obj.deinit(canvas.allocator);
try ctx.addObject(obj);
}
pub const tool = Tool.Tool{ .onCanvasClick = onCanvasClick };

View File

@@ -6,6 +6,7 @@ const Document = @import("../models/Document.zig");
const Property = @import("../models/Property.zig").Property;
const PropertyData = @import("../models/Property.zig").Data;
const Rect_i = @import("../models/basic_models.zig").Rect_i;
const Point2_f = @import("../models/basic_models.zig").Point2_f;
const Tool = @import("../toolbar/Tool.zig");
const RenderStats = @import("../render/RenderStats.zig");
const icons = @import("../icons.zig");
@@ -16,14 +17,15 @@ pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale:
var overlay = dvui.overlay(@src(), .{ .expand = .both });
{
const overlay_parent = dvui.parentGet();
var scroll = dvui.scrollArea(
@src(),
.{
const init_options: dvui.ScrollAreaWidget.InitOpts = .{
.scroll_info = &canvas.scroll,
.vertical_bar = .auto,
.horizontal_bar = .auto,
.process_events_after = false,
},
};
var scroll = dvui.scrollArea(
@src(),
init_options,
.{
.expand = .both,
.background = false,
@@ -99,7 +101,7 @@ pub fn canvasView(canvas: *Canvas, selected_object_id: ?u64, content_rect_scale:
}
}
if (!scroll.init_opts.process_events_after) {
if (!init_options.process_events_after) {
if (scroll.scroll) |*sc| {
dvui.clipSet(sc.prevClip);
sc.processEventsAfter();
@@ -379,19 +381,29 @@ fn drawStatsPanel(stats: RenderStats, frame_index: u64) void {
panel.deinit();
}
fn applyPropertyPatch(canvas: *Canvas, obj: *Document.Object, patch: Property) void {
obj.setProperty(canvas.allocator, patch) catch {};
canvas.requestRedraw();
}
fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Property, row_index: usize) void {
const row_id: usize = row_index * 16;
const is_even = row_index % 2 == 0;
var row = dvui.box(
@src(),
.{ .dir = .vertical },
.{
.id_extra = row_id,
.expand = .horizontal,
.padding = dvui.Rect{ .y = 2 },
.padding = dvui.Rect{ .y = 2, .x = 4 },
.corner_radius = dvui.Rect.all(4),
.background = is_even,
.color_fill = if (is_even) dvui.Color.black.opacity(0.4) else .{},
},
);
{
const tag = std.meta.activeTag(prop.data);
dvui.labelNoFmt(@src(), propertyLabel(tag), .{}, .{});
switch (prop.data) {
@@ -415,8 +427,7 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .position = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .position = next } });
}
},
.angle => |angle| {
@@ -429,8 +440,7 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
subrow.deinit();
if (res.changed) {
next = degrees * std.math.pi / 180.0;
obj.setProperty(canvas.allocator, .{ .data = .{ .angle = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .angle = next } });
}
}
},
@@ -454,29 +464,25 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .scale = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .scale = next } });
}
},
.visible => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Visible", .{})) {
obj.setProperty(canvas.allocator, .{ .data = .{ .visible = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .visible = next } });
}
},
.opacity => |opacity| {
var next = opacity;
if (dvui.sliderEntry(@src(), "{d:0.2}", .{ .value = &next, .min = 0.0, .max = 1.0, .interval = 0.01 }, .{ .expand = .horizontal })) {
obj.setProperty(canvas.allocator, .{ .data = .{ .opacity = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .opacity = next } });
}
},
.locked => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Locked", .{})) {
obj.setProperty(canvas.allocator, .{ .data = .{ .locked = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .locked = next } });
}
},
.size => |size| {
@@ -499,8 +505,7 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .size = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .size = next } });
}
},
.radii => |radii| {
@@ -523,8 +528,13 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .radii = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .radii = next } });
}
},
.arc_percent => |pct| {
var next = pct;
if (dvui.sliderEntry(@src(), "{d:0.0}%", .{ .value = &next, .min = 0.0, .max = 100.0, .interval = 1.0 }, .{ .expand = .horizontal })) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .arc_percent = next } });
}
},
.end_point => |pt| {
@@ -547,15 +557,16 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
changed = res.changed or changed;
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .end_point = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .end_point = next } });
}
},
.points => |points| {
var list = points.clone(canvas.allocator) catch {
dvui.label(@src(), "Points: {d}", .{points.items.len}, .{});
var list = std.ArrayList(Point2_f).empty;
list.appendSlice(canvas.allocator, points) catch {
dvui.label(@src(), "Points: {d}", .{points.len}, .{});
return;
};
defer list.deinit(canvas.allocator);
dvui.label(@src(), "Points: {d}", .{list.items.len}, .{});
var changed = false;
@@ -665,13 +676,12 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
}
if (changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .points = list } }) catch {
list.deinit(canvas.allocator);
const slice = canvas.allocator.dupe(Point2_f, list.items) catch return;
obj.setProperty(canvas.allocator, .{ .data = .{ .points = slice } }) catch {
canvas.allocator.free(slice);
return;
};
canvas.requestRedraw();
} else {
list.deinit(canvas.allocator);
}
},
.fill_rgba => |rgba| {
@@ -689,11 +699,22 @@ fn drawPropertyEditor(canvas: *Canvas, obj: *Document.Object, prop: *const Prope
const res = dvui.textEntryNumber(@src(), T, .{ .value = &next, .min = @as(T, 0.0), .max = @as(T, 100.0) }, .{ .expand = .horizontal });
subrow.deinit();
if (res.changed) {
obj.setProperty(canvas.allocator, .{ .data = .{ .thickness = next } }) catch {};
canvas.requestRedraw();
applyPropertyPatch(canvas, obj, .{ .data = .{ .thickness = next } });
}
}
},
.closed => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Closed", .{})) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .closed = next } });
}
},
.filled => |v| {
var next = v;
if (dvui.checkbox(@src(), &next, "Filled", .{})) {
applyPropertyPatch(canvas, obj, .{ .data = .{ .filled = next } });
}
},
}
}
row.deinit();
@@ -707,12 +728,11 @@ fn drawColorEditor(canvas: *Canvas, obj: *Document.Object, rgba: u32, is_fill: b
.{ .expand = .horizontal },
)) {
const next = colorToRgba(hsv.toColor());
if (is_fill) {
obj.setProperty(canvas.allocator, .{ .data = .{ .fill_rgba = next } }) catch {};
} else {
obj.setProperty(canvas.allocator, .{ .data = .{ .stroke_rgba = next } }) catch {};
}
canvas.requestRedraw();
const patch: Property = if (is_fill)
.{ .data = .{ .fill_rgba = next } }
else
.{ .data = .{ .stroke_rgba = next } };
applyPropertyPatch(canvas, obj, patch);
}
}
@@ -726,11 +746,14 @@ fn propertyLabel(tag: std.meta.Tag(PropertyData)) []const u8 {
.locked => "Locked",
.size => "Size",
.radii => "Radii",
.arc_percent => "Arc %",
.end_point => "End point",
.points => "Points",
.fill_rgba => "Fill color",
.stroke_rgba => "Stroke color",
.thickness => "Thickness",
.closed => "Closed",
.filled => "Filled",
};
}

View File

@@ -19,7 +19,6 @@ fn shapeLabel(shape: Object.ShapeKind) []const u8 {
return switch (shape) {
.line => "Line",
.ellipse => "Ellipse",
.arc => "Arc",
.broken => "Broken line",
};
}
@@ -223,11 +222,13 @@ pub fn leftPanel(ctx: *WindowContext) void {
},
);
{
dvui.label(@src(), "Objects", .{}, .{ .font = .{
.id = dvui.themeGet().font_heading.id,
dvui.label(@src(), "Objects", .{}, .{
.font = .{
.line_height_factor = dvui.themeGet().font_heading.line_height_factor,
.size = dvui.themeGet().font_heading.size + 8,
}, .gravity_x = 0.5 });
},
.gravity_x = 0.5,
});
var scroll = dvui.scrollArea(
@src(),
.{ .vertical = .auto, .horizontal = .auto },