Compare commits
11 Commits
trueOdomet
...
mobileFrie
| Author | SHA1 | Date | |
|---|---|---|---|
|
c225ee696a
|
|||
|
fb8cf9bbfc
|
|||
|
402b147654
|
|||
|
e9d3b71f28
|
|||
|
e593efafa4
|
|||
|
7d02789a39
|
|||
|
b1b67fb0bd
|
|||
|
62bb28ca9d
|
|||
|
07204a476e
|
|||
|
5662142274
|
|||
|
83049815db
|
28
README.md
Normal file
28
README.md
Normal file
@ -0,0 +1,28 @@
|
||||
# MuneBase Swerve Sim
|
||||
|
||||
A browser-based simulator for Swerve Drive robots.
|
||||
|
||||
Live demo: https://swerve-vis.munebase.dev
|
||||
|
||||
|
||||
You can host the project locally with a simple static server and open it in your browser:
|
||||
|
||||
- Python 3 (built-in):
|
||||
|
||||
python3 -m http.server 8000
|
||||
|
||||
Then open: http://localhost:8000
|
||||
|
||||
- Node.js (with npx):
|
||||
|
||||
npx http-server -c-1 .
|
||||
|
||||
Open `index.html` from the project root in your browser if your editor provides a static preview.
|
||||
|
||||
Notes
|
||||
|
||||
- Third-party scripts are in the `vendor/` directory.
|
||||
|
||||
License
|
||||
|
||||
This repository is provided as-is.
|
||||
22
icons/192.svg
Normal file
22
icons/192.svg
Normal file
@ -0,0 +1,22 @@
|
||||
<svg width="192" height="192" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="192" height="192" fill="#16213e"/>
|
||||
<circle cx="96" cy="96" r="70" fill="none" stroke="#0f3460" stroke-width="3"/>
|
||||
|
||||
<!-- Swerve modules (4 corners) -->
|
||||
<circle cx="56" cy="56" r="12" fill="#e94560"/>
|
||||
<circle cx="136" cy="56" r="12" fill="#e94560"/>
|
||||
<circle cx="56" cy="136" r="12" fill="#e94560"/>
|
||||
<circle cx="136" cy="136" r="12" fill="#e94560"/>
|
||||
|
||||
<!-- Velocity arrows -->
|
||||
<line x1="56" y1="56" x2="56" y2="40" stroke="#ff6b6b" stroke-width="3" stroke-linecap="round"/>
|
||||
<line x1="136" y1="56" x2="136" y2="40" stroke="#ff6b6b" stroke-width="3" stroke-linecap="round"/>
|
||||
<line x1="56" y1="136" x2="56" y2="152" stroke="#ff6b6b" stroke-width="3" stroke-linecap="round"/>
|
||||
<line x1="136" y1="136" x2="136" y2="152" stroke="#ff6b6b" stroke-width="3" stroke-linecap="round"/>
|
||||
|
||||
<!-- Center point -->
|
||||
<circle cx="96" cy="96" r="6" fill="#4ecca3"/>
|
||||
|
||||
<!-- Robot frame -->
|
||||
<polygon points="56,56 136,56 136,136 56,136" fill="none" stroke="#4ecca3" stroke-width="2"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
41
icons/512.svg
Normal file
41
icons/512.svg
Normal file
@ -0,0 +1,41 @@
|
||||
<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="512" height="512" fill="#16213e"/>
|
||||
<circle cx="256" cy="256" r="190" fill="none" stroke="#0f3460" stroke-width="8"/>
|
||||
|
||||
<!-- Swerve modules (4 corners) -->
|
||||
<circle cx="150" cy="150" r="32" fill="#e94560"/>
|
||||
<circle cx="362" cy="150" r="32" fill="#e94560"/>
|
||||
<circle cx="150" cy="362" r="32" fill="#e94560"/>
|
||||
<circle cx="362" cy="362" r="32" fill="#e94560"/>
|
||||
|
||||
<!-- Velocity arrows -->
|
||||
<line x1="150" y1="150" x2="150" y2="100" stroke="#ff6b6b" stroke-width="8" stroke-linecap="round"/>
|
||||
<polygon points="150,90 140,110 160,110" fill="#ff6b6b"/>
|
||||
|
||||
<line x1="362" y1="150" x2="362" y2="100" stroke="#ff6b6b" stroke-width="8" stroke-linecap="round"/>
|
||||
<polygon points="362,90 352,110 372,110" fill="#ff6b6b"/>
|
||||
|
||||
<line x1="150" y1="362" x2="150" y2="412" stroke="#ff6b6b" stroke-width="8" stroke-linecap="round"/>
|
||||
<polygon points="150,422 140,402 160,402" fill="#ff6b6b"/>
|
||||
|
||||
<line x1="362" y1="362" x2="362" y2="412" stroke="#ff6b6b" stroke-width="8" stroke-linecap="round"/>
|
||||
<polygon points="362,422 352,402 372,402" fill="#ff6b6b"/>
|
||||
|
||||
<!-- Center point -->
|
||||
<circle cx="256" cy="256" r="16" fill="#4ecca3"/>
|
||||
|
||||
<!-- Robot frame -->
|
||||
<polygon points="150,150 362,150 362,362 150,362" fill="none" stroke="#4ecca3" stroke-width="6"/>
|
||||
|
||||
<!-- Grid lines in background -->
|
||||
<g opacity="0.2" stroke="#4ecca3" stroke-width="1">
|
||||
<line x1="100" y1="100" x2="100" y2="412"/>
|
||||
<line x1="200" y1="100" x2="200" y2="412"/>
|
||||
<line x1="300" y1="100" x2="300" y2="412"/>
|
||||
<line x1="400" y1="100" x2="400" y2="412"/>
|
||||
<line x1="100" y1="100" x2="412" y2="100"/>
|
||||
<line x1="100" y1="200" x2="412" y2="200"/>
|
||||
<line x1="100" y1="300" x2="412" y2="300"/>
|
||||
<line x1="100" y1="400" x2="412" y2="400"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
257
index.html
257
index.html
@ -4,7 +4,15 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#16213e">
|
||||
<meta name="description"
|
||||
content="Interactive simulation of a swerve drive robot with configurable size, speeds, and number of wheels">
|
||||
<link rel="icon" type="image/svg+xml" href="/icons/512.svg">
|
||||
<title>Swerve Drive Visualizer</title>
|
||||
|
||||
<!-- PWA Manifest -->
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
|
||||
@ -14,94 +22,6 @@
|
||||
<p>Interactive simulation of a swerve drive robot with configurable size, speeds, and number of wheels</p>
|
||||
</header>
|
||||
<main>
|
||||
<section class="visualization-canvas">
|
||||
<h2>Robot Visualization</h2>
|
||||
<canvas id="swerve-canvas" width="800" height="800"></canvas>
|
||||
</section>
|
||||
|
||||
<section class="control-panel">
|
||||
<h2>Drive Controls</h2>
|
||||
|
||||
<fieldset>
|
||||
<legend>Translation & Rotation</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="vy-slider">Move Forward/Backward (pixels/s)</label>
|
||||
<input type="range" id="vy-slider" min="-300" max="300" step="10" value="0">
|
||||
<output id="vy-value">0</output>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="vx-slider">Strafe Left/Right (pixels/s)</label>
|
||||
<input type="range" id="vx-slider" min="-300" max="300" step="10" value="0">
|
||||
<output id="vx-value">0</output>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="omega-slider">Rotation (rad/s)</label>
|
||||
<input type="range" id="omega-slider" min="-3" max="3" step="0.1" value="0">
|
||||
<output id="omega-value">0</output>
|
||||
</div>
|
||||
|
||||
<button id="reset-btn" type="button">Reset Controls</button>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend>Performance Limits</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="max-speed-slider">Max Module Speed (pixels/s)</label>
|
||||
<input type="range" id="max-speed-slider" min="200" max="1000" step="10" value="400">
|
||||
<output id="max-speed-value">0</output>
|
||||
</div>
|
||||
</fieldset>
|
||||
</section>
|
||||
<section class="config-panel">
|
||||
<h2>Robot Configuration</h2>
|
||||
<fieldset>
|
||||
<legend>Quick Presets</legend>
|
||||
<div class="preset-buttons">
|
||||
<button id="preset-2wheel" type="button">2-Wheel</button>
|
||||
<button id="preset-3wheel" type="button">3-Wheel Triangle</button>
|
||||
<button id="preset-4wheel" type="button">4-Wheel Square</button>
|
||||
<button id="preset-4rect" type="button">4-Wheel Rectangle</button>
|
||||
<button id="preset-6wheel" type="button">6-Wheel Hexagon</button>
|
||||
<button id="preset-8wheel" type="button">8-Wheel Octagon</button>
|
||||
<button id="preset-8square" type="button">8-Wheel Square</button>
|
||||
<button id="preset-12hex" type="button">12-Wheel Hexagon</button>
|
||||
<button id="preset-16oct" type="button">16-Wheel Octogon</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Custom Configuration</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="module-count">Number of Modules</label>
|
||||
<input type="number" id="module-count" min="2" max="12" value="4" step="1">
|
||||
</div>
|
||||
|
||||
<button id="generate-inputs-btn" type="button">Generate Position Inputs</button>
|
||||
<button id="delete-inputs-btn" type="button">Remove Position Inputs</button>
|
||||
|
||||
<div id="module-position-inputs" class="position-inputs">
|
||||
<!-- Dynamically generated position inputs will appear here -->
|
||||
</div>
|
||||
|
||||
<button id="apply-custom-btn" type="button" style="display: none;">Apply Custom Configuration</button>
|
||||
</fieldset>
|
||||
</section>
|
||||
<section class="module-states">
|
||||
<h2>Module States</h2>
|
||||
<div id="current-config-info" class="config-info">
|
||||
Current Configuration: <strong id="config-name">4-Wheel Rectangle</strong>
|
||||
(<span id="module-count-display">4</span> modules)
|
||||
<br>
|
||||
Gyro Heading: <strong id="gyro-heading-display">0.0°</strong>
|
||||
</div>
|
||||
<div class="module-grid" id="module-grid">
|
||||
<!-- Dynamically generated module data will appear here -->
|
||||
</div>
|
||||
</section>
|
||||
<section class="documentation">
|
||||
<h2>About This Project</h2>
|
||||
<details>
|
||||
@ -275,10 +195,171 @@ if scale < 1:
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
<section class="visualization-canvas">
|
||||
<h2>Robot Visualization</h2>
|
||||
<canvas id="swerve-canvas" width="800" height="800"></canvas>
|
||||
</section>
|
||||
|
||||
<section class="control-panel">
|
||||
<h2>Drive Controls</h2>
|
||||
|
||||
<fieldset>
|
||||
<legend>Translation & Rotation</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<button id="control-mode-toggle" type="button">Switch to Keyboard/Joystick Controls</button>
|
||||
</div>
|
||||
|
||||
<div id="slider-controls">
|
||||
<div class="control-group">
|
||||
<label for="vy-slider">Move Forward/Backward (pixels/s)</label>
|
||||
<input type="range" id="vy-slider" min="-300" max="300" step="10" value="0">
|
||||
<output id="vy-value">0</output>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="vx-slider">Strafe Left/Right (pixels/s)</label>
|
||||
<input type="range" id="vx-slider" min="-300" max="300" step="10" value="0">
|
||||
<output id="vx-value">0</output>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="omega-slider">Rotation (rad/s)</label>
|
||||
<input type="range" id="omega-slider" min="-3" max="3" step="0.1" value="0">
|
||||
<output id="omega-value">0</output>
|
||||
</div>
|
||||
|
||||
<button id="reset-btn" type="button">Reset Controls</button>
|
||||
</div>
|
||||
|
||||
<div id="keyboard-controls" style="display: none;">
|
||||
<div class="control-group">
|
||||
<label for="keyboard-max-speed">Max Speed (pixels/s)</label>
|
||||
<input type="range" id="keyboard-max-speed" min="50" max="300" step="10" value="150">
|
||||
<output id="keyboard-max-speed-value">150</output>
|
||||
</div>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="keyboard-max-rotation">Max Rotation (rad/s)</label>
|
||||
<input type="range" id="keyboard-max-rotation" min="0.5" max="3" step="0.1" value="1.5">
|
||||
<output id="keyboard-max-rotation-value">1.5</output>
|
||||
</div>
|
||||
|
||||
<div class="keyboard-instructions">
|
||||
<h4>Keyboard Controls:</h4>
|
||||
<ul>
|
||||
<li><strong>W:</strong> Move Forward</li>
|
||||
<li><strong>A:</strong> Strafe Left</li>
|
||||
<li><strong>S:</strong> Move Backward</li>
|
||||
<li><strong>D:</strong> Strafe Right</li>
|
||||
<li><strong>Q:</strong> Rotate Counter-Clockwise</li>
|
||||
<li><strong>E:</strong> Rotate Clockwise</li>
|
||||
</ul>
|
||||
<p><em>Click on the canvas area to focus for keyboard input</em></p>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend>Performance Limits</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="max-speed-slider">Max Module Speed (pixels/s)</label>
|
||||
<input type="range" id="max-speed-slider" min="200" max="1000" step="10" value="400">
|
||||
<output id="max-speed-value">0</output>
|
||||
</div>
|
||||
</fieldset>
|
||||
</section>
|
||||
<section class="config-panel">
|
||||
<h2>Robot Configuration</h2>
|
||||
<fieldset>
|
||||
<legend>Quick Presets</legend>
|
||||
<div class="preset-buttons">
|
||||
<button id="preset-2wheel" type="button">2-Wheel</button>
|
||||
<button id="preset-3wheel" type="button">3-Wheel Triangle</button>
|
||||
<button id="preset-4wheel" type="button">4-Wheel Square</button>
|
||||
<button id="preset-4rect" type="button">4-Wheel Rectangle</button>
|
||||
<button id="preset-6wheel" type="button">6-Wheel Hexagon</button>
|
||||
<button id="preset-8wheel" type="button">8-Wheel Octagon</button>
|
||||
<button id="preset-8square" type="button">8-Wheel Square</button>
|
||||
<button id="preset-12hex" type="button">12-Wheel Hexagon</button>
|
||||
<button id="preset-16oct" type="button">16-Wheel Octogon</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Custom Configuration</legend>
|
||||
|
||||
<div class="control-group">
|
||||
<label for="module-count">Number of Modules</label>
|
||||
<input type="number" id="module-count" min="2" max="64" value="4" step="1">
|
||||
</div>
|
||||
|
||||
<button id="generate-inputs-btn" type="button">Generate Position Inputs</button>
|
||||
<button id="delete-inputs-btn" type="button">Remove Position Inputs</button>
|
||||
|
||||
<div id="module-position-inputs" class="position-inputs">
|
||||
<!-- Dynamically generated position inputs will appear here -->
|
||||
</div>
|
||||
|
||||
<button id="apply-custom-btn" type="button" style="display: none;">Apply Custom Configuration</button>
|
||||
</fieldset>
|
||||
</section>
|
||||
<section class="module-states">
|
||||
<h2>Module States</h2>
|
||||
<div id="current-config-info" class="config-info">
|
||||
Current Configuration: <strong id="config-name">4-Wheel Rectangle</strong>
|
||||
(<span id="module-count-display">4</span> modules)
|
||||
<br>
|
||||
Gyro Heading: <strong id="gyro-heading-display">0.0°</strong>
|
||||
</div>
|
||||
<div class="module-grid" id="module-grid">
|
||||
<!-- Dynamically generated module data will appear here -->
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</main>
|
||||
|
||||
<script type="module" src="vendor/lucio/graham-scan.mjs"></script>
|
||||
<script type="module" src="script.js"></script>
|
||||
|
||||
<!-- Register Service Worker for PWA -->
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register('/sw.js')
|
||||
.then((registration) => {
|
||||
console.log('Service Worker registered successfully:', registration.scope);
|
||||
|
||||
// Check for updates periodically
|
||||
setInterval(() => {
|
||||
registration.update();
|
||||
}, 60000); // Check every minute
|
||||
|
||||
// Handle updates
|
||||
registration.addEventListener('updatefound', () => {
|
||||
const newWorker = registration.installing;
|
||||
newWorker.addEventListener('statechange', () => {
|
||||
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
|
||||
// New service worker available, prompt user to reload
|
||||
if (confirm('A new version is available! Reload to update?')) {
|
||||
newWorker.postMessage({ type: 'SKIP_WAITING' });
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log('Service Worker registration failed:', error);
|
||||
});
|
||||
|
||||
// Handle controller change (new service worker activated)
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
22
manifest.json
Normal file
22
manifest.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "MuneBase Swerve Drive Sim",
|
||||
"short_name": "Swerve Sim",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"theme_color": "#16213e",
|
||||
"background_color": "#16213e",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/192.svg",
|
||||
"sizes": "192x192",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/icons/512.svg",
|
||||
"sizes": "512x512",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any"
|
||||
}
|
||||
]
|
||||
}
|
||||
421
script.js
421
script.js
@ -4,6 +4,82 @@
|
||||
|
||||
import GrahamScan from "./vendor/lucio/graham-scan.mjs";
|
||||
|
||||
class Joystick {
|
||||
constructor(ctx, x, y, radius) {
|
||||
this.ctx = ctx;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.radius = radius;
|
||||
this.nubX = x;
|
||||
this.nubY = y;
|
||||
this.active = false;
|
||||
this.visible = false;
|
||||
}
|
||||
|
||||
draw() {
|
||||
if (!this.visible)
|
||||
return;
|
||||
|
||||
this.ctx.save();
|
||||
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
|
||||
this.ctx.fillStyle = rootStyles.getPropertyValue('--primary-dark-blue');
|
||||
this.ctx.fill();
|
||||
|
||||
|
||||
this.ctx.beginPath();
|
||||
this.ctx.arc(this.nubX, this.nubY, this.radius / 3, 0, Math.PI * 2);
|
||||
this.ctx.fillStyle = rootStyles.getPropertyValue('--accent-blue');
|
||||
this.ctx.fill();
|
||||
|
||||
this.ctx.restore();
|
||||
}
|
||||
|
||||
checkShouldActivate(x, y) {
|
||||
if (!this.touchInRange(x, y))
|
||||
return;
|
||||
this.active = true;
|
||||
this.processTouch(x, y);
|
||||
}
|
||||
|
||||
deactivate() {
|
||||
this.active = false;
|
||||
this.reset();
|
||||
}
|
||||
|
||||
touchInRange(x, y) {
|
||||
const deltaX = x - this.x;
|
||||
const deltaY = y - this.y;
|
||||
const dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
return dist <= this.radius;
|
||||
}
|
||||
|
||||
processTouch(x, y) {
|
||||
if (this.touchInRange(x, y) && this.active) {
|
||||
this.nubX = x;
|
||||
this.nubY = y;
|
||||
}
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.nubX = this.x;
|
||||
this.nubY = this.y;
|
||||
}
|
||||
|
||||
getX() {
|
||||
return (this.nubX - this.x) / this.radius;
|
||||
}
|
||||
|
||||
getY() {
|
||||
return (this.y - this.nubY) / this.radius;
|
||||
}
|
||||
|
||||
setIsVisible(visible) {
|
||||
this.visible = visible;
|
||||
}
|
||||
}
|
||||
|
||||
// 2D vector class to make some of the math easier
|
||||
class Vec2D {
|
||||
constructor(x, y) {
|
||||
@ -269,6 +345,15 @@ const PresetConfigs = {
|
||||
* BEGIN DOM VARIABLES
|
||||
*/
|
||||
|
||||
// Get canvas
|
||||
const canvas = document.getElementById('swerve-canvas');
|
||||
|
||||
// Get the canvas context as constant
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Get CSS variables for use in canvas
|
||||
const rootStyles = getComputedStyle(document.documentElement);
|
||||
|
||||
// Get all control elements
|
||||
const vxSlider = document.getElementById('vx-slider');
|
||||
const vySlider = document.getElementById('vy-slider');
|
||||
@ -288,6 +373,15 @@ const generateInputsBtn = document.getElementById('generate-inputs-btn');
|
||||
const clearInputsBtn = document.getElementById('delete-inputs-btn');
|
||||
const applyCustomBtn = document.getElementById('apply-custom-btn');
|
||||
|
||||
// Get control mode elements
|
||||
const controlModeToggle = document.getElementById('control-mode-toggle');
|
||||
const sliderControls = document.getElementById('slider-controls');
|
||||
const keyboardControls = document.getElementById('keyboard-controls');
|
||||
const keyboardMaxSpeed = document.getElementById('keyboard-max-speed');
|
||||
const keyboardMaxSpeedOutput = document.getElementById('keyboard-max-speed-value');
|
||||
const keyboardMaxRotation = document.getElementById('keyboard-max-rotation');
|
||||
const keyboardMaxRotationOutput = document.getElementById('keyboard-max-rotation-value');
|
||||
|
||||
// Preset buttons
|
||||
const preset2WheelBtn = document.getElementById('preset-2wheel');
|
||||
const preset3WheelBtn = document.getElementById('preset-3wheel');
|
||||
@ -301,6 +395,29 @@ const preset16OctBtn = document.getElementById('preset-16oct');
|
||||
|
||||
/*
|
||||
* END DOM VARIABLES
|
||||
* BEGIN CONTROL MODE AND INPUT DEVICE VARIABLES
|
||||
*/
|
||||
|
||||
// Control mode state
|
||||
let isManualInputMode = false; // true = keyboard/gamepad mode, false = slider mode
|
||||
|
||||
// Keyboard state tracking
|
||||
const keyState = {
|
||||
w: false, // Forward
|
||||
a: false, // Left
|
||||
s: false, // Backward
|
||||
d: false, // Right
|
||||
q: false, // Counter-clockwise
|
||||
e: false // Clockwise
|
||||
};
|
||||
|
||||
// Current manual input velocities (from keyboard or gamepad)
|
||||
let manualInputVelX = 0;
|
||||
let manualInputVelY = 0;
|
||||
let manualInputOmega = 0;
|
||||
|
||||
/*
|
||||
* END CONTROL MODE AND INPUT DEVICE VARIABLES
|
||||
* BEGIN LISTENER CODE
|
||||
*/
|
||||
|
||||
@ -319,6 +436,97 @@ resetBtn.addEventListener('click', (e) => {
|
||||
omegaOutput.textContent = parseFloat(omegaSlider.value);
|
||||
});
|
||||
|
||||
// Keyboard control sliders
|
||||
keyboardMaxSpeed.addEventListener('input', (e) => {
|
||||
keyboardMaxSpeedOutput.textContent = parseFloat(e.target.value);
|
||||
});
|
||||
keyboardMaxSpeedOutput.textContent = parseFloat(keyboardMaxSpeed.value);
|
||||
|
||||
keyboardMaxRotation.addEventListener('input', (e) => {
|
||||
keyboardMaxRotationOutput.textContent = parseFloat(e.target.value);
|
||||
});
|
||||
keyboardMaxRotationOutput.textContent = parseFloat(keyboardMaxRotation.value);
|
||||
|
||||
// Control mode toggle
|
||||
controlModeToggle.addEventListener('click', () => {
|
||||
isManualInputMode = !isManualInputMode;
|
||||
|
||||
if (isManualInputMode) {
|
||||
// Switch to manual input mode (keyboard/gamepad)
|
||||
sliderControls.style.display = 'none';
|
||||
keyboardControls.style.display = 'block';
|
||||
controlModeToggle.textContent = 'Switch to Slider Controls';
|
||||
|
||||
// Reset slider values when switching to manual input
|
||||
vxSlider.value = 0;
|
||||
vySlider.value = 0;
|
||||
omegaSlider.value = 0;
|
||||
vxOutput.textContent = '0';
|
||||
vyOutput.textContent = '0';
|
||||
omegaOutput.textContent = '0';
|
||||
leftJoystick.setIsVisible(true);
|
||||
rightJoystick.setIsVisible(true);
|
||||
} else {
|
||||
// Switch to slider mode
|
||||
sliderControls.style.display = 'block';
|
||||
keyboardControls.style.display = 'none';
|
||||
controlModeToggle.textContent = 'Switch to Keyboard/Joystick Controls';
|
||||
|
||||
// Reset manual input state
|
||||
Object.keys(keyState).forEach(key => keyState[key] = false);
|
||||
manualInputVelX = 0;
|
||||
manualInputVelY = 0;
|
||||
manualInputOmega = 0;
|
||||
leftJoystick.setIsVisible(false);
|
||||
rightJoystick.setIsVisible(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Keyboard event listeners
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (!isManualInputMode) return;
|
||||
|
||||
const key = e.key.toLowerCase();
|
||||
if (key in keyState) {
|
||||
keyState[key] = true;
|
||||
e.preventDefault();
|
||||
updateManualInputVelocities();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keyup', (e) => {
|
||||
if (!isManualInputMode) return;
|
||||
|
||||
const key = e.key.toLowerCase();
|
||||
if (key in keyState) {
|
||||
keyState[key] = false;
|
||||
e.preventDefault();
|
||||
updateManualInputVelocities();
|
||||
}
|
||||
});
|
||||
|
||||
// Function to update velocities based on manual input devices (keyboard/gamepad)
|
||||
function updateManualInputVelocities() {
|
||||
const maxSpeed = parseFloat(keyboardMaxSpeed.value);
|
||||
const maxRotation = parseFloat(keyboardMaxRotation.value);
|
||||
|
||||
// Calculate translation velocities from keyboard input
|
||||
manualInputVelX = 0;
|
||||
manualInputVelY = 0;
|
||||
|
||||
if (keyState.d) manualInputVelX += maxSpeed; // Right
|
||||
if (keyState.a) manualInputVelX -= maxSpeed; // Left
|
||||
if (keyState.w) manualInputVelY += maxSpeed; // Forward
|
||||
if (keyState.s) manualInputVelY -= maxSpeed; // Backward
|
||||
|
||||
// Calculate rotation velocity from keyboard input
|
||||
manualInputOmega = 0;
|
||||
if (keyState.e) manualInputOmega += maxRotation; // Clockwise
|
||||
if (keyState.q) manualInputOmega -= maxRotation; // Counter-clockwise
|
||||
|
||||
// TODO: Add gamepad input processing here
|
||||
}
|
||||
|
||||
// Preset button event listeners
|
||||
preset2WheelBtn.addEventListener('click', () => {
|
||||
const positions = PresetConfigs.twoWheel(robotSize);
|
||||
@ -397,8 +605,8 @@ preset16OctBtn.addEventListener('click', () => {
|
||||
generateInputsBtn.addEventListener('click', () => {
|
||||
const count = parseInt(moduleCountInput.value);
|
||||
|
||||
if (isNaN(count) || count < 2) {
|
||||
alert('Please enter a valid number of modules above or equal to 2.');
|
||||
if (isNaN(count) || count < 2 || count > 64) {
|
||||
alert('Please enter a valid number of modules between 2 and 64.');
|
||||
return;
|
||||
}
|
||||
generateModuleInputs(count);
|
||||
@ -433,16 +641,171 @@ applyCustomBtn.addEventListener('click', () => {
|
||||
updateModuleDisplays(robot);
|
||||
});
|
||||
|
||||
function convertTouchToCanvas(inCoords) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
|
||||
// Calculate the scale factor between display size and canvas internal size
|
||||
const scaleX = canvas.width / rect.width;
|
||||
const scaleY = canvas.height / rect.height;
|
||||
|
||||
// Convert client coordinates to canvas coordinates, accounting for scaling
|
||||
const x = (inCoords.x - rect.left) * scaleX - canvas.width / 2;
|
||||
const y = (inCoords.y - rect.top) * scaleY - canvas.height / 2;
|
||||
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
canvas.addEventListener('mousedown', (event) => {
|
||||
const canvasCoords = convertTouchToCanvas({ x: event.clientX, y: event.clientY });
|
||||
leftJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
|
||||
rightJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
|
||||
});
|
||||
|
||||
canvas.addEventListener('mousemove', (event) => {
|
||||
const canvasCoords = convertTouchToCanvas({ x: event.clientX, y: event.clientY });
|
||||
leftJoystick.processTouch(canvasCoords.x, canvasCoords.y);
|
||||
rightJoystick.processTouch(canvasCoords.x, canvasCoords.y);
|
||||
});
|
||||
|
||||
canvas.addEventListener('mouseup', (event) => {
|
||||
leftJoystick.deactivate();
|
||||
rightJoystick.deactivate();
|
||||
});
|
||||
|
||||
// Touch event listeners for mobile/tablet support
|
||||
canvas.addEventListener('touchstart', (event) => {
|
||||
event.preventDefault(); // Prevent scrolling and default touch behavior
|
||||
|
||||
for (let i = 0; i < event.touches.length; i++) {
|
||||
const touch = event.touches[i];
|
||||
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
|
||||
// alert(`X: ${canvasCoords.x}, Y: ${canvasCoords.y}`);
|
||||
leftJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
|
||||
rightJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('touchmove', (event) => {
|
||||
event.preventDefault(); // Prevent scrolling while using joysticks
|
||||
|
||||
for (let i = 0; i < event.touches.length; i++) {
|
||||
const touch = event.touches[i];
|
||||
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
|
||||
leftJoystick.processTouch(canvasCoords.x, canvasCoords.y);
|
||||
rightJoystick.processTouch(canvasCoords.x, canvasCoords.y);
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('touchend', (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
// If no touches remain, deactivate both joysticks
|
||||
if (event.touches.length === 0) {
|
||||
leftJoystick.deactivate();
|
||||
rightJoystick.deactivate();
|
||||
} else {
|
||||
// Check if the remaining touches are still in range of the joysticks
|
||||
let leftStillActive = false;
|
||||
let rightStillActive = false;
|
||||
|
||||
for (let i = 0; i < event.touches.length; i++) {
|
||||
const touch = event.touches[i];
|
||||
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
|
||||
|
||||
if (leftJoystick.touchInRange(canvasCoords.x, canvasCoords.y)) {
|
||||
leftStillActive = true;
|
||||
}
|
||||
if (rightJoystick.touchInRange(canvasCoords.x, canvasCoords.y)) {
|
||||
rightStillActive = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!leftStillActive) {
|
||||
leftJoystick.deactivate();
|
||||
leftJoystick.reset();
|
||||
}
|
||||
if (!rightStillActive) {
|
||||
rightJoystick.deactivate();
|
||||
rightJoystick.reset();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
canvas.addEventListener('touchcancel', (event) => {
|
||||
// Handle touch cancellation (e.g., when system interrupts)
|
||||
leftJoystick.deactivate();
|
||||
leftJoystick.reset();
|
||||
rightJoystick.deactivate();
|
||||
rightJoystick.reset();
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* END LISTENER CODE
|
||||
* BEGIN DYNAMIC DOM FUNCTIONS
|
||||
*/
|
||||
|
||||
// Function to calculate evenly spaced module positions in circular layers
|
||||
function calculateModulePositions(count) {
|
||||
if (count <= 0) return [];
|
||||
|
||||
const baseRadius = 50; // Base radius for the first layer
|
||||
const positions = [];
|
||||
let remainingModules = count;
|
||||
let numberOfLayers = Math.ceil(count / 6);
|
||||
let modulesPerLayer = Math.ceil(count / numberOfLayers);
|
||||
let angleOffset = 0;
|
||||
let currentLayer = 0;
|
||||
let moduleIndex = 0;
|
||||
|
||||
while (remainingModules > 0) {
|
||||
// Determine modules for this layer
|
||||
let modulesInThisLayer;
|
||||
|
||||
if (remainingModules <= modulesPerLayer) {
|
||||
// Last layer gets all remaining modules
|
||||
modulesInThisLayer = remainingModules;
|
||||
} else {
|
||||
// All other layers: try to distribute evenly with max modulesPerLayer
|
||||
const remainingLayers = Math.ceil(remainingModules / modulesPerLayer);
|
||||
modulesInThisLayer = Math.min(modulesPerLayer, Math.ceil(remainingModules / remainingLayers));
|
||||
}
|
||||
|
||||
// Calculate radius for this layer
|
||||
const radius = currentLayer === 0 ? baseRadius : baseRadius * (1 + currentLayer * 0.75);
|
||||
|
||||
// Calculate positions for modules in this layer
|
||||
for (let i = 0; i < modulesInThisLayer; i++) {
|
||||
const angle = (angleOffset + 2 * Math.PI * i) / modulesInThisLayer;
|
||||
const x = Math.round(radius * Math.cos(angle));
|
||||
const y = Math.round(radius * Math.sin(angle));
|
||||
|
||||
positions.push({
|
||||
x: x,
|
||||
y: y,
|
||||
name: `Layer ${currentLayer + 1} Module ${(moduleIndex % modulesPerLayer) + 1}`
|
||||
});
|
||||
|
||||
moduleIndex++;
|
||||
}
|
||||
angleOffset += Math.PI;
|
||||
|
||||
remainingModules -= modulesInThisLayer;
|
||||
currentLayer++;
|
||||
}
|
||||
|
||||
return positions;
|
||||
}
|
||||
|
||||
function generateModuleInputs(count) {
|
||||
const container = document.getElementById('module-position-inputs');
|
||||
container.innerHTML = ''; // Clear existing inputs
|
||||
|
||||
// Calculate evenly spaced positions
|
||||
const positions = calculateModulePositions(count);
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const position = positions[i];
|
||||
const moduleFieldset = document.createElement('fieldset');
|
||||
moduleFieldset.className = 'module-input-group';
|
||||
moduleFieldset.innerHTML = `
|
||||
@ -450,15 +813,15 @@ function generateModuleInputs(count) {
|
||||
|
||||
<div class="control-group">
|
||||
<label for="module-${i}-name">Module Name</label>
|
||||
<input type="text" id="module-${i}-name" value="Module ${i + 1}" required>
|
||||
<input type="text" id="module-${i}-name" value="${position.name}" required>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label for="module-${i}-x">X Position (pixels)</label>
|
||||
<input type="number" id="module-${i}-x" step="1" value="0" required>
|
||||
<input type="number" id="module-${i}-x" step="1" value="${position.x}" required>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label for="module-${i}-y">Y Position (pixels)</label>
|
||||
<input type="number" id="module-${i}-y" step="0.1" value="0" required>
|
||||
<input type="number" id="module-${i}-y" step="0.1" value="${position.y}" required>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(moduleFieldset);
|
||||
@ -521,12 +884,8 @@ function updateModuleDisplays(robot) {
|
||||
* BEGIN ANIMATION CODE
|
||||
*/
|
||||
|
||||
// Get the canvas and context as constants
|
||||
const canvas = document.getElementById('swerve-canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// Get CSS variables for use in canvas
|
||||
const rootStyles = getComputedStyle(document.documentElement);
|
||||
const leftJoystick = new Joystick(ctx, -250, 250, 100);
|
||||
const rightJoystick = new Joystick(ctx, 250, 250, 100);
|
||||
|
||||
function drawGrid(ctx, sideLength, gridSquareSize, xOffset, yOffset) {
|
||||
ctx.save();
|
||||
@ -631,8 +990,12 @@ function drawRobot(ctx, robot, heading) {
|
||||
ctx.restore(); // Restore to remove rotation
|
||||
}
|
||||
|
||||
|
||||
// Initialize Variables
|
||||
// Joysticks
|
||||
const supportsTouch = (navigator.maxTouchPoints > 0);
|
||||
|
||||
|
||||
// General robot
|
||||
const robotSize = 200;
|
||||
const defaultModulePositions = PresetConfigs.fourWheelSquare(robotSize);
|
||||
const robot = new SwerveDrive(defaultModulePositions, "4-Wheel Square");
|
||||
@ -652,10 +1015,29 @@ function animate() {
|
||||
ctx.save();
|
||||
ctx.translate(canvas.width / 2, canvas.height / 2);
|
||||
|
||||
// Update speeds based on sliders
|
||||
// Update speeds based on control mode
|
||||
if (isManualInputMode) {
|
||||
const maxSpeed = parseFloat(keyboardMaxSpeed.value);
|
||||
const maxRotation = parseFloat(keyboardMaxRotation.value);
|
||||
|
||||
// Combine keyboard and joystick inputs
|
||||
const keyboardX = manualInputVelX;
|
||||
const keyboardY = -manualInputVelY; // Negative because canvas Y axis is inverted
|
||||
const keyboardOmega = manualInputOmega;
|
||||
|
||||
const joystickX = leftJoystick.getX() * maxSpeed;
|
||||
const joystickY = -leftJoystick.getY() * maxSpeed;
|
||||
const joystickOmega = rightJoystick.getX() * maxRotation;
|
||||
|
||||
// Use joystick if active, otherwise use keyboard
|
||||
xSpeed = leftJoystick.active ? joystickX : keyboardX;
|
||||
ySpeed = leftJoystick.active ? joystickY : keyboardY;
|
||||
turnSpeed = rightJoystick.active ? joystickOmega : keyboardOmega;
|
||||
} else {
|
||||
xSpeed = parseFloat(vxSlider.value);
|
||||
ySpeed = -parseFloat(vySlider.value);
|
||||
turnSpeed = parseFloat(omegaSlider.value);
|
||||
}
|
||||
|
||||
// Update module states before drawing the robot
|
||||
// The drive() method will update the gyroHeading internally
|
||||
@ -665,11 +1047,17 @@ function animate() {
|
||||
// Get the actual robot velocity (after scaling to max module speed) for grid animation
|
||||
const actualVelocity = robot.getActualVelocity();
|
||||
|
||||
|
||||
// Update control outputs with actual speeds
|
||||
if (isManualInputMode) {
|
||||
// In manual input mode (keyboard/gamepad), show the current values
|
||||
keyboardMaxSpeedOutput.textContent = `Max: ${keyboardMaxSpeed.value} | Current: ${Math.max(Math.abs(actualVelocity.x), Math.abs(actualVelocity.y)).toFixed(1)}`;
|
||||
keyboardMaxRotationOutput.textContent = `Max: ${keyboardMaxRotation.value} | Current: ${Math.abs(robot.actualTurnSpeed || 0).toFixed(2)}`;
|
||||
} else {
|
||||
// In slider mode, show requested vs actual
|
||||
vxOutput.textContent = `Requested: ${vxSlider.value} | Actual: ${actualVelocity.x.toFixed(2)}`;
|
||||
vyOutput.textContent = `Requested: ${vySlider.value} | Actual: ${-actualVelocity.y.toFixed(2)}`;
|
||||
omegaOutput.textContent = `Requested: ${omegaSlider.value} | Actual: ${robot.actualTurnSpeed.toFixed(2)}`;
|
||||
omegaOutput.textContent = `Requested: ${omegaSlider.value} | Actual: ${(robot.actualTurnSpeed || 0).toFixed(2)}`;
|
||||
}
|
||||
|
||||
// Animate the grid
|
||||
let offsetSpeedDivisor = (100 - gridSquareSize <= 0 ? 1 : 100 - gridSquareSize);
|
||||
@ -683,6 +1071,9 @@ function animate() {
|
||||
drawGrid(ctx, canvas.width * 2, gridSquareSize, xGridOffset, yGridOffset);
|
||||
drawRobot(ctx, robot, robot.gyroHeading);
|
||||
|
||||
leftJoystick.draw();
|
||||
rightJoystick.draw();
|
||||
|
||||
// Do it all over again
|
||||
ctx.restore();
|
||||
requestAnimationFrame(animate);
|
||||
|
||||
16
styles.css
16
styles.css
@ -238,7 +238,7 @@ tr:hover {
|
||||
|
||||
.visualization-area {
|
||||
grid-column: 1 / 2;
|
||||
grid-row: 1 / 3;
|
||||
grid-row: 2 / 4;
|
||||
}
|
||||
|
||||
#swerve-canvas {
|
||||
@ -252,22 +252,22 @@ tr:hover {
|
||||
|
||||
.controls-panel {
|
||||
grid-column: 1 / 2;
|
||||
grid-row: 2 / 3;
|
||||
grid-row: 3 / 4;
|
||||
}
|
||||
|
||||
.config-panel {
|
||||
grid-column: 2 / 3;
|
||||
grid-row: 1 / 2;
|
||||
grid-row: 2 / 3;
|
||||
}
|
||||
|
||||
.module-states {
|
||||
grid-column: 2 / 3;
|
||||
grid-row: 2 / 3;
|
||||
grid-row: 3 / 4;
|
||||
}
|
||||
|
||||
.documentation {
|
||||
grid-column: 1 / 3;
|
||||
grid-row: 4 / 5;
|
||||
grid-row: 1 / 2;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
@ -362,3 +362,9 @@ button:hover {
|
||||
color: var(--text-light);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 768px) {
|
||||
main {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
33
sw.js
Normal file
33
sw.js
Normal file
@ -0,0 +1,33 @@
|
||||
const CACHE_NAME = 'v1';
|
||||
const ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/script.js',
|
||||
'/styles.css',
|
||||
'/manifest.json',
|
||||
'/icons/192.svg',
|
||||
'/icons/512.svg',
|
||||
'/vendor/lucio/graham-scan.mjs'
|
||||
];
|
||||
|
||||
self.addEventListener('install', (e) => {
|
||||
e.waitUntil(
|
||||
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (e) => {
|
||||
e.waitUntil(
|
||||
caches.keys().then(keys =>
|
||||
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
|
||||
)
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (e) => {
|
||||
e.respondWith(
|
||||
caches.match(e.request).then(response => response || fetch(e.request))
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user