| 1 |
import {CAMERA_MODEL_PARAM_COUNTS} from "./camera_models"; |
| 2 |
import {composeRigid} from "./math"; |
| 3 |
import type { |
| 4 |
Camera, |
| 5 |
ImageRecord, |
| 6 |
LocalFile, |
| 7 |
Point3DData, |
| 8 |
Quat, |
| 9 |
Reconstruction, |
| 10 |
Rigid3d, |
| 11 |
SparseModelCandidate, |
| 12 |
Vec3, |
| 13 |
} from "./types"; |
| 14 |
|
| 15 |
class BinaryReader { |
| 16 |
private readonly view: DataView; |
| 17 |
private offset = 0; |
| 18 |
|
| 19 |
constructor(buffer: ArrayBuffer, private readonly label: string) { |
| 20 |
this.view = new DataView(buffer); |
| 21 |
} |
| 22 |
|
| 23 |
private require(bytes: number): void { |
| 24 |
if (bytes < 0 || this.offset + bytes > this.view.byteLength) { |
| 25 |
throw new Error(`${this.label} is truncated at byte ${this.offset}`); |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
u8(): number { this.require(1); return this.view.getUint8(this.offset++); } |
| 30 |
i32(): number { this.require(4); const value = this.view.getInt32(this.offset, true); this.offset += 4; return value; } |
| 31 |
u32(): number { this.require(4); const value = this.view.getUint32(this.offset, true); this.offset += 4; return value; } |
| 32 |
u64(): bigint { this.require(8); const value = this.view.getBigUint64(this.offset, true); this.offset += 8; return value; } |
| 33 |
f64(): number { this.require(8); const value = this.view.getFloat64(this.offset, true); this.offset += 8; return value; } |
| 34 |
skip(bytes: number): void { this.require(bytes); this.offset += bytes; } |
| 35 |
|
| 36 |
count(name: string, minimumBytesPerItem = 1): number { |
| 37 |
const value = this.u64(); |
| 38 |
if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`${this.label} has an invalid ${name}`); |
| 39 |
const count = Number(value); |
| 40 |
if (count > Math.floor(this.remaining / minimumBytesPerItem)) throw new Error(`${this.label} has an invalid ${name}`); |
| 41 |
return count; |
| 42 |
} |
| 43 |
|
| 44 |
string(): string { |
| 45 |
const bytes: number[] = []; |
| 46 |
while (true) { |
| 47 |
const byte = this.u8(); |
| 48 |
if (byte === 0) break; |
| 49 |
bytes.push(byte); |
| 50 |
} |
| 51 |
return new TextDecoder("utf-8", {fatal: true}).decode(new Uint8Array(bytes)); |
| 52 |
} |
| 53 |
|
| 54 |
get remaining(): number { return this.view.byteLength - this.offset; } |
| 55 |
} |
| 56 |
|
| 57 |
interface Rig { |
| 58 |
id: number; |
| 59 |
refSensor: string; |
| 60 |
sensors: Map<string, Rigid3d | null>; |
| 61 |
} |
| 62 |
|
| 63 |
interface Frame { |
| 64 |
id: number; |
| 65 |
rigId: number; |
| 66 |
rigFromWorld: Rigid3d; |
| 67 |
data: Array<{sensor: string; dataId: bigint}>; |
| 68 |
} |
| 69 |
|
| 70 |
function sensorKey(type: number, id: number): string { return `${type}:${id}`; } |
| 71 |
function readQuat(reader: BinaryReader): Quat { return [reader.f64(), reader.f64(), reader.f64(), reader.f64()]; } |
| 72 |
function readVec3(reader: BinaryReader): Vec3 { return [reader.f64(), reader.f64(), reader.f64()]; } |
| 73 |
function readRigid(reader: BinaryReader): Rigid3d { |
| 74 |
const transform = {rotation: readQuat(reader), translation: readVec3(reader)}; |
| 75 |
if (![...transform.rotation, ...transform.translation].every(Number.isFinite)) throw new Error("Reconstruction contains a non-finite pose"); |
| 76 |
return transform; |
| 77 |
} |
| 78 |
|
| 79 |
function parseCameras(buffer: ArrayBuffer): Map<number, Camera> { |
| 80 |
const reader = new BinaryReader(buffer, "cameras.bin"); |
| 81 |
const count = reader.count("camera count", 24); |
| 82 |
const cameras = new Map<number, Camera>(); |
| 83 |
for (let i = 0; i < count; ++i) { |
| 84 |
const id = reader.u32(); |
| 85 |
const modelId = reader.i32(); |
| 86 |
const paramCount = CAMERA_MODEL_PARAM_COUNTS[modelId]; |
| 87 |
if (paramCount === undefined) throw new Error(`Unsupported camera model id ${modelId}`); |
| 88 |
const widthBig = reader.u64(); |
| 89 |
const heightBig = reader.u64(); |
| 90 |
if (widthBig > BigInt(Number.MAX_SAFE_INTEGER) || heightBig > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`Camera ${id} has invalid dimensions`); |
| 91 |
const params = Array.from({length: paramCount}, () => reader.f64()); |
| 92 |
if (widthBig === 0n || heightBig === 0n || !params.every(Number.isFinite)) throw new Error(`Camera ${id} has invalid parameters`); |
| 93 |
cameras.set(id, {id, modelId, width: Number(widthBig), height: Number(heightBig), params}); |
| 94 |
} |
| 95 |
if (reader.remaining !== 0) throw new Error("cameras.bin contains trailing data"); |
| 96 |
return cameras; |
| 97 |
} |
| 98 |
|
| 99 |
function parseRigs(buffer: ArrayBuffer): Map<number, Rig> { |
| 100 |
const reader = new BinaryReader(buffer, "rigs.bin"); |
| 101 |
const count = reader.count("rig count", 8); |
| 102 |
const rigs = new Map<number, Rig>(); |
| 103 |
for (let i = 0; i < count; ++i) { |
| 104 |
const id = reader.u32(); |
| 105 |
const sensorCount = reader.u32(); |
| 106 |
if (sensorCount > reader.remaining / 8) throw new Error("rigs.bin has an invalid sensor count"); |
| 107 |
let refSensor = ""; |
| 108 |
const sensors = new Map<string, Rigid3d | null>(); |
| 109 |
if (sensorCount > 0) { |
| 110 |
refSensor = sensorKey(reader.i32(), reader.u32()); |
| 111 |
sensors.set(refSensor, {rotation: [1, 0, 0, 0], translation: [0, 0, 0]}); |
| 112 |
} |
| 113 |
for (let j = 1; j < sensorCount; ++j) { |
| 114 |
const sensor = sensorKey(reader.i32(), reader.u32()); |
| 115 |
sensors.set(sensor, reader.u8() ? readRigid(reader) : null); |
| 116 |
} |
| 117 |
rigs.set(id, {id, refSensor, sensors}); |
| 118 |
} |
| 119 |
if (reader.remaining !== 0) throw new Error("rigs.bin contains trailing data"); |
| 120 |
return rigs; |
| 121 |
} |
| 122 |
|
| 123 |
function parseFrames(buffer: ArrayBuffer): Map<number, Frame> { |
| 124 |
const reader = new BinaryReader(buffer, "frames.bin"); |
| 125 |
const count = reader.count("frame count", 68); |
| 126 |
const frames = new Map<number, Frame>(); |
| 127 |
for (let i = 0; i < count; ++i) { |
| 128 |
const id = reader.u32(); |
| 129 |
const rigId = reader.u32(); |
| 130 |
const rigFromWorld = readRigid(reader); |
| 131 |
const dataCount = reader.u32(); |
| 132 |
if (dataCount > reader.remaining / 16) throw new Error("frames.bin has an invalid data count"); |
| 133 |
const data = Array.from({length: dataCount}, () => ({ |
| 134 |
sensor: sensorKey(reader.i32(), reader.u32()), |
| 135 |
dataId: reader.u64(), |
| 136 |
})); |
| 137 |
frames.set(id, {id, rigId, rigFromWorld, data}); |
| 138 |
} |
| 139 |
if (reader.remaining !== 0) throw new Error("frames.bin contains trailing data"); |
| 140 |
return frames; |
| 141 |
} |
| 142 |
|
| 143 |
function parseImages( |
| 144 |
buffer: ArrayBuffer, |
| 145 |
rigs: Map<number, Rig> | null, |
| 146 |
frames: Map<number, Frame> | null, |
| 147 |
): Map<number, ImageRecord> { |
| 148 |
const reader = new BinaryReader(buffer, "images.bin"); |
| 149 |
const count = reader.count("image count", 72); |
| 150 |
const images = new Map<number, ImageRecord>(); |
| 151 |
const imageToFrame = new Map<bigint, Frame>(); |
| 152 |
if (frames) for (const frame of frames.values()) for (const data of frame.data) if (data.sensor.startsWith("0:")) imageToFrame.set(data.dataId, frame); |
| 153 |
|
| 154 |
for (let i = 0; i < count; ++i) { |
| 155 |
const id = reader.u32(); |
| 156 |
const serializedPose = readRigid(reader); |
| 157 |
const cameraId = reader.u32(); |
| 158 |
const name = reader.string(); |
| 159 |
const pointCount = reader.count("point2D count", 24); |
| 160 |
const points2D = {xy: new Float64Array(pointCount * 2), point3DIds: new BigUint64Array(pointCount)}; |
| 161 |
for (let pointIdx = 0; pointIdx < pointCount; ++pointIdx) { |
| 162 |
const x = reader.f64(); |
| 163 |
const y = reader.f64(); |
| 164 |
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error(`Image ${id} has a non-finite observation`); |
| 165 |
points2D.xy[pointIdx * 2] = x; |
| 166 |
points2D.xy[pointIdx * 2 + 1] = y; |
| 167 |
points2D.point3DIds[pointIdx] = reader.u64(); |
| 168 |
} |
| 169 |
|
| 170 |
let camFromWorld = serializedPose; |
| 171 |
let frameId = id; |
| 172 |
let rigId = cameraId; |
| 173 |
if (rigs && frames) { |
| 174 |
const frame = imageToFrame.get(BigInt(id)); |
| 175 |
if (!frame) throw new Error(`No frame contains image ${id}`); |
| 176 |
const rig = rigs.get(frame.rigId); |
| 177 |
if (!rig) throw new Error(`Frame ${frame.id} references missing rig ${frame.rigId}`); |
| 178 |
const sensorFromRig = rig.sensors.get(sensorKey(0, cameraId)); |
| 179 |
if (sensorFromRig === undefined) throw new Error(`Rig ${rig.id} does not contain camera ${cameraId}`); |
| 180 |
if (sensorFromRig === null) throw new Error(`Rig ${rig.id} has no pose for camera ${cameraId}`); |
| 181 |
camFromWorld = composeRigid(sensorFromRig, frame.rigFromWorld); |
| 182 |
frameId = frame.id; |
| 183 |
rigId = rig.id; |
| 184 |
} |
| 185 |
images.set(id, {id, cameraId, frameId, rigId, name, camFromWorld, points2D}); |
| 186 |
} |
| 187 |
if (reader.remaining !== 0) throw new Error("images.bin contains trailing data"); |
| 188 |
return images; |
| 189 |
} |
| 190 |
|
| 191 |
function parsePoints3D(buffer: ArrayBuffer): Point3DData { |
| 192 |
const scan = new BinaryReader(buffer, "points3D.bin"); |
| 193 |
const count = scan.count("point3D count", 51); |
| 194 |
if (count > 0xffffffff) throw new Error("points3D.bin has too many points for this browser"); |
| 195 |
const sourceIds = new BigUint64Array(count); |
| 196 |
const trackLengths = new Uint32Array(count); |
| 197 |
let totalTracks = 0; |
| 198 |
let sorted = true; |
| 199 |
for (let i = 0; i < count; ++i) { |
| 200 |
const id = scan.u64(); |
| 201 |
sourceIds[i] = id; |
| 202 |
sorted &&= i === 0 || sourceIds[i - 1]! < id; |
| 203 |
scan.skip(35); |
| 204 |
const trackLength = scan.count("track length", 8); |
| 205 |
if (trackLength > 0xffffffff || totalTracks + trackLength > 0xffffffff) { |
| 206 |
throw new Error("points3D.bin has too many track elements for this browser"); |
| 207 |
} |
| 208 |
trackLengths[i] = trackLength; |
| 209 |
totalTracks += trackLength; |
| 210 |
scan.skip(trackLength * 8); |
| 211 |
} |
| 212 |
if (scan.remaining !== 0) throw new Error("points3D.bin contains trailing data"); |
| 213 |
|
| 214 |
let ids = sourceIds; |
| 215 |
let destinationForSource: Uint32Array | null = null; |
| 216 |
let sourceForDestination: Uint32Array | null = null; |
| 217 |
if (!sorted) { |
| 218 |
sourceForDestination = new Uint32Array(count); |
| 219 |
for (let index = 0; index < count; ++index) sourceForDestination[index] = index; |
| 220 |
sourceForDestination.sort((a, b) => sourceIds[a]! < sourceIds[b]! ? -1 : sourceIds[a]! > sourceIds[b]! ? 1 : 0); |
| 221 |
ids = new BigUint64Array(count); |
| 222 |
destinationForSource = new Uint32Array(count); |
| 223 |
for (let destination = 0; destination < count; ++destination) { |
| 224 |
const source = sourceForDestination[destination]!; |
| 225 |
ids[destination] = sourceIds[source]!; |
| 226 |
destinationForSource[source] = destination; |
| 227 |
} |
| 228 |
} |
| 229 |
for (let i = 1; i < count; ++i) if (ids[i - 1] === ids[i]) throw new Error(`points3D.bin contains duplicate point id ${ids[i]}`); |
| 230 |
|
| 231 |
const points: Point3DData = { |
| 232 |
ids, |
| 233 |
xyz: new Float64Array(count * 3), |
| 234 |
colors: new Uint8Array(count * 3), |
| 235 |
errors: new Float32Array(count), |
| 236 |
trackOffsets: new Uint32Array(count + 1), |
| 237 |
trackImageIds: new Uint32Array(totalTracks), |
| 238 |
trackPoint2DIdxs: new Uint32Array(totalTracks), |
| 239 |
}; |
| 240 |
for (let destination = 0; destination < count; ++destination) { |
| 241 |
const source = sourceForDestination?.[destination] ?? destination; |
| 242 |
points.trackOffsets[destination + 1] = points.trackOffsets[destination]! + trackLengths[source]!; |
| 243 |
} |
| 244 |
|
| 245 |
const reader = new BinaryReader(buffer, "points3D.bin"); |
| 246 |
reader.count("point3D count", 51); |
| 247 |
for (let source = 0; source < count; ++source) { |
| 248 |
const destination = destinationForSource?.[source] ?? source; |
| 249 |
const id = reader.u64(); |
| 250 |
const xyz = readVec3(reader); |
| 251 |
const color: [number, number, number] = [reader.u8(), reader.u8(), reader.u8()]; |
| 252 |
const error = reader.f64(); |
| 253 |
if (![...xyz, error].every(Number.isFinite)) throw new Error(`Point ${id} contains non-finite values`); |
| 254 |
points.xyz.set(xyz, destination * 3); |
| 255 |
points.colors.set(color, destination * 3); |
| 256 |
points.errors[destination] = error; |
| 257 |
const trackLength = reader.count("track length", 8); |
| 258 |
let trackIndex = points.trackOffsets[destination]!; |
| 259 |
for (let i = 0; i < trackLength; ++i, ++trackIndex) { |
| 260 |
points.trackImageIds[trackIndex] = reader.u32(); |
| 261 |
points.trackPoint2DIdxs[trackIndex] = reader.u32(); |
| 262 |
} |
| 263 |
} |
| 264 |
return points; |
| 265 |
} |
| 266 |
|
| 267 |
export function normalizePath(path: string): string { |
| 268 |
return path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+/g, "/"); |
| 269 |
} |
| 270 |
|
| 271 |
export function discoverSparseModels(entries: LocalFile[]): SparseModelCandidate[] { |
| 272 |
const groups = new Map<string, Map<string, File>>(); |
| 273 |
for (const entry of entries) { |
| 274 |
const path = normalizePath(entry.path); |
| 275 |
const slash = path.lastIndexOf("/"); |
| 276 |
const directory = slash < 0 ? "." : path.slice(0, slash); |
| 277 |
const basename = path.slice(slash + 1); |
| 278 |
const files = groups.get(directory) ?? new Map<string, File>(); |
| 279 |
files.set(basename, entry.file); |
| 280 |
groups.set(directory, files); |
| 281 |
} |
| 282 |
return [...groups] |
| 283 |
.filter(([, files]) => ["cameras.bin", "images.bin", "points3D.bin"].every((name) => files.has(name))) |
| 284 |
.map(([path, files]) => ({path, files})) |
| 285 |
.sort((a, b) => a.path.localeCompare(b.path)); |
| 286 |
} |
| 287 |
|
| 288 |
export async function parseReconstruction(files: Map<string, File>): Promise<Reconstruction> { |
| 289 |
const required = ["cameras.bin", "images.bin", "points3D.bin"]; |
| 290 |
for (const name of required) if (!files.has(name)) throw new Error(`Missing ${name}`); |
| 291 |
const hasRigs = files.has("rigs.bin"); |
| 292 |
const hasFrames = files.has("frames.bin"); |
| 293 |
if (hasRigs !== hasFrames) throw new Error("Modern reconstructions require both rigs.bin and frames.bin"); |
| 294 |
const buffers = await Promise.all([ |
| 295 |
files.get("cameras.bin")!.arrayBuffer(), |
| 296 |
files.get("images.bin")!.arrayBuffer(), |
| 297 |
files.get("points3D.bin")!.arrayBuffer(), |
| 298 |
hasRigs ? files.get("rigs.bin")!.arrayBuffer() : Promise.resolve(null), |
| 299 |
hasFrames ? files.get("frames.bin")!.arrayBuffer() : Promise.resolve(null), |
| 300 |
]); |
| 301 |
const parsedRigs = buffers[3] ? parseRigs(buffers[3]) : null; |
| 302 |
const parsedFrames = buffers[4] ? parseFrames(buffers[4]) : null; |
| 303 |
const modernRigFormat = Boolean(parsedRigs && parsedFrames && (parsedRigs.size > 0 || parsedFrames.size > 0)); |
| 304 |
const rigs = modernRigFormat ? parsedRigs : null; |
| 305 |
const frames = modernRigFormat ? parsedFrames : null; |
| 306 |
const cameras = parseCameras(buffers[0]); |
| 307 |
const images = parseImages(buffers[1], rigs, frames); |
| 308 |
for (const image of images.values()) if (!cameras.has(image.cameraId)) throw new Error(`Image ${image.id} references missing camera ${image.cameraId}`); |
| 309 |
return {cameras, images, points3D: parsePoints3D(buffers[2]), modernRigFormat}; |
| 310 |
} |
| 311 |
|
| 312 |
export function reconstructionTransferables(reconstruction: Reconstruction): ArrayBuffer[] { |
| 313 |
const points = reconstruction.points3D; |
| 314 |
const buffers = [ |
| 315 |
points.ids.buffer, |
| 316 |
points.xyz.buffer, |
| 317 |
points.colors.buffer, |
| 318 |
points.errors.buffer, |
| 319 |
points.trackOffsets.buffer, |
| 320 |
points.trackImageIds.buffer, |
| 321 |
points.trackPoint2DIdxs.buffer, |
| 322 |
] as ArrayBuffer[]; |
| 323 |
for (const image of reconstruction.images.values()) { |
| 324 |
buffers.push(image.points2D.xy.buffer as ArrayBuffer, image.points2D.point3DIds.buffer as ArrayBuffer); |
| 325 |
} |
| 326 |
return buffers; |
| 327 |
} |