Skip to content

Commit

Permalink
Added snapshot-interpolation (dev)
Browse files Browse the repository at this point in the history
  • Loading branch information
yandeu committed Dec 14, 2021
1 parent 7608457 commit 354266e
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions src/examples/standalone/snapshot-interpolation.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Snapshot Interpolation</title>
<link rel="stylesheet" href="/css/examples.css?ver=1.0.0" />
<script src="/js/examples.js?ver=1.1.1"></script>
<script src="/lib/enable3d/enable3d.framework.0.24.0.min.js"></script>
<script src="https://unpkg.com/@geckos.io/snapshot-interpolation/bundle/snapshot-interpolation.js"></script>
</head>

<body>
<div id="info-text">The red cube is interpolated with a delay of 100ms and @ 10FPS.</div>
<script>
const { Project, Scene3D, PhysicsLoader, THREE } = ENABLE3D
const { SnapshotInterpolation, Vault } = Snap

const FPS = 10
const SI = new SnapshotInterpolation(FPS)

class MainScene extends Scene3D {
tick = 0
ghost
cube
async create() {
this.warpSpeed('-ground')

this.ghost = this.make.box({ x: -1, y: 1 }, { lambert: { color: 'gray' } })
this.cube = this.add.box({ x: 1, y: 1 }, { lambert: { color: 'red' } })

this.add.existing(this.ghost)
}

// create a snapshot on the server @ 60FPS
serverSide(time) {
this.ghost.rotation.x += 0.01
this.ghost.rotation.y += 0.01
this.ghost.position.x = Math.sin(time) - 1
this.ghost.position.y = Math.cos(time)

const quaternion = new THREE.Quaternion().setFromEuler(this.ghost.rotation)
const pos = this.ghost.position

const { _x: x, _y: y, _z: z, _z: w } = quaternion

const state = [{ id: 'cube', x: pos.x, y: pos.y, quat: { x, y, z, w } }]

const snapshot = SI.snapshot.create(state)

return snapshot
}

// later (over the wire) receives a new snapshot @10FPS
clientSide(snap) {
if (snap) SI.addSnapshot(snap)

const snapshot = SI.calcInterpolation('x quat(quat)')
if (!snapshot) return

const { state } = snapshot

const { id, quat: q, x, y } = state[0]

if (id === 'cube') {
this.cube.position.x = x + 2 // a bit more to the right
this.cube.position.y = y
this.cube.quaternion.set(q.x, q.y, q.z, q.w)
}
}

update(time) {
this.tick++

const snapshot = this.serverSide(time)

// send only at every 6th frame (10 FPS)
setTimeout(() => {
if ((this.tick % 60) / FPS !== 0) this.clientSide(snapshot)
else this.clientSide()
}, 100)
}
}

new Project({ scenes: [MainScene] })
</script>
</body>
</html>

0 comments on commit 354266e

Please sign in to comment.