This commit is contained in:
Rim 2025-04-23 20:40:48 -04:00
parent 23ffb6ea2a
commit ae9710d724
2 changed files with 217 additions and 211 deletions

44
app.js
View File

@ -7,21 +7,20 @@ const url = require("url");
const port = 8080; const port = 8080;
const host = "0.0.0.0"; const host = "0.0.0.0";
const mimeTypes = { const mimeTypes = {
".html": "text/html", ".html": "text/html",
".css": "text/css", ".css": "text/css",
".js": "application/javascript", ".js": "application/javascript",
".svg": "image/svg+xml", ".svg": "image/svg+xml",
".png": "image/png", ".png": "image/png",
".jpg": "image/jpeg", ".jpg": "image/jpeg",
".jpeg": "image/jpeg", ".jpeg": "image/jpeg",
".gif": "image/gif", ".gif": "image/gif",
".ico": "image/x-icon", ".ico": "image/x-icon",
".json": "application/json", ".json": "application/json",
".txt": "text/plain", ".txt": "text/plain",
}; };
http http.createServer((req, res) => {
.createServer((req, res) => {
// Parse the URL and extract just the pathname, ignoring query parameters // Parse the URL and extract just the pathname, ignoring query parameters
const parsedUrl = url.parse(req.url); const parsedUrl = url.parse(req.url);
let filePath = "." + decodeURIComponent(parsedUrl.pathname); let filePath = "." + decodeURIComponent(parsedUrl.pathname);
@ -31,15 +30,14 @@ http
const contentType = mimeTypes[ext] || "application/octet-stream"; const contentType = mimeTypes[ext] || "application/octet-stream";
fs.readFile(filePath, (err, content) => { fs.readFile(filePath, (err, content) => {
if (err) { if (err) {
res.writeHead(404); res.writeHead(404);
res.end("404 Not Found"); res.end("404 Not Found");
} else { } else {
res.writeHead(200, { "Content-Type": contentType }); res.writeHead(200, { "Content-Type": contentType });
res.end(content); res.end(content);
} }
}); });
}) }).listen(port, host, () => {
.listen(port, host, () => {
console.log(`Server running at http://${host}:${port}/`); console.log(`Server running at http://${host}:${port}/`);
}); });

View File

@ -22,88 +22,88 @@
*/ */
--> -->
<style> <style>
body { body {
background: #444; background: #444;
color: white; color: white;
font-family: monospace; font-family: monospace;
} }
#gamepads > * { #gamepads > * {
background: #333; background: #333;
padding: 1em; padding: 1em;
margin: 10px 5px 0 0; margin: 10px 5px 0 0;
} }
#gamepads pre { #gamepads pre {
white-space: pre-wrap; white-space: pre-wrap;
} }
.head { .head {
display: flex; display: flex;
} }
.head .id { .head .id {
flex: 1 1 auto; flex: 1 1 auto;
} }
.head .index, .head .index,
.head .id { .head .id {
display: inline-block; display: inline-block;
background: #222; background: #222;
padding: 0.5em; padding: 0.5em;
} }
.head .index { .head .index {
} }
.info .label { .info .label {
width: 7em; width: 7em;
display: inline-block; display: inline-block;
} }
.info > div { .info > div {
padding: 0.25em; padding: 0.25em;
background: #222; background: #222;
margin: 0.25em 0.25em 0 0; margin: 0.25em 0.25em 0 0;
} }
.inputs { .inputs {
display: flex; display: flex;
} }
.axes { .axes {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
} }
.svg text { .svg text {
color: #ccc; color: #ccc;
font-family: monospace; font-family: monospace;
} }
.axes svg text { .axes svg text {
font-size: 0.6px; font-size: 0.6px;
} }
.buttons svg text { .buttons svg text {
font-size: 1.2px; font-size: 1.2px;
} }
.axes > div, .axes > div,
.buttons > div { .buttons > div {
display: inline-block; display: inline-block;
background: #222; background: #222;
} }
.axes > div { .axes > div {
margin: 2px 5px 0 0; margin: 2px 5px 0 0;
} }
.buttons > div { .buttons > div {
margin: 2px 2px 0 0; margin: 2px 2px 0 0;
} }
</style> </style>
<body> <body>
<h1>HTML5 Gamepad Test</h1> <h1>HTML5 Gamepad Test</h1>
<div>running: <span id="running"></span></div> <div>running: <span id="running"></span></div>
<div id="gamepads"></div> <div id="gamepads"></div>
</body> </body>
<script> <script>
const fudgeFactor = 2; // because of bug in Chrome related to svg text alignment font sizes can not be < 1 const fudgeFactor = 2; // because of bug in Chrome related to svg text alignment font sizes can not be < 1
const runningElem = document.querySelector("#running"); const runningElem = document.querySelector("#running");
const gamepadsElem = document.querySelector("#gamepads"); const gamepadsElem = document.querySelector("#gamepads");
const gamepadsByIndex = {}; const gamepadsByIndex = {};
const controllerTemplate = ` const controllerTemplate = `
<div> <div>
<div class="head"><div class="index"></div><div class="id"></div></div> <div class="head"><div class="index"></div><div class="id"></div></div>
<div class="info"><div class="label">connected:</div><span class="connected"></span></div> <div class="info"><div class="label">connected:</div><span class="connected"></span></div>
@ -114,7 +114,7 @@
</div> </div>
</div> </div>
`; `;
const axisTemplate = ` const axisTemplate = `
<svg viewBox="-2.2 -2.2 4.4 4.4" width="128" height="128"> <svg viewBox="-2.2 -2.2 4.4 4.4" width="128" height="128">
<circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.04" /> <circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.04" />
<path d="M0,-2L0,2M-2,0L2,0" stroke="#888" stroke-width="0.04" /> <path d="M0,-2L0,2M-2,0L2,0" stroke="#888" stroke-width="0.04" />
@ -123,7 +123,7 @@
</svg> </svg>
`; `;
const buttonTemplate = ` const buttonTemplate = `
<svg viewBox="-2.2 -2.2 4.4 4.4" width="64" height="64"> <svg viewBox="-2.2 -2.2 4.4 4.4" width="64" height="64">
<circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.1" /> <circle cx="0" cy="0" r="2" fill="none" stroke="#888" stroke-width="0.1" />
<circle cx="0" cy="0" r="0" fill="none" fill="red" class="button" /> <circle cx="0" cy="0" r="0" fill="none" fill="red" class="button" />
@ -132,133 +132,141 @@
</svg> </svg>
`; `;
function addGamepad(gamepad) { function addGamepad(gamepad) {
console.log("add:", gamepad.index); console.log("add:", gamepad.index);
const elem = document.createElement("div"); const elem = document.createElement("div");
elem.innerHTML = controllerTemplate; elem.innerHTML = controllerTemplate;
const axesElem = elem.querySelector(".axes"); const axesElem = elem.querySelector(".axes");
const buttonsElem = elem.querySelector(".buttons"); const buttonsElem = elem.querySelector(".buttons");
const axes = []; const axes = [];
for (let ndx = 0; ndx < gamepad.axes.length; ndx += 2) { for (let ndx = 0; ndx < gamepad.axes.length; ndx += 2) {
const div = document.createElement("div"); const div = document.createElement("div");
div.innerHTML = axisTemplate; div.innerHTML = axisTemplate;
axesElem.appendChild(div); axesElem.appendChild(div);
axes.push({ axes.push({
axis: div.querySelector(".axis"), axis: div.querySelector(".axis"),
value: div.querySelector("text"), value: div.querySelector("text"),
}); });
} }
const buttons = []; const buttons = [];
for (let ndx = 0; ndx < gamepad.buttons.length; ++ndx) { for (let ndx = 0; ndx < gamepad.buttons.length; ++ndx) {
const div = document.createElement("div"); const div = document.createElement("div");
div.innerHTML = buttonTemplate; div.innerHTML = buttonTemplate;
buttonsElem.appendChild(div); buttonsElem.appendChild(div);
div.querySelector(".index").textContent = ndx; div.querySelector(".index").textContent = ndx;
buttons.push({ buttons.push({
circle: div.querySelector(".button"), circle: div.querySelector(".button"),
value: div.querySelector(".value"), value: div.querySelector(".value"),
}); });
} }
gamepadsByIndex[gamepad.index] = { gamepadsByIndex[gamepad.index] = {
gamepad, gamepad,
elem, elem,
axes, axes,
buttons, buttons,
index: elem.querySelector(".index"), index: elem.querySelector(".index"),
id: elem.querySelector(".id"), id: elem.querySelector(".id"),
mapping: elem.querySelector(".mapping"), mapping: elem.querySelector(".mapping"),
connected: elem.querySelector(".connected"), connected: elem.querySelector(".connected"),
}; };
gamepadsElem.appendChild(elem); gamepadsElem.appendChild(elem);
} }
function removeGamepad(gamepad) { function removeGamepad(gamepad) {
const info = gamepadsByIndex[gamepad.index]; const info = gamepadsByIndex[gamepad.index];
if (info) { if (info) {
delete gamepadsByIndex[gamepad.index]; delete gamepadsByIndex[gamepad.index];
info.elem.parentElement.removeChild(info.elem); info.elem.parentElement.removeChild(info.elem);
} }
} }
function addGamepadIfNew(gamepad) { function addGamepadIfNew(gamepad) {
const info = gamepadsByIndex[gamepad.index]; const info = gamepadsByIndex[gamepad.index];
if (!info) { if (!info) {
addGamepad(gamepad); addGamepad(gamepad);
} else { } else {
// This broke sometime in the past. It used to be // This broke sometime in the past. It used to be
// the same gamepad object was returned forever. // the same gamepad object was returned forever.
// Then Chrome only changed to a new gamepad object // Then Chrome only changed to a new gamepad object
// is returned every frame. // is returned every frame.
info.gamepad = gamepad; info.gamepad = gamepad;
} }
} }
function handleConnect(e) { function handleConnect(e) {
console.log("connect"); console.log("connect");
addGamepadIfNew(e.gamepad); addGamepadIfNew(e.gamepad);
} }
function handleDisconnect(e) { function handleDisconnect(e) {
console.log("disconnect"); console.log("disconnect");
removeGamepad(e.gamepad); removeGamepad(e.gamepad);
} }
const t = String.fromCharCode(0x26aa); const t = String.fromCharCode(0x26aa);
const f = String.fromCharCode(0x26ab); const f = String.fromCharCode(0x26ab);
function onOff(v) { function onOff(v) {
return v ? t : f; return v ? t : f;
} }
const keys = ["index", "id", "connected", "mapping" /*'timestamp'*/]; const keys = ["index", "id", "connected", "mapping" /*'timestamp'*/];
function processController(info) { function processController(info) {
const { elem, gamepad, axes, buttons } = info; const { elem, gamepad, axes, buttons } = info;
const lines = [`gamepad : ${gamepad.index}`]; const lines = [`gamepad : ${gamepad.index}`];
for (const key of keys) { for (const key of keys) {
info[key].textContent = gamepad[key]; info[key].textContent = gamepad[key];
} }
axes.forEach(({ axis, value }, ndx) => { axes.forEach(({ axis, value }, ndx) => {
const off = ndx * 2; const off = ndx * 2;
axis.setAttributeNS(null, "cx", gamepad.axes[off] * fudgeFactor); axis.setAttributeNS(null, "cx", gamepad.axes[off] * fudgeFactor);
axis.setAttributeNS(null, "cy", gamepad.axes[off + 1] * fudgeFactor); axis.setAttributeNS(
value.textContent = `${gamepad.axes[off].toFixed(2).padStart(5)},${gamepad.axes[off + 1].toFixed(2).padStart(5)}`; null,
}); "cy",
buttons.forEach(({ circle, value }, ndx) => { gamepad.axes[off + 1] * fudgeFactor,
const button = gamepad.buttons[ndx]; );
circle.setAttributeNS(null, "r", button.value * fudgeFactor); value.textContent = `${gamepad.axes[off].toFixed(2).padStart(5)},${gamepad.axes[off + 1].toFixed(2).padStart(5)}`;
circle.setAttributeNS(null, "fill", button.pressed ? "red" : "gray"); });
value.textContent = `${button.value.toFixed(2)}`; buttons.forEach(({ circle, value }, ndx) => {
}); const button = gamepad.buttons[ndx];
circle.setAttributeNS(null, "r", button.value * fudgeFactor);
circle.setAttributeNS(
null,
"fill",
button.pressed ? "red" : "gray",
);
value.textContent = `${button.value.toFixed(2)}`;
});
// lines.push(`axes : [${gamepad.axes.map((v, ndx) => `${ndx}: ${v.toFixed(2).padStart(5)}`).join(', ')} ]`); // lines.push(`axes : [${gamepad.axes.map((v, ndx) => `${ndx}: ${v.toFixed(2).padStart(5)}`).join(', ')} ]`);
// lines.push(`buttons : [${gamepad.buttons.map((v, ndx) => `${ndx}: ${onOff(v.pressed)} ${v.value.toFixed(2)}`).join(', ')} ]`); // lines.push(`buttons : [${gamepad.buttons.map((v, ndx) => `${ndx}: ${onOff(v.pressed)} ${v.value.toFixed(2)}`).join(', ')} ]`);
// elem.textContent = lines.join('\n'); // elem.textContent = lines.join('\n');
} }
function addNewPads() { function addNewPads() {
const gamepads = navigator.getGamepads(); const gamepads = navigator.getGamepads();
for (let i = 0; i < gamepads.length; i++) { for (let i = 0; i < gamepads.length; i++) {
const gamepad = gamepads[i]; const gamepad = gamepads[i];
if (gamepad) { if (gamepad) {
addGamepadIfNew(gamepad); addGamepadIfNew(gamepad);
} }
} }
} }
window.addEventListener("gamepadconnected", handleConnect); window.addEventListener("gamepadconnected", handleConnect);
window.addEventListener("gamepaddisconnected", handleDisconnect); window.addEventListener("gamepaddisconnected", handleDisconnect);
function process() { function process() {
runningElem.textContent = (((performance.now() * 0.001 * 60) | 0) % 100) runningElem.textContent = (((performance.now() * 0.001 * 60) | 0) % 100)
.toString() .toString()
.padStart(2, "0"); .padStart(2, "0");
addNewPads(); // some browsers add by polling, others by event addNewPads(); // some browsers add by polling, others by event
Object.values(gamepadsByIndex).forEach(processController); Object.values(gamepadsByIndex).forEach(processController);
requestAnimationFrame(process); requestAnimationFrame(process);
} }
requestAnimationFrame(process); requestAnimationFrame(process);
</script> </script>