Skip to content

Commit

Permalink
2D Fixed Timestep Interpolation
Browse files Browse the repository at this point in the history
Adds support to canvas items and Camera2D.
  • Loading branch information
lawnjelly committed Apr 19, 2023
1 parent 18cdf36 commit 14bc7fe
Show file tree
Hide file tree
Showing 23 changed files with 349 additions and 59 deletions.
45 changes: 45 additions & 0 deletions core/math/transform_interpolator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,51 @@

#include "transform_interpolator.h"

#include "core/math/transform_2d.h"

void TransformInterpolator::interpolate_transform2D(const Transform2D &p_prev, const Transform2D &p_curr, Transform2D &r_result, real_t p_fraction) {
//extract parameters
Vector2 p1 = p_prev.get_origin();
Vector2 p2 = p_curr.get_origin();

// Special case for physics interpolation, if flipping, don't interpolate basis.
// If the determinant polarity changes, the handedness of the coordinate system changes.
if (_sign(p_prev.basis_determinant()) != _sign(p_curr.basis_determinant())) {
r_result.elements[0] = p_curr.elements[0];
r_result.elements[1] = p_curr.elements[1];
r_result.set_origin(Vector2::linear_interpolate(p1, p2, p_fraction));
return;
}

real_t r1 = p_prev.get_rotation();
real_t r2 = p_curr.get_rotation();

Size2 s1 = p_prev.get_scale();
Size2 s2 = p_curr.get_scale();

//slerp rotation
Vector2 v1(Math::cos(r1), Math::sin(r1));
Vector2 v2(Math::cos(r2), Math::sin(r2));

real_t dot = v1.dot(v2);

dot = CLAMP(dot, -1, 1);

Vector2 v;

if (dot > 0.9995f) {
v = Vector2::linear_interpolate(v1, v2, p_fraction).normalized(); //linearly interpolate to avoid numerical precision issues
} else {
real_t angle = p_fraction * Math::acos(dot);
Vector2 v3 = (v2 - v1 * dot).normalized();
v = v1 * Math::cos(angle) + v3 * Math::sin(angle);
}

//construct matrix
r_result = Transform2D(Math::atan2(v.y, v.x), Vector2::linear_interpolate(p1, p2, p_fraction));
r_result.scale_basis(Vector2::linear_interpolate(s1, s2, p_fraction));
}

void TransformInterpolator::interpolate_transform(const Transform &p_prev, const Transform &p_curr, Transform &r_result, real_t p_fraction) {
r_result.origin = p_prev.origin + ((p_curr.origin - p_prev.origin) * p_fraction);
interpolate_basis(p_prev.basis, p_curr.basis, r_result.basis, p_fraction);
Expand Down
4 changes: 3 additions & 1 deletion core/math/transform_interpolator.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
// several frames may occur between each physics tick, which will make it cheaper
// than performing every frame.

class Transform;
struct Transform2D;

class TransformInterpolator {
public:
Expand All @@ -66,6 +66,7 @@ class TransformInterpolator {
static Quat _basis_to_quat_unchecked(const Basis &p_basis);
static bool _basis_is_orthogonal(const Basis &p_basis, real_t p_epsilon = 0.01f);
static bool _basis_is_orthogonal_any_scale(const Basis &p_basis);
static bool _sign(real_t p_val) { return p_val >= 0; }

static void interpolate_basis_linear(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction);
static void interpolate_basis_scaled_slerp(Basis p_prev, Basis p_curr, Basis &r_result, real_t p_fraction);
Expand All @@ -75,6 +76,7 @@ class TransformInterpolator {
// These will be slower.
static void interpolate_transform(const Transform &p_prev, const Transform &p_curr, Transform &r_result, real_t p_fraction);
static void interpolate_basis(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction);
static void interpolate_transform2D(const Transform2D &p_prev, const Transform2D &p_curr, Transform2D &r_result, real_t p_fraction);

// Optimized function when you know ahead of time the method
static void interpolate_transform_via_method(const Transform &p_prev, const Transform &p_curr, Transform &r_result, real_t p_fraction, Method p_method);
Expand Down
1 change: 1 addition & 0 deletions core/os/main_loop.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class MainLoop : public Object {
virtual void input_text(const String &p_text);

virtual void init();
virtual void iteration_prepare() {}
virtual bool iteration(float p_time);
virtual void iteration_end() {}
virtual bool idle(float p_time);
Expand Down
1 change: 1 addition & 0 deletions doc/classes/Control.xml
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,7 @@
<member name="mouse_filter" type="int" setter="set_mouse_filter" getter="get_mouse_filter" enum="Control.MouseFilter" default="0">
Controls whether the control will be able to receive mouse button input events through [method _gui_input] and how these events should be handled. Also controls whether the control can receive the [signal mouse_entered], and [signal mouse_exited] signals. See the constants to learn what each does.
</member>
<member name="physics_interpolation_mode" type="int" setter="set_physics_interpolation_mode" getter="get_physics_interpolation_mode" overrides="Node" enum="Node.PhysicsInterpolationMode" default="1" />
<member name="rect_clip_content" type="bool" setter="set_clip_contents" getter="is_clipping_contents" default="false">
Enables whether rendering of [CanvasItem] based children should be clipped to this control's rectangle. If [code]true[/code], parts of a child which would be visibly outside of this control's rectangle will not be rendered.
</member>
Expand Down
26 changes: 26 additions & 0 deletions doc/classes/VisualServer.xml
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,14 @@
Once finished with your RID, you will want to free the RID using the VisualServer's [method free_rid] static method.
</description>
</method>
<method name="canvas_item_reset_physics_interpolation">
<return type="void" />
<argument index="0" name="item" type="RID" />
<description>
Prevents physics interpolation for the current physics tick.
This is useful when moving a canvas item to a new location, to give an instantaneous change rather than interpolation from the previous location.
</description>
</method>
<method name="canvas_item_set_clip">
<return type="void" />
<argument index="0" name="item" type="RID" />
Expand Down Expand Up @@ -375,6 +383,14 @@
Sets the index for the [CanvasItem].
</description>
</method>
<method name="canvas_item_set_interpolated">
<return type="void" />
<argument index="0" name="item" type="RID" />
<argument index="1" name="interpolated" type="bool" />
<description>
Turns on and off physics interpolation for the canvas item.
</description>
</method>
<method name="canvas_item_set_light_mask">
<return type="void" />
<argument index="0" name="item" type="RID" />
Expand Down Expand Up @@ -463,6 +479,16 @@
Sets the [CanvasItem]'s Z index, i.e. its draw order (lower indexes are drawn first).
</description>
</method>
<method name="canvas_item_transform_physics_interpolation">
<return type="void" />
<argument index="0" name="item" type="RID" />
<argument index="1" name="xform" type="Transform2D" />
<description>
Transforms both the current and previous stored transform for a canvas item.
This allows transforming a canvas item without creating a "glitch" in the interpolation.
This is particularly useful for large worlds utilising a shifting origin.
</description>
</method>
<method name="canvas_light_attach_to_canvas">
<return type="void" />
<argument index="0" name="light" type="RID" />
Expand Down
6 changes: 6 additions & 0 deletions main/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2298,6 +2298,12 @@ bool Main::iteration() {

PhysicsServer::get_singleton()->flush_queries();

// Prepare the fixed timestep interpolated nodes
// BEFORE they are updated by the physics 2D,
// otherwise the current and previous transforms
// may be the same, and no interpolation takes place.
OS::get_singleton()->get_main_loop()->iteration_prepare();

Physics2DServer::get_singleton()->sync();
Physics2DServer::get_singleton()->flush_queries();

Expand Down
56 changes: 41 additions & 15 deletions scene/2d/camera_2d.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,12 @@ void Camera2D::_update_scroll() {
if (current) {
ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));

Transform2D xform = get_camera_transform();

Transform2D xform;
if (is_physics_interpolated_and_enabled()) {
xform = _interpolation_data.xform_prev.interpolate_with(_interpolation_data.xform_curr, Engine::get_singleton()->get_physics_interpolation_fraction());
} else {
xform = get_camera_transform();
}
viewport->set_canvas_transform(xform);

Size2 screen_size = viewport->get_visible_rect().size;
Expand All @@ -67,13 +71,18 @@ void Camera2D::_update_scroll() {
}

void Camera2D::_update_process_mode() {
// smoothing can be enabled in the editor but will never be active
if (process_mode == CAMERA2D_PROCESS_IDLE) {
set_process_internal(smoothing_active);
set_physics_process_internal(false);
if (is_physics_interpolated_and_enabled()) {
set_process_internal(is_current());
set_physics_process_internal(is_current());
} else {
set_process_internal(false);
set_physics_process_internal(smoothing_active);
// smoothing can be enabled in the editor but will never be active
if (process_mode == CAMERA2D_PROCESS_IDLE) {
set_process_internal(smoothing_active);
set_physics_process_internal(false);
} else {
set_process_internal(false);
set_physics_process_internal(smoothing_active);
}
}
}

Expand Down Expand Up @@ -236,13 +245,22 @@ Transform2D Camera2D::get_camera_transform() {

void Camera2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_INTERNAL_PROCESS:
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
case NOTIFICATION_INTERNAL_PROCESS: {
_update_scroll();

} break;
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (is_physics_interpolated_and_enabled()) {
_interpolation_data.xform_prev = _interpolation_data.xform_curr;
_interpolation_data.xform_curr = get_camera_transform();
} else {
_update_scroll();
}
} break;
case NOTIFICATION_RESET_PHYSICS_INTERPOLATION: {
_interpolation_data.xform_prev = _interpolation_data.xform_curr;
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!smoothing_active) {
if (!smoothing_active && !is_physics_interpolated_and_enabled()) {
_update_scroll();
}

Expand Down Expand Up @@ -400,10 +418,15 @@ Camera2D::Camera2DProcessMode Camera2D::get_process_mode() const {
}

void Camera2D::_make_current(Object *p_which) {
bool new_current = false;

if (p_which == this) {
current = true;
} else {
current = false;
new_current = true;
}

if (new_current != current) {
current = new_current;
_update_process_mode();
}
}

Expand All @@ -413,6 +436,7 @@ void Camera2D::_set_current(bool p_current) {
}

current = p_current;
_update_process_mode();
update();
}

Expand All @@ -427,13 +451,15 @@ void Camera2D::make_current() {
get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", this);
}
_update_scroll();
_update_process_mode();
}

void Camera2D::clear_current() {
current = false;
if (is_inside_tree()) {
get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", (Object *)nullptr);
}
_update_process_mode();
}

void Camera2D::set_limit(Margin p_margin, int p_limit) {
Expand Down
5 changes: 5 additions & 0 deletions scene/2d/camera_2d.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ class Camera2D : public Node2D {

Camera2DProcessMode process_mode;

struct InterpolationData {
Transform2D xform_curr;
Transform2D xform_prev;
} _interpolation_data;

protected:
virtual Transform2D get_camera_transform();
void _notification(int p_what);
Expand Down
10 changes: 10 additions & 0 deletions scene/2d/canvas_item.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,10 @@ void CanvasItem::_exit_canvas() {
}
}

void CanvasItem::_physics_interpolated_changed() {
VisualServer::get_singleton()->canvas_item_set_interpolated(canvas_item, is_physics_interpolated());
}

void CanvasItem::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
Expand Down Expand Up @@ -605,6 +609,12 @@ void CanvasItem::_notification(int p_what) {
}
global_invalid = true;
} break;
case NOTIFICATION_RESET_PHYSICS_INTERPOLATION: {
if (is_visible_in_tree() && is_physics_interpolated()) {
VisualServer::get_singleton()->canvas_item_reset_physics_interpolation(canvas_item);
}
} break;

case NOTIFICATION_DRAW:
case NOTIFICATION_TRANSFORM_CHANGED: {
} break;
Expand Down
1 change: 1 addition & 0 deletions scene/2d/canvas_item.h
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ class CanvasItem : public Node {
}

void item_rect_changed(bool p_size_changed = true);
virtual void _physics_interpolated_changed();

void _notification(int p_what);
static void _bind_methods();
Expand Down
11 changes: 0 additions & 11 deletions scene/3d/visual_instance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,6 @@ void VisualInstance::_notification(int p_what) {
if (_is_vi_visible() && is_physics_interpolated()) {
VisualServer::get_singleton()->instance_reset_physics_interpolation(instance);
}
#if defined(DEBUG_ENABLED) && defined(TOOLS_ENABLED)
else if (GLOBAL_GET("debug/settings/physics_interpolation/enable_warnings")) {
String node_name = is_inside_tree() ? String(get_path()) : String(get_name());
if (!_is_vi_visible()) {
WARN_PRINT("[Physics interpolation] NOTIFICATION_RESET_PHYSICS_INTERPOLATION only works with unhidden nodes: \"" + node_name + "\".");
}
if (!is_physics_interpolated()) {
WARN_PRINT("[Physics interpolation] NOTIFICATION_RESET_PHYSICS_INTERPOLATION only works with interpolated nodes: \"" + node_name + "\".");
}
}
#endif
} break;
case NOTIFICATION_EXIT_WORLD: {
VisualServer::get_singleton()->instance_set_scenario(instance, RID());
Expand Down
2 changes: 2 additions & 0 deletions scene/gui/control.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3003,6 +3003,8 @@ Control::Control() {
}
data.focus_mode = FOCUS_NONE;
data.modal_prev_focus_owner = 0;

set_physics_interpolation_mode(Node::PHYSICS_INTERPOLATION_MODE_OFF);
}

Control::~Control() {
Expand Down
10 changes: 6 additions & 4 deletions scene/main/scene_tree.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,12 @@ void SceneTree::client_physics_interpolation_remove_spatial(SelfList<Spatial> *p
_client_physics_interpolation._spatials_list.remove(p_elem);
}

void SceneTree::iteration_prepare() {
if (_physics_interpolation_enabled) {
VisualServer::get_singleton()->tick();
}
}

void SceneTree::iteration_end() {
// When physics interpolation is active, we want all pending transforms
// to be flushed to the VisualServer before finishing a physics tick.
Expand All @@ -566,10 +572,6 @@ bool SceneTree::iteration(float p_time) {

current_frame++;

if (_physics_interpolation_enabled) {
VisualServer::get_singleton()->tick();
}

// Any objects performing client physics interpolation
// should be given an opportunity to keep their previous transforms
// up to take before each new physics tick.
Expand Down
1 change: 1 addition & 0 deletions scene/main/scene_tree.h
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ class SceneTree : public MainLoop {
virtual void input_event(const Ref<InputEvent> &p_event);
virtual void init();

virtual void iteration_prepare();
virtual bool iteration(float p_time);
virtual void iteration_end();
virtual bool idle(float p_time);
Expand Down

0 comments on commit 14bc7fe

Please sign in to comment.