forked from mitxela/webrtc-pong
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pong.htm
608 lines (516 loc) · 17.4 KB
/
pong.htm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<!doctype html>
<meta charset="utf-8">
<meta name=viewport content="width=device-width, initial-scale=1.0">
<title>WebRTC Pong - mitxela.com</title>
<style>
canvas{max-width:100%;max-height:98vh}
body{text-align:center;color:#e8e8e8;background:#131313}
pre{text-align:left}
a{color:#e8e8e8}
a:hover{color:red}
@keyframes flicker{
0% {opacity:0}
59%{opacity:0}
60%{opacity:1}
79%{opacity:1}
80%{opacity:0}
99%{opacity:0}
100%{opacity:1}
}
h1 span{animation: flicker 0.5s linear both;}
@keyframes fade{
0% {opacity:0}
100%{opacity:1}
}
#box1 p{animation: fade 2s linear 2s both;}
</style>
<div id=box1>
<h1><span>W</span><span>e</span><span>b</span><span>R</span><span>T</span><span>C</span> <span>P</span><span>o</span><span>n</span><span>g</span></h1>
<p><button id="createBtn">Create Game</button>
<p><button id="joinBtn1">Join Game</button>
<p><a href=/projects/webrtc-pong>about</a> • <a href=https://github.com/mitxela/webrtc-pong>source code</a>
</div>
<form id=box2 style='display:none;padding:20px;'>
Enter ID: <input id="conid" size=8>
<button id="joinBtn2">Join</button>
</form>
<div id=box3 style='display:none'>
<h2>ID: </h2>
Buffer Size: <select id=bufsize>
<option value=Auto>Auto</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
<option value=6>6</option>
<option value=7>7</option>
<option value=8>8</option>
<option value=9>9</option>
<option value=10>10</option>
</select><p>
Difficulty: <span id=bspl></span><br><input id=ballspeed type=range min=2 max=20 value=8 oninput='bspl.textContent=this.value+" [ "+ ["boring","normal","crazy"][Math.floor(this.value/7)]+" ]"'>
</div>
<pre id=debuglog></pre>
<div id=box4 style='display:none'>
<canvas id=game style="outline:1px solid;" width=800 height=600></canvas>
<br><label><input type=checkbox id=showstats oninput="showstats=this.checked;statsbox.style.display=showstats?'block':'none'"> Show stats</label>
<div id=statsbox style="position:relative">
<pre id=stats style="display:inline-block;width:200px"></pre><br>
<canvas id=ggrid style="position:absolute;" width=800 height=600></canvas>
<canvas id=graph width=800 height=600></canvas>
</div>
</div>
<script src=DC.js></script>
<script>
document.querySelectorAll('h1 span').forEach(a=>a.style.animationDelay=2*Math.random()+'s')
canvas=document.getElementById("game")
ctx=canvas.getContext("2d")
ctx.imageSmoothingEnabled=false;
ctx.shadowColor='#e8e8e8'
ctx.shadowBlur=8;
w=canvas.width;h=canvas.height
viewport = document.querySelector('meta[name="viewport"]');
graph=document.getElementById("graph").getContext("2d")
ggrid=document.getElementById("ggrid").getContext("2d")
showstats=document.getElementById("showstats").checked;
statsbox.style.display=showstats?'block':'none';
ballspeed.oninput()
host=false;
connected=false;
bufferSize = 3;
frameNumber = -bufferSize;
driftThreshold = 1 //ms
driftTrimFactor = 0.1 //
stacksize=5 // averaging period for ping/lead times
frameLength = 1000/60 //1000/FPS target
nextFrame=0
lastAnimationFrame=0;
synctick=0;
version=1 // increment whenever the game logic changes
myInputs=[]
yoInputs=[]
rollbackState={}
rollbackInputs=[]
yoInputLastDir=0;
scaleFactor=1
paddleH=60
paddleW=20
ballSize=20
edgeGuard=paddleH/2+ballSize/2
left ={y:h/2,x:20}
right={y:h/2,x:w-20}
grabY = 0; //mouse input
scoreLeft=0
scoreRight=0
ballStartSpeed=4;
ball={x:0,y:-20,speed:0,hspeed:0,vspeed:0}
function objcopy(o){
let copy = {}
for (var a in o) {
if (o.hasOwnProperty(a)) copy[a] = o[a];
}
return copy
}
function storeRollbackState(){
rollbackState = {frame:myInputs[0].frame, seed, scoreLeft, scoreRight, ball:objcopy(ball), leftY:left.y, rightY:right.y}
}
function loadRollbackState(){
left.y=rollbackState.leftY
right.y=rollbackState.rightY
seed=rollbackState.seed
scoreLeft=rollbackState.scoreLeft
scoreRight=rollbackState.scoreRight
ball=objcopy(rollbackState.ball)
}
// Animation frame FPS could be different at each end, so don't rely on it for any timing.
draw=function(t){
ctx.clearRect( 0,0,w,h)
if (frameNumber<88) {
for (let i=0;i<frameNumber/8;i++) ctx.fillRect( w/2-5,13+i*27, 10,10),ctx.fillRect( w/2-5,580-i*27, 10,10)
} else {
ctx.fillRect( left.x - paddleW/2, left.y - paddleH/2, paddleW, paddleH)
ctx.fillRect( right.x - paddleW/2, right.y - paddleH/2, paddleW, paddleH)
ctx.fillRect( ball.x-ballSize/2,ball.y-ballSize/2, ballSize, ballSize )
for (let i=13;i<h;i+=27) ctx.fillRect( w/2-5,i, 10,10)
drawScore(w/2-45,scoreLeft,1)
drawScore(w/2+55,scoreRight)
}
if (showstats) doStats(t)
if (connected) requestAnimationFrame(draw)
lastAnimationFrame=t
}
ctx.fillStyle='#e8e8e8'
var font=new Image();
font.src="data:image/gif;base64,R0lGODlhHgAFAIAB"+btoa("\0\xe8\xe8\xe8\xff\xff")+"/yH5BAEAAAEALAAAAAAeAAUAAAIdhANom+x/WphJWTRp23h7WIEdloUaGWnpozItVQAAOw==";
function drawScore(x,score,alignRight){
let t=score.toString(), offset=alignRight?t.length*40:0;
for (var c in t) {
ctx.drawImage(font, (t[c].charCodeAt(0)-0x30)*3, 0, 3,5,x+c*40-offset,20,30,50)
}
}
seed= Math.floor(Math.random()*0xFFFFFFFF);
function rng() {
var t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function resetBall(){
// choose a random angle in a 90deg cone facing one of the players
let angle, pi=Math.PI;
angle= rng()*pi/2-pi/4;
if (rng()>0.5) angle+=pi;
ball.x=w/2
ball.y=h/2
ball.speed=ballStartSpeed
ball.hspeed = Math.cos(angle)*ball.speed
ball.vspeed = Math.sin(angle)*ball.speed
}
timePair={t1:null,t2:null} // of last received packet
pingStack=[]
leadStack=[]
function send(o){
o.t1 = timePair.t1
o.t2 = timePair.t2
o.tSend=performance.now()
DC.send(o)
}
function avg(a){
return a.reduce((x,y)=>x+y)/a.length
}
setup = {
onopen: function(){
connected=true;
requestAnimationFrame(draw)
debuglog.style.display='none';
box1.style.display='none';
box2.style.display='none';
box3.style.display='none';
box4.style.display='block';
if (!host) {
send({type:"version", version})
}
},
onclose: function(){
connected=false;
debuglog.innerHTML = '[ disconnected — refresh to play again ]'
debuglog.style.display='inline-block';
},
onmessage:function(e) {
let ping, recTime = performance.now()
var data = JSON.parse(e.data)
timePair = {t1:data.tSend, t2:recTime}
if (data.t1) {
let t1=data.t1, t2=data.t2, t3=data.tSend, t4 = recTime;
ping = t4-t1 - (t3-t2);
pingStack.push(ping)
if (pingStack.length>stacksize) pingStack.shift()
}
if (data.type) switch (data.type) {
case "version":
if (data.version != version) {
if (host) send({type:"version", version}) //force the other player to also throw this error
alert("Version mismatch! Please refresh the page and try again")
DC.dc.close()
} else send({type:"SYN"})
break;
case "SYN":
send({type:"SYNACK"})
break;
case "SYNACK":
// repeatedly send start condition to establish average ping time
if (pingStack.length < stacksize) send({type:"SYN"})
else {
pingStack.shift() // The first is usually unrepresentative, throw away
let halftrip = avg(pingStack)/2
bufferSize = (bufsize.value=="Auto") ? Math.min(5,Math.ceil(halftrip/frameLength)) : Number(bufsize.value);
initBuffer()
ballStartSpeed = Number(ballspeed.value)
send({type:"ACK", seed, bufferSize, ballStartSpeed})
// wait for half the roundtrip time before starting the first frame
nextFrame = performance.now() + halftrip
setTimeout(processFrame, nextFrame - performance.now())
}
break;
case "ACK":
seed=data.seed
bufferSize = data.bufferSize
ballStartSpeed = data.ballStartSpeed
nextFrame = performance.now()
initBuffer()
processFrame()
break;
case "input":
if (rollbackInputs.length) {
let myInput = rollbackInputs.shift()
let yoInput = data.input
loadRollbackState()
if (yoInput.frame != myInput.frame) console.log("sync error waah",myInput.frame,yoInput.frame)
processGameLogic(myInput,yoInput)
storeRollbackState()
// from here, run the rest of the buffer again
yoInputLastDir = yoInput.dir
for (let i=0;i<rollbackInputs.length;i++) {
processGameLogic( rollbackInputs[i], {dir:yoInputLastDir} )
}
} else {
yoInputs.push(data.input)
}
// check/adjust timing
//input packet contains estimate until next frame
let otherNextFrame = recTime -ping/2 + data.delay
let frameDifference = (frameNumber-1 -data.input.frame)*frameLength
let leadTime = nextFrame - otherNextFrame - frameDifference;
leadStack.push(leadTime)
if (leadStack.length>stacksize) leadStack.shift()
break;
}
}
}
function initBuffer(){
frameNumber = -bufferSize;
for (let i=0;i<bufferSize;i++) {
myInputs.push( { frame:frameNumber, dir:0 } )
yoInputs.push( { frame:frameNumber, dir:0 } )
frameNumber++
}
}
function processFrame(){
let yoInput,myInput;
if (yoInputs.length==0) {
if (rollbackInputs.length>=10){
//give up and delay
nextFrame += 1
if (connected) setTimeout(processFrame,1)
return
}
if (rollbackInputs.length==0) {
//commence rollback
storeRollbackState()
}
rollbackInputs.push(myInputs[0])
yoInput = {frame:myInputs[0].frame, dir:yoInputLastDir}
} else {
yoInput = yoInputs.shift()
yoInputLastDir = yoInput.dir
}
myInput = myInputs.shift()
if (myInput.frame != yoInput.frame) {console.log("SYNC ERROR AHHH", myInput,yoInput); return}
processGameLogic(myInput,yoInput)
// take input and add to stack
myinput = { frame:frameNumber, dir:grabY*scaleFactor }
grabY = 0;
myInputs.push( myinput )
// timing drift correction - should this be before or after transmitting?
if (leadStack.length==stacksize) {
let lead = -avg(leadStack)
if (lead>driftThreshold) { //we are running fast
nextFrame += Math.min(lead*driftTrimFactor, frameLength)
}
}
frameNumber++
nextFrame += frameLength
let now = performance.now()
if (nextFrame<now) {
//console.log('timing disrupted')
nextFrame=now
}
let delay = nextFrame - now
// send inputs to other
send({type:"input", input:myinput, delay})
let framesync = now-lastAnimationFrame-synctick;
if (framesync<2 || framesync>15) synctick=-4;
else synctick=0
if (connected) setTimeout(processFrame, delay + synctick)
}
function processGameLogic(myInput,yoInput){
let oldlefty=left.y, oldrighty=right.y
if (host) { processPlayer(left, myInput); processPlayer(right, yoInput); }
else { processPlayer(left, yoInput); processPlayer(right, myInput); }
if (myInput.frame==102) resetBall(); //end of intro animation
let impulses = Math.ceil(ball.speed), step=1/impulses;
for (let i=0;i<impulses;i++) {
ball.x += ball.hspeed*step;
ball.y += ball.vspeed*step;
// bounce off top and bottom
if ((ball.y>h-10 && ball.vspeed>0 )
|| (ball.y<10 && ball.vspeed<0 )) ball.vspeed =-ball.vspeed;
// check for face collision with paddle
if (Math.round(ball.x-ballSize/2) == Math.round(left.x+paddleW/2-1) && vcollision(left)) {
//reflect based on position
ball.speed++
let angle = Math.atan2(ball.y-left.y, 15)
ball.hspeed = Math.cos(angle)*ball.speed
ball.vspeed = Math.sin(angle)*ball.speed
ball.x++
}
else if (Math.round(ball.x+ballSize/2) == Math.round(right.x-paddleW/2+1) && vcollision(right)) {
ball.speed++
let angle = Math.atan2(ball.y-right.y, -15)
ball.hspeed = Math.cos(angle)*ball.speed
ball.vspeed = Math.sin(angle)*ball.speed
ball.x--
}
else if (ball.x-ballSize/2 < left.x+paddleW/2-1 && vcollision(left)) {
ball.vspeed = -ball.vspeed
if (ball.y<oldlefty) ball.y=left.y-paddleH/2-ballSize/2;
else ball.y=left.y+paddleH/2+ballSize/2;
}
else if (ball.x+ballSize/2 > right.x-paddleW/2+1 && vcollision(right)) {
ball.vspeed = -ball.vspeed
if (ball.y<oldrighty) ball.y=right.y-paddleH/2-ballSize/2;
else ball.y=right.y+paddleH/2+ballSize/2;
}
}
if (ball.x<-ballSize) scoreRight++,resetBall()
if (ball.x>w+ballSize) scoreLeft++,resetBall()
}
function processPlayer(p, input){
p.y += input.dir;
if (p.y > h-edgeGuard) p.y = h-edgeGuard;
if (p.y < edgeGuard) p.y = edgeGuard;
}
function vcollision(p){
return (ball.y-ballSize/2 < p.y+paddleH/2 && ball.y+ballSize/2 > p.y-paddleH/2)
}
DC.log=function(...e) {
console.log(...e)
e[1]=JSON.stringify(e[1])
document.getElementById("debuglog").innerHTML += e.join(" ")+"\n"
}
createBtn.onclick = function() {
DC.host( setup, id=> {
document.querySelector('#box3 h2').innerHTML = 'ID: '+ id
});
box3.style.display='block'
box1.style.display='none'
host=true;
}
joinBtn1.onclick = function(){
box2.style.display='block'
box1.style.display='none'
conid.value = DC.id ? DC.id:"";
conid.focus()
}
joinBtn2.onclick = function(){
DC.join( parseInt(conid.value), setup );
box2.innerHTML='Connecting...'
return false
}
canvas.onmousedown=function(e){
let sy = e.pageY
e.preventDefault()
e.stopPropagation()
document.onmousemove=function(e){
grabY += e.pageY - sy
sy = e.pageY
}
document.onmouseup=function(e){
document.onmouseup=null;
document.onmousemove=null;
}
}
touches=[];
canvas.ontouchstart=function(e){
e.preventDefault()
for (let i =e.changedTouches.length;i--;){
let t={sy:e.changedTouches[i].pageY}
touches[e.changedTouches[i].identifier]=t;
}
}
canvas.ontouchmove=function(e){
e.preventDefault()
for (let i=e.changedTouches.length;i--;){
let t=touches[e.changedTouches[i].identifier];
grabY += (e.changedTouches[i].pageY - t.sy)
t.sy=e.changedTouches[i].pageY;
}
if (e.touches.length>2) { //3-finger touch to reset zoom level
viewport.content = 'initial-scale=1';
viewport.content = 'width=device-width';
}
}
window.onload=window.onresize=function(){
scaleFactor=Math.max(1,w/(window.innerWidth-16),h/(window.innerHeight*0.98))
}
///// stats /////
rateAveragingPeriod=6;
animFrameRate=0;
animFrameRateSample=0;
animFrameRateCount=0;
gameFrameRate=0;
gameFrameSample=0;
gameFrameCount=0;
needle=50;
ggrid.strokeStyle="rgba(255,255,255,0.2)"
function drawgrid(x,y,w,h,linespace,zero){
ggrid.beginPath()
for (let i=x;i<=x+w;i+=linespace) {
ggrid.moveTo(i,y)
ggrid.lineTo(i,y+h)
}
for (let j=y;j<=y+h;j+=linespace) {
ggrid.moveTo(x, j)
ggrid.lineTo(x+w,j)
}
ggrid.stroke()
ggrid.beginPath()
ggrid.moveTo(x,y+h+zero)
ggrid.lineTo(x+w,y+h+zero)
ggrid.stroke()
}
function newGraph(name, col, y, h, zero, gridsize){
var pos = y+h +zero
var lastY=0;
if (gridsize) drawgrid(50,y,700,h,gridsize, zero)
ggrid.fillStyle=col
ggrid.fillText(name,gridsize?55:140,y-6)
return function( Y ){
graph.strokeStyle=col
graph.beginPath()
graph.moveTo(needle,lastY +pos)
graph.lineTo(needle+1,Y +pos)
graph.stroke()
lastY=Y
}
}
plotLead = newGraph("lag / lead (ms)", "green", 20, 180, -90, 20)
plotBuff = newGraph("buffer", "cyan", 220, 50, 0, 10)
plotRolb = newGraph("rollback buffer", "red", 220, 50, 0)
plotSnTc = newGraph("synctick", "teal", 290,40, 0, 20)
plotPing = newGraph("ping (ms)", "white", 350, 140, 0, 20)
plotSync = newGraph("framesync (ms)", "orange", 350,140,-20)
function doStats(t){
animFrameRateCount+=(t-lastAnimationFrame);
if (++animFrameRateSample >= rateAveragingPeriod) {
animFrameRate = rateAveragingPeriod*1000/animFrameRateCount
animFrameRateCount=0
animFrameRateSample=0
if (nextFrame>gameFrameCount) {
gameFrameRate = (frameNumber-gameFrameSample)*1000/(nextFrame-gameFrameCount)
gameFrameCount = nextFrame
gameFrameSample = frameNumber
}
}
let lead = leadStack.length? avg(leadStack) : 0;
let ping = pingStack.length? avg(pingStack) : 0;
graph.clearRect(needle,0,4,600)
plotLead(lead)
plotBuff(-yoInputs.length*5)
plotRolb(-rollbackInputs.length*5)
plotSnTc(synctick*3)
plotPing(-ping)
plotSync(Math.min(20,(t-nextFrame)*5))
if (++needle>=750) needle=50
let p="ping: " +ping.toFixed(3) + "ms\n"
+"lead: " +lead.toFixed(3) + "ms\n"
+"framesync: "+(nextFrame-t).toFixed(3)+"ms\n"
+"Display FPS: "+animFrameRate.toFixed(3)
+"\nGame FPS: "+gameFrameRate.toFixed(3)
+"\nbuffer: "+"\u25a0 ".repeat(yoInputs.length);
if (yoInputs.length<bufferSize) p+="\u25a1 ".repeat(bufferSize-yoInputs.length)
p+= "\nrollback buffer: "+ (rollbackInputs.length?"\u25a0 ".repeat(rollbackInputs.length):"");
document.getElementById("stats").innerHTML = p
}
</script>