forked from WofWca/quake3.xdc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
843 lines (752 loc) · 30 KB
/
index.html
File metadata and controls
843 lines (752 loc) · 30 KB
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
<!DOCTYPE html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="dark">
<title>VectorQuake</title>
<style>
html, body { margin: 0; padding: 0; overflow: hidden; background: rgb(0, 0, 0);
font-family: "Antonio", sans-serif;
font-optical-sizing: auto;
font-weight: 700;
font-style: normal;
letter-spacing: -.05ch;
}
canvas { max-width: 100%; max-height: 100%; min-width: 100%; min-height: 100%; object-fit: contain; }
#progress { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 80%; height: 4em; background: black; border: .5em solid white; padding: .5em; }
#blocker {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: transparent;
color: white;
user-select: none;
-webkit-user-select: none;
}
#ui {
padding: 1em;
position: absolute;
left: 0;
bottom: 0;
background: transparent;
color: rgb(197, 0, 0);
transform-origin: bottom left;
transform: scale(4) scaleY(0.6);
user-select: none;
-webkit-user-select: none;
}
.button::before,
.button::after {
content:attr(title);
display:block;
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
padding: .2em
}
.button::before {
color: rgb(200, 0, 0);
text-shadow: .5px .5px .5px rgba(0, 0, 0, 1);
}
.selected::after, .button:hover::after {
animation: blink .5s infinite;
animation-timing-function: ease-in-out;
color: rgb(255,0,0);
text-shadow: 0 0 1px rgba(255, 0, 0, 1);
}
#ui:hover .selected:not(:hover)::after {
animation: none;
text-shadow: none;
}
.button {
position: relative;
font-family: "Antonio", sans-serif;
font-optical-sizing: auto;
font-weight: 700;
font-style: normal;
padding: .2em;
font-weight: bold;
color: transparent;
background: transparent;
text-align: center;
}
@keyframes blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
#move, #look {
width: 50%;
height: 100%;
top: 0;
left: 0;
position: absolute;
}
#look {
/* Make 10x larger in pixel size because webkit rounds touch events to the nearest CSS pixel.
I'm not sure if this actually works or if WebKit rounds anyway but at least we tried. */
transform: scale(0.1);
transform-origin: top left;
width: 500%;
height: 1000%;
left: 50%;
}
#done {
width: 100%;
height: 100%;
transform: scaleX(0.05);
transform-origin: center left;
transition: transform 5s;
background: white;
}
#rotator {
transform: none;
transform-origin: bottom left;
position:absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
width: 100dvw;
height: 100dvh;
overflow:hidden;
}
@media (pointer: coarse) and (orientation: portrait) {
#rotator {
transform: rotate(90deg);
transform-origin: bottom left;
top: -100vw;
left: 0;
width: 100vh;
height: 100vw;
width: 100dvh;
height: 100dvw;
}
}
#blocker * { display: none; }
@media (pointer: coarse) {
#blocker * { display: block; }
}
</style>
<body>
<div id=rotator>
<canvas id=canvas></canvas>
<div id=blocker>
<div id="move"></div>
<div id="look"></div>
</div>
<!-- We would like `display: none;`, because when we can't enter
full-screen, this prevents clicking the game. -->
<div id="ui" style="display: none;">
<div id=multiplayerMessage class="button selected" style=display:none title="COPY MULTIPLAYER URL">COPY MULTIPLAYER URL</div>
<a id="mainMenuLink" class="button selected" style="display: none;" href="./main-menu.html" title="EXIT TO MAIN MENU">EXIT TO MAIN MENU</a>
</div>
<div id=progress><div id=done></div></div>
</div>
</body>
<script src="compression-streams-polyfill.0.1.7.js"></script>
<script src="./webxdc.js" type="module"></script>
<script src="./override-webrtc.js" type="module"></script>
<script src="./override-websocket-signaling.js" type="module"></script>
<script type='module'>
let peerServer = 's://peer-server.thelongestyard.link';
const peerServerWebSocket = `ws${peerServer}`;
const peerServerHTTP = `http${peerServer}`;
// HACK: prevent the browser from queueing too many frames. Defeat pipelineing by calling readPixels() after each frame.
const originalGetContext = HTMLCanvasElement.prototype.getContext;
let context = null;
HTMLCanvasElement.prototype.getContext = function(type, options) {
return context = originalGetContext.call(this, type, options);
};
const originalRAF = requestAnimationFrame;
const rafChannel = new MessageChannel();
const nopRAF = () => rafChannel.port1.postMessage(' ');
rafChannel.port2.onmessage = ()=>{
if (context) context.readPixels(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array(4));
originalRAF.call(self, nopRAF);
};
originalRAF.call(self, nopRAF);
// Fool Emscripten into rendering in landscape even on portrait displays.
const screenPrototype = Object.getPrototypeOf(screen);
const originalScreenWidthProperty = Object.getOwnPropertyDescriptor(screenPrototype, 'width');
const originalScreenHeightProperty = Object.getOwnPropertyDescriptor(screenPrototype, 'height');
if (screen.height > screen.width) {
Object.defineProperty(screen, 'width', originalScreenHeightProperty);
Object.defineProperty(screen, 'height', originalScreenWidthProperty);
}
import { GamepadEmulator } from './GamepadEmulator.js';
const emulator = new GamepadEmulator();
const gamepad = emulator.AddEmulatedGamepad(null, true);
const gamepadEmulatorConfig = {
directions: { up: true, down: true, left: true, right: true },
dragDistance: 100,
tapTarget: move,
xAxisIndex: 0,
yAxisIndex: 1,
swapAxes: false,
invertX: false,
invertY: false,
};
emulator.AddDisplayJoystickEventListeners(0, [gamepadEmulatorConfig]);
const rotateGamepad = e => {
gamepadEmulatorConfig.swapAxes = e.matches;
gamepadEmulatorConfig.invertX = e.matches;
};
const portraitOrientation = window.matchMedia("(orientation: portrait)");
rotateGamepad(portraitOrientation);
portraitOrientation.addEventListener('change', rotateGamepad);
let lastPointerEvent = null;
let fakeMouseDown = false;
look.addEventListener('pointerdown', (e) => {
lastPointerEvent = e;
if (e.offsetY < e.target.clientHeight / 2) {
fakeMouseDown = true;
const fakeMouseDownEvent = new MouseEvent('mousedown', {
clientX: e.offsetX / 2,
clientY: e.offsetY / 2,
bubbles: true,
cancelable: true,
view: window
});
canvas.dispatchEvent(fakeMouseDownEvent);
}
}, { passive: false });
look.addEventListener('pointermove', (e) => {
if (lastPointerEvent && lastPointerEvent.pointerId === e.pointerId) {
let deltaX = e.offsetX - lastPointerEvent.offsetX;
let deltaY = e.offsetY - lastPointerEvent.offsetY;
const fakeMouseEvent = new MouseEvent('mousemove', {
clientX: e.offsetX / 2,
clientY: e.offsetY / 2,
movementX: deltaX / 2,
movementY: deltaY / 2,
bubbles: true,
cancelable: true,
view: window
});
// Safari doesn't recognize movementX and movementY, so we have to set them manually.
if (fakeMouseEvent.movementX === undefined) {
fakeMouseEvent.movementX = deltaX / 2;
fakeMouseEvent.movementY = deltaY / 2;
}
canvas.dispatchEvent(fakeMouseEvent);
lastPointerEvent = e;
}
e.preventDefault();
}, { passive: false });
look.addEventListener('pointerup', (e) => {
if (lastPointerEvent && lastPointerEvent.pointerId === e.pointerId) {
lastPointerEvent = null;
if (fakeMouseDown) {
fakeMouseDown = false;
const fakeMouseUpEvent = new MouseEvent('mouseup', {
clientX: e.offsetX / 2,
clientY: e.offsetY / 2,
bubbles: true,
cancelable: true,
view: window
});
canvas.dispatchEvent(fakeMouseUpEvent);
}
}
}, { passive: false });
look.addEventListener('pointercancel', (e) => {
if (lastPointerEvent && lastPointerEvent.pointerId === e.pointerId) {
lastPointerEvent = null;
}
}, { passive: false });
const originalRequestPointerLock = HTMLElement.prototype.requestPointerLock;
HTMLElement.prototype.originalRequestPointerLock = originalRequestPointerLock;
// Block Emscripten from automatically calling requestPointerLock when we don't want it to.
HTMLElement.prototype.requestPointerLock = function(options) {
console.log('Intercepted requestPointerLock call');
};
// Don't use fullscreen API on iOS because Apple crippled it. Any touch input with a downward drag will exit fullscreen.
const ios = /iPad|iPhone|iPod/.test(navigator.platform) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
let saveFiles = null;
let lastSavedFilesOnEscapePressAt = Date.now();
/**
* @param {KeyboardEvent} event
*/
const saveFilesOnEscapePress = (event) => {
const alreadySavedRecently = (Date.now() - lastSavedFilesOnEscapePressAt) < 1000;
if (event.key === 'Escape' && !alreadySavedRecently && saveFiles) {
saveFiles();
lastSavedFilesOnEscapePressAt = Date.now();
}
}
document.addEventListener('keydown', saveFilesOnEscapePress, { passive: true });
document.addEventListener('pointerlockchange', ()=>{if (!ios && document.pointerLockElement && !document.fullscreenElement && document.documentElement.requestFullscreen) document.documentElement.requestFullscreen()});
async function canvasRequestPointerLock() {
try {
await canvas.originalRequestPointerLock({ unadjustedMovement: true });
return;
} catch (err) {
console.warn(
'`requestPointerLock with `unadjustedMovement: true` failed, falling back to regular',
err
);
await canvas.originalRequestPointerLock();
}
}
document.addEventListener('fullscreenchange', () => {
if (saveFiles) saveFiles();
if (document.fullscreenElement) {
document.removeEventListener('keydown', saveFilesOnEscapePress);
}
if (document.fullscreenElement && !document.pointerLockElement && canvas.originalRequestPointerLock) canvasRequestPointerLock();
ui.style.visibility = document.fullscreenElement ? 'hidden' : 'visible';
});
const fullscreenAndPointerLock = async (e) => {
if (ui.contains(e.target)) return;
if (!document.pointerLockElement && canvas.originalRequestPointerLock) canvasRequestPointerLock();
if (!ios && !document.fullscreenElement && document.documentElement.requestFullscreen) document.documentElement.requestFullscreen();
};
blocker.addEventListener('keydown', fullscreenAndPointerLock);
blocker.addEventListener('touchend', fullscreenAndPointerLock);
blocker.addEventListener('mousedown', fullscreenAndPointerLock);
blocker.addEventListener('touchmove', (e) => e.preventDefault() ); // required for touchend to fire if the touch moves
// Prevent Safari from showing a magnifying glass on double tap and hold. C'mon Apple...
blocker.addEventListener('touchstart', e=>e.preventDefault(), {passive: false});
look.addEventListener('touchstart', e=>e.preventDefault(), {passive: false});
move.addEventListener('touchstart', e=>e.preventDefault(), {passive: false});
const defaultKeyBindingKeyCodes = { "KeyW": true, "KeyA": true, "KeyS": true, "KeyD": true, "KeyC": true, "KeyT": true, "Digit1": true, "Digit2": true, "Digit3": true, "Digit4": true, "Digit5": true, "Digit6": true, "Digit7": true, "Digit8": true, "Digit9": true, "Tab": true, "Space": true, "Enter": true, "NumpadEnter": true, "Delete": true, "Slash": true, "Backslash": true, "ArrowUp": true, "ArrowDown": true, "ArrowLeft": true, "ArrowRight": true, "PageDown": true, "End": true, "Escape": true, "ControlLeft": true, "ControlRight": true, "ShiftLeft": true, "ShiftRight": true, "AltLeft": true, "AltRight": true };
window.addEventListener("keydown", (e) => {
if (!defaultKeyBindingKeyCodes[e.code]) e.preventDefault = () => false;
}, { capture: true });
// VectorQuake: hardcoded to demoq3, all game files are bundled
const basegame = 'demoq3';
let username = localStorage.getItem('username');
let model = localStorage.getItem('model');
if (!username || !model) {
// https://webxdc.org/docs/spec/selfAddr_and_selfName.html
const webxdcSelfName = globalThis.webxdc?.selfName;
if (typeof webxdcSelfName === 'string') {
const allowedChars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
+" ^[](){}!@#$%&'*+,-./<>=?|";
const withoutBadCharacters = webxdcSelfName
.split('')
.filter(nameCharacter => allowedChars.includes(nameCharacter))
.join('');
if (withoutBadCharacters !== webxdcSelfName) {
console.log(
'`webxdc.selfName = webxdcSelfName` '
+ 'contains forbidden characters, we filtered them out.'
);
}
if (withoutBadCharacters.trim().length > 0) {
username = withoutBadCharacters;
}
}
if (!username) {
username = '';
const chars = ['bcdfghjklmnprstvwz', 'aeiou'];
for (let i = 0; i < 6; i++)
username += chars[i % 2].charAt(Math.random() * chars[i % 2].length | 0);
username = username.charAt(0).toUpperCase() + username.slice(1);
}
localStorage.setItem('username', username);
const models = ['sarge', 'visor', 'major', 'major/daemia', 'major', 'major/daemia', 'grunt', 'grunt/stripe'];
model = models[Math.random() * models.length | 0];
localStorage.setItem('model', model);
}
// let server = query.get('server');
let server = 'Myname';
const query = new URLSearchParams(window.location.search);
if (query.has('multiplayer')) {
if (!server) server = username;
let newUrl = new URL(window.location);
newUrl.searchParams.delete('multiplayer');
newUrl.searchParams.set('server', server);
history.replaceState(null, '', newUrl);
}
let generatedArguments = `
+set fs_game ${basegame}
`;
let botSkill = 2;
if (window.matchMedia('(pointer: coarse)').matches) {
generatedArguments += `
+set g_forcerespawn 2
`;
}
const availableMaps = [
'q3dm1',
'q3dm7',
'q3dm17',
'q3tourney2',
];
function randomFromArray(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function randomMap() {
return randomFromArray(availableMaps);
}
let multiplayer = !!server;
multiplayerMessage.addEventListener('click', (e) => {
navigator.clipboard.writeText(window.location.href);
multiplayerMessage.innerText = `COPIED! SEND TO YOUR FRIENDS!`;
multiplayerMessage.title = multiplayerMessage.innerText;
setTimeout(() => {
multiplayerMessage.innerText = `COPY MULTIPLAYER URL`;
multiplayerMessage.title = multiplayerMessage.innerText;
}, 5000);
e.preventDefault();
e.stopPropagation();
}, { capture: true} );
let decideConnectToServer;
let connectToServer = new Promise(r=>decideConnectToServer=r);
if (server) {
server = server.replace(/"/g, '');
amITheServerP.then(amITheServer => {
amITheServer
? decideConnectToServer(false)
: decideConnectToServer(true)
})
}
let buildPath = '.';
if (location.pathname.startsWith('/ioq3/code/web/')) {
buildPath = '../../build/debug-emscripten-wasm32';
}
const getFilesAlreadyCreatedStorageKey =
(basegame) => `filesAlreadyCreated_${basegame}`;
const filesAlreadyCreated =
localStorage.getItem(getFilesAlreadyCreatedStorageKey(basegame)) === 'true'
const qhome = '/home/web_user/.q3a';
// Fool Emscripten into thinking the browser supports pointer lock.
if (!document.body.requestPointerLock) document.body.requestPointerLock = () => true;
let kickedInitialBots = false;
let firstMainLoop = true;
let module = null;
import(`${buildPath}/ioquake3_opengl2.wasm32.js`).then(async (ioquake3)=>{
module = await ioquake3.default({
canvas: canvas,
arguments: generatedArguments.trim().split(/\s+/),
locateFile: (file) => `${buildPath}/${file}`,
postMainLoop: () => {
if (firstMainLoop) {
firstMainLoop = false;
if (window.matchMedia('(pointer: coarse)').matches){
Object.defineProperty(document, 'pointerLockElement', { get: () => canvas });
const fakePointerLockChangeEvent = new Event('pointerlockchange', {
bubbles: true,
cancelable: true
});
document.dispatchEvent(fakePointerLockChangeEvent);
}
}
},
printErr: (msg) => {
if (msg === '--- Common Initialization Complete ---') {
progress.style.display = 'none';
localStorage.setItem('defaultBasegame', basegame);
} else if (msg === '----- Client Shutdown (Client quit) -----') {
saveFiles();
location.assign('./main-menu.html');
} else if (msg === '==== ShutdownGame ====') {
document.getElementById('mainMenuLink').style.display = '';
ui.style.display = '';
setTimeout(() => {
document.getElementById('mainMenuLink').style.display = 'none';
ui.style.display = 'none';
}, 10_000);
} else if (msg === '------- Game Initialization -------') {
document.getElementById('mainMenuLink').style.display = 'none';
ui.style.display = 'none';
} else if (msg?.startsWith('Client') && msg.endsWith('challenge ping')) {
// Kick all bots when a real player connects
if (!kickedInitialBots) {
window.dispatchEvent(
new KeyboardEvent('keydown', { code: 'NumpadDivide' })
);
kickedInitialBots = true;
}
}
console.error(msg);
},
preRun: [async (module) => {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
for (const c of Object.values(module.AL.contexts)) {
c.gain.gain.linearRampToValueAtTime(0, c.audioCtx.currentTime + 0.1);
}
} else {
for (const c of Object.values(module.AL.contexts)) {
c.gain.gain.setValueAtTime(0.00001, c.audioCtx.currentTime);
c.gain.gain.exponentialRampToValueAtTime(1, c.audioCtx.currentTime + 1);
}
}
});
module.addRunDependency('setup-ioq3-filesystem');
module.FS.mkdirTree(`/${basegame}`);
module.FS.mkdirTree(qhome);
module.FS.mount(module.FS.filesystems.IDBFS, {}, qhome);
let idbfsReadyResolve = null;
const idbfsReady = new Promise(r=>idbfsReadyResolve=r);
module.FS.syncfs(true, (err) => {
if (err) { console.error(err); debugger; }
idbfsReadyResolve();
});
await idbfsReady;
try {
if(!module.FS.analyzePath(`${qhome}/${basegame}/q3config.cfg`).exists) {
module.arguments.push(...`
+set model "${model}"
+set headmodel "${model}"
+set name "${username}"
`.trim().split(/\s+/));
} else {
const q3config = module.FS.readFile(`${qhome}/${basegame}/q3config.cfg`, { encoding: 'utf8' });
const lines = q3config.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('seta name')) {
localStorage.setItem('username', lines[i].split('"')[1]);
} else if (lines[i].startsWith('seta model') || lines[i].startsWith('seta headmodel')) {
localStorage.setItem('model', lines[i].split('"')[1]);
}
}
}
} catch (err) {
console.error('Error reading q3config.cfg:', err);
}
if (!filesAlreadyCreated) {
// VectorQuake: fetch bundled game files directly
const demoPak0 = fetch(`${buildPath}/demoq3-pak0.pk3`)
.then(r => r.arrayBuffer())
.then(r => new Uint8Array(r));
const fixDemoBotsMod = fetch(`${buildPath}/pak1-fix-demo-bots.pk3`)
.then(r => r.arrayBuffer())
.then(b => new Uint8Array(b))
const ztmFlexibleHudMod = fetch(`${buildPath}/ztm-flexible-hud.pk3`)
.then(r => r.arrayBuffer())
.then(r => new Uint8Array(r));
writeCommonPersistentFiles(module, basegame);
module.FS.mkdirTree(`${qhome}/${basegame}`);
// Write the bundled pak0.pk3
module.FS.writeFile(
`${qhome}/${basegame}/pak0.pk3`,
await demoPak0
);
// ztm-flexible-hud provides compatible QVMs for the demo engine
module.FS.writeFile(
`${qhome}/${basegame}/ztm-flexible-hud.pk3`,
await ztmFlexibleHudMod
);
// Fix demo bots so they use proper weapons
module.FS.writeFile(
`${qhome}/${basegame}/pak1-fix-demo-bots.pk3`,
await fixDemoBotsMod
);
}
saveFiles = () => {
module.FS.syncfs(false, (err) => {
if (err) {
console.error(err);
debugger;
return;
}
localStorage.setItem(getFilesAlreadyCreatedStorageKey(basegame), 'true');
});
};
saveFiles();
if (multiplayer) {
const tryNotifyChat = (message) => {
const selfName = globalThis.webxdc?.selfName || 'A player'
globalThis.webxdc?.sendUpdate?.({
payload: null,
info: `${selfName} ${message}`,
}, '')
}
if (await connectToServer) {
module.arguments.push(...`
+set net_peer_server "${peerServerWebSocket}"
+connect "${server}.humblenet"
`.trim().split(/\s+/));
setTimeout(async () => {
let numPlayers = 2;
const serverAdress = await globalThis.serverAddressP;
/** @type {Map<number, number>} */
const map = globalThis.addressToLastPacketTimestamp;
map.forEach((lastPacketReceivedAt, address) => {
if (address === serverAdress) return;
if (address === 0x2B2B2B2B || address === 0x2A2A2A2A) return;
if (Date.now() - lastPacketReceivedAt < 5000) {
numPlayers += 1;
}
});
tryNotifyChat(
`entered the game. Players online: ${numPlayers}`
);
}, 1000)
} else {
module.arguments.push(...`
+set net_peer_server "${peerServerWebSocket}"
+set net_server_name "${server}"
+map ${randomMap()}
+addbot random ${botSkill}
+addbot random ${botSkill}
+addbot random ${botSkill}
+addbot random ${botSkill}
+exec setNextmap.cfg
`.trim().split(/\s+/));
setTimeout(() => {
tryNotifyChat('started the server');
window.top.addEventListener('pagehide', () => {
tryNotifyChat('stopped the server');
});
}, 10 * 1000)
}
} else {
module.arguments.push(...`
+map ${randomMap()}
+addbot sarge ${botSkill}
+addbot daemia ${botSkill}
+addbot major ${botSkill}
+addbot visor ${botSkill}
+addbot stripe ${botSkill}
+exec setNextmap.cfg
`.trim().split(/\s+/));
}
module.FS.writeFile(`/${basegame}/autoexec_2_autogenerated.cfg`, `
// Map rotation. After a match has finished, go to next map.
${availableMaps
.map(mapName => ({ mapName, sortVal: Math.random() }))
.sort((a, b) => a.sortVal - b.sortVal)
.map(obj => obj.mapName)
.map((mapName, ind, arr) => {
const nextInd = ind === arr.length - 1
? 1
: ind + 2;
return `set d${ind + 1} "map ${mapName} ; set nextmap vstr d${nextInd}"`
})
.join('\n')}
set nextmap vstr d1
`, { encoding: 'utf8' });
module.removeRunDependency('setup-ioq3-filesystem');
}],
});
if (multiplayer) {
// Always run server even in background tabs.
const worker = new Worker(URL.createObjectURL(new Blob([`
setInterval(() => {
self.postMessage('tick');
}, 1000 / 60);
`], { type: 'application/javascript' })));
worker.onmessage = function(e) {
if (document.hidden && module && module.Browser && module.Browser.mainLoop)
module.Browser.mainLoop.runIter(module.Browser.mainLoop.func);
};
}
});
// VectorQuake: pak0.pk3 is bundled, just show progress bar
done.style.transform = 'scaleX(1)';
/**
* @param {string} basegame
*/
function writeCommonPersistentFiles(module, basegame) {
module.FS.mkdirTree(`${qhome}/${basegame}`);
const bots = ['random', 'random', 'random', 'random'];
const addBots = bots.map((b, i) => {
const msecDelay = 1000 + i * 2000;
return `addbot ${b} ${botSkill} free ${msecDelay}`
}).join('; ');
module.FS.writeFile(`${qhome}/${basegame}/autoexec.cfg`,
`// Execute "init.cfg" on first launch only.
toggle customVarExecInitOnce "exec init.cfg" ";"
vstr customVarExecInitOnce
seta customVarExecInitOnce "exec init.cfg"
set in_joystick 1
set in_joystickUseAnalog 1
set j_forward "0.005"
set j_side "0.005"
set j_pitch "0.005"
set j_yaw "0.01"
set customVarOnMainMenuPress "echo Press again to exit to main menu;\
set customVarOnMainMenuPress quit;"
set customVarKickBots "kickbots; kick allbots; set customVarToggleBots vstr customVarAddBots; echo Kicked bots"
set customVarAddBots "${addBots}; set customVarToggleBots vstr customVarKickBots; echo Added bots"
set customVarToggleBots "vstr customVarKickBots"
// Bound to NumpadDivide for programmatic bot kicking when a real player connects
bind KP_SLASH "kickbots; kick allbots; unbind KP_SLASH"
set r_mode -2 // make game use desktop resolution
set r_picmip 0 // full texture detail
set r_lodBias -2 // don't use lower detail models far away
set r_subdivisions 1 // smoother curves
set r_textureMode "GL_LINEAR_MIPMAP_LINEAR" // trilinear filter
set r_ext_texture_filter_anisotropic 1 // enable anisotropy texture filter
set r_ext_max_anisotropy 16 // 16x anisotropy texture filter
set r_ext_multisample 16 // use multisample antialiasing
set r_ext_framebuffer_multisample 16 // use multisample antialiasing
set r_lodCurveError 10000 // smoother curves far away (cheat protected)
set g_warmup 0
set r_mode -2
set com_maxfps 0
set r_swapInverval 1
set net_enabled 1
set r_fullscreen 0
set r_ignoreGLErrors 1
set cg_deferPlayers 0 // load player models when they connect instead of substituting a random model
set sv_maxclients 128
${globalThis.webxdc != undefined
? (
'// webxdc connection is reliable + ordered,\n' +
'// so duplicating packets is of no use.\n' +
'set cl_packetdup 0\n'
) : ''
}
set sv_pure 1
exec autoexec_2_autogenerated.cfg
`, { encoding: 'utf8' });
module.FS.writeFile(`${qhome}/${basegame}/init.cfg`,
`// This file is supposed to be run only at first ever start of the game.
set customVarPrintMotd "\
echo F4: main menu; \
echo F6: mainer menu: switch game, edit config files, install mods, etc; \
echo F8: add / kick bots; \
echo tilde: toggle console;"
bind "W" "vstr customVarPrintMotd; +forward; bind W +forward;"
bind PAD0_LEFTSTICK_LEFT "+moveleft"
bind PAD0_LEFTSTICK_RIGHT "+moveright"
bind PAD0_LEFTSTICK_UP "+forward"
bind PAD0_LEFTSTICK_DOWN "+back"
bind PAD0_DPAD_LEFT "+moveleft"
bind PAD0_DPAD_UP "+forward"
bind PAD0_DPAD_RIGHT "+moveright"
bind PAD0_DPAD_DOWN "+back"
bind PAD0_RIGHTSTICK_LEFT "+left"
bind PAD0_RIGHTSTICK_RIGHT "+right"
bind PAD0_RIGHTSTICK_UP "+lookup"
bind PAD0_RIGHTSTICK_DOWN "+lookdown"
bind PAD0_RIGHTTRIGGER "+attack"
bind PAD0_LEFTTRIGGER "+zoom"
bind PAD0_A "+moveup"
bind PAD0_B "weapnext"
bind PAD0_X "weapprev"
bind PAD0_Y "weapon 1"
bind PAD0_LEFTSHOULDER "+zoom"
bind PAD0_RIGHTSHOULDER "+attack"
bind PAD0_START "togglemenu"
bind PAD0_BACK "+button3"
bind PAD0_LEFTSTICK_CLICK "+zoom"
bind PAD0_RIGHTSTICK_CLICK "+button3"
bind F4 "togglemenu"
bind F6 "vstr customVarOnMainMenuPress"
unbind F11
bind "F8" "vstr customVarToggleBots"
seta cg_oldGibs 0
seta cg_fovAdjust 1
seta cg_fovGunAdjust 1
seta cg_fovAspectAdjust 1
seta cg_fov 90
`, { encoding: 'utf8' });
module.FS.mkdirTree(`${qhome}/${basegame}`);
module.FS.writeFile(
`${qhome}/${basegame}/setNextmap.cfg`,
`set nextmap vstr d1`,
{ encoding: 'utf8' }
)
}
</script>