Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ Built clean-room under the [IOExtend](https://github.com/IOExtend) organization.
- Packs geometry compactly: positions quantized to 16-bit steps of 2⁻¹⁰ m (error at most 0.49 mm, 0.85 mm for rotated shared geometry; geometry larger than about 64 m, or shared geometry that an instance scales up, stays 32-bit float), octahedral 16-bit normals, 16- or 32-bit indices, all in one base64 block.
- Shifts coordinates relative to the model centre (RTC), so georeferenced models with coordinates around 10⁶ m do not jitter.
- Draws large models with few draw calls: geometry is merged into spatial chunks per material (very large models draw their repeated shapes as instanced copies instead), and hiding, selection and colouring are per-object data, so they never rebuild geometry.
- Viewer interface in Russian or English, chosen from the browser language:
- Viewer interface in English, Russian, Spanish, German, French, Portuguese, Italian, Japanese, Korean, and simplified and traditional Chinese. The language picker works offline in standalone HTML. Choose Auto to follow the browser’s preferred languages. Changing the language reloads the viewer with its initial view.
- Viewer tools
- model tree with search and filters by source model, level and category, a properties panel and a selected/total counter;
- toolbar with labelled groups: navigation, sections, measure, display and view;
- context menu: properties, hide, isolate, show all, zoom to object, section box around the object, copy Id;
Expand Down
386 changes: 193 additions & 193 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

56 changes: 50 additions & 6 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const dictionaries = {
import { languageOption, locales, matchLocale, preferredLocale, storedLanguage, storeLanguage } from './locale.js';
import { additionalDictionaries } from './translations.js';

export const dictionaries = {
...additionalDictionaries,
ru: {
elements: 'Элементов',
noGeometry: 'Нет геометрии',
Expand Down Expand Up @@ -124,6 +128,14 @@ const dictionaries = {
'player.date': 'Дата графика',
'player.speed': 'Скорость',
truncated: 'Показано {meshes} из {total} мешей: модель обрезана настройкой MaxMeshVertices',
language: 'Язык',
auto: 'Авто',
model3d: '3D-модель',
retry: 'Повторить загрузку',
finding: 'Поиск элемента…',
streamLod: '{size} МиБ · точная геометрия {shown}/{total}',
streamMesh: '{size} МиБ · Кластеров {visible} · Уточняется {fallback}',
streamTiles: 'Участков {areas} · Детализация {shown}/{total} · {size}/{limit} МиБ',
},
en: {
elements: 'Elements',
Expand Down Expand Up @@ -250,15 +262,47 @@ const dictionaries = {
'player.date': 'Schedule date',
'player.speed': 'Speed',
truncated: 'Showing {meshes} of {total} meshes: the model was truncated by the MaxMeshVertices setting',
language: 'Language',
auto: 'Auto',
model3d: '3D model',
retry: 'Retry downloads',
finding: 'Finding element…',
streamLod: '{size} MiB · full detail {shown}/{total}',
streamMesh: '{size} MiB · Clusters {visible} · Refining {fallback}',
streamTiles: '{areas} areas · Detail {shown}/{total} · {size}/{limit} MiB',
},
};

export const lang = (globalThis.navigator?.language ?? '').toLowerCase().startsWith('ru') ? 'ru' : 'en';
const storageKey = 'ioviewer-language';
const hostLanguage = globalThis.parent && globalThis.parent !== globalThis &&
matchLocale(new URLSearchParams(location.hash.slice(1)).get('ioextendLang'));
const selected = new URLSearchParams(globalThis.location?.search).get('lang');
const saved = selected === 'auto' ? selected : matchLocale(selected) ?? storedLanguage(storageKey);
export const lang = hostLanguage || matchLocale(saved) ||
preferredLocale(globalThis.navigator?.languages?.length ? navigator.languages : [globalThis.navigator?.language]);
export const formatCount = new Intl.NumberFormat(lang).format;

// `language` is for tests; the UI always uses `lang`.
export function t(key, language = lang) {
const text = dictionaries[language][key];
export function t(key, language = lang, values) {
const text = dictionaries[language]?.[key];
if (text === undefined) throw new Error(`Missing UI string '${key}'.`);
return text;
return values ? text.replace(/\{(\w+)\}/g, (_, name) => values[name]) : text;
}

export function setupLanguage() {
document.documentElement.lang = lang;
document.querySelector('canvas').setAttribute('aria-label', t('model3d'));
if (hostLanguage) return;
const select = document.createElement('select');
select.id = 'ioviewer-language';
select.className = 'ioviewer-floating';
select.setAttribute('aria-label', t('language'));
select.append(new Option(t('auto'), 'auto'), ...locales.map(languageOption));
select.value = matchLocale(saved) ?? 'auto';
select.addEventListener('change', () => {
storeLanguage(storageKey, select.value);
const url = new URL(location.href);
url.searchParams.set('lang', select.value);
location.replace(url);
});
document.querySelector('#ioviewer-ui').append(select);
}
39 changes: 39 additions & 0 deletions src/IOViewer/Viewer/src/locale.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
export const locales = ['en', 'ru', 'es', 'de', 'fr', 'pt', 'it', 'ja', 'ko', 'zh-Hans', 'zh-Hant'];

export function matchLocale(tag) {
if (typeof tag !== 'string' || !tag) return undefined;
try {
const locale = new Intl.Locale(tag);
const candidate = locale.language === 'zh' ? `zh-${locale.maximize().script}` : locale.language;
return locales.includes(candidate) ? candidate : undefined;
} catch (error) {
if (!(error instanceof RangeError)) throw error;
return undefined;
}
}

export function preferredLocale(languages = []) {
return languages.map(matchLocale).find(Boolean) ?? 'en';
}

export function languageOption(locale) {
const label = new Intl.DisplayNames(locale, { type: 'language' }).of(locale);
const option = new Option(label, locale);
option.lang = locale;
return option;
}

export function storedLanguage(key) {
try { return globalThis.localStorage?.getItem(key); }
catch (error) {
if (error.name !== 'SecurityError') throw error;
return null;
}
}

export function storeLanguage(key, value) {
try { globalThis.localStorage?.setItem(key, value); }
catch (error) {
if (!['SecurityError', 'QuotaExceededError'].includes(error.name)) throw error;
}
}
4 changes: 2 additions & 2 deletions src/IOViewer/Viewer/src/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as THREE from 'three';
import { loadModelData, ModelDataError, readModelMeta } from './data.js';
import { ModelScene, ModelTooLargeError } from './engine/modelScene.js';
import { lang, t } from './i18n.js';
import { setupLanguage, t } from './i18n.js';
import { NavigationControls, needsLogarithmicDepth } from './nav/controls.js';
import { ViewCube } from './nav/viewCube.js';
import { Picker } from './engine/picking.js';
Expand All @@ -22,7 +22,7 @@ import { mountClashes } from './ui/clashesPanel.js';
import { mountTimeliner } from './ui/timeliner.js';
import { mountLinks } from './ui/linksPanel.js';

document.documentElement.lang = lang;
setupLanguage();
const canvas = document.getElementById('ioviewer-canvas');
const testOptions = window.IOVIEWER_TEST ?? {};
const startup = testOptions.startup;
Expand Down
12 changes: 6 additions & 6 deletions src/IOViewer/Viewer/src/stream/lod.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as THREE from 'three';
import { lang, t } from '../i18n.js';
import { formatCount, setupLanguage, t } from '../i18n.js';
import { NavigationControls } from '../nav/controls.js';
import { MESH_BUDGET, MIB } from './manifest.js';
import { detailInputBytes, detailMeshBytes, FACES, INSTANCE_FLOATS, STEP, VERTICES, validateClusters } from './clusters.js';
Expand All @@ -10,10 +10,9 @@ const status = document.querySelector('#ioviewer-status');
const message = document.querySelector('#ioviewer-message');
const fit = document.querySelector('#fit');
const retry = document.querySelector('#retry');
const ru = lang === 'ru';
document.documentElement.lang = lang;
setupLanguage();
fit.textContent = t('tool.fit');
retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads';
retry.textContent = t('retry');

function show(text) {
message.textContent = text;
Expand Down Expand Up @@ -259,8 +258,9 @@ function start(manifest, instances, context) {
renderer.render(world, camera);
resolveReady(performance.now());
if (animating || transferred.length) requestFrame();
status.textContent = ru ? `${Math.ceil(bytes / MIB)} МиБ · точная геометрия ${shown[3]}/${candidates.length}`
: `${Math.ceil(bytes / MIB)} MiB · full detail ${shown[3]}/${candidates.length}`;
status.textContent = t('streamLod', undefined, {
size: formatCount(Math.ceil(bytes / MIB)), shown: formatCount(shown[3]), total: formatCount(candidates.length),
});
retry.hidden = failed.size === 0;
if (failed.size) retry.title = [...failed.values()].join('\n');
}
Expand Down
14 changes: 7 additions & 7 deletions src/IOViewer/Viewer/src/stream/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as THREE from 'three';
import { lang, t } from '../i18n.js';
import { formatCount, setupLanguage, t } from '../i18n.js';
import { NavigationControls } from '../nav/controls.js';
import { MAX_TILE_MESH, MESH_BUDGET, MIB, validateManifest } from './manifest.js';

Expand All @@ -8,10 +8,9 @@ const status = document.querySelector('#ioviewer-status');
const message = document.querySelector('#ioviewer-message');
const fit = document.querySelector('#fit');
const retry = document.querySelector('#retry');
const ru = lang === 'ru';
document.documentElement.lang = lang;
setupLanguage();
fit.textContent = t('tool.fit');
retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads';
retry.textContent = t('retry');

function show(text) {
message.textContent = text;
Expand Down Expand Up @@ -203,9 +202,10 @@ function start(manifest, context) {
}
if (uploaded.length) requestFrame();
const shown = wanted.filter((key) => resident.get(key)?.next > 0).length;
status.textContent = ru
? `Участков ${tiles.length} · Детализация ${shown}/${wanted.length} · ${Math.ceil(bytes / MIB)} МиБ / ${MESH_BUDGET / MIB} МиБ`
: `${tiles.length} areas · Detail ${shown}/${wanted.length} · ${Math.ceil(bytes / MIB)} MiB / ${MESH_BUDGET / MIB} MiB`;
status.textContent = t('streamTiles', undefined, {
areas: formatCount(tiles.length), shown: formatCount(shown), total: formatCount(wanted.length),
size: formatCount(Math.ceil(bytes / MIB)), limit: formatCount(MESH_BUDGET / MIB),
});
retry.hidden = failed.size === 0;
if (failed.size) retry.title = [...failed].map(([key, error]) => `${key.tile.file}: ${error}`).join('\n');
}
Expand Down
14 changes: 7 additions & 7 deletions src/IOViewer/Viewer/src/stream/meshLod.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as THREE from 'three';
import { lang, t } from '../i18n.js';
import { formatCount, setupLanguage, t } from '../i18n.js';
import { NavigationControls } from '../nav/controls.js';
import { ViewCube } from '../nav/viewCube.js';
import { el } from '../ui/dom.js';
Expand All @@ -16,10 +16,9 @@ const retry = document.querySelector('#retry');
const status = el('span');
document.querySelector('#stream-controls').append(status);
document.querySelector('#fit').remove();
const ru = lang === 'ru';
const profile = window.IOVIEWER_MESH_PROFILE;
document.documentElement.lang = lang;
retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads';
setupLanguage();
retry.textContent = t('retry');

function show(text) {
message.textContent = text;
Expand Down Expand Up @@ -211,7 +210,7 @@ async function start(manifest, context) {
updateMaterials();
});
const tools = mountMeshTools({ manifest, roots, nodes, bounds, world, controls, canvas, scene,
fetchPage, ru, render: requestFrame, canFill: context.getContextAttributes()?.stencil === true && roots.some((node) => node.hasClosed),
fetchPage, render: requestFrame, canFill: context.getContextAttributes()?.stencil === true && roots.some((node) => node.hasClosed),
setBackground: (color) => renderer.setClearColor(color) });
let caps, capWorld, capMaterials;
function renderStencils(renderer, camera, plane) {
Expand Down Expand Up @@ -503,8 +502,9 @@ async function start(manifest, context) {
}
resolveReady(performance.now());
if (transferred.length || warm.length) requestFrame();
status.textContent = ru ? `${Math.ceil(bytes / MIB)} МиБ · Кластеров ${visible} · Уточняется ${fallback}`
: `${Math.ceil(bytes / MIB)} MiB · ${visible} clusters · ${fallback} refining`;
status.textContent = t('streamMesh', undefined, {
size: formatCount(Math.ceil(bytes / MIB)), visible: formatCount(visible), fallback: formatCount(fallback),
});
retry.hidden = failed.size === 0;
if (failed.size) retry.title = [...failed.values()].join('\n');
}
Expand Down
4 changes: 2 additions & 2 deletions src/IOViewer/Viewer/src/stream/meshTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export async function pickMeshSurface(ray, roots, nodes, getPage, sections, sign
return hit;
}

export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls, canvas, scene, fetchPage, setBackground, canFill, render, ru }) {
export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls, canvas, scene, fetchPage, setBackground, canFill, render }) {
const selection = new Selection();
const root = document.querySelector('#ioviewer-ui');
const elements = manifest.elements ?? [];
Expand Down Expand Up @@ -154,7 +154,7 @@ export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls
let failed = false;
if (!preview) {
note.hidden = false;
note.textContent = ru ? 'Поиск элемента…' : 'Finding element…';
note.textContent = t('finding');
}
try {
const rect = canvas.getBoundingClientRect();
Expand Down
Loading
Loading