#! Contains `rot`, a rotation in the plane, and `pose`, where a body is and #! which way it's turned, which places its shapes. import std::math; import std::serial; import linear; module physics2d; #! A rotation in the plane, counterclockwise, as its angle's cosine and sine, #! so turning a vector takes no trigonometry. @serial pub struct rot { @serial pub var c: f32 = 1; @serial pub var s: f32; } #! No rotation. pub val rot::identity := rot{ 1, 0 }; #! A rotation by an angle, in radians, counterclockwise. pub def rot::of(angle: f32): rot { return rot{ math::cos(angle), math::sin(angle) }; } #! Its angle, in radians, from -π to π. pub val rot::angle: f32 { get => math::atan2(this.s, this.c); } pub def rot::equals(&this, other: &rot): bool { return this.c == other.c && this.s == other.s; } #! A vector turned by it. pub def rot::apply(&this, v: vec2): vec2 { return vec2{ this.c * v.x - this.s * v.y, this.s * v.x + this.c * v.y }; } #! A vector turned back by it, as its inverse turns it. pub def rot::unapply(&this, v: vec2): vec2 { return vec2{ this.c * v.x + this.s * v.y, this.c * v.y - this.s * v.x }; } #! It after another: turning by the product turns by `other`, then by this. pub def rot::mul(&this, other: &rot): rot { return rot{ this.c * other.c - this.s * other.s, this.s * other.c + this.c * other.s }; } #! Where a body is in the plane, and which way it's turned: what a place of its #! own, as its shapes' corners are, is in the plane. @serial pub struct pose { @serial pub var at: vec2; @serial pub var turn := rot::identity; } #! At the origin, unturned. pub val pose::identity := pose{}; #! A pose at a place, turned by an angle, in radians, counterclockwise. pub def pose::of(at: vec2, angle: f32 = 0): pose { return pose{ at = at, turn = rot::of(angle) }; } pub def pose::equals(&this, other: &pose): bool { return this.at == other.at && this.turn == other.turn; } #! Where a place of the body's own is in the plane. pub def pose::apply(&this, local: vec2): vec2 { return this.at + this.turn.apply(local); } #! Where a place of the plane is in the body's own. pub def pose::unapply(&this, place: vec2): vec2 { return this.turn.unapply(place - this.at); } #! It after another: the pose of what's placed by `other` within what this #! places. pub def pose::mul(&this, other: &pose): pose { return pose{ at = this.apply(other.at), turn = this.turn * other.turn }; } #! Another pose of the plane, as one within what this places, of its own #! places: what `this * found` is `other` of. pub def pose::unapply_pose(&this, other: pose): pose { val c := this.turn.c * other.turn.c + this.turn.s * other.turn.s; val s := this.turn.c * other.turn.s - this.turn.s * other.turn.c; return pose{ at = this.unapply(other.at), turn = rot{ c, s } }; }