Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jank-free rendering & shared tickers (WIP) #10

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions demos/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<h1>Demos</h1>
<ul>
<li><a href="./1-chat-heads/index.html">Chat Heads</a></li>
<li><a href="./squares/index.html">Squares</a></li>
</ul>
</body>
</html>
15 changes: 15 additions & 0 deletions demos/squares/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<html>
<head>
<title>Squares</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style>
* {
margin: 0;
}
</style>
</head>
<body>
<div id="app"></div>
<script src="./index.tsx"></script>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why you're using .tsx here. You aren't using TypeScript or JSX, and even if you were, they'd need to be converted to JavaScript before being included in a page.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dev system transpiles it to a js when running yarn dev. I just copied from the other demo.

</body>
</html>
79 changes: 79 additions & 0 deletions demos/squares/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { Spring } from "../../dist/module"


const COUNT = 50
const squares = []

const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')

canvas.style.width = canvas.style.height = '100%'
document.body.appendChild(canvas)
resizeCanvasToDisplaySize(canvas)


class Square {
constructor(i) {
this.i = i
this.x = Math.random() * canvas.width
this.y = Math.random() * canvas.height
this.color = '#'+Math.random().toString(16).substr(2,6)
this.springs = {
x: new Spring({fromValue: this.x, raf: false}), // x
y: new Spring({fromValue: this.y, raf: false}) // y
}
this.springs.x.onUpdate(s => this.x = s.currentValue)
this.springs.y.onUpdate(s => this.y = s.currentValue)
}
setPosition(x, y) {
this.springs.x.setValue(x);
this.springs.y.setValue(y);
}
tick(now) {
this.springs.x._advanceSpringToTime(now, true)
this.springs.y._advanceSpringToTime(now, true)
//this.springs.x._step()
//this.springs.x._step()
}
}

function resizeCanvasToDisplaySize(canvas) {
let w = (canvas.clientWidth*devicePixelRatio) | 0
let h = (canvas.clientHeight*devicePixelRatio) | 0
if (canvas.width != w || canvas.height != h) {
canvas.width = w
canvas.height = h
}
}

function draw() {
const now = Date.now()
resizeCanvasToDisplaySize(canvas)
const width = canvas.width
const height = canvas.height
ctx.clearRect(0, 0, width, height)
for(var i = 0; i < squares.length; i++) {
const square = squares[i]
square.tick(now)
ctx.fillStyle = square.color
ctx.fillRect(square.x, square.y, 50, 50)
}
requestAnimationFrame(draw)
}

setInterval(() => {
randomize()
}, 100)

function randomize() {
squares[Math.floor(squares.length*Math.random())]
.setPosition(Math.random() * canvas.width, Math.random() * canvas.height)
}

for(var i = 0; i < COUNT; i++) {
squares.push(new Square(i))
}

draw()

window.randomize = randomize
51 changes: 33 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface SpringConfig {
overshootClamping: boolean; // False when overshooting is allowed, true when it is not. Defaults to false.
restVelocityThreshold: number; // When spring's velocity is below `restVelocityThreshold`, it is at rest. Defaults to .001.
restDisplacementThreshold: number; // When the spring's displacement (current value) is below `restDisplacementThreshold`, it is at rest. Defaults to .001.
raf: boolean;
[index: string]: any;
}

export type PartialSpringConfig = Partial<SpringConfig>;
Expand Down Expand Up @@ -61,6 +63,7 @@ export class Spring {
initialVelocity: withDefault(config.initialVelocity, 0),
overshootClamping: withDefault(config.overshootClamping, false),
allowsOverdamping: withDefault(config.allowsOverdamping, false),
raf: withDefault(config.raf, true),
restVelocityThreshold: withDefault(config.restVelocityThreshold, 0.001),
restDisplacementThreshold: withDefault(
config.restDisplacementThreshold,
Expand All @@ -84,9 +87,11 @@ export class Spring {

if (!this._currentAnimationStep) {
this._notifyListeners("onStart");
this._currentAnimationStep = requestAnimationFrame((t: number) => {
this._step(Date.now());
});
if (this._config.raf) {
this._currentAnimationStep = requestAnimationFrame((t: number) => {
this._step();
});
}
}
}

Expand Down Expand Up @@ -156,24 +161,34 @@ export class Spring {
// being changed in `updatedConfig`, we run the simulation with `_step()`
// and default `fromValue` and `initialVelocity` to their current values.

this._advanceSpringToTime(Date.now());
this._advanceSpringToTime();

const baseConfig = {
fromValue: this._currentValue,
initialVelocity: this._currentVelocity
};
this._config.fromValue = this._currentValue;
this._config.initialVelocity = this._currentVelocity;

this._config = {
...this._config,
...baseConfig,
...updatedConfig
};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why you felt the need to change this. Was there a problem, or do you just prefer the iterative style?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#9

for (const key in updatedConfig) {
if (this._config.hasOwnProperty(key)) {
this._config[key] = updatedConfig[key as keyof SpringConfig];
}
}

this._reset();

return this;
}

/**
*
*/
setValue(value: number): this {
this._config.fromValue = this._currentValue;
this._config.toValue = value;
this._config.initialVelocity = this._currentVelocity;
this.start();
this._advanceSpringToTime(undefined, true);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I definitely don't like this (undefined, true). Perhaps it'd be best to move the raf loop into start/stop and the spring logic in step?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this just sugar over .updateConfig({ toValue: })?

Copy link
Author

@JonDum JonDum Sep 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. To avoid the object literal and extra steps updating the config when you only need to update the value (which is going to be most use cases) instead of the whole config.

return this;
}

/**
* The provided callback will be invoked when the simulation begins.
*/
Expand Down Expand Up @@ -246,20 +261,20 @@ export class Spring {
* current state once per frame, and schedules the next frame if the spring is
* not yet at rest.
*/
private _step(timestamp: number) {
this._advanceSpringToTime(timestamp, true);
private _step() {
this._advanceSpringToTime(undefined, true);

// check `_isAnimating`, in case `stop()` got called during
// `_advanceSpringToTime()`
if (this._isAnimating) {
if (this._config.raf && this._isAnimating) {
this._currentAnimationStep = requestAnimationFrame((t: number) =>
this._step(Date.now())
this._step()
);
}
}

private _advanceSpringToTime(
timestamp: number,
timestamp: number = Date.now(),
shouldNotifyListeners: boolean = false
) {
// `_advanceSpringToTime` updates `_currentTime` and triggers the listeners.
Expand Down