Skip to content

Commit 730bd78

Browse files
lilizoeyhapenia
authored andcommitted
Impl Display for built-ins
1 parent 0ea7a23 commit 730bd78

21 files changed

+842
-42
lines changed

examples/dodge-the-creeps/rust/src/player.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl Area2DVirtual for Player {
5353

5454
fn ready(&mut self) {
5555
let viewport = self.base.get_viewport_rect();
56-
self.screen_size = viewport.size();
56+
self.screen_size = viewport.size;
5757
self.base.hide();
5858
}
5959

godot-codegen/src/api_parser.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub struct BuiltinClass {
4343
pub indexing_return_type: Option<String>,
4444
pub is_keyed: bool,
4545
pub members: Option<Vec<Member>>,
46-
pub constants: Option<Vec<Constant>>,
46+
// pub constants: Option<Vec<BuiltinConstant>>,
4747
pub enums: Option<Vec<BuiltinClassEnum>>, // no bitfield
4848
pub operators: Vec<Operator>,
4949
pub methods: Option<Vec<BuiltinClassMethod>>,
@@ -58,7 +58,7 @@ pub struct Class {
5858
pub is_instantiable: bool,
5959
pub inherits: Option<String>,
6060
// pub api_type: String,
61-
// pub constants: Option<Vec<Constant>>,
61+
pub constants: Option<Vec<ClassConstant>>,
6262
pub enums: Option<Vec<Enum>>,
6363
pub methods: Option<Vec<ClassMethod>>,
6464
// pub properties: Option<Vec<Property>>,
@@ -102,13 +102,18 @@ pub struct EnumConstant {
102102
pub value: i32,
103103
}
104104

105+
pub type ClassConstant = EnumConstant;
106+
107+
/*
108+
// Constants of builtin types have a string value like "Vector2(1, 1)", hence also a type field
105109
#[derive(DeJson)]
106-
pub struct Constant {
110+
pub struct BuiltinConstant {
107111
pub name: String,
108112
#[nserde(rename = "type")]
109113
pub type_: String,
110114
pub value: String,
111115
}
116+
*/
112117

113118
#[derive(DeJson)]
114119
pub struct Operator {

godot-codegen/src/class_generator.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ fn make_class(class: &Class, class_name: &TyName, ctx: &mut Context) -> Generate
173173
let constructor = make_constructor(class, ctx);
174174
let methods = make_methods(&class.methods, class_name, ctx);
175175
let enums = make_enums(&class.enums, class_name, ctx);
176+
let constants = make_constants(&class.constants, class_name, ctx);
176177
let inherits_macro = format_ident!("inherits_transitive_{}", class_name.rust_ty);
177178
let all_bases = ctx.inheritance_tree().collect_all_bases(class_name);
178179
let virtual_trait = make_virtual_methods_trait(class, &all_bases, &virtual_trait_str, ctx);
@@ -205,6 +206,7 @@ fn make_class(class: &Class, class_name: &TyName, ctx: &mut Context) -> Generate
205206
impl #class_name {
206207
#constructor
207208
#methods
209+
#constants
208210
}
209211
impl crate::obj::GodotClass for #class_name {
210212
type Base = #base;
@@ -420,9 +422,8 @@ fn make_builtin_methods(
420422
}
421423

422424
fn make_enums(enums: &Option<Vec<Enum>>, _class_name: &TyName, _ctx: &Context) -> TokenStream {
423-
let enums = match enums {
424-
Some(e) => e,
425-
None => return TokenStream::new(),
425+
let Some(enums) = enums else {
426+
return TokenStream::new();
426427
};
427428

428429
let definitions = enums.iter().map(util::make_enum_definition);
@@ -432,6 +433,22 @@ fn make_enums(enums: &Option<Vec<Enum>>, _class_name: &TyName, _ctx: &Context) -
432433
}
433434
}
434435

436+
fn make_constants(
437+
constants: &Option<Vec<ClassConstant>>,
438+
_class_name: &TyName,
439+
_ctx: &Context,
440+
) -> TokenStream {
441+
let Some(constants) = constants else {
442+
return TokenStream::new();
443+
};
444+
445+
let definitions = constants.iter().map(util::make_constant_definition);
446+
447+
quote! {
448+
#( #definitions )*
449+
}
450+
}
451+
435452
/// Depending on the built-in class, adds custom constructors and methods.
436453
fn make_special_builtin_methods(class_name: &TyName, _ctx: &Context) -> TokenStream {
437454
if class_name.godot_ty == "Array" {

godot-codegen/src/util.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
55
*/
66

7-
use crate::api_parser::Enum;
7+
use crate::api_parser::{ClassConstant, Enum};
88
use crate::special_cases::is_builtin_scalar;
99
use crate::{Context, ModName, RustTy, TyName};
1010
use proc_macro2::{Ident, Literal, TokenStream};
@@ -106,6 +106,15 @@ pub fn make_enum_definition(enum_: &Enum) -> TokenStream {
106106
}
107107
}
108108

109+
pub fn make_constant_definition(constant: &ClassConstant) -> TokenStream {
110+
let ClassConstant { name, value } = constant;
111+
let name = ident(name);
112+
113+
quote! {
114+
pub const #name: i32 = #value;
115+
}
116+
}
117+
109118
fn make_enum_name(enum_name: &str) -> Ident {
110119
// TODO clean up enum name
111120

godot-core/src/builtin/aabb.rs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
5+
*/
6+
7+
use godot_ffi as sys;
8+
use sys::{ffi_methods, GodotFfi};
9+
10+
use super::Vector3;
11+
12+
/// Axis-aligned bounding box in 3D space.
13+
///
14+
/// `Aabb` consists of a position, a size, and several utility functions. It is typically used for
15+
/// fast overlap tests.
16+
///
17+
/// Currently most methods are only available through [`InnerAabb`](super::inner::InnerAabb).
18+
///
19+
/// The 2D counterpart to `Aabb` is [`Rect2`](super::Rect2).
20+
#[derive(Default, Copy, Clone, PartialEq, Debug)]
21+
#[repr(C)]
22+
pub struct Aabb {
23+
pub position: Vector3,
24+
pub size: Vector3,
25+
}
26+
27+
impl Aabb {
28+
/// Create a new `Aabb` from a position and a size.
29+
///
30+
/// _Godot equivalent: `Aabb(Vector3 position, Vector3 size)`_
31+
#[inline]
32+
pub const fn new(position: Vector3, size: Vector3) -> Self {
33+
Self { position, size }
34+
}
35+
36+
/// Create a new `Aabb` with the first corner at `position` and opposite corner at `end`.
37+
#[inline]
38+
pub fn from_corners(position: Vector3, end: Vector3) -> Self {
39+
Self {
40+
position,
41+
size: position + end,
42+
}
43+
}
44+
45+
/// The end of the `Aabb` calculated as `position + size`.
46+
///
47+
/// _Godot equivalent: `Aabb.size` property_
48+
#[inline]
49+
pub fn end(&self) -> Vector3 {
50+
self.position + self.size
51+
}
52+
53+
/// Set size based on desired end-point.
54+
///
55+
/// _Godot equivalent: `Aabb.size` property_
56+
#[inline]
57+
pub fn set_end(&mut self, end: Vector3) {
58+
self.size = end - self.position
59+
}
60+
61+
/// Returns `true` if the two `Aabb`s are approximately equal, by calling `is_equal_approx` on
62+
/// `position` and `size`.
63+
///
64+
/// _Godot equivalent: `Aabb.is_equal_approx()`_
65+
#[inline]
66+
pub fn is_equal_approx(&self, other: &Self) -> bool {
67+
self.position.is_equal_approx(other.position) && self.size.is_equal_approx(other.size)
68+
}
69+
70+
/* Add in when `Aabb::abs()` is implemented.
71+
/// Assert that the size of the `Aabb` is not negative.
72+
///
73+
/// Certain functions will fail to give a correct result if the size is negative.
74+
#[inline]
75+
pub fn assert_nonnegative(&self) {
76+
assert!(
77+
self.size.x >= 0.0 && self.size.y >= 0.0 && self.size.z >= 0.0,
78+
"size {:?} is negative",
79+
self.size
80+
);
81+
}
82+
*/
83+
}
84+
85+
impl std::fmt::Display for Aabb {
86+
/// Formats `Aabb` to match godot's display style.
87+
///
88+
/// # Example
89+
///
90+
/// ```
91+
/// use godot::prelude::*;
92+
/// let aabb = Aabb::new(Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 1.0, 1.0));
93+
/// assert_eq!(format!("{}", aabb), "[P: (0, 0, 0), S: (1, 1, 1)]");
94+
/// ```
95+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96+
write!(f, "[P: {}, S: {}]", self.position, self.size)
97+
}
98+
}
99+
100+
impl GodotFfi for Aabb {
101+
ffi_methods! { type sys::GDExtensionTypePtr = *mut Self; .. }
102+
}

godot-core/src/builtin/color.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,3 +495,18 @@ fn to_be_words(mut u: u64) -> [u16; 4] {
495495
let x = (u & 0xffff) as u16;
496496
[x, y, z, w]
497497
}
498+
499+
impl std::fmt::Display for Color {
500+
/// Formats `Color` to match godot's display style.
501+
///
502+
/// # Example
503+
///
504+
/// ```
505+
/// use godot::prelude::*;
506+
/// let color = Color::from_rgba(1.0,1.0,1.0,1.0);
507+
/// assert_eq!(format!("{}", color), "(1, 1, 1, 1)");
508+
/// ```
509+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510+
write!(f, "({}, {}, {}, {})", self.r, self.g, self.b, self.a)
511+
}
512+
}

godot-core/src/builtin/mod.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
// Re-export macros.
3636
pub use crate::{array, dict, varray};
3737

38+
pub use aabb::*;
3839
pub use array_inner::{Array, VariantArray};
3940
pub use basis::*;
4041
pub use color::*;
@@ -43,8 +44,11 @@ pub use math::*;
4344
pub use node_path::*;
4445
pub use others::*;
4546
pub use packed_array::*;
47+
pub use plane::*;
4648
pub use projection::*;
4749
pub use quaternion::*;
50+
pub use rect2::*;
51+
pub use rect2i::*;
4852
pub use rid::*;
4953
pub use string::*;
5054
pub use string_name::*;
@@ -84,15 +88,19 @@ mod array_inner;
8488
#[path = "dictionary.rs"]
8589
mod dictionary_inner;
8690

91+
mod aabb;
8792
mod basis;
8893
mod color;
8994
mod glam_helpers;
9095
mod math;
9196
mod node_path;
9297
mod others;
9398
mod packed_array;
99+
mod plane;
94100
mod projection;
95101
mod quaternion;
102+
mod rect2;
103+
mod rect2i;
96104
mod rid;
97105
mod string;
98106
mod string_chars;
@@ -319,6 +327,17 @@ macro_rules! real {
319327
}};
320328
}
321329

330+
/// The side of a [`Rect2`] or [`Rect2i`].
331+
///
332+
/// _Godot equivalent: `@GlobalScope.Side`_
333+
#[repr(C)]
334+
pub enum RectSide {
335+
Left = 0,
336+
Top = 1,
337+
Right = 2,
338+
Bottom = 3,
339+
}
340+
322341
// ----------------------------------------------------------------------------------------------------------------------------------------------
323342

324343
/// Implementations of the `Export` trait for types where it can be done trivially.
@@ -352,7 +371,7 @@ mod export {
352371
impl_export_by_clone!(f32);
353372
impl_export_by_clone!(f64);
354373

355-
// impl_export_by_clone!(Aabb); // TODO uncomment once Aabb implements Clone
374+
impl_export_by_clone!(Aabb);
356375
impl_export_by_clone!(Basis);
357376
impl_export_by_clone!(Color);
358377
impl_export_by_clone!(GodotString);
@@ -366,11 +385,11 @@ mod export {
366385
impl_export_by_clone!(PackedStringArray);
367386
impl_export_by_clone!(PackedVector2Array);
368387
impl_export_by_clone!(PackedVector3Array);
369-
// impl_export_by_clone!(Plane); // TODO uncomment once Plane implements Clone
388+
impl_export_by_clone!(Plane);
370389
impl_export_by_clone!(Projection);
371390
impl_export_by_clone!(Quaternion);
372-
// impl_export_by_clone!(Rect2); // TODO uncomment once Rect2 implements Clone
373-
// impl_export_by_clone!(Rect2i); // TODO uncomment once Rect2i implements Clone
391+
impl_export_by_clone!(Rect2);
392+
impl_export_by_clone!(Rect2i);
374393
impl_export_by_clone!(Rid);
375394
impl_export_by_clone!(StringName);
376395
impl_export_by_clone!(Transform2D);

godot-core/src/builtin/others.rs

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,36 +6,16 @@
66

77
// Stub for various other built-in classes, which are currently incomplete, but whose types
88
// are required for codegen
9-
use crate::builtin::{inner, StringName, Vector2};
9+
use crate::builtin::{inner, StringName};
1010
use crate::obj::{Gd, GodotClass};
1111
use godot_ffi as sys;
1212
use sys::{ffi_methods, GodotFfi};
1313

1414
// TODO: Swap more inner math types with glam types
1515
// Note: ordered by enum ord in extension JSON
16-
impl_builtin_stub!(Rect2, OpaqueRect2);
17-
impl_builtin_stub!(Rect2i, OpaqueRect2i);
18-
impl_builtin_stub!(Plane, OpaquePlane);
19-
impl_builtin_stub!(Aabb, OpaqueAabb);
2016
impl_builtin_stub!(Callable, OpaqueCallable);
2117
impl_builtin_stub!(Signal, OpaqueSignal);
2218

23-
#[repr(C)]
24-
struct InnerRect {
25-
position: Vector2,
26-
size: Vector2,
27-
}
28-
29-
impl Rect2 {
30-
pub fn size(self) -> Vector2 {
31-
self.inner().size
32-
}
33-
34-
fn inner(self) -> InnerRect {
35-
unsafe { std::mem::transmute(self) }
36-
}
37-
}
38-
3919
impl Callable {
4020
pub fn from_object_method<T, S>(object: Gd<T>, method: S) -> Self
4121
where

0 commit comments

Comments
 (0)