@0001-labs/idv1 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +55 -2
- package/package.json +40 -3
- package/src/index.ts +4 -0
- package/src/scanCode.ts +565 -0
- package/src/scanCodeDrawing.ts +99 -0
- package/src/shapes.ts +128 -0
- package/src/space.ts +28 -0
- package/src/words.ts +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 0001
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,56 @@
|
|
|
1
|
-
#
|
|
1
|
+
# IDv1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Short codes whose shape says what they name. Every code is six characters, and one look at it tells an account from a list or an item, so a single address, `example.com/<code>`, can open any of them and never two at once.
|
|
4
|
+
|
|
5
|
+
| What | Shape | Example | How many |
|
|
6
|
+
|---|---|---|---|
|
|
7
|
+
| Account | two letters, four digits | `Jo4712` | 27 million |
|
|
8
|
+
| Product | four letters, two digits | `AbCd12` | 731 million |
|
|
9
|
+
| List | two digits, four letters | `12ABCD` | 46 million |
|
|
10
|
+
| Item | two letters, two digits, two letters or digits that are not both digits | `Ab12Cd` | 1 billion |
|
|
11
|
+
|
|
12
|
+
- **Capitals matter.** `Ab12Cd` and `ab12cd` are two codes.
|
|
13
|
+
- **An account's letters come from the person's name**, a capital and a small one: Leo is `Le0125`, Henrik `He0422`. A name without two Latin letters takes them from the email address, and failing that at random. The digits are drawn until the code is free.
|
|
14
|
+
- **A product's code is scanned, never typed.** Whoever signs up with a product's code may keep it as their account's code, so it is an account's shape too. Codes whose letters spell a rude or awkward word in any language the products speak, capitals aside, are drawn again (`words.ts`).
|
|
15
|
+
- **New lists draw four capitals.** Older lists may hold small letters, and every check reads both.
|
|
16
|
+
- **An item never ends in two digits**, or it would be an account.
|
|
17
|
+
- **A code does not change by itself.** A product may give an account a chosen code, as when it should match the code its owner has elsewhere.
|
|
18
|
+
|
|
19
|
+
## The scannable code
|
|
20
|
+
|
|
21
|
+
`scanCode.ts` turns any six-character code into a strip of 16 × 4 cells (64 bits: a format byte, the code in five bytes, a two-byte check) and reads it back from a camera frame. Any single damaged cell fails the check rather than reading wrong. `scanCodePath` draws the strip as SVG; `readRgbaScanFrame`, `locateRgbaScanFrame` and `StableScan` read it from camera pixels, also when it is written on paper beside other marks.
|
|
22
|
+
|
|
23
|
+
## What is in here
|
|
24
|
+
|
|
25
|
+
- `src/shapes.ts` — the patterns (`ACCOUNT_CODE`, `PRODUCT_CODE`, `LIST_CODE`, `ITEM_CODE`), `codeKind`, the candidates each shape is drawn from, and `nameLetters`
|
|
26
|
+
- `src/space.ts` — `ID_SPACE`, how many codes of each kind there can be, and `idUsage`
|
|
27
|
+
- `src/words.ts` — the words and digits a product's code must never spell
|
|
28
|
+
- `src/scanCode.ts`, `src/scanCodeDrawing.ts` — the scannable code
|
|
29
|
+
- `tests/` — the shapes, the counts and the scannable code
|
|
30
|
+
|
|
31
|
+
## Using it
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
vp add @0001-labs/idv1
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { accountCodeCandidate, codeKind, nameLetters } from '@0001-labs/idv1'
|
|
39
|
+
|
|
40
|
+
codeKind('Ab12Cd') // 'item'
|
|
41
|
+
const code = accountCodeCandidate(nameLetters('Leo Andersen')) // Le0125, say
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
A candidate is only a code to try: keep it when nothing in your database holds it yet, and draw again when something does. Store the code on the row beside the database's own id, with an index on it, and look rows up by it.
|
|
45
|
+
|
|
46
|
+
## Development
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
vp install
|
|
50
|
+
vp run check
|
|
51
|
+
vp test run
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Licence
|
|
55
|
+
|
|
56
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0001-labs/idv1",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Short codes whose shape says what they name: accounts, products, lists and items, how many there can be, and the scannable code that carries them.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/0001-labs/IDv1.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/index.ts"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"src/",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@types/node": "^22.13.1",
|
|
21
|
+
"typescript": "^6.0.3",
|
|
22
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@0.2.8",
|
|
23
|
+
"vite-plus": "0.2.8",
|
|
24
|
+
"vitest": "4.1.10"
|
|
25
|
+
},
|
|
26
|
+
"devEngines": {
|
|
27
|
+
"packageManager": {
|
|
28
|
+
"name": "pnpm",
|
|
29
|
+
"version": "11.7.0",
|
|
30
|
+
"onFail": "error"
|
|
31
|
+
},
|
|
32
|
+
"runtime": {
|
|
33
|
+
"name": "node",
|
|
34
|
+
"version": ">=22.12.0",
|
|
35
|
+
"onFail": "error"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"check": "vp exec tsc --noEmit",
|
|
40
|
+
"test": "vp test run",
|
|
41
|
+
"release": "node scripts/release.mjs"
|
|
42
|
+
}
|
|
6
43
|
}
|
package/src/index.ts
ADDED
package/src/scanCode.ts
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
import { isAccountCode, isListCode } from './shapes'
|
|
2
|
+
import { scanCodeChecksum, scanCodeColumns, scanCodeRows } from './scanCodeDrawing'
|
|
3
|
+
export { CODE_END_RADIUS, encodeScanCode, scanCodeColumns, scanCodePath, scanCodeRows } from './scanCodeDrawing'
|
|
4
|
+
|
|
5
|
+
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
6
|
+
const idSpace = 62 ** 6
|
|
7
|
+
|
|
8
|
+
/** Validates the format byte and CRC; any single corrupted cell yields null. */
|
|
9
|
+
export function decodeScanCode(bits: readonly boolean[]): string | null {
|
|
10
|
+
if (bits.length !== 64) return null
|
|
11
|
+
const bytes: number[] = []
|
|
12
|
+
for (let offset = 0; offset < 64; offset += 8) {
|
|
13
|
+
let byte = 0
|
|
14
|
+
for (let bit = 0; bit < 8; bit++) byte = (byte << 1) | (bits[offset + bit] ? 1 : 0)
|
|
15
|
+
bytes.push(byte)
|
|
16
|
+
}
|
|
17
|
+
if (bytes[0] !== 3 || scanCodeChecksum(bytes.slice(0, 6)) !== ((bytes[6] << 8) | bytes[7])) return null
|
|
18
|
+
let value = 0
|
|
19
|
+
for (const byte of bytes.slice(1, 6)) value = value * 256 + byte
|
|
20
|
+
if (value >= idSpace) return null
|
|
21
|
+
let id = ''
|
|
22
|
+
for (let index = 0; index < 6; index++) {
|
|
23
|
+
id = alphabet[value % 62] + id
|
|
24
|
+
value = Math.floor(value / 62)
|
|
25
|
+
}
|
|
26
|
+
return id
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const isListScanId = (id: string): boolean => isListCode(id)
|
|
30
|
+
/** A person's code: a name's `LLnnnn` or a product's `LLLLnn` (`shapes.ts`). */
|
|
31
|
+
export const isUserScanId = (id: string): boolean => isAccountCode(id)
|
|
32
|
+
/** Scanning opens lists and profiles; item codes are not scannable. */
|
|
33
|
+
export const isSupportedScanId = (id: string): boolean => isListScanId(id) || isUserScanId(id)
|
|
34
|
+
|
|
35
|
+
export type ScanRect = { x: number; y: number; width: number; height: number }
|
|
36
|
+
export type Luminance = (x: number, y: number) => number
|
|
37
|
+
export type Chroma = (x: number, y: number) => boolean
|
|
38
|
+
|
|
39
|
+
const insetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({
|
|
40
|
+
x: rect.x + dx, y: rect.y + dy, width: rect.width - 2 * dx, height: rect.height - 2 * dy,
|
|
41
|
+
})
|
|
42
|
+
const offsetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({ ...rect, x: rect.x + dx, y: rect.y + dy })
|
|
43
|
+
const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value))
|
|
44
|
+
|
|
45
|
+
/** Reads only 576 luminance samples from the guide rectangle (default: centered, 80% wide, 4:1). */
|
|
46
|
+
export function sampleScanCode(width: number, height: number, luminance: Luminance, rect?: ScanRect): string | null {
|
|
47
|
+
if (width < 80 || height < 20) return null
|
|
48
|
+
const guideWidth = rect?.width ?? width * 0.8
|
|
49
|
+
const guideHeight = rect?.height ?? guideWidth / 4
|
|
50
|
+
if (guideHeight > height) return null
|
|
51
|
+
const left = rect?.x ?? (width - guideWidth) / 2
|
|
52
|
+
const top = rect?.y ?? (height - guideHeight) / 2
|
|
53
|
+
const radius = guideWidth / 16 < 6 ? 0 : 1
|
|
54
|
+
const levels: number[] = []
|
|
55
|
+
for (let y = 0; y < scanCodeRows; y++) {
|
|
56
|
+
for (let x = 0; x < scanCodeColumns; x++) {
|
|
57
|
+
const px = Math.trunc(left + (x + 0.5) * guideWidth / scanCodeColumns)
|
|
58
|
+
const py = Math.trunc(top + (y + 0.5) * guideHeight / scanCodeRows)
|
|
59
|
+
let level = 0
|
|
60
|
+
for (let dy = -radius; dy <= radius; dy++) {
|
|
61
|
+
for (let dx = -radius; dx <= radius; dx++) level += luminance(clamp(px + dx, 0, width - 1), clamp(py + dy, 0, height - 1))
|
|
62
|
+
}
|
|
63
|
+
levels.push(level / (radius * 2 + 1) ** 2)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const low = Math.min(...levels), high = Math.max(...levels)
|
|
67
|
+
if (high - low <= 8) return null
|
|
68
|
+
const mid = (low + high) / 2
|
|
69
|
+
return decodeScanCode(levels.map(level => level < mid)) ?? decodeScanCode(levels.map(level => level > mid))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where sixty-four levels part into two tones: the cut that leaves each side
|
|
74
|
+
* closest to its own middle, so a cell buried under a letter does not move
|
|
75
|
+
* it as the middle of the darkest and the lightest would.
|
|
76
|
+
*/
|
|
77
|
+
function partedLevels(levels: readonly number[]): number | null {
|
|
78
|
+
const sorted = [...levels].sort((a, b) => a - b)
|
|
79
|
+
if (sorted[sorted.length - 1] - sorted[0] <= 8) return null
|
|
80
|
+
let total = 0
|
|
81
|
+
for (const value of sorted) total += value
|
|
82
|
+
let best = -1, cut: number | null = null, below = 0
|
|
83
|
+
for (let index = 1; index < sorted.length; index++) {
|
|
84
|
+
below += sorted[index - 1]
|
|
85
|
+
if (sorted[index] === sorted[index - 1]) continue
|
|
86
|
+
const low = below / index, high = (total - below) / (sorted.length - index)
|
|
87
|
+
const between = index * (sorted.length - index) * (high - low) ** 2
|
|
88
|
+
if (between > best) { best = between; cut = (sorted[index] + sorted[index - 1]) / 2 }
|
|
89
|
+
}
|
|
90
|
+
return cut
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The levels measured from the field's own tone where each column stands:
|
|
95
|
+
* the lightest (or, under light words, the darkest) of a column and its
|
|
96
|
+
* neighbours. A field whose colour turns across it, a spectrum month's
|
|
97
|
+
* header cell, or a shadow over half the code then parts as a plain one does.
|
|
98
|
+
*/
|
|
99
|
+
function levelledColumns(levels: readonly number[], lightest: boolean): number[] {
|
|
100
|
+
const ground: number[] = []
|
|
101
|
+
for (let column = 0; column < scanCodeColumns; column++) {
|
|
102
|
+
let found = lightest ? -Infinity : Infinity
|
|
103
|
+
for (let near = Math.max(0, column - 1); near <= Math.min(scanCodeColumns - 1, column + 1); near++) {
|
|
104
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
105
|
+
const level = levels[row * scanCodeColumns + near]
|
|
106
|
+
found = lightest ? Math.max(found, level) : Math.min(found, level)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
ground.push(found)
|
|
110
|
+
}
|
|
111
|
+
return levels.map((level, index) => level - ground[index % scanCodeColumns])
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The share of a cell's samples its own tone is read at: its lighter part under dark words, its darker under light ones. */
|
|
115
|
+
const WRITTEN_SHARES = [0.8, 0.2, 0.95, 0.05] as const
|
|
116
|
+
|
|
117
|
+
/** A code's four corners in the frame: top left, top right, bottom right, bottom left. */
|
|
118
|
+
export type ScanCorners = readonly [x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number]
|
|
119
|
+
|
|
120
|
+
const rectCorners = (rect: ScanRect): ScanCorners => [rect.x, rect.y, rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height]
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reads a code that has words written over it: a calendar's header cell is
|
|
124
|
+
* its sheet's code, two tones of the cell's colour, with Jan 2027 printed on
|
|
125
|
+
* top. The middle of a cell may then lie under a letter, so every cell is
|
|
126
|
+
* read from many points across its middle and the words' ink left out: dark
|
|
127
|
+
* words leave a cell's lighter part its own, light words its darker part.
|
|
128
|
+
* The two tones are parted where they cluster (`partedLevels`), plain and
|
|
129
|
+
* then levelled column by column (`levelledColumns`). The code is given by
|
|
130
|
+
* its rectangle, or by its four corners where the page is held askew. So
|
|
131
|
+
* many readings of one place ask more of the check than one does, so only an
|
|
132
|
+
* ID a scan can open is taken.
|
|
133
|
+
*/
|
|
134
|
+
export function sampleWrittenScanCode(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): string | null {
|
|
135
|
+
const [x0, y0, x1, y1, x2, y2, x3, y3] = 'width' in place ? rectCorners(place) : place
|
|
136
|
+
const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanCodeColumns
|
|
137
|
+
if (cell < 5) return null
|
|
138
|
+
// The cells, each read from many points across `inner` of it, darkest first.
|
|
139
|
+
const sampled = (inner: number): number[][] => {
|
|
140
|
+
const across = Math.max(2, Math.min(7, Math.floor(cell * inner)))
|
|
141
|
+
const cells: number[][] = []
|
|
142
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
143
|
+
for (let column = 0; column < scanCodeColumns; column++) {
|
|
144
|
+
const values: number[] = []
|
|
145
|
+
for (let j = 0; j < across; j++) {
|
|
146
|
+
const v = (row + (1 - inner) / 2 + (inner * (j + 0.5)) / across) / scanCodeRows
|
|
147
|
+
for (let i = 0; i < across; i++) {
|
|
148
|
+
const u = (column + (1 - inner) / 2 + (inner * (i + 0.5)) / across) / scanCodeColumns
|
|
149
|
+
const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
|
|
150
|
+
const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
|
|
151
|
+
values.push(luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1)))
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
values.sort((a, b) => a - b)
|
|
155
|
+
cells.push(values)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return cells
|
|
159
|
+
}
|
|
160
|
+
const taken = (dark: readonly boolean[]): string | null => {
|
|
161
|
+
const id = decodeScanCode(dark as boolean[]) ?? decodeScanCode(dark.map(bit => !bit))
|
|
162
|
+
return id && isSupportedScanId(id) ? id : null
|
|
163
|
+
}
|
|
164
|
+
// Words printed whole over the code: the middle of each cell, where a
|
|
165
|
+
// neighbour's tone never reaches, read at its lighter and its darker parts.
|
|
166
|
+
const middles = sampled(0.6)
|
|
167
|
+
for (const share of WRITTEN_SHARES) {
|
|
168
|
+
const read = middles.map(values => values[Math.round((values.length - 1) * share)])
|
|
169
|
+
for (const levels of [read, levelledColumns(read, share > 0.5)]) {
|
|
170
|
+
const cut = partedLevels(levels)
|
|
171
|
+
if (cut === null) continue
|
|
172
|
+
const id = taken(levels.map(level => level < cut))
|
|
173
|
+
if (id) return id
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return sampleCutScanCode((u, v) => {
|
|
177
|
+
const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
|
|
178
|
+
const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
|
|
179
|
+
return luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1))
|
|
180
|
+
}, cell, taken)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Words cut out of the code itself, two colours and no more: the words
|
|
185
|
+
* change sides cell by cell, ink on the cell's colour and the cell's colour
|
|
186
|
+
* on the ink, so a cell is the colour most of it is. Where a letter takes
|
|
187
|
+
* about half a cell neither colour is most of it; such cells, a few at the
|
|
188
|
+
* most, are read both ways, fewest changed first, and the check says which
|
|
189
|
+
* reading is the code.
|
|
190
|
+
*
|
|
191
|
+
* `at` gives the light at a place in the code, 0 to 1 across and down.
|
|
192
|
+
*/
|
|
193
|
+
function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => string | null): string | null {
|
|
194
|
+
const n = Math.max(4, Math.min(8, Math.round(cell * 0.8)))
|
|
195
|
+
const count = scanCodeColumns * scanCodeRows, each = n * n
|
|
196
|
+
const light = new Float32Array(count * each)
|
|
197
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
198
|
+
for (let column = 0; column < scanCodeColumns; column++) {
|
|
199
|
+
const base = (row * scanCodeColumns + column) * each
|
|
200
|
+
for (let j = 0; j < n; j++) {
|
|
201
|
+
for (let i = 0; i < n; i++) light[base + j * n + i] = at((column + 0.05 + (0.9 * (i + 0.5)) / n) / scanCodeColumns, (row + 0.05 + (0.9 * (j + 0.5)) / n) / scanCodeRows)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// Dark or light is judged against a column and its neighbours, since a cell's colour may turn across the code.
|
|
206
|
+
const share = new Float32Array(count)
|
|
207
|
+
for (let column = 0; column < scanCodeColumns; column++) {
|
|
208
|
+
const near: number[] = []
|
|
209
|
+
for (let other = Math.max(0, column - 1); other <= Math.min(scanCodeColumns - 1, column + 1); other++) {
|
|
210
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
211
|
+
const base = (row * scanCodeColumns + other) * each
|
|
212
|
+
for (let index = 0; index < each; index++) near.push(light[base + index])
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
near.sort((a, b) => a - b)
|
|
216
|
+
const low = near[Math.floor(near.length * 0.1)], high = near[Math.floor(near.length * 0.9)]
|
|
217
|
+
if (high - low <= 16) return null
|
|
218
|
+
const cut = (low + high) / 2
|
|
219
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
220
|
+
const index = row * scanCodeColumns + column
|
|
221
|
+
let dark = 0
|
|
222
|
+
for (let k = 0; k < each; k++) if (light[index * each + k] < cut) dark++
|
|
223
|
+
share[index] = dark / each
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const dark = Array.from(share, part => part > 0.5)
|
|
227
|
+
const unsure: number[] = []
|
|
228
|
+
share.forEach((part, index) => { if (Math.abs(part - 0.5) < WRITTEN_UNSURE) unsure.push(index) })
|
|
229
|
+
if (unsure.length > 8) return null
|
|
230
|
+
const ways = Array.from({ length: 1 << unsure.length }, (_, way) => way).sort((a, b) => ones(a) - ones(b))
|
|
231
|
+
for (const way of ways) {
|
|
232
|
+
const read = [...dark]
|
|
233
|
+
unsure.forEach((index, bit) => { if (way & (1 << bit)) read[index] = !read[index] })
|
|
234
|
+
const id = taken(read)
|
|
235
|
+
if (id) return id
|
|
236
|
+
}
|
|
237
|
+
return null
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** How near half of a cell the words may take before it is read both ways. */
|
|
241
|
+
const WRITTEN_UNSURE = 0.2
|
|
242
|
+
const ones = (value: number): number => { let count = 0; for (; value; value &= value - 1) count++; return count }
|
|
243
|
+
|
|
244
|
+
/** A line through points that mostly lie on it: `b` the middle of every pair's slope, `a` the middle of what is left, so a stray point moves neither. */
|
|
245
|
+
function lineThrough(points: readonly (readonly [number, number])[]): { a: number; b: number } | null {
|
|
246
|
+
if (points.length < 3) return null
|
|
247
|
+
const middle = (values: number[]) => values.sort((p, q) => p - q)[Math.floor(values.length / 2)]
|
|
248
|
+
const slopes: number[] = []
|
|
249
|
+
for (let i = 0; i < points.length; i++) {
|
|
250
|
+
for (let j = i + 1; j < points.length; j++) {
|
|
251
|
+
if (points[j][0] !== points[i][0]) slopes.push((points[j][1] - points[i][1]) / (points[j][0] - points[i][0]))
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (!slopes.length) return null
|
|
255
|
+
const b = middle(slopes)
|
|
256
|
+
return { a: middle(points.map(([t, value]) => value - b * t)), b }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Finds a code under words anywhere in the frame and reads it. Its cell is a
|
|
261
|
+
* field of colour on its paper, four to one: every other pixel is weighed,
|
|
262
|
+
* the pixels that stand apart from the paper (by their colour, or by their
|
|
263
|
+
* light against the frame's commonest and its lightest tones) are gathered
|
|
264
|
+
* into the fields that touch, and a field of a code's shape has a line laid
|
|
265
|
+
* along each of its four edges, so a page held askew is read along its own
|
|
266
|
+
* corners and not the frame's (`sampleWrittenScanCode`).
|
|
267
|
+
*/
|
|
268
|
+
export function locateWrittenScanCode(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
|
|
269
|
+
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
270
|
+
if (columns < 40 || rows < 10) return null
|
|
271
|
+
const size = columns * rows
|
|
272
|
+
const levels = new Uint8Array(size)
|
|
273
|
+
const histogram = new Uint32Array(256)
|
|
274
|
+
for (let y = 0, index = 0; y < rows; y++) {
|
|
275
|
+
for (let x = 0; x < columns; x++, index++) histogram[levels[index] = clamp(Math.round(luminance(x * step, y * step)), 0, 255)]++
|
|
276
|
+
}
|
|
277
|
+
// The paper: the commonest tone in the frame, and where a wall or a desk is commoner, the tone a tenth of the frame is lighter than.
|
|
278
|
+
let paper = 0
|
|
279
|
+
for (let level = 1; level < 256; level++) if (histogram[level] > histogram[paper]) paper = level
|
|
280
|
+
let light = 255
|
|
281
|
+
for (let above = histogram[255]; light > 0 && above < size / 10; above += histogram[--light]);
|
|
282
|
+
const masks: ((index: number) => boolean)[] = [index => chroma((index % columns) * step, Math.floor(index / columns) * step)]
|
|
283
|
+
for (const ground of Math.abs(paper - light) > 8 ? [paper, light] : [paper]) {
|
|
284
|
+
for (const apart of [14, 30]) masks.push(index => Math.abs(levels[index] - ground) > apart)
|
|
285
|
+
}
|
|
286
|
+
// 0 unseen, -1 not of the mask, else the field it belongs to.
|
|
287
|
+
const fields = new Int32Array(size)
|
|
288
|
+
const stack = new Int32Array(size)
|
|
289
|
+
for (const mask of masks) {
|
|
290
|
+
fields.fill(0)
|
|
291
|
+
let field = 0
|
|
292
|
+
for (let start = 0; start < size; start++) {
|
|
293
|
+
if (fields[start]) continue
|
|
294
|
+
if (!mask(start)) { fields[start] = -1; continue }
|
|
295
|
+
field++
|
|
296
|
+
let left = columns, right = 0, top = rows, bottom = 0, count = 0, depth = 0
|
|
297
|
+
stack[depth++] = start
|
|
298
|
+
fields[start] = field
|
|
299
|
+
while (depth) {
|
|
300
|
+
const index = stack[--depth]
|
|
301
|
+
const x = index % columns, y = (index - x) / columns
|
|
302
|
+
count++
|
|
303
|
+
if (x < left) left = x
|
|
304
|
+
if (x > right) right = x
|
|
305
|
+
if (y < top) top = y
|
|
306
|
+
if (y > bottom) bottom = y
|
|
307
|
+
for (const next of [x > 0 ? index - 1 : -1, x < columns - 1 ? index + 1 : -1, y > 0 ? index - columns : -1, y < rows - 1 ? index + columns : -1]) {
|
|
308
|
+
if (next < 0 || fields[next]) continue
|
|
309
|
+
if (mask(next)) { fields[next] = field; stack[depth++] = next } else fields[next] = -1
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
// A code's shape, however the page leans: about four to one, and mostly filled, its words the only holes.
|
|
313
|
+
const w = right - left + 1, h = bottom - top + 1
|
|
314
|
+
if (w * step < 80 || h * step < 16 || w / h < 2.6 || w / h > 5 || count < w * h * 0.5) continue
|
|
315
|
+
const of = (x: number, y: number) => fields[y * columns + x] === field
|
|
316
|
+
// A line along each edge, from where the field begins a tenth in from its corners, which are rounded.
|
|
317
|
+
const edge = (along: number, from: number, to: number, crosswise: boolean): number | null => {
|
|
318
|
+
const direction = to > from ? 1 : -1
|
|
319
|
+
for (let at = from; at !== to + direction; at += direction) {
|
|
320
|
+
if (crosswise ? of(at, along) : of(along, at)) return (at - direction * 0.5) * step
|
|
321
|
+
}
|
|
322
|
+
return null
|
|
323
|
+
}
|
|
324
|
+
const points = (count: number, low: number, span: number, find: (along: number) => number | null) => {
|
|
325
|
+
const found: [number, number][] = []
|
|
326
|
+
for (let k = 0; k < count; k++) {
|
|
327
|
+
const along = low + Math.round((0.12 + (0.76 * k) / (count - 1)) * (span - 1))
|
|
328
|
+
const at = find(along)
|
|
329
|
+
if (at !== null) found.push([along * step, at])
|
|
330
|
+
}
|
|
331
|
+
return lineThrough(found)
|
|
332
|
+
}
|
|
333
|
+
const topLine = points(12, left, w, x => edge(x, top, bottom, false))
|
|
334
|
+
const bottomLine = points(12, left, w, x => edge(x, bottom, top, false))
|
|
335
|
+
const leftLine = points(7, top, h, y => edge(y, left, right, true))
|
|
336
|
+
const rightLine = points(7, top, h, y => edge(y, right, left, true))
|
|
337
|
+
if (!topLine || !bottomLine || !leftLine || !rightLine) continue
|
|
338
|
+
// Where an edge along (y = a + b·x) meets an edge down (x = a + b·y).
|
|
339
|
+
const meet = (alongLine: { a: number; b: number }, downLine: { a: number; b: number }): [number, number] => {
|
|
340
|
+
const x = (downLine.a + downLine.b * alongLine.a) / (1 - downLine.b * alongLine.b)
|
|
341
|
+
return [x, alongLine.a + alongLine.b * x]
|
|
342
|
+
}
|
|
343
|
+
const corners = [meet(topLine, leftLine), meet(topLine, rightLine), meet(bottomLine, rightLine), meet(bottomLine, leftLine)]
|
|
344
|
+
const middleX = (corners[0][0] + corners[1][0] + corners[2][0] + corners[3][0]) / 4
|
|
345
|
+
const middleY = (corners[0][1] + corners[1][1] + corners[2][1] + corners[3][1]) / 4
|
|
346
|
+
// The field's edge is soft in a photograph: read it as found, then a little in and a little out.
|
|
347
|
+
for (const scale of [1, 0.97, 1.03]) {
|
|
348
|
+
const place = corners.flatMap(([x, y]) => [middleX + (x - middleX) * scale, middleY + (y - middleY) * scale]) as unknown as ScanCorners
|
|
349
|
+
const id = sampleWrittenScanCode(width, height, luminance, place)
|
|
350
|
+
if (id) return { id, rect: { x: left * step, y: top * step, width: w * step, height: h * step } }
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return null
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Groups disconnected accent cells into horizontal 4:1 code regions, without a finder border. */
|
|
358
|
+
export function scanCodeRegions(width: number, height: number, foreground: Chroma): ScanRect[] {
|
|
359
|
+
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
360
|
+
if (columns <= 0 || rows <= 0) return []
|
|
361
|
+
const mask = new Uint8Array(columns * rows)
|
|
362
|
+
const occupied = new Uint8Array(rows)
|
|
363
|
+
for (let y = 0; y < rows; y++) {
|
|
364
|
+
let count = 0
|
|
365
|
+
for (let x = 0; x < columns; x++) {
|
|
366
|
+
if (foreground(x * step, y * step)) { mask[y * columns + x] = 1; count++ }
|
|
367
|
+
}
|
|
368
|
+
occupied[y] = count >= 8 ? 1 : 0
|
|
369
|
+
}
|
|
370
|
+
const result: ScanRect[] = []
|
|
371
|
+
const seen = new Set<number>()
|
|
372
|
+
const take = (left: number, top: number, right: number, bottom: number) => {
|
|
373
|
+
const w = (right - left + 1) * step, h = (bottom - top + 1) * step
|
|
374
|
+
if (w < 48 || h < 8 || Math.abs(w / h - 4) >= 0.6) return
|
|
375
|
+
const key = ((left * 4099 + top) * 4099 + right) * 4099 + bottom
|
|
376
|
+
if (seen.has(key)) return
|
|
377
|
+
seen.add(key)
|
|
378
|
+
result.push({ x: left * step, y: top * step, width: w, height: h })
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* A code standing beside something else on its rows, the year large on a
|
|
382
|
+
* calendar's cover or a product's name before a sheet's code, is not the whole
|
|
383
|
+
* of its band: the band is as tall as its tallest thing. So each run
|
|
384
|
+
* across a band is looked at again by itself: drawn in to the rows and
|
|
385
|
+
* columns its own ink stands on, parted where it has a gap wider than it
|
|
386
|
+
* is now tall, and each part looked at the same way; and where a part is
|
|
387
|
+
* still wider than a code, the code may be its left or its right end.
|
|
388
|
+
*/
|
|
389
|
+
const cut = (left: number, top: number, right: number, bottom: number, depth: number) => {
|
|
390
|
+
const inked = (x: number, from: number, to: number) => { for (let row = from; row <= to; row++) if (mask[row * columns + x]) return true; return false }
|
|
391
|
+
const lined = (row: number) => { let count = 0; for (let x = left; x <= right; x++) if (mask[row * columns + x] && ++count >= 2) return true; return false }
|
|
392
|
+
while (top < bottom && !lined(top)) top++
|
|
393
|
+
while (bottom > top && !lined(bottom)) bottom--
|
|
394
|
+
while (left < right && !inked(left, top, bottom)) left++
|
|
395
|
+
while (right > left && !inked(right, top, bottom)) right--
|
|
396
|
+
const h = bottom - top + 1
|
|
397
|
+
if (h * step < 8 || (right - left + 1) * step < 48) return
|
|
398
|
+
take(left, top, right, bottom)
|
|
399
|
+
if (depth <= 0) return
|
|
400
|
+
// Parted across, where a gap is wider than the part is tall.
|
|
401
|
+
const parts: [number, number][] = []
|
|
402
|
+
let from = left, last = left
|
|
403
|
+
for (let x = left + 1; x <= right; x++) {
|
|
404
|
+
if (!inked(x, top, bottom)) continue
|
|
405
|
+
if (x - last > h) { parts.push([from, last]); from = x }
|
|
406
|
+
last = x
|
|
407
|
+
}
|
|
408
|
+
parts.push([from, last])
|
|
409
|
+
if (parts.length > 1) { for (const [start, end] of parts) cut(start, top, end, bottom, depth - 1); return }
|
|
410
|
+
// Parted down, where more than three rows stand empty.
|
|
411
|
+
const bands: [number, number][] = []
|
|
412
|
+
let first = top, lastRow = top
|
|
413
|
+
for (let row = top + 1; row <= bottom; row++) {
|
|
414
|
+
if (!lined(row)) continue
|
|
415
|
+
if (row - lastRow > 4) { bands.push([first, lastRow]); first = row }
|
|
416
|
+
lastRow = row
|
|
417
|
+
}
|
|
418
|
+
bands.push([first, lastRow])
|
|
419
|
+
if (bands.length > 1) { for (const [start, end] of bands) cut(left, start, right, end, depth - 1); return }
|
|
420
|
+
// Wider than a code: the code may be either end of it.
|
|
421
|
+
if ((right - left + 1) / h > 4.6) {
|
|
422
|
+
cut(right - 4 * h + 1, top, right, bottom, 0)
|
|
423
|
+
cut(left, top, left + 4 * h - 1, bottom, 0)
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
let y = 0
|
|
427
|
+
while (y < rows) {
|
|
428
|
+
if (!occupied[y]) { y++; continue }
|
|
429
|
+
const top = y
|
|
430
|
+
let bottom = y
|
|
431
|
+
while (y < rows && y - bottom <= 3) {
|
|
432
|
+
if (occupied[y]) bottom = y
|
|
433
|
+
y++
|
|
434
|
+
}
|
|
435
|
+
const h = (bottom - top + 1) * step
|
|
436
|
+
if (h < 8) continue
|
|
437
|
+
const xs: number[] = []
|
|
438
|
+
for (let x = 0; x < columns; x++) {
|
|
439
|
+
for (let row = top; row <= bottom; row++) {
|
|
440
|
+
if (mask[row * columns + x]) { xs.push(x); break }
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
let index = 0
|
|
444
|
+
while (index < xs.length) {
|
|
445
|
+
const left = xs[index]
|
|
446
|
+
let right = left
|
|
447
|
+
index++
|
|
448
|
+
while (index < xs.length && (xs[index] - right) * step <= h) { right = xs[index]; index++ }
|
|
449
|
+
const w = (right - left + 1) * step
|
|
450
|
+
if (h <= Math.floor(height / 3) && w >= 48 && Math.abs(w / h - 4) < 0.6) take(left, top, right, bottom)
|
|
451
|
+
cut(left, top, right, bottom, 3)
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return result
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** A code read from a frame, and the rectangle it was read from. */
|
|
458
|
+
export type ScanFound = { id: string; rect: ScanRect }
|
|
459
|
+
|
|
460
|
+
/** Locates and decodes an upright code anywhere in a camera frame; mirrors the native reader. */
|
|
461
|
+
export function readScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): string | null {
|
|
462
|
+
return locateScanFrame(width, height, luminance, chroma)?.id ?? null
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** As `readScanFrame`, saying where in the frame the code stands. */
|
|
466
|
+
export function locateScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
|
|
467
|
+
// Every rectangle tried, kept for a second look past words.
|
|
468
|
+
const tried: ScanRect[] = []
|
|
469
|
+
const read = (bounds: ScanRect): ScanFound | null => {
|
|
470
|
+
tried.push(bounds)
|
|
471
|
+
for (const fraction of [0, 0.05]) {
|
|
472
|
+
const rect = insetRect(bounds, bounds.width * fraction, bounds.height * fraction)
|
|
473
|
+
// Detection samples every second pixel; refine its origin before reading tiny cells.
|
|
474
|
+
for (const dy of [0, -1, 1]) {
|
|
475
|
+
for (const dx of [0, -1, 1]) {
|
|
476
|
+
const at = offsetRect(rect, dx, dy)
|
|
477
|
+
const id = sampleScanCode(width, height, luminance, at)
|
|
478
|
+
if (id) return { id, rect: at }
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return null
|
|
483
|
+
}
|
|
484
|
+
// The page itself may be chromatic too; exclude its dark pixels from the accent mask.
|
|
485
|
+
const colored = scanCodeRegions(width, height, (x, y) => luminance(x, y) > 70 && chroma(x, y))
|
|
486
|
+
for (const bounds of colored) {
|
|
487
|
+
const id = read(bounds)
|
|
488
|
+
if (id) return id
|
|
489
|
+
}
|
|
490
|
+
// Neutral accents have no chroma. Locate their light/dark rectangle using luminance.
|
|
491
|
+
let darkest = 255, lightest = 0
|
|
492
|
+
for (let y = 0; y < height; y += 8) {
|
|
493
|
+
for (let x = 0; x < width; x += 8) {
|
|
494
|
+
const value = luminance(x, y)
|
|
495
|
+
darkest = Math.min(darkest, value)
|
|
496
|
+
lightest = Math.max(lightest, value)
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
for (const threshold of [(darkest + lightest) / 2, 60, 130, 200]) {
|
|
500
|
+
for (const light of [true, false]) {
|
|
501
|
+
const candidates = scanCodeRegions(width, height, (x, y) => (light ? luminance(x, y) > threshold : luminance(x, y) < threshold))
|
|
502
|
+
for (const bounds of candidates) {
|
|
503
|
+
const id = read(bounds)
|
|
504
|
+
if (id) return id
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const w = width * 0.8
|
|
509
|
+
const guide = read({ x: (width - w) / 2, y: (height - w / 4) / 2, width: w, height: w / 4 })
|
|
510
|
+
if (guide) return guide
|
|
511
|
+
// Nothing read plainly: a code under words, a calendar's header cell. As a
|
|
512
|
+
// field of colour on its paper first (`locateWrittenScanCode`); then, where
|
|
513
|
+
// its cells stand on a cell as white as the paper, in the rectangles its
|
|
514
|
+
// ink was found in.
|
|
515
|
+
const field = locateWrittenScanCode(width, height, luminance, chroma)
|
|
516
|
+
if (field) return field
|
|
517
|
+
for (const bounds of tried) {
|
|
518
|
+
if (bounds.width < 80) continue
|
|
519
|
+
for (const fraction of [0, 0.03]) {
|
|
520
|
+
const rect = insetRect(bounds, bounds.width * fraction, bounds.height * fraction)
|
|
521
|
+
const id = sampleWrittenScanCode(width, height, luminance, rect)
|
|
522
|
+
if (id) return { id, rect }
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return null
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/** Reads an upright RGBA frame, deriving luminance and chroma the way the native YCbCr reader does. */
|
|
529
|
+
export function readRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): string | null {
|
|
530
|
+
return locateRgbaScanFrame(rgba, width, height)?.id ?? null
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** The luminance of an RGBA frame, as the reader weighs it. */
|
|
534
|
+
export function rgbaLuminance(rgba: Uint8Array | Uint8ClampedArray, width: number): Luminance {
|
|
535
|
+
return (x, y) => {
|
|
536
|
+
const p = (y * width + x) * 4
|
|
537
|
+
return 0.2126 * rgba[p] + 0.7152 * rgba[p + 1] + 0.0722 * rgba[p + 2]
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** As `readRgbaScanFrame`, saying where in the frame the code stands. */
|
|
542
|
+
export function locateRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): ScanFound | null {
|
|
543
|
+
if (rgba.length < width * height * 4) return null
|
|
544
|
+
const luminance = rgbaLuminance(rgba, width)
|
|
545
|
+
const chroma: Chroma = (x, y) => {
|
|
546
|
+
const p = (y * width + x) * 4
|
|
547
|
+
const r = rgba[p], g = rgba[p + 1], b = rgba[p + 2]
|
|
548
|
+
const cb = -0.1687 * r - 0.3313 * g + 0.5 * b
|
|
549
|
+
const cr = 0.5 * r - 0.4187 * g - 0.0813 * b
|
|
550
|
+
return Math.abs(cb) + Math.abs(cr) > 26
|
|
551
|
+
}
|
|
552
|
+
return locateScanFrame(width, height, luminance, chroma)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Accepts an ID only after three consecutive matching frames. */
|
|
556
|
+
export class StableScan {
|
|
557
|
+
private last: string | null = null
|
|
558
|
+
private count = 0
|
|
559
|
+
accept(id: string | null): string | null {
|
|
560
|
+
if (!id) { this.last = null; this.count = 0; return null }
|
|
561
|
+
if (id === this.last) this.count++
|
|
562
|
+
else { this.last = id; this.count = 1 }
|
|
563
|
+
return this.count >= 3 ? id : null
|
|
564
|
+
}
|
|
565
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/** Encoding and SVG artwork; camera pixel sampling stays in scanCode.ts. */
|
|
2
|
+
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
3
|
+
|
|
4
|
+
export const scanCodeColumns = 16
|
|
5
|
+
export const scanCodeRows = 4
|
|
6
|
+
/** The joined code's corners, a tenth of a cell: half an item cell's, 2 of its 20. */
|
|
7
|
+
export const CODE_END_RADIUS = 0.1
|
|
8
|
+
|
|
9
|
+
export function scanCodeChecksum(bytes: readonly number[]): number {
|
|
10
|
+
let crc = 0xffff
|
|
11
|
+
for (const byte of bytes) {
|
|
12
|
+
crc ^= byte << 8
|
|
13
|
+
for (let bit = 0; bit < 8; bit++) crc = ((crc << 1) ^ (crc & 0x8000 ? 0x1021 : 0)) & 0xffff
|
|
14
|
+
}
|
|
15
|
+
return crc
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Format 3: 16 × 4 upright cells, matching the iOS scanner and playground. */
|
|
19
|
+
export function encodeScanCode(id: string): boolean[] | null {
|
|
20
|
+
if (!/^[A-Za-z0-9]{6}$/.test(id)) return null
|
|
21
|
+
let value = 0
|
|
22
|
+
for (const character of id) value = value * 62 + alphabet.indexOf(character)
|
|
23
|
+
const bytes = [3]
|
|
24
|
+
for (let shift = 32; shift >= 0; shift -= 8) bytes.push(Math.floor(value / 2 ** shift) & 255)
|
|
25
|
+
const crc = scanCodeChecksum(bytes)
|
|
26
|
+
bytes.push(crc >> 8, crc & 255)
|
|
27
|
+
return bytes.flatMap(byte => Array.from({ length: 8 }, (_, bit) => !!(byte & (1 << (7 - bit)))))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A code's inked cells as one SVG path, each row's run of neighbours one
|
|
32
|
+
* rectangle. Drawn as separate squares, every square's edge is softened on
|
|
33
|
+
* its own and a hairline of the backing shows where two meet; one path is
|
|
34
|
+
* softened only at its outline. `ink` says which cells are inked (a list's
|
|
35
|
+
* code inks its clear bits), `cell` is a cell's size and `x`, `y` where the
|
|
36
|
+
* code's corner stands.
|
|
37
|
+
*
|
|
38
|
+
* With a `radius` (a share of a cell) every corner is rounded, the ink's and
|
|
39
|
+
* the backing's alike, as item cells are: a run's corner is rounded when
|
|
40
|
+
* nothing inked stands against it above or below (a lone dot round all
|
|
41
|
+
* round, whatever touches it across a corner), and stays square where the
|
|
42
|
+
* shape carries on into the next row; and where the ink turns an inside
|
|
43
|
+
* corner the backing's corner is rounded by filling it with ink. The reader
|
|
44
|
+
* samples the middle of each cell, so corners rounded by less than half a
|
|
45
|
+
* cell never change what it reads.
|
|
46
|
+
*/
|
|
47
|
+
export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) => !bit, cell = 1, x = 0, y = 0, radius = 0 }: { ink?: (bit: boolean) => boolean; cell?: number; x?: number; y?: number; radius?: number } = {}): string {
|
|
48
|
+
const round = (value: number) => Math.round(value * 1e4) / 1e4
|
|
49
|
+
const inked = (row: number, column: number) =>
|
|
50
|
+
row >= 0 && row < scanCodeRows && column >= 0 && column < scanCodeColumns && ink(bits[row * scanCodeColumns + column])
|
|
51
|
+
const r = Math.min(Math.max(radius, 0), 0.5) * cell
|
|
52
|
+
let d = ''
|
|
53
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
54
|
+
for (let column = 0; column < scanCodeColumns;) {
|
|
55
|
+
if (!inked(row, column)) { column++; continue }
|
|
56
|
+
const start = column
|
|
57
|
+
while (column < scanCodeColumns && inked(row, column)) column++
|
|
58
|
+
const left = x + start * cell, right = x + column * cell, top = y + row * cell, bottom = top + cell
|
|
59
|
+
if (!r) {
|
|
60
|
+
d += `M${round(left)} ${round(top)}h${round(right - left)}v${round(cell)}h${round(left - right)}z`
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
// A corner is rounded wherever the ink stops both ways, straight across
|
|
64
|
+
// and along: a lone dot is round at every corner, even where another
|
|
65
|
+
// touches it across a corner.
|
|
66
|
+
const end = (facing: number, inside: number) => !inked(facing, inside) ? r : 0
|
|
67
|
+
const tl = end(row - 1, start)
|
|
68
|
+
const tr = end(row - 1, column - 1)
|
|
69
|
+
const br = end(row + 1, column - 1)
|
|
70
|
+
const bl = end(row + 1, start)
|
|
71
|
+
const arc = (radius: number, toX: number, toY: number) => radius ? `A${round(radius)} ${round(radius)} 0 0 1 ${round(toX)} ${round(toY)}` : ''
|
|
72
|
+
d += `M${round(left + tl)} ${round(top)}H${round(right - tr)}${arc(tr, right, top + tr)}`
|
|
73
|
+
d += `V${round(bottom - br)}${arc(br, right - br, bottom)}`
|
|
74
|
+
d += `H${round(left + bl)}${arc(bl, left, bottom - bl)}`
|
|
75
|
+
d += `V${round(top + tl)}${arc(tl, left + tl, top)}Z`
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (!r) return d
|
|
79
|
+
// The backing's corners round too: where the ink turns an inside corner,
|
|
80
|
+
// three cells of it round a clear one, the clear cell's corner is filled
|
|
81
|
+
// with ink to the same radius. Where the ink only touches across a corner,
|
|
82
|
+
// the ink's own corners are rounded instead.
|
|
83
|
+
for (let row = 0; row < scanCodeRows; row++) {
|
|
84
|
+
for (let column = 0; column < scanCodeColumns; column++) {
|
|
85
|
+
if (inked(row, column)) continue
|
|
86
|
+
const left = x + column * cell, top = y + row * cell
|
|
87
|
+
for (const [dy, dx] of [[-1, -1], [-1, 1], [1, 1], [1, -1]] as const) {
|
|
88
|
+
if (!inked(row + dy, column) || !inked(row, column + dx) || !inked(row + dy, column + dx)) continue
|
|
89
|
+
const cornerX = left + (dx > 0 ? cell : 0), cornerY = top + (dy > 0 ? cell : 0)
|
|
90
|
+
const alongX = cornerX - dx * r, alongY = cornerY - dy * r
|
|
91
|
+
// From the corner along the cell's edge, round the arc to its other edge, and back.
|
|
92
|
+
const sweep = dx * dy > 0 ? 0 : 1
|
|
93
|
+
d += `M${round(cornerX)} ${round(cornerY)}H${round(alongX)}A${round(r)} ${round(r)} 0 0 ${sweep} ${round(cornerX)} ${round(alongY)}Z`
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return d
|
|
98
|
+
}
|
|
99
|
+
|
package/src/shapes.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IDv1: short codes whose shape says what they name, so one address,
|
|
3
|
+
* `example.com/<code>`, can be an account, a list or an item and never two of
|
|
4
|
+
* them. Every code is six characters. Capitals matter: Ab12Cd and ab12cd are
|
|
5
|
+
* two codes.
|
|
6
|
+
*
|
|
7
|
+
* - An account is two letters and four digits, the letters from the person's
|
|
8
|
+
* name: Jo4712.
|
|
9
|
+
* - A product is four letters and two digits: AbCd12. It is always scanned,
|
|
10
|
+
* never typed, and whoever signs up with a product's code may hold it as
|
|
11
|
+
* their account's code, so it is an account's shape too.
|
|
12
|
+
* - A list is two digits and four letters: 12ABCD. New lists draw capitals
|
|
13
|
+
* only; older ones may hold small letters, and both are read.
|
|
14
|
+
* - An item is two letters, two digits and two letters or digits, not both
|
|
15
|
+
* digits (that would be an account): Ab12Cd.
|
|
16
|
+
*
|
|
17
|
+
* No two shapes can be the same code.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
21
|
+
export const CAPITALS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
22
|
+
export const DIGITS = '0123456789'
|
|
23
|
+
|
|
24
|
+
/** An account's code made from a name: Jo4712. */
|
|
25
|
+
export const NAME_CODE = /^[A-Za-z]{2}\d{4}$/
|
|
26
|
+
/** A product's code: AbCd12. */
|
|
27
|
+
export const PRODUCT_CODE = /^[A-Za-z]{4}\d{2}$/
|
|
28
|
+
/** Any code an account may hold: a name's or a product's. */
|
|
29
|
+
export const ACCOUNT_CODE = /^(?:[A-Za-z]{2}\d{4}|[A-Za-z]{4}\d{2})$/
|
|
30
|
+
/** A list's code: 12ABCD, small letters read too. */
|
|
31
|
+
export const LIST_CODE = /^\d{2}[A-Za-z]{4}$/
|
|
32
|
+
/** An item's code: Ab12Cd, with at least one letter in the last two. */
|
|
33
|
+
export const ITEM_CODE = /^[A-Za-z]{2}\d{2}(?:[A-Za-z][A-Za-z0-9]|\d[A-Za-z])$/
|
|
34
|
+
|
|
35
|
+
import { blockedProductCode } from './words'
|
|
36
|
+
|
|
37
|
+
export type CodeKind = 'account' | 'product' | 'list' | 'item'
|
|
38
|
+
|
|
39
|
+
export const isAccountCode = (value: string): boolean => ACCOUNT_CODE.test(value)
|
|
40
|
+
export const isProductCode = (value: string): boolean => PRODUCT_CODE.test(value)
|
|
41
|
+
export const isListCode = (value: string): boolean => LIST_CODE.test(value)
|
|
42
|
+
export const isItemCode = (value: string): boolean => ITEM_CODE.test(value)
|
|
43
|
+
|
|
44
|
+
/** What a code names by its shape alone, or null when it is no IDv1 code. A product's shape reads as `product`. */
|
|
45
|
+
export function codeKind(value: string): CodeKind | null {
|
|
46
|
+
if (NAME_CODE.test(value)) return 'account'
|
|
47
|
+
if (PRODUCT_CODE.test(value)) return 'product'
|
|
48
|
+
if (LIST_CODE.test(value)) return 'list'
|
|
49
|
+
if (ITEM_CODE.test(value)) return 'item'
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type Random = () => number
|
|
54
|
+
const pick = (chars: string, random: Random) => chars[Math.floor(random() * chars.length)]
|
|
55
|
+
|
|
56
|
+
/** Letters a Latin alphabet writes with a mark or as one of its own, as plain ones. */
|
|
57
|
+
const PLAIN: Record<string, string> = { ø: 'o', æ: 'a', œ: 'o', ß: 's', ð: 'd', þ: 't', ł: 'l', đ: 'd', ı: 'i' }
|
|
58
|
+
|
|
59
|
+
/** The plain Latin letters of a word, in order: Åse is ase, Øystein oystein. */
|
|
60
|
+
function latinLetters(value: string): string {
|
|
61
|
+
return [...value.normalize('NFKD').toLowerCase()]
|
|
62
|
+
.map(letter => PLAIN[letter] ?? letter)
|
|
63
|
+
.join('')
|
|
64
|
+
.replace(/[^a-z]/g, '')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The two letters an account's code starts with: from the first name, a
|
|
69
|
+
* capital and a small one (Leo is Le, Henrik He), else from the email
|
|
70
|
+
* address, else none, and the caller draws them at random.
|
|
71
|
+
*/
|
|
72
|
+
export function nameLetters(name: string, email = ''): string | null {
|
|
73
|
+
const words = name.trim().split(/\s+/)
|
|
74
|
+
for (const source of [words[0] ?? '', name, email.split('@')[0] ?? '']) {
|
|
75
|
+
const letters = latinLetters(source)
|
|
76
|
+
if (letters.length >= 2) return letters[0].toUpperCase() + letters[1]
|
|
77
|
+
}
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The codes to try are drawn at random and kept when nothing holds them yet;
|
|
83
|
+
* whether one is free is the product's to check. `random` gives numbers in
|
|
84
|
+
* [0, 1), Math.random unless a test passes its own.
|
|
85
|
+
*/
|
|
86
|
+
|
|
87
|
+
/** An account's code: the name's letters (or two at random) and four digits. */
|
|
88
|
+
export function accountCodeCandidate(letters: string | null, random: Random = Math.random): string {
|
|
89
|
+
const start = letters ?? pick(LETTERS, random) + pick(LETTERS, random)
|
|
90
|
+
return start + String(Math.floor(random() * 10000)).padStart(4, '0')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A product's code: four letters, capital or small, and two digits. Nobody
|
|
95
|
+
* types one, it is always scanned, so codes differing only in capitals are
|
|
96
|
+
* different codes. Letters that spell a rude or awkward word, capitals aside,
|
|
97
|
+
* and awkward digits are drawn again (`blockedProductCode` in words.ts).
|
|
98
|
+
*/
|
|
99
|
+
export function productCodeCandidate(random: Random = Math.random): string {
|
|
100
|
+
for (let attempt = 0; attempt < 1000; attempt++) {
|
|
101
|
+
const code = Array.from({ length: 4 }, () => pick(LETTERS, random)).join('') + String(Math.floor(random() * 100)).padStart(2, '0')
|
|
102
|
+
if (!blockedProductCode(code)) return code
|
|
103
|
+
}
|
|
104
|
+
throw new Error('No product code could be drawn.')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A list's code: two digits and four capitals. */
|
|
108
|
+
export function listCodeCandidate(random: Random = Math.random): string {
|
|
109
|
+
return pick(DIGITS, random) + pick(DIGITS, random) + Array.from({ length: 4 }, () => pick(CAPITALS, random)).join('')
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** An item's code: two letters, two digits, then two letters or digits with at least one letter. */
|
|
113
|
+
export function itemCodeCandidate(random: Random = Math.random): string {
|
|
114
|
+
const start = pick(LETTERS, random) + pick(LETTERS, random) + pick(DIGITS, random) + pick(DIGITS, random)
|
|
115
|
+
const first = pick(LETTERS + DIGITS, random)
|
|
116
|
+
const second = pick(LETTERS + DIGITS, random)
|
|
117
|
+
// At least one letter among the last two, or it would be an account's shape.
|
|
118
|
+
return start + (/\d/.test(first) && /\d/.test(second) ? pick(LETTERS, random) : first) + second
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Every way a name-shaped code's two letters can be written, for a product
|
|
123
|
+
* that must keep a code free in all its capitals (Jo4712, jo4712, JO4712, jO4712).
|
|
124
|
+
*/
|
|
125
|
+
export function accountCodeCaseVariants(code: string): string[] {
|
|
126
|
+
const [first, second] = [code[0], code[1]].map(letter => [...new Set([letter.toUpperCase(), letter.toLowerCase()])])
|
|
127
|
+
return first.flatMap(a => second.map(b => a + b + code.slice(2)))
|
|
128
|
+
}
|
package/src/space.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many IDv1 codes of each kind there can be, as the candidates in
|
|
3
|
+
* `shapes.ts` draw them, so a product can show how much of each is used and
|
|
4
|
+
* how much is left.
|
|
5
|
+
*
|
|
6
|
+
* - Accounts made from a name, LLnnnn: 52² × 10⁴, 27 million.
|
|
7
|
+
* - Products, LLLLnn: 52⁴ × 10², 731 million, before the blocked words.
|
|
8
|
+
* - Lists, nnLLLL with capitals: 10² × 26⁴, 46 million.
|
|
9
|
+
* - Items, LLnnXX with a letter in the last two: 52² × 10² × (62² − 10²), 1 billion.
|
|
10
|
+
*/
|
|
11
|
+
const LETTERS = 52
|
|
12
|
+
const CAPITALS = 26
|
|
13
|
+
const DIGITS = 10
|
|
14
|
+
|
|
15
|
+
export const ID_SPACE = {
|
|
16
|
+
accounts: LETTERS ** 2 * DIGITS ** 4,
|
|
17
|
+
products: LETTERS ** 4 * DIGITS ** 2,
|
|
18
|
+
lists: DIGITS ** 2 * CAPITALS ** 4,
|
|
19
|
+
items: LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2),
|
|
20
|
+
} as const
|
|
21
|
+
|
|
22
|
+
export type IdSpaceKind = keyof typeof ID_SPACE
|
|
23
|
+
|
|
24
|
+
/** The share used, as a percentage, and how many are left. */
|
|
25
|
+
export function idUsage(kind: IdSpaceKind, used: number): { used: number; space: number; left: number; percent: number } {
|
|
26
|
+
const space = ID_SPACE[kind]
|
|
27
|
+
return { used, space, left: Math.max(0, space - used), percent: (used / space) * 100 }
|
|
28
|
+
}
|
package/src/words.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Words a paper product's code must never spell. A product's code is four
|
|
3
|
+
* letters and two digits (`productCodeCandidate` in shapes.ts),
|
|
4
|
+
* printed on every page and on the wrapper, and the account code of whoever signs up
|
|
5
|
+
* with it, so its four letters are read as a word whether anyone means them
|
|
6
|
+
* to be or not. A code is passed over when its letters, capitals aside, hold
|
|
7
|
+
* one of these anywhere in them (`blockedCodeLetters`): FUCK12, xFuk34 and
|
|
8
|
+
* Pass56 are all skipped, the last for the word inside it, which costs a few
|
|
9
|
+
* harmless codes and nothing else.
|
|
10
|
+
*
|
|
11
|
+
* Rude, crude or hurtful words, and a few merely awkward ones, in English,
|
|
12
|
+
* Danish, Japanese romaji, and the other languages the app speaks or a shop
|
|
13
|
+
* sells in. Three-letter entries catch a word inside a longer run, so they
|
|
14
|
+
* are kept to ones that are rude almost wherever they stand. The list is
|
|
15
|
+
* small on purpose: skipping a code costs nothing, since there are 731
|
|
16
|
+
* million of them.
|
|
17
|
+
*/
|
|
18
|
+
export const BLOCKED_CODE_WORDS: readonly string[] = [
|
|
19
|
+
// English
|
|
20
|
+
'fuck', 'fuk', 'fck', 'fux', 'shit', 'sht', 'crap', 'turd', 'piss', 'cunt', 'twat', 'dick', 'dik', 'cock', 'knob',
|
|
21
|
+
'wank', 'jizz', 'cum', 'porn', 'sex', 'anal', 'anus', 'arse', 'ass', 'butt', 'boob', 'tit', 'puss', 'slut',
|
|
22
|
+
'whor', 'hoe', 'bich', 'btch', 'bitc', 'damn', 'hell', 'suck', 'fart', 'puke', 'barf', 'poo', 'smeg', 'dumb', 'ugly',
|
|
23
|
+
'fat', 'kill', 'dead', 'rape', 'hate', 'nazi', 'hitl', 'heil', 'kkk', 'isis', 'fag', 'nig', 'nigg', 'coon', 'spic',
|
|
24
|
+
'kike', 'gook', 'paki', 'dyke', 'homo', 'tard',
|
|
25
|
+
// Words naming who someone is, which a code handed to a stranger should never say.
|
|
26
|
+
'jew', 'gay',
|
|
27
|
+
// Danish
|
|
28
|
+
'lort', 'pik', 'pis', 'fis', 'fiss', 'kuss', 'knep', 'hore', 'lude', 'skid', 'nege', 'fand', 'svin', 'klam',
|
|
29
|
+
// Japanese, in romaji
|
|
30
|
+
'baka', 'aho', 'kuso', 'unko', 'mank', 'chnk', 'ecch', 'etch', 'ero', 'hent', 'kasu', 'kuzu',
|
|
31
|
+
'busu', 'debu', 'hage', 'kich', 'yari', 'oppa',
|
|
32
|
+
// German, Swedish, Spanish, French, Italian, Portuguese, Korean, Chinese
|
|
33
|
+
'fick', 'fotz', 'hure', 'kack', 'arsc', 'fitt', 'kuk', 'hora', 'knul', 'puta', 'puto', 'cono', 'culo', 'mier', 'jode',
|
|
34
|
+
'pene', 'verg', 'merd', 'pute', 'bite', 'salo', 'cazz', 'figa', 'porr', 'ssib', 'shib', 'tmd', 'cao',
|
|
35
|
+
] as const
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Two digits awkward on a pad: 42 and 49 read as 死に (to die) and 死苦
|
|
39
|
+
* (suffering) in Japanese, where the pads are made and many are sold, and 69
|
|
40
|
+
* in English. Codes ending in them are passed over too.
|
|
41
|
+
*/
|
|
42
|
+
export const BLOCKED_CODE_DIGITS: readonly string[] = ['42', '49', '69'] as const
|
|
43
|
+
|
|
44
|
+
/** Whether a run of letters spells a blocked word anywhere in it, capitals aside. */
|
|
45
|
+
export function blockedCodeLetters(letters: string): boolean {
|
|
46
|
+
const small = letters.toLowerCase()
|
|
47
|
+
return BLOCKED_CODE_WORDS.some(word => small.includes(word))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Whether a product code, `LLLLnn`, is one never to print: a blocked word in its letters, or awkward digits. */
|
|
51
|
+
export function blockedProductCode(code: string): boolean {
|
|
52
|
+
return blockedCodeLetters(code.slice(0, 4)) || BLOCKED_CODE_DIGITS.includes(code.slice(4))
|
|
53
|
+
}
|