use nannou::prelude::*;
struct Model {
squares: Vec<Square>,
}
struct Square {
position: Point2,
size: f32,
rotation: f32,
border_width: f32,
holes: Vec<Hole>,
}
struct Hole {
position: f32, // Позиция отверстия на границе (0.0 - 1.0)
size: f32, // Размер отверстия
}
fn main() {
nannou::sketch(view)
.event(event)
.run();
}
fn model(app: &App) -> Model {
let mut squares = Vec::new();
// Создаем несколько квадратов с разными параметрами
squares.push(Square {
position: pt2(0.0, 0.0),
size: 200.0,
rotation: 0.0,
border_width: 20.0,
holes: vec![
Hole { position: 0.2, size: 15.0 },
Hole { position: 0.5, size: 25.0 },
Hole { position: 0.8, size: 10.0 },
],
});
squares.push(Square {
position: pt2(-250.0, 150.0),
size: 150.0,
rotation: 0.0,
border_width: 15.0,
holes: vec![
Hole { position: 0.25, size: 10.0 },
Hole { position: 0.75, size: 10.0 },
],
});
squares.push(Square {
position: pt2(250.0, 150.0),
size: 150.0,
rotation: 0.0,
border_width: 30.0,
holes: vec![
Hole { position: 0.0, size: 20.0 },
Hole { position: 0.33, size: 20.0 },
Hole { position: 0.67, size: 20.0 },
],
});
Model { squares }
}
fn event(_app: &App, model: &mut Model, event: Event) {
match event {
Event::MousePressed(MouseButton::Left) => {
let mouse_pos = _app.mouse.position();
for square in &mut model.squares {
let distance = square.position.distance(mouse_pos);
if distance < square.size / 2.0 {
square.rotation += PI / 4.0; // Поворот на 45 градусов
}
}
}
_ => (),
}
}
fn view(app: &App, model: &Model, frame: Frame) {
let draw = app.draw();
draw.background().color(DARKGRAY);
for square in &model.squares {
draw_square(&draw, square);
}
draw.to_frame(app, &frame).unwrap();
}
fn draw_square(draw: &Draw, square: &Square) {
let half_size = square.size / 2.0;
let inner_size = square.size - 2.0 * square.border_width;
// Рисуем внешний квадрат
draw.rect()
.xy(square.position)
.w_h(square.size, square.size)
.color(STEELBLUE)
.rotate(square.rotation);
// Рисуем внутренний квадрат (отверстие в центре)
draw.rect()
.xy(square.position)
.w_h(inner_size, inner_size)
.color(DARKGRAY)
.rotate(square.rotation);
// Рисуем отверстия в границе
for hole in &square.holes {
// Вычисляем позицию отверстия на границе
let perimeter_position = hole.position * 4.0; // 0.0 - 4.0 (полный периметр)
let mut hole_pos = square.position;
let offset = half_size - square.border_width / 2.0;
if perimeter_position < 1.0 {
// Верхняя сторона
hole_pos.x += map_range(perimeter_position, 0.0, 1.0, -offset, offset);
hole_pos.y += offset;
} else if perimeter_position < 2.0 {
// Правая сторона
hole_pos.x += offset;
hole_pos.y += map_range(perimeter_position, 1.0, 2.0, offset, -offset);
} else if perimeter_position < 3.0 {
// Нижняя сторона
hole_pos.x += map_range(perimeter_position, 2.0, 3.0, offset, -offset);
hole_pos.y -= offset;
} else {
// Левая сторона
hole_pos.x -= offset;
hole_pos.y += map_range(perimeter_position, 3.0, 4.0, -offset, offset);
}
// Поворачиваем позицию отверстия вокруг центра квадрата
let rotated_pos = rotate_point(hole_pos - square.position, square.rotation) + square.position;
// Рисуем отверстие
draw.ellipse()
.xy(rotated_pos)
.radius(hole.size)
.color(DARKGRAY);
}
}
// Вспомогательная функция для поворота точки
fn rotate_point(point: Point2, angle: f32) -> Point2 {
let cos_a = angle.cos();
let sin_a = angle.sin();
pt2(
point.x * cos_a - point.y * sin_a,
point.x * sin_a + point.y * cos_a
)
}
use ggez::{Context, ContextBuilder, GameResult};
use ggez::graphics::{self, Color, DrawMode, DrawParam, Mesh, MeshBuilder};
use ggez::event::{self, EventHandler, MouseButton};
use ggez::input::mouse;
use ggez::mint::{Point2, Vector2};
use std::f32::consts::PI;
struct Square {
position: Point2<f32>,
size: f32,
rotation: f32,
border_width: f32,
holes: Vec<Hole>,
}
struct Hole {
position: f32, // Позиция отверстия на границе (0.0 - 1.0)
size: f32, // Размер отверстия
}
struct MainState {
squares: Vec<Square>,
}
impl MainState {
fn new(ctx: &mut Context) -> GameResult<MainState> {
let mut squares = Vec::new();
// Создаем несколько квадратов с разными параметрами
squares.push(Square {
position: Point2 { x: 400.0, y: 300.0 },
size: 200.0,
rotation: 0.0,
border_width: 20.0,
holes: vec![
Hole { position: 0.2, size: 15.0 },
Hole { position: 0.5, size: 25.0 },
Hole { position: 0.8, size: 10.0 },
],
});
squares.push(Square {
position: Point2 { x: 200.0, y: 150.0 },
size: 150.0,
rotation: 0.0,
border_width: 15.0,
holes: vec![
Hole { position: 0.25, size: 10.0 },
Hole { position: 0.75, size: 10.0 },
],
});
squares.push(Square {
position: Point2 { x: 600.0, y: 150.0 },
size: 150.0,
rotation: 0.0,
border_width: 30.0,
holes: vec![
Hole { position: 0.0, size: 20.0 },
Hole { position: 0.33, size: 20.0 },
Hole { position: 0.67, size: 20.0 },
],
});
Ok(MainState { squares })
}
fn draw_square(&self, ctx: &mut Context, square: &Square) -> GameResult {
let half_size = square.size / 2.0;
let inner_size = square.size - 2.0 * square.border_width;
let half_inner_size = inner_size / 2.0;
// Рисуем внешний квадрат
let outer_rect = MeshBuilder::new()
.rectangle(
DrawMode::fill(),
graphics::Rect::new(-half_size, -half_size, square.size, square.size),
Color::from_rgb(70, 130, 180), // STEELBLUE
)?
.build(ctx)?;
// Рисуем внутренний квадрат (отверстие в центре)
let inner_rect = MeshBuilder::new()
.rectangle(
DrawMode::fill(),
graphics::Rect::new(-half_inner_size, -half_inner_size, inner_size, inner_size),
Color::from_rgb(50, 50, 50), // DARKGRAY
)?
.build(ctx)?;
// Рисуем квадрат с отверстием в центре
graphics::draw(
ctx,
&outer_rect,
DrawParam::default()
.dest(square.position)
.rotation(square.rotation),
)?;
graphics::draw(
ctx,
&inner_rect,
DrawParam::default()
.dest(square.position)
.rotation(square.rotation),
)?;
// Рисуем отверстия в границе
for hole in &square.holes {
// Вычисляем позицию отверстия на границе
let perimeter_position = hole.position * 4.0; // 0.0 - 4.0 (полный периметр)
let mut hole_pos = square.position;
let offset = half_size - square.border_width / 2.0;
if perimeter_position < 1.0 {
// Верхняя сторона
hole_pos.x += map_range(perimeter_position, 0.0, 1.0, -offset, offset);
hole_pos.y -= offset;
} else if perimeter_position < 2.0 {
// Правая сторона
hole_pos.x += offset;
hole_pos.y += map_range(perimeter_position, 1.0, 2.0, -offset, offset);
} else if perimeter_position < 3.0 {
// Нижняя сторона
hole_pos.x += map_range(perimeter_position, 2.0, 3.0, offset, -offset);
hole_pos.y += offset;
} else {
// Левая сторона
hole_pos.x -= offset;
hole_pos.y += map_range(perimeter_position, 3.0, 4.0, offset, -offset);
}
// Поворачиваем позицию отверстия вокруг центра квадрата
let rotated_pos = rotate_point(
Point2 {
x: hole_pos.x - square.position.x,
y: hole_pos.y - square.position.y
},
square.rotation
);
let hole_pos_rotated = Point2 {
x: rotated_pos.x + square.position.x,
y: rotated_pos.y + square.position.y
};
// Рисуем отверстие
let hole_mesh = MeshBuilder::new()
.circle(
DrawMode::fill(),
Point2 { x: 0.0, y: 0.0 },
hole.size,
0.1,
Color::from_rgb(50, 50, 50), // DARKGRAY
)?
.build(ctx)?;
graphics::draw(
ctx,
&hole_mesh,
DrawParam::default().dest(hole_pos_rotated),
)?;
}
Ok(())
}
}
impl EventHandler for MainState {
fn update(&mut self, _ctx: &mut Context) -> GameResult {
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, Color::from_rgb(50, 50, 50)); // DARKGRAY
for square in &self.squares {
self.draw_square(ctx, square)?;
}
graphics::present(ctx)?;
Ok(())
}
fn mouse_button_down_event(
&mut self,
ctx: &mut Context,
button: MouseButton,
x: f32,
y: f32,
) {
if button == MouseButton::Left {
let mouse_pos = Point2 { x, y };
for square in &mut self.squares {
let dx = square.position.x - mouse_pos.x;
let dy = square.position.y - mouse_pos.y;
let distance = (dx * dx + dy * dy).sqrt();
if distance < square.size / 2.0 {
square.rotation += PI / 4.0; // Поворот на 45 градусов
}
}
}
}
}
// Вспомогательная функция для поворота точки
fn rotate_point(point: Point2<f32>, angle: f32) -> Point2<f32> {
let cos_a = angle.cos();
let sin_a = angle.sin();
Point2 {
x: point.x * cos_a - point.y * sin_a,
y: point.x * sin_a + point.y * cos_a
}
}
// Вспомогательная функция для линейной интерполяции
fn map_range(value: f32, from_start: f32, from_end: f32, to_start: f32, to_end: f32) -> f32 {
to_start + (value - from_start) * (to_end - to_start) / (from_end - from_start)
}
fn main() -> GameResult {
let (mut ctx, event_loop) = ContextBuilder::new("squares", "author")
.window_setup(ggez::conf::WindowSetup::default().title("Вращающиеся квадраты с отверстиями"))
.window_mode(ggez::conf::WindowMode::default().dimensions(800.0, 600.0))
.build()?;
let state = MainState::new(&mut ctx)?;
event::run(ctx, event_loop, state)
}