diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49bd6e2..5d8eddd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ adds a line under **Unreleased**.
## Unreleased
+- The simulated CodeX now stands upright, its screen facing you, and its
+ accelerometer reads that way (+1 g on y), in front of a softly blurred
+ garden so the board stands out. Three buttons under the view show or hide
+ its controls over it: rotation (a slider and an editable angle, to tenths
+ of a degree, for each of its own axes, with its axes drawn from the
+ accelerometer chip while it shows), ambient light (which the light sensor
+ reads, and which visibly lights the scene), and its buttons (the arrow keys
+ and A and B on the keyboard work too). The screen-only view has a display
+ icon.
+- A lit LED's or NeoPixel's glow in the simulator stays on the light,
+ facing out of the board: no line cuts across it as the camera turns, and
+ none of it shows behind the board.
- The simulated CodeAIR can be moved by hand from the keyboard too: with the
move button on, the arrow keys and Page Up and Page Down slide and lift it
(or the reflector card), Shift with them turns and tips it, and Home sets
diff --git a/sim/tools/showroom-sky.mjs b/sim/tools/showroom-sky.mjs
index c48a2f9..21a78e4 100644
--- a/sim/tools/showroom-sky.mjs
+++ b/sim/tools/showroom-sky.mjs
@@ -1,17 +1,36 @@
// The showroom's sky (CodeX's room, src/sim/view/view.js SHOWROOM_SKY): a
// panorama in sim/assets/showroom/sky.jpg (credited in sim/assets/LICENSE).
-// Run as a script (npm run sim:assets runs it), this copies it to
-// public/sim-assets/env/showroom/sky.jpg, where the site serves it.
+// Run as a script (npm run sim:assets runs it), this writes it out of focus
+// to public/sim-assets/env/showroom/sky.jpg, where the site serves it, so
+// CodeX stands out from the garden's detail. Blurred here, once, rather than
+// in the browser: Three's background blur builds its maps on the graphics
+// chip, which takes most of a minute where the browser draws without one.
+//
+// The panorama wraps round, so it is blurred with its far edges joined: a
+// strip of each side is laid beside the other before the blur, then cut away.
//
// node sim/tools/showroom-sky.mjs
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
+import sharp from 'sharp'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const SOURCE = path.join(ROOT, 'sim/assets/showroom/sky.jpg')
const SERVED = path.join(ROOT, 'public/sim-assets/env/showroom/sky.jpg')
+// Served this wide (half the source's: a blurred sky needs no more), and
+// blurred by this much of its width (a Gaussian's sigma).
+const WIDTH = 2048
+const BLUR = 1 / 300
+const { width, height } = await sharp(SOURCE).metadata()
+const sigma = width * BLUR
+const pad = Math.ceil(sigma * 4)
+const wrapped = await sharp(SOURCE).extend({ left: pad, right: pad, extendWith: 'repeat' }).blur(sigma).toBuffer()
fs.mkdirSync(path.dirname(SERVED), { recursive: true })
-fs.copyFileSync(SOURCE, SERVED)
+await sharp(wrapped)
+ .extract({ left: pad, top: 0, width, height })
+ .resize(WIDTH, WIDTH / 2)
+ .jpeg({ quality: 82, mozjpeg: true })
+ .toFile(SERVED)
console.log('showroom sky', fs.statSync(SERVED).size)
diff --git a/src/i18n/en.js b/src/i18n/en.js
index 5f75da1..b6a529a 100644
--- a/src/i18n/en.js
+++ b/src/i18n/en.js
@@ -774,15 +774,18 @@ You just told a machine what to do, and it listened. Keep going!`,
'sim.stoppedTitle': 'The simulator stopped',
'sim.stoppedDetail': 'Reload the page to start it again.',
'sim.problemTitle': 'The simulator hit a problem',
- 'sim.keysCodex': 'Arrow keys press its direction pad, A and B its buttons; Shift and the arrow keys turn it about its own X and Y axes, Shift with Page Up and Page Down about its Z axis, Home lays it flat again; plus and minus zoom, F shows its screen alone. The Rotate buttons turn it too.',
+ 'sim.keysCodex': 'Arrow keys press its direction pad, A and B its buttons; Shift and the arrow keys turn it about its own X and Y axes, Shift with Page Up and Page Down about its Z axis, Home stands it upright again; plus and minus zoom, F shows its screen alone. The rotation sliders turn it too.',
'sim.rotate.label': 'Rotate CodeX about its own axes',
- 'sim.rotate.title': 'Rotate',
- 'sim.rotate.back': 'Turn back about {axis}',
- 'sim.rotate.on': 'Turn about {axis}',
+ 'sim.rotate.title': 'Rotation',
+ 'sim.rotate.slider': 'Turn about {axis}',
+ 'sim.rotate.degrees': 'Degrees about {axis}',
+ 'sim.light.title': 'Ambient light',
+ 'sim.light.value': '{lux} lux',
+ 'sim.pad.note': 'Your keyboard works too: the arrow keys and A and B, once you click the CodeX view.',
'sim.worldAxes': 'World axes',
'sim.cameraView': 'CodeAIR’s camera',
'sim.lcdLabel': 'The CodeX screen',
- 'sim.rotate.reset': 'Reset',
+ 'sim.rotate.reset': 'Upright',
'sim.keys3d': 'Arrow keys turn or move the camera, plus and minus zoom.',
'sim.viewLabel': 'Simulated {device}. {keys}',
'sim.ready': 'Simulator ready. Press Run!',
@@ -818,8 +821,10 @@ You just told a machine what to do, and it listened. Keep going!`,
'simPanel.courseTitle': 'A line course of black tape on the floor',
'simPanel.course': 'Line course',
'simPanel.noCourse': 'No course',
- 'simPanel.lightTitle': 'Light on the sensor (lux)',
'simPanel.light': 'Light on the sensor, lux',
+ 'simPanel.rotateShow': 'Rotation: turn CodeX about its own axes',
+ 'simPanel.lightShow': 'Ambient light: how bright the room is',
+ 'simPanel.buttonsShow': "CodeX's buttons",
'simPanel.speed': 'Simulation speed',
'simPanel.speedValue': '{speed}×',
'simPanel.buttons': "The board's buttons (hold Space or Enter)",
@@ -878,7 +883,7 @@ You just told a machine what to do, and it listened. Keep going!`,
'codex.down': 'Down',
'codex.buttonA': 'Button A',
'codex.buttonB': 'Button B',
- 'codex.fullTitle': 'Screen only: the CodeX screen filling the view (F, or Esc to go back)',
+ 'codex.fullTitle': 'Display: the CodeX screen alone, filling the view (F, or Esc to go back)',
// The simulated board in words, for a screen reader
'compass.east': 'east',
diff --git a/src/i18n/es.js b/src/i18n/es.js
index 31232dd..f952d26 100644
--- a/src/i18n/es.js
+++ b/src/i18n/es.js
@@ -749,15 +749,18 @@ Le acabas de decir a una máquina qué hacer, y te hizo caso. ¡Sigue así!`,
'sim.stoppedTitle': 'El simulador se detuvo',
'sim.stoppedDetail': 'Vuelve a cargar la página para iniciarlo otra vez.',
'sim.problemTitle': 'El simulador tuvo un problema',
- 'sim.keysCodex': 'Las flechas presionan su control de dirección, A y B sus botones; Mayús y las flechas lo giran sobre sus propios ejes X e Y, Mayús con Re Pág y Av Pág sobre su eje Z, Inicio lo deja plano otra vez; más y menos hacen zoom, F muestra solo su pantalla. Los botones de Girar también lo giran.',
+ 'sim.keysCodex': 'Las flechas presionan su control de dirección, A y B sus botones; Mayús y las flechas lo giran sobre sus propios ejes X e Y, Mayús con Re Pág y Av Pág sobre su eje Z, Inicio la vuelve a poner de pie; más y menos hacen zoom, F muestra solo su pantalla. Los controles deslizantes de rotación también la giran.',
'sim.rotate.label': 'Girar la CodeX sobre sus propios ejes',
- 'sim.rotate.title': 'Girar',
- 'sim.rotate.back': 'Girar hacia atrás sobre {axis}',
- 'sim.rotate.on': 'Girar sobre {axis}',
+ 'sim.rotate.title': 'Rotación',
+ 'sim.rotate.slider': 'Girar sobre {axis}',
+ 'sim.rotate.degrees': 'Grados sobre {axis}',
+ 'sim.light.title': 'Luz ambiente',
+ 'sim.light.value': '{lux} lux',
+ 'sim.pad.note': 'Tu teclado también funciona: las flechas y A y B, después de hacer clic en la vista de la CodeX.',
'sim.worldAxes': 'Ejes del mundo',
'sim.cameraView': 'Cámara del CodeAIR',
'sim.lcdLabel': 'La pantalla de la CodeX',
- 'sim.rotate.reset': 'Restablecer',
+ 'sim.rotate.reset': 'De pie',
'sim.keys3d': 'Las flechas giran o mueven la cámara, más y menos hacen zoom.',
'sim.viewLabel': '{device} simulado. {keys}',
'sim.ready': 'Simulador listo. ¡Presiona Ejecutar!',
@@ -793,8 +796,10 @@ Le acabas de decir a una máquina qué hacer, y te hizo caso. ¡Sigue así!`,
'simPanel.courseTitle': 'Un recorrido de cinta negra en el piso',
'simPanel.course': 'Recorrido',
'simPanel.noCourse': 'Sin recorrido',
- 'simPanel.lightTitle': 'Luz sobre el sensor (lux)',
'simPanel.light': 'Luz sobre el sensor, lux',
+ 'simPanel.rotateShow': 'Rotación: girar la CodeX sobre sus propios ejes',
+ 'simPanel.lightShow': 'Luz ambiente: qué tan iluminada está la sala',
+ 'simPanel.buttonsShow': 'Los botones de la CodeX',
'simPanel.speed': 'Velocidad de simulación',
'simPanel.speedValue': '{speed}×',
'simPanel.buttons': 'Los botones de la placa (mantén presionado Espacio o Enter)',
@@ -853,7 +858,7 @@ Le acabas de decir a una máquina qué hacer, y te hizo caso. ¡Sigue así!`,
'codex.down': 'Abajo',
'codex.buttonA': 'Botón A',
'codex.buttonB': 'Botón B',
- 'codex.fullTitle': 'Solo la pantalla: la pantalla de la CodeX llenando la vista (F, o Esc para volver)',
+ 'codex.fullTitle': 'Pantalla: solo la pantalla de la CodeX, llenando la vista (F, o Esc para volver)',
// La placa simulada en palabras, para un lector de pantalla
'compass.east': 'este',
diff --git a/src/sim/sim-device.js b/src/sim/sim-device.js
index 27923d3..ebd59a3 100644
--- a/src/sim/sim-device.js
+++ b/src/sim/sim-device.js
@@ -235,7 +235,11 @@ export class SimDevice extends EventTarget {
return this._resetting
}
orient(q) { this._post({ t: 'input', what: 'orient', q }) }
- setLight(lux) { this._post({ t: 'input', what: 'light', lux }) }
+ // The light on CodeX's sensor, in lux: the program reads it, and the view lights the scene to match.
+ setLight(lux) {
+ this._post({ t: 'input', what: 'light', lux })
+ this.view?.setLight?.(lux)
+ }
// CodeAIR in a hand (world/codeair.js hold): a pose it follows, any of
// { x, y, z, heading, roll, pitch }; release lets go.
hold(pose) { this._post({ t: 'input', what: 'hold', pose }) }
diff --git a/src/sim/sim-panel.js b/src/sim/sim-panel.js
index b239711..b1f88df 100644
--- a/src/sim/sim-panel.js
+++ b/src/sim/sim-panel.js
@@ -6,6 +6,7 @@ import { COURSES } from './world/courses.js'
import { KINDS, ROOMS, CAMERA_MODES } from './kinds.js'
import { holdButton } from './hold-button.js'
import { SettingsPanel } from './settings-panel.js'
+import { AXIS_COLORS } from './view/axis-colors.js'
import { t, tHtml } from '../i18n/index.js'
const SPEEDS = [0.5, 1, 2, 4]
@@ -23,6 +24,19 @@ const PHOTO_ICON = icon('M12 8.8a3.2 3.2 0 1 0 0 6.4 3.2 3.2 0 1 0 0-6.4zM9 2L7.
const MOVE_ICON = icon('M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z')
const CARD_ICON = icon('M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 12H5V7h14v10z')
const CENTER_ICON = icon('M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-7 7H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z')
+// CodeX's overlays (rotation, ambient light, its buttons) and its screen alone
+// (Material Icons, Apache License 2.0: 360, wb_sunny, gamepad, desktop_windows).
+const ROTATE_ICON = icon('M12 7C6.48 7 2 9.24 2 12c0 2.24 2.94 4.13 7 4.77V20l4-4-4-4v2.73c-3.15-.56-5-1.9-5-2.73 0-1.06 3.04-3 8-3s8 1.94 8 3c0 .73-1.46 1.89-4 2.53v2.05c3.53-.77 6-2.53 6-4.58 0-2.76-4.48-5-10-5z')
+const LIGHT_ICON = icon('M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z')
+const PAD_ICON = icon('M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z')
+const DISPLAY_ICON = icon('M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z')
+
+// The light on the sensor as CodeX starts (world/codex.js lux).
+const ROOM_LUX = 250
+// The overlays CodeX's view opens with: its buttons, which a program may be waiting for.
+const OVERLAYS_SHOWN = ['buttons']
+// Degrees as the rotation overlay shows them: to tenths.
+const deg = (v) => (Math.round(Number(v) * 10) / 10 || 0).toFixed(1)
// A board's two buttons (BTN 0 and 1), as the panel and the boards page show them.
export function boardButtonsHtml() {
@@ -42,9 +56,33 @@ export class SimPanel {
this.sim = sim
// title and aria-label from one key
const both = (key) => `title="${tHtml(key)}" aria-label="${tHtml(key)}"`
+ const axisRow = (a) => `
+ ${a}
+
+ °
+
`
host.innerHTML = `
-
+
+
+
+
${tHtml('sim.rotate.title')}
+ ${['X', 'Y', 'Z'].map(axisRow).join('')}
+
+
+
+
${tHtml('sim.light.title')}
+
+
+
+
+
+
+
${codexButtonsHtml()}
+
${tHtml('sim.pad.note')}
+
+
+
@@ -62,8 +100,11 @@ export class SimPanel {
-
-
+
+
+
+
+
@@ -71,10 +112,6 @@ export class SimPanel {
${boardButtonsHtml()}
-
- ${codexButtonsHtml()}
-
-
${tHtml('simPanel.moreBoards')}
@@ -113,6 +150,44 @@ export class SimPanel {
q('.sim-reset').addEventListener('click', () => sim.reset())
+ // CodeX's overlays over the view, each shown and hidden by its button in the bar
+ for (const b of host.querySelectorAll('.sim-tog')) b.addEventListener('click', () => this.showOverlay(b.dataset.ov, b.getAttribute('aria-pressed') !== 'true'))
+ for (const name of OVERLAYS_SHOWN) this.showOverlay(name, true)
+
+ // The ambient light: what the sensor reads, and the scene lit to match.
+ const light = q('.sim-light')
+ light.addEventListener('input', () => this.setLight(Number(light.value)))
+
+ // Rotation: a slider and a number for each of CodeX's own axes, turning it
+ // from upright; the keys, and Upright, turn it too and the overlay follows.
+ const rot = q('.sim-ov-rotate')
+ const field = (cls, a) => rot.querySelector(`.${cls}[data-axis="${a}"]`)
+ const turn = () => sim.view?.setAngles?.(Object.fromEntries(['X', 'Y', 'Z'].map((a) => [a, Number(field('sim-rot-range', a).value)])))
+ rot.addEventListener('input', (e) => {
+ const a = e.target.dataset.axis
+ if (!a) return
+ if (e.target.classList.contains('sim-rot-range')) field('sim-rot-num', a).value = deg(e.target.value)
+ else {
+ // a number being typed turns it as soon as it reads as one, in range
+ const v = Number(e.target.value)
+ if (e.target.value === '' || !Number.isFinite(v) || v < -180 || v > 180) return
+ field('sim-rot-range', a).value = v
+ }
+ turn()
+ })
+ rot.addEventListener('change', (e) => {
+ if (!e.target.classList.contains('sim-rot-num')) return
+ const a = e.target.dataset.axis
+ const v = Number(e.target.value)
+ const ok = e.target.value !== '' && Number.isFinite(v)
+ const to = ok ? Math.min(180, Math.max(-180, v)) : Number(field('sim-rot-range', a).value)
+ field('sim-rot-range', a).value = to
+ e.target.value = deg(to)
+ turn()
+ })
+ q('.sim-rotate-reset').addEventListener('click', () => sim.view?.resetOrient?.())
+ this.stage.addEventListener('boardorient', (e) => this.showAngles(e.detail))
+ this.rotFields = (a) => [field('sim-rot-range', a), field('sim-rot-num', a)]
// What CodeAIR's camera sees, in a corner of the view: shown and hidden
// here, and kept as the student left it for the next drone.
this.cameraView = false
@@ -122,7 +197,6 @@ export class SimPanel {
camview.setAttribute('aria-pressed', String(this.cameraView))
this.showCameraView()
})
- q('.sim-light').addEventListener('input', () => sim.setLight(Number(q('.sim-light').value)))
// CodeAIR in the student's hand: move arrows and rotation rings over it,
// and the ranger card its rangefinders see. Each kept as the student left
@@ -151,7 +225,10 @@ export class SimPanel {
this.stage.addEventListener('lcdview', (e) => q('.sim-full').setAttribute('aria-pressed', String(e.detail)))
sim.addEventListener('state', () => this.refresh())
- sim.addEventListener('device', () => this.refresh())
+ sim.addEventListener('device', () => {
+ this.newBoard()
+ this.refresh()
+ })
// A bar too long for one line (a phone) shows its first, and a button for the rest.
this.more = q('.sim-more')
@@ -179,6 +256,40 @@ export class SimPanel {
}).observe(this.bar)
}
+ /** Show or hide one of CodeX's overlays ('rotate', 'light' or 'buttons'); CodeX's own axes show with rotation. */
+ showOverlay(name, on) {
+ this.stage.querySelector(`.sim-ov-${name}`).hidden = !on
+ this.bar.querySelector(`.sim-tog[data-ov="${name}"]`).setAttribute('aria-pressed', String(on))
+ if (name !== 'rotate') return
+ this.sim.view?.showAxes?.(on)
+ if (on && this.sim.view?.angles) this.showAngles(this.sim.view.angles())
+ }
+
+ /** The rotation overlay showing angles (degrees, { X, Y, Z }); a number being typed in is left as it is. */
+ showAngles(angles) {
+ for (const [a, v] of Object.entries(angles)) {
+ const [range, num] = this.rotFields(a)
+ range.value = v
+ if (document.activeElement !== num) num.value = deg(v)
+ }
+ }
+
+ /** The light on CodeX's sensor, in lux, and its overlay showing it. */
+ setLight(lux) {
+ this.sim.setLight(lux)
+ this.stage.querySelector('.sim-light').value = lux
+ this.stage.querySelector('.sim-light-out').textContent = t('sim.light.value', { lux })
+ }
+
+ /** A board started afresh: upright in the room's light, the overlays as the student left them. */
+ newBoard() {
+ if (this.sim.targetId !== 'codex') return
+ this.stage.querySelector('.sim-light').value = ROOM_LUX
+ this.stage.querySelector('.sim-light-out').textContent = t('sim.light.value', { lux: ROOM_LUX })
+ this.showAngles({ X: 0, Y: 0, Z: 0 })
+ this.sim.view?.showAxes?.(!this.stage.querySelector('.sim-ov-rotate').hidden)
+ }
+
/** On a phone, one line of the bar or all of it: folded when it wraps, unless the student opened it. */
fold() {
const bar = this.bar
@@ -206,7 +317,7 @@ export class SimPanel {
const on = this.sim.isConnected
this.stage.dataset.off = String(!on)
this.bar.hidden = !on
- for (const el of this.bar.querySelectorAll('[data-for]')) el.hidden = !el.dataset.for.split(' ').includes(this.sim.targetId)
+ for (const el of [...this.bar.querySelectorAll('[data-for]'), this.stage.querySelector('.sim-ovs')]) el.hidden = !el.dataset.for.split(' ').includes(this.sim.targetId)
this.courseSelect.disabled = this.roomSelect.disabled = this.sim.state === 'running'
if (on) this.roomSelect.value = this.sim.room ?? KINDS[this.sim.targetId]?.env
if (!on) this.settings.close({ focus: false })
diff --git a/src/sim/sim.css b/src/sim/sim.css
index 995fcb3..8c96393 100644
--- a/src/sim/sim.css
+++ b/src/sim/sim.css
@@ -37,8 +37,10 @@
/* There, the board's own buttons come first, on the line that shows: a running program waits for them.
CodeAIR's camera, move and card buttons too, beside them. */
@media (max-width: 600px) {
- .sim-bar .sim-buttons, .sim-bar .sim-camgroup { order: -1; }
+ .sim-bar .sim-buttons, .sim-bar .sim-toggles, .sim-bar .sim-camgroup { order: -1; }
}
+.sim-tog[aria-pressed='true'] { background: var(--sky); color: #fff; }
+.sim-tog, .sim-full { display: inline-flex; padding: 2px; }
/* The settings panel (settings-panel.js), over the view's lower right. */
.sim-settings {
@@ -94,27 +96,62 @@
.sim-hands[aria-pressed='true'], .sim-cardtog[aria-pressed='true'] { background: var(--sky); color: #fff; }
.sim-group input[type='range'] { width: 72px; }
-/* CodeX's rotation widget, over the view's lower left: a row for each of its
- own axes, a button to turn it each way, and Reset. */
-.sim-rotate {
- position: absolute; left: 8px; bottom: 8px; z-index: 2;
+/* CodeX's overlays (sim-panel.js), shown and hidden from the bar: along the
+ view's foot, rotation and light at the left, the buttons at the right; on
+ a narrow view they wrap upward, the first on the bottom line. Between
+ them the view stays free to drag the camera round. Over the screen alone
+ too (.sim-lcd), where the buttons are still wanted. */
+.sim-ovs {
+ position: absolute; left: 8px; right: 8px; bottom: 8px; z-index: 4;
+ display: flex; flex-wrap: wrap-reverse; align-items: flex-end; gap: 6px;
+ pointer-events: none;
+}
+.sim-ov {
+ pointer-events: auto; box-sizing: border-box; max-width: 100%;
display: grid; gap: 4px; padding: 6px 8px; border-radius: var(--r-sm);
- background: rgba(255, 255, 255, 0.9); color: var(--ink); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
- font: 13px var(--font-body, system-ui, sans-serif); user-select: none; touch-action: none;
-}
-.sim-rotate-title { font-weight: 700; text-align: center; }
-.sim-rotate-row { display: grid; grid-template-columns: 32px 20px 32px; align-items: center; gap: 4px; }
-.sim-rotate-axis { font-weight: 800; font-size: 15px; text-align: center; }
-.sim-rotate-btn { height: 30px; padding: 0; font-size: 18px; line-height: 1; }
-.sim-rotate-reset { padding: 3px 6px; }
-.sim-rotate :focus-visible { outline: 3px solid var(--sky); outline-offset: 1px; }
-/* A short view (a phone's): the widget in one row along the bottom, so the
- middle of the view stays free to drag the camera round. */
+ background: rgba(255, 255, 255, 0.92); color: var(--ink); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
+ font: 13px var(--font-body, system-ui, sans-serif);
+}
+.sim-ovs[hidden], .sim-ov[hidden] { display: none; }
+.sim-ov-title { font-weight: 700; }
+.sim-ov :focus-visible { outline: 3px solid var(--sky); outline-offset: 1px; }
+.sim-ov input[type='range'] { width: 100%; min-width: 0; margin: 0; }
+
+/* Rotation: a row for each axis, its letter in its colour, a slider and the degrees. */
+.sim-ov-rotate { width: 290px; }
+.sim-rot-row { display: grid; grid-template-columns: 14px minmax(0, 1fr) 62px 8px; align-items: center; gap: 6px; }
+.sim-rot-axis { font-weight: 800; font-size: 15px; text-align: center; }
+.sim-rot-num {
+ width: 100%; box-sizing: border-box; font: 13px var(--font-mono); text-align: right;
+ border: 1px solid var(--line-strong); border-radius: var(--r-sm); padding: 2px 4px; background: var(--paper);
+}
+.sim-rotate-reset { justify-self: start; }
+
+/* Ambient light: its slider and the lux. */
+.sim-ov-light { width: 220px; }
+.sim-light-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; }
+.sim-light-out { font: 13px var(--font-mono); min-width: 7ch; text-align: right; }
+
+/* The buttons: big enough for a finger, with the keyboard's note under them. */
+.sim-ov-buttons { margin-left: auto; width: max-content; }
+.sim-ov-keys { display: flex; align-items: center; gap: 6px; }
+.sim-ov-keys .cx-pad { display: grid; grid-template-columns: repeat(3, 36px); grid-template-rows: repeat(3, 30px); gap: 2px; margin: 0; }
+.sim-ov-keys .cx-btn { min-width: 36px; min-height: 30px; padding: 0; touch-action: none; }
+.sim-ov-keys .cx-U { grid-area: 1 / 2; }
+.sim-ov-keys .cx-L { grid-area: 2 / 1; }
+.sim-ov-keys .cx-R { grid-area: 2 / 3; }
+.sim-ov-keys .cx-D { grid-area: 3 / 2; }
+.sim-ov-keys .cx-A, .sim-ov-keys .cx-B { min-width: 40px; min-height: 40px; }
+.sim-ov-note { margin: 0; max-width: 220px; color: var(--ink-soft); font-size: 11px; line-height: 1.3; }
+
+/* A short view (a phone's): the overlays tighter, so CodeX still shows over them. */
@container sim-view (max-height: 420px) {
- .sim-rotate { display: flex; align-items: center; gap: 6px; padding: 4px 6px; right: 8px; width: max-content; max-width: calc(100% - 16px); }
- .sim-rotate-title { display: none; }
- .sim-rotate-row { grid-template-columns: 28px 14px 28px; gap: 2px; }
- .sim-rotate-btn { height: 28px; font-size: 16px; }
+ .sim-ov { padding: 4px 6px; gap: 2px; }
+ .sim-ov-title, .sim-ov-note { display: none; }
+ .sim-ov-keys .cx-pad { display: flex; gap: 2px; }
+ .sim-ov-keys .cx-btn, .sim-ov-keys .cx-A, .sim-ov-keys .cx-B { min-width: 34px; min-height: 32px; }
+ .sim-rot-row { gap: 4px; }
+ .sim-ov-rotate { width: 260px; }
}
/* The name over the room's axes in the view's upper right (view.js _compass). */
diff --git a/src/sim/view/axes.js b/src/sim/view/axes.js
index f182401..d9ba153 100644
--- a/src/sim/view/axes.js
+++ b/src/sim/view/axes.js
@@ -2,8 +2,9 @@
// blue, as most 3D tools draw them) and a text label that always faces the
// camera.
import * as THREE from 'three'
+import { AXIS_COLORS } from './axis-colors.js'
-export const AXIS_COLORS = { X: '#e5484d', Y: '#30a46c', Z: '#3e7bfa' }
+export { AXIS_COLORS }
// `text` on a label `size` tall, drawn over everything: in `color` on a pale
// disc (the board's own axes), or with `pill`, in white on a pill of `color`
diff --git a/src/sim/view/axis-colors.js b/src/sim/view/axis-colors.js
new file mode 100644
index 0000000..875e686
--- /dev/null
+++ b/src/sim/view/axis-colors.js
@@ -0,0 +1,4 @@
+// A colour for each axis (X red, Y green, Z blue, as most 3D tools draw
+// them): the axes drawn in the view (axes.js) and the rotation overlay's
+// (sim-panel.js), which must not load Three to know them.
+export const AXIS_COLORS = { X: '#e5484d', Y: '#30a46c', Z: '#3e7bfa' }
diff --git a/src/sim/view/codex-figure.js b/src/sim/view/codex-figure.js
index 493fe21..05df9fd 100644
--- a/src/sim/view/codex-figure.js
+++ b/src/sim/view/codex-figure.js
@@ -5,15 +5,16 @@
// The model (codex.glb, built from sim/assets/CodeX.glb) is in millimetres,
// face up (+y), the top of the board toward -z, its right toward +x: the
// board's own frame (world/codex.js), so its orientation, a quaternion from
-// the snapshot, turns it as it is. Unturned it lies flat, face up, and the
-// accelerometer reads what that pose reads. The figure's root is the
-// board's centre, 10 cm above the floor.
+// the snapshot, turns it as it is. The world starts it upright, face to the
+// student (world/codex.js UPRIGHT), and the accelerometer reads what that
+// pose reads. The figure's root is the board's centre, 10 cm above the floor.
//
-// Its own axes, as the silkscreen names them, are drawn on it and turn with
-// it: X to its right, Y down the board, Z out of its face; the rotation
-// widget (view.js) turns it about them.
+// Its own axes, as the silkscreen names them, can be drawn on it (showAxes),
+// from the centre of its accelerometer chip, turning with it: X to its
+// right, Y down the board, Z out of its face. The rotation overlay
+// (sim-panel.js, view.js setAngles) turns it about them.
import * as THREE from 'three'
-import { Light, glowSprite, neoPixel, wear } from './led.js'
+import { Light, glowDome, neoPixel, wear } from './led.js'
import { Keys } from './keys.js'
import { Parts, loadParts } from './parts.js'
import { AXIS_COLORS, textSprite } from './axes.js'
@@ -45,9 +46,10 @@ const LED_AB_OVER = 1.04 // the copy a little larger than the part, o
const LED_RED = new THREE.Color(1, 0.07, 0.03)
// The board's own axes as drawn on it: the silkscreen's X, Y and Z, each an
-// arrow this long (m) from the board's centre, in its colour (view.js
-// AXIS_COLORS, the rotation widget's), and the model's direction for each
-// (X right, Y down the board, Z out of the face).
+// arrow this long (m) from the accelerometer's centre (the model's
+// Accelerometer part), in its colour (axes.js AXIS_COLORS, the rotation
+// overlay's), and the model's direction for each (X right, Y down the board,
+// Z out of the face).
const AXIS_LEN = 0.055
export const DEVICE_AXES = { X: [1, 0, 0], Y: [0, 0, 1], Z: [0, 1, 0] }
@@ -156,10 +158,13 @@ export class CodeXFigure {
this._axes()
}
- // The board's own axes, drawn on it: an arrow and a label for each,
- // turning with it, over everything so the board never hides them.
+ // The board's own axes, drawn on it from the accelerometer's centre: an
+ // arrow and a label for each, turning with it, over everything so the
+ // board never hides them. Hidden until showAxes.
_axes() {
this.axes = new THREE.Group()
+ this.axes.visible = false
+ this.axes.position.copy(this.chipCentre())
for (const [name, dir] of Object.entries(DEVICE_AXES)) {
const color = new THREE.Color(AXIS_COLORS[name])
const arrow = new THREE.ArrowHelper(new THREE.Vector3(...dir), new THREE.Vector3(), AXIS_LEN, color, 0.009, 0.005)
@@ -174,27 +179,42 @@ export class CodeXFigure {
this.turn.add(this.axes)
}
+ /** The accelerometer chip's centre, in the turned board's frame (its box in the parts list, parts.js). */
+ chipCentre() {
+ const chip = this.parts.boxes.find((b) => b.name === 'Accelerometer')
+ if (!chip) return new THREE.Vector3()
+ this.root.updateMatrixWorld(true)
+ return this.turn.worldToLocal(this.parts.model.localToWorld(chip.box.getCenter(new THREE.Vector3())))
+ }
+
+ /** The board's own axes drawn on it, or not. */
+ showAxes(on) {
+ if (this.axes) this.axes.visible = on
+ }
+
// A light on the board: the part itself lit in the program's colour (its
// own material, the look in led.js), and a glow over it (`glow` mm
// across) that shows at a distance.
_light(mesh, glow) {
const mat = mesh.material.clone()
mesh.material = mat
- const halo = glowSprite(glow)
+ const halo = glowDome(glow)
halo.position.copy(centre(mesh)).add(new THREE.Vector3(0, 1.2, 0))
mesh.parent.add(halo)
return new Light(mat, halo)
}
- // Where the camera starts: in front of the board lying flat and well above
- // it, a little to the right, as a student looks down at a CodeX on the
- // desk, near enough for the board and its axes (`size` across) to fill the
- // view and its screen to be read.
+ // Where the camera starts: in front of the upright board's face, looking
+ // north (into the room's Y axis), a little above, as a student holds a
+ // CodeX to read it, near enough for the board and its axes (`size` across)
+ // to fill the view and its screen to be read. It looks a little below the
+ // board's centre, so the board sits high, clear of the overlays along the
+ // view's foot.
home() {
return {
- target: new THREE.Vector3(0, CODEX_HEIGHT, 0.004),
- from: new THREE.Vector3(0.15, 0.85, 0.5).normalize(),
- size: 0.17,
+ target: new THREE.Vector3(0, CODEX_HEIGHT - 0.02, 0),
+ from: new THREE.Vector3(0.04, 0.18, 1).normalize(),
+ size: 0.2,
minDistance: 0.05,
}
}
diff --git a/src/sim/view/led.js b/src/sim/view/led.js
index 259ddc4..3182cea 100644
--- a/src/sim/view/led.js
+++ b/src/sim/view/led.js
@@ -19,6 +19,7 @@
// CodeSpace's simulator does the same in Babylon: its emissive colour is
// the program's colour as is, with a glow layer of that colour around it.
import * as THREE from 'three'
+import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'
const LENS = new THREE.Color(0.956, 0.921, 0.721)
const GLOW = 0.85 // the glow's strength at its middle, lit full
@@ -133,17 +134,82 @@ export function hot(c, k) {
}
const WHITE = new THREE.Color(1, 1, 1)
-// A glow `size` across (in its parent's units): a soft disc of a light's
-// colour, laid over the scene.
-export function glowSprite(size) {
- const halo = new THREE.Sprite(new THREE.SpriteMaterial({
- map: haloTexture(), transparent: true, depthWrite: false, toneMapped: false,
- }))
+// A glow `size` across (in its parent's units): a half-sphere of a light's
+// colour on the light, fixed to it and facing out of it (its +y, the way
+// the light shines), laid over the scene. How strong it is along each line
+// of sight comes from how near that line passes the light's centre, on the
+// side it shines to: full over the light, fading to nothing at the dome's
+// edge, so it has no edge or seam to see from any side, and nothing of it
+// lies behind the surface the light sits on. Seen from behind that surface,
+// it fades out. Its material's `color` and `opacity` are the glow's (Light).
+export function glowDome(size) {
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { glowColor: { value: new THREE.Color(1, 1, 1) }, glowOpacity: { value: 1 } },
+ vertexShader: GLOW_VERTEX,
+ fragmentShader: GLOW_FRAGMENT,
+ transparent: true, depthWrite: false, side: THREE.BackSide, toneMapped: false,
+ })
+ mat.color = mat.uniforms.glowColor.value
+ const halo = new THREE.Mesh(domeGeometry(), mat)
+ halo.onBeforeRender = () => { mat.uniforms.glowOpacity.value = mat.opacity }
halo.scale.setScalar(size)
halo.userData.realism = 'effects' // drawn at the levels that have them (realism.js)
return halo
}
+// The dome: a half-sphere, radius 1/2 (so `size` across), over +y, closed
+// by a disc at its base, facing out. Its inside is drawn (BackSide): each
+// line of sight through it once, its far side, from any angle and from
+// inside it too.
+let dome = null
+function domeGeometry() {
+ if (dome) return dome
+ const cap = new THREE.SphereGeometry(0.5, 24, 12, 0, Math.PI * 2, 0, Math.PI / 2)
+ const base = new THREE.CircleGeometry(0.5, 24).rotateX(Math.PI / 2)
+ dome = mergeGeometries([cap, base])
+ return dome
+}
+
+// In the world: the light's centre and its facing (the dome's +y), and its
+// radius; the fragment where it is.
+const GLOW_VERTEX = `
+varying vec3 vWorld;
+varying vec3 vCentre;
+varying vec3 vNormal;
+varying float vRadius;
+void main() {
+ vec4 world = modelMatrix * vec4(position, 1.0);
+ vWorld = world.xyz;
+ vCentre = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
+ vNormal = normalize(mat3(modelMatrix) * vec3(0.0, 1.0, 0.0));
+ vRadius = 0.5 * length(mat3(modelMatrix) * vec3(1.0, 0.0, 0.0));
+ gl_Position = projectionMatrix * viewMatrix * world;
+}`
+
+// Along the line of sight: its point nearest the light's centre on the side
+// the light faces (where it crosses the light's surface, if its nearest is
+// behind it); the glow falls off from the centre as the halo always has, to
+// nothing at the dome's radius, and fades out as the eye goes behind.
+const GLOW_FRAGMENT = `
+uniform vec3 glowColor;
+uniform float glowOpacity;
+varying vec3 vWorld;
+varying vec3 vCentre;
+varying vec3 vNormal;
+varying float vRadius;
+void main() {
+ vec3 ray = normalize(vWorld - cameraPosition);
+ vec3 p = cameraPosition + ray * dot(vCentre - cameraPosition, ray);
+ float across = dot(vNormal, ray);
+ if (dot(p - vCentre, vNormal) < 0.0 && abs(across) > 1e-5) p = cameraPosition + ray * (dot(vCentre - cameraPosition, vNormal) / across);
+ float d = clamp(length(p - vCentre) / vRadius, 0.0, 1.0);
+ float a = 1.0 - smoothstep(0.0, 1.0, d);
+ a *= a * (1.0 + 0.6 * (1.0 - d));
+ a *= smoothstep(-0.05, 0.25, dot(normalize(cameraPosition - vCentre), vNormal));
+ gl_FragColor = vec4(glowColor, clamp(a, 0.0, 1.0) * glowOpacity);
+ #include
+}`
+
export class Led extends Light {
// size [x, y, z] in the parent's units; glow: the halo's width there;
// facing: 1 for an LED on a board's top, -1 for one on its underside;
@@ -154,7 +220,8 @@ export class Led extends Light {
color: LENS, transparent: true, opacity: 0.8, roughness: 0.35, metalness: 0,
emissive: 0x000000, visible: !clear,
})
- const halo = glowSprite(glow)
+ const halo = glowDome(glow)
+ if (facing < 0) halo.rotation.x = Math.PI // facing down, out of the underside
super(mat, halo, LENS, strength)
this.color.set(color)
this.mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat)
@@ -328,21 +395,3 @@ export function reflect(object, env) {
}
})
}
-
-let halo = null
-export function haloTexture() {
- if (halo) return halo
- const c = document.createElement('canvas')
- c.width = c.height = 64
- const g = c.getContext('2d')
- const grad = g.createRadialGradient(32, 32, 0, 32, 32, 32)
- // full over the light, falling off softly: a tint that reads as its glow
- grad.addColorStop(0, 'rgba(255,255,255,1)')
- grad.addColorStop(0.2, 'rgba(255,255,255,0.85)')
- grad.addColorStop(0.5, 'rgba(255,255,255,0.35)')
- grad.addColorStop(1, 'rgba(255,255,255,0)')
- g.fillStyle = grad
- g.fillRect(0, 0, 64, 64)
- halo = new THREE.CanvasTexture(c)
- return halo
-}
diff --git a/src/sim/view/view.js b/src/sim/view/view.js
index ff62aad..09c60a1 100644
--- a/src/sim/view/view.js
+++ b/src/sim/view/view.js
@@ -12,7 +12,8 @@ import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment
import { CodeBotFigure } from './codebot-figure.js'
import { CodeAIRFigure } from './codeair-figure.js'
import { CodeXFigure, DEVICE_AXES } from './codex-figure.js'
-import { AXIS_COLORS, worldAxes } from './axes.js'
+import { UPRIGHT } from '../world/codex.js'
+import { worldAxes } from './axes.js'
import { t } from '../../i18n/index.js'
import { courseMesh } from './course-mesh.js'
import { CameraRig } from './camera-rig.js'
@@ -25,7 +26,8 @@ const FIGURES = { codebot: CodeBotFigure, codeair: CodeAIRFigure, codex: CodeXFi
const SKY = 0xdfe8ef
// The showroom's sky: a panorama in sim-assets/ (equirectangular, its
// source in sim/assets/showroom/, sim/tools/showroom-sky.mjs), or null for
-// the plain sky drawn here. A Chinese garden, after CodeSpace's Sumo Garden.
+// the plain sky drawn here. A Chinese garden, after CodeSpace's Sumo Garden,
+// out of focus so CodeX stands out from it (blurred as it is built).
const SHOWROOM_SKY = 'env/showroom/sky.jpg'
// Half the showroom's mat (m): the grid under the board, the garden round it.
const MAT = 0.15
@@ -45,9 +47,11 @@ export class SimView {
// then no longer takes; with fullScreen, F shows the board's screen alone
// (lcdView) and F or Esc goes back. With
// `onOrient(q)` too (a quaternion [w, x, y, z], world/codex.js orient), the
- // rotation widget over the view turns the board about its own X, Y and Z
- // axes, as do Shift and the arrow keys (X and Y) and Shift with Page Up and
- // Page Down (Z), 15 degrees a press; Home sets it back flat, face up.
+ // board turns: to angles about its own X, Y and Z axes (setAngles, the
+ // panel's rotation overlay), and by Shift and the arrow keys (X and Y) and
+ // Shift with Page Up and Page Down (Z), 15 degrees a press; Home stands it
+ // upright again. A turn not asked for by setAngles tells the page with a
+ // `boardorient` event from the view's host (detail: its angles).
// `onPick(name)`: a click on a board names the part it lands on (parts.js).
// `onOrbit()`: the student has turned the camera 45 degrees, by drag or
// key, in all since the last time (a mission's `orbit` event).
@@ -91,10 +95,11 @@ export class SimView {
this.scene = new THREE.Scene()
this.scene.background = new THREE.Color(SKY)
- this.scene.add(new THREE.HemisphereLight(0xffffff, 0x6b5b4b, 1.6))
- const sun = new THREE.DirectionalLight(0xffffff, 1.6)
+ const sky = new THREE.HemisphereLight(0xffffff, 0x6b5b4b, LIGHT)
+ const sun = new THREE.DirectionalLight(0xffffff, LIGHT)
sun.position.set(3, 8, 2)
- this.scene.add(sun)
+ this.scene.add(sky, sun)
+ this.lights = [sky, sun]
this.camera = new THREE.PerspectiveCamera(50, 1, 0.01, 200)
this.camera.position.set(0.6, 0.5, 0.6)
@@ -137,7 +142,6 @@ export class SimView {
canvas.addEventListener('keyup', key)
canvas.addEventListener('blur', () => { this._releaseAll(); this.rig.held.clear() })
if (buttons) this._bindPointer(canvas)
- if (buttons?.onOrient) this._rotateWidget()
// registered after the keys' and the camera's, but on the host, so a press on a handle comes to it first
this.handles = hand ? new Handles(this, hand) : null
this._changedAt = 0 // when the picture last had reason to change
@@ -577,59 +581,59 @@ export class SimView {
this._orient(q.normalize())
}
- // Back to flat, face up.
+ // Back upright, face to the student (world/codex.js UPRIGHT).
resetOrient() {
- this._orient(new THREE.Quaternion())
+ this._orient(quat(UPRIGHT))
}
- _orient(q) {
+ // Turned from upright to `angles` (degrees, { X, Y, Z }): about the board's
+ // own X, then its Y as that leaves it, then its Z (the rotation overlay's
+ // sliders).
+ setAngles({ X = 0, Y = 0, Z = 0 }) {
+ const d = THREE.MathUtils.degToRad
+ // the silkscreen's X, Y and Z are the model's x, z and y (codex-figure.js DEVICE_AXES)
+ const turn = new THREE.Quaternion().setFromEuler(new THREE.Euler(d(X), d(Z), d(Y), 'XZY'))
+ this._orient(quat(UPRIGHT).multiply(turn).normalize(), { quiet: true })
+ }
+
+ // The board's turn from upright as angles (degrees, { X, Y, Z }, setAngles),
+ // Y within -90 to 90.
+ angles() {
+ const turn = quat(UPRIGHT).invert().multiply(this._orientIs())
+ const e = new THREE.Euler().setFromQuaternion(turn, 'XZY')
+ const g = (r) => Math.round(THREE.MathUtils.radToDeg(r) * 10) / 10 || 0
+ return { X: g(e.x), Y: g(e.z), Z: g(e.y) }
+ }
+
+ // The board's own axes drawn on it (from its accelerometer), or not.
+ showAxes(on) {
+ for (const f of this.figures.values()) f.showAxes?.(on)
+ this._touch()
+ }
+
+ // The scene lit for `lux` on the light sensor: 250, the room's light, as
+ // drawn; darker below it, to a dim room at 0, brighter above, to 1000.
+ // The board's own lights and screen glow as before, in any light.
+ setLight(lux) {
+ const f = Math.max(0, Math.min(1000, lux)) / LUX_ROOM
+ const k = f <= 1 ? LIGHT_DIM + (1 - LIGHT_DIM) * f : 1 + (LIGHT_BRIGHT - 1) * ((f - 1) / 3)
+ for (const l of this.lights) l.intensity = LIGHT * k
+ this.scene.environmentIntensity = k
+ this.scene.backgroundIntensity = k
+ this._touch()
+ }
+
+ _orient(q, { quiet = false } = {}) {
this._orientAsked = q.clone()
this.buttons.onOrient([q.w, q.x, q.y, q.z])
+ if (!quiet) this.host.dispatchEvent(new CustomEvent('boardorient', { bubbles: true, detail: this.angles() }))
}
// The orientation to turn from: the last one asked for (keys come faster
// than the world's frames), else the board's as drawn.
_orientIs() {
if (this._orientAsked) return this._orientAsked.clone()
- const [w, x, y, z] = this._turnFigure()?.orient ?? [1, 0, 0, 0]
- return new THREE.Quaternion(x, y, z, w)
- }
-
- // The rotation widget, over the view's lower left: a row for each of the
- // board's own axes, labelled in its colour, with a button to turn it each
- // way (15 degrees a click, on and on while held), and Reset.
- _rotateWidget() {
- const el = document.createElement('div')
- el.className = 'sim-rotate'
- el.setAttribute('role', 'group')
- el.setAttribute('aria-label', t('sim.rotate.label'))
- const row = (axis) => `
-
- ${axis}
-
-
`
- el.innerHTML = `
${t('sim.rotate.title')}
${['X', 'Y', 'Z'].map(row).join('')}
- `
- let timer = null
- const stop = () => { clearTimeout(timer); timer = null }
- el.addEventListener('pointerdown', (e) => {
- const b = e.target.closest('.sim-rotate-btn')
- if (!b || e.button !== 0) return
- e.preventDefault()
- const go = () => this.turnBoard(b.dataset.axis, Number(b.dataset.dir) * TURN_STEP)
- go()
- const again = () => { go(); timer = setTimeout(again, TURN_REPEAT_MS) }
- timer = setTimeout(again, TURN_HOLD_MS)
- })
- for (const ev of ['pointerup', 'pointerleave', 'pointercancel']) el.addEventListener(ev, stop)
- el.addEventListener('click', (e) => {
- // the keyboard's Enter or Space on a turn button (a pointer turned it on pointerdown)
- const b = e.target.closest('.sim-rotate-btn')
- if (b && e.detail === 0) this.turnBoard(b.dataset.axis, Number(b.dataset.dir) * TURN_STEP)
- if (e.target.closest('.sim-rotate-reset')) this.resetOrient()
- })
- this.host.appendChild(el)
- this.rotateEl = el
+ return quat(this._turnFigure()?.orient ?? UPRIGHT)
}
_releaseAll() {
@@ -754,7 +758,6 @@ export class SimView {
this._studioTex?.dispose()
this.renderer.dispose()
this.renderer.domElement.remove()
- this.rotateEl?.remove()
this.compassName?.remove()
this.pipEl?.remove()
this._eye()?.dispose()
@@ -900,20 +903,29 @@ const SNAPS = 30
const PLAY_STEER = 2
const PLAY_JUMP = 15
-// Turning the board: a step (15 degrees), and while a widget button is held,
-// again after a moment and then every so often. Shift and a key turn it
-// about its own axes as [axis, angle]: the right arrow its right edge down
-// (about Y), the down arrow its bottom edge down (about X), Page Up and Page
+// Turning the board with a key: a step (15 degrees). Shift and a key turn it
+// about its own axes as [axis, angle]: the right arrow its right edge back
+// (about Y), the down arrow its bottom edge back (about X), Page Up and Page
// Down in the plane of its face (about Z).
const TURN_STEP = Math.PI / 12
-const TURN_HOLD_MS = 400
-const TURN_REPEAT_MS = 120
const TURN_KEYS = {
ArrowRight: ['Y', -TURN_STEP], ArrowLeft: ['Y', TURN_STEP],
ArrowDown: ['X', TURN_STEP], ArrowUp: ['X', -TURN_STEP],
PageUp: ['Z', TURN_STEP], PageDown: ['Z', -TURN_STEP],
}
+// The scene's light: the lights' intensity, and for setLight, the lux it
+// reads as and how much of it there is at none and at 1000 lux.
+const LIGHT = 1.6
+const LUX_ROOM = 250
+const LIGHT_DIM = 0.15
+const LIGHT_BRIGHT = 1.8
+
+// A quaternion [w, x, y, z] (world/codex.js) as Three's.
+function quat([w, x, y, z]) {
+ return new THREE.Quaternion(x, y, z, w)
+}
+
function lerpSnap(a, b, f) {
let dh = b.heading - a.heading
if (dh > Math.PI) dh -= 2 * Math.PI
diff --git a/src/sim/world/codex.js b/src/sim/world/codex.js
index 6cf59b7..29714e5 100644
--- a/src/sim/world/codex.js
+++ b/src/sim/world/codex.js
@@ -8,12 +8,18 @@
// y up, so gravity is (0, -1, 0). [1, 0, 0, 0] is the board lying flat, face
// up. The silkscreen's axes are x (right), y (down the board) and z (out of
// the face): the frame's x, z and y.
+//
+// It starts UPRIGHT: stood on its bottom edge, its face toward the student
+// (a quarter turn about its right-hand axis), as a student holds it to read
+// the screen. Upright, the accelerometer reads +1 g on y.
import { Screen } from './screen.js'
import { Gfx } from './gfx.js'
import { sincos } from './fmath.js'
import { Radio } from './radio.js'
import { Infrared } from './infrared.js'
+export const UPRIGHT = [Math.SQRT1_2, Math.SQRT1_2, 0, 0]
+
// Recorded sounds' ids start here; mixers' ids are 1000 and up (bridge/codex.js).
const CLIP_BASE = 2000
@@ -30,7 +36,7 @@ export class CodeX {
this.ioOut = 0 // the IO expander's outputs: LEDs from bit 2
this.pixels = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
this.brightness = 0 // backlight, percent
- this.orient = [1, 0, 0, 0] // flat, face up (see the top of this file)
+ this.orient = [...UPRIGHT] // see the top of this file
this.lux = 250
this.volts = 4.1
this.volume = 0
diff --git a/tests/sim-ui.mjs b/tests/sim-ui.mjs
index c0819f5..7c406df 100644
--- a/tests/sim-ui.mjs
+++ b/tests/sim-ui.mjs
@@ -5,6 +5,7 @@
*/
import { spawn } from 'node:child_process'
import { chromium } from 'playwright'
+import sharp from 'sharp'
// Its own port, so it never meets another test's (or someone's) server.
const PORT = '4183'
@@ -81,6 +82,213 @@ function lensesSeated() {
})
return out
}
+
+// Every light's glow on the board in view (`device`, its figure's `lights`)
+// is fixed to the light and faces out of it: each light is lit alone and
+// looked at from the front (along the way it shines), at an angle, from the
+// side (along the board's face) and from behind (through the board), the
+// figure held still and off the floor, the room hidden. From the front or at
+// an angle it glows; from no side has it a hard line across it (other than
+// where a part in front hides it, as a real part would, or where it ends at
+// the board's face); from the side none of it lies behind the board's face,
+// and from behind none shows. What is measured is the glow drawn alone, over
+// black, the board and its parts hiding it but not drawn. Its lit views are
+// saved under `${SHOT_DIR}/glow/`. Returns each light's result, by name.
+const GLOW_VIEWS = { front: [0.05, 1, 0.15], oblique: [0.8, 0.55, 0.25], side: [1, 0.04, 0], back: [0.15, -1, 0.1] }
+async function glowCheck(device) {
+ // drawing is the same on either VM: checked once, on the JSPI run
+ if (FALLBACK) return null
+ const fs = await import('node:fs')
+ fs.mkdirSync(`${SHOT_DIR}/glow`, { recursive: true })
+ const names = await page.evaluate((device) => {
+ const v = window.openCodeBot.device.sim.view
+ const f = [...v.figures.values()][0]
+ const C = v.camera.position.constructor
+ const c = v.controls
+ // the figure held as the test sets it, the camera free to go anywhere
+ window.__glow = {
+ was: { pos: v.camera.position.toArray(), target: c.target.toArray(), min: c.minDistance, maxPolar: c.maxPolarAngle, mode: v.rig.mode, ratio: v.renderer.getPixelRatio() },
+ lights: f.lights,
+ names: device === 'codebot'
+ ? Object.entries(f.leds).flatMap(([g, ls]) => ls.map((_, n) => ({ user: `user LED ${n}`, ls: `line sensor LED ${n}`, prox: `proximity LED ${n}`, pwr: 'power LED' })[g]))
+ : device === 'codex'
+ ? [...f.leds.map((_, n) => (n < 4 ? `LED ${n}` : `LED ${n} (${n === 4 ? 'A' : 'B'})`)), ...f.pixels.map((_, n) => `NeoPixel ${n}`)]
+ : [...f.leds.map((_, n) => (n < 8 ? `BYTE LED ${n}` : 'STA LED')), ...['2 top', '2 under', '1 top', '1 under', '3 under', '3 top', '4 top', '4 under'].map((p) => `NeoPixel ${p}`)],
+ }
+ f.update = () => {}
+ v.renderer.setPixelRatio(1) // one pixel read back for each pixel of the page
+ f.root.position.y += 0.3 // off the floor, so a light under the board is seen from below
+ // the room hidden: only the board is drawn, so no wall comes between the camera and a light
+ window.__glow.room = v.scene.children.filter((o) => o.visible && !o.isLight && !o.isCamera && o !== f.root && !o.getObjectById(f.root.id))
+ for (const o of window.__glow.room) o.visible = false
+ window.__glow.clear = v.renderer.getClearColor(new (f.lights[0].color.constructor)())
+ window.__glow.clearAlpha = v.renderer.getClearAlpha()
+ v.rig.setMode('rotate') // a camera that follows the board (CodeAIR's) stays where it is put
+ c.minDistance = 0
+ c.maxPolarAngle = Math.PI
+ // light n alone, or none
+ window.__glow.light = (n) => window.__glow.lights.forEach((l, i) => {
+ if (i !== n) l.show(l.color, 0)
+ else if (l.part) l.rgb(255, 0, 128)
+ else if (l.set) l.set(1)
+ else l.show(new l.color.constructor(1, 0, 0), 1)
+ })
+ // the camera looking at light n's glow from `dir` (in the glow's frame:
+ // y the way it shines), its size about a sixth of the view's height;
+ // where the glow's centre and a point just behind it fall on the view,
+ // in pixels
+ window.__glow.aim = (n, dir) => {
+ const h = window.__glow.lights[n].halo
+ h.updateMatrixWorld(true)
+ const ctr = new C().setFromMatrixPosition(h.matrixWorld)
+ const axes = [0, 1, 2].map((i) => new C().setFromMatrixColumn(h.matrixWorld, i).normalize())
+ const size = new C().setFromMatrixScale(h.matrixWorld).x
+ const d = axes[0].clone().multiplyScalar(dir[0]).addScaledVector(axes[1], dir[1]).addScaledVector(axes[2], dir[2]).normalize()
+ const dist = Math.max(0.02, (size * 6) / (2 * Math.tan((v.camera.fov * Math.PI) / 360)))
+ c.target.copy(ctr)
+ v.camera.position.copy(ctr).addScaledVector(d, dist)
+ c.update()
+ v.camera.updateMatrixWorld()
+ v._touch()
+ const r = v.renderer.domElement.getBoundingClientRect()
+ const px = (p) => { const s = p.clone().project(v.camera); return [((s.x + 1) / 2) * r.width, ((1 - s.y) / 2) * r.height] }
+ const back = ctr.clone().addScaledVector(axes[1], -size * 0.2)
+ return { centre: px(ctr), back: px(back), rect: [r.left, r.top, r.width, r.height] }
+ }
+ // light n alone (-1 none), drawn at once, and the view S pixels
+ // square from (x, y) read back as it was drawn (RGBA, top row first,
+ // base64): what the scene draws, without the page over it. Only that
+ // square is drawn. `mode`: 'scene' as it looks; 'glow' its glow alone
+ // over black, the board and its parts hiding it where they stand in
+ // front of it but not drawn (the glow's own strength, whatever is
+ // behind it); 'through' its glow alone with nothing hiding it.
+ window.__glow.grab = (n, x, y, S, mode = 'scene') => {
+ window.__glow.light(n)
+ const halo = n >= 0 && window.__glow.lights[n].halo
+ const r = v.renderer
+ const alone = mode !== 'scene'
+ const was = []
+ const background = v.scene.background
+ if (alone) {
+ v.scene.background = null
+ r.setClearColor(0x000000, 1)
+ v.scene.traverse((o) => {
+ if (o === halo || !o.material) return
+ for (const m of [o.material].flat()) { was.push([m, m.colorWrite]); m.colorWrite = false }
+ })
+ if (mode === 'through') halo.material.depthTest = false
+ }
+ r.setScissor(x, v.host.clientHeight - y - S, S, S)
+ r.setScissorTest(true)
+ r.render(v.scene, v.camera)
+ r.setScissorTest(false)
+ if (alone) {
+ for (const [m, w] of was) m.colorWrite = w
+ v.scene.background = background
+ r.setClearColor(window.__glow.clear, window.__glow.clearAlpha)
+ halo.material.depthTest = true
+ }
+ const gl = v.renderer.getContext()
+ const k = v.renderer.getPixelRatio()
+ const w = Math.round(S * k)
+ const px = new Uint8Array(w * w * 4)
+ gl.readPixels(Math.round(x * k), gl.drawingBufferHeight - Math.round(y * k) - w, w, w, gl.RGBA, gl.UNSIGNED_BYTE, px)
+ const rows = new Uint8Array(px.length)
+ for (let r = 0; r < w; r++) rows.set(px.subarray((w - 1 - r) * w * 4, (w - r) * w * 4), r * w * 4)
+ let bin = ""
+ for (let i = 0; i < rows.length; i += 0x8000) bin += String.fromCharCode(...rows.subarray(i, i + 0x8000))
+ return btoa(bin)
+ }
+ return window.__glow.names
+ }, device)
+ // the view round the light, S pixels square
+ const S = 360
+ const shot = async (n, x, y, mode = 'scene') => {
+ const data = Buffer.from(await page.evaluate(([n, x, y, S, mode]) => window.__glow.grab(n, x, y, S, mode), [n, x, y, S, mode]), 'base64')
+ const w = Math.round(Math.sqrt(data.length / 4))
+ return { data, w, h: w, ch: 4 }
+ }
+ // one view drawn before the first is measured (the glow's shader is built on first use)
+ await page.evaluate(() => window.__glow.aim(0, [0, 1, 0.1]))
+ await shot(0, 0, 0)
+ await shot(0, 0, 0, 'glow')
+ const results = {}
+ for (let n = 0; n < names.length; n++) {
+ const fails = []
+ let scale = 1
+ for (const [name, dir] of Object.entries(GLOW_VIEWS)) {
+ const where = await page.evaluate(([n, dir]) => window.__glow.aim(n, dir), [n, dir])
+ const [, , rw, rh] = where.rect
+ const cx = Math.round(Math.min(Math.max(0, where.centre[0] - S / 2), rw - S)), cy = Math.round(Math.min(Math.max(0, where.centre[1] - S / 2), rh - S))
+ // the view lit (saved), its glow alone, and its glow with nothing in front of it
+ const a = await shot(n, cx, cy)
+ const g = await shot(n, cx, cy, 'glow')
+ const t = await shot(n, cx, cy, 'through')
+ await sharp(a.data, { raw: { width: a.w, height: a.h, channels: a.ch } })
+ .png().toFile(`${SHOT_DIR}/glow/${device}-${names[n].replace(/[^A-Za-z0-9]+/g, '-').toLowerCase()}-${name}.png`)
+ // where the glow's centre and the point behind it are in the shot
+ // (its pixels may be fewer than the page's: k of them to one)
+ const k = (scale = g.w / S)
+ const at = ([x, y]) => [(x - cx) * k, (y - cy) * k]
+ const centre = at(where.centre), back = at(where.back)
+ // the glow's strength at each pixel (0 to 255), and whether a part in front of it hides it there
+ const strength = (img, x, y) => { const o = (y * img.w + x) * img.ch; return Math.max(img.data[o], img.data[o + 1], img.data[o + 2]) }
+ const d0 = (x, y) => strength(g, x, y)
+ const hidden = (x, y) => Math.abs(d0(x, y) - strength(t, x, y)) > 6
+ // the side of the board's face a pixel is on: + in front, - behind (along the line from the glow's centre to the point behind it)
+ const bx = back[0] - centre[0], by = back[1] - centre[1], bl = Math.hypot(bx, by)
+ const along = (x, y) => ((x - centre[0]) * bx + (y - centre[1]) * by) / bl
+ const behind = (x, y) => bl > 1 && along(x, y) > 3
+ // on the board's face, seen edge on: where the glow ends, by design
+ const onFace = (x, y) => bl > 1 && Math.abs(along(x, y)) <= 3
+ let glow = 0, seam = 0, behindLit = 0
+ for (let y = 1; y < g.h - 1; y++) {
+ for (let x = 1; x < g.w - 1; x++) {
+ const d = d0(x, y)
+ if (d < 12) continue
+ glow++
+ if (name === 'back' || (name === 'side' && behind(x, y))) behindLit++
+ // a hard line in the glow itself: stepping from strong to nothing
+ // between neighbours, not where a part in front of it hides it
+ // (as a real part would) nor along the board's face, where it ends
+ const near = [[x + 1, y], [x, y + 1], [x - 1, y], [x, y - 1]]
+ if (d > 45 && !hidden(x, y) && !onFace(x, y) && near.every(([u, w]) => !hidden(u, w)) &&
+ Math.min(...near.map(([u, w]) => d0(u, w))) < 6) seam++
+ }
+ }
+ if (seam > 6) fails.push(`from the ${name}, a hard edge in the glow (${seam} pixels)`)
+ if (behindLit > 6) fails.push(`from the ${name}, glow behind the board (${behindLit} pixels)`)
+ results[names[n]] = { ...results[names[n]], [name]: { glow, seam, behind: behindLit } }
+ }
+ // seen from the front or at an angle (one of them may be behind the board's own parts)
+ const seen = Math.max(results[names[n]].front.glow, results[names[n]].oblique.glow)
+ if (seen < 200 * scale * scale) fails.push(`hardly any glow from the front or at an angle (${seen} pixels)`)
+ results[names[n]].fails = fails
+ if (fails.length) problems.push(`glow: ${device} ${names[n]}: ${fails.join('; ')}`)
+ }
+ await page.evaluate(() => {
+ const v = window.openCodeBot.device.sim.view
+ const f = [...v.figures.values()][0]
+ const { was } = window.__glow
+ delete f.update
+ f.root.position.y -= 0.3
+ for (const o of window.__glow.room) o.visible = true
+ v.rig.setMode(was.mode)
+ v.renderer.setPixelRatio(was.ratio)
+ v.controls.minDistance = was.min
+ v.controls.maxPolarAngle = was.maxPolar
+ v.camera.position.fromArray(was.pos)
+ v.controls.target.fromArray(was.target)
+ v.controls.update()
+ v._touch()
+ delete window.__glow
+ })
+ fs.writeFileSync(`${SHOT_DIR}/glow/${device}.json`, JSON.stringify(results, null, 1))
+ const bad = Object.values(results).filter((r) => r.fails.length).length
+ if (!bad) console.log(`sim-ui: ${device}: each of its ${names.length} lights glows soft and fixed to it, from the front, at an angle, from the side and from behind, and none shows behind the board`)
+ return results
+}
+
// OCB_CHROMIUM: use an installed Chromium when Playwright's own is missing.
const browser = await chromium.launch(process.env.OCB_CHROMIUM ? { executablePath: process.env.OCB_CHROMIUM } : {})
// One context, so a second page is another tab of the same browser.
@@ -514,6 +722,7 @@ const redOf = ([r, g, b]) => r > 0.5 && g < r / 3 && b < r / 3
const greenOf = ([r, g, b]) => g > 0.5 && r < g / 3 && b < g / 3
if (!cbLeds || !redOf(cbLeds.user0) || !greenOf(cbLeds.ls0) || Math.min(...cbLeds.user1) < 0.5 || Math.max(...cbLeds.user1Glow) > 0) problems.push(`CodeBot LEDs: drawn ${JSON.stringify(cbLeds)}`)
else console.log('sim-ui: CodeBot\'s LEDs lit red and green, unlit ones pale')
+await glowCheck('codebot')
// A click on the model's BTN-1 presses it, as the bar's button does (and the
// camera stays put); while held it is drawn down.
@@ -890,14 +1099,34 @@ if ((await page.evaluate(() => window.openCodeBot.device.sim.view.camera.positio
await page.evaluate(() => window.openCodeBot.device.stop())
}
-// Rotation: the widget over the view turns the CodeX about its own X, Y and
-// Z axes (the model turns, the accelerometer reads it, the camera stays);
-// Shift and the arrow keys turn it too, and Home lays it flat again.
+// Rotation: CodeX starts upright, face to the camera; the rotation overlay,
+// shown from the bar, turns it from there about its own X, Y and Z axes, by
+// slider or typed degrees (the model turns, the accelerometer reads it, the
+// camera stays), and draws its axes only while it shows; Shift and the arrow
+// keys turn it too, the overlay following, and Upright and Home stand it up.
{
const before = problems.length
- if (await page.$('.sim-tilt-x, .sim-tilt-y')) problems.push('rotate: the bar still has tilt sliders')
- const labels = await page.$$eval('.sim-rotate .sim-rotate-axis', (els) => els.map((e) => e.textContent))
- if (labels.join() !== 'X,Y,Z') problems.push(`rotate: the widget's axes are ${labels}, not X, Y, Z`)
+ const overlay = () => page.evaluate(() => ({
+ shown: !document.querySelector('.sim-ov-rotate').hidden,
+ pressed: document.querySelector('.sim-tog[data-ov="rotate"]').getAttribute('aria-pressed'),
+ axes: [...window.openCodeBot.device.sim.view.figures.values()][0].axes.visible,
+ nums: [...document.querySelectorAll('.sim-rot-num')].map((n) => n.value).join(),
+ }))
+ let o = await overlay()
+ if (o.shown || o.axes) problems.push(`rotate: the overlay or the board's axes show before it is asked for (${JSON.stringify(o)})`)
+ await page.click('.sim-tog[data-ov="rotate"]')
+ o = await overlay()
+ if (!o.shown || !o.axes || o.pressed !== 'true') problems.push(`rotate: its button did not show the overlay and the board's axes (${JSON.stringify(o)})`)
+ const labels = await page.$$eval('.sim-ov-rotate .sim-rot-axis', (els) => els.map((e) => e.textContent))
+ if (labels.join() !== 'X,Y,Z') problems.push(`rotate: the overlay's axes are ${labels}, not X, Y, Z`)
+ // the axes start at the accelerometer chip's centre (the model's Accelerometer part), not the board's
+ const fromChip = await page.evaluate(() => {
+ const f = [...window.openCodeBot.device.sim.view.figures.values()][0]
+ const chip = f.parts.boxes.find((b) => b.name === 'Accelerometer')
+ const c = f.parts.model.localToWorld(chip.box.getCenter(f.axes.position.clone()))
+ return { off: c.distanceTo(f.axes.getWorldPosition(f.axes.position.clone())), fromCentre: f.axes.position.length() }
+ })
+ if (!(fromChip.off < 0.001 && fromChip.fromCentre > 0.005)) problems.push(`rotate: the board's axes are not at the accelerometer's centre (${JSON.stringify(fromChip)})`)
await page.evaluate(() => { window.__sim.out = ''; window.openCodeBot.device.run(`from codex import *
import time
while True:
@@ -917,37 +1146,101 @@ while True:
const q = f.turn.quaternion
return { world: window.openCodeBot.device.sim.lastFrame.devices[0].orient, model: [q.w, q.x, q.y, q.z], cam: v.camera.position.toArray().join() }
})
- const turn = async (axis, dir, times) => {
- for (let i = 0; i < times; i++) await page.click(`.sim-rotate-btn[data-axis="${axis}"][data-dir="${dir}"]`)
+ // degrees typed in for an axis (Enter), or its slider moved there
+ const type = async (axis, deg) => {
+ await page.fill(`.sim-rot-num[data-axis="${axis}"]`, String(deg))
+ await page.press(`.sim-rot-num[data-axis="${axis}"]`, 'Enter')
}
- await reads('Math.abs(x) < 1500 && Math.abs(y) < 1500 && z < -14000', 'flat did not read flat, face up')
- const cam0 = (await now()).cam
+ const slide = (axis, deg) => page.locator(`.sim-rot-range[data-axis="${axis}"]`).fill(String(deg))
// (readings are gravity along the silkscreen's axes, x right, y down the
// board, z out of the face, as a CodeX reads: an axis pointing down reads
// above zero on it)
- await turn('Y', -1, 6) // 90 degrees about Y the other way: right edge down
- await reads('x > 15000 && Math.abs(z) < 2000', 'six turns back about Y did not stand it on its right edge')
- await turn('Z', 1, 6) // 90 degrees about Z, in the face's plane: now its bottom edge down
- await reads('y > 15000 && Math.abs(x) < 2000', 'six turns about Z did not stand it on its bottom edge')
+ await reads('Math.abs(x) < 1500 && y > 14000 && Math.abs(z) < 1500', 'it did not start upright (y down)')
+ const cam0 = (await now()).cam
+ await type('X', -90) // its bottom edge brought forward and up: flat, face up
+ await reads('Math.abs(x) < 1500 && Math.abs(y) < 1500 && z < -14000', '-90 about X did not lay it flat, face up')
+ await type('X', 0)
+ await slide('Z', 90) // in the face's plane: its x arrow up
+ await reads('x < -14000 && Math.abs(y) < 1500', 'the Z slider at 90 did not stand it with its x arrow up')
+ o = await overlay()
+ if (o.nums !== '0.0,0.0,90.0') problems.push(`rotate: the degrees read ${o.nums}, not 0.0, 0.0, 90.0`)
const t = await now()
if (t.model.some((v, i) => Math.abs(v - t.world[i]) > 0.01)) problems.push(`rotate: the model turned to ${t.model}, the board is at ${t.world}`)
if (t.cam !== cam0) problems.push('rotate: turning the board turned the camera')
await page.screenshot({ path: `${SHOT_DIR}/ocb-sim-codex-rotate.png` })
await page.click('.sim-rotate-reset')
- await reads('Math.abs(x) < 1500 && Math.abs(y) < 1500 && z < -14000', 'Reset did not lay it flat, face up')
+ await reads('Math.abs(x) < 1500 && y > 14000', 'Upright did not stand it up')
+ o = await overlay()
+ if (o.nums !== '0.0,0.0,0.0') problems.push(`rotate: Upright left the degrees at ${o.nums}`)
await page.focus('.sim-canvas')
- await page.keyboard.press('Shift+ArrowLeft')
- await page.keyboard.press('Shift+ArrowLeft')
- await reads('x < -6000 && Math.abs(y) < 1500', 'Shift+Left did not tilt the left edge down')
await page.keyboard.press('Shift+ArrowDown')
- await reads('x < -6000 && y > 2000', 'Shift+Down did not tilt the bottom edge down')
+ await page.keyboard.press('Shift+ArrowDown')
+ await reads('y > 12000 && y < 15500 && Math.abs(x) < 1500', 'Shift+Down did not lean it back')
+ o = await overlay()
+ if (o.nums !== '30.0,0.0,0.0') problems.push(`rotate: two Shift+Down left the degrees at ${o.nums}, not 30.0, 0.0, 0.0`)
await page.keyboard.press('Home')
- await reads('Math.abs(x) < 1500 && Math.abs(y) < 1500 && z < -14000', 'Home did not lay it flat')
+ await reads('Math.abs(x) < 1500 && y > 14000 && Math.abs(z) < 1500', 'Home did not stand it upright')
+ await page.click('.sim-tog[data-ov="rotate"]')
+ o = await overlay()
+ if (o.shown || o.axes) problems.push('rotate: its button again did not hide the overlay and the board\'s axes')
+ await page.evaluate(() => window.openCodeBot.device.stop())
+ if (problems.length === before) console.log('sim-ui: CodeX starts upright; the rotation overlay turns it about its own X, Y and Z by slider and degrees, its axes from the accelerometer showing with it; the keys too, Upright and Home stand it up')
+}
+
+// Ambient light: its overlay sets the light the sensor reads and lights the scene to match.
+{
+ const before = problems.length
+ await page.click('.sim-tog[data-ov="light"]')
+ if (await page.evaluate(() => document.querySelector('.sim-ov-light').hidden)) problems.push('light: its button did not show the overlay')
+ const lit = () => page.evaluate(() => window.openCodeBot.device.sim.view.lights[0].intensity)
+ const room = await lit()
+ await page.evaluate(() => { window.__sim.out = ''; window.openCodeBot.device.run(`from codex import *
+import time
+while True:
+ print('L', light.read())
+ time.sleep(0.1)
+`) })
+ const lightReads = (ok, what) => page.waitForFunction((src) => {
+ const m = [...window.__sim.out.matchAll(/L (\d+)/g)].pop()
+ return m && new Function('v', `return ${src}`)(Number(m[1])) && Number(m[1])
+ }, ok, { timeout: 5000 }).then((h) => h.jsonValue(), () => { problems.push(`light: ${what}`); return null })
+ const at250 = await lightReads('v > 0', 'the sensor read nothing in the room\'s light')
+ await page.locator('.sim-light').fill('1000')
+ if (at250 != null) await lightReads(`v > ${at250} * 2`, 'the sensor did not read more at 1000 lux')
+ if (!((await lit()) > room)) problems.push('light: 1000 lux did not light the scene more')
+ if ((await page.textContent('.sim-light-out')).trim() !== '1,000 lux' && (await page.textContent('.sim-light-out')).trim() !== '1000 lux') problems.push(`light: the overlay reads ${await page.textContent('.sim-light-out')}`)
+ await page.locator('.sim-light').fill('0')
+ if (!((await lit()) < room)) problems.push('light: 0 lux did not darken the scene')
+ await page.locator('.sim-light').fill('250')
+ await page.click('.sim-tog[data-ov="light"]')
await page.evaluate(() => window.openCodeBot.device.stop())
- if (problems.length === before) console.log('sim-ui: the rotation widget turns CodeX about its own X, Y and Z, the keys too, Reset and Home lay it flat')
+ if (problems.length === before) console.log('sim-ui: the ambient light overlay sets what the sensor reads and lights the scene to match')
}
-// The full-screen button in CodeX's bar shows its screen alone, filling the
+// The buttons overlay shows from the start, and its keys press CodeX's buttons.
+{
+ const before = problems.length
+ if (await page.evaluate(() => document.querySelector('.sim-ov-buttons').hidden)) problems.push('buttons: the overlay does not show from the start')
+ if (await page.$('.sim-bar .cx-btn, .sim-bar .sim-light')) problems.push('buttons: the bar still has the board\'s keys or the light slider')
+ await page.evaluate(() => window.openCodeBot.device.run(`from codex import *
+while not buttons.was_pressed(BTN_B):
+ pass
+`))
+ await page.waitForTimeout(1000)
+ await page.click('.sim-ov-buttons .cx-B', { delay: 150 })
+ await page.waitForFunction(() => window.openCodeBot.device.state === 'ready', null, { timeout: 15000 }).catch(() => problems.push('buttons: the overlay\'s B did not press button B'))
+ await page.click('.sim-tog[data-ov="buttons"]')
+ if (!(await page.evaluate(() => document.querySelector('.sim-ov-buttons').hidden))) problems.push('buttons: its button did not hide the overlay')
+ await page.click('.sim-tog[data-ov="buttons"]')
+ if (problems.length === before) console.log('sim-ui: the buttons overlay presses CodeX\'s buttons, and hides and shows from the bar')
+}
+
+// Every light's glow on CodeX (glowCheck), the view clear of overlays.
+await page.click('.sim-tog[data-ov="buttons"]')
+await glowCheck('codex')
+await page.click('.sim-tog[data-ov="buttons"]')
+
+// The display button in CodeX's bar shows its screen alone, filling the
// view, crisp, and the program's picture on it; again, or Esc, the board.
{
const before = problems.length
@@ -972,7 +1265,7 @@ while True:
await page.click('.sim-full')
if (await page.evaluate(() => !document.querySelector('.sim-lcd').hidden || document.querySelector('.sim-full').getAttribute('aria-pressed') !== 'false')) problems.push('lcd: the button again did not go back to the board')
await page.evaluate(() => window.openCodeBot.device.stop())
- if (problems.length === before) console.log('sim-ui: the full-screen button shows the CodeX screen alone, filling the view; again or Esc, the board')
+ if (problems.length === before) console.log('sim-ui: the display button shows the CodeX screen alone, filling the view; again or Esc, the board')
}
// CodeAIR flies only in a build with its flight library (SIM_FLIGHT=1,
@@ -1123,6 +1416,7 @@ with recorder:
const landed = await page.evaluate(() => window.openCodeBot.device.sim.lastFrame.devices[0].z)
if (landed > 0.08) problems.push(`CodeAIR: stopped inside with recorder:, it did not land (at ${landed} m)`)
else console.log('sim-ui: CodeAIR flew, and a stop landed it')
+ await glowCheck('codeair')
// camera.take() in the page: each frame drawn by the view at the drone's
// pose (view.js capture), colour then grey, costing take()'s 25 ms of
diff --git a/tests/sim.mjs b/tests/sim.mjs
index b7c45d4..e40ca3c 100644
--- a/tests/sim.mjs
+++ b/tests/sim.mjs
@@ -405,6 +405,12 @@ await test('the CodeX accelerometer reads +1 g on whichever axis points down', a
}
})
+await test('a CodeX starts upright, face to the user: +1 g on y', async () => {
+ const r = await runHeadless({ kind: 'codex', seconds: 2, source: 'from codex import *\nprint(*accel.read())' })
+ const [x, y, z] = r.output.trim().split(/\s+/).map(Number)
+ assert.ok(Math.abs(x) < 400 && Math.abs(y - 16384) < 400 && Math.abs(z) < 400, `read ${[x, y, z]}`)
+})
+
await test('the device modules are the CB3\'s own, on the CircuitPython layer', async () => {
const r = await runHeadless({ source: 'import botcore, botservices, board, digitalio, busio\nprint(botcore.System.__name__, hasattr(botcore, \'__doc__\'))\nprint(board.I2C().scan())' })
assert.equal(r.output.trim(), 'System False\n[14, 28]')