diff --git a/.gitignore b/.gitignore index 4d448f2..89bc31f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ __pycache__/ *.pyc .venv/ +# Local viewer builds, reference exports and benchmark dependencies +/artifacts/ + # Editors and OS metadata .vs/ .idea/ diff --git a/site/.gitignore b/site/.gitignore new file mode 100644 index 0000000..4fe6703 --- /dev/null +++ b/site/.gitignore @@ -0,0 +1,4 @@ +bin/ +obj/ +wwwroot/paged-viewer.html +wwwroot/paged-storage.js diff --git a/site/AUDIT.md b/site/AUDIT.md new file mode 100644 index 0000000..8bbffb0 --- /dev/null +++ b/site/AUDIT.md @@ -0,0 +1,113 @@ +# Аудит IOExtend Web + +| Область | Что проверено | Результат | +| --- | --- | --- | +| Обновление сайта | Одна сессия Chromium со старым CSS в HTTP-кэше, переход на новую страницу, обычная перезагрузка | На старых адресах баннер вырос до 1280 CSS-пикселей. Версионированная сборка загрузила согласованные ресурсы и показала баннер шириной 224 пикселя. При недоступности CSS атрибуты HTML ограничивают размер баннера. | +| Интерфейс | Просмотр, экспорт и даунгрейд на ширинах 320, 390, 768, 1024, 1440, 1707, 2560 CSS-пикселей | В проверенных состояниях нет горизонтального переполнения, обрезанной навигации или ошибок загрузки. Конфигурация 1707 пикселей и DPR 2,25 повторяет размеры исходной вкладки Chrome. | +| Доступность | axe-core 4.10.3 с правилами WCAG 2.0–2.2 A/AA на трёх вкладках при 390 и 1707 CSS-пикселях | Автоматическая проверка прошла. Навигацию также проверили клавиатурой и эмулированным касанием в Chromium. | +| Просмотр | Реальные RVT и NWC, перетаскивание, замена, отмена и очистка временных данных | Все сценарии браузерной проверки прошли. | +| Экспорт | Загрузка NWC и RVT, скачивание GLB, JSON и IFC | Файлы скачались, проверены сигнатуры и структура. Браузерный тест не обнаружил внешних запросов. | +| Даунгрейд | Метаданные Revit 2020, 2025 и 2027, крупный образец RVT, повреждённый контейнер | На четырёх файлах прочитано по 64 КиБ исходника за 0,20–0,34 с в локальном Chromium. Список содержит только более старые версии, при ошибке прежний выбор сбрасывается. | +| Результат даунгрейда | Браузер 2025 → 2024, нативная проверка 2024 → 2023 с уменьшенным профилем | В браузере скачаны RVT и отчёт с совпадающей версией. Нативный результат побайтно совпал с результатом для полного файла-профиля. | + +Регрессии воспроизводятся через `release-smoke.cjs`, `smoke.cjs` и `operations-smoke.cjs`. Открытие новых копий в настольном Revit и проверка на физических мобильных устройствах в этот прогон не входили. Время чтения метаданных измерено при локальной раздаче браузерного приложения. + +## Сравнение с RvtIO main + +Сборка Chromium WebAssembly с RvtIO `c54aa06` падала при ожидании фоновой задачи в `ElementBuilder.PostProcess`. С исправлением #310 браузер экспортировал Compact JSON публичного образца Revit за 47,5 с против 88,6 с в предыдущей сборке. Файлы совпали побайтно. Это один сравнительный прогон на одной машине. + +Без API временного хранения из #308 крупный локальный образец достиг лимита линейной памяти WebAssembly сразу после распаковки. Базовый профиль сайта для больших RVT использует #308. [Нативные измерения в RvtIO #309](https://github.com/IOExtend/RvtIO/pull/309) · [Исправление WebAssembly в RvtIO #310](https://github.com/IOExtend/RvtIO/pull/310) + +## Восстановление после сбоя многопоточного воркера + +В Chromium многопоточная сборка .NET 10 воспроизвела ошибку доступа к памяти в SGen и исключение внутри параллельного декодирования. Также зафиксирован запуск, при котором WASM не дошёл до чтения файла. Многопоточный профиль остаётся экспериментальным. + +На публичном структурном образце Revit 2024 автоматический переход на однопоточную сборку дошёл до первого кадра на сервере с заголовками изоляции и на статическом сервере с Service Worker. В обоих прогонах получено 129 страниц и 84 494 треугольника. SHA-256 всех четырёх файлов сцены совпал с прямым однопоточным открытием. + +На `rmeadvancedsampleproject.rvt` после реального сбоя многопоточного чтения Chromium показал первый кадр через 245 секунд с начала открытия. Постраничная сцена содержит 1 505 страниц и 1 495 077 треугольников. Свойства элементов доступны. В диагностике ядра 1 385 предупреждений и 0 ошибок. + +`reader-recovery-smoke.cjs` проверяет переход при сбое WASM и зависании при запуске, открытие без изоляции, отмену, очистку временных данных и сохранение предыдущей сцены при ошибке резервного воркера. + +## Публичный образец Core Interior + +В Chromium запустили два открытия демо `2024_Core_Interior.rvt` (33,7 МБ) на сайте rvt-rs и один прогон того же файла в IOExtend. SHA-256 файла совпал с каталогом демо. [Каталог демо](https://github.com/DrunkOnJava/rvt-rs/blob/eb268fdd22ced8e43bf8b2236b582f182880a2d8/docs/viewer-demos.json) + +| Сборка | Интервал | Время | Линейная память WASM | +| --- | --- | --- | --- | +| rvt-rs, опубликованное демо | Клик до статуса Loaded, включая загрузку файла | 19,4 и 22,6 с | 308 МиБ | +| rvt-rs, опубликованное демо | Работа воркера после загрузки файла | 12,2 и 16,5 с | 308 МиБ | +| IOExtend, однопоточная AOT-сборка с #308 | Локальный файл до первого кадра | 225,6 с | 836,6 МиБ | + +В парном прогоне однопоточной сборки с #312 восстановление стен заняло 71,2 с против 72,6 с на базовой сборке, а первый кадр появился за 201,2 с против 203,7 с. Все четыре файла пакета сцены совпали по SHA-256. Базовая сборка использовала RvtIO `9f9a43f`, а #312 основан на `39c00e4`. [RvtIO #312](https://github.com/IOExtend/RvtIO/pull/312) + +В GLB из rvt-rs прочитано 971 узел с геометрией и 38 812 треугольников. IOExtend вывел 1 314 элементов, 1 607 экземпляров и 41 032 треугольника в 300 страницах. В IOExtend восстановление геометрии стен заняло 80 с, финализация модели — 36 с. + +rvt-rs разбирает модель в одном WASM-воркере, использует кэш распакованных разделов и отложенно читает сохранённые параметры выбранного элемента. Начальный разбор принимает содержимое всего файла, а просмотр получает готовый GLB. В IOExtend файл читается по диапазонам, а сцена и свойства передаются в страницы через OPFS. [Воркеры и параметры rvt-rs](https://github.com/DrunkOnJava/rvt-rs/blob/eb268fdd22ced8e43bf8b2236b582f182880a2d8/docs/viewer-api.md#saved-parameters) · [Кэш распакованных разделов](https://github.com/DrunkOnJava/rvt-rs/blob/eb268fdd22ced8e43bf8b2236b582f182880a2d8/src/reader.rs#L969-L1014) + +## Сквозная модель и первый кадр + +Вкладки используют один выбранный файл. Chromium подтвердил, что при выборе на странице экспорта 3D-читатель запускается после перехода на вкладку просмотра. `ioextend:first-frame` измеряет подготовку сцены и первый отрисованный кадр. Прошли 13 проверок быстрого читателя, включая отмену, ошибки чтения и первого кадра, резервный путь и первый визит на статический сайт без серверных заголовков изоляции. Проверка согласованности статических ресурсов прошла отдельно. + +В локальной серии на `racbasicsampleproject.rvt` из Revit 2027 контрольная экспериментальная AOT-сборка показала полный кадр через 13,825 с после выбора файла. Чистый RvtIO `main` по краям той же серии записал HTML за 9,466 и 9,438 с. Открытие этих HTML дошло до полного кадра через 10,204 и 10,076 с от запуска нативного процесса. Время около 8 с до первого кадра в браузере пока не достигнуто. + +Ядро построило 466 элементов, 730 экземпляров и 460 геометрий. В HTML-пакет записано 403 геометрии. Проверены три группы свойств в интерфейсе, один запрос WASM, совпадение свойств и метаданных с нативным экспортом после удаления времени создания. Бинарная секция геометрии браузерного контрольного воркера имеет отдельный SHA-256. `first-frame-smoke.cjs` принимает один из этих двух контрольных хэшей геометрии и измеряет обычное открытие исходного файла. Серия относится к этому образцу и сборке. + +В двух последующих сериях сравнили разбор параметров и сборку модели из RvtIO #327 с тем же браузерным декодером геометрии и сканером строк. Медианы первого кадра уменьшились с 23,330 до 20,411 с и с 19,843 до 18,155 с. Во всех восьми открытиях совпали метаданные, геометрия и свойства браузерного контроля. Нативный `main` `718374b` записал HTML за 31,746 и 19,012 с по краям первой серии. Доступная оперативная память перед браузерными запусками менялась от 1 до 10 720 МиБ. Эти замеры относятся к экспериментальным сборкам. [RvtIO #327](https://github.com/IOExtend/RvtIO/pull/327) + +Проверочный запуск `first-frame-smoke.cjs` в Chromium 159.0.8154.6 подтвердил кадр с контрольной геометрией и свойствами нативного HTML из чистого `095a2ca`. Время от выбора файла составило 28,197 с. + +В повторном замере на том же исходном RVT локальный релиз с ранним завершением декодеров показал полный кадр за 19,418 с. Предыдущая локальная сборка показала кадр за 24,013 с. Чистый RvtIO `main` `095a2ca` записал HTML за 13,394 и 12,234 с по краям этой серии. Во время двух браузерных открытий минимум доступной памяти составил 2 257 и 473 МиБ соответственно. Оба открытия дали контрольные хэши, видимый кадр, три группы свойств и один запрос WASM. + +В двух сериях на одном WASM проверили вычисление границ при преобразовании вершин и повторное использование геометрии внутри коробки отсечения. В порядке ABBA медиана первого кадра уменьшилась с 17,935 до 16,656 с, в обратном порядке с 17,973 до 16,947 с. Медиана сборки модели в первой серии уменьшилась с 3,081 до 2,631 с, во второй составила 2,735 и 2,757 с. Чистый `main` записал HTML за 10,165 и 10,711 с по краям первой серии. Во всех восьми открытиях совпали метаданные, геометрия и свойства. Подтверждены видимый кадр, три группы свойств и один запрос WASM. Доступная память во время открытий различалась. Ускорение самой сборки модели не воспроизвелось во второй серии, поэтому изменения геометрии остаются локальным экспериментом. + +На той же модели чистый RvtIO `main` после включения #329 записал HTML за 7,116 и 7,113 с. Эти два экспорта открыли и завершили одну серию замеров. С учётом запуска процесса и показа HTML в Chromium полный кадр занял 7,643 и 7,472 с. Между экспортами локальная браузерная сборка на предыдущем ядре открыла исходный RVT четыре раза. Контроль показал полный кадр за 9,993 и 9,704 с, эксперимент с прямой передачей геометрии из памяти WASM — за 9,706 и 9,670 с. Во время каждого браузерного замера оставалось не менее 28 984 МиБ свободной оперативной памяти. Совпали контрольные хэши геометрии браузера, метаданных и свойств. Во всех четырёх открытиях просмотрщик показал три группы свойств и загрузил WASM один раз. [Ревизия ядра d6e7d8b](https://github.com/IOExtend/RvtIO/commit/d6e7d8b8b447a18750c4e75ab03487e24b75c541) + +В обратном порядке запусков медианы составили 9,778 с для контроля и 9,832 с для прямой передачи. В каждом открытии с прямой передачей декодеры обработали 134 ответа общим объёмом 95 686 204 байта. Выигрыш по времени для этого изменения не воспроизвёлся. + +После переноса изменений из RvtIO #329 в локальную AOT-сборку медианы готовности сцены в двух порядках запусков составили 9,684 и 9,700 с. Контроль показал 9,708 и 9,661 с соответственно. Во всех восьми открытиях совпали хэши браузерной сцены. В тестах геометрии, размещения и чтения записей прошли 155 проверок на каждой из версий .NET 8 и .NET 10. На каждой версии один тест с отдельной RVT-фикстурой был пропущен. + +В следующих трёх открытиях проверка измерила интервал от выбора исходного файла до второго кадра анимации родительской страницы после показа готового iframe. Chromium 159.0.8154.6 показал 9,737, 9,677 и 9,691 с. Между подтверждением готовности просмотрщика и этим замером прошло 28–30 мс. Во всех трёх запусках проверены 466 элементов, 730 экземпляров, 403 геометрии в HTML-пакете, три группы свойств и один запрос WASM. Сразу после этой серии чистый `d6e7d8b` записал HTML за 7,101 с, а от запуска нативного процесса до готовности HTML в Chromium прошло 7,425 с. Разница между медианой показа в веб-просмотрщике и записью HTML составила 2,590 с. + +## Отдельная AOT-сборка для небольших RVT + +Профиль `IOExtendFastReader` собран из исходников сайта с чистым RvtIO `d6e7d8b`. Размер основного файла WASM составил 27 721 279 байт. Прошли 14 сценариев Chromium для выбора читателя, ошибок, отмены и статического хостинга. При открытии настоящего NWC основной загрузчик показал сцену с 4 035 экземплярами. + +На локальном экспериментальном читателе с параллельными декодерами полная обрезка кода уменьшила WASM с 49 692 953 до 30 367 562 байт. На исходном `racbasicsampleproject.rvt` медиана времени от выбора файла до показа сцены снизилась с 9,915 до 9,364 с за четыре открытия каждого варианта. В следующей серии изменения в обработке размещённой геометрии в экспериментальном ядре снизили медиану с 9,281 до 8,998 с. Хэши метаданных, геометрии и свойств совпали с браузерным контролем на четырёх образцах RVT 2027. Чистый RvtIO записал HTML за 7,059 и 6,952 с по краям серии проверки обрезки. Экспериментальные декодеры и изменения размещения собирались отдельно от исходников PR. + +В сборке из исходников PR с чистым RvtIO `d6e7d8b` быстрый читатель завершился с `Arg_PlatformNotSupported`. Сайт автоматически открыл образец через основной постраничный загрузчик. При повторной проверке от выбора файла до показа кадра прошло 60,448 с, загрузились два модуля WASM. Проверка быстрого пути теперь сообщает об этом сразу после показа кадра. + +При сборке того же RVT-профиля с локальными параллельными декодерами и изменениями размещения WASM занял 28 105 814 байт. В четырёх открытиях первый кадр появился через 8,870, 8,924, 8,912 и 8,864 с, медиана 8,891 с. В каждом открытии подтверждены 466 элементов, 730 экземпляров, 403 геометрии, три группы свойств и один запрос WASM. + +## Быстрый путь на опубликованных исходниках RvtIO + +При открытии исходного `racbasicsampleproject.rvt` в чистом `d6e7d8b` Chromium зафиксировал вызов `Task.SpinThenBlockingWait` из `ElementBuilder.PostProcess`. В отдельной копии ядра применили публичный коммит `74d2c997` из RvtIO #310. Восемь открытий в Chromium 159.0.8154.6 прошли через быстрый читатель с одной загрузкой WASM. Для настроек GC 512/16 МиБ медиана видимого кадра составила 25,005 с, для 2048/64 МиБ — 24,100 с (по четыре открытия, порядок ABBA/BAAB). Чистое ядро по окончании серии записало HTML за 7,111 с. [Исправление RvtIO](https://github.com/IOExtend/RvtIO/pull/310) + +Изменение GC применяется к отдельной AOT-сборке с пулом SGen для небольших RVT. На четырёх образцах RVT 2027 совпали контрольные суммы геометрии, свойств и метаданных до и после изменения. На исходном образце максимальный зарегистрированный размер линейной памяти WASM вырос с 1 488 до 1 589 МиБ, на инженерном образце — с 3 255 до 3 526 МиБ. Это показания воркера в точках отчёта о прогрессе. + +При повторной сборке из опубликованных ревизий RvtIO и IOViewer по командам в README кадры появились через 24,212, 23,935 и 24,073 с (медиана 24,073 с). Во всех трёх запусках проверены 466 элементов, 730 экземпляров, 403 геометрии, три группы свойств и единственная загрузка WASM. Перед этой серией `NativeHtmlExport` записал HTML из чистого RvtIO за 6,999 с. Метаданные после удаления времени создания, геометрия и свойства этого HTML совпали с нативным контролем. Разница между записью HTML и медианой веб-кадра составила 17,074 с. + +В отдельном сравнении чтение исходного файла по диапазонам дало медиану 24,012 с, а предварительное копирование всего RVT в управляемый `MemoryStream` — 23,996 с (по четыре запуска одного WASM). По сообщениям о прогрессе опубликованной сборки на этом образце от начала обработки параметров до начала восстановления геометрии прошло 6,636 с. Результат поддерживает сохранение чтения по диапазонам. + +Через локальный сервер `serve-preview.py` экспериментальный параллельный читатель показал полный кадр за 8,875, 8,887 и 8,906 с. Дополнительные проверки выбрали быстрый читатель ровно на 50 МиБ и основной постраничный читатель на 50 МиБ плюс один байт. Вместе с проверкой первого посещения статического сайта прошли 16 сценариев Chromium. + +## Параллельные декодеры из исходников сайта + +Профиль `IOExtendParallelReader` собран из отдельной копии `d6e7d8b`, исправления #310 +и патча `parallel/rvtio-browser.patch`. В Chromium 159.0.8154.6 от выбора исходного +`racbasicsampleproject.rvt` до первого видимого кадра прошло 10,890, 10,428 и 10,331 с. +Медиана составила 10,428 с при 24,073 с в предыдущей серии с одним воркером. +Каждый запуск загрузил нативный WASM один раз и показал 466 элементов, 730 экземпляров, +403 геометрии и три группы свойств. Проверка подтвердила браузерную контрольную сумму +геометрии и совпадение нормализованных метаданных и свойств с нативным HTML. + +## Оконный обход параметров с прогрессом + +Быстрый профиль использует оконный обход RvtIO и при включённом прогрессе. Сканер пропускает +позиции, где заголовок невозможен, и сохраняет проверки границ и порядка записей. +`first-frame-smoke.cjs` проверяет последовательность отчётов от начала до конца потока. + +На исходном `racbasicsampleproject.rvt` четыре открытия без изменения дали кадр за 10,642, 9,639, +9,911 и 9,836 с. Четыре открытия с оконным обходом дали кадр за 14,166, 10,489, 9,672 и 9,614 с. +Проверки сцены прошли во всех восьми запусках. Во время серии выполнялся отдельный постраничный +замер. Эти результаты подтверждают совместимость, а медианы 9,874 и 10,081 с не подтверждают +ускорение на этом образце. diff --git a/site/BrowserFileStream.cs b/site/BrowserFileStream.cs new file mode 100644 index 0000000..651853a --- /dev/null +++ b/site/BrowserFileStream.cs @@ -0,0 +1,60 @@ +using System.Runtime.InteropServices.JavaScript; +using System.Runtime.Versioning; + +[SupportedOSPlatform("browser")] +internal sealed partial class BrowserFileStream(long length) : Stream +{ + private long position; + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => position; + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + position = value; + } + } + + public override int Read(byte[] buffer, int offset, int count) + { + ValidateBufferArguments(buffer, offset, count); + return Read(buffer.AsSpan(offset, count)); + } + + public override int Read(Span buffer) + { + if (position >= length || buffer.IsEmpty) return 0; + int count = (int)Math.Min(buffer.Length, length - position); + ReadRange(position, buffer[..count]); + position += count; + return count; + } + + public override long Seek(long offset, SeekOrigin origin) + { + long start = origin switch + { + SeekOrigin.Begin => 0, + SeekOrigin.Current => position, + SeekOrigin.End => length, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + Position = checked(start + offset); + return position; + } + + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + [JSImport("readRange", "viewer")] + private static partial void ReadRange( + [JSMarshalAs] long offset, + [JSMarshalAs] Span destination); +} diff --git a/site/BrowserScratchStream.cs b/site/BrowserScratchStream.cs new file mode 100644 index 0000000..e0730b5 --- /dev/null +++ b/site/BrowserScratchStream.cs @@ -0,0 +1,84 @@ +using System.Runtime.InteropServices.JavaScript; +using System.Runtime.Versioning; + +[SupportedOSPlatform("browser")] +internal sealed partial class BrowserScratchStream(bool triangles = false) : Stream +{ + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => true; + public override long Length => length; + public override long Position + { + get => position; + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + position = value; + } + } + + private long length; + private long position; + + public override int Read(byte[] buffer, int offset, int count) + { + ValidateBufferArguments(buffer, offset, count); + return Read(buffer.AsSpan(offset, count)); + } + + public override unsafe int Read(Span buffer) + { + int count = (int)Math.Min(buffer.Length, Math.Max(0, length - position)); + if (count == 0) return 0; + fixed (byte* pointer = buffer) + { + int read = Transfer(position, (int)pointer, count, writing: false); + position += read; + return read; + } + } + + public override void Write(byte[] buffer, int offset, int count) + { + ValidateBufferArguments(buffer, offset, count); + Write(buffer.AsSpan(offset, count)); + } + + public override unsafe void Write(ReadOnlySpan buffer) + { + if (buffer.IsEmpty) return; + fixed (byte* pointer = buffer) + { + int written = Transfer(position, (int)pointer, buffer.Length, writing: true); + if (written != buffer.Length) throw new IOException("Не удалось записать временные данные модели."); + position += written; + length = Math.Max(length, position); + } + } + + public override long Seek(long offset, SeekOrigin origin) + { + long start = origin switch + { + SeekOrigin.Begin => 0, + SeekOrigin.Current => position, + SeekOrigin.End => length, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + return Position = checked(start + offset); + } + + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + + private int Transfer(long offset, int address, int count, bool writing) => triangles + ? TransferTriangles(offset, address, count, writing) + : TransferPartitions(offset, address, count, writing); + + [JSImport("scratchTransfer", "viewer")] + private static partial int TransferPartitions([JSMarshalAs] long offset, int address, int count, bool writing); + + [JSImport("triangleTransfer", "viewer")] + private static partial int TransferTriangles([JSMarshalAs] long offset, int address, int count, bool writing); +} diff --git a/site/DESIGN.md b/site/DESIGN.md new file mode 100644 index 0000000..85293d7 --- /dev/null +++ b/site/DESIGN.md @@ -0,0 +1,20 @@ +# Оформление IOExtend Web + +Интерфейс наследует графитовый фон, яркие верхние грани и ступенчатую глубину из баннеров IOExtend, IOViewer, RvtIO и NwcIO. Графика опирается на геометрию BIM, а текст и элементы управления используют системный шрифт. + +| Назначение | Цвет | +| --- | --- | +| Фон и рабочая поверхность | `#12161c` и `#191e27` | +| Основной и вторичный текст | `#edf3fa` и `#aebaca` | +| Просмотр и IOViewer | `#a5f3fc` | +| Экспорт | `#dbc0ff` | +| Понижение версии Revit | `#ffdc82` | +| Ошибки | `#ffc3ad` | + +Акцент инструмента отмечает выбранную вкладку и основное действие. Светлая и тёмная грани кнопок повторяют логику пиксельной графики. На узком экране иллюстрация располагается под действием, а настройки экспорта переходят в одну колонку. Встроенный IOViewer получает ту же палитру панелей через `wwwroot/viewer-theme.js`. + +## Графика + +- `wwwroot/brand/banner.png` — оригинальный баннер из каталога `profile` репозитория организации. [IOExtend на GitHub](https://github.com/IOExtend) +- `wwwroot/brand/avatar.png` — оригинальный аватар организации. [Аватар IOExtend](https://avatars.githubusercontent.com/u/354825687?s=200&v=4) +- `wwwroot/brand/voxel-building.png` — иллюстрация из прямоугольных объёмов в параллельной проекции. Исходник построения в `artwork/voxel-building.py`. diff --git a/site/IOExtend.Web.csproj b/site/IOExtend.Web.csproj new file mode 100644 index 0000000..c3296ef --- /dev/null +++ b/site/IOExtend.Web.csproj @@ -0,0 +1,89 @@ + + + net10.0 + Exe + enable + enable + true + false + false + true + true + $(DefineConstants);PARALLEL_RVT_READER + $(DefineConstants);FAST_RVT_READER + <_BuildPagedViewer Condition="'$(IOViewerSource)' != '' and '$(IOExtendFastReader)' != 'true'">true + ../RvtIO + $(DefineConstants);RVT_PARTITION_SCRATCH + $(DefineConstants);LOCAL_MESH_PAGES + $(DefaultItemExcludes);operations/**;wwwroot/paged-viewer.html;wwwroot/paged-storage.js + $(DefaultItemExcludes);wwwroot/thread-isolation.js + + + net11.0 + true + true + true + partial + full + 33554432 + 4294901760 + $(EmccExtraLDFlags) -sMALLOC=dlmalloc + + + true + + + $(DefineConstants);BROWSER_THREADS + + + $(DefineConstants);POOLED_BROWSER_GC + $(EmccExtraLDFlags) -Wl,--wrap=sgen_alloc_os_memory_aligned -Wl,--wrap=sgen_free_os_memory + + + + + + + + + + + + + + + + + + + + + + + + + + <_ReaderProfile>$(IntermediateOutputPath)reader-profile.js + <_UsePooledGc>false + <_DecoderExport Condition="'$(IOExtendParallelReader)' == 'true'">export * as decoders from './reader-decoders.js' + <_UsePooledGc Condition="'$(IOExtendPooledGc)' == 'true'">true + <_RvtGcParams>soft-heap-limit=512m + <_RvtGcParams Condition="'$(_UsePooledGc)' == 'true'">soft-heap-limit=512m,nursery-size=16m + <_RvtGcParams Condition="'$(_UsePooledGc)' == 'true' and '$(IOExtendFastReader)' == 'true'">soft-heap-limit=2048m,nursery-size=64m + <_UseThreads>false + <_UseThreads Condition="'$(WasmEnableThreads)' == 'true'">true + + + + + + + + diff --git a/site/Program.cs b/site/Program.cs new file mode 100644 index 0000000..f8f4a6a --- /dev/null +++ b/site/Program.cs @@ -0,0 +1,288 @@ +using System.Runtime.InteropServices.JavaScript; +using System.Runtime.Versioning; +using IOScene; +using IOViewer.Exporters; +#if LOCAL_MESH_PAGES +using IOViewer.Model; +#endif +#if !FAST_RVT_READER +using NwcIO; +using NwcIO.Model; +using NwcIO.Scene; +#endif +using RvtIO; +using RvtIO.Scene; + +[SupportedOSPlatform("browser")] +internal static partial class Program +{ + private static void Main() { } + +#if BROWSER_THREADS + [JSExport] + internal static Task OpenModel(string name, [JSMarshalAs] long length, bool useScratch) => + OpenForWorker(name, length, useScratch, usePages: false); + +#if LOCAL_MESH_PAGES + [JSExport] + internal static Task OpenPagedModel(string name, [JSMarshalAs] long length) => + OpenForWorker(name, length, useScratch: true, usePages: true); +#endif + + private static Task OpenForWorker(string name, long length, bool useScratch, bool usePages) + { + try + { + var html = OpenModelCore(name, length, useScratch, usePages); + if (html.Length > 0) ReportHtml(html); + } + catch (Exception error) + { + // Exceptions thrown before returning a task do not reach the threaded JS caller. + ReportFailure(error is OutOfMemoryException ? nameof(OutOfMemoryException) : error.Message, + error is AggregateException); + } + return Task.CompletedTask; + } +#else + [JSExport] + internal static byte[] OpenModel(string name, [JSMarshalAs] long length, bool useScratch) => + OpenModelCore(name, length, useScratch, usePages: false); + +#if LOCAL_MESH_PAGES + [JSExport] + internal static byte[] OpenPagedModel(string name, [JSMarshalAs] long length) => + OpenModelCore(name, length, useScratch: true, usePages: true); +#endif +#endif + + private static byte[] OpenModelCore(string name, long length, bool useScratch, bool usePages) + { + if (length <= 0) + throw new InvalidDataException("emptyFile"); + + string extension = Path.GetExtension(name).ToLowerInvariant(); + using var stream = new BrowserFileStream(length); + using var triangleScratch = extension == ".rvt" && useScratch + ? new BufferedStream(new BrowserScratchStream(triangles: true), 64 * 1024) : null; + var (scene, diagnostics) = extension switch + { + ".rvt" => ReadRvt(stream, name, triangleScratch), +#if !FAST_RVT_READER + ".nwc" => ReadNwc(stream, name), +#endif + _ => throw new InvalidDataException("chooseRvtNwc"), + }; + + if (scene.Instances.Count == 0) + throw new InvalidDataException("view.noGeometry"); + + ReportDiagnostics( + diagnostics.Count(d => d.Severity == SceneSeverity.Warning), + diagnostics.Count(d => d.Severity == SceneSeverity.Error)); + ReportScene(scene.Elements.Count, scene.Instances.Count, scene.Geometries.Count); + +#if LOCAL_MESH_PAGES + if (usePages && scene.Geometries.All(geometry => geometry.Topology == SceneTopology.Triangles)) + { + using var cluster = new BufferedStream(new BrowserScratchStream(), 64 * 1024); + ReportCluster(ClusterSourceWriter.Export(new ViewerDocument(scene), cluster)); + return []; + } +#endif + + using var html = new MemoryStream(); + HtmlViewerExporter.Export(scene, html); + return html.ToArray(); + } + +#if BROWSER_THREADS + [JSImport("reportHtml", "viewer")] + private static partial void ReportHtml(byte[] html); + + [JSImport("reportFailure", "viewer")] + private static partial void ReportFailure(string detail, bool parallelFailure); +#endif + + [JSImport("reportScene", "viewer")] + private static partial void ReportScene(int elements, int instances, int geometries); + + [JSImport("resetPartitionScratch", "viewer")] + private static partial void ResetPartitionScratch(); + +#if LOCAL_MESH_PAGES + [JSImport("reportCluster", "viewer")] + private static partial void ReportCluster([JSMarshalAs] long triangles); +#endif + + private static (SceneDocument, IReadOnlyList) ReadRvt(Stream stream, string name, Stream? triangleScratch) + { +#if RVT_PARTITION_SCRATCH + bool releasePartitions = triangleScratch != null; +#endif + var options = new RvtSceneOptions + { + ModelKey = name, + ReadProgress = new InlineProgress(ReportRvtProgress), +#if RVT_PARTITION_SCRATCH + MeshProgress = new InlineProgress<(int Completed, int Total)>(update => + { + // The reader has disposed its partition stream before mesh extraction starts. + if (releasePartitions) + { + ResetPartitionScratch(); + releasePartitions = false; + } + ReportRvtMeshProgress(update); + }), + CreatePartitionScratch = triangleScratch == null ? null : () => new BufferedStream(new BrowserScratchStream(), 64 * 1024), +#endif + }; +#if RVT_PARTITION_SCRATCH + var result = triangleScratch == null + ? RvtSceneReader.ReadStream(stream, options) + : RvtSceneReader.ReadStream(stream, options, triangleScratch); +#else + var result = RvtSceneReader.ReadStream(stream, options); +#endif + return (result.Document, result.Diagnostics); + } + + private static void ReportRvtMeshProgress((int Completed, int Total) update) + { + if (update.Total == 0) return; + int percent = 92 + (int)(3L * update.Completed / update.Total); + ReportProgress(percent, "view.rvtScene", update.Completed, update.Total); + } + +#if !FAST_RVT_READER + private static (SceneDocument, IReadOnlyList) ReadNwc(Stream stream, string name) + { + ReportProgress(8, "view.nwcContainer"); + var document = NwcDocument.Open(stream, null, Path.GetFileNameWithoutExtension(name), + new InlineProgress(ReportNwcProgress), default); + var result = NwcSceneReader.Read(document, new NwcSceneOptions { ModelKey = name }); + return (result.Document, result.Diagnostics); + } +#endif + + private static void ReportRvtProgress(RvtReadProgress update) + { +#if POOLED_BROWSER_GC + if (update.Completed == 0 && update.Phase is "build-model" or "finalize-model") + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); + UpdateGcProfile(update.Phase, update.Total); + } +#endif + // Stage ranges approximate overall work. Only the counters within a stage are measured. + switch (update.Phase) + { + case "metadata": ReportProgress(8, "view.metadata"); break; + case "partitions": + ReportProgress(Within(10, 19, update), "view.partitions", update.Completed, update.Total); + break; + case "class-schema": ReportProgress(20, "phase.class-schema"); break; + case "element-records": + ReportProgress(Within(25, 30, update), update.Total == 0 ? "phase.element-records" : "view.records", + update.Completed, update.Total); + break; + case "element-blocks": +#if RVT_PARTITION_SCRATCH + if (update.GeometryBlocks is { } geometry) + { + double pass = update.Completed + geometry.Completed / (double)geometry.Total; + int percent = 31 + (int)(15 * pass / update.Total); + ReportProgress(percent, "view.geometry", geometry.Completed, geometry.Total); + } + else +#endif + ReportProgress(Within(31, 46, update), "view.blocks", update.Completed, update.Total); + break; + case "parameter-stream": + ReportProgress(Within(47, 63, update), update.Total > 0 ? "view.paramCount" : "phase.parameter-stream", + ToMiB(update.Completed), ToMiB(update.Total)); + break; + case "recover-geometry": +#if RVT_PARTITION_SCRATCH + if (update.GeometryBlocks is { } recovered) + { + var (percent, stage) = update.Completed switch + { + 2 => (66, "view.decodeFound"), + 3 => (67, "view.wallGeometry"), + _ => (64, "view.decodeGeometry"), + }; + if (recovered.Completed == recovered.Total) percent++; + ReportProgress(percent, stage, recovered.Completed, recovered.Total); + } + else +#endif + { + switch (update.Completed) + { + case 0: ReportProgress(64, "phase.recover-geometry"); break; + case 1: ReportProgress(65, "view.seekGeometry"); break; + case 2: ReportProgress(66, "view.decodeFound"); break; + case 3: ReportProgress(67, "view.wallGeometry"); break; + } + } + break; + case "element-properties": + ReportProgress(Within(68, 74, update), update.Total == 0 ? "phase.element-properties" : "view.properties", + update.Completed, update.Total); + break; + case "build-model": + ReportProgress(Within(75, 87, update), update.Total > 0 ? "view.buildModel" : "phase.build-model", + update.Completed, update.Total); + break; + case "finalize-model": + switch (update.Completed) + { + case 0: ReportProgress(88, "view.linkTypes"); break; + case 1: ReportProgress(88, "view.modelValues"); break; + case 2: ReportProgress(89, "view.derivedProperties"); break; + case 3: ReportProgress(89, "view.phasesLevels"); break; + case 4: ReportProgress(90, "view.systemNames"); break; + case 5: ReportProgress(90, "view.resolveRefs"); break; + case 6: ReportProgress(91, "view.unitsCoordinates"); break; + } + break; + case "complete": ReportProgress(92, "view.prepareScene"); break; + } + } + +#if POOLED_BROWSER_GC + [JSImport("updateGcProfile", "viewer")] + private static partial void UpdateGcProfile(string phase, [JSMarshalAs] long total); +#endif + + private static double ToMiB(long bytes) => bytes / (1024d * 1024d); + + private static int Within(int start, int end, RvtReadProgress update) => update.Total == 0 + ? start + : start + (int)((end - start) * (update.Completed / (double)update.Total)); + +#if !FAST_RVT_READER + private static void ReportNwcProgress(NwcProgress update) + { + switch (update.Phase) + { + case "read-container": ReportProgress(23, "view.nwcGeometry"); break; + case "read-geometry": ReportProgress(72, "view.nwcProperties"); break; + case "open": ReportProgress(92, "view.nwcScene"); break; + } + } +#endif + + private sealed class InlineProgress(Action report) : IProgress + { + public void Report(T value) => report(value); + } + + [JSImport("reportProgress", "viewer")] + private static partial void ReportProgress(int percent, string key, double completed = 0, double total = 0); + + [JSImport("reportDiagnostics", "viewer")] + private static partial void ReportDiagnostics(int warnings, int errors); +} diff --git a/site/README.md b/site/README.md new file mode 100644 index 0000000..0f3ea64 --- /dev/null +++ b/site/README.md @@ -0,0 +1,184 @@ +# IOExtend Web + +Локальная сборка инструментов IOExtend для просмотра, экспорта и понижения версии Revit. Выберите RVT через диалог или перетащите его на любую вкладку. Вкладки используют один исходный файл. 3D-сцена RVT или NWC подготавливается при открытии вкладки «Просмотр». Ракурс сохраняется при возвращении к сцене. Форматы, доступные для выбора и обработки, зависят от вкладки. + +Язык сайта и встроенного просмотрщика выбирается в шапке. В режиме «Авто» используется первый поддерживаемый язык из списка браузера. Если подходящего языка нет, используется английский. Ручной выбор сохраняется в браузере. При смене языка 3D-просмотр заново открывается из подготовленных данных с начальным ракурсом. Автономный HTML IOViewer имеет собственный переключатель и работает без сети. + +Во время открытия видны текущий этап, примерный процент и время ожидания. Для RVT дополнительно видны счётчики +распакованных потоков, проходов разбора, блоков при восстановлении геометрии, блоков записей и имён, +прочитанных байтов и элементов, для которых построены сетки. При подготовке просмотра видны счётчики записанных +треугольников, обзорных страниц на каждом уровне и обработанных элементов. Веса этапов используются для оценки общего хода +работы. Обработку можно отменить кнопкой «Отменить». Замер `ioextend:first-frame` в браузере идёт от начала открытия модели во «Просмотре» до первого отрисованного кадра. + +## Запуск + +Соберите проект с .NET 10 SDK и запустите статический сервер в папке с результатом. +Локальная сборка использует ветку `codex/rvt-segment-spooling` с чтением сегментов через временное хранилище. Чтобы подключить постраничный просмотр, подготовьте зависимости Node.js в исходниках IOViewer и передайте обе папки при сборке. [RvtIO PR #308](https://github.com/IOExtend/RvtIO/pull/308) · [IOViewer PR #81](https://github.com/IOExtend/IOViewer/pull/81) +[Прогресс чтения](https://github.com/IOExtend/RvtIO/pull/304), [ограничение временных результатов декодирования](https://github.com/IOExtend/RvtIO/pull/305), [чтение RVT из потока](https://github.com/IOExtend/RvtIO/pull/306), [чтение страниц RVT без копии потока](https://github.com/IOExtend/RvtIO/pull/307). + +```powershell +dotnet publish -c Release -o publish-web -p:RvtIOProgressSource=/path/to/RvtIO -p:IOViewerSource=/path/to/IOViewer +python -m http.server 8976 --bind 127.0.0.1 --directory publish-web/wwwroot +``` + +Откройте [локальную страницу](http://127.0.0.1:8976/). Для GitHub Pages каталог `publish-web/wwwroot` можно использовать как артефакт публикации. В нём должны остаться `index.html` и папка `_framework`. [Документация GitHub Pages](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site) + +Для AOT-сборки разработчика используйте .NET 11 SDK с рабочей нагрузкой `wasm-tools`. Откройте статический сервер в каталоге `publish-web-aot/wwwroot`. + +```powershell +dotnet publish -c Release -o publish-web-aot -p:IOExtendAot=true -p:RvtIOProgressSource=/path/to/RvtIO -p:IOViewerSource=/path/to/IOViewer +``` + +Профиль `-p:IOExtendPooledGc=true` включает экспериментальное групповое выделение блоков Mono SGen в +однопоточной сборке .NET 11 WebAssembly. Пул включается при сборке записей RVT и остаётся активным при +финализации. Для этого профиля добавьте флаг к команде AOT-сборки. Посетитель открывает её как обычную +статическую страницу в Chromium. + +При сравнении с исходниками без API временного хранения из #308 передайте `-p:RvtIOPartitionScratch=false`. В этом режиме RvtIO держит распакованные сегменты в памяти, а IOViewer может записать готовую сцену в страницы. Для крупных RVT используйте сборку с временным хранилищем. + +Для небольших RVT профиль `IOExtendFastReader` собирает отдельный однопоточный AOT-воркер с полной обрезкой +неиспользуемого кода. Воркер читает RVT и возвращает автономный HTML. Основная сборка обслуживает NWC, +постраничный просмотр и резервное открытие RVT. Для сравнения с нативным экспортом передайте ту же ревизию +IOViewer. Используйте отдельный каталог промежуточных файлов для каждого профиля, чтобы компоновщик применил +параметры обрезки. В чистом RvtIO `d6e7d8b` расчёт количеств дверей и окон ожидает фоновую задачу. +Однопоточный WebAssembly в этом месте выдаёт `Arg_PlatformNotSupported`, и сайт открывает файл повторно. +Для быстрого читателя подготовьте отдельный каталог с этой ревизией и исправлением браузерного пути. +Команды подготовки исходников рассчитаны на новый каталог. [RvtIO #310](https://github.com/IOExtend/RvtIO/pull/310) + +```powershell +$readerCore = "../artifacts/fast-reader-src" +$main = "d6e7d8b8b447a18750c4e75ab03487e24b75c541" +$browserFix = "74d2c997bf80e7a923e6036f98a1fbbf70141e4a" +git init $readerCore +git -C $readerCore remote add origin https://github.com/IOExtend/RvtIO.git +git -C $readerCore sparse-checkout set src/RvtIO src/RvtIO.Scene +git -C $readerCore fetch --no-tags --depth=2 --filter=blob:none origin $main $browserFix +git -C $readerCore checkout --detach $main +git -C $readerCore cherry-pick --no-commit $browserFix +``` + +В проверенной паре сборок веб-читатель и нативный экспортёр используют IOViewer +`b12b27a5708b0b08c2a241311ac2254cac31a984`. Передайте каталог этой ревизии в `IOViewerSource`. [IOViewer #82](https://github.com/IOExtend/IOViewer/pull/82) + +Профиль `IOExtendParallelReader` распределяет обработку параметров и геометрии между четырьмя +браузерными воркерами. Ещё один воркер читает имена. Координатор загружает нативный WASM один раз +через загрузчик .NET и передаёт полученные байты воркерам. Для этого профиля примените патч +из каталога `site` к подготовленной выше копии ядра. + +Во время чтения параметров этот профиль использует окна по 64 МиБ с запасом для записи на +границе окна. Счётчик показывает позицию в исходном потоке параметров. + +```powershell +$decoderPatch = (Resolve-Path parallel/rvtio-browser.patch).Path +git -C $readerCore apply --check $decoderPatch +git -C $readerCore apply $decoderPatch +dotnet publish IOExtend.Web.csproj -c Release --artifacts-path ../artifacts/fast-reader -o ../artifacts/fast-reader/publish -p:IOExtendParallelReader=true -p:IOExtendPooledGc=true -p:RvtIOPartitionScratch=false "-p:RvtIOProgressSource=$((Resolve-Path $readerCore).Path)" -p:IOViewerSource=/path/to/IOViewer +node prepare-web-release.mjs publish-web-aot/wwwroot --fast-reader ../artifacts/fast-reader/publish/wwwroot +``` + +Для контрольной сборки с одним воркером используйте ядро с исправлением #310 до применения +патча, отдельный каталог артефактов и `-p:IOExtendFastReader=true` вместо `-p:IOExtendParallelReader=true`. + +Рабочая страница выбирает быстрый воркер для RVT до 50 МиБ при изоляции источника, от 8 ГиБ памяти по данным браузера +и от пяти логических процессоров. Воркер формирует автономную сцену из того же исходного RVT. Страница повторяет +открытие через основной постраничный путь при ошибке, после 25 секунд без продвижения чтения или после 25 секунд +ожидания первого кадра готовой сцены. +Выбор файла и отмена остаются общими для обоих режимов. +На статическом хостинге без серверных заголовков изоляции релиз с быстрым читателем использует локальный +Service Worker. При первом посещении он перезагружает страницу, пока посетитель ещё не начал выбирать файл. +Аргумент со статическим URL без заголовков в `fast-reader-smoke.cjs` проверяет этот запуск в отдельном контексте Chromium. + +Экспериментальный профиль `-p:IOExtendThreaded=true` собирает AOT-версию на .NET 10 SDK с `wasm-tools` и исходниками RvtIO из #311 поверх #308. Передавайте его вместе с `-p:IOExtendAot=true` и `-p:IOExtendFallbackSite=/path/to/publish-web-aot/wwwroot`. Для обеих сборок используйте одну ревизию IOViewer. Профиль декодирует геометрию в четырёх потоках или меньше и применяет результаты в порядке записей RVT. [RvtIO #311](https://github.com/IOExtend/RvtIO/pull/311) + +На хостинге с заголовками `Cross-Origin-Opener-Policy: same-origin` и `Cross-Origin-Embedder-Policy: require-corp` доступна общая память WebAssembly. Файлы `.mjs` должны отдаваться с типом JavaScript. Для GitHub Pages разместите эту сборку в отдельном каталоге, например `parallel/`. При первом визите Service Worker добавит заголовки в пределах этого каталога и перезагрузит страницу, если посетитель ещё не начал выбирать файл. Без изоляции сайт использует однопоточную сборку. [Поддержка потоков в .NET WebAssembly](https://github.com/dotnet/runtime/blob/main/src/mono/wasm/features.md#multi-threading) + +На запуск каждого обработчика просмотра отводится до минуты, пока среда WebAssembly готовится к чтению файла. Если многопоточный воркер зависнет при запуске или завершится со сбоем WebAssembly, сайт один раз повторит открытие того же локального файла в однопоточном режиме. Прогресс показывает повторное открытие, а следующие модели в этой вкладке сразу идут в однопоточный обработчик. Если он завершится ошибкой или зависнет на запуске, сайт покажет сообщение и снова позволит выбрать файл. Ранее открытая модель останется доступной. После запуска время чтения модели не ограничено. Данные модели обрабатываются локально. + +Переменная `IOEXTEND_REQUIRE_THREADS=1` включает проверку изоляции и общей памяти WebAssembly в `smoke.cjs`. Команда `node reader-recovery-smoke.cjs [unisolated-url]` проверяет восстановление после сбоя WebAssembly, зависание при запуске обоих воркеров, продолжение чтения после истечения минуты, отказ резервного воркера, отмену и прямую загрузку без изоляции. + +## Экспорт и даунгрейд + +После публикации сайта соберите браузерные обработчики в тот же `wwwroot` с .NET 10 SDK. Для экспорта используйте ту же ревизию RvtIO, что и для просмотра, и NwcIO `d2c8469` (0.17.0). Для даунгрейда использовалась ветка `feat/revit-downgrade` RvtIO, коммит `7936c6e`. + +```powershell +./operations/Publish.ps1 -Site ./publish-web/wwwroot -Build ./obj/site-tools -RvtIOProgressSource /path/to/RvtIO-export -NwcIOSource /path/to/NwcIO -DowngradeSource /path/to/RvtIO-downgrade +``` + +С .NET 11 SDK и рабочей нагрузкой `wasm-tools` к команде можно добавить `-ExportLargeHeap`. Этот профиль собирает обработчик экспорта с верхней границей линейной памяти почти 4 ГиБ. +Для сравнительной сборки экспорта с исходниками из #310 передайте `-RvtIOPartitionScratch:$false`. Доступные счётчики этапов зависят от API выбранного ядра. + +Добавьте `-IOViewerSource /path/to/IOViewer`, чтобы использовать актуальную сборку автономного просмотрщика в HTML-экспорте RVT, RFA, NWC и NWD. Перед сборкой выполните `npm ci` и `npm run build` в каталоге `src/IOViewer/Viewer`. Прежний HTML Navisworks доступен отдельно среди дополнительных форматов. + +Доступные форматы зависят от исходного файла. За один запуск можно получить несколько файлов. Дополнительные результаты Navisworks, например TimeLiner, требуют соответствующих данных в модели. Повторное сохранение Navisworks в NWC использует собственный формат записи NwcIO и отклоняет модели с линейными сетками. Для даунгрейда выберите исходный RVT или RFA. Сайт определит версию из потока `BasicFileInfo` и предложит более ранние версии из диапазона 2020–2026. RvtIO проверяет схему модели после запуска и создаёт отдельную копию с отчётом. Даунгрейд экспериментальный. + +Обработчики читают исходные файлы по диапазонам. Для RVT и RFA используется `MONO_GC_PARAMS=soft-heap-limit=512m`, чтобы Mono раньше освобождал временные данные. Выходной файл собирается в памяти браузера. Предельный размер зависит от модели и доступной памяти. + +Во время экспорта и даунгрейда видны этап, время обработки и объём чтения и записи. Счётчики ввода и вывода учитывают повторные обращения к файлу. Процент этапа появляется, если ядро сообщает выполненный и общий объём работы. При экспорте в несколько форматов отдельно видно, сколько обработок завершилось. + +Браузерная проверка запускается через `node operations-smoke.cjs <локальный URL> <пример.nwc> <пример.rvt> <целевая-версия> [<пример-для-даунгрейда.rvt>]`. Она проверяет этапы и отмену, скачивание файлов, список версий, отчёт и отказ при повреждённых метаданных. +Проверка `node localization-smoke.cjs <локальный URL> <пример.nwc> [<пример.rvt>]` проверяет словари, режим «Авто», сохранение выбора, встроенный просмотр и скачанный HTML без сети. + +Файлы в `wwwroot/profiles` содержат только таблицу классов, архивный заголовок и поля версии и сборки. Генератор в `operations/profile-tool` извлекает их из файлов целевых версий и сверяет заголовок со схемой. Полная модель и путь последнего сохранения в профиль не попадают. + +При публикации интерфейс и загрузчики WebAssembly получают адреса с отпечатками содержимого. `prepare-web-release.mjs` записывает ресурсы до обновления `index.html`. Проверка `node release-smoke.cjs ` воспроизводит смешивание разметки и старых стилей на прогретом кэше и проверяет обычную перезагрузку. + +## Как это работает + +Весь разбор RVT и NWC и построение сцены должны выполняться в браузере пользователя. Посетителю должно +быть достаточно открыть страницу и выбрать файл. GitHub Pages используется для раздачи файлов приложения. +Модели RVT размером порядка 300 МБ и выше входят в целевой сценарий и требуют проверки на реальных проектах. + +Браузер запускает RvtIO.Scene или NwcIO.Scene в отдельном Web Worker через .NET WebAssembly. Адаптер формирует IOScene, а IOViewer рендерит результат через WebGL 2. Файл модели остаётся в браузере. Для RVT с поддержкой OPFS ядро читает и пишет временные данные порциями. Однопоточная сборка с `IOExtendPooledGc=true` использует общий буфер до 512 МиБ вне линейной памяти WebAssembly. Поток, исчерпавший общий лимит, сохраняется в OPFS и продолжает работать с диска. Если браузер не поддерживает расширяемые буферы, оба потока сразу работают через OPFS. После сборки записей Revit временный поток сегментов освобождается перед построением сеток. + +В сборке с исходниками IOViewer отдельный рабочий процесс преобразует треугольную сцену RVT в страницы геометрии и свойств. Перед передачей файла этому процессу читатель записывает его в OPFS. IOViewer запрашивает нужные диапазоны из локальных файлов пакета. Промежуточные файлы удаляются после построения страниц. Страницы остаются доступны до замены или закрытия модели. При отмене или ошибке удаляется папка текущего открытия. При следующем открытии сайт очищает оставшиеся папки, которые не используются другими вкладками. + +До первого кадра новый фрейм просмотра остаётся прозрачным и недоступным для взаимодействия. Он находится в области просмотра, чтобы Chromium мог вызвать `requestAnimationFrame` внутри изолированного фрейма. + +Для RVT сборщик мусора Mono настроен запускаться раньше через `MONO_GC_PARAMS=soft-heap-limit=512m`. Это порог для сборки мусора. Фактическое потребление памяти может быть выше. + +Прототип обрабатывает одну модель за раз. Web Worker даёт .NET доступ к выбранному файлу диапазонами +по 512 КиБ для RVT и по 64 КиБ для NWC с кэшем до 16 МиБ. Пиковая память зависит от распакованных потоков, сложности геометрии +и временных данных ядра. При ошибках декодирования интерфейс сообщает, что часть элементов может отсутствовать. + +У штатной сборки верхняя граница линейной памяти WebAssembly составляет 2 ГиБ. Для испытаний больших RVT +используется также AOT-сборка с границей почти 4 ГиБ. Измерения ниже относятся к указанным версиям прототипа. + +## Проверка больших файлов + +На локальных образцах браузер отрисовал постраничную геометрию, открыл свойства элементов и освободил временные данные после отмены. Синтетический RVT-контейнер на 10,01 ГиБ для проверки больших смещений сохранил исходную геометрию контрольной модели. Сложность реальной модели определяет расход памяти независимо от размера входного контейнера. + +## Браузерная проверка + +С установленным в среде Node.js пакетом Playwright запустите тест и передайте пути к локальным образцам. Тест проверяет перетаскивание, диалог выбора, замену и отмену, ошибки ввода и рендеринг обеих моделей. + +```powershell +node smoke.cjs http://127.0.0.1:8976/ path/to/sample.rvt path/to/sample.nwc +``` + +Установите `IOEXTEND_REQUIRE_PAGED=1`, чтобы тест потребовал постраничный рендеринг для треугольной модели RVT. +Для сборки с `-p:RvtIOPartitionScratch=false` задайте `IOEXTEND_RVT_PARTITION_SCRATCH=0`, чтобы проверка учитывала набор событий прогресса этой версии ядра. + +Для замера полного кадра подготовьте релиз с быстрым читателем и откройте его через локальный HTTP-сервер с +`Cross-Origin-Opener-Policy: same-origin` и `Cross-Origin-Embedder-Policy: require-corp`. Из каталога `site` +такой сервер запускается командой `python serve-preview.py publish-web-aot/wwwroot`. Для нативного контроля +передайте чистый RvtIO `main` и ту же ревизию IOViewer, что использует сайт. `NativeHtmlExport` читает исходный +RVT через `RvtSceneReader.Read` и записывает автономную сцену через `HtmlViewerExporter.Export` в новый файл. + +Для постраничного читателя запустите `node paged-first-frame-smoke.cjs <путь-к-rvt> [секунды]`. +Сценарий создаёт чистый профиль Chromium с обычной квотой OPFS, замеряет время от выбора файла до +показа сцены и проверяет отрисовку и чтение свойств элемента. Вывод JSON содержит этапы загрузки +и состояние на отметке 120 секунд, если кадр ещё не появился. Тайм-аут по умолчанию составляет 30 минут. +В JSON-результате `readMs` включает чтение и построение сцены, а `exportMs` также включает запись и закрытие +HTML. Запускайте нативный и браузерный замеры последовательно. + +```powershell +dotnet build ../tools/NativeHtmlExport -c Release --artifacts-path ../artifacts/native -p:RvtIOSource=/path/to/clean/RvtIO -p:IOViewerSource=/path/to/IOViewer +dotnet ../artifacts/native/bin/NativeHtmlExport/release/NativeHtmlExport.dll path/to/racbasicsampleproject.rvt path/to/native-export.html +node first-frame-smoke.cjs http://127.0.0.1:8976/ path/to/racbasicsampleproject.rvt path/to/native-export.html +``` + +Проверка запускает новый Chromium и передаёт RVT в обычное поле выбора файла. `viewerReadyMs` показывает время +до подтверждения рендера и показа iframe на странице. `firstFrameMs` измеряется от события выбора файла +до второго `requestAnimationFrame` после появления iframe. Между этими вызовами Chromium может вывести сцену +на экран. Проверка сверяет состав сцены, свойства, контрольную геометрию и единственную загрузку WASM +быстрого читателя. Время записи нативного HTML замеряется отдельно. Результаты описаны в [аудите](AUDIT.md). diff --git a/site/SgenBlockPool.c b/site/SgenBlockPool.c new file mode 100644 index 0000000..91a275d --- /dev/null +++ b/site/SgenBlockPool.c @@ -0,0 +1,117 @@ +#include +#include +#include +#include +#include + +#if !defined(__wasm32__) || defined(__EMSCRIPTEN_PTHREADS__) +#error The SGen block pool requires single-threaded wasm32. +#endif + +// Mono 11 requests aligned major-heap blocks individually in single-threaded wasm32. +// Group those exact requests to reduce alignment gaps in the linear heap. +enum { BlockSize = 16 * 1024, BlocksPerSlab = 32, SlabSize = BlockSize * BlocksPerSlab }; +enum { PageMapSize = UINT32_MAX / BlockSize + 1 }; + +struct Slab { + unsigned char *base; + uint32_t available; + struct Slab *previous; + struct Slab *next; +}; + +static struct Slab *pages[PageMapSize]; +static struct Slab *available; +static unsigned allocations; +static int pool_enabled; + +EMSCRIPTEN_KEEPALIVE void ioextend_set_sgen_pool(int enabled) +{ + pool_enabled = enabled; +} + +void *__real_sgen_alloc_os_memory_aligned(size_t, uintptr_t, int, const char *, int); +void __real_sgen_free_os_memory(void *, size_t, int, int); + +static void add_available(struct Slab *slab) +{ + slab->previous = NULL; + slab->next = available; + if (available) + available->previous = slab; + available = slab; +} + +static void remove_available(struct Slab *slab) +{ + if (slab->previous) + slab->previous->next = slab->next; + else + available = slab->next; + if (slab->next) + slab->next->previous = slab->previous; +} + +void *__wrap_sgen_alloc_os_memory_aligned(size_t size, uintptr_t alignment, int flags, + const char *description, int account_type) +{ + if (!pool_enabled || size != BlockSize || alignment != BlockSize || + !description || strcmp(description, "major heap section") != 0) + return __real_sgen_alloc_os_memory_aligned(size, alignment, flags, description, account_type); + + if (!available) { + struct Slab *slab = malloc(sizeof(*slab)); + if (!slab) + return __real_sgen_alloc_os_memory_aligned(size, alignment, flags, description, account_type); + + slab->base = __real_sgen_alloc_os_memory_aligned(SlabSize, BlockSize, flags, NULL, account_type); + if (!slab->base) { + free(slab); + return __real_sgen_alloc_os_memory_aligned(size, alignment, flags, description, account_type); + } + slab->available = UINT32_MAX; + unsigned first_page = (uintptr_t)slab->base / BlockSize; + for (unsigned index = 0; index < BlocksPerSlab; index++) + pages[first_page + index] = slab; + add_available(slab); + } + + struct Slab *slab = available; + unsigned index = __builtin_ctz(slab->available); + slab->available &= ~(UINT32_C(1) << index); + if (!slab->available) + remove_available(slab); + + void *block = slab->base + index * BlockSize; + memset(block, 0, BlockSize); + if (allocations++ == 0) + puts("IOExtend SGen aligned block pool active."); + return block; +} + +void __wrap_sgen_free_os_memory(void *block, size_t size, int flags, int account_type) +{ + uintptr_t address = (uintptr_t)block; + struct Slab *slab = size == BlockSize && address % BlockSize == 0 ? pages[address / BlockSize] : NULL; + if (!slab) { + __real_sgen_free_os_memory(block, size, flags, account_type); + return; + } + + unsigned index = (address - (uintptr_t)slab->base) / BlockSize; + uint32_t bit = UINT32_C(1) << index; + if (slab->available & bit) + abort(); + if (!slab->available) + add_available(slab); + slab->available |= bit; + if (slab->available != UINT32_MAX) + return; + + remove_available(slab); + unsigned first_page = (uintptr_t)slab->base / BlockSize; + for (unsigned slot = 0; slot < BlocksPerSlab; slot++) + pages[first_page + slot] = NULL; + __real_sgen_free_os_memory(slab->base, SlabSize, flags, account_type); + free(slab); +} diff --git a/site/artwork/voxel-building.py b/site/artwork/voxel-building.py new file mode 100644 index 0000000..7f9933e --- /dev/null +++ b/site/artwork/voxel-building.py @@ -0,0 +1,90 @@ +"""Draw the IOExtend landing illustration in a compact, pixel-aligned projection.""" + +from pathlib import Path + +from PIL import Image, ImageDraw, PngImagePlugin + + +image = Image.new("RGBA", (272, 192)) +draw = ImageDraw.Draw(image) +origin = (137, 107) + + +def point(x, y, z=0): + return origin[0] + (x - y) * 8, origin[1] + (x + y) * 4 - z * 8 + + +def polygon(vertices, color): + draw.polygon([point(*vertex) for vertex in vertices], fill=color) + + +def line(vertices, color): + draw.line([point(*vertex) for vertex in vertices], fill=color) + + +def block(x, y, z, width, depth, height, colors): + right, front, top = x + width, y + depth, z + height + polygon([(right, y, z), (right, front, z), (right, front, top), (right, y, top)], colors[2]) + polygon([(x, front, z), (right, front, z), (right, front, top), (x, front, top)], colors[1]) + polygon([(x, y, top), (right, y, top), (right, front, top), (x, front, top)], colors[0]) + + +# Projected ground grid and registration marks extend the drawing beyond the model. +for offset in range(-7, 8): + tone = "#405068" if offset == 0 else "#2d3647" + line([(offset, -8, -2), (offset, 8, -2)], tone) + line([(-8, offset, -2), (8, offset, -2)], tone) + +for x, y in [(-7, 7), (7, -7), (-7, -3), (4, 7)]: + px, py = point(x, y, -2) + draw.line([(px - 3, py), (px + 3, py)], fill="#70839d") + draw.line([(px, py - 3), (px, py + 3)], fill="#70839d") + +palette = { + "ground": ("#39465e", "#28354b", "#1d293c"), + "foundation": ("#7289ad", "#42597b", "#293b5e"), + "cyan": ("#a5f3fc", "#27b8d0", "#146384"), + "blue": ("#93c5fd", "#4386e6", "#234b9f"), + "purple": ("#d8b4fe", "#9860e1", "#5633a1"), + "amber": ("#ffdb76", "#e89c3f", "#9b5d29"), + "glass": ("#547fa9", "#315578", "#20395b"), +} + +block(-6, -6, -2, 12, 12, 1, palette["ground"]) +block(-5, -5, -1, 10, 10, 1, palette["foundation"]) + +# Rear wing, central column grid, and the two lower volumes. +block(-4, -4, 0, 4, 3, 4, palette["blue"]) +for floor in (1, 2, 3): + line([(-4, -1, floor), (0, -1, floor)], "#6da8ef") + line([(0, -4, floor), (0, -1, floor)], "#2a5bae") + +block(0, -4, 0, 4, 4, 6, palette["glass"]) +for floor in (0, 2, 4, 6): + block(0, -4, floor, 4, 4, 0.34, palette["cyan"]) +for x in (0, 1.2, 2.4, 3.6): + block(x, -0.4, 0.34, 0.35, 0.4, 6, palette["cyan"]) +for y in (-3.6, -2.4, -1.2): + block(3.65, y, 0.34, 0.35, 0.4, 6, palette["blue"]) +block(0.5, -3.5, 6.34, 3, 3, 1, palette["blue"]) +block(1, -3, 7.34, 2, 2, 1, palette["cyan"]) + +block(-4, 0, 0, 4, 4, 2, palette["amber"]) +block(-4, 0, 2, 4, 2, 1, palette["amber"]) +for x in (-3.5, -2.5, -1.5): + line([(x, 4, 0.5), (x, 4, 1.5)], "#a76832") + +block(0, 0, 0, 4, 4, 2, palette["purple"]) +block(1, 1, 2, 3, 3, 1, palette["purple"]) +for y in (0.5, 1.5, 2.5, 3.5): + line([(4, y, 0.5), (4, y, 1.5)], "#7547b8") + +# Detached register blocks carry the palette into the plan without obscuring its outline. +block(-7, 0, -1, 1, 1, 1, palette["amber"]) +block(0, -7, -1, 1, 1, 1, palette["cyan"]) +block(6, 4, -1, 1, 1, 1, palette["purple"]) + +metadata = PngImagePlugin.PngInfo() +metadata.add_text("Source", "Original parallel-projected geometry drawn by artwork/voxel-building.py for IOExtend.Web") +output = Path(__file__).resolve().parents[1] / "wwwroot" / "brand" / "voxel-building.png" +image.save(output, pnginfo=metadata, optimize=True) diff --git a/site/build-paged-viewer.mjs b/site/build-paged-viewer.mjs new file mode 100644 index 0000000..b44e4e3 --- /dev/null +++ b/site/build-paged-viewer.mjs @@ -0,0 +1,53 @@ +import { createRequire } from 'node:module'; +import { readFile, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { viewerTheme } from './wwwroot/viewer-theme.js'; + +const viewer = resolve(process.argv[2], 'src/IOViewer/Viewer'); +const { build } = createRequire(resolve(viewer, 'package.json'))('esbuild'); +const output = name => new URL('./wwwroot/' + name, import.meta.url); + +const [{ outputFiles }, { outputFiles: storage }, css] = await Promise.all([ + build({ + stdin: { + contents: await readFile(new URL('./paged-frame.js', import.meta.url), 'utf8'), + resolveDir: viewer, + sourcefile: 'paged-frame.js', + }, + bundle: true, minify: true, format: 'esm', write: false, + }), + build({ + entryPoints: [resolve(viewer, 'src/stream/meshStorage.js')], + bundle: true, minify: true, format: 'esm', write: false, + }), + readFile(resolve(viewer, 'styles/viewer.css'), 'utf8'), +]); + +const html = ` + + + + +IOViewer + + +
+
+ + +
+ +
+
+ + +`; + +await Promise.all([ + writeFile(output('paged-viewer.html'), html), + writeFile(output('paged-storage.js'), storage[0].text), +]); diff --git a/site/fast-reader-smoke.cjs b/site/fast-reader-smoke.cjs new file mode 100644 index 0000000..2dcf377 --- /dev/null +++ b/site/fast-reader-smoke.cjs @@ -0,0 +1,194 @@ +const assert = require('node:assert/strict'); +const { chromium } = require('playwright'); + +const [url, staticUrl] = process.argv.slice(2); +assert(url, 'Usage: node fast-reader-smoke.cjs [static-site-url]'); + +const html = "Test view"; +const blob = "new Blob([" + JSON.stringify(html) + "], {type:'text/html'})"; +const workerCode = expression => 'self.onmessage = () => self.postMessage(' + expression + ');'; +const timedReader = ` + self.onmessage = ({ data }) => { + if (data.finish) self.postMessage({ html: ${blob} }); + else self.postMessage({ progress: data.progress ?? { percent: 5, key: 'view.check' } }); + }; +`; + +async function sendToFastReader(page, message) { + assert(await page.evaluate(() => typeof window.testFastReader?.onmessage === 'function'), + 'The fast reader stopped before the next progress update.'); + return page.evaluate(message => new Promise(resolve => { + const worker = window.testFastReader; + worker.addEventListener('message', () => resolve(), { once: true }); + worker.postMessage(message); + }), message); +} + +async function run(browser, scenario) { + const name = scenario === 'nwc' ? 'fast-reader-smoke.nwc' : 'fast-reader-smoke.rvt'; + const file = { name, mimeType: 'application/octet-stream', buffer: Buffer.from('fixture') }; + const context = await browser.newContext({ serviceWorkers: 'block' }); + try { + const page = await context.newPage(); + const timed = scenario === 'timeout' || scenario === 'progress'; + const slowFrame = scenario === 'slow-frame'; + const frameTimeout = scenario === 'frame-timeout'; + const clocked = timed || slowFrame || frameTimeout || scenario === 'cancel'; + if (clocked) await page.clock.install(); + if (scenario === 'fast') await page.addInitScript(() => { + const measure = performance.measure.bind(performance); + performance.measure = (name, ...options) => { + if (name === 'ioextend:first-frame') { + const frame = document.querySelector('#viewer'); + window.visibleAtFirstFrame = Boolean(frame && !frame.inert && + frame.checkVisibility({ opacityProperty: true }) && !document.querySelector('.viewer-loading')); + } + return measure(name, ...options); + }; + }); + if (timed) await page.addInitScript(() => { + const Worker = window.Worker; + window.Worker = class extends Worker { + constructor(url, options) { + super(url, options); + if (url.pathname.includes('/fast-reader/')) window.testFastReader = this; + } + }; + }); + await context.addInitScript(memory => { + Object.defineProperty(navigator, 'deviceMemory', { value: memory }); + Object.defineProperty(navigator, 'hardwareConcurrency', { value: 8 }); + }, scenario === 'memory' ? 4 : 8); + if (scenario === 'unisolated') await context.route(url, async route => { + const response = await route.fetch(); + const headers = response.headers(); + delete headers['cross-origin-opener-policy']; + delete headers['cross-origin-embedder-policy']; + await route.fulfill({ response, headers }); + }); + + const workers = []; + const failures = []; + page.on('pageerror', error => failures.push(error.message)); + await context.route('**/reader.js', async route => { + const fast = new URL(route.request().url()).pathname.includes('/fast-reader/'); + workers.push(fast ? 'fast' : 'bounded'); + let body = workerCode('{ html: ' + blob + ' }'); + if (fast) { + if (scenario === 'failure') return route.abort('failed'); + if (scenario === 'read-error') body = workerCode('{ html: ' + blob + ', errors: 1 }'); + if (scenario === 'renderer') body = workerCode( + "{ html: new Blob([\"\"], {type:'text/html'}) }"); + if (slowFrame || frameTimeout) body = workerCode( + "{ html: new Blob(['Waiting'], {type:'text/html'}) }"); + if (timed) body = timedReader; + if (scenario === 'cancel') body = workerCode( + "{ progress: { percent: 5, key: 'view.check' } }"); + } + return route.fulfill({ response: await route.fetch(), body }); + }); + + await page.goto(scenario === 'shared-file' ? url + '#export' : url); + assert.equal(await page.evaluate(() => crossOriginIsolated), scenario !== 'unisolated'); + const waitForWorker = page.waitForRequest(request => new URL(request.url()).pathname.endsWith('/reader.js')); + if (scenario === 'shared-file') { + await page.locator('#app[data-mode="export"]').waitFor(); + await page.locator('#operation-input').setInputFiles(file); + assert.equal(await page.locator('#operation-file').textContent(), name); + await page.locator('nav a[href="#view"]').click(); + } else if (scenario === 'at-limit' || scenario === 'over-limit') { + await page.locator('#file-input').evaluate((input, { name, over }) => { + const mib = new Blob([new Uint8Array(1024 * 1024)]); + const parts = Array(50).fill(mib); + if (over) parts.push(new Uint8Array(1)); + const transfer = new DataTransfer(); + transfer.items.add(new File(parts, name)); + input.files = transfer.files; + input.dispatchEvent(new Event('change', { bubbles: true })); + }, { name, over: scenario === 'over-limit' }); + } else { + await page.locator('#file-input').setInputFiles(file); + } + await waitForWorker; + + if (scenario === 'cancel') { + await page.locator('#cancel').click(); + await page.locator('#cancel').waitFor({ state: 'hidden' }); + await page.clock.fastForward(30_000); + assert.deepEqual(workers, ['fast']); + assert.equal(await page.locator('#viewer').isHidden(), true); + } else { + if (timed) { + await page.locator('#open-meter[value="5"]').waitFor(); + await page.clock.fastForward(20_000); + if (scenario === 'timeout') { + await sendToFastReader(page, { progress: { percent: 5, key: 'view.check' } }); + await page.clock.fastForward(5_001); + } else { + const progress = { percent: 55, key: 'view.paramCount', completed: 1, total: 10 }; + await sendToFastReader(page, { progress }); + await page.clock.fastForward(20_000); + await sendToFastReader(page, { progress: { ...progress, completed: 2 } }); + await page.clock.fastForward(20_000); + await sendToFastReader(page, { finish: true }); + } + } + if (slowFrame || frameTimeout) { + const waiting = page.locator('.viewer-loading'); + await waiting.waitFor({ state: 'attached' }); + if (slowFrame) { + await page.clock.fastForward(5_001); + assert.equal(await waiting.count(), 1, 'The slow renderer must keep the prepared scene.'); + assert.deepEqual(workers, ['fast']); + const frame = await (await waiting.elementHandle()).contentFrame(); + await frame.locator('title').waitFor({ state: 'attached' }); + await frame.evaluate(() => parent.postMessage({ type: 'ioviewer-page-ready' }, '*')); + } else { + await page.clock.fastForward(25_001); + } + } + await page.locator('#model-name').getByText(name, { exact: true }).waitFor(); + if (!clocked) assert.equal(await page.evaluate(() => performance.getEntriesByName('ioextend:first-frame').length), 1); + if (scenario === 'fast') assert.equal(await page.evaluate(() => window.visibleAtFirstFrame), true); + assert.equal(await page.locator('#viewer').count(), 1); + assert.equal(await page.locator('.viewer-loading').count(), 0); + assert.deepEqual(workers, ['fast', 'shared-file', 'progress', 'slow-frame', 'at-limit'].includes(scenario) ? ['fast'] + : ['memory', 'unisolated', 'nwc', 'over-limit'].includes(scenario) ? ['bounded'] : ['fast', 'bounded']); + } + assert.deepEqual(failures, []); + console.log('Fast reader smoke passed (' + scenario + ').'); + } finally { + await context.close(); + } +} + +async function runIsolation(browser, root) { + const context = await browser.newContext({ serviceWorkers: 'allow' }); + try { + await context.addInitScript(() => { + Object.defineProperty(navigator, 'deviceMemory', { value: 8 }); + Object.defineProperty(navigator, 'hardwareConcurrency', { value: 8 }); + }); + const page = await context.newPage(); + const response = await page.goto(root, { waitUntil: 'commit' }); + assert.equal(await response.headerValue('cross-origin-opener-policy'), null); + assert.equal(await response.headerValue('cross-origin-embedder-policy'), null); + await page.waitForFunction(() => crossOriginIsolated && Boolean(navigator.serviceWorker.controller)); + assert.equal(await page.evaluate(() => navigator.serviceWorker.controller.scriptURL), + new URL('thread-isolation.js', root).href); + console.log('Fast reader smoke passed (static isolation).'); + } finally { + await context.close(); + } +} + +(async () => { + const browser = await chromium.launch({ executablePath: process.env.VIEWER_CHROME || undefined }); + try { + for (const scenario of ['fast', 'shared-file', 'failure', 'read-error', 'renderer', 'timeout', 'progress', 'slow-frame', 'frame-timeout', 'cancel', 'memory', 'unisolated', 'nwc', 'at-limit', 'over-limit']) + await run(browser, scenario); + if (staticUrl) await runIsolation(browser, staticUrl); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/site/first-frame-smoke.cjs b/site/first-frame-smoke.cjs new file mode 100644 index 0000000..e450f4c --- /dev/null +++ b/site/first-frame-smoke.cjs @@ -0,0 +1,135 @@ +const assert = require('node:assert/strict'); +const { createHash } = require('node:crypto'); +const { readFile } = require('node:fs/promises'); +const { basename } = require('node:path'); +const { chromium } = require('playwright'); + +const [url, rvtPath, nativePath] = process.argv.slice(2); +assert(url && rvtPath && nativePath, + 'Usage: node first-frame-smoke.cjs <2027-racbasicsampleproject.rvt> '); + +const sha256 = value => createHash('sha256').update(value).digest('hex'); +const sceneParts = ['meta', 'bin', 'props']; +const checkpointGeometry = 'aae5c11bdfa3b679b57c4dbdaec8b0fc6b34faead93980615a48c51cc428e955'; + +async function main() { + assert.equal(sha256(await readFile(rvtPath)), 'c9ce4d013b630028973e4549d3be4b38b3640641948b035680eeea7306491a01', + 'Expected the original Revit 2027 racbasicsampleproject.rvt'); + const nativeHtml = await readFile(nativePath, 'utf8'); + const [nativeMeta, nativeBin, nativeProps] = sceneParts.map(name => { + const section = nativeHtml.match(new RegExp('')); + assert(section, 'Native HTML is missing ioviewer-' + name); + return section[1]; + }); + + const browser = await chromium.launch({ + executablePath: process.env.VIEWER_CHROME, + args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + }); + try { + const context = await browser.newContext({ + serviceWorkers: 'block', viewport: { width: 1280, height: 750 }, + }); + const requests = []; + context.on('request', request => requests.push(new URL(request.url()).pathname)); + await context.addInitScript(() => { + window.parameterProgress = []; + window.Worker = class extends Worker { + constructor(url, options) { + super(url, options); + if (String(url).includes('/fast-reader/')) { + this.addEventListener('message', ({ data }) => { + if (data.progress?.key === 'view.paramCount') + window.parameterProgress.push([data.progress.completed, data.progress.total]); + }); + } + } + }; + }); + const page = await context.newPage(); + await page.goto(url); + const capabilities = await page.evaluate(() => ({ + isolated: crossOriginIsolated, cores: navigator.hardwareConcurrency, memoryGiB: navigator.deviceMemory, + })); + assert(capabilities.isolated && capabilities.cores >= 5 && capabilities.memoryGiB >= 8, + 'Fast opening requires an isolated page, at least five logical processors and 8 GiB reported by Chromium'); + await page.evaluate(() => { + const original = document.querySelector('#viewer'); + document.querySelector('#file-input').addEventListener('change', () => { + const selectedAt = performance.now(); + const observer = new MutationObserver(() => { + const frame = document.querySelector('#viewer'); + if (!frame || frame === original || frame.inert || !frame.checkVisibility({ opacityProperty: true })) return; + observer.disconnect(); + // Allow the parent page to paint the revealed iframe before sampling the clock. + requestAnimationFrame(() => requestAnimationFrame(() => { + if (frame.isConnected && !document.hidden && frame.checkVisibility({ opacityProperty: true })) + performance.measure('smoke:visible-frame', { start: selectedAt }); + })); + }); + observer.observe(original.parentNode, { childList: true }); + }, { capture: true, once: true }); + }); + await page.locator('#file-input').setInputFiles(rvtPath); + const selected = page.locator('#model-name').getByText(basename(rvtPath), { exact: true }); + const error = page.locator('#status[data-error]'); + await selected.or(error).waitFor({ timeout: 120_000 }); + assert(await selected.isVisible() && !await error.isVisible(), await page.locator('#status').textContent()); + + await page.waitForFunction(() => performance.getEntriesByName('smoke:visible-frame').length > 0); + const { readyMs, frameMs } = await page.evaluate(() => ({ + readyMs: performance.getEntriesByName('ioextend:first-frame').at(-1)?.duration, + frameMs: performance.getEntriesByName('smoke:visible-frame').at(-1).duration, + })); + assert(Number.isFinite(readyMs) && readyMs > 0 && frameMs >= readyMs, 'Invalid visible-frame timing'); + const wasm = requests.filter(path => /\/dotnet\.native\.[a-z0-9]+\.wasm$/.test(path)); + assert(wasm.length === 1 && wasm[0].includes('/fast-reader/'), + `Expected only the fast reader for the visible frame at ${Math.round(frameMs)} ms. WASM requests: ${wasm.join(', ')}`); + const progress = await page.evaluate(() => window.parameterProgress); + assert(progress.length > 2, 'Expected progress throughout the parameter scan'); + const total = progress[0][1]; + assert(total > 0 && progress[0][0] === 0 && progress.at(-1)[0] === total, + 'Parameter progress must cover the full input'); + assert(progress.every(([completed, length], i) => length === total && + completed >= (progress[i - 1]?.[0] ?? 0) && completed <= total), 'Parameter progress must advance in order'); + const viewer = page.frameLocator('#viewer[src^="blob:"]'); + await viewer.locator('#ioviewer-canvas').waitFor({ state: 'visible' }); + assert(await viewer.locator('#ioviewer-message').isHidden(), 'IOViewer reported a model or WebGL error'); + const [meta, bin, props] = await Promise.all(sceneParts.map(name => + viewer.locator('#ioviewer-' + name).textContent())); + const metadata = JSON.parse(meta); + const reference = JSON.parse(nativeMeta); + const { elements, instances, geometries } = metadata; + const counts = [elements.length, instances.count, geometries.length]; + assert.deepEqual(counts, [466, 730, 403]); + delete metadata.createdAt; + delete reference.createdAt; + assert.deepEqual(metadata, reference, 'Scene metadata differs from the native export'); + assert.equal(sha256(props), sha256(nativeProps), 'Element properties differ from the native export'); + const geometryHash = sha256(bin); + const nativeGeometryHash = sha256(nativeBin); + assert(geometryHash === checkpointGeometry || geometryHash === nativeGeometryHash, + 'Unexpected geometry digest: ' + geometryHash); + const groups = await viewer.locator('#ioviewer-canvas').evaluate(async () => { + const viewer = window.__ioviewer; + await viewer.ready; + const { elements } = JSON.parse(document.querySelector('#ioviewer-meta').textContent); + for (let index = 0; index < elements.length; index++) { + viewer.selection.set([index]); + const groups = document.querySelectorAll('.ioviewer-properties-body section').length; + if (groups >= 3) return groups; + } + return 0; + }); + assert.equal(groups, 3, 'Expected three property groups in IOViewer'); + console.log(JSON.stringify({ chromium: browser.version(), firstFrameMs: Math.round(frameMs), viewerReadyMs: Math.round(readyMs), + elements: counts[0], instances: counts[1], packagedGeometries: counts[2], groups, geometryHash, nativeGeometryHash })); + } finally { + await browser.close(); + } +} + +main().catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/site/localization-smoke.cjs b/site/localization-smoke.cjs new file mode 100644 index 0000000..1aa9dc9 --- /dev/null +++ b/site/localization-smoke.cjs @@ -0,0 +1,130 @@ +const assert = require('node:assert/strict'); +const { copyFile, mkdtemp, rm } = require('node:fs/promises'); +const { tmpdir } = require('node:os'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { chromium } = require('playwright'); + +const [url, nwc, rvt] = process.argv.slice(2); +assert(url && nwc, 'Usage: node localization-smoke.cjs []'); +const origin = new URL(url).origin; + +(async () => { + const { dictionaries } = await import('./wwwroot/translations.js'); + const { locales } = await import('./wwwroot/locale.js'); + const keys = Object.keys(dictionaries.en).sort(); + const placeholders = text => [...text.matchAll(/\{\w+\}/g)].map(([token]) => token).sort(); + for (const locale of locales) { + assert.deepEqual(Object.keys(dictionaries[locale]).sort(), keys, locale); + for (const key of keys) { + assert(dictionaries[locale][key].trim(), `${locale} ${key}`); + assert.deepEqual(placeholders(dictionaries[locale][key]), placeholders(dictionaries.en[key]), `${locale} ${key}`); + } + } + + const directory = await mkdtemp(path.join(tmpdir(), 'ioextend-languages-')); + const browser = await chromium.launch({ executablePath: process.env.VIEWER_CHROME }); + try { + const context = await browser.newContext({ acceptDownloads: true, locale: 'es-MX' }); + const page = await context.newPage(); + const pageErrors = []; + const externalRequests = []; + page.on('pageerror', error => pageErrors.push(error.message)); + page.on('request', request => { + const requestUrl = new URL(request.url()); + if (requestUrl.protocol.startsWith('http') && requestUrl.origin !== origin) + externalRequests.push(request.url()); + }); + await page.goto(url); + const picker = page.locator('#site-language'); + await page.getByRole('heading', { name: dictionaries.es.drop }).waitFor(); + assert.equal(await page.locator('html').getAttribute('lang'), 'es'); + assert.deepEqual(await picker.locator('option').evaluateAll(options => options.map(option => option.value)), ['auto', ...locales]); + for (const locale of locales) { + await picker.selectOption(locale); + await page.getByRole('heading', { name: dictionaries[locale].drop }).waitFor(); + assert.equal(await page.locator('html').getAttribute('lang'), locale); + } + await picker.selectOption('de'); + await page.setViewportSize({ width: 320, height: 700 }); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + await page.reload(); + await page.getByRole('heading', { name: dictionaries.de.drop }).waitFor(); + assert.equal(await picker.inputValue(), 'de'); + await picker.selectOption('auto'); + await page.getByRole('heading', { name: dictionaries.es.drop }).waitFor(); + await page.setViewportSize({ width: 1280, height: 900 }); + + for (const [filePath, kind] of [[nwc, 'nwc'], ...(rvt ? [[rvt, 'rvt']] : [])]) { + await page.locator('.tools-nav a[href="#view"]').click(); + await page.locator('#file-input').setInputFiles(filePath); + await page.locator('#model-name').getByText(path.basename(filePath), { exact: true }).waitFor({ timeout: 360_000 }); + const viewer = page.frameLocator('#viewer'); + await viewer.getByRole('button', { name: 'Modelo', exact: true }).waitFor({ timeout: 360_000 }); + assert.equal(await viewer.locator('#ioviewer-language').count(), 0); + const readerRequests = []; + const recordReader = request => { if (new URL(request.url()).pathname.endsWith('/reader.js')) readerRequests.push(request.url()); }; + page.on('request', recordReader); + await picker.selectOption('ja'); + await viewer.getByRole('button', { name: 'モデル', exact: true }).waitFor({ timeout: 60_000 }); + assert.equal(await viewer.locator('html').getAttribute('lang'), 'ja'); + assert.deepEqual(readerRequests, []); + page.off('request', recordReader); + console.log(`Embedded ${kind.toUpperCase()} switched languages without reading the source again.`); + + await page.locator('a[href="#export"]').click(); + await page.locator('#operation-input').setInputFiles(filePath); + await page.locator('input[value=html]').check(); + await picker.selectOption('fr'); + assert(await page.locator('input[value=html]').isChecked()); + const gate = Promise.withResolvers(); + const blockWorker = async route => { + await gate.promise; + await route.continue(); + }; + await page.route('**/export-worker.js', blockWorker, { times: 1 }); + await page.getByRole('button', { name: dictionaries.fr.exportAction }).click(); + try { + await page.locator('#operation-progress').waitFor(); + await picker.selectOption('de'); + assert.match(await page.locator('#operation-phase').innerText(), /Eigenständiger 3D-Viewer/); + } finally { + gate.resolve(); + } + const link = page.getByRole('link', { name: /^Herunterladen .*\.html$/ }); + const error = page.locator('#operation-downloads [data-error]'); + await link.or(error).waitFor({ timeout: 360_000 }); + assert(await link.isVisible(), await page.locator('#operation-results').innerText()); + const started = page.waitForEvent('download'); + await link.click(); + const download = await started; + assert.equal(await download.failure(), null); + const exported = path.join(directory, kind + '.html'); + await copyFile(await download.path(), exported); + + const offline = await browser.newContext({ locale: 'zh-TW', offline: true }); + try { + const standalone = await offline.newPage(); + standalone.on('pageerror', error => pageErrors.push(error.message)); + await standalone.goto(pathToFileURL(exported).href); + await standalone.getByRole('button', { name: '模型', exact: true }).waitFor(); + assert.equal(await standalone.locator('html').getAttribute('lang'), 'zh-Hant'); + await standalone.locator('#ioviewer-language').selectOption('it'); + await standalone.getByRole('button', { name: 'Modello', exact: true }).waitFor(); + console.log(`Standalone ${kind.toUpperCase()} switched languages offline.`); + } finally { + await offline.close(); + } + await picker.selectOption('auto'); + } + await page.locator('a[href="#downgrade"]').click(); + await picker.selectOption('pt'); + await page.getByLabel(dictionaries.pt.targetVersion).waitFor(); + assert.deepEqual(externalRequests, []); + assert.deepEqual(pageErrors, []); + console.log('Site locale detection, persistence, 11 dictionaries, mobile layout, embedded and exported offline viewers verified.'); + } finally { + await browser.close(); + await rm(directory, { recursive: true, force: true }); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/site/operations-smoke.cjs b/site/operations-smoke.cjs new file mode 100644 index 0000000..d2f4241 --- /dev/null +++ b/site/operations-smoke.cjs @@ -0,0 +1,187 @@ +const assert = require('node:assert/strict'); +const { readFile } = require('node:fs/promises'); +const { basename } = require('node:path'); +const { chromium } = require('playwright'); + +const [url, nwc, rvt, target, downgradeSource = rvt] = process.argv.slice(2); +assert(url && nwc && rvt && /^20\d\d$/.test(target ?? ''), + 'Usage: node operations-smoke.cjs []'); +const origin = new URL(url).origin; + +async function select(page, route, path) { + await page.goto(url + '#' + route); + await page.locator(`#app[data-mode="${route}"]`).waitFor(); + await page.locator('#operation-input').setInputFiles(path); + const file = await page.locator('#operation-file').textContent(); + assert(file.toLowerCase().endsWith(route === 'export' && path === nwc ? '.nwc' : '.rvt')); +} + +async function ready(page) { + const success = page.locator('#operation-status').getByText('Готово. Результаты можно скачать.'); + await success.or(page.locator('#operation-status[data-error]')).waitFor({ timeout: 480_000 }); + assert(await success.isVisible(), await page.locator('#operation-downloads').innerText()); + assert(await page.locator('#operation-progress').isHidden()); + assert(await page.locator('#cancel-operation').isHidden()); +} + +async function observeProgress(page) { + await page.evaluate(() => { + const element = document.getElementById('operation-progress'); + window.operationProgress = { phases: [], counts: [], io: [], batches: [] }; + const record = (key, id) => { + const value = document.getElementById(id).textContent; + if (value && window.operationProgress[key].at(-1) !== value) + window.operationProgress[key].push(value); + }; + new MutationObserver(() => { + if (element.hidden) return; + record('phases', 'operation-phase'); + record('counts', 'operation-count'); + record('io', 'operation-io'); + if (!document.getElementById('operation-batch').hidden) + record('batches', 'operation-batch-label'); + }).observe(element, { attributes: true, childList: true, subtree: true }); + }); +} + +async function download(page, selector) { + const started = page.waitForEvent('download'); + await page.locator(selector).click(); + const file = await started; + assert.equal(await file.failure(), null); + return readFile(await file.path()); +} + +(async () => { + const browser = await chromium.launch({ executablePath: process.env.VIEWER_CHROME }); + try { + const context = await browser.newContext({ acceptDownloads: true, locale: 'ru-RU' }); + const errors = []; + const outside = []; + const readerRequests = []; + context.on('request', request => { + if (new URL(request.url()).pathname.endsWith('/reader.js')) readerRequests.push(request.url()); + }); + await context.route('**/*', route => { + const request = route.request(); + if (new URL(request.url()).origin === origin && request.method() === 'GET') return route.continue(); + outside.push(request.method() + ' ' + new URL(request.url()).origin); + return route.abort(); + }); + const page = await context.newPage(); + page.on('pageerror', error => errors.push(error.message)); + await page.goto(url + '#export'); + await page.locator('#operation-drop').evaluate((target, { name, bytes }) => { + const dataTransfer = new DataTransfer(); + dataTransfer.items.add(new File([Uint8Array.from(atob(bytes), char => char.charCodeAt(0))], name)); + target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer })); + }, { name: basename(nwc), bytes: (await readFile(nwc)).toString('base64') }); + assert.equal(await page.locator('#operation-file').textContent(), basename(nwc)); + assert(await page.locator('#workspace').isHidden()); + await page.getByRole('link', { name: 'Версия Revit' }).click(); + await page.locator('#downgrade-settings').waitFor(); + assert.equal(await page.locator('#operation-file').textContent(), basename(nwc)); + assert(await page.locator('#run-operation').isDisabled()); + assert(await page.locator('#workspace').isHidden()); + assert.deepEqual(readerRequests, []); + await page.getByRole('link', { name: 'Просмотр' }).click(); + await page.locator('#model-name').getByText(basename(nwc), { exact: true }).waitFor(); + assert(readerRequests.length > 0); + await page.getByRole('link', { name: 'Экспорт' }).click(); + await page.locator('input[value=glb]').check(); + await page.locator('input[value=json]').check(); + await observeProgress(page); + await page.getByRole('button', { name: 'Экспортировать' }).click(); + await ready(page); + const batchProgress = await page.evaluate(() => window.operationProgress); + assert.deepEqual(batchProgress.batches, ['Завершено форматов 0 из 2', 'Завершено форматов 1 из 2']); + assert(batchProgress.phases.some(label => label.startsWith('Читаем и разбираем модель'))); + assert(batchProgress.phases.some(label => label.startsWith('Записываем результат'))); + assert(batchProgress.io.some(label => label.includes('Записано'))); + const glb = await download(page, '#operation-downloads a[download$=".glb"]'); + assert.equal(glb.toString('ascii', 0, 4), 'glTF'); + assert.equal(glb.readUInt32LE(8), glb.length); + const json = await download(page, '#operation-downloads a[download$=".json"]'); + assert(Object.keys(JSON.parse(json)).length); + console.log('NWC exports both selected formats and downloads valid GLB and JSON.'); + + await select(page, 'export', rvt); + await page.locator('input[value=ifc-parameters]').check(); + await page.getByRole('button', { name: 'Экспортировать' }).click(); + await ready(page); + const ifc = (await download(page, '#operation-downloads a[download$=".ifc"]')).toString('utf8'); + assert.match(ifc, /^ISO-10303-21;/); + assert.match(ifc, /IFCPROJECT\(/i); + assert.match(ifc, /IFCPROPERTYSET\(/i); + assert.match(ifc, /END-ISO-10303-21;\s*$/); + console.log('RVT exports and downloads a complete IFC project with property sets.'); + + await select(page, 'downgrade', downgradeSource); + assert(await page.locator('#run-operation').isDisabled()); + const sourceVersion = page.locator('#source-version'); + await sourceVersion.getByText(/Исходный файл · Revit \d{4}/).waitFor(); + const year = Number((await sourceVersion.textContent()).match(/\d{4}/)[0]); + const choices = await page.locator('#target-version option').evaluateAll(options => + options.map(option => Number(option.value)).filter(Boolean)); + assert.deepEqual(choices, [2026, 2025, 2024, 2023, 2022, 2021, 2020].filter(version => version < year)); + await page.getByLabel('Целевая версия Revit').selectOption(target); + await observeProgress(page); + await page.getByRole('button', { name: 'Создать копию' }).click(); + await ready(page); + const downgradeProgress = await page.evaluate(() => window.operationProgress); + assert.deepEqual(downgradeProgress.counts, Array.from({ length: 9 }, (_, i) => `Этап ${i + 1} из 9`), + downgradeProgress.phases.join(' → ')); + assert(downgradeProgress.io.some(label => label.includes('Прочитано из исходника'))); + assert(downgradeProgress.io.some(label => label.includes('Записано'))); + const downgraded = await download(page, '#operation-downloads a[download$=".rvt"]'); + assert.equal(downgraded.toString('hex', 0, 8), 'd0cf11e0a1b11ae1'); + await page.getByText('Сведения обработки', { exact: true }).click(); + const report = JSON.parse(await download(page, '#operation-downloads a[download$=".json"]')); + assert.equal(report.source.release, year); + assert.equal(report.output.release, Number(target)); + assert.equal(report.output.release, report.profile.release); + console.log(`Revit ${report.source.release} → ${report.output.release} produces a compound-file copy and matching report.`); + + await page.locator('#operation-input').setInputFiles({ + name: 'damaged.rvt', mimeType: 'application/octet-stream', buffer: Buffer.from('not a compound file') + }); + await sourceVersion.getByText('Не удалось определить версию.', { exact: false }).waitFor(); + assert(await page.locator('#target-version').isDisabled()); + assert(await page.locator('#run-operation').isDisabled()); + assert.equal(await page.locator('#operation-downloads a').count(), 0); + + await select(page, 'export', rvt); + await page.locator('input[value=glb]').check(); + await page.locator('#run-operation').click(); + await page.locator('#operation-count').getByText(/% этапа/).waitFor({ timeout: 60_000 }); + const meter = await page.locator('#operation-meter').evaluate(element => + ({ value: element.value, max: element.max, determinate: element.hasAttribute('value') })); + assert(meter.determinate && meter.max > 0 && meter.value >= 0 && meter.value <= meter.max); + await page.locator('#operation-elapsed').getByText(/Прошло (?!0:00)\d+:\d{2}/).waitFor(); + await page.getByRole('link', { name: 'Версия Revit' }).click(); + await page.locator('#operation-progress').waitFor({ state: 'hidden' }); + await page.getByRole('link', { name: 'Экспорт' }).click(); + await page.locator('#operation-progress').waitFor(); + await page.locator('#cancel-operation').click(); + await page.locator('#operation-status').getByText('Обработка отменена.').waitFor(); + assert(await page.locator('#operation-progress').isHidden()); + assert(await page.locator('#run-operation').isEnabled()); + + await page.locator('#operation-input').setInputFiles({ + name: 'damaged.rvt', mimeType: 'application/octet-stream', buffer: Buffer.from('not a compound file') + }); + await page.locator('input[value=ifc-parameters]').check(); + await page.locator('#run-operation').click(); + await page.locator('#operation-downloads [data-error]').waitFor(); + assert.doesNotMatch(await page.locator('#operation-downloads [data-error]').innerText(), /Program terminated/); + assert(await page.locator('#operation-progress').isHidden()); + + await page.getByRole('link', { name: 'Просмотр' }).click(); + await page.locator('#status[data-error]').getByText('Не удалось открыть модель.', { exact: false }).waitFor(); + assert.deepEqual(outside, []); + assert.deepEqual(errors, []); + console.log('Invalid metadata clears the previous version choices, the preview route remains usable, and model data stays local.'); + } finally { + await browser.close(); + } +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/site/operations/IOExtend.Operations.csproj b/site/operations/IOExtend.Operations.csproj new file mode 100644 index 0000000..de4fdcc --- /dev/null +++ b/site/operations/IOExtend.Operations.csproj @@ -0,0 +1,38 @@ + + + net10.0 + Exe + enable + enable + true + false + false + + false + + + net11.0 + true + 4294901760 + $(EmccExtraLDFlags) -sMALLOC=dlmalloc + + + $(DefineConstants);MODEL_EXPORT + $(DefineConstants);RVT_PARTITION_SCRATCH + + + + + + + + + + + + + + + + + diff --git a/site/operations/Publish.ps1 b/site/operations/Publish.ps1 new file mode 100644 index 0000000..aca3667 --- /dev/null +++ b/site/operations/Publish.ps1 @@ -0,0 +1,43 @@ +param( + [Parameter(Mandatory)] [string] $Site, + [Parameter(Mandatory)] [string] $Build, + [Parameter(Mandatory)] [string] $RvtIOProgressSource, + [Parameter(Mandatory)] [string] $NwcIOSource, + [Parameter(Mandatory)] [string] $DowngradeSource, + [switch] $ExportLargeHeap, + [string] $IOViewerSource, + [bool] $RvtIOPartitionScratch = $true +) + +$ErrorActionPreference = 'Stop' +$project = Join-Path $PSScriptRoot 'IOExtend.Operations.csproj' +$siteRoot = (Resolve-Path -LiteralPath $Site).Path +if (!(Test-Path -LiteralPath (Join-Path $siteRoot 'index.html'))) { + throw 'Site must point to the published wwwroot containing index.html.' +} +$Build = [IO.Path]::GetFullPath($Build) + +function Publish-Tool([string] $name, [string[]] $properties) { + $folder = Join-Path $Build $name + $output = Join-Path $folder 'publish' + dotnet publish $project -c Release -m:1 -nodeReuse:false --artifacts-path (Join-Path $folder 'artifacts') -o $output @properties + if ($LASTEXITCODE -ne 0) { throw "Could not build $name." } + $destination = Join-Path $siteRoot $name + New-Item -ItemType Directory -Path $destination -Force | Out-Null + Copy-Item -Path (Join-Path $output 'wwwroot/*') -Destination $destination -Recurse -Force +} + +Publish-Tool 'model-export' @( + "-p:RvtIOProgressSource=$((Resolve-Path -LiteralPath $RvtIOProgressSource).Path)" + "-p:NwcIOSource=$((Resolve-Path -LiteralPath $NwcIOSource).Path)" + "-p:CustomAfterMicrosoftCommonTargets=$(Join-Path $PSScriptRoot 'compat/BrowserRvt.targets')" + "-p:IOExtendLargeExportHeap=$($ExportLargeHeap.IsPresent.ToString().ToLowerInvariant())" + "-p:RvtIOPartitionScratch=$($RvtIOPartitionScratch.ToString().ToLowerInvariant())" + if ($IOViewerSource) { "-p:IOViewerSource=$((Resolve-Path -LiteralPath $IOViewerSource).Path)" } +) +Publish-Tool 'revit-downgrade' @( + "-p:DowngradeSource=$((Resolve-Path -LiteralPath $DowngradeSource).Path)" +) + +node (Join-Path $PSScriptRoot '../prepare-web-release.mjs') $siteRoot +if ($LASTEXITCODE -ne 0) { throw 'Could not prepare the site release.' } diff --git a/site/operations/Runner.cs b/site/operations/Runner.cs new file mode 100644 index 0000000..79cb25b --- /dev/null +++ b/site/operations/Runner.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using System.Reflection; +using System.Runtime.InteropServices.JavaScript; +using System.Runtime.Versioning; +using System.Text; +using System.Text.Json; +#if !MODEL_EXPORT +using OpenMcdf; +#endif +#if MODEL_EXPORT +using IOScene; +using IOScene.Formats; +using IOViewer.Exporters; +using NwcIO.Scene; +using RvtIO.Scene; +using RvtIO; +#endif + +[SupportedOSPlatform("browser")] +internal static partial class Runner +{ + private static void Main() { } + +#if !MODEL_EXPORT + [JSExport] + internal static int ReadRevitVersion(string path) + { + using var root = RootStorage.OpenRead(path); + if (!root.TryOpenStream("BasicFileInfo", out var stream)) + throw new InvalidDataException("В контейнере отсутствуют метаданные Revit."); + using (stream) + { + if (stream.Length is < 12 or > 256 * 1024) + throw new InvalidDataException("Некорректный размер метаданных Revit."); + var bytes = new byte[stream.Length]; + stream.ReadExactly(bytes); + var reader = typeof(RvtIO.RvtFileReader).Assembly.GetType("RvtIO.Parsing.BasicFileInfoReader", throwOnError: true)!; + var parse = reader.GetMethod("Parse", BindingFlags.Static | BindingFlags.NonPublic)!; + var info = (Dictionary)parse.Invoke(null, [bytes])!; + return int.TryParse(info.GetValueOrDefault("RevitVersion"), out int year) && year is >= 2008 and <= 2099 + ? year + : throw new InvalidDataException("По метаданным не удалось определить версию Revit."); + } + } +#endif + + [JSExport] + internal static string Run(string tool, string arguments) + { + string[] args = JsonSerializer.Deserialize(arguments) ?? throw new ArgumentException("Не заданы аргументы."); +#if MODEL_EXPORT + if (tool is "RevitScene" or "NwcScene") + { + try { return ExportScene(tool, args); } + catch (Exception error) { return Failure(error, "", ""); } + } +#endif + if (tool is not ("RvtIO.Cli" or "RvtIO.Nwc" or "NwcIO.Cli")) + throw new ArgumentException("Неизвестный обработчик.", nameof(tool)); + Assembly assembly = Assembly.Load(tool); + using var output = new TailWriter(args is ["downgrade", ..] ? ReportDowngradeLine : null); + using var errors = new TailWriter(tool == "RvtIO.Cli" && args is not ["downgrade", ..] + ? ReportExportLine : null); + TextWriter originalOutput = Console.Out; + TextWriter originalErrors = Console.Error; + try + { + Console.SetOut(output); + Console.SetError(errors); + int exitCode; + if (tool == "NwcIO.Cli" && Array.IndexOf(args, "-") >= 0) + { + var run = assembly.EntryPoint!.DeclaringType!.GetMethod("Run", BindingFlags.Static | BindingFlags.NonPublic); + exitCode = (int)run!.Invoke(null, [args, Stream.Null, output, errors])!; + } + else + { + var entryPoint = assembly.EntryPoint ?? throw new InvalidOperationException("Не найден обработчик."); + exitCode = (int)entryPoint.Invoke(null, [args])!; + } + return JsonSerializer.Serialize(new { exitCode, output = output.ToString(), diagnostics = errors.ToString() }); + } + catch (Exception error) + { + if (error is TargetInvocationException { InnerException: { } cause }) error = cause; + return Failure(error, output.ToString(), errors.ToString()); + } + finally + { + Console.SetOut(originalOutput); + Console.SetError(originalErrors); + } + } + + private static string Failure(Exception error, string output, string diagnostics) => + JsonSerializer.Serialize(new { exitCode = 1, output, diagnostics, error = error.GetBaseException().Message }); + + private static void ReportExportLine(string? line) + { + // RvtIO.Cli reports this timing after the reader has returned. + if (line?.StartsWith("Timing: read ", StringComparison.Ordinal) == true) + ReportProgress("encode", 0, 0); + } + + private static void ReportDowngradeLine(string? line) + { + // The CLI writes this line after planning and before it calls DowngradeWriter. + if (line?.StartsWith("Classes in both: ", StringComparison.Ordinal) == true) + ReportProgress("rewrite", 0, 0); + else if (line?.StartsWith("Downgraded: ", StringComparison.Ordinal) == true) + ReportProgress("report", 0, 0); + } + + [JSImport("reportProgress", "operation")] + private static partial void ReportProgress(string phase, + [JSMarshalAs] long completed, [JSMarshalAs] long total); + +#if MODEL_EXPORT + private static string ExportScene(string tool, string[] args) + { + if (args is not [var input, var output]) throw new ArgumentException("Не заданы пути к файлам."); + if (tool == "NwcScene") + { + var nwc = NwcSceneReader.Read(input); + return WriteScene(nwc.Document, nwc.Diagnostics, output); + } + var result = RvtSceneReader.Read(input, new RvtSceneOptions + { + ReadProgress = new InlineProgress(update => + { +#if RVT_PARTITION_SCRATCH + if (update.GeometryBlocks is { } blocks) + ReportProgress("geometry-blocks", blocks.Completed, blocks.Total); + else +#endif + ReportProgress(update.Phase, update.Completed, update.Total); + }), +#if RVT_PARTITION_SCRATCH + MeshProgress = new InlineProgress<(int Completed, int Total)>(update => + ReportProgress("meshes", update.Completed, update.Total)), +#endif + }); + return WriteScene(result.Document, result.Diagnostics, output); + } + + private static string WriteScene(SceneDocument document, IReadOnlyList warnings, string output) + { + var error = warnings.FirstOrDefault(item => item.Severity == SceneSeverity.Error); + if (error is not null) throw new InvalidDataException(error.Message); + if (document.Instances.Count == 0) throw new InvalidDataException("The model has no geometry to export."); + ReportProgress("encode", 0, 0); + using var stream = File.Create(output); + switch (Path.GetExtension(output)) + { + case ".glb": + GlbSceneWriter.Write(document, stream); + break; + case ".obj": + using (var writer = new StreamWriter(stream)) ObjSceneWriter.Write(document, writer); + break; + case ".html": + HtmlViewerExporter.Export(document, stream); + break; + default: + throw new ArgumentException("Неизвестный формат экспорта."); + } + var diagnostics = string.Join("\n", warnings.Take(30).Select(item => item.Message)); + return JsonSerializer.Serialize(new { exitCode = 0, diagnostics, output = "" }); + } + + private sealed class InlineProgress(Action report) : IProgress + { + public void Report(T value) => report(value); + } +#endif + + private sealed class TailWriter(Action? onLine = null) : StringWriter(CultureInfo.InvariantCulture) + { + private const int Limit = 16_384; + + public override void WriteLine(string? value) + { + Write(value); + Write(NewLine); + onLine?.Invoke(value); + } + + public override void Write(char value) + { + base.Write(value); + Trim(); + } + + public override void Write(string? value) + { + base.Write(value is { Length: > Limit } ? value[^Limit..] : value); + Trim(); + } + + public override void Write(ReadOnlySpan value) + { + base.Write(value.Length > Limit ? value[^Limit..] : value); + Trim(); + } + + private void Trim() + { + StringBuilder text = GetStringBuilder(); + if (text.Length > Limit * 2) text.Remove(0, text.Length - Limit); + } + } +} diff --git a/site/operations/compat/BrowserIfcHash.cs b/site/operations/compat/BrowserIfcHash.cs new file mode 100644 index 0000000..66005ec --- /dev/null +++ b/site/operations/compat/BrowserIfcHash.cs @@ -0,0 +1,16 @@ +global using MD5 = BrowserIfcHash; + +using Org.BouncyCastle.Crypto.Digests; + +// IFC export uses this digest for stable IDs, including on browsers without MD5 in the runtime. +internal static class BrowserIfcHash +{ + public static byte[] HashData(byte[] input) + { + var digest = new MD5Digest(); + digest.BlockUpdate(input, 0, input.Length); + var output = new byte[digest.GetDigestSize()]; + digest.DoFinal(output, 0); + return output; + } +} diff --git a/site/operations/compat/BrowserRvt.targets b/site/operations/compat/BrowserRvt.targets new file mode 100644 index 0000000..7d5155c --- /dev/null +++ b/site/operations/compat/BrowserRvt.targets @@ -0,0 +1,8 @@ + + + + + $(NuGetPackageRoot)bouncycastle.cryptography/2.6.2/lib/net6.0/BouncyCastle.Cryptography.dll + + + diff --git a/site/operations/profile-tool/BuildProfiles.csproj b/site/operations/profile-tool/BuildProfiles.csproj new file mode 100644 index 0000000..2f9fcb3 --- /dev/null +++ b/site/operations/profile-tool/BuildProfiles.csproj @@ -0,0 +1,11 @@ + + + net10.0 + Exe + enable + enable + + + + + diff --git a/site/operations/profile-tool/Program.cs b/site/operations/profile-tool/Program.cs new file mode 100644 index 0000000..336cbc6 --- /dev/null +++ b/site/operations/profile-tool/Program.cs @@ -0,0 +1,69 @@ +using System.Reflection; +using System.Text; +using OpenMcdf; + +if (args.Length < 3 || args.Length % 2 != 1) + throw new ArgumentException("Usage: BuildProfiles [...]"); + +Directory.CreateDirectory(args[0]); +var assembly = typeof(RvtIO.RvtFileReader).Assembly; +var reader = assembly.GetType("RvtIO.Parsing.BasicFileInfoReader", throwOnError: true)!; +var read = reader.GetMethod("Read", BindingFlags.Public | BindingFlags.Static)!; +var planner = assembly.GetType("RvtIO.Writing.DowngradePlanner", throwOnError: true)!; +var plan = planner.GetMethod("Plan", BindingFlags.NonPublic | BindingFlags.Static)!; +var rule = Enum.Parse(plan.GetParameters()[2].ParameterType, "Exact"); + +for (int i = 1; i < args.Length; i += 2) +{ + int year = int.Parse(args[i]); + if (year is < 2020 or > 2026) throw new ArgumentException($"Unsupported profile year {year}."); + using var source = RootStorage.OpenRead(args[i + 1]); + var info = (Dictionary)read.Invoke(null, [source])!; + if (info.GetValueOrDefault("RevitVersion") != args[i]) + throw new InvalidDataException($"Input metadata must match Revit {year}."); + if (!info.TryGetValue("Build", out string? build) || string.IsNullOrWhiteSpace(build)) + throw new InvalidDataException($"Input metadata must contain the Revit {year} build."); + + string output = Path.Combine(args[0], $"{year}.rvt"); + string temporary = output + ".tmp"; + try + { + using (var profile = RootStorage.Create(temporary, OpenMcdf.Version.V3)) + { + using (var metadata = profile.CreateStream("BasicFileInfo")) + using (var writer = new BinaryWriter(metadata)) + { + writer.Write(int.Parse(info["StreamVersion"])); + foreach (string value in new[] { args[i], build }) + { + writer.Write(value.Length); + writer.Write(Encoding.Unicode.GetBytes(value)); + } + } + using (var contents = source.OpenStream("Contents")) + using (var target = profile.CreateStream("Contents")) + contents.CopyTo(target); + using (var schema = source.OpenStorage("Formats").OpenStream("Latest")) + using (var target = profile.CreateStorage("Formats").CreateStream("Latest")) + schema.CopyTo(target); + } + // The planner treats this as a source and checks its saved year against the class table. + // Its expected same-year refusal proves the reduced profile passed both container reads. + try + { + plan.Invoke(null, [temporary, args[i + 1], rule, false]); + throw new InvalidDataException($"The Revit {year} profile was not validated."); + } + catch (TargetInvocationException error) when ( + error.InnerException?.GetType().GetProperty("Kind", BindingFlags.Instance | BindingFlags.NonPublic) + ?.GetValue(error.InnerException) as string == "profile-not-older") + { + File.Move(temporary, output, overwrite: true); + } + Console.WriteLine($"Revit {year}: {new FileInfo(output).Length:N0} bytes"); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } +} diff --git a/site/paged-first-frame-smoke.cjs b/site/paged-first-frame-smoke.cjs new file mode 100644 index 0000000..966a3bc --- /dev/null +++ b/site/paged-first-frame-smoke.cjs @@ -0,0 +1,120 @@ +const assert = require('node:assert/strict'); +const { mkdtemp, rm } = require('node:fs/promises'); +const { tmpdir } = require('node:os'); +const { basename, join } = require('node:path'); +const { chromium } = require('playwright'); + +const [url, model, timeoutSeconds = '1800'] = process.argv.slice(2); +const timeout = Number(timeoutSeconds) * 1000; +assert(url && model && Number.isSafeInteger(timeout) && timeout > 0, + 'Usage: node paged-first-frame-smoke.cjs [timeout-seconds]'); + +async function main() { + // A fresh persistent profile gives OPFS its normal quota and starts with an empty model cache. + const directory = await mkdtemp(join(tmpdir(), 'ioextend-paged-')); + let context; + try { + context = await chromium.launchPersistentContext(directory, { + executablePath: process.env.VIEWER_CHROME, + serviceWorkers: 'block', + viewport: { width: 1280, height: 750 }, + args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'], + }); + const page = context.pages()[0]; + const runtimes = []; + const origin = new URL(url).origin; + const externalOrigins = new Set(); + let scene; + let memory; + context.on('request', request => { + const requested = new URL(request.url()); + if (/^https?:$/.test(requested.protocol) && requested.origin !== origin) + externalOrigins.add(requested.origin); + if (/\/dotnet\.native\.[^/]+\.wasm$/.test(requested.pathname)) + runtimes.push(requested.pathname); + }); + page.on('console', message => { + const line = message.text(); + if (line.startsWith('IOExtend scene ')) scene = JSON.parse(line.slice('IOExtend scene '.length)); + if (line.startsWith('IOExtend memory ')) memory = JSON.parse(line.slice('IOExtend memory '.length)); + }); + await page.goto(url); + await page.evaluate(() => { + const status = document.querySelector('#status'); + const oldFrame = document.querySelector('#viewer'); + document.querySelector('#file-input').addEventListener('change', () => { + const started = performance.now(); + const phases = []; + window.pagedSmoke = { phases }; + const phaseObserver = new MutationObserver(() => { + const label = status.textContent.split(' · ', 1)[0]; + if (label && label !== phases.at(-1)?.label) + phases.push({ label, atMs: Math.round(performance.now() - started) }); + }); + phaseObserver.observe(status, { childList: true, subtree: true }); + const frameObserver = new MutationObserver(() => { + const frame = document.querySelector('#viewer'); + if (!frame || frame === oldFrame || frame.inert || !frame.checkVisibility({ opacityProperty: true })) return; + frameObserver.disconnect(); + requestAnimationFrame(() => requestAnimationFrame(() => { + if (frame.isConnected && !document.hidden && frame.checkVisibility({ opacityProperty: true })) { + window.pagedSmoke.firstFrameMs = Math.round(performance.now() - started); + phaseObserver.disconnect(); + } + })); + }); + frameObserver.observe(oldFrame.parentNode, { childList: true }); + setTimeout(() => { + if (!window.pagedSmoke.firstFrameMs) + window.pagedSmoke.atTwoMinutes = status.textContent.split(' · ').slice(0, -1).join(' · '); + }, 120_000); + }, { capture: true, once: true }); + }); + await page.locator('#file-input').setInputFiles(model); + const selected = page.locator('#model-name').getByText(basename(model), { exact: true }); + const error = page.locator('#status[data-error]'); + try { + await selected.or(error).waitFor({ timeout }); + assert(await selected.isVisible(), await page.locator('#status').textContent()); + await page.waitForFunction(() => window.pagedSmoke.firstFrameMs > 0); + } catch (failure) { + const status = await page.locator('#status').textContent(); + console.error(JSON.stringify({ status, memory, runtimes })); + throw failure; + } + const frame = await (await page.locator('#viewer').elementHandle()).contentFrame(); + const render = await frame.evaluate(async () => { + const view = window.__ioviewerMeshLod; + if (!view) throw new Error('Expected the paged viewer.'); + const { manifest } = view; + const propertyIndex = manifest.elements.findIndex(element => element.size > 0); + const response = await window.IOVIEWER_MESH_SOURCE.fetch('/elements/' + propertyIndex); + const element = await response.json(); + const { draws, triangles } = view.stats(); + return { + elements: manifest.elements.length, pages: manifest.pages.length, draws, triangles, + propertyRead: response.ok && element.id === manifest.elements[propertyIndex]?.id + && Object.keys(element.properties ?? {}).length > 0, + }; + }); + assert.equal(externalOrigins.size, 0, 'The viewer contacted an external origin.'); + assert(runtimes.length === 1 && !runtimes[0].includes('/fast-reader/'), 'Expected a single paged reader.'); + assert.equal(scene?.errors, 0); + assert.equal(render.elements, scene.elements); + assert(render.pages > 0 && render.draws > 0 && render.triangles > 0 && render.propertyRead); + assert(await frame.locator('#ioviewer-message').isHidden()); + const timing = await page.evaluate(() => window.pagedSmoke); + console.log(JSON.stringify({ ...timing, scene, render, memory })); + } finally { + try { + await context?.close(); + } finally { + await rm(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + } +} + +main().catch(error => { + console.error(error); + process.exitCode = 1; +}); diff --git a/site/paged-frame.js b/site/paged-frame.js new file mode 100644 index 0000000..a9077c7 --- /dev/null +++ b/site/paged-frame.js @@ -0,0 +1,38 @@ +import { openMeshPackage } from './src/stream/meshSource.js'; + +window.addEventListener('dragover', event => { + if (!event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + event.dataTransfer.dropEffect = 'copy'; +}); +window.addEventListener('drop', event => { + if (!event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + parent.postMessage({ type: 'ioviewer-drop', files: Array.from(event.dataTransfer.files) }, '*'); +}); + +const files = await new Promise(resolve => { + function receive(event) { + if (event.source !== parent || event.data?.type !== 'ioviewer-pages') return; + window.removeEventListener('message', receive); + resolve(event.data.files); + } + window.addEventListener('message', receive); + parent.postMessage({ type: 'ioviewer-page-request' }, '*'); +}); + +try { + globalThis.IOVIEWER_MESH_SOURCE = await openMeshPackage(name => files[name]); + await import('./src/stream/meshLod.js'); + const view = globalThis.__ioviewerMeshLod; + if (!view) throw new Error(document.querySelector('#ioviewer-message').textContent || 'WebGL недоступен.'); + await view.ready; + while (view.stats().triangles === 0) { + const message = document.querySelector('#ioviewer-message'); + if (!message.hidden) throw new Error(message.textContent); + await new Promise(resolve => requestAnimationFrame(resolve)); + } + parent.postMessage({ type: 'ioviewer-page-ready' }, '*'); +} catch (error) { + parent.postMessage({ type: 'ioviewer-page-error', error: error.message }, '*'); +} diff --git a/site/parallel/.gitattributes b/site/parallel/.gitattributes new file mode 100644 index 0000000..23c47b5 --- /dev/null +++ b/site/parallel/.gitattributes @@ -0,0 +1,2 @@ +# Unified diffs represent an empty context line with one space. +rvtio-browser.patch text eol=lf whitespace=-blank-at-eol diff --git a/site/parallel/BrowserDecoders.cs b/site/parallel/BrowserDecoders.cs new file mode 100644 index 0000000..9654ecb --- /dev/null +++ b/site/parallel/BrowserDecoders.cs @@ -0,0 +1,89 @@ +#if PARALLEL_RVT_READER +using System.Runtime.InteropServices.JavaScript; +using RvtIO; + +internal static partial class Program +{ + [JSExport] + internal static void EnableBrowserPartitionInflate() => RvtFileReader.BrowserInflatePartitionMembers = InflatePartitionMembers; + + [JSImport("inflatePartitionMembers", "viewer")] + private static partial byte[] InflatePartitionMembers(byte[] input); + + [JSExport] + internal static void SetNameScanner() + { + RvtFileReader.BrowserBeginNameScan = BeginNameScan; + RvtFileReader.BrowserSendNameChunk = SendNameChunk; + RvtFileReader.BrowserSealNameScan = SealNameScan; + RvtFileReader.BrowserCollectNameScan = CollectNameScan; + } + + [JSImport("beginNameScan", "viewer")] + private static partial bool BeginNameScan(byte[] ids, string culture); + + [JSImport("sendNameChunk", "viewer")] + private static partial void SendNameChunk(int index, byte[] bytes); + + [JSImport("sealNameScan", "viewer")] + private static partial void SealNameScan(); + + [JSImport("collectNameScan", "viewer")] + private static partial byte[] CollectNameScan(); + + [JSExport] + internal static void StartWorkerNames(byte[] ids, string culture) => RvtFileReader.BeginBrowserNameScan(ids, culture); + + [JSExport] + internal static void ScanWorkerNames(int index, byte[] bytes) => RvtFileReader.ScanBrowserNameChunk(index, bytes); + + [JSExport] + internal static byte[] FinishWorkerNames() => RvtFileReader.FinishBrowserNameScan(); + + [JSExport] + internal static void SetParameterWorkers() + { + RvtFileReader.BrowserDecodeParameterBatches = DecodeParameterBatches; + RvtFileReader.BrowserDecodeGeometryBatches = DecodeGeometryBatches; + RvtFileReader.BrowserCollectDecoder = CollectDecoderBatch; + RvtFileReader.BrowserStartInitialGeo = StartDecoderBatch; + RvtFileReader.BrowserStartDeferredParams = StartDecoderBatch; + RvtFileReader.BrowserStartGeometryPipeline = StartDecoderBatch; + } + + [JSImport("startDecoderBatch", "viewer")] + private static partial void StartDecoderBatch(int channel, byte[] first, byte[] second, byte[] third, byte[] fourth); + + [JSImport("collectDecoderBatch", "viewer")] + private static partial byte[] CollectDecoderBatch(int channel); + + [JSExport] + internal static byte[] DecodeGeometryBatch(byte[] input) => RvtFileReader.DecodeBrowserGeometryBatch(input); + + [JSExport] + internal static void EnableBrowserR22Ranges() => RvtFileReader.BrowserRewriteR22Ranges = RewriteR22Ranges; + + [JSExport] + internal static void BeginBrowserR22RangeWorker(byte[] schema, int width, bool trackIds) => + RvtFileReader.BeginBrowserR22RangeWorker(schema, width, trackIds); + + [JSExport] + internal static byte[] DecodeBrowserR22Range(byte[] input, byte[] plan) => + RvtFileReader.DecodeBrowserR22Range(input, plan); + + [JSExport] + internal static void EndBrowserR22RangeWorker() => RvtFileReader.EndBrowserR22RangeWorker(); + + [JSImport("rewriteR22Ranges", "viewer")] + private static partial byte[] RewriteR22Ranges(byte[] schema, int width, bool trackIds, byte[] input, byte[] plan); + + [JSImport("decodeGeometryBatches", "viewer")] + private static partial byte[] DecodeGeometryBatches(byte[] first, byte[] second, byte[] third, byte[] fourth); + + [JSExport] + internal static byte[] DecodeParameterBatch(byte[] input) => RvtFileReader.DecodeBrowserParameterBatch(input); + + [JSImport("decodeParameterBatches", "viewer")] + private static partial byte[] DecodeParameterBatches(byte[] first, byte[] second, byte[] third, byte[] fourth); +} +#endif diff --git a/site/parallel/reader-decoders.js b/site/parallel/reader-decoders.js new file mode 100644 index 0000000..3dbadcc --- /dev/null +++ b/site/parallel/reader-decoders.js @@ -0,0 +1,667 @@ +const shardCapacity = 16 * 1024 * 1024; +const namesCapacity = 4 * 1024 * 1024; +const initialGeometryBatchBytes = 128 * 1024; + +function createParameterWorker(role, wasmBlob) { + const worker = new Worker(new URL('./reader.js', import.meta.url), { type: 'module' }); + worker.parameterPriority = new Int32Array(new SharedArrayBuffer(4)); + worker.startup = new Promise((resolve, reject) => { + worker.onmessage = ({ data }) => (data.ready ? resolve() : reject(new Error(data.error))); + worker.onerror = (event) => reject(new Error(event.message)); + }); + worker.postMessage({ parameterWorker: true, role }); + wasmBlob + .then((blob) => worker.postMessage({ wasmBlob: blob })) + .catch((error) => { + console.warn('IOExtend WASM transfer failed.', error); + worker.postMessage({ wasmBlob: null }); + }); + return worker; +} + +async function startParameterWorker(dotnet, role) { + try { + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_GEOMETRY_RESULT_24', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_DIRECT_TRIM', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_GREP_EXACT_SOURCES', '1'); + const { getAssemblyExports, getConfig, localHeapViewU8 } = await dotnet.create(); + const { Program } = await getAssemblyExports(getConfig().mainAssemblyName); + if (role === 'names') { + let status, + output, + failed = false; + self.onmessage = ({ data: { kind, mailbox, input, index, culture } }) => { + if (failed) return; + try { + if (kind === 'begin') { + status = new Int32Array(mailbox, 0, 2); + output = new Uint8Array(mailbox, 8); + Program.StartWorkerNames(input, culture); + } else if (kind === 'chunk') Program.ScanWorkerNames(index, input); + else if (kind === 'finish') { + const encoded = Program.FinishWorkerNames(); + if (encoded.length > output.length) throw new Error('Name scan exceeds mailbox capacity.'); + output.set(encoded); + Atomics.store(status, 1, localHeapViewU8().byteLength); + Atomics.store(status, 0, encoded.length + 1); + Atomics.notify(status, 0, 1); + } + } catch (error) { + failed = true; + console.warn('IOExtend name worker', error); + Atomics.store(status, 0, -1); + Atomics.notify(status, 0, 1); + } + }; + self.postMessage({ ready: true }); + return; + } + self.onmessage = async ({ + data: { + parameterPriority, + queuedParameters, + input, + mailbox, + geometry, + yieldDecode, + work, + arena, + transcode, + inflate, + }, + }) => { + const status = new Int32Array(mailbox, 0, 2); + const output = new Uint8Array(mailbox, 8); + try { + let length = 0; + let omittedBytes = 0; + function append(encoded) { + if (arena) { + const stored = appendGeometryResults(arena, encoded); + length += stored; + omittedBytes += encoded.length - stored; + return; + } + if (encoded.length > output.length - length) throw new Error('Worker shard exceeds mailbox capacity.'); + output.set(encoded, length); + length += encoded.length; + } + function decodeGeometry(input) { + append(Program.DecodeGeometryBatch(input)); + } + if (inflate) { + const { source, jobs, claim, output } = inflate; + for (let i = Atomics.add(claim, 0, 1); i < jobs.length; i = Atomics.add(claim, 0, 1)) { + await inflatePartitionMember(source, jobs[i], output); + length += jobs[i].outputEnd - jobs[i].outputStart; + } + } else if (transcode) { + const { schema, width, trackIds, source, plan, jobs, claim, result } = transcode; + Program.BeginBrowserR22RangeWorker(schema, width, trackIds); + try { + for (let i = Atomics.add(claim, 0, 1); i < jobs.length; i = Atomics.add(claim, 0, 1)) { + const job = jobs[i]; + const encoded = Program.DecodeBrowserR22Range( + source.subarray(job.start, job.end), + plan.subarray(job.first, job.last) + ); + if (encoded.length === 0) throw new Error('R22 range needs sequential element IDs.'); + const at = Atomics.add(result.cursor, 0, encoded.length + 8); + if (encoded.length + 8 > result.data.length - at) + throw new Error('R22 range output exceeds capacity.'); + const header = new DataView(result.data.buffer, result.data.byteOffset + at, 8); + header.setUint32(0, i, true); + header.setUint32(4, encoded.length, true); + result.data.set(encoded, at + 8); + length += encoded.length + 8; + } + } finally { + Program.EndBrowserR22RangeWorker(); + } + } else if (work) { + for (;;) { + const i = Atomics.add(work.next, 0, 1); + if (i + 1 >= work.ends.length) break; + decodeGeometry(work.input.subarray(work.ends[i], work.ends[i + 1])); + } + } else if (yieldDecode) { + let yields = 0; + const view = new DataView(input.buffer, input.byteOffset, input.byteLength); + let begin = 0; + for (let end = 0; end < input.length; ) { + if (end + 8 > input.length) throw new Error('Incomplete GRep frame.'); + end += 24 + view.getUint32(end + 4, true); + if (end > input.length) throw new Error('Incomplete GRep block.'); + if (end - begin < initialGeometryBatchBytes && end !== input.length) continue; + for (let pending; (pending = Atomics.load(parameterPriority, 0)) > 0; ) { + yields++; + const turn = pendingParameterTurn(parameterPriority, pending); + if (turn) await turn; + } + decodeGeometry(input.subarray(begin, end)); + begin = end; + } + console.debug('IOExtend parameter priority yields', yields); + } else if (geometry) decodeGeometry(input); + else append(Program.DecodeParameterBatch(input)); + if (omittedBytes) console.debug('IOExtend geometry arena deferred bytes', omittedBytes); + Atomics.store(status, 1, localHeapViewU8().byteLength); + Atomics.store(status, 0, length + 1); + } catch (error) { + console.warn('IOExtend decoder worker', error); + Atomics.store(status, 0, -1); + } finally { + if (queuedParameters) releaseParameterPriority(parameterPriority); + Atomics.notify(status, 0, 1); + } + }; + self.postMessage({ ready: true }); + } catch (error) { + self.postMessage({ error: String(error) }); + } +} + +function decoderMailboxes(pool, capacity) { + return pool.map((worker) => { + const mailbox = new SharedArrayBuffer(8 + capacity); + return { worker, mailbox, status: new Int32Array(mailbox, 0, 2), data: new Uint8Array(mailbox, 8) }; + }); +} + +function appendGeometryResults(arena, encoded) { + const cursor = new Int32Array(arena, 0, 1); + const output = new Uint8Array(arena, 4); + function append(bytes) { + let begin = Atomics.load(cursor, 0); + while (bytes.length <= output.length - begin) { + const previous = Atomics.compareExchange(cursor, 0, begin, begin + bytes.length); + if (previous === begin) { + output.set(bytes, begin); + return bytes.length; + } + begin = previous; + } + return 0; + } + + if (append(encoded) === encoded.length) return encoded.length; + + // Preserve complete records. The original decoder applies them by index and replays missing ones. + const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength); + let retained = 0; + for (let offset = 0; offset < encoded.length; ) { + if (offset + 8 > encoded.length) throw new Error('Incomplete geometry result header.'); + const length = view.getInt32(offset + 4, true); + const end = offset + 8 + Math.max(0, length); + if (length < -1 || end > encoded.length) throw new Error('Invalid geometry result length.'); + retained += append(encoded.subarray(offset, end)); + offset = end; + } + return retained; +} + +function recoveryWork(inputs) { + const length = inputs.reduce((sum, data) => sum + data.length, 0); + const target = Math.max(32 * 1024, Math.ceil(length / 12)); + const input = new Uint8Array(new SharedArrayBuffer(length)); + const ends = [0]; + let start = 0; + for (const data of inputs) { + input.set(data, start); + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + for (let offset = 0; offset < data.length; ) { + if (offset + 24 > data.length) throw new Error('Incomplete geometry frame header.'); + offset += 24 + view.getUint32(offset + 4, true); + if (offset > data.length) throw new Error('Incomplete geometry frame payload.'); + if (start + offset - ends[ends.length - 1] >= target) ends.push(start + offset); + } + start += data.length; + } + if (ends[ends.length - 1] < length) ends.push(length); + return { next: new Int32Array(new SharedArrayBuffer(4)), input, ends }; +} + +const inflateBudget = 32 * 1024 * 1024; + +function planPartitionInflation(input) { + if (input.length < 4 || input.length > inflateBudget) throw new Error('Invalid partition gzip packet.'); + const view = new DataView(input.buffer, input.byteOffset, input.byteLength); + const count = view.getUint32(0, true); + if (count < 2 || count > 128 || 4 + 4 * count > input.length) throw new Error('Invalid gzip member count.'); + const jobs = []; + let start = 4 + 4 * count, + outputStart = 0; + for (let i = 0; i < count; i++) { + const length = view.getUint32(4 + 4 * i, true); + const end = start + length; + if (length < 18 || end > input.length) throw new Error('Invalid gzip member bounds.'); + const outputEnd = outputStart + view.getUint32(end - 4, true); + if (outputEnd > inflateBudget) throw new Error('Partition gzip output exceeds the batch budget.'); + jobs.push({ start, end, outputStart, outputEnd }); + start = end; + outputStart = outputEnd; + } + if (start !== input.length || outputStart === 0) throw new Error('Invalid partition gzip packet length.'); + return { jobs, outputLength: outputStart }; +} + +async function inflatePartitionMember(source, job, output) { + let position = job.start; + const input = new ReadableStream({ + pull(controller) { + if (position === job.end) { + controller.close(); + return; + } + const next = Math.min(position + 8 * 1024, job.end); + controller.enqueue(source.slice(position, next)); + position = next; + }, + }); + const reader = input.pipeThrough(new DecompressionStream('gzip')).getReader(); + let offset = job.outputStart; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (value.length > job.outputEnd - offset) { + await reader.cancel(); + throw new Error('Partition gzip member exceeds its declared length.'); + } + output.set(value, offset); + offset += value.length; + } + } finally { + reader.releaseLock(); + } + if (offset !== job.outputEnd) throw new Error('Partition gzip member length differs.'); +} + +function indexR22Jobs(sourceLength, plan) { + const view = new DataView(plan.buffer, plan.byteOffset, plan.byteLength); + if (plan.length < 4) throw new Error('Missing R22 range count.'); + const count = view.getUint32(0, true); + if (!count || count > (plan.length - 4) / 24) throw new Error('Invalid R22 range count.'); + const jobs = []; + let previousEnd = 0, + at = 4; + for (let i = 0; i < count; i++) { + if (plan.length - at < 12) throw new Error('Incomplete R22 range header.'); + const start = view.getUint32(at, true); + const length = view.getUint32(at + 4, true); + const items = view.getUint32(at + 8, true); + const first = at + 12; + const end = start + length, + last = first + 12 * items; + if (!length || !items || start !== previousEnd || end > sourceLength || last > plan.length) + throw new Error('Invalid R22 range boundary.'); + jobs.push({ start, end, first, last }); + previousEnd = end; + at = last; + } + if (at !== plan.length) throw new Error('Unexpected R22 range data.'); + return jobs; +} + +function dispatchRecoveryBatch(mailboxes, work, arena) { + for (const { status, worker, mailbox } of mailboxes) { + Atomics.store(status, 0, work.ends.length > 1 ? 0 : 1); + if (work.ends.length > 1) worker.postMessage({ mailbox, work, arena }); + } +} + +function pendingParameterTurn(priority, pending) { + if (typeof Atomics.waitAsync !== 'function') return new Promise((resolve) => setTimeout(resolve, 0)); + const waiting = Atomics.waitAsync(priority, 0, pending); + return waiting.async ? waiting.value : undefined; +} + +function releaseParameterPriority(priority) { + if (Atomics.sub(priority, 0, 1) === 1) Atomics.notify(priority, 0, 1); +} + +function postDecoderShard(worker, message) { + const parameterPriority = worker.parameterPriority; + const queuedParameters = !message.geometry; + if (queuedParameters) Atomics.add(parameterPriority, 0, 1); + try { + worker.postMessage({ ...message, parameterPriority, queuedParameters }); + } catch (error) { + if (queuedParameters) releaseParameterPriority(parameterPriority); + throw error; + } +} + +function dispatchBatch(mailboxes, inputs, geometry, yieldDecode, arena) { + for (let i = 0; i < mailboxes.length; i++) { + const { status, worker, mailbox } = mailboxes[i]; + Atomics.store(status, 0, inputs[i].length ? 0 : 1); + if (inputs[i].length) postDecoderShard(worker, { input: inputs[i], mailbox, geometry, yieldDecode, arena }); + } +} + +function waitBatch(mailboxes, deadline = performance.now() + 20_000) { + const sizes = []; + let timedOut = false; + for (const { status } of mailboxes) { + const waited = Atomics.wait(status, 0, 0, Math.max(0, deadline - performance.now())); + timedOut ||= waited === 'timed-out'; + sizes.push(Atomics.load(status, 0) - 1); + } + if (timedOut || sizes.some((size) => size < 0)) { + console.warn('IOExtend decoder batch will replay locally', sizes); + if (timedOut) mailboxes.forEach(({ worker }) => worker.terminate()); + return { sizes: null, mailboxes, length: 4, timedOut }; + } + return { sizes, mailboxes, length: sizes.reduce((total, size) => total + size + 4, 0), timedOut }; +} + +function writeBatch(batch, destination) { + const { sizes, mailboxes, length } = batch; + if (destination.length !== length) throw new Error('Decoder output length changed.'); + const header = new Uint8Array(4); + const view = new DataView(header.buffer); + if (batch.arena) { + view.setInt32(0, batch.arena.length, true); + destination.set(header, 0); + destination.set(batch.arena, 4); + view.setInt32(0, 0, true); + for (let offset = batch.arena.length + 4; offset < destination.length; offset += 4) + destination.set(header, offset); + return; + } + if (!sizes) { + view.setInt32(0, -1, true); + destination.set(header, 0); + return; + } + let pos = 0; + for (let i = 0; i < mailboxes.length; i++) { + const size = sizes[i]; + view.setInt32(0, size, true); + destination.set(header, pos); + pos += 4; + destination.set(mailboxes[i].data.subarray(0, size), pos); + pos += size; + } +} + +export function startDecoder(dotnet, { role }) { + { + const binary = new Promise((resolve, reject) => { + self.onmessage = ({ data: { wasmBlob } }) => + wasmBlob instanceof Blob ? resolve(wasmBlob) : reject(new Error('Missing worker runtime binary.')); + }); + dotnet.withResourceLoader((type) => + type === 'dotnetwasm' + ? binary.then((blob) => new Response(blob, { headers: { 'Content-Type': 'application/wasm' } })) + : null + ); + } + return startParameterWorker(dotnet, role); +} + +export function createDecoders(dotnet) { + let localHeapViewU8; + const parameterPool = []; + let wasmBlob, nameWorker, nameReady, nameStatus, nameOutput; + let parameterPoolDisabled = false; + let retiredDecoders; + const channels = new Map(); + const geometryArenas = new Map(); + const busyChannels = new Set(); + function start(channel, inputs) { + const yieldDecode = channel === 2; + const recovery = channel === 1 || channel === 3; + if (channel === 2) channel = 3; + if (parameterPoolDisabled || retiredDecoders) return; + if (busyChannels.has(channel)) throw new Error('Decoder channel already in use.'); + const parameters = channel === 0 || channel === 4; + let mailboxes = channels.get(channel); + if (!mailboxes) { + const capacity = shardCapacity; + if (!parameters) geometryArenas.set(channel, new SharedArrayBuffer(4 + capacity * parameterPool.length)); + channels.set( + channel, + (mailboxes = decoderMailboxes(parameterPool, geometryArenas.has(channel) ? 0 : capacity)) + ); + } + const arena = geometryArenas.get(channel); + if (arena) Atomics.store(new Int32Array(arena, 0, 1), 0, 0); + if (recovery) { + dispatchRecoveryBatch(mailboxes, recoveryWork(inputs), arena); + } else dispatchBatch(mailboxes, inputs, !parameters, yieldDecode, arena); + busyChannels.add(channel); + } + function getReadyBatch(channel) { + if (channel === 2) channel = 3; + const mailboxes = channels.get(channel); + if (!busyChannels.delete(channel)) return { sizes: null, length: 4 }; + const batch = waitBatch(mailboxes); + const parameters = channel === 0 || channel === 4; + if (!parameters && batch.sizes) { + const arena = geometryArenas.get(channel); + if (arena) { + const length = Atomics.load(new Int32Array(arena, 0, 1), 0); + if (batch.length !== length + 16) throw new Error('Geometry arena length differs.'); + batch.arena = new Uint8Array(arena, 4, length); + } + } + if (batch.timedOut) { + parameterPoolDisabled = true; + busyChannels.clear(); + } + return batch; + } + function collect(channel) { + const batch = getReadyBatch(channel); + const result = new Uint8Array(batch.length); + writeBatch(batch, result); + return result; + } + function decoderMailboxBytes() { + let bytes = 0; + for (const mailboxes of channels.values()) for (const { data } of mailboxes) bytes += data.byteLength; + for (const arena of geometryArenas.values()) bytes += arena.byteLength - 4; + return bytes; + } + function retireIdleDecoders() { + if (!parameterPool.length || parameterPoolDisabled || busyChannels.size) return; + retiredDecoders = { workers: parameterPool.length, mailboxBytes: decoderMailboxBytes() }; + for (const worker of parameterPool) worker.terminate(); + parameterPool.length = 0; + channels.clear(); + geometryArenas.clear(); + console.debug('IOExtend retired decoders', JSON.stringify(retiredDecoders)); + } + let share, fail; + wasmBlob = new Promise((resolve, reject) => { + share = resolve; + fail = reject; + }); + dotnet.withResourceLoader((type, name, url, integrity) => { + if (type !== 'dotnetwasm') return null; + const download = fetch(url, { integrity }).then((response) => { + if (!response.ok) throw new Error('WASM download failed: ' + response.status); + response.clone().blob().then(share, fail); + return response; + }); + download.catch(fail); + return download; + }); + for (let i = 0; i < 4; i++) parameterPool.push(createParameterWorker(undefined, wasmBlob)); + nameWorker = createParameterWorker('names', wasmBlob); + if (nameWorker) { + nameReady = nameWorker.startup.then( + () => true, + (error) => { + console.warn('IOExtend name worker startup', error); + return false; + } + ); + } + + const workersReady = Promise.allSettled( + parameterPool.map(async (worker, index) => { + try { + await worker.startup; + } catch (error) { + console.warn('IOExtend retrying parameter worker startup', index, error); + worker.terminate(); + const replacement = createParameterWorker(undefined, wasmBlob); + parameterPool[index] = replacement; + await replacement.startup; + } + }) + ).then((outcomes) => { + const failure = outcomes.find((result) => result.status === 'rejected'); + if (failure) console.warn('IOExtend parameter worker setup failed', failure.reason); + return outcomes.length > 0 && !failure; + }); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_COPY_CONTROL', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_GUID_SEARCH', '2'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_RECOVERY_BATCH_MIB', '4'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_DIRECT_TRIM', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_SKIP_RESOLVED_PARAMETERS', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_CAPTIONS_DURING_GEOMETRY', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_FUSED_PLACEMENT_BOUNDS', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_REUSE_CONTAINED_PLACEMENT', '1'); + dotnet.withEnvironmentVariable('IOEXTEND_PROBE_DEFER_PLACED_FACES', '1'); + function sendNameMessage(kind, input, fields) { + if ( + !(input.buffer instanceof ArrayBuffer) || + input.buffer === localHeapViewU8().buffer || + input.byteOffset !== 0 || + input.byteLength !== input.buffer.byteLength + ) + input = input.slice(); + nameWorker.postMessage({ kind, input, ...fields }, [input.buffer]); + } + + const imports = { + inflatePartitionMembers(input) { + if (parameterPoolDisabled || retiredDecoders) return new Uint8Array(); + const started = performance.now(); + try { + const { jobs, outputLength } = planPartitionInflation(input); + const source = new Uint8Array(new SharedArrayBuffer(input.length)); + source.set(input); + const output = new Uint8Array(new SharedArrayBuffer(outputLength)); + const claim = new Int32Array(new SharedArrayBuffer(4)); + const workers = decoderMailboxes(parameterPool, 0); + const inflate = { source, output, claim, jobs }; + for (const { worker, mailbox } of workers) worker.postMessage({ mailbox, inflate }); + const batch = waitBatch(workers); + if (batch.timedOut) parameterPoolDisabled = true; + if (!batch.sizes || batch.length !== outputLength + workers.length * 4) { + console.warn('IOExtend browser inflate fallback'); + return new Uint8Array(); + } + const result = output.slice(); + console.debug( + 'IOExtend browser inflate', + jobs.length, + input.length, + result.length, + Math.round(performance.now() - started) + ); + return result; + } catch (error) { + console.warn('IOExtend browser inflate fallback', String(error)); + return new Uint8Array(); + } + }, + rewriteR22Ranges(schema, width, trackIds, input, plan) { + if (parameterPoolDisabled || retiredDecoders) return new Uint8Array(); + const started = performance.now(); + const jobs = indexR22Jobs(input.length, plan); + const source = new Uint8Array(new SharedArrayBuffer(input.length)); + source.set(input); + const schemaData = new Uint8Array(new SharedArrayBuffer(schema.length)); + schemaData.set(schema); + const sharedPlan = new Uint8Array(new SharedArrayBuffer(plan.length)); + sharedPlan.set(plan); + const capacity = Math.min(192 * 1024 * 1024, 2 * input.length); + const arena = new SharedArrayBuffer(4 + capacity); + const result = { cursor: new Int32Array(arena, 0, 1), data: new Uint8Array(arena, 4) }; + const claim = new Int32Array(new SharedArrayBuffer(4)); + const workers = decoderMailboxes(parameterPool, 0); + const transcode = { schema: schemaData, width, trackIds, source, plan: sharedPlan, jobs, claim, result }; + for (const { worker, mailbox } of workers) worker.postMessage({ mailbox, transcode }); + const batch = waitBatch(workers); + if (batch.timedOut) parameterPoolDisabled = true; + if (!batch.sizes) return new Uint8Array(); + const length = Atomics.load(result.cursor, 0); + if (length > capacity || length !== batch.length - workers.length * 4) return new Uint8Array(); + console.debug( + 'IOExtend R22 browser ranges', + jobs.length, + input.length, + length, + Math.round(performance.now() - started) + ); + return result.data.slice(0, length); + }, + beginNameScan(ids, culture) { + const mailbox = new SharedArrayBuffer(8 + namesCapacity); + nameStatus = new Int32Array(mailbox, 0, 2); + nameOutput = new Uint8Array(mailbox, 8); + sendNameMessage('begin', ids, { mailbox, culture }); + return true; + }, + sendNameChunk(index, input) { + sendNameMessage('chunk', input, { index }); + }, + sealNameScan() { + nameWorker.postMessage({ kind: 'finish' }); + }, + collectNameScan() { + const start = performance.now(); + const waited = Atomics.wait(nameStatus, 0, 0, 15_000); + const code = Atomics.load(nameStatus, 0); + const buffer = waited === 'timed-out' || code <= 0 ? new Uint8Array() : nameOutput.slice(0, code - 1); + console.debug( + 'IOExtend name wait', + performance.now() - start, + buffer.length, + Atomics.load(nameStatus, 1), + namesCapacity + ); + nameWorker.terminate(); + nameWorker = nameStatus = nameOutput = undefined; + return buffer; + }, + startDecoderBatch(channel, ...inputs) { + start(channel, inputs); + }, + collectDecoderBatch(channel) { + return collect(channel); + }, + decodeGeometryBatches(...inputs) { + const started = performance.now(); + start(1, inputs); + const result = collect(1); + console.debug('IOExtend geometry mailbox', performance.now() - started, result.length); + return result; + }, + decodeParameterBatches(...inputs) { + if (parameterPoolDisabled || retiredDecoders) return new Uint8Array([255, 255, 255, 255]); + start(0, inputs); + return collect(0); + }, + }; + async function connect(Program, heapView) { + localHeapViewU8 = heapView; + if (await workersReady) { + Program.SetParameterWorkers(); + Program.EnableBrowserR22Ranges(); + if (typeof DecompressionStream === 'function') Program.EnableBrowserPartitionInflate(); + } + if (await nameReady) Program.SetNameScanner(); + } + function close() { + nameWorker?.terminate(); + for (const worker of parameterPool) worker.terminate(); + } + return { imports, connect, retireIdleDecoders, close }; +} diff --git a/site/parallel/rvtio-browser.patch b/site/parallel/rvtio-browser.patch new file mode 100644 index 0000000..a1c3fff --- /dev/null +++ b/site/parallel/rvtio-browser.patch @@ -0,0 +1,4969 @@ +--- a/src/RvtIO/Geometry/Meshing/GeTess.cs ++++ b/src/RvtIO/Geometry/Meshing/GeTess.cs +@@ -6,6 +6,40 @@ + internal const double RendererTolerance = -1e-10; + + private const double Infinity = 1e300; ++ private static readonly bool FastProfile = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_TESS_CONTROL") != "1"; ++ ++ internal static readonly bool UseDirectTriangle = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_DIRECT_SCENE_TRIANGLES") == "1"; ++ ++ /// A triangle that passes the existing first orientation check without removing a vertex keeps its head. ++ internal static bool TryUnmodifiedTriangle((double X, double Y) a, (double X, double Y) b, ++ (double X, double Y) c, out bool clockwise) ++ { ++ clockwise = false; ++ double area = ((a.Y * b.X - b.Y * a.X) + (b.Y * c.X - c.Y * b.X) ++ + (c.Y * a.X - a.Y * c.X)) * 0.5; ++ if (!double.IsFinite(area)) return false; ++ ++ double sumX = Math.Abs(a.X) + Math.Abs(b.X) + Math.Abs(c.X); ++ double sumY = Math.Abs(a.Y) + Math.Abs(b.Y) + Math.Abs(c.Y); ++ double maxX = Math.Max(Math.Max(Math.Abs(a.X), Math.Abs(b.X)), Math.Abs(c.X)); ++ double maxY = Math.Max(Math.Max(Math.Abs(a.Y), Math.Abs(b.Y)), Math.Abs(c.Y)); ++ double max = Math.Max(maxX, maxY); ++ double otherAxisSum = max == maxX ? sumY : sumX; ++ double areaTolerance = Math.Max((max + max) * (otherAxisSum * 2.220446049250313e-16), ++ (sumY + sumX) * RendererTolerance); ++ if (!(Math.Abs(area) > areaTolerance)) return false; ++ ++ double spanX = Math.Max(Math.Max(a.X, b.X), c.X) - Math.Min(Math.Min(a.X, b.X), c.X); ++ double spanY = Math.Max(Math.Max(a.Y, b.Y), c.Y) - Math.Min(Math.Min(a.Y, b.Y), c.Y); ++ double extent = Hypot(spanX, spanY); ++ if (!double.IsFinite(extent)) return false; ++ double tolerance = Math.Min(-RendererTolerance, extent * 1e-9); ++ if (!(Hypot(a.X - b.X, a.Y - b.Y) > tolerance && Hypot(b.X - c.X, b.Y - c.Y) > tolerance ++ && Hypot(c.X - a.X, c.Y - a.Y) > tolerance)) return false; ++ clockwise = area > 0; ++ return true; ++ } + + private sealed class Vtx + { +@@ -567,16 +601,21 @@ + } + var pieces = new List(); + if (root == null) return pieces; ++ Decompose(root, tolArg); ++ for (var c = root; c != null; c = c.Next) ++ { ++ if ((c.Flag & flagMask) != 0) ok = false; ++ var vs = c.Verts(); ++ if (vs.Count >= 3) pieces.Add(vs.Select(v => v.Idx).ToArray()); ++ } ++ return pieces; ++ } ++ ++ private static void Decompose(Contour root, double tolArg) ++ { + double maxc = CalcMaxCoord(root); + root.Tol = tolArg >= 0.0 ? (tolArg <= 0.0 ? 1e-9 : tolArg) * maxc : Math.Min(-tolArg, maxc * 1e-9); + if (Normalize(root, maxc, tolArg)) BreakToConvex2(root, maxc); +- for (var c = root; c != null; c = c.Next) +- { +- if ((c.Flag & flagMask) != 0) ok = false; +- var vs = c.Verts(); +- if (vs.Count >= 3) pieces.Add(vs.Select(v => v.Idx).ToArray()); +- } +- return pieces; + } + + internal static double SignedArea(IReadOnlyList<(double X, double Y)> poly) +@@ -653,6 +692,30 @@ + internal static List<(int A, int B, int C)> TriangulateProfile(IReadOnlyList<(double X, double Y)> pts, + IReadOnlyList loops, bool[]? outerFlags = null) + { ++ if (FastProfile && loops.Count == 1) ++ { ++ var loop = loops[0]; ++ if (UseDirectTriangle && loop.Length == 3 && outerFlags is { Length: > 0 } && outerFlags[0] ++ && TryUnmodifiedTriangle(pts[loop[0]], pts[loop[1]], pts[loop[2]], out bool clockwise)) ++ return [clockwise ? (loop[0], loop[1], loop[2]) : (loop[0], loop[2], loop[1])]; ++ ++ var points = new (double X, double Y)[loop.Length]; ++ for (int i = 0; i < loop.Length; i++) points[i] = pts[loop[i]]; ++ var fans = new List<(int A, int B, int C)>(); ++ if (!(outerFlags?[0] ?? SignedArea(points) > 0)) return fans; ++ ++ var root = new Contour(points); ++ for (int i = 0; i < points.Length; i++) root.AddVertex(i); ++ Decompose(root, RendererTolerance); ++ for (Contour? contour = root; contour != null; contour = contour.Next) ++ { ++ if (contour.Head is not { } head) continue; ++ for (var b = head.Nxt; b.Nxt != head; b = b.Nxt) ++ fans.Add((loop[head.Idx], loop[b.Idx], loop[b.Nxt.Idx])); ++ } ++ return fans; ++ } ++ + var flat = loops.SelectMany(l => l).ToArray(); + var coords = flat.Select(i => pts[i]).ToArray(); + var local = new List(); +--- a/src/RvtIO/Geometry/Meshing/MeshModel.cs ++++ b/src/RvtIO/Geometry/Meshing/MeshModel.cs +@@ -54,6 +54,7 @@ + public double ArcEps { get; init; } = 1.0; + /// Any other profile (an elliptical arc, a NURBS or Hermite curve): the world point of the profile at the parameter u for the rotation V0. + public Func? ProfileAt { get; init; } ++ internal RvtIO.Parsing.GRepParserV2.MeridianProfile? ProfileRecipe { get; init; } + /// [uLo, uHi, vLo, vHi] in the mesher order (u = profile, v = rotation). + public required double[] GeEnvelope { get; init; } + /// The surface normal is reversed: the rotation of the edge uv is negated; together with Flipped it decides the winding. +--- a/src/RvtIO/Internal/GRepData.cs ++++ b/src/RvtIO/Internal/GRepData.cs +@@ -93,14 +93,24 @@ + public GRepData? Coarse { get; set; } + + private Lazy? _coarseQuantities; ++ internal bool HasCoarseQuantitySource => _coarseQuantities != null; ++ internal bool CanReplayCoarseQuantitySource { get; private set; } + + /// Coarse solids including non-visible objects, used only for computed door/window surface quantities. + public GRepData? CoarseQuantities + { + get => _coarseQuantities?.Value; +- set => _coarseQuantities = value == null ? null : new Lazy(() => value); ++ set ++ { ++ _coarseQuantities = value == null ? null : new Lazy(() => value); ++ CanReplayCoarseQuantitySource = false; ++ } + } +- internal void SetCoarseQuantityFactory(Func factory) => _coarseQuantities = new(factory); ++ internal void SetCoarseQuantityFactory(Func factory, bool replaySource = false) ++ { ++ _coarseQuantities = new(factory); ++ CanReplayCoarseQuantitySource = replaySource; ++ } + + /// The same block at the Medium detail level, kept only when it differs from this (Fine) one. + public GRepData? Medium { get; set; } +@@ -229,3 +239,4 @@ + public List FaceIndices { get; set; } = new(); + public bool IsClosed { get; set; } + } ++ +--- a/src/RvtIO/Meshes/ElementMeshes.cs ++++ b/src/RvtIO/Meshes/ElementMeshes.cs +@@ -85,7 +85,7 @@ + { + if (geometry.ExactMappedInstances is not { Count: > 0 } mapped || geometry.PlacedSymbolClipped || geometry.PlacedSymbolBox) + return null; +- bool dropsUntaken = DropsUntakenNodes(geometry.Faces, geometry.GhostNodes is { Count: > 0 }); ++ bool? dropsUntaken = null; + var placements = new List(mapped.Count); + int failed = 0; + int untriangulatedInSymbols = 0; +@@ -98,7 +98,9 @@ + if (Math.Abs(Math.Abs(transform.Determinant) - 1) > RigidTolerance) return null; + if (SymbolOf(instance.SymbolId) is not { } symbol) return null; + // The hidden nodes of the symbol must be dropped in the element exactly when they are in the symbol alone. +- if (symbol.HasHiddenNode && symbol.DropsUntakenNodes != dropsUntaken) return null; ++ if (symbol.HasHiddenNode && symbol.DropsUntakenNodes != ++ (dropsUntaken ??= DropsUntakenNodes(geometry.Faces, geometry.GhostNodes is { Count: > 0 }))) ++ return null; + placements.Add(new SymbolPlacement(instance.SymbolId, transform)); + failed += symbol.Failed; + untriangulatedInSymbols += symbol.UntriangulatedFaces; +@@ -182,6 +184,7 @@ + }); + } + } ++ GeometryData.ReportDeferredPlacementCounts(); + return new MeshSet { Elements = elements, Symbols = placedSymbols, GeometryUndecoded = info.WideLayoutNotRewritten }; + } + +@@ -396,15 +399,31 @@ + /// Appends the triangles of one polygon face with its holes; false when the face has no polygon, its triangles do not + /// cover its area, or (for a face with holes) they cover more than its area: a hole that is filled. A face of no area is drawn + /// as nothing and counts as triangulated. +- internal static bool AppendFace(GeoFace face, MeshBuilder target) ++ internal static bool AppendFace(GeoFace face, MeshBuilder target) => ++ AppendFace(face, target, GeTess.UseDirectTriangle); ++ ++ internal static bool AppendFace(GeoFace face, MeshBuilder target, bool directTriangle) + { + if (face.OuterVertices is not { Count: >= 3 } outer) return false; +- var rings = new List> { outer }; +- if (face.InnerVertices != null) rings.AddRange(face.InnerVertices.Where(ring => ring is { Count: >= 3 })); +- foreach (var ring in rings) ++ ++ static bool ValidRing(List ring) ++ { + foreach (var point in ring) + if (point.Length < 3 || !double.IsFinite(point[0]) || !double.IsFinite(point[1]) || !double.IsFinite(point[2])) + return false; ++ return true; ++ } ++ ++ if (!ValidRing(outer)) return false; ++ bool simpleTriangle = directTriangle && outer.Count == 3 && face.InnerVertices is not { Count: > 0 }; ++ List>? rings = null; ++ if (!simpleTriangle) ++ { ++ rings = [outer]; ++ if (face.InnerVertices != null) rings.AddRange(face.InnerVertices.Where(ring => ring is { Count: >= 3 })); ++ for (int ring = 1; ring < rings.Count; ring++) ++ if (!ValidRing(rings[ring])) return false; ++ } + + // The plane of the face: the Newell normal of its outer ring (relative to its first corner, so that large coordinates keep + // their precision), turned to the side of the face normal. +@@ -438,6 +457,23 @@ + ux /= uLength; uy /= uLength; uz /= uLength; + double vx = ny * uz - nz * uy, vy = nz * ux - nx * uz, vz = nx * uy - ny * ux; + ++ (double X, double Y) Project(double[] point) ++ { ++ double dx = point[0] - origin[0], dy = point[1] - origin[1], dz = point[2] - origin[2]; ++ return (dx * ux + dy * uy + dz * uz, dx * vx + dy * vy + dz * vz); ++ } ++ ++ if (simpleTriangle && GeTess.TryUnmodifiedTriangle(Project(outer[0]), Project(outer[1]), Project(outer[2]), ++ out bool clockwise)) ++ { ++ int first = target.VertexCount; ++ foreach (var point in outer) target.AddVertex(point, nx, ny, nz); ++ if (clockwise) target.AddTriangle(first, first + 2, first + 1); ++ else target.AddTriangle(first, first + 1, first + 2); ++ return true; ++ } ++ ++ rings ??= [outer]; + var points = new List<(double X, double Y)>(); + var loops = new List(rings.Count); + var outerFlags = new bool[rings.Count]; +@@ -449,8 +485,7 @@ + var projected = new (double X, double Y)[ring.Count]; + for (int index = 0; index < ring.Count; index++) + { +- double dx = ring[index][0] - origin[0], dy = ring[index][1] - origin[1], dz = ring[index][2] - origin[2]; +- projected[index] = (dx * ux + dy * uy + dz * uz, dx * vx + dy * vy + dz * vz); ++ projected[index] = Project(ring[index]); + loop[index] = points.Count; + points.Add(projected[index]); + } +--- a/src/RvtIO/Model/Geometry.cs ++++ b/src/RvtIO/Model/Geometry.cs +@@ -18,17 +18,68 @@ + /// The m_bbox of the root representation (feet, in the frame of the geometry), which may exceed the tight box. + internal double[]? RootBoundingBox { get; set; } + ++ private List _faces = new(); ++ private List? _meshNodes; ++ private List? _nodeMeasures; ++ private List? _brepSolids; ++ private volatile Lazy? _deferredPlacement; ++ private static int _deferredCount; ++ private static int _materializedCount; ++ ++ internal bool HasDeferredPlacement => _deferredPlacement != null; ++ ++ internal static void ReportDeferredPlacementCounts() ++ { ++ if (_deferredCount == 0) return; ++ Console.WriteLine($"DEFERRED_BODIES {_deferredCount} {_materializedCount}"); ++ } ++ ++ internal void DeferPlacement(Func build) ++ { ++ _deferredPlacement = new(build); ++ System.Threading.Interlocked.Increment(ref _deferredCount); ++ } ++ ++ private void MaterializePlacement() ++ { ++ var pending = _deferredPlacement; ++ if (pending == null) return; ++ // Keep the pending reader visible until all fields are available. ++ lock (pending) ++ { ++ if (!ReferenceEquals(pending, _deferredPlacement)) return; ++ var geometry = pending.Value; ++ _faces = geometry.Faces; ++ _meshNodes = geometry.MeshNodes; ++ _nodeMeasures = geometry.NodeMeasures; ++ _brepSolids = geometry.BrepSolids; ++ System.Threading.Interlocked.Increment(ref _materializedCount); ++ _deferredPlacement = null; ++ } ++ } + /// List of geometry nodes (GGroups containing faces/edges). +- public List Faces { get; set; } = new(); ++ public List Faces ++ { ++ get { MaterializePlacement(); return _faces; } ++ set { MaterializePlacement(); _faces = value; } ++ } + + /// Classifier-only faces: no boundary and no rendered geometry. + internal List? InactiveFaces { get; set; } + + /// The Geometry nodes written as triangle sets, in the frame of (see GRepParserV2.BuildNodes). +- internal List? MeshNodes { get; set; } ++ internal List? MeshNodes ++ { ++ get { MaterializePlacement(); return _meshNodes; } ++ set { MaterializePlacement(); _meshNodes = value; } ++ } + + /// The surface integrals of the Geometry nodes (see GRepData.NodeMeasures), under the node ids of . +- internal List? NodeMeasures { get; set; } ++ internal List? NodeMeasures ++ { ++ get { MaterializePlacement(); return _nodeMeasures; } ++ set { MaterializePlacement(); _nodeMeasures = value; } ++ } + + /// A Geometry node written as a triangle set has a face that is not a plane (a round end, a hole): the body is the face meshes, + /// whatever the dense polygons of the planar faces close into. +@@ -46,7 +97,11 @@ + + /// Topological BRep shells decoded directly from Revit geometry. Face + /// indices refer to ; separate shells are separate solids. +- public List? BrepSolids { get; set; } ++ public List? BrepSolids ++ { ++ get { MaterializePlacement(); return _brepSolids; } ++ set { MaterializePlacement(); _brepSolids = value; } ++ } + + /// + /// 3x4 transform matrix [r00,r01,r02,tx, r10,r11,r12,ty, r20,r21,r22,tz] +--- a/src/RvtIO/Model/ProductRules.cs ++++ b/src/RvtIO/Model/ProductRules.cs +@@ -19,7 +19,7 @@ + /// an instance whose own geometry is null is not exported (for example the floor-hosted family + /// "Assignment - Rectangular opening (floor)"). Faces whose flags are not known (placed from a nested symbol) count as filled. + internal static bool HasOnlyUnfilledFaces(Element element) => +- element.Geometry?.Faces is { Count: > 0 } faces ++ element.Geometry is { HasDeferredPlacement: false, Faces: { Count: > 0 } faces } + && faces.All(face => face.GInfoFlags is uint flags && (flags & FaceFillFlag) == 0); + + /// Whether the element names its created phase (PHASE_CREATED) in its own record graph. Preview and type records +--- a/src/RvtIO/Parsing/BlockParser.cs ++++ b/src/RvtIO/Parsing/BlockParser.cs +@@ -38,6 +38,18 @@ + internal static void ApplyPendingGReps(ParsingState state, List pending, HashSet? unreadable = null) + { + if (pending.Count == 0) return; ++ if (RvtFileReader.TryDecodeBrowserGeometry(pending.Count, index => ++ { ++ var job = pending[index]; ++ return (job.Chunk, job.Start, job.Size); ++ }, ++ (index, geometry) => ++ { ++ var job = pending[index]; ++ if (geometry == null) unreadable?.Add(new(job.Chunk, job.Start, job.Size)); ++ ApplyPendingGRep(state, job, geometry); ++ })) ++ return; + if (OperatingSystem.IsBrowser()) + { + foreach (var job in pending) +@@ -596,22 +608,22 @@ + if (strings?.Count >= MaxBlockStrings || end - start < 8) return; + Span chars = stackalloc char[MaxBlockStringLength]; + int position = start, limit = end - 7; +- if (start >= 0 && end <= d.Length && BitConverter.IsLittleEndian && Vector256.IsHardwareAccelerated) ++ if (start >= 0 && end <= d.Length && BitConverter.IsLittleEndian && Vector128.IsHardwareAccelerated) + { + ref byte data = ref MemoryMarshal.GetArrayDataReference(d); +- int width = Vector256.Count; ++ int width = Vector128.Count; + for (; position <= limit - width; position += width) + { + // The 32-bit length is 2..500. Skip bytes that cannot start that length. +- var low = Vector256.LoadUnsafe(ref data, (nuint)position); +- var second = Vector256.LoadUnsafe(ref data, (nuint)(position + 1)); +- var high = Vector256.LoadUnsafe(ref data, (nuint)(position + 2)) +- | Vector256.LoadUnsafe(ref data, (nuint)(position + 3)); +- var shortLengths = Vector256.Equals(second, Vector256.Zero) +- & Vector256.GreaterThan(low, Vector256.Create((byte)1)); +- var longLengths = Vector256.Equals(second, Vector256.Create((byte)1)) +- & Vector256.LessThanOrEqual(low, Vector256.Create((byte)(MaxBlockStringLength - 256))); +- uint candidates = ((shortLengths | longLengths) & Vector256.Equals(high, Vector256.Zero)) ++ var low = Vector128.LoadUnsafe(ref data, (nuint)position); ++ var second = Vector128.LoadUnsafe(ref data, (nuint)(position + 1)); ++ var high = Vector128.LoadUnsafe(ref data, (nuint)(position + 2)) ++ | Vector128.LoadUnsafe(ref data, (nuint)(position + 3)); ++ var shortLengths = Vector128.Equals(second, Vector128.Zero) ++ & Vector128.GreaterThan(low, Vector128.Create((byte)1)); ++ var longLengths = Vector128.Equals(second, Vector128.Create((byte)1)) ++ & Vector128.LessThanOrEqual(low, Vector128.Create((byte)(MaxBlockStringLength - 256))); ++ uint candidates = ((shortLengths | longLengths) & Vector128.Equals(high, Vector128.Zero)) + .ExtractMostSignificantBits(); + while (candidates != 0) + { +@@ -2589,3 +2601,5 @@ + } + } + } ++ ++ +--- a/src/RvtIO/Parsing/ElementBuilder.cs ++++ b/src/RvtIO/Parsing/ElementBuilder.cs +@@ -16,6 +16,99 @@ + + internal enum GeometryDetail { Fine, Coarse, Medium, CoarseQuantities } + ++ private sealed record LocalPlacementBounds(double[]? Box); ++ ++ private static readonly ConditionalWeakTable PlacementBoundsCache = new(); ++ ++ private static LocalPlacementBounds BoundsForPlacement(GeometryData geometry) ++ { ++ double[] result = [double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, ++ double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity]; ++ foreach (var face in geometry.Faces) ++ { ++ if (face.OuterVertices is not { Count: >= 3 } ring) continue; ++ if (!AddRing(ring)) return new(null); ++ if (face.InnerVertices is { Count: > 0 } holes) ++ foreach (var hole in holes) ++ if (!AddRing(hole)) return new(null); ++ } ++ return new(double.IsFinite(result[0]) ? result : null); ++ ++ bool AddRing(List? ring) ++ { ++ if (ring == null) return false; ++ foreach (var point in ring) ++ { ++ if (point is not { Length: >= 2 }) return false; ++ for (int axis = 0; axis < 3; axis++) ++ { ++ double value = axis < point.Length ? point[axis] : 0; ++ if (!double.IsFinite(value)) return false; ++ result[axis] = Math.Min(result[axis], value); ++ result[axis + 3] = Math.Max(result[axis + 3], value); ++ } ++ } ++ return true; ++ } ++ } ++ ++ private static readonly bool FusedPlacementBounds = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_FUSED_PLACEMENT_BOUNDS") == "1"; ++ ++ private static readonly bool ReuseContainedPlacement = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_REUSE_CONTAINED_PLACEMENT") == "1"; ++ ++ private static readonly bool DeferPlacedFaces = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_DEFER_PLACED_FACES") == "1"; ++ ++ private static string CheckLeafPlacement(GRepData grep, ParsingState state, int ownFaceCount, GeometryDetail detail, ++ out GeometryData? local) ++ { ++ local = null; ++ if (ownFaceCount != 0 || detail != GeometryDetail.Fine) return "own-faces-or-detail"; ++ if (grep.Instances.Count != 1) return "multiple-placements"; ++ var instance = grep.Instances[0]; ++ if (instance.SymbolElemId <= 0 || instance.Transform.Length < 12 || !IsRigidPlacement(instance.Transform) ++ || !state.GrepBlocks.TryGetValue((uint)instance.SymbolElemId, out var symbol)) ++ return "invalid-symbol-or-transform"; ++ if (symbol.Instances.Count != 0) return "nested"; ++ if (state.SymbolPlacementGeometry == null) return "no-symbol-cache"; ++ local = LocalSymbolGeometry(symbol, state); ++ if (local == null || local.Faces.Count < 3) return "less-than-three-local-faces"; ++ var box = PlacementBoundsCache.GetValue(local, BoundsForPlacement).Box; ++ if (box == null) return "invalid-coordinates"; ++ ++ double[]? target = grep.BoundingBox; ++ bool clips = target is { Length: 6 } && target.All(double.IsFinite) ++ && target[0] <= target[3] && target[1] <= target[4] && target[2] <= target[5]; ++ // Each row of the placement is monotone in each coordinate when the other ++ // coordinates are fixed. Evaluating the enclosing corners with the same ++ // floating-point operations bounds every point in every ring. ++ for (int corner = 0; corner < 8; corner++) ++ { ++ double x = box[(corner & 1) == 0 ? 0 : 3]; ++ double y = box[(corner & 2) == 0 ? 1 : 4]; ++ double z = box[(corner & 4) == 0 ? 2 : 5]; ++ for (int axis = 0; axis < 3; axis++) ++ { ++ double[] t = instance.Transform; ++ int row = 3 * axis; ++ double value = t[9 + axis] + x * t[row] + y * t[row + 1] + z * t[row + 2]; ++ if (!double.IsFinite(value)) return "nonfinite-placement"; ++ if (clips && (value < target![axis] || value > target[axis + 3])) return "outside-box"; ++ } ++ } ++ ++ // The old code removes duplicate corners and duplicate faces. Confirm that ++ // at least three distinct faces survive, which is all the early caller needs. ++ var witness = TransformGeometry(new GeometryData { Faces = local.Faces.GetRange(0, 3) }, instance.Transform, areaOnly: false); ++ if (witness == null) return "no-witness"; ++ witness = ClipGeometryToBounds(witness, target, out bool changed, ownsSource: true); ++ if (changed || witness == null) return "clipped-witness"; ++ DeduplicateExactFaces(witness); ++ return witness.Faces.Count == 3 ? "certified" : "duplicate-witness"; ++ } ++ + /// + /// Family instance (GInstance GRep): replace the element's placeholder geometry with the + /// SYMBOL's mesh placed by the instance transform (IfcMappedItem architecture); symbols may +@@ -27,6 +120,23 @@ + if (grep.Instances.Count == 0) return; + elem.Geometry ??= new GeometryData(); + int ownFaceCount = elem.Geometry.Faces.Count; ++ if (DeferPlacedFaces && ownFaceCount == 0 && elem.Geometry.MeshNodes == null ++ && elem.Geometry.NodeMeasures == null && elem.Geometry.BrepSolids == null ++ && CheckLeafPlacement(grep, state, ownFaceCount, detail, out var local) == "certified") ++ { ++ var instance = grep.Instances[0]; ++ var transform = (double[])instance.Transform.Clone(); ++ double[]? bounds = grep.BoundingBox is { } box ? (double[])box.Clone() : null; ++ long nodeOrder = instance.NodeOrder; ++ elem.Geometry.ExactMappedInstances = ++ [ ++ new GeoInstance { SymbolId = instance.SymbolElemId, Transform = (double[])transform.Clone() }, ++ ]; ++ elem.Geometry.UntriangulatedFaces += local!.UntriangulatedFaces; ++ // Capture only the leaf's local geometry. The parsing state can be released. ++ elem.Geometry.DeferPlacement(() => BuildDeferredLeaf(local, transform, bounds, nodeOrder)); ++ return; ++ } + var expandedTopLevel = new List(); + var placedBox = new StrongBox(); + var unresolvedNested = new StrongBox(); +@@ -43,7 +153,8 @@ + } + if (detail != GeometryDetail.CoarseQuantities) + { +- placed = ClipGeometryToBounds(placed, grep.BoundingBox, out bool clipped, ownsSource: true); ++ placed = ClipGeometryToBounds(placed, grep.BoundingBox, out bool clipped, ownsSource: true, ++ reuseContained: ReuseContainedPlacement); + if (clipped) elem.Geometry.PlacedSymbolClipped = true; + } + if (placed == null) { LogUnresolvedSymbol(elem, instance.SymbolElemId, "clipped-away", state); continue; } +@@ -58,7 +169,22 @@ + if (placedBox.Value) elem.Geometry.PlacedSymbolBox = true; + if (unresolvedNested.Value) elem.Geometry.UnresolvedSymbol = true; + if (ownFaceCount == 0 && expandedTopLevel.Count > 0) ++ { + elem.Geometry.ExactMappedInstances = expandedTopLevel; ++ } ++ } ++ ++ private static GeometryData BuildDeferredLeaf(GeometryData local, double[] transform, double[]? bounds, long nodeOrder) ++ { ++ var placed = new GeometryData(); ++ if (TransformGeometry(local, transform, areaOnly: false) is { } body) ++ AppendPlacedGeometry(placed, body); ++ SetGeometryBoundsFromFaces(placed); ++ var result = new GeometryData(); ++ if (ClipGeometryToBounds(placed, bounds, out _, ownsSource: true) is { } clipped) ++ AppendPlacedGeometry(result, clipped, nodeOrder); ++ DeduplicateExactFaces(result); ++ return result; + } + + /// +@@ -68,9 +194,9 @@ + private static void ExpandTransformOnlyInstanceGeometry( + Element elem, uint elemId, ParsingState state, GeometryDetail detail = GeometryDetail.Fine) + { +- if ((elem.Geometry?.Faces?.Count ?? 0) >= 3) return; +- if (!state.FamilyInstanceTransforms.TryGetValue(elemId, out var fi)) return; +- if (fi.SymbolId <= 0 || fi.SymbolId == elem.Id) return; ++ if (!state.FamilyInstanceTransforms.TryGetValue(elemId, out var fi) ++ || fi.SymbolId <= 0 || fi.SymbolId == elem.Id ++ || elem.Geometry is { HasDeferredPlacement: true } or { Faces.Count: >= 3 }) return; + var placedBox = new StrongBox(); + var unresolvedNested = new StrongBox(); + var placed = BuildPlacedSymbolGeometry(fi.SymbolId, fi.Trf, state, new HashSet(), placedBox: placedBox, +@@ -93,8 +219,10 @@ + Transform = (double[])fi.Trf.Clone(), + }); + if (!hadOwnFaces) ++ { + elem.Geometry.ExactMappedInstances = +- [new GeoInstance { SymbolId = fi.SymbolId, Transform = (double[])fi.Trf.Clone() }]; ++ [new GeoInstance { SymbolId = fi.SymbolId, Transform = (double[])fi.Trf.Clone() }]; ++ } + // The tight box of the placed symbol, or the one the element's own GRep stores (a + // transform-only instance of a symbol-less family keeps its record's own box). + elem.Geometry.BoundingBox = state.GrepBlocks.TryGetValue(elemId, out var ownGrep) && ownGrep.BoundingBox != null +@@ -257,22 +385,18 @@ + return BuildPlacedBox(symbol.BoundingBox, transform, material > 0 ? material : null, style); + } + var result = new GeometryData(); +- +- var cache = state.SymbolPlacementGeometry; +- GeometryData? own; +- if (symbol.Faces.Count == 0) own = null; +- else if (cache == null) own = BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false); +- else +- { +- // Only placements of the same representation wait for its local faces. +- own = cache.GetOrAdd(symbol, static (block, separate) => new Lazy( +- () => BuildGeometryData(block, separate, includeEdgesAndInstances: false)), +- state.SeparateFacesWithDistinctOpenings).Value; +- } ++ bool areaOnly = detail == GeometryDetail.CoarseQuantities; ++ bool collectBounds = FusedPlacementBounds && !areaOnly && symbol.Instances.Count == 0; ++ ++ var own = LocalSymbolGeometry(symbol, state); + if (own?.Faces is { Count: > 0 }) + { +- var placedOwn = TransformGeometry(own, transform, areaOnly: detail == GeometryDetail.CoarseQuantities); +- if (placedOwn != null) AppendPlacedGeometry(result, placedOwn); ++ var placedOwn = TransformGeometry(own, transform, areaOnly, collectBounds); ++ if (placedOwn != null) ++ { ++ AppendPlacedGeometry(result, placedOwn); ++ result.BoundingBox = placedOwn.BoundingBox; ++ } + } + + foreach (var child in symbol.Instances) +@@ -285,7 +409,7 @@ + } + + if (result.Faces.Count == 0) return null; +- if (detail != GeometryDetail.CoarseQuantities) SetGeometryBoundsFromFaces(result); ++ if (!areaOnly && !collectBounds) SetGeometryBoundsFromFaces(result); + return result; + + } +@@ -293,6 +417,34 @@ + { + path.Remove(symbolId); + } ++ } ++ ++ private static GeometryData? LocalSymbolGeometry(GRepData symbol, ParsingState state) ++ { ++ if (symbol.Faces.Count == 0) return null; ++ var cache = state.SymbolPlacementGeometry; ++ if (cache == null) return BuildGeometryData(symbol, state.SeparateFacesWithDistinctOpenings, includeEdgesAndInstances: false); ++ // Only placements of the same representation wait for its local faces. ++ return cache.GetOrAdd(symbol, static (block, separate) => new Lazy( ++ () => BuildGeometryData(block, separate, includeEdgesAndInstances: false)), ++ state.SeparateFacesWithDistinctOpenings).Value; ++ } ++ ++ private struct PlacedOuterBounds ++ { ++ private double _minX = double.MaxValue, _minY = double.MaxValue, _minZ = double.MaxValue; ++ private double _maxX = double.MinValue, _maxY = double.MinValue, _maxZ = double.MinValue; ++ ++ public PlacedOuterBounds() { } ++ ++ public void Add(double[] point) ++ { ++ _minX = Math.Min(_minX, point[0]); _maxX = Math.Max(_maxX, point[0]); ++ _minY = Math.Min(_minY, point[1]); _maxY = Math.Max(_maxY, point[1]); ++ _minZ = Math.Min(_minZ, point[2]); _maxZ = Math.Max(_maxZ, point[2]); ++ } ++ ++ public readonly double[] ToArray() => [_minX, _minY, _minZ, _maxX, _maxY, _maxZ]; + } + + private static void SetGeometryBoundsFromFaces(GeometryData geometry) +@@ -522,7 +674,8 @@ + /// Apply a GInstance placement (rows: basisX, basisY, basisZ, origin - 12 doubles) to a + /// symbol's geometry, producing world-space faces for the instance. + /// +- private static GeometryData? TransformGeometry(GeometryData sym, double[] t, bool areaOnly) ++ private static GeometryData? TransformGeometry( ++ GeometryData sym, double[] t, bool areaOnly, bool collectBounds = false) + { + if (t.Length < 12) return null; + double[] MapCoordinates(double x, double y, double z) => +@@ -537,18 +690,22 @@ + bool rigid = IsRigidPlacement(t); + var outGeo = new GeometryData(); + var faceMap = sym.BrepSolids is { Count: > 0 } ? new int[sym.Faces.Count] : null; ++ var bounds = new PlacedOuterBounds(); + for (int sourceFaceIndex = 0; sourceFaceIndex < sym.Faces.Count; sourceFaceIndex++) + { + var f = sym.Faces[sourceFaceIndex]; + if (f.OuterVertices is not { Count: >= 3 } ov) continue; + var verts = new List(ov.Count); ++ var faceBounds = bounds; + foreach (var v in ov) + { + var w = Map(v); + if (!double.IsFinite(w[0]) || !double.IsFinite(w[1]) || !double.IsFinite(w[2])) { verts = null; break; } ++ if (collectBounds) faceBounds.Add(w); + verts.Add(w); + } + if (verts == null) continue; ++ bounds = faceBounds; + double[] normal = []; + double[] origin = []; + if (!areaOnly) +@@ -578,6 +735,7 @@ + if (faceMap != null) faceMap[sourceFaceIndex] = outGeo.Faces.Count; + } + if (outGeo.Faces.Count == 0) return null; ++ if (collectBounds) outGeo.BoundingBox = bounds.ToArray(); + // the Revit face meshes of the nodes are made in the frame of the symbol and placed + // with the transform of the instance (a rotation or a mirror image; a scaled instance keeps + // the polygons) +@@ -613,13 +771,16 @@ + internal static GeometryData? ClipGeometryToBounds(GeometryData source, double[]? bounds) => + ClipGeometryToBounds(source, bounds, out _); + ++ private static readonly bool ReuseClipLists = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_REUSE_CLIP_LISTS") == "1"; ++ + /// True when the result is not the faces of as they are: a face was cut + /// or left out, or nothing is left (null). + internal static GeometryData? ClipGeometryToBounds(GeometryData source, double[]? bounds, out bool changed) => + ClipGeometryToBounds(source, bounds, out changed, ownsSource: false); + + private static GeometryData? ClipGeometryToBounds( +- GeometryData source, double[]? bounds, out bool changed, bool ownsSource) ++ GeometryData source, double[]? bounds, out bool changed, bool ownsSource, bool reuseContained = false) + { + changed = false; + if (bounds is not { Length: 6 } +@@ -638,6 +799,36 @@ + && (face.OuterVertices ?? []).Concat(face.InnerVertices.SelectMany(ring => ring)) + .Any(point => !Inside(point, bounds))) + return source; ++ ++ // BuildPlacedSymbolGeometry already returned distinct valid shell indices. ++ if (reuseContained && source.BoundingBox is { Length: 6 } box ++ && box[0] >= bounds[0] && box[1] >= bounds[1] && box[2] >= bounds[2] ++ && box[3] <= bounds[3] && box[4] <= bounds[4] && box[5] <= bounds[5] ++ && HasUnchangedPolygons()) ++ { ++ foreach (var face in source.Faces) ++ { ++ face.Envelope = null; ++ face.QuadratureArea = null; ++ } ++ return source; ++ } ++ ++ bool HasUnchangedPolygons() ++ { ++ foreach (var face in source.Faces) ++ { ++ if (face.OuterVertices is not { Count: >= 3 } polygon) return false; ++ // The bound excludes nonfinite vertices. Scaled boxes can still contain them. ++ var previous = polygon[^1]; ++ foreach (var point in polygon) ++ { ++ if (!Inside(point, bounds) || point.AsSpan().SequenceEqual(previous)) return false; ++ previous = point; ++ } ++ } ++ return true; ++ } + + static void RemoveAdjacentDuplicates(List polygon) + { +@@ -665,25 +856,36 @@ + return point; + } + +- var output = new List(); ++ List? output = ReuseClipLists ? null : new(); + var previous = polygon[^1]; + bool previousInside = IsInside(previous); +- foreach (var current in polygon) +- { ++ for (int index = 0; index < polygon.Count; index++) ++ { ++ var current = polygon[index]; + bool currentInside = IsInside(current); + if (currentInside) + { +- if (!previousInside) { output.Add(Intersect(previous, current)); changed = true; } +- output.Add(current); ++ if (!previousInside) ++ { ++ (output ??= new()).Add(Intersect(previous, current)); ++ changed = true; ++ } ++ output?.Add(current); + } + else + { ++ if (output == null) ++ { ++ output = new(index); ++ for (int i = 0; i < index; i++) output.Add(polygon[i]); ++ } + changed = true; + if (previousInside) output.Add(Intersect(previous, current)); + } + previous = current; + previousInside = currentInside; + } ++ output ??= polygon; + RemoveAdjacentDuplicates(output); + return output; + } +@@ -6679,9 +6881,8 @@ + AddViewAndDatumDefaults(rvtInfo); + AddCurtainQuantities(rvtInfo); + EnrichTypeLevelBips(rvtInfo, state, elemByIdLookup); +- // Detached quantity geometry can run beside parameter propagation on runtimes with background threads. +- var quantities = state != null && !OperatingSystem.IsBrowser() +- && SymbolDiagPath == null && !GRepParserV2.IsDecodeTracingEnabled() ++ // Detached quantity geometry reads final categories and GRep, independently of parameter propagation. ++ var quantities = state != null && !OperatingSystem.IsBrowser() && SymbolDiagPath == null && !GRepParserV2.IsDecodeTracingEnabled() + && Environment.GetEnvironmentVariable("RVTIO_MESH_LOG") != "1" + && Environment.GetEnvironmentVariable("RVTIO_TRACE_ID") == null + && !TfBlockDeserializer.CaptureAllFields +@@ -9265,3 +9466,4 @@ + }; + } + } ++ +--- a/src/RvtIO/Parsing/ElementIdMap.cs ++++ b/src/RvtIO/Parsing/ElementIdMap.cs +@@ -19,6 +19,8 @@ + } + + internal long SourceId(int key) => _sourceIds.TryGetValue(key, out long id) ? id : key; ++ ++ internal bool HasRemappedIds => _keys.Count != 0; + + internal IReadOnlyDictionary? SourceIdsAsText() => _sourceIds.Count == 0 ? null + : _sourceIds.ToDictionary(pair => pair.Key, pair => pair.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); +--- a/src/RvtIO/Parsing/GRepParserV2.cs ++++ b/src/RvtIO/Parsing/GRepParserV2.cs +@@ -886,6 +886,24 @@ + internal static GRepData? ParseNativeWallBodyCandidate(byte[] data, int start, uint size) + => ParseCore(data, start, size, nativeWallBody: true, includeDetailLevels: true, requireCylinderEdgeBounds: true); + ++ internal static void InstallCoarseQuantityReplay(GRepData geometry, byte[] bytes, int start, uint dataSize, ++ bool nativeWallBody = false) ++ { ++ // Retain the block without retaining its complete decompressed partition. ++ int end = (int)Math.Min((long)start + 16 + dataSize, bytes.Length); ++ var source = bytes.AsSpan(start, end - start).ToArray(); ++ geometry.SetCoarseQuantityFactory(() => ++ { ++ int previousDetailLevel = t_detailLevel; ++ try ++ { ++ t_detailLevel = CoarseDetailLevel; ++ return ParseCore(source, 0, dataSize, nativeWallBody, includeNonVisible: true); ++ } ++ finally { t_detailLevel = previousDetailLevel; } ++ }, replaySource: true); ++ } ++ + private static GRepData? ParseCore(byte[] d, int blockStart, uint dataSize, bool nativeWallBody, bool includeNonVisible = false, + bool requireCompleteWalk = false, bool measureSourceNodes = false, bool measureLighting = false, bool measureFills = false, + BodyMeasure bodyMeasure = BodyMeasure.None, bool includeDetailLevels = false, bool requireCylinderEdgeBounds = false) +@@ -1074,19 +1092,9 @@ + && c.Queue.Any(node => (node.Cls == SolidClass || ShouldAttachSymbolGeometry(node.Cls)) + && c.ObjectGInfo.TryGetValue(node.V, out var info) && IsHiddenInstanceVariant(info.Flags))) + { +- // Retain only this block, not the decompressed partition; decode quantities only when a consumer needs them. +- var source = d.AsSpan(blockStart, payloadEnd - blockStart).ToArray(); +- built.SetCoarseQuantityFactory(() => +- { +- int previousDetailLevel = t_detailLevel; +- try +- { +- t_detailLevel = CoarseDetailLevel; +- return ParseCore(source, 0, dataSize, nativeWallBody, includeNonVisible: true); +- } +- finally { t_detailLevel = previousDetailLevel; } +- }); +- } ++ InstallCoarseQuantityReplay(built, d, blockStart, dataSize, nativeWallBody); ++ } ++ + if (MeshDiagPath != null) WriteMeshDiag(c, built, payloadEnd - blockStart); + if (includeDetailLevels && built is { HasDetailLevelAlternatives: true }) + { +@@ -1564,7 +1572,7 @@ + { + // [GInfo 16][endParams 2xf64][xVec 3][yVec 3][radius][center 3][bFilled] = + // 113b. +- if (!c.CanRead(113)) throw Stop; ++ if (!c.CanRead(GArcBytes)) throw Stop; + var ar = new ArcRec + { + T0 = BitConverter.ToDouble(c.D, c.Pos + 16), +@@ -1577,7 +1585,7 @@ + ar.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); + ar.C[k] = BitConverter.ToDouble(c.D, c.Pos + 88 + 8 * k); + } +- c.Take(113); ++ c.Take(GArcBytes); + if (IsFinite(ar.R) && IsFinite(ar.C[0]) && Math.Abs(ar.R) > 1e-9 && Math.Abs(ar.R) < 1e5) + c.Curves[(uint)v] = ar; + } +@@ -1585,7 +1593,7 @@ + { + // [GInfo 16][endParams 2*f64][center 3][xVec 3][yVec 3] [xLen f64][yLen f64] = + // 120 bytes. +- if (!c.CanRead(120)) throw Stop; ++ if (!c.CanRead(GEllipseBytes)) throw Stop; + var ellipse = new ArcRec + { + T0 = BitConverter.ToDouble(c.D, c.Pos + 16), +@@ -1599,7 +1607,7 @@ + ellipse.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); + ellipse.Y[k] = BitConverter.ToDouble(c.D, c.Pos + 80 + 8 * k); + } +- c.Take(120); ++ c.Take(GEllipseBytes); + if (IsFinite(ellipse.R) && IsFinite(ellipse.RY) + && Math.Abs(ellipse.R) > 1e-9 && Math.Abs(ellipse.R) < 1e5 + && Math.Abs(ellipse.RY) > 1e-9 && Math.Abs(ellipse.RY) < 1e5) +@@ -1619,7 +1627,7 @@ + else if (cls == 1736) // GLine -> capture as degenerate curve (R=0) + { + // [GInfo 16][endParams 2xf64][origin 3][dirVec 3] = 80b. +- if (!c.CanRead(80)) throw Stop; ++ if (!c.CanRead(GLineBytes)) throw Stop; + var ln = new ArcRec + { + R = 0, +@@ -1631,7 +1639,7 @@ + ln.C[k] = BitConverter.ToDouble(c.D, c.Pos + 32 + 8 * k); + ln.X[k] = BitConverter.ToDouble(c.D, c.Pos + 56 + 8 * k); + } +- c.Take(80); ++ c.Take(GLineBytes); + if (IsFinite(ln.C[0]) && IsFinite(ln.X[0])) + c.Curves[(uint)v] = ln; + } +@@ -3154,6 +3162,8 @@ + : c.RootBoundingBox; + var faceIndicesByHandle = new Dictionary>(); + var faceHandleByIndex = new List(); ++ var preparedBounds = DirectTrim && authoritativeBounds is { Length: >= 6 } ++ ? new SerializedFaceBounds(authoritativeBounds) : (SerializedFaceBounds?)null; + var rejectedFaceHandles = new HashSet(); + var kindCounts = new Dictionary(); + bool kindDiag = Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; +@@ -3165,7 +3175,7 @@ + kindCounts[kindName] = kindCounts.GetValueOrDefault(kindName) + 1; + } + if (!bodyFaceHandles.Contains(handle) && walkedFaceHandles.Contains(handle)) return; +- var boundedFace = ClipToSerializedBounds(face, authoritativeBounds); ++ var boundedFace = ClipToSerializedBounds(face, authoritativeBounds, preparedBounds); + if (c.ExactPlanarSpaceBoundary && !ReferenceEquals(boundedFace, face)) + throw Stop; + if (boundedFace == null) +@@ -4075,6 +4085,7 @@ + internal static bool IsWithinSerializedBounds(GRepFace face, double[]? bounds) + { + if (bounds is not { Length: >= 6 }) return true; ++ if (DirectTrim) return new SerializedFaceBounds(bounds).Contains(face); + const double MachineEpsilon = 2.2204460492503131e-16; + double scale = Math.Max(1.0, bounds.Take(6).Select(Math.Abs).Max()); + double roundoff = 64 * MachineEpsilon * scale; +@@ -4085,14 +4096,56 @@ + && point[2] >= bounds[2] - roundoff && point[2] <= bounds[5] + roundoff); + } + ++ private readonly struct SerializedFaceBounds ++ { ++ private readonly double _minX, _minY, _minZ, _maxX, _maxY, _maxZ; ++ ++ public SerializedFaceBounds(double[] bounds) ++ { ++ const double MachineEpsilon = 2.2204460492503131e-16; ++ double scale = Math.Max(1.0, MaxAbsIgnoringNaN(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5])); ++ double roundoff = 64 * MachineEpsilon * scale; ++ _minX = bounds[0] - roundoff; ++ _minY = bounds[1] - roundoff; ++ _minZ = bounds[2] - roundoff; ++ _maxX = bounds[3] + roundoff; ++ _maxY = bounds[4] + roundoff; ++ _maxZ = bounds[5] + roundoff; ++ } ++ ++ public bool Contains(GRepFace face) ++ { ++ if (!ContainsAll(face.Vertices)) return false; ++ if (face.InnerVertices is { } rings) ++ foreach (var ring in rings) ++ if (!ContainsAll(ring)) return false; ++ return true; ++ } ++ ++ private bool ContainsAll(List? points) ++ { ++ if (points == null) return true; ++ foreach (var point in points) ++ if (!(point.Length >= 3 ++ && point[0] >= _minX && point[0] <= _maxX ++ && point[1] >= _minY && point[1] <= _maxY ++ && point[2] >= _minZ && point[2] <= _maxZ)) ++ return false; ++ return true; ++ } ++ } ++ + /// + /// Clips a reconstructed polygon to the exact serialized representation extent. Rejecting the + /// whole polygon when one tessellation vertex crosses m_tightbBox loses the valid portion of + /// analytic surfaces. + /// +- internal static GRepFace? ClipToSerializedBounds(GRepFace face, double[]? bounds) +- { +- if (bounds is not { Length: >= 6 } || IsWithinSerializedBounds(face, bounds)) return face; ++ internal static GRepFace? ClipToSerializedBounds(GRepFace face, double[]? bounds) => ++ ClipToSerializedBounds(face, bounds, null); ++ ++ private static GRepFace? ClipToSerializedBounds(GRepFace face, double[]? bounds, SerializedFaceBounds? prepared) ++ { ++ if (bounds is not { Length: >= 6 } || (prepared?.Contains(face) ?? IsWithinSerializedBounds(face, bounds))) return face; + if (face.Vertices is not { Count: >= 3 } vertices + || face.InnerVertices is { Count: > 0 }) return null; + +@@ -5014,14 +5067,29 @@ + Func evaluate, + IReadOnlyList<(double[] First, double[] Second)>? worldBoundary = null) + { ++ if (authoredEdges.Count == 0) return evaluate; ++ var prepared = new TrimBoundaryEdge[authoredEdges.Count]; + double edgeScale = 1.0; +- foreach (var edge in authoredEdges) +- edgeScale = Math.Max(edgeScale, MaxAbsIgnoringNaN(edge.U1, edge.V1, edge.U2, edge.V2, 0, 0)); +- return (u, v) => EvaluateTrimBoundaryChord(u, v, authoredEdges, evaluate, worldBoundary, edgeScale); +- } ++ for (int i = 0; i < prepared.Length; i++) ++ { ++ var (u1, v1, u2, v2) = authoredEdges[i]; ++ double du = u2 - u1, dv = v2 - v1; ++ double endU = u1 + du, endV = v1 + dv; ++ double scale = Math.Max(1, MaxAbsIgnoringNaN(u1, v1, u2, v2, 0, 0)); ++ edgeScale = Math.Max(edgeScale, scale); ++ prepared[i] = new(u1, v1, du, dv, du * du + dv * dv, ++ Math.Min(u1, endU), Math.Max(u1, endU), Math.Min(v1, endV), Math.Max(v1, endV), scale); ++ } ++ return (u, v) => EvaluateTrimBoundaryChord(u, v, authoredEdges, prepared, evaluate, worldBoundary, edgeScale); ++ } ++ ++ private readonly record struct TrimBoundaryEdge( ++ double U1, double V1, double Du, double Dv, double LengthSquared, ++ double MinU, double MaxU, double MinV, double MaxV, double Scale); + + private static double[] EvaluateTrimBoundaryChord(double u, double v, + IReadOnlyList<(double U1, double V1, double U2, double V2)> authoredEdges, ++ TrimBoundaryEdge[] prepared, + Func evaluate, IReadOnlyList<(double[] First, double[] Second)>? worldBoundary, + double edgeScale) + { +@@ -5032,24 +5100,23 @@ + double maxDistanceSquared = maxTolerance * maxTolerance; + int bestEdge = -1; + double bestDistanceSquared = double.PositiveInfinity; +- for (int edgeIndex = 0; edgeIndex < authoredEdges.Count; edgeIndex++) +- { +- var edge = authoredEdges[edgeIndex]; +- double du = edge.U2 - edge.U1, dv = edge.V2 - edge.V1; +- if (useBounds && (Outside(u, edge.U1, du, maxDistanceSquared) || Outside(v, edge.V1, dv, maxDistanceSquared))) ++ double queryScale = useBounds ? Math.Max(Math.Abs(u), Math.Abs(v)) : MaxAbsIgnoringNaN(u, v, 0, 0, 0, 0); ++ for (int edgeIndex = 0; edgeIndex < prepared.Length; edgeIndex++) ++ { ++ ref readonly var edge = ref prepared[edgeIndex]; ++ if (useBounds && (Outside(u, edge.MinU, edge.MaxU, maxDistanceSquared) || Outside(v, edge.MinV, edge.MaxV, maxDistanceSquared))) + continue; +- double lengthSquared = du * du + dv * dv; ++ double lengthSquared = edge.LengthSquared; + if (lengthSquared == 0 || !IsFinite(lengthSquared)) continue; +- double fraction = ((u - edge.U1) * du + (v - edge.V1) * dv) ++ double fraction = ((u - edge.U1) * edge.Du + (v - edge.V1) * edge.Dv) + / lengthSquared; +- double parameterScale = Math.Max(1, +- MaxAbsIgnoringNaN(u, v, edge.U1, edge.V1, edge.U2, edge.V2)); ++ double parameterScale = Math.Max(queryScale, edge.Scale); + double parameterTolerance = toleranceFactor * parameterScale; + if (fraction < -parameterTolerance || fraction > 1 + parameterTolerance) + continue; + fraction = Math.Clamp(fraction, 0, 1); +- double projectedU = edge.U1 + du * fraction; +- double projectedV = edge.V1 + dv * fraction; ++ double projectedU = edge.U1 + edge.Du * fraction; ++ double projectedV = edge.V1 + edge.Dv * fraction; + double deltaU = u - projectedU, deltaV = v - projectedV; + double distanceSquared = deltaU * deltaU + deltaV * deltaV; + if (distanceSquared > parameterTolerance * parameterTolerance +@@ -5060,8 +5127,8 @@ + } + if (bestEdge < 0) return evaluate(u, v); + var boundary = authoredEdges[bestEdge]; +- double boundaryDu = boundary.U2 - boundary.U1; +- double boundaryDv = boundary.V2 - boundary.V1; ++ double boundaryDu = prepared[bestEdge].Du; ++ double boundaryDv = prepared[bestEdge].Dv; + // Orthogonal projection mixes both rounded coordinates; two adjacent clipping cells can + // then produce fractions separated by one floating-point bit for the same topological + // point. +@@ -5078,11 +5145,9 @@ + first[2] + (second[2] - first[2]) * bestFraction, + ]; + +- static bool Outside(double point, double start, double direction, double limitSquared) +- { +- // Use the rounded projection endpoints to bound the same arithmetic as the exact test. +- double end = start + direction; +- double distance = Math.Max(Math.Min(start, end) - point, point - Math.Max(start, end)); ++ static bool Outside(double point, double min, double max, double limitSquared) ++ { ++ double distance = Math.Max(min - point, point - max); + return distance > 0 && distance * distance > limitSquared; + } + } +@@ -5637,15 +5702,47 @@ + int uCount = ClipFlat(buffers.UTemp, uTempCount, 0, uSamples[uIndex + 1], false, ref buffers.UClipped); + if (uCount == 0) continue; + int vCellCount = allVCells ? vSamples.Count - 1 : 1; ++ double minV = double.NaN, maxV = double.NaN; ++ if (DirectTrim && vCellCount > 1) ++ { ++ minV = maxV = buffers.UClipped[1]; ++ for (int i = 1; i < uCount; i++) ++ { ++ double v = buffers.UClipped[2 * i + 1]; ++ if (double.IsNaN(v)) ++ { ++ minV = maxV = v; ++ break; ++ } ++ if (v < minV) minV = v; ++ if (v > maxV) maxV = v; ++ } ++ } + for (int vIndex = 0; vIndex < vCellCount; vIndex++) + { + double[] polygon = buffers.UClipped; + int count = uCount; + if (vCellCount > 1) + { +- int vTempCount = ClipFlat(buffers.UClipped, uCount, 1, vSamples[vIndex], true, ref buffers.VTemp); +- count = ClipFlat(buffers.VTemp, vTempCount, 1, vSamples[vIndex + 1], false, ref buffers.VClipped); +- polygon = buffers.VClipped; ++ double lower = vSamples[vIndex], upper = vSamples[vIndex + 1]; ++ // Use the same tests as the clipper. The upper bound can reject a strip ++ // only when the lower clip would keep every vertex without intersections. ++ bool lowerKeepsAll = false, bothKeepAll = false; ++ if (DirectTrim) ++ { ++ double lowerLimit = lower - GridClipTolerance, upperLimit = upper + GridClipTolerance; ++ lowerKeepsAll = minV >= lowerLimit; ++ if (maxV < lowerLimit || (lowerKeepsAll && minV > upperLimit)) continue; ++ bothKeepAll = lowerKeepsAll && maxV <= upperLimit; ++ } ++ if (!bothKeepAll) ++ { ++ int vTempCount = lowerKeepsAll ? uCount ++ : ClipFlat(buffers.UClipped, uCount, 1, lower, true, ref buffers.VTemp); ++ var vInput = lowerKeepsAll ? buffers.UClipped : buffers.VTemp; ++ count = ClipFlat(vInput, vTempCount, 1, upper, false, ref buffers.VClipped); ++ polygon = buffers.VClipped; ++ } + } + count = CleanFlat(polygon, count, ref buffers.Clean); + polygon = buffers.Clean; +@@ -5669,6 +5766,8 @@ + finally { buffers.InUse = false; } + } + ++ private const double GridClipTolerance = 1e-12; ++ + /// One Sutherland-Hodgman step: keeps the part of the polygon (points from ) on one side of the line + /// axis = value, and writes it to . Returns the number of points written. + private static int ClipFlat(double[] input, int count, int axis, double value, bool keepGreater, ref double[] output) +@@ -5698,7 +5797,8 @@ + } + return written; + +- bool Inside(double coordinate) => keepGreater ? coordinate >= value - 1e-12 : coordinate <= value + 1e-12; ++ bool Inside(double coordinate) => keepGreater ++ ? coordinate >= value - GridClipTolerance : coordinate <= value + GridClipTolerance; + + void Intersect(double firstX, double firstY, double secondX, double secondY) + { +@@ -5972,6 +6072,9 @@ + if (ok) yield return quad; + } + } ++ ++ internal static readonly bool DirectTrim = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_DIRECT_TRIM") == "1"; + + // Each decoder reuses these buffers across faces. Returned rings own their lists and point references. + private sealed class RingGraph +@@ -6529,3 +6632,4 @@ + + + } ++ +--- /dev/null ++++ b/src/RvtIO/Parsing/GRepParserV2.CurveOnly.cs +@@ -0,0 +1,85 @@ ++using System.Buffers.Binary; ++ ++namespace RvtIO.Parsing; ++ ++internal static partial class GRepParserV2 ++{ ++ private const int GLineBytes = 80, GArcBytes = 113, GEllipseBytes = 120; ++ private const int GInfoBytes = 16; ++ private const int GRepScalarBytes = 2 * 6 * sizeof(double) + 2 * sizeof(int); ++ private static readonly Lazy CurveOnlyLayout = new(() => ++ { ++ TfBlockDeserializer.TfField info = new("m_GInfo", 14, 0, null, null, 1246); ++ TfBlockDeserializer.TfField nodes = new("m_subNodes", 14, 81, null, null, 2009); ++ TfBlockDeserializer.TfField[] root = ++ [ ++ info, nodes, new("m_bBox", 13, 16, null, 2, 2008), ++ new("m_tightbBox", 13, 16, null, 2, 2008), ++ new("m_gElemType", 4, 0, null, null, 2008), new("m_flags", 5, 0, null, null, 2008), ++ ]; ++ return TfBlockDeserializer.SerializationFields(2007)?.SequenceEqual(root) == true ++ && TfBlockDeserializer.SerializationFields(2009)?.SequenceEqual([info, nodes]) == true ++ && TfBlockDeserializer.Schemas.ContainsKey(1736) ++ && TfBlockDeserializer.Schemas.ContainsKey(1974) ++ && TfBlockDeserializer.Schemas.ContainsKey(2010); ++ }); ++ ++ // The mesh walker only uses these curves as profiles of other nodes. A complete graph ++ // containing only groups and these profiles cannot contribute edges, mesh faces or instances. ++ internal static bool IsCurveOnlyRepresentation(byte[] data, int start, uint size) ++ { ++ if (start < 0 || size < 2 + GInfoBytes + sizeof(int) + GRepScalarBytes ++ || (long)start + 16 + size > data.Length ++ || BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(start + 12, 2)) != 2007 ++ || !CurveOnlyLayout.Value) return false; ++ ++ ReadOnlySpan remaining = data.AsSpan(start + 14, (int)size - 2); ++ Span queue = stackalloc ushort[64]; ++ int end = 0; ++ if (!ReadCurveGroup(ref remaining, queue, ref end) || remaining.Length < GRepScalarBytes) return false; ++ remaining = remaining[GRepScalarBytes..]; ++ ++ for (int index = 0; index < end; index++) ++ { ++ if (queue[index] == 2009) ++ { ++ if (!ReadCurveGroup(ref remaining, queue, ref end)) return false; ++ continue; ++ } ++ int length = queue[index] switch ++ { ++ 1736 => GLineBytes, ++ 1974 => GArcBytes, ++ 2010 => GEllipseBytes, ++ _ => 0, ++ }; ++ if (length == 0 || remaining.Length < length) return false; ++ remaining = remaining[length..]; ++ } ++ // Extra bytes could include an unwalked face graph recovered by the ordinary decoder. ++ return remaining.IsEmpty; ++ } ++ ++ private static bool ReadCurveGroup(ref ReadOnlySpan bytes, scoped Span queue, ref int end) ++ { ++ if (bytes.Length < GInfoBytes + sizeof(int) ++ || BinaryPrimitives.ReadInt32LittleEndian(bytes[8..]) < -3_000_000) return false; ++ uint count = BinaryPrimitives.ReadUInt32LittleEndian(bytes[GInfoBytes..]); ++ bytes = bytes[(GInfoBytes + sizeof(int))..]; ++ if (count == uint.MaxValue) return true; ++ if (count > 64 || count > bytes.Length / sizeof(int)) return false; ++ for (uint index = 0; index < count; index++) ++ { ++ if (bytes.Length < sizeof(int)) return false; ++ int handle = BinaryPrimitives.ReadInt32LittleEndian(bytes); ++ bytes = bytes[sizeof(int)..]; ++ if (handle == 0) continue; ++ if (bytes.Length < sizeof(ushort) || end == queue.Length) return false; ++ ushort cls = BinaryPrimitives.ReadUInt16LittleEndian(bytes); ++ if (cls is not (1736 or 1974 or 2010 or 2009)) return false; ++ queue[end++] = cls; ++ bytes = bytes[sizeof(ushort)..]; ++ } ++ return true; ++ } ++} +--- a/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs ++++ b/src/RvtIO/Parsing/GRepParserV2.MeshFaces.cs +@@ -1003,6 +1003,19 @@ + return Enumerable.Range(0, 3).Select(k => local[0] * (c * s.X[k] + sn * s.Y[k]) + local[2] * s.Z[k]).ToArray(); + } + ++ internal sealed class MeridianProfile(double[] origin, double[] x, double[] y, double[] z, ArcRec curve) ++ { ++ private readonly SurfaceRec frame = new() { O = origin, X = x, Y = y, Z = z }; ++ internal double[] Origin => frame.O; ++ internal double[] Radial => frame.X; ++ internal double[] Transverse => frame.Y; ++ internal double[] Axis => frame.Z; ++ internal ArcRec Curve { get; } = curve; ++ ++ internal double[] Evaluate(double u) => MeshMeridian(frame, Curve.Eval(u)) ++ .Select((value, k) => value + frame.O[k]).ToArray(); ++ } ++ + internal static RevolvedSurface MeshRevolvedSurfaceOf(SurfaceRec s, ArcRec profile, bool normalReversed) + { + // a left handed frame (Z against X x Y): Revit turns about Z and sees the rotation +@@ -1019,11 +1032,12 @@ + { + // the profile point (x,., z) of the local frame: x along the radial direction at the + // rotation 0, z along the axis +- var local = profile; ++ var recipe = new MeridianProfile(s.O, s.X, s.Y, s.Z, profile); + return new RevolvedSurface + { + Origin = s.O, Axis = axis, V0 = 0, U0 = 0, GeEnvelope = [env[1], env[3], rotLo, rotHi], NormalReversed = normalReversed, +- ProfileAt = u => MeshMeridian(s, local.Eval(u)).Select((x, k) => x + s.O[k]).ToArray(), ++ ProfileAt = recipe.Evaluate, ++ ProfileRecipe = recipe, + }; + } + return profile.R == 0 +--- a/src/RvtIO/Parsing/PartitionFraming.cs ++++ b/src/RvtIO/Parsing/PartitionFraming.cs +@@ -92,7 +92,7 @@ + /// Walks the stream; sees every record of every block in file order. Returns false + /// with the reason in when the framing does not hold. is 4 or 8. + internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onRecord, out string? failure, out int blocks, +- List? segmentLengths = null, List? segmentBytes = null) ++ List? segmentLengths = null, List? segmentBytes = null, Func? inflateBatch = null) + { + failure = null; + blocks = 0; +@@ -102,7 +102,8 @@ + Require(input.U32() == 9 && input.U32() == 0, "format"); + var keys = new HashSet(); + var scratch = new InflateScratch(); +- using var prefetch = segmentBytes == null || OperatingSystem.IsBrowser() ? null : new SegmentPrefetch(tags); ++ using var prefetch = segmentBytes == null || (OperatingSystem.IsBrowser() && inflateBatch == null) ++ ? null : new SegmentPrefetch(tags, inflateBatch); + long inflated = 0; // output of all finished chains + while (true) + { +@@ -222,7 +223,7 @@ + + // A verified member is independent of its neighbours. Look ahead only for work + // scheduling, then let the main cursor commit records and report failures in order. +- private sealed class SegmentPrefetch(Tags tags) : IDisposable ++ private sealed class SegmentPrefetch(Tags tags, Func? inflateBatch) : IDisposable + { + private const int BatchSize = 128; + private const int BatchBytes = 32 * 1024 * 1024; +@@ -231,6 +232,7 @@ + private readonly string?[] _errors = new string?[BatchSize]; + private readonly ThreadLocal _scratch = new(() => new InflateScratch()); + private int _next; ++ private bool _browserUnavailable; + + internal bool Prepare(Cursor input) + { +@@ -253,6 +255,7 @@ + _batch.Clear(); + _next = 0; + long expectedBytes = 0; ++ if (_browserUnavailable) return; + while (_batch.Count < BatchSize && cursor.Remaining >= 18) + { + int position = cursor.Position; +@@ -266,13 +269,24 @@ + var member = cursor.Take((int)size - 8); + if (cursor.U16() != tags.SegmentCheckback || cursor.U32() != size + || !member.Span[..10].SequenceEqual(GzipHeader)) break; +- expectedBytes += BinaryPrimitives.ReadUInt32LittleEndian(member.Span[^4..]); +- if (expectedBytes > BatchBytes) break; ++ long nextExpected = expectedBytes + BinaryPrimitives.ReadUInt32LittleEndian(member.Span[^4..]); ++ if (nextExpected > BatchBytes) break; ++ expectedBytes = nextExpected; + _batch.Add((position, member)); + } + if (_batch.Count <= 1) + { + _batch.Clear(); ++ return; ++ } ++ ++ if (inflateBatch != null) ++ { ++ if (!TryBrowserInflate(inflateBatch, (int)expectedBytes)) ++ { ++ _browserUnavailable = true; ++ _batch.Clear(); ++ } + return; + } + +@@ -292,6 +306,35 @@ + _errors[index] = exception.Message; + } + }); ++ } ++ ++ private bool TryBrowserInflate(Func dispatch, int expectedBytes) ++ { ++ long inputLength = 4 + 4 * _batch.Count; ++ foreach (var entry in _batch) inputLength += entry.Payload.Length; ++ if (expectedBytes <= 0 || inputLength > BatchBytes) return false; ++ ++ var input = GC.AllocateUninitializedArray((int)inputLength); ++ BinaryPrimitives.WriteInt32LittleEndian(input, _batch.Count); ++ int position = 4 + 4 * _batch.Count; ++ for (int i = 0; i < _batch.Count; i++) ++ { ++ var member = _batch[i].Payload.Span; ++ BinaryPrimitives.WriteInt32LittleEndian(input.AsSpan(4 + i * 4), member.Length); ++ member.CopyTo(input.AsSpan(position)); ++ position += member.Length; ++ } ++ ++ var result = dispatch(input); ++ if (result.Length != expectedBytes) return false; ++ position = 0; ++ for (int i = 0; i < _batch.Count; i++) ++ { ++ int length = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(_batch[i].Payload.Span[^4..])); ++ _decoded[i] = result.AsSpan(position, length).ToArray(); ++ position += length; ++ } ++ return true; + } + + public void Dispose() => _scratch.Dispose(); +--- /dev/null ++++ b/src/RvtIO/Parsing/R22Transcoder.BrowserRanges.cs +@@ -0,0 +1,150 @@ ++namespace RvtIO.Parsing; ++ ++internal sealed partial class R22Transcoder ++{ ++ internal static R22Transcoder CreateBrowserRangeWorker(SchemaDocument source, SchemaDocument target, int width, bool trackIds) ++ => new(new R22Transcoder(source, target, width), trackIds); ++ ++ internal byte[] EncodeBrowserRange(byte[] input, byte[] plan) ++ { ++ const int entryBytes = 3 * sizeof(int); ++ if (plan.Length == 0 || plan.Length % entryBytes != 0) ++ throw new InvalidDataException("Incomplete R22 range plan."); ++ using var reader = new BinaryReader(new MemoryStream(plan, writable: false)); ++ var items = new List(plan.Length / entryBytes); ++ int position = 0; ++ while (reader.BaseStream.Position < reader.BaseStream.Length) ++ { ++ int offset = reader.ReadInt32(), length = reader.ReadInt32(), kind = reader.ReadInt32(); ++ if (offset != position || length <= 0 || length > input.Length - position ++ || (uint)kind > (uint)StreamItemKind.SectionEnd) ++ throw new InvalidDataException("Invalid R22 range entry."); ++ var item = new StreamItem(offset, length, (StreamItemKind)kind); ++ bool valid = item.Kind switch ++ { ++ StreamItemKind.Record => TryRecord(input, offset, _sourceWidth, out int actual) && length == actual, ++ StreamItemKind.Block or StreamItemKind.RootBlock => TryBlock(input, offset, _sourceWidth, out int actual) && length == actual, ++ StreamItemKind.Separator => length == _sourceWidth + 8, ++ _ => length == _sourceWidth + 12, ++ }; ++ if (!valid) throw new InvalidDataException("R22 range entry has an invalid size."); ++ items.Add(item); ++ position += length; ++ } ++ if (position != input.Length) throw new InvalidDataException("R22 range has unplanned bytes."); ++ ++ RangeResult result; ++ try { result = RewriteRange(input, items, 0, items.Count); } ++ catch (NeedsRemapping) { return []; } ++ ++ using var output = new MemoryStream(); ++ using var writer = new BinaryWriter(output); ++ var stats = result.Stats; ++ writer.Write(stats.Records); ++ writer.Write(stats.RecordsRewritten); ++ writer.Write(stats.RootBlocks); ++ writer.Write(stats.RootBlocksRewritten); ++ writer.Write(stats.OtherBlocks); ++ writer.Write(stats.OtherBlocksRewritten); ++ writer.Write(stats.Failures.Count); ++ foreach (var (reason, count) in stats.Failures) ++ { ++ writer.Write(reason); ++ writer.Write(count); ++ } ++ writer.Write(result.Ids?.Length ?? 0); ++ if (result.Ids != null) ++ foreach (int id in result.Ids) writer.Write(id); ++ foreach (int end in result.Ends) writer.Write(end); ++ writer.Write(result.Bytes.Span); ++ return output.ToArray(); ++ } ++ ++ private RangeResult?[]? RewriteBrowserRanges(byte[] source, List items, List<(int First, int End)> ranges, ++ Func dispatch) ++ { ++ using var plan = new MemoryStream(); ++ using var writer = new BinaryWriter(plan); ++ writer.Write(ranges.Count); ++ foreach (var (first, end) in ranges) ++ { ++ int start = items[first].Start; ++ var last = items[end - 1]; ++ writer.Write(start); ++ writer.Write(last.Start + last.Length - start); ++ writer.Write(end - first); ++ for (int i = first; i < end; i++) ++ { ++ var item = items[i]; ++ writer.Write(item.Start - start); ++ writer.Write(item.Length); ++ writer.Write((int)item.Kind); ++ } ++ } ++ var bytes = dispatch(source, plan.ToArray()); ++ if (bytes.Length == 0) return null; ++ ++ var results = new RangeResult?[ranges.Count]; ++ using var input = new MemoryStream(bytes, writable: false); ++ using var reader = new BinaryReader(input); ++ try ++ { ++ while (input.Position < input.Length) ++ { ++ int index = reader.ReadInt32(), length = reader.ReadInt32(); ++ if ((uint)index >= (uint)ranges.Count || results[index] != null || length <= 0 ++ || length > input.Length - input.Position) ++ throw new InvalidDataException("Invalid R22 range result header."); ++ var range = ranges[index]; ++ results[index] = ReadBrowserRange(bytes, (int)input.Position, length, range.End - range.First, _ids != null); ++ input.Position += length; ++ } ++ if (Array.Exists(results, result => result == null)) ++ throw new InvalidDataException("Missing R22 range result."); ++ return results; ++ } ++ catch (Exception error) when (error is IOException or InvalidDataException or FormatException or ArgumentException) ++ { ++ Console.WriteLine($"IOExtend R22 browser range result ignored: {error.Message}"); ++ return null; ++ } ++ } ++ ++ private static RangeResult ReadBrowserRange(byte[] bytes, int start, int length, int items, bool trackIds) ++ { ++ using var input = new MemoryStream(bytes, start, length, writable: false); ++ using var reader = new BinaryReader(input); ++ var stats = new Stats ++ { ++ Records = reader.ReadInt32(), RecordsRewritten = reader.ReadInt32(), ++ RootBlocks = reader.ReadInt32(), RootBlocksRewritten = reader.ReadInt32(), ++ OtherBlocks = reader.ReadInt32(), OtherBlocksRewritten = reader.ReadInt32(), ++ }; ++ int failures = reader.ReadInt32(); ++ if ((uint)failures > (uint)items) throw new InvalidDataException("Invalid R22 failure count."); ++ for (int i = 0; i < failures; i++) ++ stats.Failures.Add(reader.ReadString(), reader.ReadInt32()); ++ int keys = reader.ReadInt32(); ++ if (keys < 0 || (!trackIds && keys != 0) || keys > (input.Length - input.Position) / sizeof(int)) ++ throw new InvalidDataException("Invalid R22 key count."); ++ int[]? ids = keys == 0 ? null : new int[keys]; ++ if (ids != null) ++ for (int i = 0; i < ids.Length; i++) ++ { ++ int id = reader.ReadInt32(); ++ if (id <= 0) throw new InvalidDataException("Invalid identity key."); ++ ids[i] = id; ++ } ++ ++ var ends = new int[items + 1]; ++ for (int i = 0; i < ends.Length; i++) ++ { ++ ends[i] = reader.ReadInt32(); ++ if ((i == 0 && ends[i] != 0) || (i > 0 && ends[i] <= ends[i - 1])) ++ throw new InvalidDataException("Invalid R22 output position."); ++ } ++ if (ends[^1] != input.Length - input.Position) ++ throw new InvalidDataException("R22 output length differs."); ++ return new(bytes.AsMemory(start + (int)input.Position, ends[^1]), ends, stats, ids); ++ } ++} +--- a/src/RvtIO/Parsing/R22Transcoder.cs ++++ b/src/RvtIO/Parsing/R22Transcoder.cs +@@ -1,4 +1,5 @@ + using System.Buffers.Binary; ++using System.Runtime.InteropServices; + + namespace RvtIO.Parsing; + +@@ -15,7 +16,7 @@ + /// to the payload bytes. A block that cannot be rewritten (unknown class at the root, an extensible-storage blob, a field of a + /// class the 2022 table lacks) keeps its bytes with the root class tag 0xFFFE, which no reader recognises. + /// +-internal sealed class R22Transcoder ++internal sealed partial class R22Transcoder + { + internal const ushort UnknownTag = 0xFFFE; + +@@ -30,11 +31,17 @@ + private readonly int _sourceWidth; + private readonly int _sourceIdentifier; + private readonly ElementIdMap? _ids; ++ private readonly HashSet? _identityIds; ++ private readonly bool _bulkScalars = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_BULK_R22_SCALARS") == "1"; + private readonly Dictionary _plans = new(); ++ private readonly Dictionary _sourceChains = new(); + + /// Source fields in serialization order, the target class of the same name and the target field positions by (declaring class, field). + private sealed record Plan((SchemaClass Declaring, SchemaField Field)[] Source, (SchemaClass Declaring, SchemaField Field)[] Target, +- int[] TargetIndex, bool[] TargetPresent, bool Reordered, bool[] Narrow); ++ int[] TargetIndex, bool[] TargetPresent, int[]? SourceByTarget, bool[] Narrow) ++ { ++ internal readonly byte[]?[] Defaults = new byte[Target.Length][]; ++ } + + internal R22Transcoder(SchemaDocument source, SchemaDocument target, int sourceIdWidth, ElementIdMap? ids = null) + { +@@ -55,31 +62,39 @@ + + /// The chunks of one partition stream in the 2022 layout, cut at item boundaries; the input is the same stream + /// concatenated. Bytes outside the section grammar are copied as they are. +- internal List Stream(IReadOnlyList chunks, out Stats stats) ++ internal List Stream(IReadOnlyList chunks, out Stats stats, bool parallel = false, ++ Func? browserRewrite = null) + { + long total = 0; + foreach (var c in chunks) total += c.Length; + var buf = new byte[total]; + long off = 0; + foreach (var c in chunks) { Buffer.BlockCopy(c, 0, buf, (int)off, c.Length); off += c.Length; } ++ if ((parallel || browserRewrite != null) && TryParallelStream(buf, browserRewrite, out var rewritten, out var parallelStats)) ++ { ++ stats = parallelStats; ++ return rewritten; ++ } ++ ++ using var output = new MemoryStream(); + var result = new List(); +- var output = new MemoryStream(); +- stats = new Stats(); +- int w = _sourceWidth; +- int n = buf.Length, p = 0; +- void Flush(bool force) +- { +- if (output.Length > 0 && (force || output.Length >= 1 << 20)) { result.Add(output.ToArray()); output.SetLength(0); } +- } +- void Separator(int length, bool counted) +- { +- // ff*W [u32 k]? 00*8 in the source width, ff*4 ... in the target width +- var sep = new byte[(counted ? 4 : 0) + 4 + 8]; +- sep.AsSpan(0, 4).Fill(0xFF); +- if (counted) BinaryPrimitives.WriteUInt32LittleEndian(sep.AsSpan(4), BitConverter.ToUInt32(buf, p + w)); +- output.Write(sep); +- p += length; +- } ++ var sequentialStats = new Stats(); ++ int stop = ScanStream(buf, item => ++ { ++ WriteStreamItem(buf, item, output, sequentialStats); ++ FlushAfterItem(output, result, item.Kind); ++ }); ++ FinishStream(buf, stop, output, result, sequentialStats); ++ stats = sequentialStats; ++ return result; ++ } ++ ++ private enum StreamItemKind { Record, RootBlock, Block, Separator, CountedSeparator, SectionEnd } ++ private readonly record struct StreamItem(int Start, int Length, StreamItemKind Kind); ++ ++ private int ScanStream(byte[] buf, Action visit) ++ { ++ int w = _sourceWidth, n = buf.Length, p = 0; + bool IsSeparator(int at) => at + w <= n && buf.AsSpan(at, w).IndexOfAnyExcept((byte)0xFF) < 0; + bool HasRecordlessSectionAhead(int at) + { +@@ -97,38 +112,81 @@ + int recordsAt = p; + while (p + w + 8 <= n && !IsSeparator(p) && TryRecord(buf, p, w, out int length)) + { +- WriteRecord(buf, p, output, stats); ++ visit(new(p, length, StreamItemKind.Record)); + p += length; +- Flush(false); + } + if (!IsSeparator(p) || p + w + 8 > n || (p == recordsAt && !HasRecordlessSectionAhead(p))) break; +- Separator(w + 8, false); ++ visit(new(p, w + 8, StreamItemKind.Separator)); ++ p += w + 8; + // root blocks + while (p + w + 12 <= n && !IsSeparator(p) && TryBlock(buf, p, w, out int length)) + { +- WriteBlock(buf, p, output, stats, root: true); ++ visit(new(p, length, StreamItemKind.RootBlock)); + p += length; +- Flush(false); + } + if (!IsSeparator(p) || p + w + 12 > n) break; +- Separator(w + 12, true); ++ visit(new(p, w + 12, StreamItemKind.CountedSeparator)); ++ p += w + 12; + // second blocks (one per record: placeholders and geometry) + while (p + w + 12 <= n && !IsSeparator(p) && TryBlock(buf, p, w, out int length)) + { +- WriteBlock(buf, p, output, stats, root: false); ++ visit(new(p, length, StreamItemKind.Block)); + p += length; +- Flush(false); + } + if (!IsSeparator(p) || p + w + 12 > n) break; +- Separator(w + 12, true); +- Flush(true); +- } +- if (p < n) output.Write(buf, p, n - p); +- Flush(true); +- stats.UnparsedBytes = n - p; +- stats.StoppedAt = p; +- if (p < n) stats.StoppedBytes = Convert.ToHexString(buf, p, Math.Min(48, n - p)); +- return result; ++ visit(new(p, w + 12, StreamItemKind.SectionEnd)); ++ p += w + 12; ++ } ++ return p; ++ } ++ ++ private void WriteStreamItem(byte[] buf, StreamItem item, MemoryStream output, Stats stats) ++ { ++ switch (item.Kind) ++ { ++ case StreamItemKind.Record: ++ WriteRecord(buf, item.Start, output, stats); ++ break; ++ case StreamItemKind.RootBlock: ++ case StreamItemKind.Block: ++ WriteBlock(buf, item.Start, output, stats, root: item.Kind == StreamItemKind.RootBlock); ++ break; ++ default: ++ // ff*W [u32 k]? 00*8 in the source width, ff*4 ... in the target width ++ var sep = new byte[item.Kind == StreamItemKind.Separator ? 12 : 16]; ++ sep.AsSpan(0, 4).Fill(0xFF); ++ if (sep.Length == 16) ++ BinaryPrimitives.WriteUInt32LittleEndian(sep.AsSpan(4), BitConverter.ToUInt32(buf, item.Start + _sourceWidth)); ++ output.Write(sep); ++ break; ++ } ++ } ++ ++ private static void FlushAfterItem(MemoryStream output, List result, StreamItemKind kind) ++ { ++ if (kind == StreamItemKind.SectionEnd) ++ FlushStreamChunk(output, result); ++ else if (kind is StreamItemKind.Record or StreamItemKind.RootBlock or StreamItemKind.Block && output.Length >= 1 << 20) ++ FlushStreamChunk(output, result); ++ } ++ ++ private static void FlushStreamChunk(MemoryStream output, List result) ++ { ++ if (output.Length == 0) return; ++ result.Add(output.ToArray()); ++ output.SetLength(0); ++ } ++ ++ private static void FinishStream(byte[] buf, int stop, MemoryStream output, List result, Stats stats) ++ { ++ if (stop < buf.Length) ++ { ++ output.Write(buf, stop, buf.Length - stop); ++ stats.StoppedBytes = Convert.ToHexString(buf, stop, Math.Min(48, buf.Length - stop)); ++ } ++ FlushStreamChunk(output, result); ++ stats.UnparsedBytes = buf.Length - stop; ++ stats.StoppedAt = stop; + } + + /// The channel-102 and 103 records of the project's own block of one framed stream in the 2022 layout, each rewritten as +@@ -159,6 +217,7 @@ + internal sealed class Stats + { + public int Records, RecordsRewritten, RootBlocks, RootBlocksRewritten, OtherBlocks, OtherBlocksRewritten; ++ public int ParallelRanges; + public long UnparsedBytes; + public long StoppedAt; + public string? StoppedBytes; +@@ -188,8 +247,8 @@ + private void WriteId(byte[] b, int p, MemoryStream output) + { + Span id = stackalloc byte[4]; +- uint key = _ids != null && _sourceWidth == 8 +- ? unchecked((uint)_ids.Key(BitConverter.ToInt64(b, p))) : BitConverter.ToUInt32(b, p); ++ uint key = HasIdMap && _sourceWidth == 8 ++ ? unchecked((uint)MapId(BitConverter.ToInt64(b, p))) : BitConverter.ToUInt32(b, p); + BinaryPrimitives.WriteUInt32LittleEndian(id, key); + output.Write(id); + } +@@ -251,11 +310,21 @@ + + private static uint Adler32(byte[] data) + { ++ const uint modulus = 65521; ++ // At most 5552 bytes can be accumulated before the unsigned 32-bit sum could overflow. ++ const int batch = 5552; + uint a = 1, b = 0; +- foreach (byte x in data) +- { +- a = (a + x) % 65521; +- b = (b + a) % 65521; ++ for (int offset = 0; offset < data.Length;) ++ { ++ int count = Math.Min(batch, data.Length - offset); ++ foreach (byte value in data.AsSpan(offset, count)) ++ { ++ a += value; ++ b += a; ++ } ++ a %= modulus; ++ b %= modulus; ++ offset += count; + } + return (b << 16) | a; + } +@@ -318,7 +387,7 @@ + failure = _source[rootClass].Name + ": " + fail.Message; + return null; + } +- try { return Apply(data, offset, offset + size, c.Edits); } ++ try { return Apply(data, offset, offset + size, CollectionsMarshal.AsSpan(c.Edits)); } + catch (Fail fail) + { + failure = _source[rootClass].Name + ": " + fail.Message; +@@ -327,12 +396,24 @@ + } + + /// The bytes [start, end) with the edits applied (insertions sort before the replacement that starts at the same place). +- private static byte[] Apply(byte[] data, int start, int end, List edits) +- { +- var ordered = edits.OrderBy(e => e.Start).ThenBy(e => e.End > e.Start ? 1 : 0).ToList(); +- var output = new byte[end - start + ordered.Sum(e => e.Replacement.Length - (e.End - e.Start))]; ++ private static byte[] Apply(byte[] data, int start, int end, ReadOnlySpan edits) ++ { ++ int length = end - start; ++ bool ordered = true; ++ int previousEnd = start; ++ foreach (var edit in edits) ++ { ++ length += edit.Replacement.Length - (edit.End - edit.Start); ++ ordered &= edit.Start >= previousEnd; ++ previousEnd = edit.End; ++ } ++ // Array counts are occasionally rewritten after their contents. Keep insertion order ++ // at a shared offset and move insertions ahead of the replacement. ++ if (!ordered) ++ edits = edits.ToArray().OrderBy(e => e.Start).ThenBy(e => e.End > e.Start ? 1 : 0).ToArray(); ++ var output = new byte[length]; + int at = 0, source = start; +- foreach (var e in ordered) ++ foreach (var e in edits) + { + int gap = e.Start - source; + if (gap < 0 || e.End > end) throw new Fail("overlapping edits"); +@@ -357,7 +438,7 @@ + { + if (_plans.TryGetValue(sourceClass, out var plan)) return plan; + if (!_tagMap.TryGetValue(sourceClass, out int targetClass)) throw new Fail("class without a 2022 counterpart"); +- var source = Chain(_source, sourceClass); ++ var source = SourceChain(sourceClass); + var target = Chain(_target, targetClass); + var index = new Dictionary<(string, string), int>(); + for (int i = 0; i < target.Length; i++) index[(target[i].Declaring.Name, target[i].Field.Name)] = i; +@@ -382,9 +463,20 @@ + if (narrow[i]) present[targetIndex[i]] = true; + // the fields both classes have are stored in another order (Revit 2024 and later store many classes in a changed order) + var kept = targetIndex.Where(k => k >= 0).ToArray(); +- bool reordered = kept.Zip(kept.Skip(1), (a, b) => b < a).Any(x => x); +- return _plans[sourceClass] = new Plan(source, target, targetIndex, present, reordered, narrow); +- } ++ int[]? sourceByTarget = null; ++ if (kept.Zip(kept.Skip(1), (a, b) => b < a).Any(x => x)) ++ { ++ sourceByTarget = new int[target.Length]; ++ Array.Fill(sourceByTarget, -1); ++ for (int i = 0; i < targetIndex.Length; i++) ++ if (targetIndex[i] >= 0) sourceByTarget[targetIndex[i]] = i; ++ } ++ return _plans[sourceClass] = new Plan(source, target, targetIndex, present, sourceByTarget, narrow); ++ } ++ ++ private (SchemaClass Declaring, SchemaField Field)[] SourceChain(int sourceClass) => ++ _sourceChains.TryGetValue(sourceClass, out var fields) ++ ? fields : _sourceChains[sourceClass] = Chain(_source, sourceClass); + + private static (SchemaClass Declaring, SchemaField Field)[] Chain(Dictionary classes, int id) + { +@@ -403,7 +495,7 @@ + { + if (c.Cutting) + { +- foreach (var (_, field) in Chain(_source, sourceClass)) ReadField(c, field, 0); ++ foreach (var (_, field) in SourceChain(sourceClass)) ReadField(c, field, 0); + return; + } + ReadFields(c, sourceClass, 0); +@@ -415,7 +507,8 @@ + { + var plan = PlanOf(sourceClass); + int regionStart = c.Pos, regionEdits = c.Edits.Count; +- var spans = new (int Start, int End, int EditFrom, int EditTo)[plan.Source.Length]; ++ var bySource = plan.SourceByTarget; ++ var spans = bySource == null ? null : new (int Start, int End, int EditFrom, int EditTo)[plan.Source.Length]; + int last = -1, lastQueuing = -1; + for (int i = 0; i < plan.Source.Length; i++) + { +@@ -429,20 +522,19 @@ + c.Cutting = false; + c.Edits.RemoveRange(editFrom, c.Edits.Count - editFrom); + c.Edits.Add(new(start, c.Pos, [])); +- spans[i] = (-1, -1, 0, 0); + continue; + } +- if (!plan.Reordered) ++ if (bySource == null) + { + for (int j = last + 1; j < k; j++) +- if (!plan.TargetPresent[j]) c.Edits.Add(new(start, start, Default(plan.Target[j]))); ++ if (!plan.TargetPresent[j]) c.Edits.Add(new(start, start, Default(plan, j))); + last = Math.Max(last, k); + editFrom = c.Edits.Count; + } + c.Narrow = plan.Narrow[i]; + ReadField(c, plan.Source[i].Field, depth); + c.Narrow = false; +- spans[i] = (start, c.Pos, editFrom, c.Edits.Count); ++ if (spans != null) spans[i] = (start, c.Pos, editFrom, c.Edits.Count); + if (c.Queue.Count != queued) + { + // the objects of the pointers follow in the order of the fields: they cannot change places +@@ -450,26 +542,26 @@ + lastQueuing = k; + } + } +- if (!plan.Reordered) ++ if (bySource == null) + { + for (int j = last + 1; j < plan.Target.Length; j++) +- if (!plan.TargetPresent[j]) c.Edits.Add(new(c.Pos, c.Pos, Default(plan.Target[j]))); ++ if (!plan.TargetPresent[j]) c.Edits.Add(new(c.Pos, c.Pos, Default(plan, j))); + return; + } +- var bySource = new int[plan.Target.Length]; +- Array.Fill(bySource, -1); +- for (int i = 0; i < plan.Source.Length; i++) +- if (plan.TargetIndex[i] >= 0) bySource[plan.TargetIndex[i]] = i; +- var composed = new MemoryStream(); ++ using var composed = new MemoryStream(); ++ var edits = CollectionsMarshal.AsSpan(c.Edits); + for (int j = 0; j < plan.Target.Length; j++) + { +- if (bySource[j] < 0) { composed.Write(Default(plan.Target[j])); continue; } +- var (start, end, from, to) = spans[bySource[j]]; +- composed.Write(Apply(c.D, start, end, c.Edits.GetRange(from, to - from))); ++ if (bySource[j] < 0) { composed.Write(Default(plan, j)); continue; } ++ var (start, end, from, to) = spans![bySource[j]]; ++ if (from == to) composed.Write(c.D.AsSpan(start, end - start)); ++ else composed.Write(Apply(c.D, start, end, edits[from..to])); + } + c.Edits.RemoveRange(regionEdits, c.Edits.Count - regionEdits); + c.Edits.Add(new(regionStart, c.Pos, composed.ToArray())); + } ++ ++ private byte[] Default(Plan plan, int index) => plan.Defaults[index] ??= Default(plan.Target[index]); + + + private static int Take(Context c, int n) +@@ -488,7 +580,9 @@ + if (hi == 6) { ReadScalar(c, f, depth); return; } + if (hi == 1) + { +- for (int i = 0; i < (f.Fixed ?? 0); i++) ReadScalar(c, f, depth); ++ int count = f.Fixed.GetValueOrDefault(); ++ if (_bulkScalars && TryTakeFixedScalars(c, f.Type, count)) return; ++ for (int i = 0; i < count; i++) ReadScalar(c, f, depth); + return; + } + if (hi == 5) +@@ -498,6 +592,7 @@ + if (n == 0xFFFFFFFF) n = 0; + if (n > 5_000_000) throw new Fail("count"); + if (f.Type is 1 or 2 && (f.Mods & 15) == 0) { Take(c, (int)n); return; } ++ if (_bulkScalars && TryTakeFixedScalars(c, f.Type, (int)n)) return; + int before = c.Dropped; + bool outer = c.InArray; + c.InArray = true; +@@ -507,6 +602,24 @@ + return; + } + ReadScalar(c, f, depth); ++ } ++ ++ private static bool TryTakeFixedScalars(Context c, byte type, int count) ++ { ++ int width = type switch ++ { ++ 1 or 2 => 1, ++ 3 => 2, ++ 4 or 5 or 6 => 4, ++ 7 => 8, ++ 9 => 16, ++ _ => 0, ++ }; ++ if (width == 0) return false; ++ if (count <= 0) return true; ++ if (count > (c.End - c.Pos) / width) throw new Fail("end of payload"); ++ c.Pos += count * width; ++ return true; + } + + private void ReadScalar(Context c, SchemaField f, int depth) +@@ -550,6 +663,7 @@ + case 13: + { + if (f.Args is not { Count: 1 } args || args[0].Fixed is not int count) throw new Fail("template field"); ++ if (_bulkScalars && TryTakeFixedScalars(c, args[0].Type, count)) return; + var item = args[0] with { Mods = (byte)(args[0].Mods & 15) }; + for (int i = 0; i < count; i++) ReadScalar(c, item, depth); + return; +@@ -578,8 +692,8 @@ + if (_sourceWidth == 8 && !c.Cutting) + { + long id = BitConverter.ToInt64(c.D, p); +- if (_ids == null && (id < int.MinValue || id > int.MaxValue)) throw new Fail("id beyond 32 bits"); +- c.Edits.Add(new(p, p + 8, BitConverter.GetBytes(_ids?.Key(id) ?? (int)id))); ++ if (!HasIdMap && (id < int.MinValue || id > int.MaxValue)) throw new Fail("id beyond 32 bits"); ++ c.Edits.Add(new(p, p + 8, BitConverter.GetBytes(HasIdMap ? MapId(id) : (int)id))); + } + return; + } +--- /dev/null ++++ b/src/RvtIO/Parsing/R22Transcoder.Parallel.cs +@@ -0,0 +1,119 @@ ++namespace RvtIO.Parsing; ++ ++internal sealed partial class R22Transcoder ++{ ++ private sealed class NeedsRemapping : Exception; ++ ++ private readonly record struct RangeResult(ReadOnlyMemory Bytes, int[] Ends, Stats Stats, int[]? Ids); ++ ++ private R22Transcoder(R22Transcoder source, bool trackIds) ++ { ++ _source = source._source; ++ _target = source._target; ++ _targetByName = source._targetByName; ++ _tagMap = source._tagMap; ++ _sourceWidth = source._sourceWidth; ++ _sourceIdentifier = source._sourceIdentifier; ++ _bulkScalars = source._bulkScalars; ++ if (trackIds) _identityIds = []; ++ } ++ ++ private bool HasIdMap => _ids != null || _identityIds != null; ++ ++ private int MapId(long id) ++ { ++ if (_identityIds == null) return _ids!.Key(id); ++ if (id is < int.MinValue or > int.MaxValue) throw new NeedsRemapping(); ++ int key = (int)id; ++ if (key > 0) _identityIds.Add(key); ++ return key; ++ } ++ ++ private bool TryParallelStream(byte[] source, Func? browserRewrite, ++ out List result, out Stats stats) ++ { ++ const int rangeBytes = 1024 * 1024; ++ result = []; ++ stats = new(); ++ if (_ids?.HasRemappedIds == true || source.Length > 128 * rangeBytes ++ || (browserRewrite != null && source.Length < 8 * rangeBytes)) return false; ++ ++ var items = new List(); ++ int stop = ScanStream(source, items.Add); ++ var ranges = new List<(int First, int End)>(); ++ int first = 0; ++ for (int i = 0; i < items.Count; i++) ++ { ++ var item = items[i]; ++ if (item.Start + item.Length - items[first].Start < rangeBytes && i + 1 < items.Count) continue; ++ ranges.Add((first, i + 1)); ++ first = i + 1; ++ } ++ if (ranges.Count < 2) return false; ++ ++ var rewrites = browserRewrite == null ++ ? RewriteNativeRanges(source, items, ranges) ++ : RewriteBrowserRanges(source, items, ranges, browserRewrite); ++ if (rewrites == null) return false; ++ ++ using var output = new MemoryStream(); ++ for (int index = 0; index < rewrites.Length; index++) ++ { ++ var range = rewrites[index]!.Value; ++ if (range.Ids != null) ++ foreach (int id in range.Ids) _ids!.Key(id); ++ MergeRangeStats(stats, range.Stats); ++ for (int i = 0; i + 1 < range.Ends.Length; i++) ++ { ++ output.Write(range.Bytes.Span[range.Ends[i]..range.Ends[i + 1]]); ++ FlushAfterItem(output, result, items[ranges[index].First + i].Kind); ++ } ++ } ++ stats.ParallelRanges = ranges.Count; ++ FinishStream(source, stop, output, result, stats); ++ return true; ++ } ++ ++ private RangeResult?[]? RewriteNativeRanges(byte[] source, List items, List<(int First, int End)> ranges) ++ { ++ var rewrites = new RangeResult?[ranges.Count]; ++ var loop = Parallel.For(0, ranges.Count, new ParallelOptions { MaxDegreeOfParallelism = 4 }, ++ () => new R22Transcoder(this, trackIds: _ids != null), ++ (index, state, worker) => ++ { ++ var (begin, end) = ranges[index]; ++ try { rewrites[index] = worker.RewriteRange(source, items, begin, end); } ++ catch (NeedsRemapping) { state.Stop(); } ++ return worker; ++ }, ++ _ => { }); ++ // A worker cannot allocate aliases out of order. The serial pass starts from the untouched ID map. ++ return loop.IsCompleted ? rewrites : null; ++ } ++ ++ private RangeResult RewriteRange(byte[] source, List items, int first, int end) ++ { ++ _identityIds?.Clear(); ++ using var output = new MemoryStream(); ++ var ends = new int[end - first + 1]; ++ var stats = new Stats(); ++ for (int i = first; i < end; i++) ++ { ++ WriteStreamItem(source, items[i], output, stats); ++ ends[i - first + 1] = checked((int)output.Length); ++ } ++ return new(output.ToArray(), ends, stats, _identityIds?.ToArray()); ++ } ++ ++ private static void MergeRangeStats(Stats output, Stats input) ++ { ++ output.Records += input.Records; ++ output.RecordsRewritten += input.RecordsRewritten; ++ output.RootBlocks += input.RootBlocks; ++ output.RootBlocksRewritten += input.RootBlocksRewritten; ++ output.OtherBlocks += input.OtherBlocks; ++ output.OtherBlocksRewritten += input.OtherBlocksRewritten; ++ foreach (var (reason, count) in input.Failures) ++ output.Failures[reason] = output.Failures.GetValueOrDefault(reason) + count; ++ } ++} +--- a/src/RvtIO/Parsing/RecordParser.cs ++++ b/src/RvtIO/Parsing/RecordParser.cs +@@ -6,6 +6,8 @@ + + internal static class RecordParser + { ++ private static readonly bool FastRecordResync = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_RECORD_CONTROL") != "1"; ++ + internal static bool ContainsAnchoredR22Record(byte[] chunk, IReadOnlySet knownIds) + { + int limit = chunk.Length - 11; +@@ -50,8 +52,14 @@ + { + int pos = 0; + bool aligned = false; +- while (pos + 12 <= chunk.Length) +- { ++ while (pos <= chunk.Length - 12) ++ { ++ if (FastRecordResync && !aligned) ++ { ++ int skip = chunk.AsSpan(pos + 8, chunk.Length - pos - 11).IndexOfAny((byte)0x3C, (byte)0xF8); ++ if (skip < 0) break; ++ pos += skip; ++ } + if (TryReadR22Header(chunk, pos, out uint elemId, out int recordSize)) + { + int next = pos + recordSize; +--- a/src/RvtIO/Parsing/TfBlockDeserializer.WallAuxiliaryFields.cs ++++ b/src/RvtIO/Parsing/TfBlockDeserializer.WallAuxiliaryFields.cs +@@ -2,6 +2,8 @@ + + internal static partial class TfBlockDeserializer + { ++ private static readonly Lazy OriginalWallAuxiliarySchemas = new(HasOriginalWallAuxiliarySchemas); ++ + // PairSerialization descriptor contracts. These correct missing concrete references + // only; the shared r22 descriptors are not modified. + private static bool TryReadOriginalWallAuxiliaryField(Cursor c, TfField f, +@@ -19,13 +21,13 @@ + }; + if (target != 0) + { +- if (depth > 40 || !HasOriginalWallAuxiliarySchemas()) throw Fail; ++ if (depth > 40 || !OriginalWallAuxiliarySchemas.Value) throw Fail; + ReadField(c, f with { Ref = target }, queue, depth, capture); + return true; + } + if (f.Declaring != 496 || f.Mods != 80 || f.Ref != null + || f.Name is not ("m_PatternPositionMap" or "m_substituteFaceMap")) return false; +- if (depth > 40 || !HasOriginalWallAuxiliarySchemas()) throw Fail; ++ if (depth > 40 || !OriginalWallAuxiliarySchemas.Value) throw Fail; + uint count = ReadU32(c); + if (count == uint.MaxValue) return true; + int valueClass = f.Name == "m_PatternPositionMap" ? 78 : 91; +@@ -74,3 +76,4 @@ + } + } + } ++ +--- a/src/RvtIO/Parsing/TfStreamWalker.Bounded.cs ++++ b/src/RvtIO/Parsing/TfStreamWalker.Bounded.cs +@@ -6,14 +6,17 @@ + // next item. Only the original logical segment boundaries reset alignment. + internal static void WalkBounded(IReadOnlyList chunks, HashSet knownIds, + BlockVisitor visit, RecordVisitor? visitRecord, SegmentSources sources, +- int segmentTarget = SegmentTarget, int windowSize = 64 * 1024 * 1024) ++ int segmentTarget = SegmentTarget, int windowSize = 64 * 1024 * 1024, ++ Action? progress = null) + { + if (segmentTarget <= 3 * MaxBlock) throw new ArgumentOutOfRangeException(nameof(segmentTarget)); + if (windowSize <= 0) throw new ArgumentOutOfRangeException(nameof(windowSize)); + + var offsets = new long[chunks.Count + 1]; + for (int i = 0; i < chunks.Count; i++) offsets[i + 1] = offsets[i] + chunks[i].Length; +- if (offsets[^1] == 0) return; ++ long total = offsets[^1]; ++ progress?.Invoke(0, total); ++ if (total == 0) return; + const int lookahead = 2 * MaxBlock; + var buffer = GC.AllocateUninitializedArray((int)Math.Min(offsets[^1], (long)windowSize + lookahead)); + +@@ -45,10 +48,12 @@ + offset = 0; + } + sources.SetSegment(chunks, source, chunk, (int)(offsets[source] - start)); ++ Action? report = progress == null ? null : offset => progress(start + offset, total); + resume = start + WalkWindow(buffer, length, (int)Math.Max(0, resume - start), +- (int)(end - start), ref aligned, knownIds, visit, visitRecord); ++ (int)(end - start), ref aligned, knownIds, visit, visitRecord, report); + } + segmentStart = visitEnd; + } ++ progress?.Invoke(total, total); + } + } +--- a/src/RvtIO/Parsing/TfStreamWalker.cs ++++ b/src/RvtIO/Parsing/TfStreamWalker.cs +@@ -140,7 +140,7 @@ + if (!it.HasValue) + { + aligned = false; +- pos = reportPosition == null ? NextPossibleItem(buf, n, pos + 1) : pos + 1; ++ pos = NextPossibleItem(buf, n, pos + 1, (int)Math.Min(visitLimit, nextReport)); + continue; + } + var (isBlock, size, eid, cls, dataSize) = it.Value; +@@ -154,30 +154,36 @@ + return pos; + } + +- // Skip only positions where the serialized size and both record markers rule out a header. +- // The anchor and size-echo checks still run on every candidate, including unaligned ones. +- private static int NextPossibleItem(byte[] data, int length, int position) +- { +- if (position <= length - 16 && BitConverter.ToUInt64(data, position) == 0 ++ // Scanning stops before a progress boundary. Header lookahead uses the full ++ // window so an item starting just before the boundary remains a candidate. ++ private static int NextPossibleItem(byte[] data, int length, int position, int stop) ++ { ++ int candidateLimit = Math.Min(stop, length - 15); ++ if (position < candidateLimit && BitConverter.ToUInt64(data, position) == 0 + && BitConverter.ToUInt64(data, position + 8) == 0) + { +- // No all-zero header can anchor. Keep starts whose header reaches the first nonzero byte. +- int nonzero = data.AsSpan(position + 16, length - position - 16).IndexOfAnyExcept((byte)0); +- if (nonzero < 0) return length - 15; ++ int nonzero = data.AsSpan(position + 16, candidateLimit - position - 1).IndexOfAnyExcept((byte)0); ++ if (nonzero < 0) return candidateLimit; + position += nonzero + 1; + } +- if (!BitConverter.IsLittleEndian || !Vector256.IsHardwareAccelerated) return position; +- int width = Vector256.Count; ++ if (!BitConverter.IsLittleEndian || !Vector128.IsHardwareAccelerated) return position; ++ int width = Vector128.Count; ++ int vectorLimit = Math.Min(stop, length - 11); ++ var blockSizeLimit = Vector128.Create((byte)16); ++ var r22Low = Vector128.Create((byte)0x3C); ++ var r22High = Vector128.Create((byte)0x05); ++ var r20Low = Vector128.Create((byte)0xF8); ++ var r20High = Vector128.Create((byte)0x04); + ref byte first = ref MemoryMarshal.GetArrayDataReference(data); +- for (; position <= length - 11 - width; position += width) +- { +- var low = Vector256.LoadUnsafe(ref first, (nuint)(position + 8)); +- var high = Vector256.LoadUnsafe(ref first, (nuint)(position + 9)); +- var middleSize = Vector256.LoadUnsafe(ref first, (nuint)(position + 10)); +- var highSize = Vector256.LoadUnsafe(ref first, (nuint)(position + 11)); +- var block = Vector256.LessThan(middleSize, Vector256.Create((byte)16)) & Vector256.Equals(highSize, Vector256.Zero); +- var r22 = Vector256.Equals(low, Vector256.Create((byte)0x3C)) & Vector256.Equals(high, Vector256.Create((byte)0x05)); +- var r20 = Vector256.Equals(low, Vector256.Create((byte)0xF8)) & Vector256.Equals(high, Vector256.Create((byte)0x04)); ++ for (; position <= vectorLimit - width; position += width) ++ { ++ var low = Vector128.LoadUnsafe(ref first, (nuint)(position + 8)); ++ var high = Vector128.LoadUnsafe(ref first, (nuint)(position + 9)); ++ var middleSize = Vector128.LoadUnsafe(ref first, (nuint)(position + 10)); ++ var highSize = Vector128.LoadUnsafe(ref first, (nuint)(position + 11)); ++ var block = Vector128.LessThan(middleSize, blockSizeLimit) & Vector128.Equals(highSize, Vector128.Zero); ++ var r22 = Vector128.Equals(low, r22Low) & Vector128.Equals(high, r22High); ++ var r20 = Vector128.Equals(low, r20Low) & Vector128.Equals(high, r20High); + uint candidates = (block | r22 | r20).ExtractMostSignificantBits(); + if (candidates != 0) return position + BitOperations.TrailingZeroCount(candidates); + } +--- /dev/null ++++ b/src/RvtIO/RvtFileReader.BrowserGRepWire.cs +@@ -0,0 +1,758 @@ ++using System.Buffers.Binary; ++using System.Runtime.InteropServices; ++using System.Text; ++using RvtIO.Geometry.Meshing; ++using RvtIO.Internal; ++using RvtIO.Parsing; ++ ++namespace RvtIO; ++ ++internal sealed partial class BrowserGRepWire ++{ ++ private readonly Dictionary _written = new(ReferenceEqualityComparer.Instance); ++ private readonly List _read = []; ++ private readonly List _solidFaces = []; ++ private readonly List _coarsePending = []; ++ private readonly bool _exactSources; ++ internal static readonly bool Reuse = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_WIRE_ALLOC_CONTROL") != "1"; ++ private BinaryReader Reader { get; set; } ++ private BinaryWriter Writer { get; } ++ ++ internal void SetReader(BinaryReader reader) => Reader = reader; ++ ++ private sealed class UnsupportedShapeException : Exception; ++ private static UnsupportedShapeException Unsupported => new(); ++ ++ internal BrowserGRepWire(BinaryWriter? writer = null, BinaryReader? reader = null, bool exactSources = false) => ++ (Writer, Reader, _exactSources) = (writer!, reader!, exactSources); ++ ++ internal bool TryWrite(GRepData value) ++ { ++ _written.Clear(); ++ _solidFaces.Clear(); ++ try ++ { ++ WriteRef(value, WriteGRepData); ++ // The face holds an edge to its containing solid, which in turn includes the ++ // original face. Write these references after the constructible part of the graph. ++ for (int i = 0; i < _solidFaces.Count; i++) ++ WriteList(_solidFaces[i].Solid, face => WriteRef(face, WriteBrFace)); ++ return true; ++ } ++ catch (UnsupportedShapeException) ++ { ++ return false; ++ } ++ } ++ ++ internal GRepData Read((byte[] Data, int Start, uint Size)? original) ++ { ++ _read.Clear(); ++ _solidFaces.Clear(); ++ _coarsePending.Clear(); ++ var value = ReadRef(ReadGRepData) ?? throw new InvalidDataException("Missing geometry."); ++ for (int i = 0; i < _solidFaces.Count; i++) ++ _solidFaces[i].Solid = ReadList(() => ReadRef(ReadBrFace)!); ++ if (_coarsePending.Count > 0) ++ { ++ var block = original ?? throw new InvalidDataException("The geometry source block is missing."); ++ foreach (var geometry in _coarsePending) ++ GRepParserV2.InstallCoarseQuantityReplay(geometry, block.Data, block.Start, block.Size); ++ } ++ ++ return value; ++ } ++ ++ private bool BeginReference(object? value) ++ { ++ if (value == null) ++ { ++ Writer.Write(0); ++ return false; ++ } ++ if (_written.TryGetValue(value, out int existing)) ++ { ++ Writer.Write(-existing); ++ return false; ++ } ++ int id = _written.Count + 1; ++ _written.Add(value, id); ++ Writer.Write(id); ++ return true; ++ } ++ ++ private void WriteRef(T? value, Action write) where T : class ++ { ++ if (BeginReference(value)) write(value!); ++ } ++ ++ private int BeginReadReference(out T? value) where T : class ++ { ++ int tag = Reader.ReadInt32(); ++ value = null; ++ if (tag == 0) return -1; ++ if (tag < 0) ++ { ++ value = _read[-tag - 1] as T ?? throw new InvalidDataException("Invalid geometry reference."); ++ return -1; ++ } ++ if (tag != _read.Count + 1) throw new InvalidDataException("Invalid geometry reference order."); ++ _read.Add(null); ++ return tag - 1; ++ } ++ ++ private T? ReadRef(Func read) where T : class ++ { ++ int slot = BeginReadReference(out var value); ++ if (slot < 0) return value; ++ value = read(); ++ _read[slot] = value; ++ return value; ++ } ++ ++ private void WriteDoubles(double[]? values) ++ { ++ if (!BeginReference(values)) return; ++ Writer.Write(values!.Length); ++ Writer.Write(MemoryMarshal.AsBytes(values.AsSpan())); ++ } ++ ++ private double[]? ReadDoubles() ++ { ++ if (!Reuse) return ReadRef(ReadNewDoubles); ++ int slot = BeginReadReference(out var value); ++ if (slot < 0) return value; ++ value = ReadNewDoubles(); ++ _read[slot] = value; ++ return value; ++ } ++ ++ private double[] ReadNewDoubles() ++ { ++ var values = new double[Reader.ReadInt32()]; ++ Reader.BaseStream.ReadExactly(MemoryMarshal.AsBytes(values.AsSpan())); ++ return values; ++ } ++ ++ private void WriteNullable(T? value, Action write) where T : struct ++ { ++ Writer.Write(value.HasValue); ++ if (value is { } item) write(item); ++ } ++ ++ private T? ReadNullable(Func read) where T : struct => Reader.ReadBoolean() ? read() : null; ++ ++ private void WriteList(IReadOnlyList? values, Action write) ++ { ++ if (!BeginReference(values)) return; ++ Writer.Write(values is T[]); ++ Writer.Write(values!.Count); ++ foreach (var item in values) write(item); ++ } ++ ++ private IReadOnlyList? ReadList(Func read) ++ { ++ if (!Reuse) return ReadListWithDelegate(read); ++ int slot = BeginReadReference>(out var value); ++ if (slot < 0) return value; ++ value = ReadNewList(read); ++ _read[slot] = value; ++ return value; ++ } ++ ++ private IReadOnlyList? ReadListWithDelegate(Func read) => ++ ReadRef>(() => ReadNewList(read)); ++ ++ private IReadOnlyList ReadNewList(Func read) ++ { ++ bool isArray = Reader.ReadBoolean(); ++ int count = Reader.ReadInt32(); ++ if (isArray) ++ { ++ var array = new T[count]; ++ for (int i = 0; i < count; i++) array[i] = read(); ++ return array; ++ } ++ var values = new List(count); ++ for (int i = 0; i < count; i++) values.Add(read()); ++ return values; ++ } ++ ++ private void WriteSet(IReadOnlySet? values, Action write) ++ { ++ if (!BeginReference(values)) return; ++ Writer.Write(values!.Count); ++ foreach (var item in values) write(item); ++ } ++ ++ private IReadOnlySet? ReadSet(Func read) => ReadRef>(() => ++ { ++ int count = Reader.ReadInt32(); ++ var values = new HashSet(count); ++ for (int i = 0; i < count; i++) values.Add(read()); ++ return values; ++ }); ++ ++ private void WriteDictionary(Dictionary? values, Action writeKey, ++ Action writeValue) where TKey : notnull ++ { ++ if (!BeginReference(values)) return; ++ Writer.Write(values!.Count); ++ foreach (var (key, value) in values) ++ { ++ writeKey(key); ++ writeValue(value); ++ } ++ } ++ ++ private Dictionary? ReadDictionary(Func readKey, Func readValue) ++ where TKey : notnull => ReadRef(() => ++ { ++ int count = Reader.ReadInt32(); ++ var values = new Dictionary(count); ++ for (int i = 0; i < count; i++) values.Add(readKey(), readValue()); ++ return values; ++ }); ++} ++ ++public partial class RvtFileReader ++{ ++ /// Dispatches local experiment geometry batches to independent decoders. ++ public static Func? BrowserDecodeGeometryBatches { get; set; } ++ ++ /// Decodes the original GRep blocks of one shard, retaining ordered result positions. ++ public static byte[] DecodeBrowserGeometryBatch(byte[] input) ++ { ++ using var output = new MemoryStream(); ++ WriteBrowserGeometryBatch(input, output); ++ return output.ToArray(); ++ } ++ ++ /// Publishes the encoded shard from its backing buffer during a synchronous call. ++ public static void DecodeBrowserGeometryBatchTo(byte[] input, Action> publish) ++ { ++ ArgumentNullException.ThrowIfNull(publish); ++ using var output = new MemoryStream(); ++ WriteBrowserGeometryBatch(input, output); ++ publish(new ArraySegment(output.GetBuffer(), 0, checked((int)output.Length))); ++ } ++ ++ private static void WriteBrowserGeometryBatch(byte[] input, MemoryStream output) ++ { ++ using var source = new MemoryStream(input, writable: false); ++ using var reader = new BinaryReader(source); ++ using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); ++ bool exactSources = Environment.GetEnvironmentVariable("IOEXTEND_GREP_EXACT_SOURCES") == "1"; ++ bool reuseWriter = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_REUSE_GREP_WRITER") == "1"; ++ bool skipCurveOnly = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_WORKER_CURVE_ONLY") == "1" ++ && !GRepParserV2.IsDecodeTracingEnabled(); ++ bool verifyCurveOnly = skipCurveOnly && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_VERIFY_CURVE_ONLY") == "1"; ++ int curveOnly = 0; ++ int capMiB = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_GEOMETRY_RESULT_24") == "1" ? 24 : 8; ++ var retainedWire = reuseWriter ? new BrowserGRepWire(writer: writer, exactSources: exactSources) : null; ++ while (source.Position < source.Length) ++ { ++ int index = reader.ReadInt32(); ++ uint size = reader.ReadUInt32(); ++ int start = checked((int)source.Position); ++ source.Seek(checked((int)size + 16), SeekOrigin.Current); ++ if (source.Position > source.Length) throw new InvalidDataException("Incomplete geometry block."); ++ writer.Write(index); ++ if (skipCurveOnly && GRepParserV2.IsCurveOnlyRepresentation(input, start, size)) ++ { ++ if (verifyCurveOnly && GRepParserV2.Parse(input, start, size) != null) ++ throw new InvalidDataException("The full decoder found geometry in a curve-only block."); ++ curveOnly++; ++ writer.Write(0); ++ continue; ++ } ++ var geometry = GRepParserV2.Parse(input, start, size); ++ if (geometry == null) ++ { ++ writer.Write(0); ++ continue; ++ } ++ long begin = output.Position; ++ writer.Write(0); ++ bool supported = (retainedWire ?? new BrowserGRepWire(writer: writer, exactSources: exactSources)).TryWrite(geometry); ++ long end = output.Position; ++ output.Position = begin; ++ if (!supported || end - begin > 8 * 1024 * 1024) ++ Console.WriteLine($"IOExtend geometry result index {index} input {size} supported {supported} wire {end - begin} capMiB {capMiB} directTrim {GRepParserV2.DirectTrim}"); ++ if (supported && end - begin <= capMiB * 1024 * 1024) ++ { ++ writer.Write(checked((int)(end - begin - 4))); ++ output.Position = end; ++ } ++ else ++ { ++ writer.Write(-1); ++ output.SetLength(output.Position); ++ } ++ } ++ if (curveOnly != 0) Console.WriteLine($"IOExtend worker curve-only records {curveOnly}"); ++ if (output.Length > 8 * 1024 * 1024) ++ Console.WriteLine($"IOExtend geometry shard wire {output.Length} capMiB {capMiB}"); ++ } ++ ++ ++ /// Begins the first collected geometry pass before the remaining block walk. ++ public static Action? BrowserStartInitialGeo { get; set; } ++ ++ /// Starts one deferred parameter batch while the scalar walk continues. ++ public static Action? BrowserStartDeferredParams { get; set; } ++ ++ /// Queues the next geometry batch while the previous batch is being applied. ++ public static Action? BrowserStartGeometryPipeline { get; set; } ++ ++ /// Collects a result from a separately addressed decoder mailbox. ++ public static Func? BrowserCollectDecoder { get; set; } ++ ++ /// Collects published geometry records. A single byte 1 completes the reply. Empty switches to the full collector. ++ public static Func? BrowserCollectGeometryPart { get; set; } ++ ++ /// Claims the source indices of one decoder job for local decoding. Empty means no job is available. ++ public static Func? BrowserClaimGeometryJob { get; set; } ++ ++ private const int GeometryBatchBytes = 1024 * 1024; ++ private const int InitialGeometryBytes = 24 * 1024 * 1024; ++ ++ internal static Action? TryStartInitialGeometry(List jobs, ++ ParsingState state, HashSet? unreadable) ++ { ++ if (BrowserStartInitialGeo is not { } start || BrowserCollectDecoder is not { } collect ++ || jobs.Count == 0 || jobs.Count > 8192) ++ return null; ++ ++ long total = 0; ++ foreach (var job in jobs) ++ { ++ if ((long)job.Size + 16 > GeometryBatchBytes) return null; ++ total += job.Size + 24L; ++ if (total > InitialGeometryBytes) return null; ++ } ++ ++ using var packet = new BrowserGeometryPacket(); ++ for (int i = 0; i < jobs.Count; i++) packet.Add(i, GetBlock(i)); ++ var clock = System.Diagnostics.Stopwatch.StartNew(); ++ const int channel = 2; ++ packet.Start(channel, start); ++ ++ return () => ++ { ++ var (received, replayed, _, applyBytes) = ReceiveBrowserGeometry(channel, collect, 0, jobs.Count, GetBlock, Apply); ++ Console.WriteLine($"IOExtend initial geometry {jobs.Count} jobs {received} received {replayed} replayed {clock.ElapsedMilliseconds} ms applyBytes {applyBytes}"); ++ }; ++ ++ (byte[] Data, int Start, uint Size) GetBlock(int index) ++ { ++ var job = jobs[index]; ++ return (job.Chunk, job.Start, job.Size); ++ } ++ ++ void Apply(int index, GRepData? geometry) ++ { ++ var job = jobs[index]; ++ if (geometry == null) unreadable?.Add(new(job.Chunk, job.Start, job.Size)); ++ BlockParser.ApplyPendingGRep(state, job, geometry); ++ } ++ } ++ ++ private static int BrowserRecoveryBatchBytes() => ++ int.TryParse(Environment.GetEnvironmentVariable("IOEXTEND_PROBE_RECOVERY_BATCH_MIB"), out int mib) ++ && mib is >= 1 and <= 8 ? mib * 1024 * 1024 : GeometryBatchBytes; ++ ++ internal readonly record struct PreparedGeometryBatch(int Count, int Bytes); ++ ++ private static readonly bool PrefetchAnchoredGeometry = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_ANCHORED_GEOMETRY") == "1"; ++ ++ private sealed class BrowserAnchoredGeometry(Action start, ++ Func collect) : IDisposable ++ { ++ private readonly BrowserGeometryPacket _packet = new(); ++ private readonly List _jobs = []; ++ private readonly int _budget = BrowserRecoveryBatchBytes(); ++ private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew(); ++ private bool _sent; ++ private int _bytes; ++ ++ internal void Add(BlockParser.GRepRange job) ++ { ++ if (_sent || (long)job.Size + 16 > GeometryBatchBytes) return; ++ _packet.Add(_jobs.Count, (job.Chunk, job.Start, job.Size)); ++ _jobs.Add(job); ++ _bytes += checked((int)job.Size + 24); ++ if (_bytes >= _budget) Send(); ++ } ++ ++ private void Send() ++ { ++ _packet.Start(1, start); ++ _sent = true; ++ Console.WriteLine($"IOExtend anchored geometry dispatched {_jobs.Count} jobs {_bytes} bytes after {_clock.ElapsedMilliseconds} ms"); ++ } ++ ++ internal byte[] Receive() ++ { ++ if (_jobs.Count == 0) return []; ++ if (!_sent) Send(); ++ return collect(1); ++ } ++ ++ internal Dictionary ReadResults(byte[] encoded) ++ { ++ var result = new Dictionary(); ++ if (encoded.Length == 0) return result; ++ ApplyBrowserGeometry(encoded, 0, _jobs.Count, index => ++ { ++ var job = _jobs[index]; ++ return (job.Chunk, job.Start, job.Size); ++ }, (index, geometry) => result.TryAdd(_jobs[index], geometry), replayMissing: false); ++ return result; ++ } ++ ++ public void Dispose() => _packet.Dispose(); ++ } ++ ++ private sealed class BrowserRecoveryPrefix(Action start) : IDisposable ++ { ++ private readonly BrowserGeometryPacket _packet = new(); ++ private readonly int _budget = BrowserRecoveryBatchBytes(); ++ private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew(); ++ private int _count, _bytes; ++ private bool _finished; ++ internal readonly List Batches = []; ++ ++ internal void Add((byte[] Data, int Start, uint Size) block) ++ { ++ if (_finished) return; ++ int size = checked((int)block.Size + 16); ++ if (size > GeometryBatchBytes) ++ { ++ CompleteBatch(); ++ _finished = true; ++ return; ++ } ++ _packet.Add(_count++, block); ++ _bytes += size + 8; ++ if (_bytes >= _budget) CompleteBatch(); ++ } ++ ++ internal void CompleteBatch() ++ { ++ if (_count == 0) return; ++ _packet.Start(Batches.Count == 0 ? 1 : 3, start); ++ Batches.Add(new(_count, _bytes)); ++ Console.WriteLine($"IOExtend recovery prefix {_count} jobs {_bytes} bytes after {_clock.ElapsedMilliseconds} ms"); ++ _packet.Clear(); ++ _count = _bytes = 0; ++ _finished = Batches.Count == 2; ++ } ++ ++ public void Dispose() => _packet.Dispose(); ++ } ++ ++ internal static bool TryDecodeBrowserGeometry(int count, Func getBlock, ++ Action apply, Action? beforeFirstWait = null, IReadOnlyList? prefix = null) ++ { ++ if (BrowserDecodeGeometryBatches is not { } decoder || GRepParserV2.IsDecodeTracingEnabled()) ++ return false; ++ ++ using var packet = new BrowserGeometryPacket(); ++ int offset = 0, received = 0, replayed = 0, batches = 0; ++ long sentBytes = 0, encodedBytes = 0, applyBytes = 0; ++ var clock = System.Diagnostics.Stopwatch.StartNew(); ++ var start = BrowserStartGeometryPipeline; ++ var collect = BrowserCollectDecoder; ++ var pending = new Queue<(int Channel, int Begin, int End)>(2); ++ int batchBudget = BrowserRecoveryBatchBytes(); ++ bool sendLargeRecords = start != null && collect != null ++ && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_RECOVERY_LARGE_RECORDS") == "1"; ++ bool overlapLocal = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_RECOVERY_OVERLAP_LOCAL") == "1"; ++ int recordLimit = sendLargeRecords ? Math.Max(GeometryBatchBytes, batchBudget - 8) : GeometryBatchBytes; ++ int largeRemote = 0, largeLocal = 0; ++ int localOverlapped = 0; ++ long localDecodeTicks = 0; ++ int channel = 1; ++ if (prefix != null) ++ foreach (var batch in prefix) ++ { ++ int end = checked(offset + batch.Count); ++ if (end > count) throw new InvalidOperationException("Prepared geometry exceeds candidate count."); ++ pending.Enqueue((channel, offset, end)); ++ channel = channel == 1 ? 3 : 1; ++ offset = end; ++ batches++; ++ sentBytes += batch.Bytes; ++ } ++ while (offset < count) ++ { ++ int next = offset, total = 0; ++ bool containsLargeRecord = false; ++ for (; next < count && total < batchBudget; next++) ++ { ++ var block = getBlock(next); ++ int size = checked((int)block.Size + 16); ++ if (size > recordLimit) ++ { ++ if (next == offset) ++ { ++ largeLocal++; ++ bool decodeEarly = overlapLocal && pending.Count != 0; ++ if (!decodeEarly) ++ while (pending.Count != 0) Drain(); ++ ++ long began = decodeEarly ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; ++ var geometry = GRepParserV2.Parse(block.Data, block.Start, block.Size); ++ if (decodeEarly) ++ { ++ localOverlapped++; ++ localDecodeTicks += System.Diagnostics.Stopwatch.GetTimestamp() - began; ++ // The oversized block is decoded independently. Apply it only after earlier records commit. ++ while (pending.Count != 0) Drain(); ++ } ++ apply(next, geometry); ++ offset = next + 1; ++ } ++ break; ++ } ++ // Preserve the established packet boundaries for ordinary records. ++ bool isLargeRecord = size > GeometryBatchBytes; ++ if ((containsLargeRecord || isLargeRecord) && size + 8 > batchBudget - total) ++ break; ++ if (isLargeRecord) ++ { ++ containsLargeRecord = true; ++ largeRemote++; ++ } ++ packet.Add(next - offset, block); ++ total += size + 8; ++ } ++ if (next <= offset) continue; ++ ++ if (start != null && collect != null) ++ { ++ if (pending.Count == 2) Drain(); ++ packet.Start(channel, start); ++ Drain(); ++ pending.Enqueue((channel, offset, next)); ++ channel = channel == 1 ? 3 : 1; ++ } ++ else ApplyBatch(packet.Decode(decoder), offset, next); ++ ++ batches++; ++ sentBytes += total; ++ packet.Clear(); ++ offset = next; ++ } ++ while (pending.Count != 0) Drain(); ++ if (largeRemote != 0 || largeLocal != 0) ++ Console.WriteLine($"IOExtend recovery large records remote {largeRemote} local {largeLocal}"); ++ if (localOverlapped != 0) ++ Console.WriteLine(FormattableString.Invariant($"IOExtend recovery overlapped local {localOverlapped} decodeMs {System.Diagnostics.Stopwatch.GetElapsedTime(0, localDecodeTicks).TotalMilliseconds:F3}")); ++ Console.WriteLine(FormattableString.Invariant($"IOExtend GRep jobs {count} received {received} replayed {replayed} batches {batches} inputBytes {sentBytes} outputBytes {encodedBytes} applyBytes {applyBytes} elapsedMs {clock.ElapsedMilliseconds}")); ++ return true; ++ ++ void Drain() ++ { ++ if (!pending.TryDequeue(out var completion)) return; ++ var overlap = beforeFirstWait; ++ beforeFirstWait = null; ++ overlap?.Invoke(); ++ var result = ReceiveBrowserGeometry(completion.Channel, collect!, completion.Begin, completion.End, getBlock, apply); ++ encodedBytes += result.EncodedBytes; ++ applyBytes += result.ApplyBytes; ++ received += result.Received; ++ replayed += result.Replayed; ++ } ++ ++ void ApplyBatch(byte[] encoded, int begin, int end) ++ { ++ encodedBytes += encoded.Length; ++ long before = GC.GetAllocatedBytesForCurrentThread(); ++ var (successes, replays) = ApplyBrowserGeometry(encoded, begin, end, getBlock, apply); ++ applyBytes += GC.GetAllocatedBytesForCurrentThread() - before; ++ received += successes; ++ replayed += replays; ++ } ++ } ++ ++ private static (int Received, int Replayed, long EncodedBytes, long ApplyBytes) ReceiveBrowserGeometry( ++ int channel, Func collect, int offset, int next, ++ Func getBlock, Action apply) ++ { ++ BrowserGeometryReceiver? local = null; ++ long localBytes = 0; ++ if (BrowserClaimGeometryJob is { } claim) ++ { ++ int claimedJobs = 0; ++ long started = System.Diagnostics.Stopwatch.GetTimestamp(); ++ long allocatedBefore = GC.GetAllocatedBytesForCurrentThread(); ++ for (byte[] indices = claim(channel); indices.Length != 0; indices = claim(channel)) ++ { ++ local ??= new BrowserGeometryReceiver(offset, next, getBlock); ++ local.DecodeLocal(indices); ++ claimedJobs++; ++ } ++ if (local != null) ++ { ++ localBytes = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore; ++ Console.WriteLine(FormattableString.Invariant($"IOExtend local geometry jobs {claimedJobs} records {local.Received} allocatedBytes {localBytes} elapsedMs {System.Diagnostics.Stopwatch.GetElapsedTime(started).TotalMilliseconds:F3}")); ++ } ++ } ++ ++ if (local == null && BrowserCollectGeometryPart is { } collectPart) ++ { ++ byte[] part = collectPart(channel); ++ if (part.Length != 0) ++ { ++ long before = GC.GetAllocatedBytesForCurrentThread(); ++ var receiver = new BrowserGeometryReceiver(offset, next, getBlock); ++ long applyBytes = GC.GetAllocatedBytesForCurrentThread() - before; ++ long encodedBytes = 16; // The equivalent legacy reply has four shard headers. ++ while (part.Length != 0) ++ { ++ before = GC.GetAllocatedBytesForCurrentThread(); ++ if (part.Length == 1 && part[0] == 1) ++ { ++ var (received, replayed) = receiver.Apply(apply, replayMissing: true); ++ return (received, replayed, encodedBytes, ++ applyBytes + GC.GetAllocatedBytesForCurrentThread() - before); ++ } ++ ++ using (var source = new MemoryStream(part, writable: false)) ++ using (var reader = new BinaryReader(source)) ++ receiver.ReadRecords(reader, part.Length); ++ applyBytes += GC.GetAllocatedBytesForCurrentThread() - before; ++ encodedBytes += part.Length; ++ part = collectPart(channel); ++ } ++ // Nothing has been applied yet. The existing collector owns replay if the stream aborts. ++ } ++ } ++ ++ byte[] encoded = collect(channel); ++ long allocated = GC.GetAllocatedBytesForCurrentThread(); ++ var result = ApplyBrowserGeometry(encoded, offset, next, getBlock, apply, receiver: local); ++ return (result.Received, result.Replayed, encoded.Length, localBytes + GC.GetAllocatedBytesForCurrentThread() - allocated); ++ } ++ ++ private static (int Received, int Replayed) ApplyBrowserGeometry(byte[] encoded, int offset, int next, ++ Func getBlock, Action apply, bool replayMissing = true, ++ BrowserGeometryReceiver? receiver = null) ++ { ++ receiver ??= new BrowserGeometryReceiver(offset, next, getBlock); ++ using var source = new MemoryStream(encoded, writable: false); ++ using var reader = new BinaryReader(source); ++ for (int shard = 0; shard < 4; shard++) ++ { ++ int size = reader.ReadInt32(); ++ if (size < 0) break; ++ long end = source.Position + size; ++ if (end > source.Length) throw new InvalidDataException("Incomplete geometry shard."); ++ receiver.ReadRecords(reader, end); ++ } ++ return receiver.Apply(apply, replayMissing); ++ } ++ ++ private sealed class BrowserGeometryReceiver(int offset, int next, ++ Func getBlock) ++ { ++ private readonly GRepData?[] _decoded = new GRepData?[next - offset]; ++ private readonly bool[] _handled = new bool[next - offset]; ++ private readonly BrowserGRepWire? _wire = BrowserGRepWire.Reuse ? new BrowserGRepWire() : null; ++ private int _received; ++ internal int Received => _received; ++ ++ internal void DecodeLocal(byte[] indices) ++ { ++ if (indices.Length % sizeof(int) != 0) throw new InvalidDataException("Incomplete geometry job index."); ++ for (int at = 0; at < indices.Length; at += sizeof(int)) ++ { ++ int index = BinaryPrimitives.ReadInt32LittleEndian(indices.AsSpan(at, sizeof(int))); ++ if ((uint)index >= (uint)_decoded.Length || _handled[index]) ++ throw new InvalidDataException("Invalid locally claimed geometry index."); ++ var (data, start, size) = getBlock(offset + index); ++ _decoded[index] = GRepParserV2.Parse(data, start, size); ++ _handled[index] = true; ++ _received++; ++ } ++ } ++ ++ internal void ReadRecords(BinaryReader reader, long end) ++ { ++ _wire?.SetReader(reader); ++ var source = reader.BaseStream; ++ while (source.Position < end) ++ { ++ if (end - source.Position < 8) throw new InvalidDataException("Incomplete geometry record header."); ++ int index = reader.ReadInt32(); ++ int length = reader.ReadInt32(); ++ if (length < 0) continue; ++ long recordEnd = source.Position + length; ++ if ((uint)index >= (uint)_decoded.Length || recordEnd > end) ++ throw new InvalidDataException("Invalid geometry record boundary."); ++ _handled[index] = true; ++ _received++; ++ if (length != 0) _decoded[index] = (_wire ?? new BrowserGRepWire(reader: reader)).Read(getBlock(offset + index)); ++ if (source.Position != recordEnd) throw new InvalidDataException("Geometry record length differs."); ++ } ++ } ++ ++ internal (int Received, int Replayed) Apply(Action apply, bool replayMissing) ++ { ++ int replayed = 0; ++ for (int i = 0; i < _decoded.Length; i++) ++ { ++ if (!_handled[i]) ++ { ++ if (!replayMissing) continue; ++ replayed++; ++ var local = getBlock(offset + i); ++ _decoded[i] = GRepParserV2.Parse(local.Data, local.Start, local.Size); ++ } ++ apply(offset + i, _decoded[i]); ++ } ++ return (_received, replayed); ++ } ++ } ++ ++ private sealed class BrowserGeometryPacket : IDisposable ++ { ++ private readonly MemoryStream[] inputs = [new(), new(), new(), new()]; ++ private readonly BinaryWriter[] writers; ++ ++ internal BrowserGeometryPacket() => ++ writers = Array.ConvertAll(inputs, input => new BinaryWriter(input, Encoding.UTF8, leaveOpen: true)); ++ ++ internal void Add(int index, (byte[] Data, int Start, uint Size) block) ++ { ++ int shard = 0; ++ for (int i = 1; i < inputs.Length; i++) ++ if (inputs[i].Length < inputs[shard].Length) shard = i; ++ var writer = writers[shard]; ++ writer.Write(index); ++ writer.Write(block.Size); ++ writer.Write(block.Data.AsSpan(block.Start, checked((int)block.Size + 16))); ++ } ++ ++ internal byte[] Decode(Func decode) => ++ decode(inputs[0].ToArray(), inputs[1].ToArray(), inputs[2].ToArray(), inputs[3].ToArray()); ++ ++ internal void Start(int channel, Action start) => ++ start(channel, inputs[0].ToArray(), inputs[1].ToArray(), inputs[2].ToArray(), inputs[3].ToArray()); ++ ++ internal void Clear() ++ { ++ foreach (var input in inputs) input.SetLength(0); ++ } ++ ++ public void Dispose() ++ { ++ foreach (var writer in writers) writer.Dispose(); ++ foreach (var input in inputs) input.Dispose(); ++ } ++ } ++} ++ +--- /dev/null ++++ b/src/RvtIO/RvtFileReader.BrowserGRepWire.Generated.cs +@@ -0,0 +1,600 @@ ++// Mechanically generated from the geometry data records for the local transport benchmark. ++using RvtIO.Geometry.Meshing; ++using RvtIO.Internal; ++using RvtIO.Parsing; ++using ParserArc = RvtIO.Internal.Arc; ++using Arc = RvtIO.Geometry.Meshing.Arc; ++ ++namespace RvtIO; ++ ++internal sealed partial class BrowserGRepWire ++{ ++ private void WriteGRepData(GRepData value) ++ { ++ if (value.HasCoarseQuantitySource && (!_exactSources || !value.CanReplayCoarseQuantitySource)) ++ throw Unsupported; ++ Writer.Write(value.HasCoarseQuantitySource); ++ Writer.Write(value.GStyleElemId); ++ Writer.Write(value.Flags); ++ WriteDoubles(value.BoundingBox); ++ WriteDoubles(value.RootBoundingBox); ++ WriteList(value.Faces, item0 => { WriteRef(item0, WriteGRepFace); }); ++ WriteList(value.InactiveFaces, item0 => { WriteRef(item0, WriteGRepFace); }); ++ WriteList(value.MeshNodes, item0 => { WriteRef(item0, WriteGeometryNode); }); ++ WriteList(value.NodeMeasures, item0 => { WriteRef(item0, WriteMeshNodeMeasure); }); ++ Writer.Write(value.CurvedSpaceBoundary); ++ WriteList(value.Solids, item0 => { WriteRef(item0, WriteGRepSolid); }); ++ WriteList(value.DisplayOnlyNodes, item0 => { Writer.Write(item0.Item1); Writer.Write(item0.Item2); Writer.Write(item0.Item3); }); ++ Writer.Write(value.PreserveSourceFaceIdentity); ++ Writer.Write(value.IsOpenSurface); ++ WriteNullable(value.LightingBodyMeasures, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); Writer.Write(value.Item3); }); ++ WriteNullable(value.SourceBodyMeasures, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); Writer.Write(value.Item3); }); ++ WriteNullable(value.SourceCapAreas, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); }); ++ WriteNullable(value.TrimmedBodyMeasures, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); }); ++ WriteNullable(value.FilledArea, value => { Writer.Write(value); }); ++ Writer.Write(value.UntriangulatedFaces); ++ WriteDoubles(value.Transform); ++ Writer.Write(value.SymbolElemId); ++ WriteDoubles(value.InstanceTransform); ++ WriteList(value.Instances, item0 => { WriteRef(item0, WriteGRepInstance); }); ++ WriteDoubles(value.FamilyClosurePlaneOrigin); ++ WriteDoubles(value.FamilyClosurePlaneNormal); ++ Writer.Write(value.IsFamilyComplexCut); ++ WriteNullable(value.QueueSummary, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); Writer.Write(value.Item3); }); ++ WriteDictionary(value.QueueClassCounts, key => { Writer.Write(key); }, item => { Writer.Write(item); }); ++ Writer.Write(value.HasDetailLevelAlternatives); ++ WriteRef(value.Coarse, WriteGRepData); ++ WriteRef(value.Medium, WriteGRepData); ++ } ++ ++ private GRepData ReadGRepData() ++ { ++ bool restoreCoarse = Reader.ReadBoolean(); ++ var geometry = new GRepData() ++ { ++ GStyleElemId = Reader.ReadInt32(), ++ Flags = Reader.ReadUInt32(), ++ BoundingBox = ReadDoubles(), ++ RootBoundingBox = ReadDoubles(), ++ Faces = (ReadList(() => ReadRef(ReadGRepFace)!) as List)!, ++ InactiveFaces = (ReadList(() => ReadRef(ReadGRepFace)!) as List), ++ MeshNodes = (ReadList(() => ReadRef(ReadGeometryNode)!) as List), ++ NodeMeasures = (ReadList(() => ReadRef(ReadMeshNodeMeasure)!) as List), ++ CurvedSpaceBoundary = Reader.ReadBoolean(), ++ Solids = (ReadList(() => ReadRef(ReadGRepSolid)!) as List)!, ++ DisplayOnlyNodes = (ReadList(() => (Reader.ReadInt32(), Reader.ReadInt32(), Reader.ReadInt32())) as List<(int Node, int Style, int RenderStyleId)>), ++ PreserveSourceFaceIdentity = Reader.ReadBoolean(), ++ IsOpenSurface = Reader.ReadBoolean(), ++ LightingBodyMeasures = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble(), Reader.ReadInt32())), ++ SourceBodyMeasures = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble(), Reader.ReadInt32())), ++ SourceCapAreas = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble())), ++ TrimmedBodyMeasures = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble())), ++ FilledArea = ReadNullable(() => Reader.ReadDouble()), ++ UntriangulatedFaces = Reader.ReadInt32(), ++ Transform = ReadDoubles(), ++ SymbolElemId = Reader.ReadInt32(), ++ InstanceTransform = ReadDoubles(), ++ Instances = (ReadList(() => ReadRef(ReadGRepInstance)!) as List)!, ++ FamilyClosurePlaneOrigin = ReadDoubles(), ++ FamilyClosurePlaneNormal = ReadDoubles(), ++ IsFamilyComplexCut = Reader.ReadBoolean(), ++ QueueSummary = ReadNullable(() => (Reader.ReadInt32(), Reader.ReadInt32(), Reader.ReadInt32())), ++ QueueClassCounts = ReadDictionary(() => Reader.ReadUInt16(), () => Reader.ReadInt32()), ++ HasDetailLevelAlternatives = Reader.ReadBoolean(), ++ Coarse = ReadRef(ReadGRepData), ++ Medium = ReadRef(ReadGRepData), ++ }; ++ if (restoreCoarse) _coarsePending.Add(geometry); ++ return geometry; ++ } ++ ++ private void WriteGRepInstance(GRepInstance value) ++ { ++ Writer.Write(value.SymbolElemId); ++ WriteDoubles(value.Transform); ++ Writer.Write(value.NodeOrder); ++ } ++ ++ private GRepInstance ReadGRepInstance() ++ { ++ return new GRepInstance() ++ { ++ SymbolElemId = Reader.ReadInt32(), ++ Transform = ReadDoubles()!, ++ NodeOrder = Reader.ReadInt64(), ++ }; ++ } ++ ++ private void WriteGRepFace(GRepFace value) ++ { ++ WriteNullable(value.RenderStyleId, value => { Writer.Write(value); }); ++ WriteDoubles(value.Envelope); ++ Writer.Write(value.Orient); ++ WriteDoubles(value.Origin); ++ WriteDoubles(value.XVector); ++ WriteDoubles(value.YVector); ++ WriteList(value.InnerLoops, item0 => { WriteDoubles(item0); }); ++ WriteList(value.Vertices, item0 => { WriteDoubles(item0); }); ++ WriteList(value.InnerVertices, item1 => { WriteList(item1, item0 => { WriteDoubles(item0); }); }); ++ WriteList(value.FirstSourceLoop, item0 => { WriteDoubles(item0); }); ++ WriteList(value.SourceLoops, item1 => { WriteList(item1, item0 => { WriteDoubles(item0); }); }); ++ WriteList(value.AlternativeOuterVertices, item0 => { WriteDoubles(item0); }); ++ WriteDoubles(value.AnalyticCylinderOrigin); ++ WriteDoubles(value.AnalyticCylinderAxis); ++ WriteDoubles(value.AnalyticCylinderReferenceDirection); ++ Writer.Write(value.AnalyticCylinderRadius); ++ WriteDoubles(value.MeshEdgeBounds); ++ WriteDoubles(value.MeshPlaneEnvelopeCorners); ++ WriteList(value.MeshArcs, item0 => { WriteRef(item0, WriteParserArc); }); ++ WriteNullable(value.QuadratureArea, value => { Writer.Write(value); }); ++ Writer.Write(value.CurvedSurface); ++ Writer.Write(value.PlaneSurface); ++ WriteDoubles(value.PlaneX); ++ WriteDoubles(value.PlaneY); ++ Writer.Write(value.SourceFace); ++ Writer.Write(value.GeometryNode); ++ Writer.Write(value.NodeOrder); ++ Writer.Write(value.GeometryStyle); ++ WriteNullable(value.GInfoFlags, value => { Writer.Write(value); }); ++ WriteNullable(value.GInfoTag, value => { Writer.Write(value); }); ++ } ++ ++ private GRepFace ReadGRepFace() ++ { ++ return new GRepFace() ++ { ++ RenderStyleId = ReadNullable(() => Reader.ReadInt32()), ++ Envelope = ReadDoubles()!, ++ Orient = Reader.ReadBoolean(), ++ Origin = ReadDoubles()!, ++ XVector = ReadDoubles()!, ++ YVector = ReadDoubles()!, ++ InnerLoops = (ReadList(() => ReadDoubles()!) as List)!, ++ Vertices = (ReadList(() => ReadDoubles()!) as List), ++ InnerVertices = (ReadList(() => (ReadList(() => ReadDoubles()!) as List)!) as List>), ++ FirstSourceLoop = (ReadList(() => ReadDoubles()!) as List), ++ SourceLoops = ReadList(() => (ReadList(() => ReadDoubles()!) as List)!), ++ AlternativeOuterVertices = (ReadList(() => ReadDoubles()!) as List), ++ AnalyticCylinderOrigin = ReadDoubles(), ++ AnalyticCylinderAxis = ReadDoubles(), ++ AnalyticCylinderReferenceDirection = ReadDoubles(), ++ AnalyticCylinderRadius = Reader.ReadDouble(), ++ MeshEdgeBounds = ReadDoubles(), ++ MeshPlaneEnvelopeCorners = ReadDoubles(), ++ MeshArcs = ReadList(() => ReadRef(ReadParserArc)!), ++ QuadratureArea = ReadNullable(() => Reader.ReadDouble()), ++ CurvedSurface = Reader.ReadBoolean(), ++ PlaneSurface = Reader.ReadBoolean(), ++ PlaneX = ReadDoubles(), ++ PlaneY = ReadDoubles(), ++ SourceFace = Reader.ReadUInt32(), ++ GeometryNode = Reader.ReadInt32(), ++ NodeOrder = Reader.ReadInt64(), ++ GeometryStyle = Reader.ReadInt32(), ++ GInfoFlags = ReadNullable(() => Reader.ReadUInt32()), ++ GInfoTag = ReadNullable(() => Reader.ReadInt32()), ++ }; ++ } ++ ++ private void WriteGRepSolid(GRepSolid value) ++ { ++ WriteList(value.FaceIndices, item0 => { Writer.Write(item0); }); ++ Writer.Write(value.IsClosed); ++ } ++ ++ private GRepSolid ReadGRepSolid() ++ { ++ return new GRepSolid() ++ { ++ FaceIndices = (ReadList(() => Reader.ReadInt32()) as List)!, ++ IsClosed = Reader.ReadBoolean(), ++ }; ++ } ++ ++ private void WriteParserArc(ParserArc value) ++ { ++ WriteDoubles(value.Centre); ++ WriteDoubles(value.X); ++ WriteDoubles(value.Y); ++ Writer.Write(value.Radius); ++ Writer.Write(value.First); ++ Writer.Write(value.Last); ++ Writer.Write(value.Edge); ++ } ++ ++ private ParserArc ReadParserArc() ++ { ++ return new ParserArc(ReadDoubles()!, ReadDoubles()!, ReadDoubles()!, Reader.ReadDouble(), Reader.ReadDouble(), Reader.ReadDouble(), Reader.ReadUInt32()); ++ } ++ ++ private void WriteMeshNodeMeasure(MeshNodeMeasure value) ++ { ++ Writer.Write(value.Node); ++ Writer.Write(value.Area); ++ Writer.Write(value.Volume); ++ WriteSet(value.SourceFaces, item0 => { Writer.Write(item0); }); ++ } ++ ++ private MeshNodeMeasure ReadMeshNodeMeasure() ++ { ++ return new MeshNodeMeasure(Reader.ReadInt32(), Reader.ReadDouble(), Reader.ReadDouble()) ++ { ++ SourceFaces = ReadSet(() => Reader.ReadUInt32()), ++ }; ++ } ++ ++ private void WriteGeometryNode(GeometryNode value) ++ { ++ Writer.Write(value.Node); ++ Writer.Write(value.NodeOrder); ++ WriteList(value.Faces, item0 => { WriteRef(item0, WriteBrFace); }); ++ Writer.Write(value.Diagonal); ++ WriteDoubles(value.Placement); ++ WriteNullable(value.SourceMeasures, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); }); ++ Writer.Write(value.Ghost); ++ Writer.Write(value.Style); ++ Writer.Write(value.RenderStyleId); ++ } ++ ++ private GeometryNode ReadGeometryNode() ++ { ++ return new GeometryNode(Reader.ReadInt32(), Reader.ReadInt64(), ReadList(() => ReadRef(ReadBrFace)!)!, Reader.ReadDouble(), ReadDoubles()) ++ { ++ SourceMeasures = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble())), ++ Ghost = Reader.ReadBoolean(), ++ Style = Reader.ReadInt32(), ++ RenderStyleId = Reader.ReadInt32(), ++ }; ++ } ++ ++ private void WritePlaneSurface(PlaneSurface value) ++ { ++ WriteDoubles(value.Origin); ++ WriteDoubles(value.U); ++ WriteDoubles(value.V); ++ WriteDoubles(value.Normal); ++ } ++ ++ private PlaneSurface ReadPlaneSurface() ++ { ++ return new PlaneSurface() ++ { ++ Origin = ReadDoubles()!, ++ U = ReadDoubles()!, ++ V = ReadDoubles()!, ++ Normal = ReadDoubles(), ++ }; ++ } ++ ++ private void WriteCylinderSurface(CylinderSurface value) ++ { ++ Writer.Write(value.Radius); ++ WriteDoubles(value.Origin); ++ WriteDoubles(value.Axis); ++ WriteDoubles(value.Ref); ++ Writer.Write(value.UScale); ++ Writer.Write(value.AngleLo); ++ Writer.Write(value.AngleHi); ++ Writer.Write(value.HeightLo); ++ Writer.Write(value.HeightHi); ++ Writer.Write(value.Outer); ++ Writer.Write(value.ConeHalfAngle); ++ } ++ ++ private CylinderSurface ReadCylinderSurface() ++ { ++ return new CylinderSurface() ++ { ++ Radius = Reader.ReadDouble(), ++ Origin = ReadDoubles()!, ++ Axis = ReadDoubles()!, ++ Ref = ReadDoubles()!, ++ UScale = Reader.ReadDouble(), ++ AngleLo = Reader.ReadDouble(), ++ AngleHi = Reader.ReadDouble(), ++ HeightLo = Reader.ReadDouble(), ++ HeightHi = Reader.ReadDouble(), ++ Outer = Reader.ReadBoolean(), ++ ConeHalfAngle = Reader.ReadDouble(), ++ }; ++ } ++ ++ private void WriteRevolvedSurface(RevolvedSurface value) ++ { ++ if (value.ProfileAt != null && (!_exactSources || value.ProfileRecipe == null)) ++ throw Unsupported; ++ WriteRef(value.ProfileAt == null ? null : value.ProfileRecipe, WriteMeridianProfile); ++ ++ WriteDoubles(value.Origin); ++ WriteDoubles(value.Axis); ++ Writer.Write(value.V0); ++ Writer.Write(value.U0); ++ WriteDoubles(value.ProfileStart); ++ WriteDoubles(value.ProfileDir); ++ WriteDoubles(value.ArcCenter); ++ WriteDoubles(value.ArcE1); ++ WriteDoubles(value.ArcE2); ++ Writer.Write(value.ArcRadius); ++ Writer.Write(value.ArcEps); ++ ++ WriteDoubles(value.GeEnvelope); ++ Writer.Write(value.NormalReversed); ++ } ++ ++ private RevolvedSurface ReadRevolvedSurface() ++ { ++ var recipe = ReadRef(ReadMeridianProfile); ++ return new RevolvedSurface() ++ { ++ Origin = ReadDoubles()!, ++ Axis = ReadDoubles()!, ++ V0 = Reader.ReadDouble(), ++ U0 = Reader.ReadDouble(), ++ ProfileStart = ReadDoubles(), ++ ProfileDir = ReadDoubles(), ++ ArcCenter = ReadDoubles(), ++ ArcE1 = ReadDoubles(), ++ ArcE2 = ReadDoubles(), ++ ArcRadius = Reader.ReadDouble(), ++ ArcEps = Reader.ReadDouble(), ++ ProfileRecipe = recipe, ++ ProfileAt = recipe == null ? null : recipe.Evaluate, ++ GeEnvelope = ReadDoubles()!, ++ NormalReversed = Reader.ReadBoolean(), ++ }; ++ } ++ ++ private void WriteRuledSurface(RuledSurface value) ++ { ++ WriteRef(value.Profile0, WriteMeshCurve); ++ WriteRef(value.Profile1, WriteMeshCurve); ++ WriteDoubles(value.Point0); ++ WriteDoubles(value.Point1); ++ } ++ ++ private RuledSurface ReadRuledSurface() ++ { ++ return new RuledSurface() ++ { ++ Profile0 = ReadRef(ReadMeshCurve), ++ Profile1 = ReadRef(ReadMeshCurve), ++ Point0 = ReadDoubles(), ++ Point1 = ReadDoubles(), ++ }; ++ } ++ ++ private void WriteNurbsSurface(NurbsSurface value) ++ { ++ Writer.Write(value.DegreeU); ++ Writer.Write(value.DegreeV); ++ WriteDoubles(value.KnotsU); ++ WriteDoubles(value.KnotsV); ++ WriteList(value.ControlPoints, item => { WriteDoubles(item); }); ++ WriteDoubles(value.Weights); ++ } ++ ++ private NurbsSurface ReadNurbsSurface() ++ { ++ return new NurbsSurface() ++ { ++ DegreeU = Reader.ReadInt32(), ++ DegreeV = Reader.ReadInt32(), ++ KnotsU = ReadDoubles()!, ++ KnotsV = ReadDoubles()!, ++ ControlPoints = (ReadList(() => ReadDoubles()!) as double[][])!, ++ Weights = ReadDoubles(), ++ }; ++ } ++ ++ private void WriteNurbs(Nurbs value) ++ { ++ Writer.Write(value.Degree); ++ WriteDoubles(value.Knots); ++ WriteList(value.ControlPoints, item => { WriteDoubles(item); }); ++ WriteDoubles(value.Weights); ++ } ++ ++ private Nurbs ReadNurbs() ++ { ++ return new Nurbs() ++ { ++ Degree = Reader.ReadInt32(), ++ Knots = ReadDoubles()!, ++ ControlPoints = (ReadList(() => ReadDoubles()!) as double[][])!, ++ Weights = ReadDoubles(), ++ }; ++ } ++ ++ private void WriteArc(Arc value) ++ { ++ WriteDoubles(value.Center); ++ Writer.Write(value.Radius); ++ WriteDoubles(value.Normal); ++ WriteDoubles(value.Ref); ++ Writer.Write(value.Start); ++ Writer.Write(value.End); ++ WriteNullable(value.EdgeRange, value => { Writer.Write(value.Item1); Writer.Write(value.Item2); }); ++ } ++ ++ private Arc ReadArc() ++ { ++ return new Arc() ++ { ++ Center = ReadDoubles()!, ++ Radius = Reader.ReadDouble(), ++ Normal = ReadDoubles()!, ++ Ref = ReadDoubles()!, ++ Start = Reader.ReadDouble(), ++ End = Reader.ReadDouble(), ++ EdgeRange = ReadNullable(() => (Reader.ReadDouble(), Reader.ReadDouble())), ++ }; ++ } ++ ++ private void WriteEllipse(Ellipse value) ++ { ++ WriteDoubles(value.Center); ++ WriteDoubles(value.MajorAxis); ++ WriteDoubles(value.MinorAxis); ++ Writer.Write(value.MajorRadius); ++ Writer.Write(value.MinorRadius); ++ Writer.Write(value.Start); ++ Writer.Write(value.End); ++ } ++ ++ private Ellipse ReadEllipse() ++ { ++ return new Ellipse() ++ { ++ Center = ReadDoubles()!, ++ MajorAxis = ReadDoubles()!, ++ MinorAxis = ReadDoubles()!, ++ MajorRadius = Reader.ReadDouble(), ++ MinorRadius = Reader.ReadDouble(), ++ Start = Reader.ReadDouble(), ++ End = Reader.ReadDouble(), ++ }; ++ } ++ ++ private void WriteMeshCurve(MeshCurve value) ++ { ++ Writer.Write((int)value.Kind); ++ Writer.Write(value.Lo); ++ Writer.Write(value.Hi); ++ WriteDoubles(value.P0); ++ WriteDoubles(value.P1); ++ WriteRef(value.Arc, WriteArc); ++ WriteRef(value.Nurbs, WriteNurbs); ++ WriteRef(value.Ellipse, WriteEllipse); ++ } ++ ++ private MeshCurve ReadMeshCurve() ++ { ++ return new MeshCurve() ++ { ++ Kind = (CurveKind)Reader.ReadInt32(), ++ Lo = Reader.ReadDouble(), ++ Hi = Reader.ReadDouble(), ++ P0 = ReadDoubles(), ++ P1 = ReadDoubles(), ++ Arc = ReadRef(ReadArc), ++ Nurbs = ReadRef(ReadNurbs), ++ Ellipse = ReadRef(ReadEllipse), ++ }; ++ } ++ ++ private void WriteParamCurve(ParamCurve value) ++ { ++ Writer.Write(value.Lo); ++ Writer.Write(value.Hi); ++ WriteDoubles(value.P0); ++ WriteDoubles(value.P1); ++ WriteRef(value.Nurbs, WriteNurbs); ++ Writer.Write(value.Projected); ++ } ++ ++ private ParamCurve ReadParamCurve() ++ { ++ return new ParamCurve() ++ { ++ Lo = Reader.ReadDouble(), ++ Hi = Reader.ReadDouble(), ++ P0 = ReadDoubles(), ++ P1 = ReadDoubles(), ++ Nurbs = ReadRef(ReadNurbs), ++ Projected = Reader.ReadBoolean(), ++ }; ++ } ++ ++ private void WriteMeshCoedge(MeshCoedge value) ++ { ++ Writer.Write(value.EdgeMarker); ++ Writer.Write(value.OrientToLoop); ++ Writer.Write(value.EdgeOrientToCurve); ++ WriteDoubles(value.V1); ++ WriteDoubles(value.V2); ++ Writer.Write(value.ParamV1); ++ Writer.Write(value.ParamV2); ++ WriteRef(value.Curve, WriteMeshCurve); ++ WriteRef(value.OrientedCurve, WriteMeshCurve); ++ WriteRef(value.ParamCurve, WriteParamCurve); ++ WriteDoubles(value.Start); ++ WriteDoubles(value.End); ++ WriteList(value.Samples, item => { WriteDoubles(item); }); ++ WriteDoubles(value.UvStart); ++ WriteDoubles(value.UvEnd); ++ WriteList(value.UvFit, item => { WriteDoubles(item); }); ++ } ++ ++ private MeshCoedge ReadMeshCoedge() ++ { ++ return new MeshCoedge() ++ { ++ EdgeMarker = Reader.ReadInt32(), ++ OrientToLoop = Reader.ReadBoolean(), ++ EdgeOrientToCurve = Reader.ReadBoolean(), ++ V1 = ReadDoubles(), ++ V2 = ReadDoubles(), ++ ParamV1 = Reader.ReadDouble(), ++ ParamV2 = Reader.ReadDouble(), ++ Curve = ReadRef(ReadMeshCurve), ++ OrientedCurve = ReadRef(ReadMeshCurve), ++ ParamCurve = ReadRef(ReadParamCurve), ++ Start = ReadDoubles(), ++ End = ReadDoubles(), ++ Samples = (ReadList(() => ReadDoubles()!) as double[][]), ++ UvStart = ReadDoubles(), ++ UvEnd = ReadDoubles(), ++ UvFit = (ReadList(() => ReadDoubles()!) as double[][]), ++ }; ++ } ++ ++ private void WriteLoop(Loop value) ++ { ++ WriteList(value.Coedges, item0 => { WriteRef(item0, WriteMeshCoedge); }); ++ } ++ ++ private Loop ReadLoop() ++ { ++ return new Loop() ++ { ++ Coedges = ReadList(() => ReadRef(ReadMeshCoedge)!)!, ++ }; ++ } ++ ++ private void WriteBrFace(BrFace value) ++ { ++ Writer.Write(value.Marker); ++ Writer.Write((int)value.SurfaceKind); ++ Writer.Write(value.OrientToSurface); ++ Writer.Write(value.Flipped); ++ WriteDoubles(value.Envelope); ++ WriteRef(value.Plane, WritePlaneSurface); ++ WriteRef(value.Cylinder, WriteCylinderSurface); ++ WriteRef(value.Revolved, WriteRevolvedSurface); ++ WriteRef(value.Ruled, WriteRuledSurface); ++ WriteRef(value.Nurbs, WriteNurbsSurface); ++ WriteList(value.Loops, item0 => { WriteRef(item0, WriteLoop); }); ++ _solidFaces.Add(value); ++ } ++ ++ private BrFace ReadBrFace() ++ { ++ var value = new BrFace() ++ { ++ Marker = Reader.ReadInt32(), ++ SurfaceKind = (SurfaceKind)Reader.ReadInt32(), ++ OrientToSurface = Reader.ReadBoolean(), ++ Flipped = Reader.ReadBoolean(), ++ Envelope = ReadDoubles(), ++ Plane = ReadRef(ReadPlaneSurface), ++ Cylinder = ReadRef(ReadCylinderSurface), ++ Revolved = ReadRef(ReadRevolvedSurface), ++ Ruled = ReadRef(ReadRuledSurface), ++ Nurbs = ReadRef(ReadNurbsSurface), ++ Loops = ReadList(() => ReadRef(ReadLoop)!)!, ++ }; ++ _solidFaces.Add(value); ++ return value; ++ } ++ ++} +--- /dev/null ++++ b/src/RvtIO/RvtFileReader.BrowserGRepWire.Profile.cs +@@ -0,0 +1,79 @@ ++using RvtIO.Parsing; ++ ++namespace RvtIO; ++ ++internal sealed partial class BrowserGRepWire ++{ ++ private void WriteMeridianProfile(GRepParserV2.MeridianProfile value) ++ { ++ WriteDoubles(value.Origin); ++ WriteDoubles(value.Radial); ++ WriteDoubles(value.Transverse); ++ WriteDoubles(value.Axis); ++ var curve = value.Curve; ++ WriteDoubles(curve.C); ++ WriteDoubles(curve.X); ++ WriteDoubles(curve.Y); ++ Writer.Write(curve.R); ++ Writer.Write(curve.RY); ++ Writer.Write(curve.T0); ++ Writer.Write(curve.T1); ++ WriteList(curve.HermiteNodes, node => WriteRef(node, WriteHermiteNode)); ++ Writer.Write(curve.NurbDegree); ++ Writer.Write(curve.NurbClosed); ++ Writer.Write(curve.NurbRational); ++ WriteList(curve.NurbControlPoints, point => WriteRef(point, WriteControlPoint)); ++ WriteDoubles(curve.NurbKnots); ++ } ++ ++ private GRepParserV2.MeridianProfile ReadMeridianProfile() ++ { ++ var origin = ReadDoubles()!; ++ var radial = ReadDoubles()!; ++ var transverse = ReadDoubles()!; ++ var axis = ReadDoubles()!; ++ var curve = new GRepParserV2.ArcRec ++ { ++ C = ReadDoubles()!, ++ X = ReadDoubles()!, ++ Y = ReadDoubles()!, ++ R = Reader.ReadDouble(), ++ RY = Reader.ReadDouble(), ++ T0 = Reader.ReadDouble(), ++ T1 = Reader.ReadDouble(), ++ HermiteNodes = ReadList(() => ReadRef(ReadHermiteNode)!) as List, ++ NurbDegree = Reader.ReadInt32(), ++ NurbClosed = Reader.ReadBoolean(), ++ NurbRational = Reader.ReadBoolean(), ++ NurbControlPoints = ReadList(() => ReadRef(ReadControlPoint)!) as List, ++ NurbKnots = ReadDoubles(), ++ }; ++ return new GRepParserV2.MeridianProfile(origin, radial, transverse, axis, curve); ++ } ++ ++ private void WriteHermiteNode(GRepParserV2.HermiteNode value) ++ { ++ Writer.Write(value.T); ++ WriteDoubles(value.Point); ++ WriteDoubles(value.Tangent); ++ } ++ ++ private GRepParserV2.HermiteNode ReadHermiteNode() => new() ++ { ++ T = Reader.ReadDouble(), ++ Point = ReadDoubles()!, ++ Tangent = ReadDoubles()!, ++ }; ++ ++ private void WriteControlPoint(GRepParserV2.NurbControlPoint value) ++ { ++ Writer.Write(value.Weight); ++ WriteDoubles(value.Point); ++ } ++ ++ private GRepParserV2.NurbControlPoint ReadControlPoint() => new() ++ { ++ Weight = Reader.ReadDouble(), ++ Point = ReadDoubles()!, ++ }; ++} +--- /dev/null ++++ b/src/RvtIO/RvtFileReader.BrowserNameScan.cs +@@ -0,0 +1,142 @@ ++using System.Globalization; ++using System.Runtime.InteropServices; ++using System.Text; ++using RvtIO.Parsing; ++ ++namespace RvtIO; ++ ++public partial class RvtFileReader ++{ ++ /// Starts a browser worker with the exact ID snapshot and comparison culture. ++ public static Func? BrowserBeginNameScan { get; set; } ++ ++ /// Queues a complete chunk for the browser name scanner. ++ public static Action? BrowserSendNameChunk { get; set; } ++ ++ /// Seals the name scan input. ++ public static Action? BrowserSealNameScan { get; set; } ++ ++ /// Gets ordered name contributions after the main parser's overlapping work. ++ public static Func? BrowserCollectNameScan { get; set; } ++ ++ private const long NameInputBudget = 96 * 1024 * 1024; ++ private static HashSet? _sideNameIds; ++ private static Dictionary>? _sideNames; ++ private static Dictionary>? _sideNameSeen; ++ private static int _sideLastChunk; ++ private static int _sideChunkCount; ++ ++ /// Initializes a dedicated worker's name scanner. ++ public static void BeginBrowserNameScan(byte[] ids, string culture) ++ { ++ if (_sideNameIds != null || ids.Length % sizeof(uint) != 0) ++ throw new InvalidDataException("Invalid name scanner initialization."); ++ CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); ++ _sideNameIds = new HashSet(ids.Length / sizeof(uint)); ++ foreach (uint id in MemoryMarshal.Cast(ids.AsSpan())) ++ _sideNameIds.Add(id); ++ _sideNames = new(); ++ _sideNameSeen = new(); ++ _sideLastChunk = -1; ++ _sideChunkCount = 0; ++ } ++ ++ /// Scans an entire chunk and merges the names in source chunk order. ++ public static void ScanBrowserNameChunk(int index, byte[] data) ++ { ++ if (_sideNameIds == null || index <= _sideLastChunk) ++ throw new InvalidDataException("Name scanner chunk order differs."); ++ var names = new Dictionary>(); ++ StringScanner.ScanChunk(data, _sideNameIds, names); ++ MergeElemScanStringChunk(names, _sideNames!, _sideNameSeen!); ++ _sideLastChunk = index; ++ _sideChunkCount++; ++ } ++ ++ /// Encodes the merged owner lists using a shared ordinal string table. ++ public static byte[] FinishBrowserNameScan() ++ { ++ var names = _sideNames ?? throw new InvalidOperationException("Missing name scanner."); ++ var table = new Dictionary(StringComparer.Ordinal); ++ using var ownerData = new MemoryStream(); ++ using var ownerWriter = new BinaryWriter(ownerData, Encoding.UTF8, leaveOpen: true); ++ foreach (var (id, values) in names) ++ { ++ ownerWriter.Write(id); ++ ownerWriter.Write(values.Count); ++ foreach (string value in values) ++ { ++ if (!table.TryGetValue(value, out int index)) ++ { ++ index = table.Count; ++ table.Add(value, index); ++ } ++ ownerWriter.Write(index); ++ } ++ } ++ using var output = new MemoryStream(); ++ using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); ++ writer.Write(_sideChunkCount); ++ writer.Write(table.Count); ++ foreach (string value in table.Keys) WriteBrowserString(writer, value); ++ writer.Write(names.Count); ++ writer.Write(ownerData.GetBuffer().AsSpan(0, (int)ownerData.Length)); ++ _sideNameIds = null; ++ _sideNames = null; ++ _sideNameSeen = null; ++ return output.ToArray(); ++ } ++ ++ private static Action>?[]>? TryStartBrowserNameScan( ++ IReadOnlyList chunks, HashSet scanIds) ++ { ++ if (BrowserBeginNameScan is not { } begin || BrowserSendNameChunk is not { } send ++ || BrowserSealNameScan is not { } seal || BrowserCollectNameScan is not { } collect) ++ return null; ++ uint[] ids = scanIds.ToArray(); ++ if (!begin(MemoryMarshal.AsBytes(ids.AsSpan()).ToArray(), CultureInfo.CurrentCulture.Name)) ++ return null; ++ ++ int prefix = 0, sent = 0; ++ long bytes = 0; ++ for (; prefix < chunks.Count; prefix++) ++ { ++ var chunk = chunks[prefix]; ++ if (chunk.Length > NameInputBudget - bytes) break; ++ if (chunk.Length < 6) continue; ++ send(prefix, chunk); ++ sent++; ++ bytes += chunk.Length; ++ } ++ seal(); ++ ++ return result => ++ { ++ byte[] encoded = collect(); ++ if (encoded.Length == 0 || prefix == 0) return; ++ using var source = new MemoryStream(encoded, writable: false); ++ using var reader = new BinaryReader(source); ++ if (reader.ReadInt32() != sent) ++ throw new InvalidDataException("Incomplete name worker prefix."); ++ var table = new string[reader.ReadInt32()]; ++ for (int i = 0; i < table.Length; i++) table[i] = ReadBrowserString(reader); ++ int owners = reader.ReadInt32(); ++ var merged = new Dictionary>(owners); ++ for (int i = 0; i < owners; i++) ++ { ++ uint id = reader.ReadUInt32(); ++ int size = reader.ReadInt32(); ++ var values = new List(size); ++ for (int j = 0; j < size; j++) values.Add(table[reader.ReadInt32()]); ++ merged.Add(id, values); ++ } ++ if (source.Position != source.Length) ++ throw new InvalidDataException("Unexpected name worker data."); ++ ++ result[0] = merged; ++ var completedEmpty = new Dictionary>(); ++ Array.Fill(result, completedEmpty, 1, prefix - 1); ++ Console.WriteLine($"IOExtend name prefix {prefix}/{chunks.Count} input {bytes} output {encoded.Length}, {table.Length} names."); ++ }; ++ } ++} +--- /dev/null ++++ b/src/RvtIO/RvtFileReader.BrowserParameterBatches.cs +@@ -0,0 +1,184 @@ ++using System.Runtime.InteropServices; ++using System.Text; ++using RvtIO.Parsing; ++using static RvtIO.Parsing.TfBlockDeserializer; ++ ++namespace RvtIO; ++ ++public partial class RvtFileReader ++{ ++ private static readonly bool ParameterStringTable = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAM_STRING_CONTROL") != "1"; ++ ++ /// Dispatches local browser parameter work. ++ public static Func? BrowserDecodeParameterBatches { get; set; } ++ ++ /// Decodes one independent browser parameter batch. ++ public static byte[] DecodeBrowserParameterBatch(byte[] input) ++ { ++ using var source = new MemoryStream(input, writable: false); ++ using var reader = new BinaryReader(source); ++ using var output = new MemoryStream(); ++ using var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true); ++ var strings = ParameterStringTable ? new Dictionary(StringComparer.Ordinal) : null; ++ while (source.Position < source.Length) ++ { ++ int group = reader.ReadInt32(); ++ bool hasNative = reader.ReadBoolean(), hasRoot = reader.ReadBoolean(), r22View = reader.ReadBoolean(); ++ int jobs = reader.ReadInt32(); ++ for (int j = 0; j < jobs; j++) ++ { ++ int index = reader.ReadInt32(); ++ uint size = reader.ReadUInt32(); ++ ushort cls = reader.ReadUInt16(); ++ bool root = reader.ReadBoolean(); ++ int start = checked((int)source.Position); ++ source.Seek(checked((int)size + 16), SeekOrigin.Current); ++ if (source.Position > source.Length) throw new InvalidDataException("Incomplete parameter block."); ++ bool mergeDrive = hasNative && root && hasRoot && r22View && IsSubclassOf(cls, 1794); ++ if (hasNative && (!root || hasRoot) && !mergeDrive) continue; ++ var values = ExtractParams(input, start, size, cls); ++ if (values == null || (!mergeDrive && values.Count == 0)) continue; ++ // Complex entities are replayed through the regular decoder for this owner. ++ if (values.ExtensibleStorage != null) ++ { ++ writer.Write(~group); ++ continue; ++ } ++ if (!mergeDrive) ++ { ++ hasNative = true; ++ hasRoot |= root; ++ } ++ writer.Write(index); ++ writer.Write(root && !mergeDrive); ++ writer.Write(mergeDrive); ++ WriteBrowserParameters(writer, values, strings); ++ } ++ } ++ return output.ToArray(); ++ } ++ ++ private static void WriteBrowserString(BinaryWriter writer, string value, ++ Dictionary? table = null) ++ { ++ if (table != null) ++ { ++ int index = table.Count; ++ ref int entry = ref CollectionsMarshal.GetValueRefOrAddDefault(table, value, out bool existing); ++ if (existing) ++ { ++ writer.Write(~entry); ++ return; ++ } ++ entry = index; ++ } ++ writer.Write(value.Length); ++ writer.Write(MemoryMarshal.AsBytes(value.AsSpan())); ++ } ++ ++ private static string ReadBrowserString(BinaryReader reader, List? table = null) ++ { ++ int token = reader.ReadInt32(); ++ if (token < 0) ++ { ++ int index = ~token; ++ if (table == null || (uint)index >= (uint)table.Count) ++ throw new InvalidDataException("Unknown parameter string reference."); ++ return table[index]; ++ } ++ string value = string.Create(token, reader.BaseStream, ++ static (chars, stream) => stream.ReadExactly(MemoryMarshal.AsBytes(chars))); ++ table?.Add(value); ++ return value; ++ } ++ ++ private static void WriteBrowserParameters(BinaryWriter writer, NativeParams values, Dictionary? strings) ++ { ++ writer.Write(values.RootParameterStoresComplete); ++ writer.Write(values.TailWalkComplete); ++ writer.Write(values.CellClasses?.Length ?? -1); ++ if (values.CellClasses != null) ++ foreach (int item in values.CellClasses) writer.Write(item); ++ writer.Write(values.RoofExtrusionFaceTags?.Count ?? -1); ++ if (values.RoofExtrusionFaceTags != null) ++ foreach (int item in values.RoofExtrusionFaceTags) writer.Write(item); ++ writer.Write(values.Doubles.Count); ++ foreach (var (id, value) in values.Doubles) { writer.Write(id); writer.Write(value); } ++ writer.Write(values.Ints.Count); ++ foreach (var (id, value) in values.Ints) { writer.Write(id); writer.Write(value); } ++ writer.Write(values.Strings.Count); ++ foreach (var (id, value) in values.Strings) { writer.Write(id); WriteBrowserString(writer, value, strings); } ++ writer.Write(values.ElementIds.Count); ++ foreach (var (id, value) in values.ElementIds) { writer.Write(id); writer.Write(value); } ++ writer.Write(values.NamedParams.Count); ++ foreach (var value in values.NamedParams) ++ { ++ writer.Write(value.ParamId); ++ writer.Write(value.Str != null); ++ if (value.Str != null) WriteBrowserString(writer, value.Str, strings); ++ writer.Write(value.Value); ++ writer.Write(value.ElemId); ++ writer.Write(value.Int); ++ writer.Write(value.Instance); ++ writer.Write(value.Reporting); ++ } ++ writer.Write(values.Fields.Count); ++ foreach (var (key, value) in values.Fields) { WriteBrowserString(writer, key, strings); writer.Write(value); } ++ var doubles = values.CapturedDoubleFields; ++ writer.Write(doubles?.Count ?? 0); ++ if (doubles != null) ++ foreach (var (key, value) in doubles) { WriteBrowserString(writer, key, strings); writer.Write(value); } ++ var stringsByField = values.CapturedStringFields; ++ writer.Write(stringsByField?.Count ?? 0); ++ if (stringsByField != null) ++ foreach (var (key, value) in stringsByField) { WriteBrowserString(writer, key, strings); WriteBrowserString(writer, value, strings); } ++ } ++ ++ private static NativeParams ReadBrowserParameters(BinaryReader reader, List? strings) ++ { ++ var values = new NativeParams ++ { ++ RootParameterStoresComplete = reader.ReadBoolean(), ++ TailWalkComplete = reader.ReadBoolean(), ++ }; ++ int length = reader.ReadInt32(); ++ if (length >= 0) ++ { ++ values.CellClasses = new int[length]; ++ for (int i = 0; i < length; i++) values.CellClasses[i] = reader.ReadInt32(); ++ } ++ length = reader.ReadInt32(); ++ if (length >= 0) ++ { ++ values.RoofExtrusionFaceTags = new(length); ++ for (int i = 0; i < length; i++) values.RoofExtrusionFaceTags.Add(reader.ReadInt32()); ++ } ++ length = reader.ReadInt32(); ++ values.Doubles.EnsureAdditionalCapacity(length); ++ for (int i = 0; i < length; i++) values.Doubles.Add((reader.ReadInt32(), reader.ReadDouble())); ++ length = reader.ReadInt32(); ++ values.Ints.EnsureAdditionalCapacity(length); ++ for (int i = 0; i < length; i++) values.Ints.Add((reader.ReadInt32(), reader.ReadInt32())); ++ length = reader.ReadInt32(); ++ values.Strings.EnsureAdditionalCapacity(length); ++ for (int i = 0; i < length; i++) values.Strings.Add((reader.ReadInt32(), ReadBrowserString(reader, strings))); ++ length = reader.ReadInt32(); ++ values.ElementIds.EnsureAdditionalCapacity(length); ++ for (int i = 0; i < length; i++) values.ElementIds.Add((reader.ReadInt32(), reader.ReadInt32())); ++ length = reader.ReadInt32(); ++ values.NamedParams.EnsureAdditionalCapacity(length); ++ for (int i = 0; i < length; i++) ++ values.NamedParams.Add(new(reader.ReadInt32(), reader.ReadBoolean() ? ReadBrowserString(reader, strings) : null, ++ reader.ReadDouble(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadBoolean(), reader.ReadBoolean())); ++ length = reader.ReadInt32(); ++ for (int i = 0; i < length; i++) values.Fields.Add(ReadBrowserString(reader, strings), reader.ReadInt32()); ++ length = reader.ReadInt32(); ++ for (int i = 0; i < length; i++) values.DoubleFields.Add(ReadBrowserString(reader, strings), reader.ReadDouble()); ++ length = reader.ReadInt32(); ++ for (int i = 0; i < length; i++) values.StringFields.Add(ReadBrowserString(reader, strings), ReadBrowserString(reader, strings)); ++ return values; ++ } ++} ++ ++ ++ +--- a/src/RvtIO/RvtFileReader.cs ++++ b/src/RvtIO/RvtFileReader.cs +@@ -1,3 +1,5 @@ ++using System.Buffers; ++using System.Runtime.InteropServices; + using OpenMcdf; + using RvtIO.Internal; + using RvtIO.Model; +@@ -227,24 +229,39 @@ + LogPhase("Records parsed"); + + var unreadableGReps = GRepParserV2.IsDecodeTracingEnabled() ? null : new HashSet(); ++ var browserWork = BrowserStartInitialGeo != null && unreadableGReps != null ++ && OperatingSystem.IsBrowser() && (state.WideSchema == null || state.R22View) ++ ? new BrowserGeometryOverlap() : null; + var blockGeometry = ParseBlocks(state, diag, progress, unreadableGReps, + overlapGeometry: progress == null && unreadableGReps != null +- && !OperatingSystem.IsBrowser() && (state.WideSchema == null || state.R22View)); ++ && !OperatingSystem.IsBrowser() && (state.WideSchema == null || state.R22View), ++ browserWork: browserWork); + // ParseBlocks has finished adding record/block-only IDs. The scalar walk and + // geometry recovery only read that set; neither consumes the scanned strings. + // Snapshot the ID set: the background geometry decode still runs while the scan reads it. + bool releasePartitions = ReleaseExportPartitions && wideSchema == null; + var scanIds = new HashSet(state.AllKnownIds); ++ var browserNames = releasePartitions ? null : TryStartBrowserNameScan(chunks, scanIds); + var stringScan = blockGeometry != null ? Task.Run(ScanElementStrings) : null; + // The anchored walk reaches blocks spanning chunks and decodes the native parameter stores. ++ ExternalCaptionCandidates? stagedCaptions = null; ++ Action? scanWhileWaiting = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_CAPTIONS_DURING_GEOMETRY") == "1" ++ ? () => ++ { ++ var clock = System.Diagnostics.Stopwatch.StartNew(); ++ stagedCaptions = ScanExternalParamCaptions(state); ++ Console.WriteLine($"IOExtend captions during geometry {clock.ElapsedMilliseconds} ms"); ++ } ++ : null; + try + { + LogPhase("Blocks parsed"); + progress?.Report(new("parameter-stream")); +- RunTfStreamWalk(state, progress, unreadableGReps, blockGeometry); ++ RunTfStreamWalk(state, progress, unreadableGReps, blockGeometry, browserWork, scanWhileWaiting); + } + finally + { ++ browserWork?.Complete(); + // Join both background tasks. A single failure keeps its type; two surface together instead of one hiding the other. + try { Task.WaitAll(new Task?[] { blockGeometry, stringScan }.OfType().ToArray()); } + catch (AggregateException failure) when (failure.InnerExceptions.Count == 1) +@@ -274,9 +291,12 @@ + + void ScanElementStrings() + { ++ var nameClock = System.Diagnostics.Stopwatch.StartNew(); + var partialResults = new Dictionary>?[chunks.Count]; ++ browserNames?.Invoke(partialResults); + Parallel.For(0, chunks.Count, chunkIndex => + { ++ if (partialResults[chunkIndex] != null) return; + var localStrings = new Dictionary>(); + StringScanner.ScanChunk(chunks[chunkIndex], scanIds, localStrings, namesAndCaptionsOnly: releasePartitions); + if (localStrings.Count > 0) partialResults[chunkIndex] = localStrings; +@@ -506,7 +526,7 @@ + } + + // Method 2: FFFFFFFF+GUID+Caption scan in raw chunk regions (for External params) +- ExtractExternalParamCaptionsFromRaw(state, ref rawCaptionApplied, diag); ++ ExtractExternalParamCaptionsFromRaw(state, ref rawCaptionApplied, diag, stagedCaptions); + + // Method 3: Tf ParamDef structure parsing - find m_paramElemId after ForgeId+GroupTypeId + // Layout: [Caption][FFFFFFFF+hdr+GUID][ForgeId][GroupTypeId?][m_paramElemId:int64/int32] +@@ -1040,19 +1060,25 @@ + partialResults[chunkIndex] = null; + if (partial == null) continue; + +- foreach (var (eid, strings) in partial) +- { +- // ScanChunk has already deduplicated each local list. Transfer the first +- // one; only owners seen in another chunk need a cross-chunk membership set. +- if (elemScanStrings.TryAdd(eid, strings)) continue; +- var list = elemScanStrings[eid]; +- mergeSeen.TryGetValue(eid, out var seen); +- foreach (var s in strings) +- { +- if (namesAndCaptionsOnly && list.Count > 0 && !StringScanner.UsedForParameterCaption(s)) continue; +- if (seen == null) mergeSeen[eid] = seen = new HashSet(list); +- if (seen.Add(s)) list.Add(s); +- } ++ MergeElemScanStringChunk(partial, elemScanStrings, mergeSeen, namesAndCaptionsOnly); ++ } ++ } ++ ++ private static void MergeElemScanStringChunk(Dictionary> partial, ++ Dictionary> elemScanStrings, Dictionary> mergeSeen, bool namesAndCaptionsOnly = false) ++ { ++ foreach (var (eid, strings) in partial) ++ { ++ // ScanChunk has already deduplicated each local list. Transfer the first ++ // one; only owners seen in another chunk need a cross-chunk membership set. ++ if (elemScanStrings.TryAdd(eid, strings)) continue; ++ var list = elemScanStrings[eid]; ++ mergeSeen.TryGetValue(eid, out var seen); ++ foreach (var s in strings) ++ { ++ if (namesAndCaptionsOnly && list.Count > 0 && !StringScanner.UsedForParameterCaption(s)) continue; ++ if (seen == null) mergeSeen[eid] = seen = new HashSet(list); ++ if (seen.Add(s)) list.Add(s); + } + } + } +@@ -1545,6 +1571,9 @@ + return allChunks; + } + ++ /// Dispatches complete framed gzip members to the browser's local decoders. ++ public static Func? BrowserInflatePartitionMembers { get; set; } ++ + /// The chunks of a partition stream: when its framing holds (), the output of each segment, every one a + /// gzip member checked by its CRC and length, and null; otherwise the members a search for gzip headers + /// finds, with the recovery of damaged ones (), and the reason the framing does not hold. +@@ -1570,7 +1599,7 @@ + if (r.Body.Span.IndexOf(cellTagBytes!) >= 0) + familyItems.Add(new(r.Key, new(r.Channel, r.Owner, r.Offset, r.Item.Length))); + } +- }, out framingFailure, out _, null, segments)) ++ }, out framingFailure, out _, null, segments, BrowserInflatePartitionMembers)) + { + stats = (segments.Count, segments.Count, 0, 0, 0); + framed = new PartitionFraming.Framed(segments, items, idWidth) { FamilyEntityCandidates = familyItems, FamilyKeys = familyKeys }; +@@ -2688,7 +2717,8 @@ + /// stores + full-coverage re-run of block-driven signals (curve owners, node owners, + /// registry categories, sketch/detail curves). + internal static void RunTfStreamWalk(ParsingState state, IProgress? progress = null, +- HashSet? unreadable = null, Task? blockGeometry = null) ++ HashSet? unreadable = null, Task? blockGeometry = null, ++ BrowserGeometryOverlap? browserWork = null, Action? beforeRecoveryWait = null) + { + // The walk reads 4-byte ids and Revit 2022 class numbers; a 64-bit-id file is decoded by WideElementRecords. + if (state.WideSchema != null && !state.R22View) return; +@@ -2699,6 +2729,10 @@ + foreach (var part in dumpGrepEnv.Split(',')) + if (uint.TryParse(part, out uint dge)) dumpGrepEids.Add(dge); + var wallGeometryCandidates = new List<(byte[] Data, int Start, uint Size, ushort Cls, uint Owner)>(); ++ using var earlyAnchored = PrefetchAnchoredGeometry && blockGeometry == null && !GRepParserV2.IsDecodeTracingEnabled() ++ && BrowserDecodeGeometryBatches != null && BrowserStartGeometryPipeline is { } startAnchored ++ && BrowserCollectDecoder is { } collectAnchored ++ ? new BrowserAnchoredGeometry(startAnchored, collectAnchored) : null; + var segmentSources = new TfStreamWalker.SegmentSources(); + var nativeBlocks = new TfNativeBlocks(state, segmentSources); + // the roots the class and stair sources count: the records of the project's block when every stream is read by its framing +@@ -2706,11 +2740,13 @@ + List<(byte[] Data, int Start, uint Size, ushort Class, uint Owner)>? unanchoredTypeRoots = + framedRoots ? [] : null; + if (framedRoots) RecordFramedRoots(state, unanchoredTypeRoots); +- if (progress is null && dumpGrepEids.Count == 0 && !TfBlockDeserializer.CaptureAllFields) +- TfStreamWalker.WalkBounded(state.Chunks, state.AllKnownIds, VisitBlock, VisitRecord, segmentSources); ++ Action? reportPosition = progress is null ++ ? null : (completed, total) => progress.Report(new("parameter-stream", completed, total)); ++ if (dumpGrepEids.Count == 0 && !TfBlockDeserializer.CaptureAllFields) ++ TfStreamWalker.WalkBounded(state.Chunks, state.AllKnownIds, VisitBlock, VisitRecord, segmentSources, ++ progress: reportPosition); + else +- TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, VisitBlock, VisitRecord, +- progress is null ? null : (completed, total) => progress.Report(new("parameter-stream", completed, total)), ++ TfStreamWalker.Walk(state.Chunks, state.AllKnownIds, VisitBlock, VisitRecord, reportPosition, + sources: segmentSources); + nativeBlocks.Flush(); + +@@ -2833,6 +2869,9 @@ + { + var (data, start) = segmentSources.Retain(seg, bs, (int)ds + 16); + wallGeometryCandidates.Add((data, start, ds, cls, eid)); ++ if (earlyAnchored != null && browserWork?.PendingOwners?.Contains(eid) != true ++ && !state.GrepBlocks.ContainsKey(eid) && unreadable?.Contains(new(data, start, ds)) != true) ++ earlyAnchored.Add(new(data, start, ds)); + } + // Sketch/detail curves at full coverage (safe: extraction has strict filters). + if (cls == 0x0346 && !state.SketchCurves.ContainsKey(eid)) +@@ -2888,11 +2927,14 @@ + blockGeometry.GetAwaiter().GetResult(); + DiagnosticSink.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); + } ++ byte[]? earlyAnchoredResult = earlyAnchored?.Receive(); ++ browserWork?.Complete(); + var walkGReps = new List<(byte[] Segment, int Start, uint Size, uint Eid)>(); + foreach (var candidate in wallGeometryCandidates) + if (!state.GrepBlocks.ContainsKey(candidate.Owner)) + walkGReps.Add((candidate.Data, candidate.Start, candidate.Size, candidate.Owner)); +- ApplyFirstDecodableGReps(state, walkGReps, unreadable); ++ var prefetchedAnchored = earlyAnchoredResult is { Length: > 0 } ? earlyAnchored!.ReadResults(earlyAnchoredResult) : null; ++ ApplyFirstDecodableGReps(state, walkGReps, unreadable, prefetched: prefetchedAnchored); + + // Second pass: geometry blocks the anchored walk missed. Family symbols live in + // the family doc's own id space (absent from ElemTable), so whole symbol regions +@@ -2923,9 +2965,18 @@ + int foundSketch = 0; + var scanGReps = new List<(byte[] Segment, int Start, uint Size, uint Eid)>(); + bool scanSlices = dumpGrepEids.Count == 0 && !GRepParserV2.IsDecodeTracingEnabled(); ++ using var prepared = scanSlices ++ && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_RECOVERY_SCAN") == "1" ++ && BrowserDecodeGeometryBatches != null && BrowserCollectDecoder != null ++ && BrowserStartGeometryPipeline is { } startRecovery ++ ? new BrowserRecoveryPrefix(startRecovery) : null; ++ var scanClock = System.Diagnostics.Stopwatch.StartNew(); + if (scanSlices) TfStreamWalker.ScanBlockSlices(state.Chunks, missingIds, VisitTarget); + else TfStreamWalker.ScanBlocks(state.Chunks, missingIds, VisitTarget, segmentSources); +- int found = ApplyFirstDecodableGReps(state, scanGReps, unreadable); ++ prepared?.CompleteBatch(); ++ if (BrowserStartGeometryPipeline != null) ++ Console.WriteLine($"IOExtend recovery scan {scanGReps.Count} candidates {scanClock.ElapsedMilliseconds} ms"); ++ int found = ApplyFirstDecodableGReps(state, scanGReps, unreadable, beforeRecoveryWait, prepared?.Batches); + DiagnosticSink.WriteLine($" [gscan] targeted scan recovered {found} G-blocks + {foundSketch} sketch curves for {missingIds.Count} candidate ids"); + + void VisitTarget(byte[] seg, int bs, uint ds, ushort cls, uint eid) +@@ -2967,6 +3018,8 @@ + if (state.GrepBlocks.ContainsKey(eid)) return; + var (data, start) = scanSlices ? (seg, bs) : segmentSources.Retain(seg, bs, (int)ds + 16); + scanGReps.Add((data, start, ds, eid)); ++ if (prepared != null && unreadable?.Contains(new(data, start, ds)) != true) ++ prepared.Add((data, start, ds)); + } + } + ReadOwnWallPlanarBodies(state, wallGeometryCandidates); +@@ -2974,14 +3027,64 @@ + + /// Decodes collected GRep blocks in parallel and stores, in collection order, the first decodable block of + /// each element that has none yet. Returns the number stored. +- private static int ApplyFirstDecodableGReps( ++ internal static int ApplyFirstDecodableGReps( + ParsingState state, List<(byte[] Segment, int Start, uint Size, uint Eid)> jobs, +- HashSet? unreadable) ++ HashSet? unreadable, Action? beforeRecoveryWait = null, ++ IReadOnlyList? prefix = null, ++ IReadOnlyDictionary? prefetched = null) + { + // Previous passes already rejected these exact byte ranges. Group only candidates that can be tried. + if (unreadable is { Count: > 0 }) + jobs.RemoveAll(job => unreadable.Contains(new(job.Segment, job.Start, job.Size))); + if (jobs.Count == 0) return 0; ++ int fromWorkers = 0; ++ List? missing = null; ++ bool skipCurves = BrowserDecodeGeometryBatches != null ++ && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_CURVE_ONLY_GEOMETRY") == "1" ++ && !GRepParserV2.IsDecodeTracingEnabled(); ++ if (prefetched is { Count: > 0 } || skipCurves) ++ { ++ missing = []; ++ bool verifyCurves = skipCurves && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_VERIFY_CURVE_ONLY") == "1"; ++ int curves = 0, reused = 0; ++ long curveBytes = 0; ++ for (int i = 0; i < jobs.Count; i++) ++ { ++ var job = jobs[i]; ++ if (prefetched?.ContainsKey(Key(job)) == true) ++ reused++; ++ else if (skipCurves && GRepParserV2.IsCurveOnlyRepresentation(job.Segment, job.Start, job.Size)) ++ { ++ if (verifyCurves && GRepParserV2.Parse(job.Segment, job.Start, job.Size) != null) ++ throw new InvalidDataException("The full decoder found geometry in a curve-only block."); ++ curves++; ++ curveBytes += job.Size + 24L; ++ } ++ else missing.Add(i); ++ } ++ if (prefetched is { Count: > 0 }) ++ Console.WriteLine($"IOExtend anchored geometry reused {reused} of {jobs.Count} jobs"); ++ if (curves > 0) ++ Console.WriteLine($"IOExtend curve-only geometry skipped {curves} of {jobs.Count} jobs, {curveBytes} bytes"); ++ if (missing.Count == jobs.Count) missing = null; ++ } ++ int applied = 0; ++ if (missing?.Count == 0 || TryDecodeBrowserGeometry(missing?.Count ?? jobs.Count, index => ++ { ++ var job = jobs[missing?[index] ?? index]; ++ return (job.Segment, job.Start, job.Size); ++ }, ++ (index, geometry) => ++ { ++ int position = missing?[index] ?? index; ++ ApplyThrough(position); ++ Apply(position, geometry); ++ applied = position + 1; ++ }, beforeRecoveryWait, prefix)) ++ { ++ if (missing != null) ApplyThrough(jobs.Count); ++ return fromWorkers; ++ } + bool slowDiag = Environment.GetEnvironmentVariable("RVTIO_GREP_SLOW") is { Length: > 0 }; + if (OperatingSystem.IsBrowser() || unreadable == null || slowDiag) + { +@@ -3027,6 +3130,27 @@ + } + return stored; + ++ void ApplyThrough(int end) ++ { ++ while (applied < end) ++ { ++ GRepData? geometry = null; ++ prefetched?.TryGetValue(Key(jobs[applied]), out geometry); ++ Apply(applied, geometry); ++ applied++; ++ } ++ } ++ ++ void Apply(int index, GRepData? geometry) ++ { ++ var job = jobs[index]; ++ if (geometry == null) unreadable?.Add(Key(job)); ++ if (StoreFirstDecodableGRep(state, job.Eid, geometry)) fromWorkers++; ++ } ++ ++ static BlockParser.GRepRange Key((byte[] Segment, int Start, uint Size, uint Eid) job) => ++ new(job.Segment, job.Start, job.Size); ++ + GRepData? Decode((byte[] Segment, int Start, uint Size, uint Eid) job) + { + var clock = slowDiag ? System.Diagnostics.Stopwatch.StartNew() : null; +@@ -3041,8 +3165,21 @@ + internal static bool StoreFirstDecodableGRep(ParsingState state, uint eid, GRepData? geometry) => + geometry != null && state.GrepBlocks.TryAdd(eid, geometry); + ++ internal sealed class BrowserGeometryOverlap ++ { ++ internal Action? Finish; ++ internal HashSet? PendingOwners; ++ internal void Complete() ++ { ++ var pending = Finish; ++ Finish = null; ++ pending?.Invoke(); ++ } ++ } ++ + internal static Task? ParseBlocks(ParsingState state, TextWriter? diag, IProgress? progress = null, +- HashSet? unreadable = null, bool overlapGeometry = false) ++ HashSet? unreadable = null, bool overlapGeometry = false, ++ BrowserGeometryOverlap? browserWork = null) + { + const int passCount = 8; + int completedPasses = 0; +@@ -3117,7 +3254,9 @@ + BlockParser.ParseChunk(chunk, state, collectBlockOnlyIds: true, deferred: firstPassGReps); + foreach (var chunk in state.RecordChunks.Where(Scanned)) + BlockParser.ParseChunk(chunk, state, collectBlockOnlyIds: true, deferred: firstPassGReps); +- if (!overlapGeometry) BlockParser.ApplyPendingGReps(state, firstPassGReps, unreadable); ++ Action? firstPassCompletion = browserWork == null ? null : TryStartInitialGeometry(firstPassGReps, state, unreadable); ++ if (!overlapGeometry && firstPassCompletion == null) ++ BlockParser.ApplyPendingGReps(state, firstPassGReps, unreadable); + diag?.WriteLine($"Block-only elements: {state.BlockOnlyIds.Count}"); + + Lap("first parse pass"); +@@ -3133,11 +3272,22 @@ + foreach (var chunk in state.RecordChunks.Where(Scanned)) + BlockParser.ParseChunk(chunk, state, deferred: secondPassGReps); + BlockParser.SkipRepeatedFirstGReps(firstPassGReps, secondPassGReps); +- if (!overlapGeometry) BlockParser.ApplyPendingGReps(state, secondPassGReps, unreadable); ++ if (!overlapGeometry && firstPassCompletion == null) ++ BlockParser.ApplyPendingGReps(state, secondPassGReps, unreadable); + } + Lap("second parse pass"); + bool deferGeometry = overlapGeometry && (firstPassGReps.Count > 0 || secondPassGReps.Count > 0); +- if (!deferGeometry) diag?.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); ++ if (firstPassCompletion != null) ++ { ++ if (PrefetchAnchoredGeometry) ++ browserWork!.PendingOwners = firstPassGReps.Concat(secondPassGReps).Select(job => job.Eid).ToHashSet(); ++ browserWork!.Finish = () => ++ { ++ firstPassCompletion(); ++ BlockParser.ApplyPendingGReps(state, secondPassGReps, unreadable); ++ }; ++ } ++ else if (!deferGeometry) diag?.WriteLine($"GRep blocks: {state.GrepBlocks.Count} elements"); + diag?.WriteLine($"FamilyInstance transforms: {state.FamilyInstanceTransforms.Count} elements"); + diag?.WriteLine($"Dimensions/constraints (0x091F+0x009D): {state.Dimensions.Count} elements"); + diag?.WriteLine($"Sketch-line curves (0x0346): {state.SketchCurves.Count} elements"); +@@ -3234,9 +3384,11 @@ + } + + +- /// Extract External param captions from FFFFFFFF+GUID+Caption pattern in raw chunk data. +- /// Also resolves GUID to elemId via record chunk [GUID:16][elemId:4] table. +- private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref int applied, TextWriter? diag) ++ private sealed record ExternalCaptionCandidates(Dictionary Captions, ++ Dictionary?[] ElementIdsByChunk); ++ ++ // Reads raw chunks and the known-ID index. Applying the captions still follows the catalog and ForgeId passes. ++ private static ExternalCaptionCandidates ScanExternalParamCaptions(ParsingState state) + { + // Scan all chunks for [FFFFFFFF][header][GUID:16][00 00][nameLen:4][caption] + var guidToCaption = new Dictionary(); +@@ -3290,6 +3442,31 @@ + } + return captions; + } ++ var guidMapClock = System.Diagnostics.Stopwatch.StartNew(); ++ var captionPrefixes = BuildGuidPrefixSet(guidToCaption.Keys); ++ string? guidSearchMode = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_GUID_SEARCH"); ++ var captionPrefixBitmap = guidSearchMode == "2" && captionPrefixes.Count != 0 ++ ? BuildGuidPrefixBitmap(captionPrefixes) ++ : null; ++ var captionFirstWords = BitConverter.IsLittleEndian && guidSearchMode == "1" && captionPrefixes.Count != 0 ++ ? SearchValues.Create(captionPrefixes.Select(prefix => (char)prefix).ToArray()) ++ : null; ++ var idsByChunk = new Dictionary?[state.RecordChunks.Count]; ++ Parallel.For(0, idsByChunk.Length, index => ++ { ++ var ids = new Dictionary(); ++ MapRecordChunkGuids(state.RecordChunks[index], guidToCaption, captionPrefixes, state.AllKnownIds, ids, captionFirstWords, captionPrefixBitmap); ++ if (ids.Count > 0) idsByChunk[index] = ids; ++ }); ++ Console.WriteLine($"IOExtend record GUIDs {guidMapClock.ElapsedMilliseconds} ms " + ++ $"prefixes {captionPrefixes.Count} search {guidSearchMode ?? "0"}"); ++ return new(guidToCaption, idsByChunk); ++ } ++ ++ private static void ExtractExternalParamCaptionsFromRaw(ParsingState state, ref int applied, TextWriter? diag, ++ ExternalCaptionCandidates? staged) ++ { ++ var (guidToCaption, idsByChunk) = staged ?? ScanExternalParamCaptions(state); + // Resolve GUID to elemId via record chunk table [GUID:16][elemId:4] + var guidToElemId = new Dictionary(); + foreach (var (eid, g) in state.ParamDefGuids) +@@ -3299,14 +3476,6 @@ + var g = BipHelpers.ParseGuidFromForgeId(def.ForgeId); + if (g.HasValue) guidToElemId.TryAdd(g.Value, eid); + } +- var captionPrefixes = BuildGuidPrefixSet(guidToCaption.Keys); +- var idsByChunk = new Dictionary?[state.RecordChunks.Count]; +- Parallel.For(0, idsByChunk.Length, index => +- { +- var ids = new Dictionary(); +- MapRecordChunkGuids(state.RecordChunks[index], guidToCaption, captionPrefixes, state.AllKnownIds, ids); +- if (ids.Count > 0) idsByChunk[index] = ids; +- }); + foreach (var ids in idsByChunk) + if (ids != null) + foreach (var (guid, eid) in ids) guidToElemId[guid] = eid; +@@ -3338,15 +3507,48 @@ + return set; + } + ++ private const int GuidPrefixBitmapSize = 1 << 18; ++ ++ internal static ulong[] BuildGuidPrefixBitmap(HashSet prefixes) ++ { ++ var bitmap = new ulong[GuidPrefixBitmapSize / 64]; ++ foreach (ulong prefix in prefixes) ++ { ++ int index = GuidPrefixBitmapIndex(prefix); ++ bitmap[index >> 6] |= 1UL << (index & 63); ++ } ++ return bitmap; ++ } ++ ++ private static int GuidPrefixBitmapIndex(ulong prefix) => ++ (int)((prefix ^ (prefix >> 32)) & (GuidPrefixBitmapSize - 1UL)); ++ + /// Scans one record chunk at every even offset for [GUID:16][elemId:4] where the GUID has a caption; the last match wins. + /// No allocation per offset: a GUID can be a key only if its first 8 bytes are in . + internal static void MapRecordChunkGuids(byte[] chunk, Dictionary guidToCaption, HashSet prefixes, +- HashSet knownIds, Dictionary guidToElemId) ++ HashSet knownIds, Dictionary guidToElemId, SearchValues? firstWords = null, ++ ulong[]? prefixBitmap = null) + { + if (prefixes.Count == 0) return; +- for (int i = 0; i + 20 <= chunk.Length; i += 2) +- { +- if (!prefixes.Contains(System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(chunk.AsSpan(i, 8)))) continue; ++ int lastStart = chunk.Length - 20; ++ for (int i = 0; i <= lastStart; i += 2) ++ { ++ if (firstWords != null) ++ { ++ // Every eligible GUID starts on an even byte offset and begins with a known 16-bit prefix word. ++ int candidateBytes = ((lastStart - i) & ~1) + 2; ++ var candidates = MemoryMarshal.Cast(chunk.AsSpan(i, candidateBytes)); ++ int next = candidates.IndexOfAny(firstWords); ++ if (next < 0) break; ++ i += next * 2; ++ } ++ ulong prefix = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(chunk.AsSpan(i, 8)); ++ if (prefixBitmap != null) ++ { ++ int index = GuidPrefixBitmapIndex(prefix); ++ if ((prefixBitmap[index >> 6] & (1UL << (index & 63))) == 0) continue; ++ } ++ if (!prefixes.Contains(prefix)) continue; + var g = new Guid(chunk.AsSpan(i, 16)); + if (!guidToCaption.ContainsKey(g)) continue; + uint eid = BitConverter.ToUInt32(chunk, i + 16); +@@ -4026,3 +4228,6 @@ + public string ClassIdxHex => $"0x{ClassIdx:X8}"; + public double AvgSize => Count > 0 ? (double)TotalBytes / Count : 0; + } ++ ++ ++ +--- a/src/RvtIO/RvtFileReader.R22Layout.cs ++++ b/src/RvtIO/RvtFileReader.R22Layout.cs +@@ -5,6 +5,29 @@ + + public partial class RvtFileReader + { ++ /// Dispatches independent partition ranges to the browser's local workers. ++ public static Func? BrowserRewriteR22Ranges { get; set; } ++ private static R22Transcoder? _browserR22Worker; ++ ++ /// Prepares one browser worker to read ranges from the given source schema. ++ public static void BeginBrowserR22RangeWorker(byte[] schema, int width, bool trackIds) ++ { ++ ArgumentNullException.ThrowIfNull(schema); ++ if (width is not (4 or 8)) throw new ArgumentOutOfRangeException(nameof(width)); ++ using var shipped = typeof(RvtFileReader).Assembly.GetManifestResourceStream("RvtIO.Resources.r22_schemas.json") ++ ?? throw new InvalidOperationException("The Revit 2022 schema is unavailable."); ++ _browserR22Worker = R22Transcoder.CreateBrowserRangeWorker( ++ TfSchemaReader.Parse(schema), TfSchemaReader.ReadShipped2022(shipped), width, trackIds); ++ } ++ ++ /// Rewrites one prepared range and returns its output boundaries and identity keys. ++ public static byte[] DecodeBrowserR22Range(byte[] input, byte[] plan) => ++ (_browserR22Worker ?? throw new InvalidOperationException("The R22 worker was not initialized.")) ++ .EncodeBrowserRange(input, plan); ++ ++ /// Releases the range worker's source schema and rewrite plans. ++ public static void EndBrowserR22RangeWorker() => _browserR22Worker = null; ++ + /// The partition chunks of a file with the class schema of a later release () rewritten into the + /// Revit 2022 layout (see ); the chunks after the partition streams are kept. Also the number of rewritten + /// partition chunks and the framed streams with their records of the project's own block in that layout (null for a stream without +@@ -27,10 +50,18 @@ + // The unit of work is a stream: each partition stream and each framed stream the rewrite reads. + int streamCount = partitionStreams.Count + framedStreams.Count(frame => frame != null); + int streamsDone = 0; ++ bool parallel = !OperatingSystem.IsBrowser() ++ && Environment.GetEnvironmentVariable("IOEXTEND_PROBE_R22_PARALLEL") == "1"; ++ var dispatch = BrowserRewriteR22Ranges; ++ Func? browserRewrite = OperatingSystem.IsBrowser() && dispatch != null ++ ? (input, plan) => dispatch(schemaBytes, width, ids != null, input, plan) ++ : null; + progress?.Report(new("r22-layout", 0, streamCount)); + foreach (var stream in partitionStreams) + { +- rewritten.AddRange(transcoder.Stream(stream, out var stats)); ++ rewritten.AddRange(transcoder.Stream(stream, out var stats, parallel, browserRewrite)); ++ if (stats.ParallelRanges > 0) ++ Console.WriteLine($"IOExtend R22 parallel {stats.ParallelRanges} ranges"); + diag?.WriteLine($"Revit 2022 layout: {stats.Records} records ({stats.RecordsRewritten} rewritten), " + + $"{stats.RootBlocks} root blocks ({stats.RootBlocksRewritten}), {stats.OtherBlocks} other blocks ({stats.OtherBlocksRewritten}), " + + $"{stats.UnparsedBytes} bytes outside the section grammar"); +--- a/src/RvtIO/RvtFileReader.TfNativeBlocks.cs ++++ b/src/RvtIO/RvtFileReader.TfNativeBlocks.cs +@@ -1,3 +1,4 @@ ++using System.Text; + using RvtIO.Internal; + using RvtIO.Parsing; + +@@ -9,10 +10,29 @@ + private sealed class TfNativeBlocks(ParsingState state, TfStreamWalker.SegmentSources sources) + { + private const int Capacity = 32_768; +- private readonly List _blocks = []; ++ private static readonly int BrowserBatchBytes = ++ int.TryParse(Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAM_BATCH_MIB"), out int mib) ++ && mib is 2 or 8 ? mib * 1024 * 1024 : 4 * 1024 * 1024; ++ private static readonly bool TraceBatches = ++ Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAM_BATCH_DIAG") == "1"; ++ private List _blocks = []; ++ private HashSet? _previousOwners; ++ private Action? _pending; ++ private HashSet? _pendingOwners; ++ private int _nextChannel; ++ private static readonly bool Pipeline = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAMETER_PIPELINE") == "1"; ++ private static readonly bool SkipResolved = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_SKIP_RESOLVED_PARAMETERS") == "1"; ++ private static readonly bool DynamicPackets = Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAMETER_PACKETS") == "1"; ++ private readonly bool _defer = (OperatingSystem.IsBrowser() ++ || Environment.GetEnvironmentVariable("IOEXTEND_PROBE_PARAMETER_NATIVE_DEFER") == "1") ++ && BrowserStartDeferredParams != null && BrowserCollectDecoder != null; ++ private readonly Func? _browserDecoder = BrowserDecodeParameterBatches; ++ private long _batchBytes; + private readonly Dictionary _first = new(); + private int[]? _next; + private Update[]? _updates; ++ private int[]? _alternateNext; ++ private Update[]? _alternateUpdates; + + private readonly record struct Block(byte[] Data, int Start, uint Size, ushort Class, uint Owner, bool Root); + private readonly record struct Update(TfBlockDeserializer.NativeParams? Values, GridDatumData? Grid, +@@ -26,7 +46,7 @@ + return; + + var block = new Block(data, start, size, cls, owner, root); +- if (TfBlockDeserializer.CaptureAllFields || OperatingSystem.IsBrowser()) ++ if (TfBlockDeserializer.CaptureAllFields || (OperatingSystem.IsBrowser() && _browserDecoder == null)) + { + bool hasNative = state.NativeParams.ContainsKey(owner); + bool hasRoot = state.NativeParamsFromRootClass.Contains(owner); +@@ -37,39 +57,228 @@ + // Queued blocks outlive the walk's segment buffer, which can reach 1.4 GB; keep only the block. + var (kept, keptStart) = sources.Retain(data, start, (int)size + 16); + _blocks.Add(block with { Data = kept, Start = keptStart }); +- if (_blocks.Count == Capacity) Flush(); +- } +- +- internal void Flush() +- { ++ _batchBytes += size + 16; ++ if (_blocks.Count == Capacity || (_browserDecoder != null && _batchBytes >= BrowserBatchBytes)) ++ Flush(drain: false); ++ } ++ ++ internal void Flush(bool drain = true) ++ { ++ var pending = _pending; ++ var pendingOwners = _pendingOwners; ++ _pending = null; ++ _pendingOwners = null; ++ if (!Pipeline || drain || _blocks.Count == 0) ++ { ++ pending?.Invoke(); ++ pending = null; ++ pendingOwners = null; ++ } + if (_blocks.Count == 0) return; +- if (_next == null || _next.Length < _blocks.Count) +- { +- _next = new int[_blocks.Count]; +- _updates = new Update[_blocks.Count]; +- } +- var next = _next; +- var updates = _updates!; +- for (int i = _blocks.Count - 1; i >= 0; i--) +- { +- uint owner = _blocks[i].Owner; ++ ++ int channel = _defer && Pipeline ? _nextChannel : 0; ++ if (_defer && Pipeline) _nextChannel = channel == 0 ? 4 : 0; ++ var blocks = _blocks; ++ ref int[]? nextSlot = ref (channel == 0 ? ref _next : ref _alternateNext); ++ ref Update[]? updateSlot = ref (channel == 0 ? ref _updates : ref _alternateUpdates); ++ if (nextSlot == null || nextSlot.Length < blocks.Count) ++ { ++ nextSlot = new int[blocks.Count]; ++ updateSlot = new Update[blocks.Count]; ++ } ++ var next = nextSlot; ++ var updates = updateSlot!; ++ for (int i = blocks.Count - 1; i >= 0; i--) ++ { ++ uint owner = blocks[i].Owner; + next[i] = _first.GetValueOrDefault(owner, -1); + _first[owner] = i; + } +- Parallel.ForEach(_first, group => +- { +- bool hasNative = state.NativeParams.ContainsKey(group.Key); +- bool hasRoot = state.NativeParamsFromRootClass.Contains(group.Key); +- for (int i = group.Value; i >= 0; i = next[i]) +- updates[i] = Decode(_blocks[i], ref hasNative, ref hasRoot); +- }); +- for (int i = 0; i < _blocks.Count; i++) +- Apply(_blocks[i].Owner, updates[i]); +- Array.Clear(updates, 0, _blocks.Count); +- _blocks.Clear(); ++ ++ Action? receive = null; ++ Action? decodeBlocked = null; ++ if (_browserDecoder != null) ++ { ++ if (TraceBatches) ++ { ++ int overlaps = _previousOwners == null ? 0 : _first.Keys.Count(_previousOwners.Contains); ++ Console.WriteLine($"IOExtend parameter packet blocks {blocks.Count} owners {_first.Count} raw {_batchBytes} adjacentOwners {overlaps}"); ++ _previousOwners = new HashSet(_first.Keys); ++ } ++ receive = StartBrowserGroups(blocks, next, updates, _browserDecoder, _defer, channel, pendingOwners, out decodeBlocked); ++ } ++ else ++ Parallel.ForEach(_first, group => DecodeGroup(blocks, group.Value, next, updates)); ++ // Keep the scalar walk's visibility of parameter state unchanged between flushes. ++ pending?.Invoke(); ++ decodeBlocked?.Invoke(); ++ if (_defer && Pipeline && !drain && receive != null) _pendingOwners = new(_first.Keys); + _first.Clear(); +- } +- ++ _batchBytes = 0; ++ ++ void ApplyBatch() ++ { ++ receive?.Invoke(); ++ for (int i = 0; i < blocks.Count; i++) ++ Apply(blocks[i].Owner, updates[i]); ++ Array.Clear(updates, 0, blocks.Count); ++ blocks.Clear(); ++ } ++ ++ if (_defer && !drain && receive != null) ++ { ++ _blocks = []; ++ _pending = ApplyBatch; ++ } ++ else ApplyBatch(); ++ } ++ ++ private void DecodeGroup(List blocks, int head, int[] next, Update[] updates) ++ { ++ uint owner = blocks[head].Owner; ++ bool hasNative = state.NativeParams.ContainsKey(owner); ++ bool hasRoot = state.NativeParamsFromRootClass.Contains(owner); ++ for (int i = head; i >= 0; i = next[i]) ++ updates[i] = Decode(blocks[i], ref hasNative, ref hasRoot); ++ } ++ private Action? StartBrowserGroups(List blocks, int[] next, Update[] updates, ++ Func decode, bool defer, int channel, ++ HashSet? pendingOwners, out Action? decodeBlocked) ++ { ++ List? blocked = null; ++ var inputs = Enumerable.Range(0, 4).Select(_ => new MemoryStream()).ToArray(); ++ var writers = inputs.Select(stream => new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)).ToArray(); ++ var heads = new List(); ++ int skippedOwners = 0; ++ long skippedBytes = 0; ++ foreach (var (owner, head) in _first) ++ { ++ if (pendingOwners?.Contains(owner) == true) ++ { ++ (blocked ??= []).Add(head); ++ continue; ++ } ++ bool hasNative = state.NativeParams.ContainsKey(owner); ++ bool hasRoot = state.NativeParamsFromRootClass.Contains(owner); ++ bool needsDecode = !SkipResolved || !hasNative; ++ int count = 0; ++ long bytes = 0; ++ bool ordinary = true; ++ for (int i = head; i >= 0; i = next[i]) ++ { ++ var block = blocks[i]; ++ ordinary &= block.Class is not (2299 or 0x083C); ++ if (!needsDecode && block.Root) ++ needsDecode = !hasRoot || (state.R22View && TfBlockDeserializer.IsSubclassOf(block.Class, 1794)); ++ count++; ++ bytes += block.Size + 27; ++ } ++ if (ordinary && !needsDecode) ++ { ++ skippedOwners++; ++ skippedBytes += bytes; ++ continue; ++ } ++ if (!ordinary || bytes > 1024 * 1024) ++ { ++ DecodeGroup(blocks, head, next, updates); ++ continue; ++ } ++ ++ int shard = 0; ++ for (int i = 1; i < inputs.Length; i++) ++ if (inputs[i].Length < inputs[shard].Length) shard = i; ++ var writer = writers[shard]; ++ writer.Write(head); ++ writer.Write(hasNative); ++ writer.Write(hasRoot); ++ writer.Write(state.R22View); ++ writer.Write(count); ++ for (int i = head; i >= 0; i = next[i]) ++ { ++ var block = blocks[i]; ++ writer.Write(i); ++ writer.Write(block.Size); ++ writer.Write(block.Class); ++ writer.Write(block.Root); ++ writer.Write(block.Data.AsSpan(block.Start, checked((int)block.Size + 16))); ++ } ++ heads.Add(head); ++ } ++ ++ byte[][]? packed = heads.Count == 0 ? null : Array.ConvertAll(inputs, stream => stream.ToArray()); ++ foreach (var writer in writers) writer.Dispose(); ++ foreach (var input in inputs) input.Dispose(); ++ decodeBlocked = blocked == null ? null : DecodeBlocked; ++ if (TraceBatches && blocked is { Count: > 0 }) Console.WriteLine($"IOExtend parameter delayed owners {blocked.Count} channel {channel}"); ++ if (TraceBatches && skippedOwners > 0) ++ Console.WriteLine($"IOExtend parameter skipped owners {skippedOwners} bytes {skippedBytes}"); ++ if (packed == null) return null; ++ if (defer) ++ { ++ BrowserStartDeferredParams!(channel, packed[0], packed[1], packed[2], packed[3]); ++ return () => ReadResults(BrowserCollectDecoder!(channel)); ++ } ++ ++ ReadResults(decode(packed[0], packed[1], packed[2], packed[3])); ++ return null; ++ ++ void DecodeBlocked() ++ { ++ if (blocked == null) return; ++ foreach (int head in blocked) DecodeGroup(blocks, head, next, updates); ++ } ++ ++ void ReadResults(byte[] results) ++ { ++ using var source = new MemoryStream(results, writable: false); ++ using var reader = new BinaryReader(source); ++ var fallback = new HashSet(); ++ for (int shard = 0; shard < inputs.Length; shard++) ++ { ++ int length = reader.ReadInt32(); ++ if (length < 0) ++ { ++ foreach (int head in heads) DecodeGroup(blocks, head, next, updates); ++ break; ++ } ++ long end = source.Position + length; ++ if (end > source.Length) throw new InvalidDataException("Incomplete parameter batch."); ++ if (!DynamicPackets) ++ { ++ ReadPacket(end); ++ continue; ++ } ++ while (source.Position < end) ++ { ++ if (end - source.Position < sizeof(int)) throw new InvalidDataException("Incomplete parameter packet header."); ++ int packetLength = reader.ReadInt32(); ++ if (packetLength < 0 || packetLength > end - source.Position) ++ throw new InvalidDataException("Invalid parameter packet length."); ++ ReadPacket(source.Position + packetLength); ++ } ++ } ++ foreach (int head in fallback) DecodeGroup(blocks, head, next, updates); ++ ++ void ReadPacket(long end) ++ { ++ var strings = ParameterStringTable ? new List() : null; ++ while (source.Position < end) ++ { ++ int index = reader.ReadInt32(); ++ if (index < 0) ++ { ++ fallback.Add(~index); ++ continue; ++ } ++ bool root = reader.ReadBoolean(); ++ bool mergeDrive = reader.ReadBoolean(); ++ updates[index] = new Update(ReadBrowserParameters(reader, strings), null, root, mergeDrive); ++ } ++ if (source.Position != end) throw new InvalidDataException("Parameter packet length differs."); ++ } ++ } ++ } + private Update Decode(Block block, ref bool hasNative, ref bool hasRoot) + { + var (data, start, size, cls, _, root) = block; +@@ -116,3 +325,6 @@ + } + } + } ++ ++ ++ diff --git a/site/prepare-web-release.mjs b/site/prepare-web-release.mjs new file mode 100644 index 0000000..936828d --- /dev/null +++ b/site/prepare-web-release.mjs @@ -0,0 +1,181 @@ +import { createHash } from 'node:crypto'; +import { cp, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { brotliCompressSync, gzipSync } from 'node:zlib'; +import { downgradeProfiles } from './wwwroot/revit-versions.js'; + +const [destination, ...arguments_] = process.argv.slice(2); +const fallbackSource = arguments_[0] && !arguments_[0].startsWith('--') ? arguments_.shift() : undefined; +let fastSource; +if (arguments_[0] === '--fast-reader' && arguments_.length === 2) { + fastSource = arguments_[1]; + arguments_.length = 0; +} +if (!destination || arguments_.length) + throw new Error('Usage: node prepare-web-release.mjs [single-threaded-wwwroot] [--fast-reader ]'); +const root = resolve(destination); +const template = await readFile(new URL('./wwwroot/index.html', import.meta.url), 'utf8'); +const entries = [ + 'site.css', 'operations.css', 'site.js', 'operations.js', 'i18n.js', 'locale.js', 'translations.js', + 'formats.js', 'reader.js', 'reader-host.js', 'reader-profile.js', 'reader-scratch.js', 'viewer-theme.js', + 'export-worker.js', 'downgrade-worker.js', 'operation-worker.js', + 'revit-versions.js', ...downgradeProfiles.map(year => `profiles/${year}.rvt`), + 'brand/avatar.png', 'brand/banner.png', 'brand/voxel-building.png', +]; +const paged = ['mesh-pages-worker.js', 'paged-storage.js', 'paged-viewer.html']; +const parallelProfile = /^export \* as decoders from '\.\/reader-decoders\.js';?$/m; +if (parallelProfile.test(await readFile(join(root, 'reader-profile.js'), 'utf8'))) entries.push('reader-decoders.js'); +const optional = await Promise.all(paged.map(file => readFile(join(root, file)).catch(error => { + if (error.code === 'ENOENT') return null; + throw error; +}))); +if (optional.some((bytes, i) => i > 0 && Boolean(bytes) !== Boolean(optional[1]))) + throw new Error('The paged viewer and its storage module must be published together.'); +if (optional[1]) entries.push(...paged); + +const runtimeImports = { + 'reader.js': './_framework/dotnet.js', + 'export-worker.js': './model-export/_framework/dotnet.js', + 'downgrade-worker.js': './revit-downgrade/_framework/dotnet.js', +}; +const loaders = new Map(); +for (const specifier of Object.values(runtimeImports)) { + const name = specifier.slice(2); + const bytes = await readFile(join(root, name)).catch(error => { + if (error.code === 'ENOENT' && name.includes('/_framework/')) return null; + throw error; + }); + if (!bytes) { + loaders.set(specifier, name); + continue; + } + const fingerprint = createHash('sha256').update(bytes).digest('hex').slice(0, 24); + const versioned = name.replace(/\.js$/, `.${fingerprint}.js`); + await writeAsset(join(root, versioned), bytes); + loaders.set(specifier, versioned); +} +const assets = new Map(await Promise.all(entries.map(async name => { + const filename = join(root, name); + const runtime = runtimeImports[name]; + if (!runtime) return [name, await readFile(filename)]; + const source = await readFile(filename, 'utf8'); + const specifier = `'${runtime}'`; + if (!source.includes(specifier)) throw new Error(`Expected the runtime import in ${name}.`); + return [name, Buffer.from(source.replace(specifier, `'../../${loaders.get(runtime)}'`))]; +}))); + +let profile = assets.get('reader-profile.js').toString('utf8'); +if (/^export const threaded = true;?$/m.test(profile)) { + const fallback = await installFallback(fallbackSource); + profile += "\nexport const fallbackReader = '" + fallback + "'\n"; +} +if (fastSource) { + if (!optional[1]) throw new Error('The fast reader requires the paged fallback.'); + const fast = await installFastReader(fastSource); + const isolation = await readFile(new URL('./wwwroot/thread-isolation.js', import.meta.url)); + await writeAsset(join(root, 'thread-isolation.js'), isolation); + profile += "\nexport const fastReader = '" + fast + "'\n"; +} +assets.set('reader-profile.js', Buffer.from(profile)); + +const digest = createHash('sha256').update(template); +for (const [name, bytes] of assets) { + digest.update(`${name}\0${bytes.length}\0`).update(bytes); +} +const revision = `ui/${digest.digest('hex').slice(0, 24)}`; +const html = template.replace(/(href|src)="\.\/([^"]+)"/g, (_, attribute, name) => { + if (!assets.has(name)) throw new Error(`Missing release asset: ${name}`); + return `${attribute}="./${revision}/${name}"`; +}); + +async function writeAsset(path, bytes) { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, bytes); + if (/\.(?:css|js|html)$/.test(path)) { + await Promise.all([ + writeFile(path + '.br', brotliCompressSync(bytes)), + writeFile(path + '.gz', gzipSync(bytes)), + ]); + } +} + +async function readReaderModules(ui) { + const reader = await readFile(join(ui, 'reader.js')); + const dependencies = ['reader-host.js', 'reader-profile.js', 'viewer-theme.js']; + if (parallelProfile.test(await readFile(join(ui, 'reader-profile.js'), 'utf8'))) dependencies.push('reader-decoders.js'); + if (reader.includes("from './reader-scratch.js'")) dependencies.push('reader-scratch.js'); + const modules = await Promise.all(dependencies.map(async name => [name, await readFile(join(ui, name))])); + return new Map([['reader.js', reader], ...modules]); +} + +async function installFastReader(source) { + const index = await readFile(join(source, 'index.html'), 'utf8'); + const revision = index.match(/ + + + +
+
+
+
+

+ +
+ +
+
+
+

Перетащите модель

+
    +
  • .rvt Revit
  • +
  • .nwc Navisworks
  • +
+ +

Файл обрабатывается на вашем устройстве.

+
+ +
+ + + +
+ +
+ + diff --git a/site/wwwroot/locale.js b/site/wwwroot/locale.js new file mode 100644 index 0000000..1ae0551 --- /dev/null +++ b/site/wwwroot/locale.js @@ -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; + } +} diff --git a/site/wwwroot/mesh-pages-worker.js b/site/wwwroot/mesh-pages-worker.js new file mode 100644 index 0000000..4bf6144 --- /dev/null +++ b/site/wwwroot/mesh-pages-worker.js @@ -0,0 +1,51 @@ +import { buildLocalMeshPackage } from './paged-storage.js'; + +self.onmessage = async ({ data: { scratchDirectory, triangles, inlineViewer } }) => { + try { + let html; + if (inlineViewer) { + // The sandboxed frame has an opaque origin and cannot use the isolation service worker. + const viewer = await fetch(new URL('./paged-viewer.html', import.meta.url)); + if (!viewer.ok) throw new Error('view.pageFailed'); + html = await viewer.blob(); + } + await scratchDirectory.removeEntry('triangles'); + const source = await scratchDirectory.getFileHandle('partitions'); + const pages = await scratchDirectory.getDirectoryHandle('pages', { create: true }); + let lastUpdate = -Infinity; + const manifest = await buildLocalMeshPackage(await source.getFile(), pages, true, ({ phase, completed, total, level }) => { + const now = performance.now(); + if (completed > 0 && completed < total && now - lastUpdate < 500) return; + lastUpdate = now; + let percent = 98; + let key; + switch (phase) { + case 'triangles': + if (completed < total) percent = 97; + key = 'view.pageTriangles'; + break; + case 'overview': + key = 'view.pageOverview'; + break; + case 'properties': + key = 'view.pageProperties'; + break; + default: + return; + } + self.postMessage({ progress: { percent, key, completed, total, level } }); + }); + if (manifest.triangles !== triangles) + throw new Error('view.badTriangles'); + await scratchDirectory.removeEntry('partitions'); + const files = Object.create(null); + for await (const [name, handle] of pages.entries()) + files[name] = await handle.getFile(); + self.postMessage({ files, pages: manifest.pages.length, triangles, html }); + } catch (error) { + const detail = error.name === 'QuotaExceededError' || /no space available/i.test(error.message) + ? 'view.pageStorage' : error.message; + self.postMessage(detail === 'view.pageStorage' || detail === 'view.badTriangles' || detail === 'view.pageFailed' + ? { localized: { key: detail } } : { error: detail }); + } +}; diff --git a/site/wwwroot/operation-worker.js b/site/wwwroot/operation-worker.js new file mode 100644 index 0000000..b655a60 --- /dev/null +++ b/site/wwwroot/operation-worker.js @@ -0,0 +1,158 @@ +import { exportFormats, extensionOf, isRevit } from './formats.js'; +import { targetReleases } from './revit-versions.js'; + +function fail(key, values) { + throw Object.assign(new Error(key), { localized: { key, values } }); +} + +function mountInput(fs, directory, file, onRead) { + fs.mkdir(directory); + const name = file.name.replace(/[\\/:\u0000-\u001f]/g, '_'); + const path = directory + '/' + name; + fs.writeFile(path, new Uint8Array()); + const { node } = fs.lookupPath(path); + node.usedBytes = file.size; + node.timestamp = file.lastModified; + const reader = new FileReaderSync(); + const windowSize = 64 * 1024; + const cache = new Map(); + node.stream_ops = { ...node.stream_ops, + read(stream, buffer, offset, length, position) { + const count = Math.min(length, Math.max(0, file.size - position)); + let copied = 0; + while (copied < count) { + const start = position - position % windowSize; + let bytes = cache.get(start); + if (!bytes) { + bytes = new Uint8Array(reader.readAsArrayBuffer(file.slice(start, start + windowSize))); + onRead?.(bytes.length); + if (cache.size === 256) cache.delete(cache.keys().next().value); + } else { + cache.delete(start); + } + cache.set(start, bytes); + const inside = position - start; + const take = Math.min(count - copied, bytes.length - inside); + if (take <= 0) fail('sourceReadFailed'); + buffer.set(bytes.subarray(inside, inside + take), offset + copied); + position += take; + copied += take; + } + return copied; + }, + }; + return path; +} + +export async function runOperation(dotnet, { file, format, target }) { + let memoryError; + try { + const downgrade = format === 'downgrade'; + const probe = format === 'revit-version'; + const spec = exportFormats(file.name).find(candidate => candidate.id === format); + if (!file.size || (downgrade || probe ? !isRevit(file.name) : !spec)) + fail('invalidOperation'); + + let progress = {}; + let bytesRead = 0; + let bytesWritten = 0; + let lastUpdate = -Infinity; + function publish(force = false) { + if (probe || (!force && performance.now() - lastUpdate < 250)) return; + lastUpdate = performance.now(); + self.postMessage({ progress: { ...progress, bytesRead, bytesWritten } }); + } + function stage(phase, completed = 0, total = 0) { + const changed = phase !== progress.phase || total !== progress.total; + progress = { phase, completed, total }; + publish(changed || (total > 0 && completed === total)); + } + + stage('runtime'); + const builder = !probe && isRevit(file.name) + ? dotnet.withEnvironmentVariable('MONO_GC_PARAMS', 'soft-heap-limit=512m') + : dotnet; + const runtime = await builder.withModuleConfig({ + printErr(message) { + const line = String(message); + if (/Garbage collector could not allocate|Out of memory|Cannot enlarge memory/i.test(line)) + memoryError = line; + console.error(line); + }, + }).create(); + runtime.setModuleImports('operation', { reportProgress: stage }); + const fs = runtime.Module.FS; + const input = mountInput(fs, '/input', file, count => { + bytesRead += count; + publish(); + }); + const { Runner } = await runtime.getAssemblyExports(runtime.getConfig().mainAssemblyName); + if (probe) { + const version = Runner.ReadRevitVersion(input); + self.postMessage({ version, bytesRead }); + return; + } + fs.mkdir('/result'); + const suffix = downgrade ? '.revit-' + target + extensionOf(file.name) : spec.suffix; + const output = '/result/model' + (downgrade ? extensionOf(file.name) : suffix); + const report = '/result/downgrade.json'; + let args; + if (downgrade) { + stage('metadata'); + if (!targetReleases(Runner.ReadRevitVersion(input)).includes(target)) fail('invalidTarget'); + stage('profile'); + const response = await fetch(new URL(`./profiles/${target}.rvt`, import.meta.url)); + if (!response.ok) fail('profileFailed', { year: target }); + const profile = `/result/profile-${target}.rvt`; + fs.writeFile(profile, new Uint8Array(await response.arrayBuffer())); + args = ['downgrade', input, '--target-profile', profile, '--output', output, '--report', report]; + } else { + args = spec.args(input, output); + } + + const write = fs.write; + fs.write = function (stream, ...args) { + const count = write.call(this, stream, ...args); + // Some writers save a temporary sibling and rename it after a successful write. + if (count > 0 && stream.path.startsWith('/result/') && + progress.phase !== 'report' && stream.path !== report) { + bytesWritten += count; + stage('write'); + } + return count; + }; + if (downgrade) { + const read = fs.read; + fs.read = function (stream, ...args) { + if (progress.phase === 'write' && stream.path === output && !stream.isWrite) + stage('verify'); + return read.call(this, stream, ...args); + }; + } + stage(downgrade ? 'plan' : 'decode'); + const result = JSON.parse(Runner.Run(downgrade ? 'RvtIO.Cli' : spec.tool, JSON.stringify(args))); + const diagnostics = [result.output.trim(), result.diagnostics.trim()].filter(Boolean).join('\n'); + const exists = path => fs.analyzePath(path).exists; + const stem = file.name.slice(0, -extensionOf(file.name).length); + if (result.exitCode !== 0 || !exists(output)) { + const error = result.error || result.diagnostics.trim().split(/\r?\n/).at(-1); + self.postMessage({ + error, + localized: error ? undefined : { key: 'missingOutput' }, + diagnostics, + }); + return; + } + if (!fs.stat(output).size) fail('emptyOutput'); + + stage('download'); + const reportFile = downgrade && exists(report) ? new File([fs.readFile(report)], stem + '.downgrade.json') : undefined; + const resultFile = new File([fs.readFile(output)], stem + suffix); + self.postMessage({ file: resultFile, report: reportFile, diagnostics }); + } catch (error) { + const message = error?.message; + self.postMessage(memoryError || error?.name === 'OutOfMemoryException' + ? { localized: { key: 'operationMemory' }, diagnostics: memoryError ?? message } + : { error: error?.localized ? undefined : message, localized: error?.localized ?? (!message ? { key: 'processFailed' } : undefined) }); + } +} diff --git a/site/wwwroot/operations.css b/site/wwwroot/operations.css new file mode 100644 index 0000000..cd01900 --- /dev/null +++ b/site/wwwroot/operations.css @@ -0,0 +1,175 @@ +#operations { + width: min(100%, 80rem); + margin-inline: auto; + padding: 3.5rem var(--gutter) 3rem; + display: block; +} +.operation-heading { + position: relative; + margin-bottom: 2rem; + padding-inline-end: 4rem; +} +.operation-heading::after { + content: ""; + position: absolute; + inset: 4px 0 auto auto; + width: 42px; + aspect-ratio: 1; + background: conic-gradient(var(--accent-top) 0 63.4deg, var(--accent-face) 63.4deg 180deg, + var(--accent) 180deg 296.6deg, var(--accent-top) 296.6deg); + clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); +} +.operation-heading p { margin: .65rem 0 0; max-width: 65ch; color: var(--muted); } +.operation-form { + display: grid; + grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); + align-items: start; + gap: clamp(1.5rem, 4vw, 3.5rem); + border-block: 1px solid var(--line); + padding-block: 1.75rem; +} +#operations h2 { margin: 0 0 .8rem; font-size: 1.1rem; font-weight: 700; letter-spacing: -.01em; } +.operation-drop { + padding: 1.2rem; + min-height: 9rem; + border: 1px dashed color-mix(in srgb, var(--accent) 42%, var(--line)); + border-radius: 12px; + background: var(--surface); +} +.operation-drop.dragging { + background: color-mix(in srgb, var(--surface) 88%, var(--accent)); + border-color: var(--accent); +} +.file-name { margin: 0; overflow-wrap: anywhere; font-weight: 650; } +.operation-hint { margin: 0 0 .9rem; color: var(--muted); font-size: .9rem; } +.operation-drop .operation-hint { margin-top: .25rem; } +.operation-privacy { margin: .9rem 0 0; } +.operation-section-title { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 0 .65rem; } +.secondary, .quiet { + background: transparent; + color: var(--ink); + border: 1px solid var(--line); +} +.secondary:hover:not(:disabled) { background: var(--surface-hover); border-color: var(--accent); } +.quiet { border-color: transparent; color: var(--accent); padding: .25rem 0; font-size: .85rem; } +.quiet:hover:not(:disabled) { background: transparent; text-decoration: underline; } +#formats-empty { margin: .15rem 0 0; } +#format-list, #optional-format-list { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + row-gap: 1px; + column-gap: .75rem; +} +.format-option { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: start; + gap: .55rem; + min-height: 2.65rem; + padding: .48rem .35rem; + font-size: .89rem; + border-bottom: 1px solid var(--line); + cursor: pointer; + overflow-wrap: anywhere; +} +.format-option:hover { background: var(--surface); } +.format-option:has(input:checked) { + background: color-mix(in srgb, var(--surface) 93%, var(--accent)); +} +.format-option input { inline-size: 1rem; block-size: 1rem; margin: .16rem 0 0; accent-color: var(--accent); } +.format-option small { display: block; color: var(--muted); font: .75rem/1.4 ui-monospace, monospace; } +#optional-formats { margin-top: 1.15rem; } +#optional-formats summary { padding-block: .75rem; cursor: pointer; color: var(--ink); font-size: .9rem; font-weight: 650; } +#optional-formats .operation-hint { margin: .5rem 0 .35rem; } +#target-version { + width: min(100%, 18rem); + min-height: 44px; + padding: .5rem .75rem; + border: 1px solid var(--line); + border-radius: 4px; + background: var(--surface); + color: var(--ink); + font: inherit; +} +#target-version:disabled { opacity: .65; } +#source-version[data-error] { color: var(--error); } +.downgrade-note { margin: 1rem 0 0; max-width: 42ch; } +.operation-actions { display: flex; flex-wrap: wrap; gap: .55rem; margin-top: 1.35rem; } +#operation-progress { + margin-top: 1.15rem; + padding: .85rem 0 0; + border-top: 1px solid var(--line); + font-size: .85rem; + color: var(--muted); + font-variant-numeric: tabular-nums; +} +.operation-progress-row { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: baseline; + gap: .2rem 1rem; +} +#operation-phase { color: var(--ink); font-size: .95rem; } +#operation-progress progress { + display: block; + width: 100%; + height: .5rem; + margin-block: .55rem .45rem; + appearance: none; + border: 0; + border-radius: 2px; + background: var(--line); + overflow: hidden; +} +#operation-progress progress::-webkit-progress-bar { background: transparent; } +#operation-progress progress::-webkit-progress-value { background: var(--accent); } +#operation-progress progress::-moz-progress-bar { background: var(--accent); } +#operation-progress progress:indeterminate { + background: linear-gradient(var(--accent), var(--accent)) 50% center / 25% 100% no-repeat var(--line); +} +@media (prefers-reduced-motion: no-preference) { + #operation-progress progress:indeterminate { animation: operation-wait 1.8s ease-in-out infinite alternate; } + @keyframes operation-wait { + from { background-position: 0 center; } + to { background-position: 100% center; } + } +} +#operation-progress p { margin: .35rem 0 0; } +#operation-progress p:empty { display: none; } +#operation-batch { margin-top: .9rem; } +#operation-batch-meter { opacity: .75; } +.operation-status { + margin: 1rem 0 0; + font-size: .9rem; + color: var(--muted); + overflow-wrap: anywhere; +} +.operation-status[data-error] { color: var(--error); } +.operation-status:empty { margin: 0; } +.operation-results { margin-top: 1.75rem; } +.operation-results ul { list-style: none; padding: 0; margin: 0; } +.operation-result { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: .4rem 1rem; + border-top: 1px solid var(--line); + padding-block: .7rem; + overflow-wrap: anywhere; +} +.operation-result p { margin: 0; } +.operation-result [data-error] { color: var(--error); font-size: .88rem; grid-column: 1 / -1; } +.operation-result a { display: inline-block; min-height: 44px; padding-block: .65rem; font-size: .88rem; font-weight: 650; } +.operation-result details { grid-column: 1 / -1; color: var(--muted); font-size: .85rem; } +.operation-result summary { cursor: pointer; } +.operation-result pre { white-space: pre-wrap; font: inherit; overflow-wrap: anywhere; } +@media (max-width: 700px) { + #operations { padding-top: 2.25rem; } + .operation-heading h1 { font-size: 2rem; } + .operation-heading { padding-inline-end: 3rem; } + .operation-heading::after { width: 30px; } + .operation-form { grid-template-columns: 1fr; padding-block: 1.25rem; } +} +@media (max-width: 380px) { + #format-list, #optional-format-list { grid-template-columns: 1fr; } +} diff --git a/site/wwwroot/operations.js b/site/wwwroot/operations.js new file mode 100644 index 0000000..3758f8b --- /dev/null +++ b/site/wwwroot/operations.js @@ -0,0 +1,417 @@ +import { exportFormats, extensionOf } from './formats.js'; +import { targetReleases } from './revit-versions.js'; +import { formatNumber, hasTranslation, localize, message, t } from './i18n.js'; + +const byId = id => document.getElementById(id); +const app = byId('app'); +const workspace = byId('workspace'); +const panel = byId('operations'); +const drop = byId('operation-drop'); +const input = byId('operation-input'); +const targetVersion = byId('target-version'); +const sourceVersion = byId('source-version'); +const chooseFile = byId('choose-operation'); +const submit = byId('run-operation'); +const cancel = byId('cancel-operation'); +const status = byId('operation-status'); +const progress = byId('operation-progress'); +const phaseLabel = byId('operation-phase'); +const stageMeter = byId('operation-meter'); +const batch = byId('operation-batch'); +const batchMeter = byId('operation-batch-meter'); +const phaseUnits = { + partitions: 'streams', 'r22-layout': 'streams', 'element-records': 'blocks', 'element-blocks': 'passes', + 'parameter-stream': 'bytes', 'recover-geometry': 'passes', 'geometry-blocks': 'blocks', + 'element-properties': 'blocks', 'build-model': 'records', 'finalize-model': 'passes', meshes: 'elements', +}; +const downgradePhases = ['runtime', 'metadata', 'profile', 'plan', 'rewrite', 'write', 'verify', 'report', 'download']; +const downloads = byId('operation-downloads'); +const allFormats = byId('select-formats'); +const optional = byId('optional-formats'); +const tabs = [...document.querySelectorAll('.tools-nav a')]; +const modes = { + export: { + accept: '.rvt,.rfa,.nwc,.nwd', + }, + downgrade: { + accept: '.rvt,.rfa', + }, +}; +const states = Object.fromEntries(Object.keys(modes).map(mode => + [mode, { selected: new Set(), results: [], message: '', error: false }])); +let mode, task, modelFile; + +const accepts = (mode, file) => file && modes[mode].accept.split(',').includes(extensionOf(file.name)); +export const isModelSelectionLocked = () => Boolean(task); + +function formatOption(state, format) { + const label = document.createElement('label'); + label.className = 'format-option'; + const checkbox = document.createElement('input'); + checkbox.type = 'checkbox'; + checkbox.value = format.id; + checkbox.checked = state.selected.has(format.id); + checkbox.disabled = Boolean(task); + checkbox.addEventListener('change', () => { + if (checkbox.checked) state.selected.add(format.id); + else state.selected.delete(format.id); + updateControls(state); + }); + const text = document.createElement('span'); + text.textContent = format.title; + const suffix = document.createElement('small'); + suffix.textContent = format.suffix; + text.append(suffix); + label.append(checkbox, text); + return label; +} + +function renderFormats(state) { + const formats = modelFile ? exportFormats(modelFile.name) : []; + const primary = formats.filter(format => !format.optional); + const additional = formats.filter(format => format.optional); + byId('formats-empty').hidden = formats.length > 0; + allFormats.hidden = !primary.length; + optional.hidden = !additional.length; + byId('format-list').replaceChildren(...primary.map(format => formatOption(state, format))); + byId('optional-format-list').replaceChildren(...additional.map(format => formatOption(state, format))); +} + +function downloadLink(file, url, label) { + const link = document.createElement('a'); + link.href = url; + link.download = file.name; + link.textContent = label; + link.setAttribute('aria-label', `${label} ${file.name}`); + return link; +} + +function renderResults(state) { + byId('operation-results').hidden = !state.results.length; + downloads.replaceChildren(...state.results.map(result => { + const item = document.createElement('li'); + item.className = 'operation-result'; + const title = document.createElement('p'); + title.textContent = result.file?.name ?? t(result.title); + item.append(title); + if (result.file) item.append(downloadLink(result.file, result.url, t('save'))); + if (result.error) { + const error = document.createElement('p'); + error.textContent = localize(result.error); + error.setAttribute('data-error', ''); + item.append(error); + } + if (result.diagnostics || result.report) { + const details = document.createElement('details'); + const summary = document.createElement('summary'); + summary.textContent = t('diagnostics'); + const diagnostics = document.createElement('pre'); + diagnostics.textContent = result.diagnostics; + details.append(summary); + if (result.diagnostics) details.append(diagnostics); + if (result.report) details.append(downloadLink(result.report, result.reportUrl, t('saveReport'))); + item.append(details); + } + return item; + })); +} + +function clearResults(state) { + for (const result of state.results) { + if (result.url) URL.revokeObjectURL(result.url); + if (result.reportUrl) URL.revokeObjectURL(result.reportUrl); + } + state.results = []; +} + +function updateControls(state) { + const running = Boolean(task); + chooseFile.disabled = allFormats.disabled = running; + targetVersion.disabled = running || mode !== 'downgrade' || !targetReleases(state.version).length; + drop.classList.toggle('busy', running); + for (const checkbox of panel.querySelectorAll('input[type=checkbox]')) checkbox.disabled = running; + submit.disabled = running || !accepts(mode, modelFile) || + (mode === 'export' ? !state.selected.size : !state.target); + cancel.hidden = task?.mode !== mode || !running; +} + +function showStatus(state, message, error = false) { + state.message = message; + state.error = error; + if (states[mode] !== state) return; + status.textContent = localize(message); + status.toggleAttribute('data-error', error); +} + +function showFile() { + byId('operation-file').textContent = modelFile?.name ?? t('dropHere'); + byId('operation-accept').textContent = modelFile + ? fileSize(modelFile.size) + : modes[mode].accept.replaceAll('.', '').toUpperCase().split(',').join(', '); + chooseFile.textContent = t(modelFile ? 'chooseAnother' : 'chooseFile'); +} + +function showVersions(state) { + const versions = targetReleases(state.version); + targetVersion.replaceChildren(new Option(t('chooseVersion'), ''), + ...versions.map(year => new Option(`Revit ${year}`, year))); + targetVersion.value = state.target || ''; + sourceVersion.textContent = state.versionError ? t('versionError') : state.probe ? t('versionProbe') + : state.version ? t(versions.length ? 'detectedVersion' : 'noEarlierVersion', { year: state.version }) + : t('chooseSourceRvt'); + sourceVersion.toggleAttribute('data-error', Boolean(state.versionError)); +} + +async function inspectVersion(state) { + if (!accepts('downgrade', modelFile) || state.probe || state.version || state.versionError) return; + const controller = new AbortController(); + state.probe = controller; + showVersions(state); + try { + const result = await runWorker({ mode: 'downgrade', signal: controller.signal }, + { file: modelFile, format: 'revit-version' }); + if (state.probe === controller) state.version = result.version; + } catch { + if (state.probe === controller) state.versionError = true; + } finally { + if (state.probe === controller) { + state.probe = undefined; + if (mode === 'downgrade') { + showVersions(state); + updateControls(state); + } + } + } +} + +function fileSize(size) { + const [unit, factor] = size >= 1_000_000_000 ? ['gigabyte', 1_000_000_000] + : size >= 1_000_000 ? ['megabyte', 1_000_000] : size >= 1000 ? ['kilobyte', 1000] : ['byte', 1]; + return formatNumber(size / factor, { style: 'unit', unit, maximumFractionDigits: 2 }); +} + +function elapsed(start, now) { + const seconds = Math.floor((now - start) / 1000); + const minutes = Math.floor(seconds / 60); + return `${minutes}:${String(seconds % 60).padStart(2, '0')}`; +} + +function renderClock(job) { + if (progress.hidden || mode !== job.mode) return; + const now = performance.now(); + byId('operation-elapsed').textContent = t('operationTime', { + elapsed: elapsed(job.started, now), stageTime: elapsed(job.stageStarted, now), + }); +} + +function renderProgress() { + progress.hidden = !task || mode !== task.mode; + if (progress.hidden) return; + const { phase, completed, total, bytesRead, bytesWritten } = task.progress; + const unit = phaseUnits[phase]; + const key = `phase.${phase}`; + const title = `${t(hasTranslation(key) ? key : 'phase.decode')} · ${task.label()}`; + if (phaseLabel.textContent !== title) phaseLabel.textContent = title; + if (total > 0) { + stageMeter.max = total; + stageMeter.value = completed; + const display = unit === 'bytes' ? fileSize : formatNumber; + const count = t('count', { completed: display(completed), total: display(total) }); + byId('operation-count').textContent = + t('stagePercent', { percent: Math.floor(100 * stageMeter.position), count }) + + (unit && unit !== 'bytes' ? ` · ${t(`unit.${unit}`)}` : ''); + } else { + stageMeter.removeAttribute('value'); + const step = task.mode === 'downgrade' ? downgradePhases.indexOf(phase) + 1 : 0; + byId('operation-count').textContent = step ? t('step', { step, total: downgradePhases.length }) : ''; + } + byId('operation-io').textContent = [ + bytesRead ? t('readBytes', { size: fileSize(bytesRead) }) : '', + bytesWritten ? t('writtenBytes', { size: fileSize(bytesWritten) }) : '', + ].filter(Boolean).join(' · '); + batch.hidden = task.total === 1; + if (!batch.hidden) { + batchMeter.max = task.total; + batchMeter.value = task.index; + byId('operation-batch-label').textContent = t('batchCount', { done: task.index, total: task.total }); + } + renderClock(task); +} + +function route() { + const requested = location.hash.slice(1); + const previous = mode; + mode = Object.hasOwn(modes, requested) ? requested : 'view'; + for (const tab of tabs) { + if (tab.hash === '#' + mode) tab.setAttribute('aria-current', 'page'); + else tab.removeAttribute('aria-current'); + } + app.dataset.mode = mode; + workspace.hidden = mode !== 'view'; + panel.hidden = mode === 'view'; + workspace.classList.remove('dragging'); + if (panel.hidden) { + if (mode !== previous) document.dispatchEvent(new Event('view-activated')); + return; + } + const settings = modes[mode]; + const state = states[mode]; + byId('operation-title').textContent = t(`${mode}Title`); + byId('operation-description').textContent = t(`${mode}Description`); + byId('export-settings').hidden = mode !== 'export'; + byId('downgrade-settings').hidden = mode !== 'downgrade'; + input.accept = settings.accept; + submit.textContent = t(`${mode}Action`); + showFile(); + if (mode === 'downgrade') { + showVersions(state); + inspectVersion(state); + } + renderFormats(states.export); + renderResults(state); + showStatus(state, state.message, state.error); + updateControls(state); + renderProgress(); +} + +export function selectModelFile(file) { + if (task) return; + modelFile = file; + for (const state of Object.values(states)) { + state.probe?.abort(); + state.probe = state.version = state.versionError = state.target = undefined; + state.selected.clear(); + clearResults(state); + showStatus(state, ''); + } + route(); + document.dispatchEvent(new CustomEvent('model-file-selected', { detail: file })); +} + +function selectFile(file) { + const state = states[mode]; + if (!state || !file || task) return; + if (!accepts(mode, file) || !file.size) { + showStatus(state, message(!file.size ? 'emptyFile' : 'badFormat'), true); + return; + } + selectModelFile(file); +} + +function runWorker(job, data, onProgress) { + job.signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const entry = job.mode === 'downgrade' ? './downgrade-worker.js' : './export-worker.js'; + const worker = new Worker(new URL(entry, import.meta.url), { type: 'module' }); + function finish(callback, value) { + job.signal.removeEventListener('abort', abort); + worker.onmessage = worker.onmessageerror = worker.onerror = null; + worker.terminate(); + callback(value); + } + const abort = () => finish(reject, job.signal.reason); + job.signal.addEventListener('abort', abort, { once: true }); + worker.onerror = event => { + event.preventDefault(); + finish(reject, Object.assign(new Error(), { localized: message('workerFailed') })); + }; + worker.onmessageerror = event => { + event.preventDefault(); + finish(reject, Object.assign(new Error(), { localized: message('workerResult') })); + }; + worker.onmessage = ({ data: result }) => { + if (result.progress) onProgress?.(result.progress); + else if (result.error || result.localized) { + const error = new Error(result.error); + error.localized = result.localized; + error.diagnostics = result.diagnostics; + finish(reject, error); + } + else finish(resolve, result); + }; + try { worker.postMessage(data); } + catch (error) { finish(reject, error); } + }); +} + +async function start(event) { + event.preventDefault(); + if (submit.disabled) return; + const state = states[mode]; + const job = { mode, controller: new AbortController() }; + job.signal = job.controller.signal; + task = job; + document.dispatchEvent(new Event('operation-statechange')); + const formats = mode === 'downgrade' ? [{ id: 'downgrade', titleKey: 'revitCopy' }] + : exportFormats(modelFile.name).filter(format => state.selected.has(format.id)); + job.started = performance.now(); + job.total = formats.length; + clearResults(state); + renderResults(state); + showStatus(state, ''); + updateControls(state); + const timer = setInterval(() => renderClock(job), 1000); + try { + for (const [index, format] of formats.entries()) { + job.index = index; + job.label = () => job.mode === 'downgrade' ? `Revit ${state.version} → ${state.target}` : format.title; + job.progress = undefined; + const reportProgress = update => { + if (update.phase !== job.progress?.phase) job.stageStarted = performance.now(); + job.progress = update; + renderProgress(); + }; + reportProgress({ phase: 'prepare' }); + try { + const result = await runWorker(job, { file: modelFile, format: format.id, target: state.target }, reportProgress); + state.results.push({ ...result, url: URL.createObjectURL(result.file), + reportUrl: result.report ? URL.createObjectURL(result.report) : undefined }); + } catch (error) { + if (job.signal.aborted) throw error; + state.results.push({ title: format.titleKey, error: error.localized ?? error.message, diagnostics: error.diagnostics }); + } + if (mode === job.mode) renderResults(state); + } + const completed = state.results.filter(result => result.file).length; + showStatus(state, completed === formats.length ? message('done') + : completed ? message('partlyDone', { done: completed, total: formats.length }) : message('failed'), !completed); + } catch (error) { + showStatus(state, job.signal.aborted ? message('operationCanceled') : error.localized ?? error.message, !job.signal.aborted); + } finally { + clearInterval(timer); + task = undefined; + document.dispatchEvent(new Event('operation-statechange')); + renderProgress(); + if (!panel.hidden) updateControls(states[mode]); + } +} + +chooseFile.addEventListener('click', () => input.click()); +input.addEventListener('change', () => { selectFile(input.files[0]); input.value = ''; }); +targetVersion.addEventListener('change', () => { + const state = states.downgrade; + state.target = Number(targetVersion.value); + updateControls(state); +}); +byId('operation-form').addEventListener('submit', start); +cancel.addEventListener('click', () => task?.controller.abort()); +allFormats.addEventListener('click', () => { + const state = states.export; + for (const format of exportFormats(modelFile.name).filter(format => !format.optional)) state.selected.add(format.id); + renderFormats(state); + updateControls(state); +}); +for (const type of ['dragenter', 'dragover', 'dragleave', 'drop']) { + window.addEventListener(type, event => { + if (panel.hidden || !event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + if (type === 'dragover') event.dataTransfer.dropEffect = task ? 'none' : 'copy'; + drop.classList.toggle('dragging', !task && (type === 'dragenter' || type === 'dragover')); + if (type !== 'drop' || task) return; + if (event.dataTransfer.files.length === 1) selectFile(event.dataTransfer.files[0]); + else showStatus(states[mode], message('oneFile'), true); + }); +} +window.addEventListener('hashchange', route); +document.addEventListener('localechange', route); +route(); diff --git a/site/wwwroot/profiles/2020.rvt b/site/wwwroot/profiles/2020.rvt new file mode 100644 index 0000000..319b09b Binary files /dev/null and b/site/wwwroot/profiles/2020.rvt differ diff --git a/site/wwwroot/profiles/2021.rvt b/site/wwwroot/profiles/2021.rvt new file mode 100644 index 0000000..c002c44 Binary files /dev/null and b/site/wwwroot/profiles/2021.rvt differ diff --git a/site/wwwroot/profiles/2022.rvt b/site/wwwroot/profiles/2022.rvt new file mode 100644 index 0000000..1104933 Binary files /dev/null and b/site/wwwroot/profiles/2022.rvt differ diff --git a/site/wwwroot/profiles/2023.rvt b/site/wwwroot/profiles/2023.rvt new file mode 100644 index 0000000..b66c600 Binary files /dev/null and b/site/wwwroot/profiles/2023.rvt differ diff --git a/site/wwwroot/profiles/2024.rvt b/site/wwwroot/profiles/2024.rvt new file mode 100644 index 0000000..69dc95a Binary files /dev/null and b/site/wwwroot/profiles/2024.rvt differ diff --git a/site/wwwroot/profiles/2025.rvt b/site/wwwroot/profiles/2025.rvt new file mode 100644 index 0000000..21e9138 Binary files /dev/null and b/site/wwwroot/profiles/2025.rvt differ diff --git a/site/wwwroot/profiles/2026.rvt b/site/wwwroot/profiles/2026.rvt new file mode 100644 index 0000000..63e624f Binary files /dev/null and b/site/wwwroot/profiles/2026.rvt differ diff --git a/site/wwwroot/reader-host.js b/site/wwwroot/reader-host.js new file mode 100644 index 0000000..315fed4 --- /dev/null +++ b/site/wwwroot/reader-host.js @@ -0,0 +1,7 @@ +import { threaded } from './reader-profile.js'; + +if (threaded) { + // .NET 10 must treat this dedicated worker as the host of its own pthread pool. + self.importScripts = undefined; + self.window = self; +} diff --git a/site/wwwroot/reader-scratch.js b/site/wwwroot/reader-scratch.js new file mode 100644 index 0000000..d919d88 --- /dev/null +++ b/site/wwwroot/reader-scratch.js @@ -0,0 +1,80 @@ +const growth = 4 * 1024 * 1024; + +export function bufferScratchFile(file, budget) { + if (!budget || typeof ArrayBuffer.prototype.resize !== 'function' || + typeof ArrayBuffer.prototype.transferToFixedLength !== 'function') return file; + + let buffer; + try { + buffer = new ArrayBuffer(0, { maxByteLength: budget.available }); + } catch (error) { + if (!(error instanceof RangeError)) throw error; + return file; + } + let size = 0; + + function resize(length) { + const delta = length - buffer.byteLength; + buffer.resize(length); + budget.available -= delta; + } + + function commit() { + if (!buffer) return; + const capacity = buffer.byteLength; + // OPFS writes require a view backed by a fixed-length buffer. + const bytes = new Uint8Array(buffer.transferToFixedLength(size)); + buffer = undefined; + budget.available += capacity; + for (let at = 0; at < size;) { + const written = file.write(bytes.subarray(at), { at }); + if (written <= 0) throw new Error('view.scratchFailed'); + at += written; + } + } + + return { + read(destination, { at }) { + if (!buffer) return file.read(destination, { at }); + const count = Math.min(destination.byteLength, Math.max(0, size - at)); + if (count) destination.set(new Uint8Array(buffer, at, count)); + return count; + }, + write(source, { at }) { + const end = at + source.byteLength; + if (buffer && end > buffer.byteLength) { + const limit = Math.min(buffer.maxByteLength, buffer.byteLength + budget.available); + if (end > limit) commit(); + else { + try { + resize(Math.min(limit, Math.ceil(end / growth) * growth)); + } catch (error) { + if (!(error instanceof RangeError)) throw error; + commit(); + } + } + } + if (!buffer) return file.write(source, { at }); + new Uint8Array(buffer, at, source.byteLength).set(source); + size = Math.max(size, end); + return source.byteLength; + }, + truncate(length) { + if (!buffer || length !== 0) { + commit(); + file.truncate(length); + return; + } + resize(0); + size = 0; + }, + commit, + close() { + if (buffer) { + budget.available += buffer.byteLength; + buffer = undefined; + } + file.close(); + }, + }; +} diff --git a/site/wwwroot/reader.js b/site/wwwroot/reader.js new file mode 100644 index 0000000..1d74305 --- /dev/null +++ b/site/wwwroot/reader.js @@ -0,0 +1,262 @@ +import './reader-host.js'; +import { dotnet } from './_framework/dotnet.js'; +import * as profile from './reader-profile.js'; +import { bufferScratchFile } from './reader-scratch.js'; +import { viewerTheme } from './viewer-theme.js'; + +const { pooledGc, rvtGcParams, threaded } = profile; +const parallel = profile.decoders; + +const memoryError = /garbage collector could not allocate|failed to allocate memory for the lock free allocator|out of memory|outofmemoryexception|cannot enlarge memory|could not allocate \d+.* bytes/i; +// Release versions of Mono can report the eglib allocation failure with its text stripped. +const monoAllocatorError = /\[MONO\] [^\r\n]*\/eglib\/gmem\.c:\d+ /; +const runtimeTrap = /memory access out of bounds/; +const inputCacheBytes = 16 * 1024 * 1024; +const scratchCacheBytes = 512 * 1024 * 1024; +const localizedErrors = new Set([ + 'emptyFile', 'chooseRvtNwc', 'view.noGeometry', 'view.pageFailed', + 'view.profileMissing', 'view.scratchFailed', 'view.rangeRead', 'view.outOfRange', +]); + +const dropScript = ``; + +function viewerPage(bytes) { + // The upstream standalone template ends with the closing body and HTML tags. + const tailOffset = Math.max(0, bytes.length - 256); + const tail = new TextDecoder().decode(bytes.subarray(tailOffset)); + const closeBody = tail.lastIndexOf(''); + if (closeBody === -1) throw new Error('view.pageFailed'); + + const offset = bytes.length - new TextEncoder().encode(tail.slice(closeBody)).length; + return new Blob([bytes.subarray(0, offset), ``, dropScript, bytes.subarray(offset)], { + type: 'text/html;charset=utf-8' + }); +} + +self.onmessage = async ({ data }) => { + if (data.parameterWorker && parallel) return parallel.startDecoder(dotnet, data); + const { file, scratchDirectory } = data; + let decoders; + let exhaustedMemory = false; + let exhaustedStorage = false; + let trapped = false; + let loadingRuntime = false; + const scratch = []; + const scratchLengths = [0, 0]; + let scratchBytes = 0; + const logError = console.error; + console.error = (...messages) => { + // Mono emits the reason before throwing an opaque WebAssembly ExitStatus. + for (const message of messages) { + if (typeof message !== 'string' && !(message instanceof Error)) continue; + const diagnostic = String(message); + exhaustedMemory ||= memoryError.test(diagnostic) || monoAllocatorError.test(diagnostic); + trapped ||= runtimeTrap.test(diagnostic); + } + logError.apply(console, messages); + }; + + let result; + try { + const isRvt = /\.rvt$/i.test(file.name); + if (parallel && isRvt && crossOriginIsolated) decoders = parallel.createDecoders(dotnet); + if (scratchDirectory && globalThis.FileSystemFileHandle?.prototype.createSyncAccessHandle) { + try { + const budget = isRvt && pooledGc ? { available: scratchCacheBytes } : null; + for (const name of ['partitions', 'triangles']) { + const handle = await scratchDirectory.getFileHandle(name, { create: true }); + scratch.push(bufferScratchFile(await handle.createSyncAccessHandle(), budget)); + } + } catch (error) { + if (!['SecurityError', 'NotAllowedError', 'NotSupportedError'].includes(error.name)) throw error; + console.debug('Временное хранилище недоступно. Используем обычное чтение модели.'); + } + } + let warnings = 0; + let errors = 0; + let triangles = 0; + let html; + let failure; + const inputWindowSize = (isRvt ? 512 : 64) * 1024; + const inputWindowCount = inputCacheBytes / inputWindowSize; + const inputWindows = new Map(); + let totalInputBytes = 0; + let maxWindowBytes = 0; + let lastLoggedPercent = -1; + let checkingContainer = true; + let nextContainerReport = 0; + const fileReader = new FileReaderSync(); + loadingRuntime = true; + if (threaded) { + dotnet.withEnvironmentVariable('DOTNET_PROCESSOR_COUNT', String(Math.min(4, navigator.hardwareConcurrency || 1))); + // .NET 10's generated interpreter stubs import a heap capped at 2 GiB. + dotnet.withRuntimeOptions(['--no-jiterpreter-traces-enabled']); + } + // Mono's WebAssembly heap cannot shrink. Collect temporary RVT decode data before growing it. + const runtime = isRvt + ? dotnet.withEnvironmentVariable('MONO_GC_PARAMS', rvtGcParams) + : dotnet; + const { getAssemblyExports, getConfig, localHeapViewU8, Module, setModuleImports } = await runtime.create(); + if (threaded) + console.debug('IOExtend shared heap', localHeapViewU8().buffer instanceof SharedArrayBuffer); + const setSgenPool = Module?._ioextend_set_sgen_pool; + if (pooledGc && typeof setSgenPool !== 'function') + throw new Error('view.profileMissing'); + function transfer(index, offset, address, count, writing) { + const handle = scratch[index]; + const start = address >>> 0; + const bytes = localHeapViewU8().subarray(start, start + count); + if (!handle || bytes.length !== count) throw new Error('view.scratchFailed'); + if (!writing) return handle.read(bytes, { at: offset }); + let written; + try { + written = handle.write(bytes, { at: offset }); + } catch (error) { + exhaustedStorage = error.name === 'QuotaExceededError' || /no space available/i.test(error.message); + throw error; + } + const previous = scratchBytes; + scratchLengths[index] = Math.max(scratchLengths[index], offset + written); + scratchBytes = scratchLengths[0] + scratchLengths[1]; + const interval = 256 * 1024 * 1024; + if (Math.floor(previous / interval) < Math.floor(scratchBytes / interval)) + console.debug('IOExtend scratch', JSON.stringify({ scratchBytes, wasmBytes: localHeapViewU8().byteLength })); + return written; + } + setModuleImports('viewer', { + ...decoders?.imports, + updateGcProfile(phase, total) { + if (phase === 'build-model' && total > 0) setSgenPool(1); + }, + scratchTransfer: transfer.bind(null, 0), + triangleTransfer: transfer.bind(null, 1), + resetPartitionScratch() { + scratch[0].truncate(0); + const partitionBytes = scratchLengths[0]; + scratchLengths[0] = 0; + scratchBytes = scratchLengths[1]; + if (partitionBytes > 0) + console.debug('IOExtend partitions released', JSON.stringify({ partitionBytes, scratchBytes })); + }, + reportCluster(count) { triangles = count; }, + reportHtml(bytes) { html = viewerPage(bytes); }, + reportFailure(detail, parallelFailure) { + failure = Object.assign(new Error(detail), { parallelFailure }); + }, + reportScene(elements, instances, geometries) { + console.debug('IOExtend scene', JSON.stringify({ elements, instances, geometries, warnings, errors })); + }, + readRange(offset, destination) { + let copied = 0; + while (copied < destination.length) { + const start = Math.floor(offset / inputWindowSize) * inputWindowSize; + let fileWindow = inputWindows.get(start); + if (fileWindow === undefined) { + const end = Math.min(start + inputWindowSize, file.size); + fileWindow = new Uint8Array(fileReader.readAsArrayBuffer(file.slice(start, end))); + if (fileWindow.length !== end - start) throw new Error('view.rangeRead'); + if (inputWindows.size === inputWindowCount) inputWindows.delete(inputWindows.keys().next().value); + totalInputBytes += fileWindow.length; + maxWindowBytes = Math.max(maxWindowBytes, fileWindow.length); + if (checkingContainer && performance.now() >= nextContainerReport) { + nextContainerReport = performance.now() + 500; + self.postMessage({ progress: { percent: 5, key: 'view.checkBytes', completed: totalInputBytes / (1024 * 1024) } }); + } + } else { + inputWindows.delete(start); + } + inputWindows.set(start, fileWindow); + const inside = offset - start; + const length = Math.min(destination.length - copied, fileWindow.length - inside); + if (length <= 0) throw new Error('view.outOfRange'); + destination.set(fileWindow.subarray(inside, inside + length), copied); + copied += length; + offset += length; + } + }, + reportProgress(percent, key, completed, total) { + if (key === 'phase.element-properties') decoders?.retireIdleDecoders(); + checkingContainer = false; + if (key === 'view.geometry') { + console.debug('IOExtend geometry', JSON.stringify({ key, completed, total, wasmBytes: localHeapViewU8().byteLength })); + } + if (percent !== lastLoggedPercent) { + console.debug('IOExtend memory', JSON.stringify({ + percent, fileBytes: file.size, totalInputBytes, maxWindowBytes, wasmBytes: localHeapViewU8().byteLength, scratchBytes + })); + lastLoggedPercent = percent; + } + self.postMessage({ progress: { percent, key, completed, total } }); + }, + reportDiagnostics(warningCount, errorCount) { + warnings = warningCount; + errors = errorCount; + self.postMessage({ progress: { percent: 96, key: 'view.prepare' } }); + } + }); + + const exports = await getAssemblyExports(getConfig().mainAssemblyName); + loadingRuntime = false; + self.postMessage({ progress: { percent: 5, key: 'view.check' } }); + nextContainerReport = performance.now() + 500; + const { Program } = exports; + if (decoders) await decoders.connect(Program, localHeapViewU8); + const bytes = scratch.length === 2 && typeof Program.OpenPagedModel === 'function' + ? await Program.OpenPagedModel(file.name, file.size) + : await Program.OpenModel(file.name, file.size, scratch.length === 2); + if (failure) throw failure; + if (bytes?.length) html = viewerPage(bytes); + if (!(triangles > 0) && !html) throw new Error('view.pageFailed'); + if (triangles > 0) scratch[0].commit?.(); + result = { warnings, errors, ...(triangles > 0 ? { triangles } : { html }) }; + } catch (error) { + const detail = error?.message; + const outOfMemory = exhaustedMemory || memoryError.test(detail ?? ''); + exhaustedStorage ||= error?.name === 'QuotaExceededError' || /no space available/i.test(detail ?? ''); + if (exhaustedStorage) + result = { localized: { key: 'view.storage' } }; + else if (outOfMemory) + result = { localized: { key: 'view.memory' } }; + else if (localizedErrors.has(detail)) + result = { localized: { key: detail } }; + else result = detail ? { error: detail } : { localized: { key: 'processFailed' } }; + if (threaded && !exhaustedStorage) + result.retryable = loadingRuntime || outOfMemory || trapped || error?.parallelFailure === true || + error instanceof WebAssembly.RuntimeError || runtimeTrap.test(detail ?? ''); + } finally { + console.error = logError; + decoders?.close(); + for (const handle of scratch) { + try { + handle.close(); + } catch (error) { + console.warn('Не удалось закрыть временные данные модели.', error); + } + } + } + self.postMessage(result); +}; diff --git a/site/wwwroot/revit-versions.js b/site/wwwroot/revit-versions.js new file mode 100644 index 0000000..09a9dfa --- /dev/null +++ b/site/wwwroot/revit-versions.js @@ -0,0 +1,5 @@ +export const downgradeProfiles = [2026, 2025, 2024, 2023, 2022, 2021, 2020]; + +export function targetReleases(source) { + return source <= 2027 ? downgradeProfiles.filter(year => year < source) : []; +} diff --git a/site/wwwroot/site.css b/site/wwwroot/site.css new file mode 100644 index 0000000..e4c2856 --- /dev/null +++ b/site/wwwroot/site.css @@ -0,0 +1,292 @@ +:root { + color-scheme: dark; + font: 16px/1.5 system-ui, sans-serif; + --page: #12161c; + --surface: #191e27; + --surface-hover: #212936; + --line: #364152; + --muted: #aebaca; + --ink: #edf3fa; + --cyan: #a5f3fc; + --violet: #dbc0ff; + --amber: #ffdc82; + --accent: var(--cyan); + --accent-top: #d2faff; + --accent-face: #07586c; + --accent-ink: #10202a; + --error: #ffc3ad; + --gutter: clamp(1rem, 4vw, 3.5rem); + background: var(--page); + color: var(--ink); +} + +body:has(a[href="#export"][aria-current]) { + --accent: var(--violet); + --accent-top: #efdeff; + --accent-face: #644096; + --accent-ink: #29183c; +} + +body:has(a[href="#downgrade"][aria-current]) { + --accent: var(--amber); + --accent-top: #fff1ba; + --accent-face: #886020; + --accent-ink: #30230e; +} + +* { box-sizing: border-box; } +body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; } +[hidden] { display: none !important; } +a { color: var(--accent); text-underline-offset: 0.25em; } +::selection { background: #514171; color: var(--ink); } +:focus-visible { outline: 2px solid var(--accent-top); outline-offset: 3px; } + +.site-header { border-bottom: 1px solid var(--line); } +.site-header::before { + content: ""; + display: block; + height: 3px; + background: linear-gradient(90deg, #f2a33a 0 26%, #38bdf8 26% 66%, #a855f7 66% 100%); +} +.header-inner { + max-width: 88rem; + margin-inline: auto; + padding-inline: var(--gutter); + min-height: 72px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 1rem; +} +.brand { justify-self: start; display: block; } +.brand img { display: block; width: clamp(9.25rem, 18vw, 14rem); height: auto; image-rendering: pixelated; } +.header-actions { + display: flex; + align-items: center; + justify-self: end; + gap: .5rem; +} +.language-control { + position: relative; + display: flex; + align-items: center; + color: var(--muted); +} +.language-control::after { + content: ""; + position: absolute; + right: .85rem; + width: .38rem; + height: .38rem; + border: solid currentColor; + border-width: 0 2px 2px 0; + transform: translateY(-.1rem) rotate(45deg); + pointer-events: none; +} +.language-globe { + position: absolute; + left: .75rem; + width: 1rem; + height: 1rem; + border: 1px solid currentColor; + border-radius: 50%; + pointer-events: none; +} +.language-globe::before, .language-globe::after { + content: ""; + position: absolute; +} +.language-globe::before { + inset: -1px 3px; + border: 1px solid currentColor; + border-radius: 50%; +} +.language-globe::after { inset: 50% 0 auto; border-top: 1px solid currentColor; } +#site-language { + appearance: none; + min-height: 44px; + max-width: 11rem; + padding-inline: 2.2rem 1.8rem; + border: 1px solid var(--line); + border-radius: 5px; + background: var(--surface); + color: var(--ink); + font: inherit; + font-size: .875rem; + font-weight: 600; + text-overflow: ellipsis; + cursor: pointer; +} +.language-control:hover, .language-control:focus-within { color: var(--accent-top); } +#site-language:hover { background: var(--surface-hover); } +.source-link { + justify-self: end; + display: inline-grid; + place-items: center; + min-height: 44px; + padding-inline: .35rem; + font-size: .875rem; + color: var(--muted); +} +.source-link:hover { color: var(--ink); } +.tools-nav { display: flex; gap: .25rem; align-self: stretch; } +.tools-nav a { + --tab: var(--cyan); + display: flex; + align-items: center; + gap: .625rem; + padding: .75rem 1rem; + border-bottom: 3px solid transparent; + color: var(--muted); + font-size: .875rem; + font-weight: 650; + text-decoration: none; + white-space: nowrap; +} +.tools-nav a[href="#export"] { --tab: var(--violet); } +.tools-nav a[href="#downgrade"] { --tab: var(--amber); } +.tools-nav a::before { + content: ""; + width: .56rem; + height: .56rem; + flex: none; + background: var(--tab); + border-right: 2px solid #12161c55; + border-bottom: 2px solid #12161c75; + opacity: .65; +} +.tools-nav a:hover { color: var(--ink); background: var(--surface); } +.tools-nav a[aria-current] { color: var(--tab); border-color: var(--tab); } +.tools-nav a[aria-current]::before { opacity: 1; } + +main, #workspace { display: flex; flex-direction: column; flex: 1; min-height: 0; min-width: 0; } +#drop-area { + position: relative; + width: min(calc(100% - var(--gutter) * 2), 80rem); + min-height: 27rem; + margin: clamp(1.5rem, 5vw, 4rem) auto; + padding: clamp(1.5rem, 5vw, 4.75rem); + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.03fr); + align-items: center; + gap: clamp(1rem, 4vw, 4rem); + border: 1px solid var(--line); + border-radius: 12px; + background: var(--surface); +} +#drop-area::before, #drop-area::after { + content: ""; + position: absolute; + width: 18px; + height: 18px; + pointer-events: none; + border: 2px solid #82a3b5; +} +#drop-area::before { inset: 12px auto auto 12px; border-width: 2px 0 0 2px; } +#drop-area::after { inset: auto 12px 12px auto; border-width: 0 2px 2px 0; } +#workspace.dragging #drop-area { border-color: var(--cyan); background: #1b3039; } +#workspace.dragging #drop-area::before, #workspace.dragging #drop-area::after { border-color: var(--cyan); } + +h1 { margin: 0; font-size: 2.75rem; line-height: 1.06; letter-spacing: -.038em; } +.drop-content h1 { font-size: 4rem; max-width: 13ch; } +.viewer-formats { + margin: 1.3rem 0 1.65rem; + padding: 0; + display: flex; + flex-wrap: wrap; + gap: .75rem 1rem; + list-style: none; + color: var(--muted); + font-size: .875rem; +} +.viewer-formats li { display: flex; align-items: baseline; gap: .4rem; } +.viewer-formats code { + padding: .12rem .32rem; + color: var(--amber); + background: var(--page); + border: 1px solid var(--line); +} +.viewer-formats li + li code { color: #a8ceff; } +.privacy { margin: .9rem 0 0; color: var(--muted); font-size: .875rem; } +.viewport-illustration { width: 100%; height: auto; image-rendering: pixelated; pointer-events: none; } + +button { + min-height: 44px; + border: 0; + border-top: 2px solid var(--accent-top); + border-bottom: 4px solid var(--accent-face); + border-radius: 4px; + padding: .52rem .94rem .46rem; + background: var(--accent); + color: var(--accent-ink); + font: inherit; + font-weight: 700; + cursor: pointer; +} +button:hover:not(:disabled) { background: var(--accent-top); } +button:active:not(:disabled) { translate: 0 1px; } +button:disabled { cursor: default; opacity: .5; } + +#model-bar, #status-bar { + display: flex; + align-items: center; + gap: .75rem; + padding: .7rem var(--gutter); + background: var(--surface); + border-bottom: 1px solid var(--line); +} +#model-bar { justify-content: space-between; } +#model-name { min-width: 0; overflow-wrap: anywhere; } +#status-bar:has(#status:empty) { display: none; } +#status-content { flex: 1; min-width: 0; } +#status { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +#status[data-error] { color: var(--error); } + +#open-progress { display: flex; align-items: center; gap: .65rem; max-width: 30rem; margin-top: .25rem; } +#open-meter { + flex: 1; + min-width: 0; + height: .38rem; + appearance: none; + border: 0; + background: var(--line); +} +#open-meter::-webkit-progress-bar { background: var(--line); } +#open-meter::-webkit-progress-value { background: var(--cyan); } +#open-meter::-moz-progress-bar { background: var(--cyan); } +#open-percent, #open-elapsed { font-size: .875rem; font-variant-numeric: tabular-nums; white-space: nowrap; } +#open-percent { min-width: 5ch; } +#open-elapsed { color: var(--muted); } + +.viewer-frame { display: block; flex: 1; width: 100%; min-height: 65vh; border: 0; } +/* The sandboxed viewer needs a frame inside the viewport to draw its first WebGL frame. */ +.viewer-loading { position: fixed; inset: 0; opacity: 0; } + +@media (max-width: 1050px) { + .drop-content h1 { font-size: 3.1rem; } +} +@media (max-width: 800px) { + .header-inner { grid-template-columns: minmax(0, 1fr) auto; gap: 0 1rem; padding-block-start: .375rem; } + .brand img { width: clamp(7rem, 32vw, 11rem); } + #site-language { max-width: 8.5rem; } + .tools-nav { grid-column: 1 / -1; grid-row: 2; } + .tools-nav a { padding-inline: .52rem; white-space: normal; } + #drop-area { min-height: 0; margin-block: 1.5rem; padding: 2rem; gap: 1.25rem; } + .drop-content h1 { font-size: 2.6rem; } +} +@media (max-width: 640px) { + #drop-area { grid-template-columns: minmax(0, 1fr); padding: 1.75rem; } + .viewport-illustration { max-width: 18rem; justify-self: center; } + .drop-content h1 { font-size: 2.5rem; } + .tools-nav a { gap: .34rem; font-size: .8rem; } + .tools-nav a::before { width: .48rem; height: .48rem; } + #model-bar { align-items: flex-start; flex-direction: column; } +} +@media (max-width: 380px) { + .header-inner { column-gap: .5rem; } + .header-actions { gap: .15rem; } + .language-globe { display: none; } + #site-language { max-width: 7rem; padding-inline-start: .65rem; } + .tools-nav { flex-wrap: wrap; gap: 0; } + .tools-nav a { padding-inline: .45rem; } +} diff --git a/site/wwwroot/site.js b/site/wwwroot/site.js new file mode 100644 index 0000000..79365f8 --- /dev/null +++ b/site/wwwroot/site.js @@ -0,0 +1,499 @@ +import { formatNumber, lang, localize, message, setupLanguage, t } from './i18n.js'; +import { isModelSelectionLocked, selectModelFile } from './operations.js'; +import * as readerProfile from './reader-profile.js'; + +const { fallbackReader, fastReader, threaded } = readerProfile; + +const app = document.querySelector('#app'); +const workspace = document.querySelector('#workspace'); +const dropArea = document.querySelector('#drop-area'); +const input = document.querySelector('#file-input'); +const openButton = document.querySelector('#open-file'); +const replaceButton = document.querySelector('#replace-file'); +const cancelButton = document.querySelector('#cancel'); +const status = document.querySelector('#status'); +const openingProgress = document.querySelector('#open-progress'); +const openingMeter = document.querySelector('#open-meter'); +const percentLabel = document.querySelector('#open-percent'); +const elapsedLabel = document.querySelector('#open-elapsed'); +const modelBar = document.querySelector('#model-bar'); +const modelName = document.querySelector('#model-name'); +let viewer = document.querySelector('#viewer'); +const readerStartupTimeout = 60_000; +const fastOpenIdleTimeout = 25_000; +const fastReaderMaxBytes = 50 * 1024 * 1024; +const fastReaderSupported = fastReader && navigator.deviceMemory >= 8 && navigator.hardwareConcurrency >= 5; +const useViewerIsolation = threaded || fastReaderSupported; + +function canUseFastReader(file) { + return fastReaderSupported && /\.rvt$/i.test(file.name) && file.size <= fastReaderMaxBytes && + crossOriginIsolated && typeof SharedArrayBuffer !== 'undefined'; +} + +let opening; +let pendingFile; +let displayedScratch; +let displayedFiles; +let elapsedTimer; +let modelUrl; +let dragDepth = 0; +let statusText; +let readerPath = './reader.js'; +let stopIsolationReload; + +if (useViewerIsolation && !crossOriginIsolated && navigator.serviceWorker && !navigator.serviceWorker.controller) { + const reload = () => location.reload(); + stopIsolationReload = () => navigator.serviceWorker.removeEventListener('controllerchange', reload); + navigator.serviceWorker.addEventListener('controllerchange', reload, { once: true }); + navigator.serviceWorker.register(new URL('../../thread-isolation.js', import.meta.url)).catch(error => { + stopIsolationReload(); + console.warn('Could not enable viewer isolation.', error); + }); +} + +function showStatus(text, error = false) { + statusText = typeof text === 'function' ? text : () => localize(text); + status.textContent = statusText(); + status.toggleAttribute('data-error', error); +} + +function startOpeningProgress() { + const started = performance.now(); + const updateElapsed = () => { + const seconds = Math.floor((performance.now() - started) / 1000); + elapsedLabel.textContent = t('elapsed', { elapsed: `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` }); + }; + + updateElapsed(); + openingMeter.value = 0; + percentLabel.textContent = '≈ 0%'; + openingProgress.hidden = false; + elapsedTimer = setInterval(updateElapsed, 1000); + opening.updateElapsed = updateElapsed; +} + +function finish(open) { + if (opening !== open) return; + opening = undefined; + updateOpenButtons(); + cancelButton.hidden = true; + clearInterval(elapsedTimer); + openingProgress.hidden = true; + syncViewerLanguage(); +} + +function updateOpenButtons() { + openButton.disabled = replaceButton.disabled = Boolean(opening) || isModelSelectionLocked(); +} + +function showProgress(open, { percent, key, completed, total, level, label }) { + if (opening !== open) return; + openingMeter.value = Math.max(openingMeter.value, percent); + percentLabel.textContent = `≈ ${openingMeter.value}%`; + showStatus(() => { + const options = { maximumFractionDigits: 1 }; + const values = { + completed: formatNumber(completed ?? 0, options), + total: formatNumber(total ?? 0, options), + level: formatNumber(level ?? 0), + }; + const withCount = total > 0 && ['view.decodeFound', 'view.wallGeometry', 'view.decodeGeometry'].includes(key); + return [open.recovering && t('view.fallback'), key ? t(key, values) : label, + withCount && t('count', values), open.file.name].filter(Boolean).join(' · '); + }); +} + +async function removeScratch(name) { + try { + const directory = await navigator.storage.getDirectory(); + for (;;) { + try { + await directory.removeEntry(name, { recursive: true }); + return; + } catch (error) { + if (error.name === 'NotFoundError') return; + // Terminating the worker and releasing its sync file handle are asynchronous. + if (error.name !== 'NoModificationAllowedError') throw error; + await new Promise(resolve => setTimeout(resolve, 250)); + } + } + } catch (error) { + console.warn('Не удалось удалить временные данные модели.', error); + } +} + +function holdScratchLease(name) { + if (!navigator.locks) return Promise.resolve(undefined); + return new Promise((resolve, reject) => { + navigator.locks.request(name, () => new Promise(release => resolve(release))).catch(reject); + }); +} + +async function disposeScratch(scratch) { + if (!scratch) return; + try { await removeScratch(scratch.name); } + finally { scratch.release?.(); } +} + +async function cleanAbandonedScratch() { + if (!navigator.locks || !navigator.storage?.getDirectory) return; + try { + const directory = await navigator.storage.getDirectory(); + for await (const name of directory.keys()) { + if (!/^ioviewer-open-[a-f0-9-]{36}\.tmp$/.test(name)) continue; + await navigator.locks.request(name, { ifAvailable: true }, lease => lease && removeScratch(name)); + } + } catch (error) { + if (!['SecurityError', 'NotAllowedError', 'NotSupportedError'].includes(error.name)) + console.warn('Не удалось очистить временные данные модели.', error); + } +} + +function runWorker(open, path, data, startupTimeout, idleTimeout) { + const { signal } = open.controller; + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const failed = (error = new Error()) => Object.assign(error, { + localized: message('workerFailed'), retryable: true, + }); + let worker; + try { worker = new Worker(new URL(path, import.meta.url), { type: 'module' }); } + catch (error) { reject(failed(error)); return; } + function settle(callback, value) { + clearTimeout(startup); + clearTimeout(inactivity); + signal.removeEventListener('abort', abort); + worker.onmessage = worker.onmessageerror = worker.onerror = null; + worker.terminate(); + callback(value); + } + const abort = () => settle(reject, signal.reason); + signal.addEventListener('abort', abort, { once: true }); + worker.onerror = worker.onmessageerror = event => { + event.preventDefault(); + settle(reject, failed()); + }; + let lastProgress; + worker.onmessage = ({ data: result }) => { + const progress = result?.progress; + if (progress) { + if (progress.key === 'view.check') clearTimeout(startup); + if (idleTimeout && (!lastProgress || progress.percent > lastProgress.percent || + (progress.percent === lastProgress.percent && progress.key === lastProgress.key && + progress.completed > (lastProgress.completed ?? 0)))) { + lastProgress = progress; + clearTimeout(inactivity); + inactivity = setTimeout(timedOut, idleTimeout); + } + showProgress(open, progress); + return; + } + if (result?.error || result?.localized) + settle(reject, Object.assign(new Error(result.error), { + localized: result.localized, retryable: result.retryable, + })); + else if (result?.html || result?.triangles || result?.files) settle(resolve, result); + }; + const timedOut = () => settle(reject, failed()); + const startup = startupTimeout && setTimeout(timedOut, startupTimeout); + let inactivity = idleTimeout && setTimeout(timedOut, idleTimeout); + try { worker.postMessage(data); } + catch (error) { settle(reject, error); } + }); +} + +async function prepareScratch(open) { + if (!/\.rvt$/i.test(open.file.name) || !globalThis.crypto?.randomUUID || !navigator.storage?.getDirectory) return; + const name = `ioviewer-open-${crypto.randomUUID()}.tmp`; + open.scratch = { name }; + try { + open.scratch.release = await holdScratchLease(name); + const directory = await navigator.storage.getDirectory(); + open.controller.signal.throwIfAborted(); + return await directory.getDirectoryHandle(name, { create: true }); + } catch (error) { + if (!['SecurityError', 'NotAllowedError', 'NotSupportedError'].includes(error.name)) throw error; + } +} + +function setViewerSource(frame, source) { + const url = new URL(source); + url.hash = new URLSearchParams({ ioextendLang: lang }); + frame.dataset.locale = lang; + frame.src = url; +} + +const pagedViewerUrl = new URL('./paged-viewer.html', import.meta.url); + +function syncViewerLanguage() { + if (opening || workspace.hidden || viewer.hidden || viewer.dataset.locale === lang) return; + const frame = viewer.cloneNode(false); + setViewerSource(frame, modelUrl ?? pagedViewerUrl); + viewer.replaceWith(frame); + viewer = frame; +} + +function stageFrame(open, files, deadline) { + const { signal } = open.controller; + signal.throwIfAborted(); + const frame = viewer.cloneNode(false); + frame.removeAttribute('id'); + frame.hidden = false; + frame.inert = true; + frame.classList.add('viewer-loading'); + setViewerSource(frame, open.url ?? pagedViewerUrl); + open.frame = frame; + return new Promise((resolve, reject) => { + function settle(callback, value) { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + frame.onerror = null; + window.removeEventListener('message', receive); + callback(value); + } + const abort = () => settle(reject, signal.reason); + function receive(event) { + if (event.source !== frame.contentWindow || event.origin !== 'null') return; + switch (event.data?.type) { + case 'ioviewer-page-request': + if (files) frame.contentWindow.postMessage({ type: 'ioviewer-pages', files }, '*'); + break; + case 'ioviewer-page-ready': + settle(resolve, frame); + break; + case 'ioviewer-page-error': + settle(reject, new Error(event.data.error)); + break; + } + } + signal.addEventListener('abort', abort, { once: true }); + const failed = detail => settle(reject, Object.assign(new Error(detail), { localized: message('view.pageFailed') })); + frame.onerror = () => failed('Viewer iframe failed to load.'); + const timer = deadline && setTimeout(() => failed('Viewer iframe did not report readiness.'), deadline); + window.addEventListener('message', receive); + viewer.after(frame); + }); +} + +function selectViewerFile(file) { + if (!(file instanceof File) || opening || isModelSelectionLocked()) return; + if (!/\.(rvt|nwc)$/i.test(file.name)) { + showStatus(message('chooseRvtNwc'), true); + return; + } + + if (file.size === 0) { + showStatus(message('emptyFile'), true); + return; + } + selectModelFile(file); +} + +async function openFile(file) { + const started = performance.now(); + const canPreview = /\.(rvt|nwc)$/i.test(file.name); + if (!canPreview) { + viewer.hidden = modelBar.hidden = true; + dropArea.hidden = false; + viewer.removeAttribute('src'); + if (modelUrl) URL.revokeObjectURL(modelUrl); + disposeScratch(displayedScratch); + modelUrl = displayedScratch = displayedFiles = undefined; + showStatus(() => `${file.name} · ${t('chooseRvtNwc')}`); + return; + } + if (threaded && (!crossOriginIsolated || typeof SharedArrayBuffer === 'undefined')) { + if (!fallbackReader) { + showStatus(message('workerFailed'), true); + return; + } + readerPath = fallbackReader; + } + const open = { file, controller: new AbortController() }; + opening = open; + showStatus(message('loadKernel')); + updateOpenButtons(); + cancelButton.hidden = false; + startOpeningProgress(); + + try { + let scratchDirectory, result, frame; + if (canUseFastReader(file)) { + try { + const fastResult = await runWorker(open, fastReader, { file }, readerStartupTimeout, fastOpenIdleTimeout); + if (!fastResult.html || fastResult.errors) throw new Error('Fast reader did not produce a complete view.'); + open.url = URL.createObjectURL(fastResult.html); + frame = await stageFrame(open, undefined, fastOpenIdleTimeout); + result = fastResult; + } catch (error) { + open.controller.signal.throwIfAborted(); + open.frame?.remove(); + if (open.url) URL.revokeObjectURL(open.url); + open.frame = open.url = undefined; + console.debug('IOExtend fast reader fallback', error.message || error.localized); + openingMeter.value = 0; + showProgress(open, { percent: 0, key: 'loadKernel' }); + } + } + if (!result) { + scratchDirectory = await prepareScratch(open); + try { + result = await runWorker(open, readerPath, { file, scratchDirectory }, readerStartupTimeout); + } catch (error) { + open.controller.signal.throwIfAborted(); + if (!fallbackReader || readerPath === fallbackReader || !error.retryable) throw error; + readerPath = fallbackReader; + open.recovering = true; + openingMeter.value = 0; + showProgress(open, { percent: 0, key: 'loadKernel' }); + await disposeScratch(open.scratch); + open.scratch = undefined; + open.controller.signal.throwIfAborted(); + scratchDirectory = await prepareScratch(open); + result = await runWorker(open, readerPath, { file, scratchDirectory }, readerStartupTimeout); + } + } + let pagesFiles; + if (result.triangles) { + showProgress(open, { percent: 97, key: 'view.preparePages', completed: result.triangles }); + const { files, pages, html } = await runWorker(open, './mesh-pages-worker.js', { + scratchDirectory, triangles: result.triangles, + inlineViewer: useViewerIsolation && Boolean(navigator.serviceWorker?.controller), + }); + showProgress(open, { percent: 99, key: 'view.openPages', completed: pages }); + pagesFiles = files; + if (html) open.url = URL.createObjectURL(html); + } else if (!frame) { + open.url = URL.createObjectURL(result.html); + } + frame ??= await stageFrame(open, pagesFiles); + open.controller.signal.throwIfAborted(); + + const oldScratch = displayedScratch; + const oldUrl = modelUrl; + viewer.remove(); + viewer = frame; + viewer.id = 'viewer'; + viewer.classList.remove('viewer-loading'); + viewer.inert = false; + displayedScratch = pagesFiles ? open.scratch : undefined; + if (pagesFiles) open.scratch = undefined; + displayedFiles = pagesFiles; + open.frame = undefined; + modelUrl = open.url; + open.url = undefined; + if (oldUrl) URL.revokeObjectURL(oldUrl); + disposeScratch(oldScratch); + viewer.hidden = modelBar.hidden = false; + dropArea.hidden = true; + modelName.textContent = file.name; + performance.measure('ioextend:first-frame', { start: started }); + + if (result.errors) showStatus(message('view.readErrors'), true); + else if (result.warnings) showStatus(message('view.readWarnings')); + else showStatus(''); + } catch (error) { + if (!open.controller.signal.aborted) + showStatus(() => t('view.failed', { detail: localize(error.localized ?? error.message) }), true); + } finally { + open.frame?.remove(); + if (open.url) URL.revokeObjectURL(open.url); + disposeScratch(open.scratch); + finish(open); + } +} + +for (const button of [openButton, replaceButton]) { + button.addEventListener('click', () => { + stopIsolationReload?.(); + input.click(); + }); +} + +input.addEventListener('change', () => { + selectViewerFile(input.files[0]); + input.value = ''; +}); + +cancelButton.addEventListener('click', () => { + if (!opening) return; + const open = opening; + open.controller.abort(); + finish(open); + showStatus(message('view.canceled')); + (viewer.hidden ? openButton : replaceButton).focus(); +}); + +function openDrop(files) { + if (workspace.hidden || opening || isModelSelectionLocked()) return; + if (files.length > 1) showStatus(message('oneViewerFile'), true); + else selectViewerFile(files[0]); +} + +window.addEventListener('message', event => { + if (event.source !== viewer.contentWindow || event.origin !== 'null') return; + if (event.data?.type === 'ioviewer-drop' && Array.isArray(event.data.files)) openDrop(event.data.files); + else if (event.data?.type === 'ioviewer-page-request' && displayedFiles) + viewer.contentWindow.postMessage({ type: 'ioviewer-pages', files: displayedFiles }, '*'); +}); + +window.addEventListener('dragenter', event => { + if (app.dataset.mode !== 'view' || !event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + dragDepth++; + if (!opening && !isModelSelectionLocked()) workspace.classList.add('dragging'); +}); + +window.addEventListener('dragleave', () => { + if (dragDepth > 0 && --dragDepth === 0) workspace.classList.remove('dragging'); +}); + +window.addEventListener('dragover', event => { + if (app.dataset.mode !== 'view' || !event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + event.dataTransfer.dropEffect = opening || isModelSelectionLocked() ? 'none' : 'copy'; +}); + +window.addEventListener('drop', event => { + if (app.dataset.mode !== 'view' || !event.dataTransfer.types.includes('Files')) return; + event.preventDefault(); + dragDepth = 0; + workspace.classList.remove('dragging'); + openDrop(event.dataTransfer.files); +}); + +window.addEventListener('pagehide', event => { + if (event.persisted) return; + opening?.controller.abort(); + disposeScratch(displayedScratch); +}); + +document.addEventListener('localechange', () => { + if (statusText) status.textContent = statusText(); + opening?.updateElapsed?.(); + syncViewerLanguage(); +}); +function openPendingFile() { + if (workspace.hidden) return; + if (!pendingFile) { + syncViewerLanguage(); + return; + } + const file = pendingFile; + pendingFile = undefined; + openFile(file); +} + +document.addEventListener('model-file-selected', ({ detail: file }) => { + stopIsolationReload?.(); + if (opening) { + opening.controller.abort(); + finish(opening); + } + pendingFile = file; + openPendingFile(); +}); +document.addEventListener('view-activated', openPendingFile); +document.addEventListener('operation-statechange', updateOpenButtons); +setupLanguage(); +cleanAbandonedScratch(); diff --git a/site/wwwroot/thread-isolation.js b/site/wwwroot/thread-isolation.js new file mode 100644 index 0000000..deec4f0 --- /dev/null +++ b/site/wwwroot/thread-isolation.js @@ -0,0 +1,19 @@ +self.addEventListener('install', event => event.waitUntil(self.skipWaiting())); +self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); + +const scope = new URL(self.registration.scope); +self.addEventListener('fetch', event => { + const request = event.request; + const url = new URL(request.url); + if (!['GET', 'HEAD'].includes(request.method) || url.origin !== scope.origin || !url.pathname.startsWith(scope.pathname)) + return; + + event.respondWith(fetch(request).then(response => { + if (!response.ok || response.redirected) return response; + const headers = new Headers(response.headers); + headers.set('Cross-Origin-Opener-Policy', 'same-origin'); + headers.set('Cross-Origin-Embedder-Policy', 'require-corp'); + if (url.pathname.endsWith('.mjs')) headers.set('Content-Type', 'text/javascript'); + return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); + })); +}); diff --git a/site/wwwroot/translations.js b/site/wwwroot/translations.js new file mode 100644 index 0000000..7f374fd --- /dev/null +++ b/site/wwwroot/translations.js @@ -0,0 +1,1917 @@ +const formatNames = { + "format.ifc": "IFC 2×3", + "format.scene": "IOScene", + "format.glb": "glTF Binary", + "format.obj": "Wavefront OBJ", + "format.ifc4": "IFC 4", + "format.scheduleCsv": "TimeLiner CSV", + "format.scheduleXml": "TimeLiner XML", + "format.msproject": "Microsoft Project XML", + "format.primavera": "Primavera P6 XER" +}; + +export const dictionaries = { + 'en': { + ...formatNames, + "phase.r22-layout": "Normalizing the Revit 2022 layout", + "phase.quantities": "Calculating quantities", + "phase.wide-model": "Reading the model with wide IDs", + "view.profileMissing": "This build does not include the selected memory profile.", + "view.scratchFailed": "Could not access temporary model data.", + "view.rangeRead": "Could not read the requested file range.", + "view.outOfRange": "The requested data extends past the end of the file.", + "siteTitle": "IOExtend — BIM tools", + "language": "Language", + "auto": "Auto", + "navigation": "BIM tools", + "view": "Viewer", + "export": "Export", + "downgrade": "Revit version", + "openingProgress": "Estimated model opening progress", + "cancel": "Cancel", + "drop": "Drop a model", + "supported": "Supported formats", + "chooseFile": "Choose a file", + "privacy": "Your device processes the file locally.", + "replaceModel": "Open another model", + "viewerTitle": "3D model viewer", + "sourceFile": "Source file", + "operationPrivacy": "Your browser processes files locally on this device.", + "exportFormats": "Export formats", + "selectMain": "Select main formats", + "formatsEmpty": "Choose a source file to see available formats.", + "optionalFormats": "Additional model data", + "optionalHint": "Some formats require corresponding data in the source model.", + "targetVersion": "Target Revit version", + "downgradeNote": "Experimental. Some data specific to newer versions may be unavailable in the copy.", + "operationProgress": "Processing progress", + "results": "Results", + "exportTitle": "Export model", + "exportDescription": "Choose one or more formats to save the model.", + "exportAction": "Export", + "downgradeTitle": "Downgrade Revit version", + "downgradeDescription": "Create a model copy for an earlier version of Revit.", + "downgradeAction": "Create copy", + "save": "Download", + "diagnostics": "Processing details", + "saveReport": "Download report", + "dropHere": "Drop a model here", + "chooseAnother": "Choose another file", + "chooseVersion": "Select a version", + "versionError": "Could not detect the version. Check that the RVT or RFA opens in Revit.", + "versionProbe": "Detecting the Revit version from metadata…", + "detectedVersion": "Source file · Revit {year}.", + "noEarlierVersion": "Source file · Revit {year}. No earlier versions are available for this file.", + "chooseSourceRvt": "Choose a source RVT or RFA file.", + "emptyFile": "The file must not be empty.", + "badFormat": "Choose a supported file format.", + "workerFailed": "Could not start processing.", + "workerResult": "Could not receive the result.", + "revitCopy": "Revit copy", + "done": "Done. Your files are ready to download.", + "partlyDone": "Completed {done} of {total}. See details below.", + "failed": "Processing failed. See details below.", + "operationCanceled": "Processing canceled.", + "oneFile": "Drop one source file.", + "elapsed": "Elapsed {elapsed}", + "operationTime": "Elapsed {elapsed} · stage {stageTime}", + "count": "{completed} of {total}", + "stagePercent": "{percent}% of this stage · {count}", + "step": "Stage {step} of {total}", + "readBytes": "Read from source (including rereads) {size}", + "writtenBytes": "Written {size}", + "batchCount": "Formats processed {done} of {total}", + "chooseRvtNwc": "Choose an RVT or NWC file.", + "loadKernel": "Loading the model engine…", + "view.fallback": "Reopening in single-threaded mode", + "oneViewerFile": "Drop one RVT or NWC file.", + "sourceReadFailed": "Could not read the source file.", + "invalidOperation": "Check the source file and selected format.", + "invalidTarget": "The target version is unavailable for this file.", + "profileFailed": "Could not load the Revit {year} profile.", + "missingOutput": "The engine did not create an output file.", + "emptyOutput": "The engine created an empty output file.", + "operationMemory": "The engine ran out of WebAssembly memory.", + "processFailed": "Could not process the file.", + "phase.prepare": "Preparing the job", + "phase.runtime": "Loading the processor", + "phase.metadata": "Reading Revit metadata", + "phase.profile": "Loading the target version profile", + "phase.plan": "Comparing source and target structures", + "phase.rewrite": "Converting the model for the target version", + "phase.write": "Writing the output", + "phase.verify": "Verifying the saved copy", + "phase.report": "Preparing the downgrade report", + "phase.decode": "Reading and decoding the model", + "phase.class-schema": "Reading Revit class schemas", + "phase.partitions": "Reading model partitions", + "phase.element-records": "Reading element records", + "phase.element-blocks": "Decoding element data", + "phase.parameter-stream": "Reading parameters", + "phase.recover-geometry": "Recovering geometry", + "phase.geometry-blocks": "Reading geometry blocks", + "phase.element-properties": "Collecting element properties", + "phase.build-model": "Assembling the model", + "phase.finalize-model": "Resolving model relationships", + "phase.complete": "Preparing geometry for export", + "phase.meshes": "Building meshes", + "phase.encode": "Encoding the export file", + "phase.download": "Preparing the download", + "unit.streams": "streams", + "unit.blocks": "blocks", + "unit.passes": "passes", + "unit.records": "records", + "unit.elements": "elements", + "format.ifcParameters": "IFC with Revit parameters", + "format.compact": "Compact JSON", + "format.full": "Full JSON", + "format.html": "Standalone 3D viewer", + "format.htmlLegacy": "Legacy Navisworks HTML", + "format.nwc": "Navisworks cache", + "format.pdfPlan": "PDF plan", + "format.pdf": "PDF sheets", + "format.pdfViews": "All views as PDF", + "format.sheets": "Sheet list", + "format.json": "Properties and tree JSON", + "format.viewpointsBcf": "BCF 2.1 viewpoints", + "format.viewpointsXml": "Navisworks viewpoints XML", + "format.sets": "Navisworks sets XML", + "format.grids": "Grids XML", + "format.clashBcf": "BCF 2.1 clashes", + "format.clashXml": "Navisworks clashes XML", + "format.clashHtml": "HTML clash report", + "view.nwcContainer": "Reading the NWC container", + "view.metadata": "Reading RVT metadata", + "view.partitions": "Unpacking RVT streams · {completed}/{total}", + "view.records": "Reading element records · {completed}/{total} blocks", + "view.geometry": "Geometry · {completed}/{total} blocks", + "view.blocks": "Decoding model blocks · {completed}/{total} passes", + "view.paramCount": "Reading parameters · {completed}/{total} MiB", + "view.decodeFound": "Decoding recovered blocks", + "view.wallGeometry": "Recovering wall geometry", + "view.decodeGeometry": "Decoding geometry blocks", + "view.seekGeometry": "Searching for additional geometry blocks", + "view.properties": "Matching names and properties · {completed}/{total} blocks", + "view.buildModel": "Assembling the Revit model · {completed}/{total} records", + "view.linkTypes": "Linking elements and types", + "view.modelValues": "Recovering model values", + "view.derivedProperties": "Calculating derived properties", + "view.phasesLevels": "Matching phases and levels", + "view.systemNames": "Resolving names and system data", + "view.resolveRefs": "Resolving element references", + "view.unitsCoordinates": "Resolving units and coordinates", + "view.prepareScene": "Preparing the model for 3D", + "view.rvtScene": "Building the RVT scene · {completed}/{total} elements", + "view.nwcGeometry": "Decoding NWC structure and geometry", + "view.nwcProperties": "Reading NWC properties and views", + "view.nwcScene": "Building the NWC 3D scene", + "view.check": "Checking the file", + "view.checkBytes": "Checking the file · read {completed} MiB", + "view.prepare": "Preparing the viewer", + "view.preparePages": "Preparing pages · {completed} triangles", + "view.openPages": "Opening the viewer · {completed} pages", + "view.pageTriangles": "Building pages · {completed}/{total} triangles", + "view.pageOverview": "Building the overview · level {level} · {completed}/{total} pages", + "view.pageProperties": "Preparing element properties · {completed}/{total}", + "view.readErrors": "The reader reported errors. Some elements may be missing.", + "view.readWarnings": "The reader reported warnings. The scene may be incomplete.", + "view.failed": "Could not open the model. {detail}", + "view.canceled": "Model opening canceled.", + "view.pageFailed": "Could not prepare the viewer page.", + "view.storage": "There is not enough storage for temporary model data. Free up disk space and try again.", + "view.memory": "The browser ran out of memory while processing the model.", + "view.noGeometry": "The file has no geometry to display.", + "view.badTriangles": "The page triangle count differs from the engine result.", + "view.pageStorage": "There is not enough storage for temporary model pages.", + }, + 'ru': { + ...formatNames, + "phase.r22-layout": "Приводим данные к структуре Revit 2022", + "phase.quantities": "Рассчитываем объёмы и количества", + "phase.wide-model": "Читаем модель с широкими идентификаторами", + "view.profileMissing": "Сборка не содержит выбранный профиль памяти.", + "view.scratchFailed": "Не удалось обратиться к временным данным модели.", + "view.rangeRead": "Не удалось прочитать диапазон файла.", + "view.outOfRange": "Чтение за концом файла.", + "siteTitle": "IOExtend — инструменты для BIM", + "language": "Язык", + "auto": "Авто", + "navigation": "Инструменты BIM", + "view": "Просмотр", + "export": "Экспорт", + "downgrade": "Версия Revit", + "openingProgress": "Примерный прогресс открытия модели", + "cancel": "Отменить", + "drop": "Перетащите модель", + "supported": "Поддерживаемые форматы", + "chooseFile": "Выбрать файл", + "privacy": "Файл обрабатывается на вашем устройстве.", + "replaceModel": "Открыть другую модель", + "viewerTitle": "3D-просмотр модели", + "sourceFile": "Исходный файл", + "operationPrivacy": "Файлы обрабатываются в браузере и остаются на вашем устройстве.", + "exportFormats": "Форматы экспорта", + "selectMain": "Выбрать основные", + "formatsEmpty": "Список появится после выбора исходного файла.", + "optionalFormats": "Дополнительные данные модели", + "optionalHint": "Для некоторых форматов исходная модель должна содержать соответствующие данные.", + "targetVersion": "Целевая версия Revit", + "downgradeNote": "Экспериментально. Часть данных, специфичных для новой версии, может быть недоступна в полученной копии.", + "operationProgress": "Ход обработки", + "results": "Результаты", + "exportTitle": "Экспорт модели", + "exportDescription": "Выберите один или несколько форматов для сохранения модели.", + "exportAction": "Экспортировать", + "downgradeTitle": "Понижение версии Revit", + "downgradeDescription": "Создайте копию модели для более ранней версии Revit.", + "downgradeAction": "Создать копию", + "save": "Скачать", + "diagnostics": "Сведения обработки", + "saveReport": "Скачать отчёт", + "dropHere": "Перетащите модель сюда", + "chooseAnother": "Выбрать другой файл", + "chooseVersion": "Выберите версию", + "versionError": "Не удалось определить версию. Проверьте, что файл RVT или RFA открывается в Revit.", + "versionProbe": "Читаем версию из метаданных…", + "detectedVersion": "Исходный файл · Revit {year}.", + "noEarlierVersion": "Исходный файл · Revit {year}. Более ранние версии для этого файла недоступны.", + "chooseSourceRvt": "Выберите исходный RVT или RFA.", + "emptyFile": "Размер файла должен быть больше нуля.", + "badFormat": "Выберите файл поддерживаемого формата.", + "workerFailed": "Не удалось запустить обработчик.", + "workerResult": "Не удалось получить результат.", + "revitCopy": "Копия Revit", + "done": "Готово. Результаты можно скачать.", + "partlyDone": "Готово {done} из {total}. Подробности ниже.", + "failed": "Обработка завершилась с ошибкой. Подробности ниже.", + "operationCanceled": "Обработка отменена.", + "oneFile": "Перетащите один исходный файл.", + "elapsed": "Прошло {elapsed}", + "operationTime": "Прошло {elapsed} · на этапе {stageTime}", + "count": "{completed} из {total}", + "stagePercent": "{percent}% этапа · {count}", + "step": "Этап {step} из {total}", + "readBytes": "Прочитано из исходника (с повторами) {size}", + "writtenBytes": "Записано {size}", + "batchCount": "Завершено форматов {done} из {total}", + "chooseRvtNwc": "Выберите файл RVT или NWC.", + "loadKernel": "Загружаем ядро…", + "view.fallback": "Повторяем открытие в однопоточном режиме", + "oneViewerFile": "Перетащите один файл RVT или NWC.", + "sourceReadFailed": "Не удалось прочитать исходный файл.", + "invalidOperation": "Проверьте исходный файл и выбранный формат.", + "invalidTarget": "Целевая версия недоступна для этого файла.", + "profileFailed": "Не удалось загрузить профиль Revit {year}.", + "missingOutput": "Обработчик не создал выходной файл.", + "emptyOutput": "Обработчик создал пустой файл.", + "operationMemory": "Обработчику не хватило памяти WebAssembly.", + "processFailed": "Не удалось обработать файл.", + "phase.prepare": "Готовим обработку", + "phase.runtime": "Загружаем обработчик", + "phase.metadata": "Читаем метаданные Revit", + "phase.profile": "Загружаем профиль целевой версии", + "phase.plan": "Сравниваем структуры исходной и целевой версий", + "phase.rewrite": "Преобразуем модель для целевой версии", + "phase.write": "Записываем результат", + "phase.verify": "Проверяем записанную копию", + "phase.report": "Формируем отчёт о понижении версии", + "phase.decode": "Читаем и разбираем модель", + "phase.class-schema": "Читаем схемы классов Revit", + "phase.partitions": "Читаем разделы модели", + "phase.element-records": "Читаем записи элементов", + "phase.element-blocks": "Разбираем данные элементов", + "phase.parameter-stream": "Читаем параметры", + "phase.recover-geometry": "Восстанавливаем геометрию", + "phase.geometry-blocks": "Читаем блоки геометрии", + "phase.element-properties": "Собираем свойства элементов", + "phase.build-model": "Собираем модель", + "phase.finalize-model": "Обрабатываем связи модели", + "phase.complete": "Готовим геометрию к экспорту", + "phase.meshes": "Строим сетки", + "phase.encode": "Формируем файл экспорта", + "phase.download": "Подготавливаем скачивание", + "unit.streams": "потоки", + "unit.blocks": "блоки", + "unit.passes": "проходы", + "unit.records": "записи", + "unit.elements": "элементы", + "format.ifcParameters": "IFC с параметрами Revit", + "format.compact": "Компактный JSON", + "format.full": "Полный JSON", + "format.html": "Автономный 3D-просмотр", + "format.htmlLegacy": "Прежний HTML Navisworks", + "format.nwc": "Кэш Navisworks", + "format.pdfPlan": "План PDF", + "format.pdf": "Листы PDF", + "format.pdfViews": "Все виды PDF", + "format.sheets": "Ведомость листов", + "format.json": "Свойства и дерево JSON", + "format.viewpointsBcf": "Виды BCF 2.1", + "format.viewpointsXml": "Виды Navisworks XML", + "format.sets": "Наборы Navisworks XML", + "format.grids": "Сетка осей XML", + "format.clashBcf": "Коллизии BCF 2.1", + "format.clashXml": "Коллизии Navisworks XML", + "format.clashHtml": "Отчёт о коллизиях HTML", + "view.nwcContainer": "Читаем контейнер NWC", + "view.metadata": "Читаем метаданные RVT", + "view.partitions": "Распаковываем потоки RVT · {completed} из {total}", + "view.records": "Читаем записи элементов · {completed} из {total} блоков", + "view.geometry": "Геометрия · {completed} из {total} блоков", + "view.blocks": "Разбираем блоки модели · {completed} из {total} проходов", + "view.paramCount": "Читаем параметры · {completed} из {total} МиБ", + "view.decodeFound": "Декодируем найденные блоки", + "view.wallGeometry": "Восстанавливаем геометрию стен", + "view.decodeGeometry": "Декодируем блоки геометрии", + "view.seekGeometry": "Ищем дополнительные блоки геометрии", + "view.properties": "Сопоставляем имена и свойства · {completed} из {total} блоков", + "view.buildModel": "Собираем модель Revit · {completed} из {total} записей", + "view.linkTypes": "Связываем элементы и типы", + "view.modelValues": "Восстанавливаем значения из модели", + "view.derivedProperties": "Рассчитываем производные свойства", + "view.phasesLevels": "Сопоставляем фазы и уровни", + "view.systemNames": "Уточняем имена и данные систем", + "view.resolveRefs": "Разрешаем ссылки на элементы", + "view.unitsCoordinates": "Уточняем единицы измерения и координаты", + "view.prepareScene": "Готовим модель к построению 3D-сцены", + "view.rvtScene": "Строим 3D-сцену RVT · {completed} из {total} элементов", + "view.nwcGeometry": "Разбираем структуру и геометрию NWC", + "view.nwcProperties": "Читаем свойства и виды NWC", + "view.nwcScene": "Строим 3D-сцену NWC", + "view.check": "Проверяем файл", + "view.checkBytes": "Проверяем файл · прочитано {completed} МиБ", + "view.prepare": "Подготавливаем просмотр", + "view.preparePages": "Готовим страницы · {completed} треугольников", + "view.openPages": "Открываем просмотр · {completed} страниц", + "view.pageTriangles": "Собираем страницы · {completed} из {total} треугольников", + "view.pageOverview": "Готовим обзор · уровень {level} · {completed} из {total} страниц", + "view.pageProperties": "Готовим свойства элементов · {completed} из {total}", + "view.readErrors": "При чтении возникли ошибки. В сцене могут отсутствовать элементы.", + "view.readWarnings": "Ядро сообщило о предупреждениях при чтении. Сцена может быть неполной.", + "view.failed": "Не удалось открыть модель. {detail}", + "view.canceled": "Открытие модели отменено.", + "view.pageFailed": "Не удалось подготовить страницу просмотра.", + "view.storage": "Не хватило места для временных данных модели. Освободите место на диске профиля браузера и повторите попытку.", + "view.memory": "Браузеру не хватило памяти для обработки модели.", + "view.noGeometry": "В файле не найдена геометрия для просмотра.", + "view.badTriangles": "Количество треугольников в страницах отличается от результата ядра.", + "view.pageStorage": "Не хватило места для временных страниц модели.", + }, + 'es': { + ...formatNames, + "phase.r22-layout": "Normalizando la estructura de Revit 2022", + "phase.quantities": "Calculando cantidades", + "phase.wide-model": "Leyendo el modelo con identificadores amplios", + "view.profileMissing": "Esta compilación no incluye el perfil de memoria seleccionado.", + "view.scratchFailed": "No se pudo acceder a los datos temporales del modelo.", + "view.rangeRead": "No se pudo leer el intervalo solicitado del archivo.", + "view.outOfRange": "Los datos solicitados superan el final del archivo.", + "siteTitle": "IOExtend — Herramientas BIM", + "language": "Idioma", + "auto": "Automático", + "navigation": "Herramientas BIM", + "view": "Visor", + "export": "Exportar", + "downgrade": "Versión de Revit", + "openingProgress": "Progreso estimado al abrir el modelo", + "cancel": "Cancelar", + "drop": "Arrastra un modelo", + "supported": "Formatos compatibles", + "chooseFile": "Elegir archivo", + "privacy": "El archivo se procesa en tu dispositivo.", + "replaceModel": "Abrir otro modelo", + "viewerTitle": "Visor de modelos 3D", + "sourceFile": "Archivo de origen", + "operationPrivacy": "El navegador procesa los archivos en este dispositivo.", + "exportFormats": "Formatos de exportación", + "selectMain": "Seleccionar formatos principales", + "formatsEmpty": "Elige un archivo de origen para ver los formatos disponibles.", + "optionalFormats": "Datos adicionales del modelo", + "optionalHint": "Algunos formatos requieren datos específicos en el modelo de origen.", + "targetVersion": "Versión de destino de Revit", + "downgradeNote": "Experimental. Es posible que ciertos datos de versiones más nuevas no estén disponibles en la copia.", + "operationProgress": "Progreso del procesamiento", + "results": "Resultados", + "exportTitle": "Exportar modelo", + "exportDescription": "Elige uno o varios formatos para guardar el modelo.", + "exportAction": "Exportar", + "downgradeTitle": "Convertir a una versión anterior de Revit", + "downgradeDescription": "Crea una copia del modelo para una versión anterior de Revit.", + "downgradeAction": "Crear copia", + "save": "Descargar", + "diagnostics": "Detalles del procesamiento", + "saveReport": "Descargar informe", + "dropHere": "Arrastra el modelo aquí", + "chooseAnother": "Elegir otro archivo", + "chooseVersion": "Selecciona una versión", + "versionError": "No se pudo detectar la versión. Comprueba que el RVT o RFA se abre en Revit.", + "versionProbe": "Detectando la versión en los metadatos…", + "detectedVersion": "Archivo de origen · Revit {year}.", + "noEarlierVersion": "Archivo de origen · Revit {year}. No hay versiones anteriores disponibles para este archivo.", + "chooseSourceRvt": "Elige un archivo RVT o RFA de origen.", + "emptyFile": "El archivo no puede estar vacío.", + "badFormat": "Elige un formato de archivo compatible.", + "workerFailed": "No se pudo iniciar el procesamiento.", + "workerResult": "No se pudo recibir el resultado.", + "revitCopy": "Copia de Revit", + "done": "Listo. Ya puedes descargar los archivos.", + "partlyDone": "Completados {done} de {total}. Consulta los detalles abajo.", + "failed": "Error de procesamiento. Consulta los detalles abajo.", + "operationCanceled": "Procesamiento cancelado.", + "oneFile": "Arrastra un solo archivo de origen.", + "elapsed": "Tiempo {elapsed}", + "operationTime": "Tiempo {elapsed} · etapa {stageTime}", + "count": "{completed} de {total}", + "stagePercent": "{percent}% de la etapa · {count}", + "step": "Etapa {step} de {total}", + "readBytes": "Lectura del origen (incluidas repeticiones) {size}", + "writtenBytes": "Escrito {size}", + "batchCount": "Formatos procesados {done} de {total}", + "chooseRvtNwc": "Elige un archivo RVT o NWC.", + "loadKernel": "Cargando el motor de modelos…", + "view.fallback": "Abriendo de nuevo en modo de un solo hilo", + "oneViewerFile": "Arrastra un solo archivo RVT o NWC.", + "sourceReadFailed": "No se pudo leer el archivo de origen.", + "invalidOperation": "Comprueba el archivo de origen y el formato seleccionado.", + "invalidTarget": "La versión de destino no está disponible para este archivo.", + "profileFailed": "No se pudo cargar el perfil de Revit {year}.", + "missingOutput": "El motor no generó un archivo de salida.", + "emptyOutput": "El motor generó un archivo vacío.", + "operationMemory": "El motor agotó la memoria de WebAssembly.", + "processFailed": "No se pudo procesar el archivo.", + "phase.prepare": "Preparando el proceso", + "phase.runtime": "Cargando el procesador", + "phase.metadata": "Leyendo metadatos de Revit", + "phase.profile": "Cargando el perfil de la versión de destino", + "phase.plan": "Comparando las estructuras de origen y destino", + "phase.rewrite": "Convirtiendo el modelo a la versión de destino", + "phase.write": "Escribiendo el resultado", + "phase.verify": "Verificando la copia guardada", + "phase.report": "Preparando el informe de conversión", + "phase.decode": "Leyendo y decodificando el modelo", + "phase.class-schema": "Leyendo esquemas de clases de Revit", + "phase.partitions": "Leyendo particiones del modelo", + "phase.element-records": "Leyendo registros de elementos", + "phase.element-blocks": "Decodificando datos de elementos", + "phase.parameter-stream": "Leyendo parámetros", + "phase.recover-geometry": "Recuperando geometría", + "phase.geometry-blocks": "Leyendo bloques de geometría", + "phase.element-properties": "Recopilando propiedades de elementos", + "phase.build-model": "Ensamblando el modelo", + "phase.finalize-model": "Resolviendo relaciones del modelo", + "phase.complete": "Preparando la geometría para la exportación", + "phase.meshes": "Generando mallas", + "phase.encode": "Generando el archivo de exportación", + "phase.download": "Preparando la descarga", + "unit.streams": "flujos", + "unit.blocks": "bloques", + "unit.passes": "pasadas", + "unit.records": "registros", + "unit.elements": "elementos", + "format.ifcParameters": "IFC con parámetros de Revit", + "format.compact": "JSON compacto", + "format.full": "JSON completo", + "format.html": "Visor 3D autónomo", + "format.htmlLegacy": "HTML clásico de Navisworks", + "format.nwc": "Caché de Navisworks", + "format.pdfPlan": "Plano en PDF", + "format.pdf": "Planos en PDF", + "format.pdfViews": "Todas las vistas en PDF", + "format.sheets": "Lista de planos", + "format.json": "Propiedades y árbol en JSON", + "format.viewpointsBcf": "Vistas BCF 2.1", + "format.viewpointsXml": "Vistas de Navisworks en XML", + "format.sets": "Conjuntos de Navisworks en XML", + "format.grids": "Rejillas en XML", + "format.clashBcf": "Interferencias BCF 2.1", + "format.clashXml": "Interferencias de Navisworks en XML", + "format.clashHtml": "Informe de interferencias HTML", + "view.nwcContainer": "Leyendo el contenedor NWC", + "view.metadata": "Leyendo metadatos RVT", + "view.partitions": "Descomprimiendo flujos RVT · {completed}/{total}", + "view.records": "Leyendo registros de elementos · {completed}/{total} bloques", + "view.geometry": "Geometría · {completed}/{total} bloques", + "view.blocks": "Decodificando bloques del modelo · {completed}/{total} pasadas", + "view.paramCount": "Leyendo parámetros · {completed}/{total} MiB", + "view.decodeFound": "Decodificando bloques recuperados", + "view.wallGeometry": "Recuperando la geometría de muros", + "view.decodeGeometry": "Decodificando bloques de geometría", + "view.seekGeometry": "Buscando más bloques de geometría", + "view.properties": "Relacionando nombres y propiedades · {completed}/{total} bloques", + "view.buildModel": "Ensamblando modelo Revit · {completed}/{total} registros", + "view.linkTypes": "Vinculando elementos y tipos", + "view.modelValues": "Recuperando valores del modelo", + "view.derivedProperties": "Calculando propiedades derivadas", + "view.phasesLevels": "Relacionando fases y niveles", + "view.systemNames": "Resolviendo nombres y datos de sistemas", + "view.resolveRefs": "Resolviendo referencias a elementos", + "view.unitsCoordinates": "Resolviendo unidades y coordenadas", + "view.prepareScene": "Preparando el modelo para 3D", + "view.rvtScene": "Creando la escena RVT · {completed}/{total} elementos", + "view.nwcGeometry": "Decodificando estructura y geometría de NWC", + "view.nwcProperties": "Leyendo propiedades y vistas de NWC", + "view.nwcScene": "Creando la escena 3D de NWC", + "view.check": "Comprobando el archivo", + "view.checkBytes": "Comprobando el archivo · {completed} MiB leídos", + "view.prepare": "Preparando el visor", + "view.preparePages": "Preparando páginas · {completed} triángulos", + "view.openPages": "Abriendo el visor · {completed} páginas", + "view.pageTriangles": "Creando páginas · {completed}/{total} triángulos", + "view.pageOverview": "Creando la vista general · nivel {level} · {completed}/{total} páginas", + "view.pageProperties": "Preparando propiedades de elementos · {completed}/{total}", + "view.readErrors": "Se produjeron errores de lectura. Es posible que falten elementos.", + "view.readWarnings": "Hubo avisos durante la lectura. Es posible que la escena esté incompleta.", + "view.failed": "No se pudo abrir el modelo. {detail}", + "view.canceled": "Se canceló la apertura del modelo.", + "view.pageFailed": "No se pudo preparar la página del visor.", + "view.storage": "No hay espacio para los datos temporales del modelo. Libera espacio y vuelve a intentarlo.", + "view.memory": "El navegador se quedó sin memoria al procesar el modelo.", + "view.noGeometry": "El archivo no contiene geometría que mostrar.", + "view.badTriangles": "El número de triángulos de las páginas difiere del resultado del motor.", + "view.pageStorage": "No hay espacio para las páginas temporales del modelo.", + }, + 'de': { + ...formatNames, + "phase.r22-layout": "Revit-2022-Struktur wird vereinheitlicht", + "phase.quantities": "Mengen werden berechnet", + "phase.wide-model": "Modell mit breiten IDs wird gelesen", + "view.profileMissing": "Dieser Build enthält das ausgewählte Speicherprofil nicht.", + "view.scratchFailed": "Auf temporäre Modelldaten konnte nicht zugegriffen werden.", + "view.rangeRead": "Der angeforderte Dateibereich konnte nicht gelesen werden.", + "view.outOfRange": "Die angeforderten Daten liegen hinter dem Dateiende.", + "siteTitle": "IOExtend — BIM-Werkzeuge", + "language": "Sprache", + "auto": "Automatisch", + "navigation": "BIM-Werkzeuge", + "view": "Viewer", + "export": "Export", + "downgrade": "Revit-Version", + "openingProgress": "Geschätzter Fortschritt beim Öffnen des Modells", + "cancel": "Abbrechen", + "drop": "Modell hierher ziehen", + "supported": "Unterstützte Formate", + "chooseFile": "Datei auswählen", + "privacy": "Die Datei wird auf Ihrem Gerät verarbeitet.", + "replaceModel": "Anderes Modell öffnen", + "viewerTitle": "3D-Modellviewer", + "sourceFile": "Quelldatei", + "operationPrivacy": "Der Browser verarbeitet Dateien lokal auf diesem Gerät.", + "exportFormats": "Exportformate", + "selectMain": "Hauptformate auswählen", + "formatsEmpty": "Wählen Sie eine Quelldatei, um verfügbare Formate zu sehen.", + "optionalFormats": "Zusätzliche Modelldaten", + "optionalHint": "Einige Formate erfordern passende Daten im Quellmodell.", + "targetVersion": "Revit-Zielversion", + "downgradeNote": "Experimentell. Einige Daten neuerer Versionen sind in der Kopie möglicherweise nicht verfügbar.", + "operationProgress": "Verarbeitungsfortschritt", + "results": "Ergebnisse", + "exportTitle": "Modell exportieren", + "exportDescription": "Wählen Sie ein oder mehrere Formate zum Speichern des Modells.", + "exportAction": "Exportieren", + "downgradeTitle": "Revit-Version herabstufen", + "downgradeDescription": "Erstellen Sie eine Modellkopie für eine frühere Revit-Version.", + "downgradeAction": "Kopie erstellen", + "save": "Herunterladen", + "diagnostics": "Verarbeitungsdetails", + "saveReport": "Bericht herunterladen", + "dropHere": "Modell hier ablegen", + "chooseAnother": "Andere Datei auswählen", + "chooseVersion": "Version auswählen", + "versionError": "Version konnte nicht erkannt werden. Prüfen Sie, ob sich RVT oder RFA in Revit öffnen lässt.", + "versionProbe": "Revit-Version wird aus Metadaten ermittelt…", + "detectedVersion": "Quelldatei · Revit {year}.", + "noEarlierVersion": "Quelldatei · Revit {year}. Für diese Datei sind keine früheren Versionen verfügbar.", + "chooseSourceRvt": "Wählen Sie eine RVT- oder RFA-Quelldatei.", + "emptyFile": "Die Datei darf nicht leer sein.", + "badFormat": "Wählen Sie ein unterstütztes Dateiformat.", + "workerFailed": "Verarbeitung konnte nicht gestartet werden.", + "workerResult": "Ergebnis konnte nicht empfangen werden.", + "revitCopy": "Revit-Kopie", + "done": "Fertig. Die Dateien stehen zum Download bereit.", + "partlyDone": "{done} von {total} abgeschlossen. Details siehe unten.", + "failed": "Verarbeitung fehlgeschlagen. Details siehe unten.", + "operationCanceled": "Verarbeitung abgebrochen.", + "oneFile": "Legen Sie eine einzelne Quelldatei ab.", + "elapsed": "Verstrichen {elapsed}", + "operationTime": "Verstrichen {elapsed} · Schritt {stageTime}", + "count": "{completed} von {total}", + "stagePercent": "{percent} % dieses Schritts · {count}", + "step": "Schritt {step} von {total}", + "readBytes": "Aus Quelle gelesen (mit Wiederholungen) {size}", + "writtenBytes": "Geschrieben {size}", + "batchCount": "Formate verarbeitet {done} von {total}", + "chooseRvtNwc": "Wählen Sie eine RVT- oder NWC-Datei.", + "loadKernel": "Modell-Engine wird geladen…", + "view.fallback": "Modell wird im Einzelthreadmodus erneut geöffnet", + "oneViewerFile": "Legen Sie eine RVT- oder NWC-Datei ab.", + "sourceReadFailed": "Quelldatei konnte nicht gelesen werden.", + "invalidOperation": "Prüfen Sie Quelldatei und gewähltes Format.", + "invalidTarget": "Die Zielversion ist für diese Datei nicht verfügbar.", + "profileFailed": "Das Revit-{year}-Profil konnte nicht geladen werden.", + "missingOutput": "Die Engine hat keine Ausgabedatei erstellt.", + "emptyOutput": "Die Engine hat eine leere Ausgabedatei erstellt.", + "operationMemory": "Der Engine ist der WebAssembly-Speicher ausgegangen.", + "processFailed": "Datei konnte nicht verarbeitet werden.", + "phase.prepare": "Verarbeitung wird vorbereitet", + "phase.runtime": "Prozessor wird geladen", + "phase.metadata": "Revit-Metadaten werden gelesen", + "phase.profile": "Profil der Zielversion wird geladen", + "phase.plan": "Quell- und Zielstrukturen werden verglichen", + "phase.rewrite": "Modell wird für die Zielversion konvertiert", + "phase.write": "Ausgabedatei wird geschrieben", + "phase.verify": "Gespeicherte Kopie wird geprüft", + "phase.report": "Bericht zur Versionsumstellung wird erstellt", + "phase.decode": "Modell wird gelesen und dekodiert", + "phase.class-schema": "Revit-Klassenschemata werden gelesen", + "phase.partitions": "Modellpartitionen werden gelesen", + "phase.element-records": "Elementdatensätze werden gelesen", + "phase.element-blocks": "Elementdaten werden dekodiert", + "phase.parameter-stream": "Parameter werden gelesen", + "phase.recover-geometry": "Geometrie wird rekonstruiert", + "phase.geometry-blocks": "Geometrieblöcke werden gelesen", + "phase.element-properties": "Elementeigenschaften werden gesammelt", + "phase.build-model": "Modell wird zusammengesetzt", + "phase.finalize-model": "Modellbeziehungen werden aufgelöst", + "phase.complete": "Geometrie wird für den Export vorbereitet", + "phase.meshes": "Netze werden erstellt", + "phase.encode": "Exportdatei wird erstellt", + "phase.download": "Download wird vorbereitet", + "unit.streams": "Datenströme", + "unit.blocks": "Blöcke", + "unit.passes": "Durchläufe", + "unit.records": "Datensätze", + "unit.elements": "Elemente", + "format.ifcParameters": "IFC mit Revit-Parametern", + "format.compact": "Kompaktes JSON", + "format.full": "Vollständiges JSON", + "format.html": "Eigenständiger 3D-Viewer", + "format.htmlLegacy": "Klassisches Navisworks-HTML", + "format.nwc": "Navisworks-Cache", + "format.pdfPlan": "Plan als PDF", + "format.pdf": "Pläne als PDF", + "format.pdfViews": "Alle Ansichten als PDF", + "format.sheets": "Planliste", + "format.json": "Eigenschaften und Baum als JSON", + "format.viewpointsBcf": "BCF-2.1-Ansichtspunkte", + "format.viewpointsXml": "Navisworks-Ansichtspunkte als XML", + "format.sets": "Navisworks-Sätze als XML", + "format.grids": "Rasterachsen als XML", + "format.clashBcf": "Kollisionen als BCF 2.1", + "format.clashXml": "Navisworks-Kollisionen als XML", + "format.clashHtml": "Kollisionsbericht als HTML", + "view.nwcContainer": "NWC-Container wird gelesen", + "view.metadata": "RVT-Metadaten werden gelesen", + "view.partitions": "RVT-Datenströme werden entpackt · {completed}/{total}", + "view.records": "Elementdatensätze werden gelesen · {completed}/{total} Blöcke", + "view.geometry": "Geometrie · {completed}/{total} Blöcke", + "view.blocks": "Modellblöcke werden dekodiert · {completed}/{total} Durchläufe", + "view.paramCount": "Parameter werden gelesen · {completed}/{total} MiB", + "view.decodeFound": "Gefundene Blöcke werden dekodiert", + "view.wallGeometry": "Wandgeometrie wird rekonstruiert", + "view.decodeGeometry": "Geometrieblöcke werden dekodiert", + "view.seekGeometry": "Weitere Geometrieblöcke werden gesucht", + "view.properties": "Namen und Eigenschaften werden zugeordnet · {completed}/{total} Blöcke", + "view.buildModel": "Revit-Modell wird zusammengesetzt · {completed}/{total} Datensätze", + "view.linkTypes": "Elemente und Typen werden verknüpft", + "view.modelValues": "Modellwerte werden rekonstruiert", + "view.derivedProperties": "Abgeleitete Eigenschaften werden berechnet", + "view.phasesLevels": "Phasen und Ebenen werden zugeordnet", + "view.systemNames": "Namen und Systemdaten werden abgeglichen", + "view.resolveRefs": "Elementreferenzen werden aufgelöst", + "view.unitsCoordinates": "Einheiten und Koordinaten werden abgeglichen", + "view.prepareScene": "Modell wird für 3D vorbereitet", + "view.rvtScene": "RVT-Szene wird erstellt · {completed}/{total} Elemente", + "view.nwcGeometry": "NWC-Struktur und -Geometrie werden dekodiert", + "view.nwcProperties": "NWC-Eigenschaften und -Ansichten werden gelesen", + "view.nwcScene": "NWC-3D-Szene wird erstellt", + "view.check": "Datei wird geprüft", + "view.checkBytes": "Datei wird geprüft · {completed} MiB gelesen", + "view.prepare": "Viewer wird vorbereitet", + "view.preparePages": "Seiten werden vorbereitet · {completed} Dreiecke", + "view.openPages": "Viewer wird geöffnet · {completed} Seiten", + "view.pageTriangles": "Seiten werden erstellt · {completed}/{total} Dreiecke", + "view.pageOverview": "Übersicht wird erstellt · Ebene {level} · {completed}/{total} Seiten", + "view.pageProperties": "Elementeigenschaften werden vorbereitet · {completed}/{total}", + "view.readErrors": "Beim Lesen sind Fehler aufgetreten. Einige Elemente fehlen möglicherweise.", + "view.readWarnings": "Beim Lesen gab es Warnungen. Die Szene ist möglicherweise unvollständig.", + "view.failed": "Modell konnte nicht geöffnet werden. {detail}", + "view.canceled": "Öffnen des Modells abgebrochen.", + "view.pageFailed": "Viewer-Seite konnte nicht vorbereitet werden.", + "view.storage": "Nicht genügend Speicherplatz für temporäre Modelldaten. Geben Sie Speicherplatz frei und versuchen Sie es erneut.", + "view.memory": "Dem Browser ist beim Verarbeiten des Modells der Speicher ausgegangen.", + "view.noGeometry": "Die Datei enthält keine darstellbare Geometrie.", + "view.badTriangles": "Die Anzahl der Seitendreiecke weicht vom Ergebnis der Engine ab.", + "view.pageStorage": "Nicht genügend Speicherplatz für temporäre Modellseiten.", + }, + 'fr': { + ...formatNames, + "phase.r22-layout": "Normalisation de la structure Revit 2022", + "phase.quantities": "Calcul des quantités", + "phase.wide-model": "Lecture du modèle avec identifiants longs", + "view.profileMissing": "Cette version ne contient pas le profil mémoire sélectionné.", + "view.scratchFailed": "Impossible d’accéder aux données temporaires du modèle.", + "view.rangeRead": "Impossible de lire la plage de fichier demandée.", + "view.outOfRange": "Les données demandées dépassent la fin du fichier.", + "siteTitle": "IOExtend — Outils BIM", + "language": "Langue", + "auto": "Automatique", + "navigation": "Outils BIM", + "view": "Visionneuse", + "export": "Exporter", + "downgrade": "Version Revit", + "openingProgress": "Progression estimée de l’ouverture du modèle", + "cancel": "Annuler", + "drop": "Déposez un modèle", + "supported": "Formats pris en charge", + "chooseFile": "Choisir un fichier", + "privacy": "Votre appareil traite le fichier localement.", + "replaceModel": "Ouvrir un autre modèle", + "viewerTitle": "Visionneuse de modèles 3D", + "sourceFile": "Fichier source", + "operationPrivacy": "Le navigateur traite les fichiers sur cet appareil.", + "exportFormats": "Formats d’export", + "selectMain": "Sélectionner les formats principaux", + "formatsEmpty": "Choisissez un fichier source pour voir les formats disponibles.", + "optionalFormats": "Données de modèle supplémentaires", + "optionalHint": "Certains formats nécessitent des données spécifiques dans le modèle source.", + "targetVersion": "Version Revit cible", + "downgradeNote": "Expérimental. Certaines données propres aux versions récentes peuvent manquer dans la copie.", + "operationProgress": "Progression du traitement", + "results": "Résultats", + "exportTitle": "Exporter le modèle", + "exportDescription": "Choisissez un ou plusieurs formats pour enregistrer le modèle.", + "exportAction": "Exporter", + "downgradeTitle": "Convertir vers une version Revit antérieure", + "downgradeDescription": "Créez une copie du modèle pour une version antérieure de Revit.", + "downgradeAction": "Créer une copie", + "save": "Télécharger", + "diagnostics": "Détails du traitement", + "saveReport": "Télécharger le rapport", + "dropHere": "Déposez un modèle ici", + "chooseAnother": "Choisir un autre fichier", + "chooseVersion": "Choisissez une version", + "versionError": "Version indétectable. Vérifiez que le fichier RVT ou RFA s’ouvre dans Revit.", + "versionProbe": "Détection de la version Revit à partir des métadonnées…", + "detectedVersion": "Fichier source · Revit {year}.", + "noEarlierVersion": "Fichier source · Revit {year}. Aucune version antérieure disponible pour ce fichier.", + "chooseSourceRvt": "Choisissez un fichier source RVT ou RFA.", + "emptyFile": "Le fichier doit être non vide.", + "badFormat": "Choisissez un format de fichier pris en charge.", + "workerFailed": "Impossible de démarrer le traitement.", + "workerResult": "Impossible de recevoir le résultat.", + "revitCopy": "Copie Revit", + "done": "Terminé. Vous pouvez télécharger les fichiers.", + "partlyDone": "{done} sur {total} terminés. Voir les détails ci-dessous.", + "failed": "Le traitement a échoué. Voir les détails ci-dessous.", + "operationCanceled": "Traitement annulé.", + "oneFile": "Déposez un seul fichier source.", + "elapsed": "Écoulé {elapsed}", + "operationTime": "Écoulé {elapsed} · étape {stageTime}", + "count": "{completed} sur {total}", + "stagePercent": "{percent} % de cette étape · {count}", + "step": "Étape {step} sur {total}", + "readBytes": "Lu depuis la source (relectures comprises) {size}", + "writtenBytes": "Écrit {size}", + "batchCount": "Formats traités {done} sur {total}", + "chooseRvtNwc": "Choisissez un fichier RVT ou NWC.", + "loadKernel": "Chargement du moteur de modèles…", + "view.fallback": "Réouverture en mode monothread", + "oneViewerFile": "Déposez un seul fichier RVT ou NWC.", + "sourceReadFailed": "Impossible de lire le fichier source.", + "invalidOperation": "Vérifiez le fichier source et le format sélectionné.", + "invalidTarget": "La version cible est indisponible pour ce fichier.", + "profileFailed": "Impossible de charger le profil Revit {year}.", + "missingOutput": "Le moteur n’a pas créé de fichier de sortie.", + "emptyOutput": "Le moteur a créé un fichier de sortie vide.", + "operationMemory": "Le moteur a épuisé la mémoire WebAssembly.", + "processFailed": "Impossible de traiter le fichier.", + "phase.prepare": "Préparation du traitement", + "phase.runtime": "Chargement du processeur", + "phase.metadata": "Lecture des métadonnées Revit", + "phase.profile": "Chargement du profil de la version cible", + "phase.plan": "Comparaison des structures source et cible", + "phase.rewrite": "Conversion du modèle vers la version cible", + "phase.write": "Écriture du résultat", + "phase.verify": "Vérification de la copie enregistrée", + "phase.report": "Création du rapport de conversion", + "phase.decode": "Lecture et décodage du modèle", + "phase.class-schema": "Lecture des schémas de classes Revit", + "phase.partitions": "Lecture des partitions du modèle", + "phase.element-records": "Lecture des enregistrements d’éléments", + "phase.element-blocks": "Décodage des données des éléments", + "phase.parameter-stream": "Lecture des paramètres", + "phase.recover-geometry": "Reconstitution de la géométrie", + "phase.geometry-blocks": "Lecture des blocs de géométrie", + "phase.element-properties": "Collecte des propriétés des éléments", + "phase.build-model": "Assemblage du modèle", + "phase.finalize-model": "Résolution des relations du modèle", + "phase.complete": "Préparation de la géométrie pour l’export", + "phase.meshes": "Création des maillages", + "phase.encode": "Création du fichier d’export", + "phase.download": "Préparation du téléchargement", + "unit.streams": "flux", + "unit.blocks": "blocs", + "unit.passes": "passes", + "unit.records": "enregistrements", + "unit.elements": "éléments", + "format.ifcParameters": "IFC avec paramètres Revit", + "format.compact": "JSON compact", + "format.full": "JSON complet", + "format.html": "Visionneuse 3D autonome", + "format.htmlLegacy": "HTML Navisworks classique", + "format.nwc": "Cache Navisworks", + "format.pdfPlan": "Plan PDF", + "format.pdf": "Feuilles PDF", + "format.pdfViews": "Toutes les vues en PDF", + "format.sheets": "Liste des feuilles", + "format.json": "Propriétés et arborescence JSON", + "format.viewpointsBcf": "Points de vue BCF 2.1", + "format.viewpointsXml": "Points de vue Navisworks XML", + "format.sets": "Jeux Navisworks XML", + "format.grids": "Quadrillages XML", + "format.clashBcf": "Conflits BCF 2.1", + "format.clashXml": "Conflits Navisworks XML", + "format.clashHtml": "Rapport de conflits HTML", + "view.nwcContainer": "Lecture du conteneur NWC", + "view.metadata": "Lecture des métadonnées RVT", + "view.partitions": "Décompression des flux RVT · {completed}/{total}", + "view.records": "Lecture des enregistrements d’éléments · {completed}/{total} blocs", + "view.geometry": "Géométrie · {completed}/{total} blocs", + "view.blocks": "Décodage des blocs du modèle · {completed}/{total} passes", + "view.paramCount": "Lecture des paramètres · {completed}/{total} Mio", + "view.decodeFound": "Décodage des blocs récupérés", + "view.wallGeometry": "Reconstitution de la géométrie des murs", + "view.decodeGeometry": "Décodage des blocs de géométrie", + "view.seekGeometry": "Recherche de blocs de géométrie supplémentaires", + "view.properties": "Association des noms et propriétés · {completed}/{total} blocs", + "view.buildModel": "Assemblage du modèle Revit · {completed}/{total} enregistrements", + "view.linkTypes": "Liaison des éléments et types", + "view.modelValues": "Récupération des valeurs du modèle", + "view.derivedProperties": "Calcul des propriétés dérivées", + "view.phasesLevels": "Association des phases et niveaux", + "view.systemNames": "Résolution des noms et données système", + "view.resolveRefs": "Résolution des références aux éléments", + "view.unitsCoordinates": "Résolution des unités et coordonnées", + "view.prepareScene": "Préparation du modèle pour la 3D", + "view.rvtScene": "Création de la scène RVT · {completed}/{total} éléments", + "view.nwcGeometry": "Décodage de la structure et de la géométrie NWC", + "view.nwcProperties": "Lecture des propriétés et vues NWC", + "view.nwcScene": "Création de la scène 3D NWC", + "view.check": "Vérification du fichier", + "view.checkBytes": "Vérification du fichier · {completed} Mio lus", + "view.prepare": "Préparation de la visionneuse", + "view.preparePages": "Préparation des pages · {completed} triangles", + "view.openPages": "Ouverture de la visionneuse · {completed} pages", + "view.pageTriangles": "Création des pages · {completed}/{total} triangles", + "view.pageOverview": "Création de la vue d’ensemble · niveau {level} · {completed}/{total} pages", + "view.pageProperties": "Préparation des propriétés des éléments · {completed}/{total}", + "view.readErrors": "La lecture a rencontré des erreurs. Certains éléments peuvent manquer.", + "view.readWarnings": "La lecture a émis des avertissements. La scène peut être incomplète.", + "view.failed": "Impossible d’ouvrir le modèle. {detail}", + "view.canceled": "Ouverture du modèle annulée.", + "view.pageFailed": "Impossible de préparer la page de la visionneuse.", + "view.storage": "Espace insuffisant pour les données temporaires du modèle. Libérez de l’espace disque et réessayez.", + "view.memory": "Le navigateur a manqué de mémoire pendant le traitement du modèle.", + "view.noGeometry": "Le fichier ne contient aucune géométrie à afficher.", + "view.badTriangles": "Le nombre de triangles des pages diffère du résultat du moteur.", + "view.pageStorage": "Espace insuffisant pour les pages temporaires du modèle.", + }, + 'pt': { + ...formatNames, + "phase.r22-layout": "Normalizando a estrutura do Revit 2022", + "phase.quantities": "Calculando quantitativos", + "phase.wide-model": "Lendo o modelo com identificadores longos", + "view.profileMissing": "Esta compilação não inclui o perfil de memória selecionado.", + "view.scratchFailed": "Não foi possível acessar os dados temporários do modelo.", + "view.rangeRead": "Não foi possível ler o intervalo solicitado do arquivo.", + "view.outOfRange": "Os dados solicitados ultrapassam o fim do arquivo.", + "siteTitle": "IOExtend — Ferramentas BIM", + "language": "Idioma", + "auto": "Automático", + "navigation": "Ferramentas BIM", + "view": "Visualizador", + "export": "Exportar", + "downgrade": "Versão do Revit", + "openingProgress": "Progresso estimado da abertura do modelo", + "cancel": "Cancelar", + "drop": "Arraste um modelo", + "supported": "Formatos compatíveis", + "chooseFile": "Escolher arquivo", + "privacy": "O arquivo é processado no seu dispositivo.", + "replaceModel": "Abrir outro modelo", + "viewerTitle": "Visualizador de modelos 3D", + "sourceFile": "Arquivo de origem", + "operationPrivacy": "O navegador processa os arquivos neste dispositivo.", + "exportFormats": "Formatos de exportação", + "selectMain": "Selecionar formatos principais", + "formatsEmpty": "Escolha um arquivo de origem para ver os formatos disponíveis.", + "optionalFormats": "Dados adicionais do modelo", + "optionalHint": "Alguns formatos exigem dados específicos no modelo de origem.", + "targetVersion": "Versão de destino do Revit", + "downgradeNote": "Experimental. Alguns dados específicos de versões novas podem não estar disponíveis na cópia.", + "operationProgress": "Progresso do processamento", + "results": "Resultados", + "exportTitle": "Exportar modelo", + "exportDescription": "Escolha um ou mais formatos para salvar o modelo.", + "exportAction": "Exportar", + "downgradeTitle": "Converter para uma versão anterior do Revit", + "downgradeDescription": "Crie uma cópia do modelo para uma versão anterior do Revit.", + "downgradeAction": "Criar cópia", + "save": "Baixar", + "diagnostics": "Detalhes do processamento", + "saveReport": "Baixar relatório", + "dropHere": "Arraste o modelo aqui", + "chooseAnother": "Escolher outro arquivo", + "chooseVersion": "Selecione uma versão", + "versionError": "Não foi possível detectar a versão. Verifique se o RVT ou RFA abre no Revit.", + "versionProbe": "Detectando a versão do Revit nos metadados…", + "detectedVersion": "Arquivo de origem · Revit {year}.", + "noEarlierVersion": "Arquivo de origem · Revit {year}. Não há versões anteriores disponíveis para este arquivo.", + "chooseSourceRvt": "Escolha um arquivo RVT ou RFA de origem.", + "emptyFile": "O arquivo não pode estar vazio.", + "badFormat": "Escolha um formato de arquivo compatível.", + "workerFailed": "Não foi possível iniciar o processamento.", + "workerResult": "Não foi possível receber o resultado.", + "revitCopy": "Cópia do Revit", + "done": "Pronto. Os arquivos já podem ser baixados.", + "partlyDone": "{done} de {total} concluídos. Veja os detalhes abaixo.", + "failed": "O processamento falhou. Veja os detalhes abaixo.", + "operationCanceled": "Processamento cancelado.", + "oneFile": "Arraste apenas um arquivo de origem.", + "elapsed": "Tempo {elapsed}", + "operationTime": "Tempo {elapsed} · etapa {stageTime}", + "count": "{completed} de {total}", + "stagePercent": "{percent}% da etapa · {count}", + "step": "Etapa {step} de {total}", + "readBytes": "Leitura da origem (inclui releituras) {size}", + "writtenBytes": "Gravado {size}", + "batchCount": "Formatos processados {done} de {total}", + "chooseRvtNwc": "Escolha um arquivo RVT ou NWC.", + "loadKernel": "Carregando o mecanismo de modelos…", + "view.fallback": "Reabrindo em modo de thread único", + "oneViewerFile": "Arraste apenas um arquivo RVT ou NWC.", + "sourceReadFailed": "Não foi possível ler o arquivo de origem.", + "invalidOperation": "Verifique o arquivo de origem e o formato selecionado.", + "invalidTarget": "A versão de destino não está disponível para este arquivo.", + "profileFailed": "Não foi possível carregar o perfil do Revit {year}.", + "missingOutput": "O mecanismo não criou um arquivo de saída.", + "emptyOutput": "O mecanismo criou um arquivo de saída vazio.", + "operationMemory": "O mecanismo ficou sem memória WebAssembly.", + "processFailed": "Não foi possível processar o arquivo.", + "phase.prepare": "Preparando o processamento", + "phase.runtime": "Carregando o processador", + "phase.metadata": "Lendo metadados do Revit", + "phase.profile": "Carregando o perfil da versão de destino", + "phase.plan": "Comparando as estruturas de origem e de destino", + "phase.rewrite": "Convertendo o modelo para a versão de destino", + "phase.write": "Gravando o resultado", + "phase.verify": "Verificando a cópia salva", + "phase.report": "Preparando o relatório de conversão", + "phase.decode": "Lendo e decodificando o modelo", + "phase.class-schema": "Lendo esquemas de classes do Revit", + "phase.partitions": "Lendo partições do modelo", + "phase.element-records": "Lendo registros de elementos", + "phase.element-blocks": "Decodificando dados dos elementos", + "phase.parameter-stream": "Lendo parâmetros", + "phase.recover-geometry": "Recuperando a geometria", + "phase.geometry-blocks": "Lendo blocos de geometria", + "phase.element-properties": "Coletando propriedades dos elementos", + "phase.build-model": "Montando o modelo", + "phase.finalize-model": "Resolvendo relações do modelo", + "phase.complete": "Preparando a geometria para exportação", + "phase.meshes": "Gerando malhas", + "phase.encode": "Gerando o arquivo de exportação", + "phase.download": "Preparando o download", + "unit.streams": "fluxos", + "unit.blocks": "blocos", + "unit.passes": "passagens", + "unit.records": "registros", + "unit.elements": "elementos", + "format.ifcParameters": "IFC com parâmetros do Revit", + "format.compact": "JSON compacto", + "format.full": "JSON completo", + "format.html": "Visualizador 3D autônomo", + "format.htmlLegacy": "HTML clássico do Navisworks", + "format.nwc": "Cache do Navisworks", + "format.pdfPlan": "Planta em PDF", + "format.pdf": "Folhas em PDF", + "format.pdfViews": "Todas as vistas em PDF", + "format.sheets": "Lista de folhas", + "format.json": "Propriedades e árvore em JSON", + "format.viewpointsBcf": "Pontos de vista BCF 2.1", + "format.viewpointsXml": "Pontos de vista do Navisworks em XML", + "format.sets": "Conjuntos do Navisworks em XML", + "format.grids": "Eixos em XML", + "format.clashBcf": "Interferências BCF 2.1", + "format.clashXml": "Interferências do Navisworks em XML", + "format.clashHtml": "Relatório de interferências HTML", + "view.nwcContainer": "Lendo o contêiner NWC", + "view.metadata": "Lendo metadados RVT", + "view.partitions": "Descompactando fluxos RVT · {completed}/{total}", + "view.records": "Lendo registros de elementos · {completed}/{total} blocos", + "view.geometry": "Geometria · {completed}/{total} blocos", + "view.blocks": "Decodificando blocos do modelo · {completed}/{total} passagens", + "view.paramCount": "Lendo parâmetros · {completed}/{total} MiB", + "view.decodeFound": "Decodificando blocos recuperados", + "view.wallGeometry": "Recuperando a geometria das paredes", + "view.decodeGeometry": "Decodificando blocos de geometria", + "view.seekGeometry": "Procurando blocos de geometria adicionais", + "view.properties": "Associando nomes e propriedades · {completed}/{total} blocos", + "view.buildModel": "Montando modelo Revit · {completed}/{total} registros", + "view.linkTypes": "Vinculando elementos e tipos", + "view.modelValues": "Recuperando valores do modelo", + "view.derivedProperties": "Calculando propriedades derivadas", + "view.phasesLevels": "Associando fases e níveis", + "view.systemNames": "Resolvendo nomes e dados de sistemas", + "view.resolveRefs": "Resolvendo referências a elementos", + "view.unitsCoordinates": "Resolvendo unidades e coordenadas", + "view.prepareScene": "Preparando o modelo para 3D", + "view.rvtScene": "Criando a cena RVT · {completed}/{total} elementos", + "view.nwcGeometry": "Decodificando estrutura e geometria NWC", + "view.nwcProperties": "Lendo propriedades e vistas NWC", + "view.nwcScene": "Criando a cena 3D NWC", + "view.check": "Verificando o arquivo", + "view.checkBytes": "Verificando o arquivo · {completed} MiB lidos", + "view.prepare": "Preparando o visualizador", + "view.preparePages": "Preparando páginas · {completed} triângulos", + "view.openPages": "Abrindo o visualizador · {completed} páginas", + "view.pageTriangles": "Criando páginas · {completed}/{total} triângulos", + "view.pageOverview": "Criando a visão geral · nível {level} · {completed}/{total} páginas", + "view.pageProperties": "Preparando propriedades dos elementos · {completed}/{total}", + "view.readErrors": "Houve erros de leitura. Alguns elementos podem estar ausentes.", + "view.readWarnings": "Houve avisos durante a leitura. A cena pode estar incompleta.", + "view.failed": "Não foi possível abrir o modelo. {detail}", + "view.canceled": "Abertura do modelo cancelada.", + "view.pageFailed": "Não foi possível preparar a página do visualizador.", + "view.storage": "Não há espaço para os dados temporários do modelo. Libere espaço em disco e tente novamente.", + "view.memory": "O navegador ficou sem memória ao processar o modelo.", + "view.noGeometry": "O arquivo não contém geometria para exibir.", + "view.badTriangles": "A contagem de triângulos das páginas não confere com o resultado do mecanismo.", + "view.pageStorage": "Não há espaço para as páginas temporárias do modelo.", + }, + 'it': { + ...formatNames, + "phase.r22-layout": "Normalizzazione della struttura Revit 2022", + "phase.quantities": "Calcolo delle quantità", + "phase.wide-model": "Lettura del modello con identificatori estesi", + "view.profileMissing": "Questa build non include il profilo di memoria selezionato.", + "view.scratchFailed": "Impossibile accedere ai dati temporanei del modello.", + "view.rangeRead": "Impossibile leggere l’intervallo richiesto del file.", + "view.outOfRange": "I dati richiesti superano la fine del file.", + "siteTitle": "IOExtend — Strumenti BIM", + "language": "Lingua", + "auto": "Automatico", + "navigation": "Strumenti BIM", + "view": "Visualizzatore", + "export": "Esporta", + "downgrade": "Versione Revit", + "openingProgress": "Avanzamento stimato dell’apertura del modello", + "cancel": "Annulla", + "drop": "Trascina un modello", + "supported": "Formati supportati", + "chooseFile": "Scegli file", + "privacy": "Il file viene elaborato sul tuo dispositivo.", + "replaceModel": "Apri un altro modello", + "viewerTitle": "Visualizzatore di modelli 3D", + "sourceFile": "File di origine", + "operationPrivacy": "Il browser elabora i file su questo dispositivo.", + "exportFormats": "Formati di esportazione", + "selectMain": "Seleziona formati principali", + "formatsEmpty": "Scegli un file di origine per vedere i formati disponibili.", + "optionalFormats": "Dati aggiuntivi del modello", + "optionalHint": "Alcuni formati richiedono dati specifici nel modello di origine.", + "targetVersion": "Versione di destinazione di Revit", + "downgradeNote": "Sperimentale. Alcuni dati delle versioni più recenti potrebbero non essere disponibili nella copia.", + "operationProgress": "Avanzamento dell’elaborazione", + "results": "Risultati", + "exportTitle": "Esporta modello", + "exportDescription": "Scegli uno o più formati per salvare il modello.", + "exportAction": "Esporta", + "downgradeTitle": "Converti a una versione precedente di Revit", + "downgradeDescription": "Crea una copia del modello per una versione precedente di Revit.", + "downgradeAction": "Crea copia", + "save": "Scarica", + "diagnostics": "Dettagli dell’elaborazione", + "saveReport": "Scarica rapporto", + "dropHere": "Trascina qui un modello", + "chooseAnother": "Scegli un altro file", + "chooseVersion": "Seleziona una versione", + "versionError": "Impossibile rilevare la versione. Verifica che il file RVT o RFA si apra in Revit.", + "versionProbe": "Rilevamento della versione di Revit dai metadati…", + "detectedVersion": "File di origine · Revit {year}.", + "noEarlierVersion": "File di origine · Revit {year}. Nessuna versione precedente disponibile per questo file.", + "chooseSourceRvt": "Scegli un file RVT o RFA di origine.", + "emptyFile": "Il file non può essere vuoto.", + "badFormat": "Scegli un formato di file supportato.", + "workerFailed": "Impossibile avviare l’elaborazione.", + "workerResult": "Impossibile ricevere il risultato.", + "revitCopy": "Copia Revit", + "done": "Fatto. Puoi scaricare i file.", + "partlyDone": "Completati {done} su {total}. Vedi i dettagli sotto.", + "failed": "Elaborazione non riuscita. Vedi i dettagli sotto.", + "operationCanceled": "Elaborazione annullata.", + "oneFile": "Trascina un solo file di origine.", + "elapsed": "Trascorso {elapsed}", + "operationTime": "Trascorso {elapsed} · fase {stageTime}", + "count": "{completed} su {total}", + "stagePercent": "{percent}% della fase · {count}", + "step": "Fase {step} di {total}", + "readBytes": "Letti dall’origine (riletture incluse) {size}", + "writtenBytes": "Scritti {size}", + "batchCount": "Formati elaborati {done} su {total}", + "chooseRvtNwc": "Scegli un file RVT o NWC.", + "loadKernel": "Caricamento del motore dei modelli…", + "view.fallback": "Riapertura in modalità a thread singolo", + "oneViewerFile": "Trascina un solo file RVT o NWC.", + "sourceReadFailed": "Impossibile leggere il file di origine.", + "invalidOperation": "Controlla il file di origine e il formato selezionato.", + "invalidTarget": "La versione di destinazione non è disponibile per questo file.", + "profileFailed": "Impossibile caricare il profilo Revit {year}.", + "missingOutput": "Il motore non ha creato un file di output.", + "emptyOutput": "Il motore ha creato un file di output vuoto.", + "operationMemory": "Il motore ha esaurito la memoria WebAssembly.", + "processFailed": "Impossibile elaborare il file.", + "phase.prepare": "Preparazione dell’elaborazione", + "phase.runtime": "Caricamento del processore", + "phase.metadata": "Lettura dei metadati Revit", + "phase.profile": "Caricamento del profilo della versione di destinazione", + "phase.plan": "Confronto delle strutture di origine e destinazione", + "phase.rewrite": "Conversione del modello per la versione di destinazione", + "phase.write": "Scrittura del risultato", + "phase.verify": "Verifica della copia salvata", + "phase.report": "Preparazione del rapporto di conversione", + "phase.decode": "Lettura e decodifica del modello", + "phase.class-schema": "Lettura degli schemi delle classi Revit", + "phase.partitions": "Lettura delle partizioni del modello", + "phase.element-records": "Lettura dei record degli elementi", + "phase.element-blocks": "Decodifica dei dati degli elementi", + "phase.parameter-stream": "Lettura dei parametri", + "phase.recover-geometry": "Ricostruzione della geometria", + "phase.geometry-blocks": "Lettura dei blocchi geometrici", + "phase.element-properties": "Raccolta delle proprietà degli elementi", + "phase.build-model": "Composizione del modello", + "phase.finalize-model": "Risoluzione delle relazioni del modello", + "phase.complete": "Preparazione della geometria per l’esportazione", + "phase.meshes": "Creazione delle mesh", + "phase.encode": "Creazione del file di esportazione", + "phase.download": "Preparazione del download", + "unit.streams": "flussi", + "unit.blocks": "blocchi", + "unit.passes": "passaggi", + "unit.records": "record", + "unit.elements": "elementi", + "format.ifcParameters": "IFC con parametri Revit", + "format.compact": "JSON compatto", + "format.full": "JSON completo", + "format.html": "Visualizzatore 3D autonomo", + "format.htmlLegacy": "HTML classico Navisworks", + "format.nwc": "Cache Navisworks", + "format.pdfPlan": "Pianta PDF", + "format.pdf": "Tavole PDF", + "format.pdfViews": "Tutte le viste in PDF", + "format.sheets": "Elenco delle tavole", + "format.json": "Proprietà e albero JSON", + "format.viewpointsBcf": "Punti di vista BCF 2.1", + "format.viewpointsXml": "Punti di vista Navisworks XML", + "format.sets": "Set Navisworks XML", + "format.grids": "Griglie XML", + "format.clashBcf": "Interferenze BCF 2.1", + "format.clashXml": "Interferenze Navisworks XML", + "format.clashHtml": "Rapporto interferenze HTML", + "view.nwcContainer": "Lettura del contenitore NWC", + "view.metadata": "Lettura dei metadati RVT", + "view.partitions": "Decompressione dei flussi RVT · {completed}/{total}", + "view.records": "Lettura dei record degli elementi · {completed}/{total} blocchi", + "view.geometry": "Geometria · {completed}/{total} blocchi", + "view.blocks": "Decodifica dei blocchi del modello · {completed}/{total} passaggi", + "view.paramCount": "Lettura dei parametri · {completed}/{total} MiB", + "view.decodeFound": "Decodifica dei blocchi recuperati", + "view.wallGeometry": "Ricostruzione della geometria delle pareti", + "view.decodeGeometry": "Decodifica dei blocchi geometrici", + "view.seekGeometry": "Ricerca di altri blocchi geometrici", + "view.properties": "Associazione di nomi e proprietà · {completed}/{total} blocchi", + "view.buildModel": "Composizione del modello Revit · {completed}/{total} record", + "view.linkTypes": "Collegamento di elementi e tipi", + "view.modelValues": "Recupero dei valori del modello", + "view.derivedProperties": "Calcolo delle proprietà derivate", + "view.phasesLevels": "Associazione di fasi e livelli", + "view.systemNames": "Risoluzione di nomi e dati di sistema", + "view.resolveRefs": "Risoluzione dei riferimenti agli elementi", + "view.unitsCoordinates": "Risoluzione di unità e coordinate", + "view.prepareScene": "Preparazione del modello per il 3D", + "view.rvtScene": "Creazione della scena RVT · {completed}/{total} elementi", + "view.nwcGeometry": "Decodifica della struttura e della geometria NWC", + "view.nwcProperties": "Lettura delle proprietà e delle viste NWC", + "view.nwcScene": "Creazione della scena 3D NWC", + "view.check": "Verifica del file", + "view.checkBytes": "Verifica del file · {completed} MiB letti", + "view.prepare": "Preparazione del visualizzatore", + "view.preparePages": "Preparazione delle pagine · {completed} triangoli", + "view.openPages": "Apertura del visualizzatore · {completed} pagine", + "view.pageTriangles": "Creazione delle pagine · {completed}/{total} triangoli", + "view.pageOverview": "Creazione della panoramica · livello {level} · {completed}/{total} pagine", + "view.pageProperties": "Preparazione delle proprietà degli elementi · {completed}/{total}", + "view.readErrors": "Si sono verificati errori di lettura. Alcuni elementi potrebbero mancare.", + "view.readWarnings": "La lettura ha generato avvisi. La scena potrebbe essere incompleta.", + "view.failed": "Impossibile aprire il modello. {detail}", + "view.canceled": "Apertura del modello annullata.", + "view.pageFailed": "Impossibile preparare la pagina del visualizzatore.", + "view.storage": "Spazio insufficiente per i dati temporanei del modello. Libera spazio su disco e riprova.", + "view.memory": "Il browser ha esaurito la memoria durante l’elaborazione del modello.", + "view.noGeometry": "Il file non contiene geometria da mostrare.", + "view.badTriangles": "Il numero di triangoli delle pagine differisce dal risultato del motore.", + "view.pageStorage": "Spazio insufficiente per le pagine temporanee del modello.", + }, + 'ja': { + ...formatNames, + "phase.r22-layout": "Revit 2022 のデータ構造に変換中", + "phase.quantities": "数量を計算中", + "phase.wide-model": "拡張 ID のモデルを読み取り中", + "view.profileMissing": "このビルドには選択したメモリプロファイルが含まれていません。", + "view.scratchFailed": "モデルの一時データにアクセスできませんでした。", + "view.rangeRead": "指定されたファイル範囲を読み取れませんでした。", + "view.outOfRange": "要求されたデータがファイルの末尾を超えています。", + "siteTitle": "IOExtend — BIM ツール", + "language": "言語", + "auto": "自動", + "navigation": "BIM ツール", + "view": "ビューアー", + "export": "エクスポート", + "downgrade": "Revit バージョン", + "openingProgress": "モデルを開く進捗の目安", + "cancel": "キャンセル", + "drop": "モデルをドロップ", + "supported": "対応形式", + "chooseFile": "ファイルを選択", + "privacy": "ファイルはお使いの端末で処理されます。", + "replaceModel": "別のモデルを開く", + "viewerTitle": "3D モデルビューアー", + "sourceFile": "元のファイル", + "operationPrivacy": "ファイルはこの端末のブラウザーで処理されます。", + "exportFormats": "エクスポート形式", + "selectMain": "主な形式を選択", + "formatsEmpty": "元のファイルを選ぶと利用可能な形式が表示されます。", + "optionalFormats": "モデルの追加データ", + "optionalHint": "一部の形式では、元のモデルに対応するデータが必要です。", + "targetVersion": "変換先の Revit バージョン", + "downgradeNote": "実験的な機能です。新しいバージョン固有のデータはコピーで使えない場合があります。", + "operationProgress": "処理の進捗", + "results": "結果", + "exportTitle": "モデルをエクスポート", + "exportDescription": "モデルの保存形式を選択してください。複数選択できます。", + "exportAction": "エクスポート", + "downgradeTitle": "Revit のバージョンを下げる", + "downgradeDescription": "以前の Revit バージョン用にモデルのコピーを作成します。", + "downgradeAction": "コピーを作成", + "save": "ダウンロード", + "diagnostics": "処理の詳細", + "saveReport": "レポートをダウンロード", + "dropHere": "モデルをここにドロップ", + "chooseAnother": "別のファイルを選択", + "chooseVersion": "バージョンを選択", + "versionError": "バージョンを検出できませんでした。RVT または RFA が Revit で開けるか確認してください。", + "versionProbe": "メタデータから Revit バージョンを確認中…", + "detectedVersion": "元のファイル · Revit {year}。", + "noEarlierVersion": "元のファイル · Revit {year}。このファイルで選べる以前のバージョンはありません。", + "chooseSourceRvt": "元の RVT または RFA ファイルを選択してください。", + "emptyFile": "空のファイルは読み込めません。", + "badFormat": "対応する形式のファイルを選択してください。", + "workerFailed": "処理を開始できませんでした。", + "workerResult": "結果を受け取れませんでした。", + "revitCopy": "Revit のコピー", + "done": "完了しました。ファイルをダウンロードできます。", + "partlyDone": "{total} 件中 {done} 件が完了しました。詳細は下に表示されます。", + "failed": "処理に失敗しました。詳細は下に表示されます。", + "operationCanceled": "処理をキャンセルしました。", + "oneFile": "元のファイルを 1 つドロップしてください。", + "elapsed": "経過 {elapsed}", + "operationTime": "経過 {elapsed} · この段階 {stageTime}", + "count": "{total} 件中 {completed} 件", + "stagePercent": "この段階の {percent}% · {count}", + "step": "全 {total} 段階の {step} 番目", + "readBytes": "元ファイルから読み取り済み(再読み取りを含む){size}", + "writtenBytes": "書き込み済み {size}", + "batchCount": "{total} 形式中 {done} 形式を処理済み", + "chooseRvtNwc": "RVT または NWC ファイルを選択してください。", + "loadKernel": "モデル処理エンジンを読み込み中…", + "view.fallback": "シングルスレッドモードで開き直しています", + "oneViewerFile": "RVT または NWC ファイルを 1 つドロップしてください。", + "sourceReadFailed": "元のファイルを読み取れませんでした。", + "invalidOperation": "元のファイルと選択した形式を確認してください。", + "invalidTarget": "このファイルには指定の変換先バージョンを使用できません。", + "profileFailed": "Revit {year} のプロファイルを読み込めませんでした。", + "missingOutput": "エンジンが出力ファイルを作成できませんでした。", + "emptyOutput": "エンジンが空の出力ファイルを作成しました。", + "operationMemory": "エンジンの WebAssembly メモリが不足しました。", + "processFailed": "ファイルを処理できませんでした。", + "phase.prepare": "処理を準備中", + "phase.runtime": "処理プログラムを読み込み中", + "phase.metadata": "Revit メタデータを読み取り中", + "phase.profile": "変換先バージョンのプロファイルを読み込み中", + "phase.plan": "元と変換先の構造を比較中", + "phase.rewrite": "変換先バージョン用にモデルを変換中", + "phase.write": "出力ファイルを書き込み中", + "phase.verify": "保存したコピーを検証中", + "phase.report": "バージョン変換のレポートを作成中", + "phase.decode": "モデルを読み取り、デコード中", + "phase.class-schema": "Revit のクラススキーマを読み取り中", + "phase.partitions": "モデルのパーティションを読み取り中", + "phase.element-records": "要素レコードを読み取り中", + "phase.element-blocks": "要素データをデコード中", + "phase.parameter-stream": "パラメータを読み取り中", + "phase.recover-geometry": "ジオメトリを復元中", + "phase.geometry-blocks": "ジオメトリブロックを読み取り中", + "phase.element-properties": "要素プロパティを収集中", + "phase.build-model": "モデルを組み立て中", + "phase.finalize-model": "モデル内の関連付けを処理中", + "phase.complete": "エクスポート用のジオメトリを準備中", + "phase.meshes": "メッシュを作成中", + "phase.encode": "エクスポートファイルを作成中", + "phase.download": "ダウンロードを準備中", + "unit.streams": "ストリーム", + "unit.blocks": "ブロック", + "unit.passes": "パス", + "unit.records": "レコード", + "unit.elements": "要素", + "format.ifcParameters": "Revit パラメータ付き IFC", + "format.compact": "コンパクト JSON", + "format.full": "完全版 JSON", + "format.html": "スタンドアロン 3D ビューアー", + "format.htmlLegacy": "従来の Navisworks HTML", + "format.nwc": "Navisworks キャッシュ", + "format.pdfPlan": "平面図 PDF", + "format.pdf": "シート PDF", + "format.pdfViews": "すべてのビューを PDF に", + "format.sheets": "シート一覧", + "format.json": "プロパティとツリーの JSON", + "format.viewpointsBcf": "BCF 2.1 視点", + "format.viewpointsXml": "Navisworks 視点 XML", + "format.sets": "Navisworks セット XML", + "format.grids": "通り芯 XML", + "format.clashBcf": "BCF 2.1 干渉", + "format.clashXml": "Navisworks 干渉 XML", + "format.clashHtml": "干渉レポート HTML", + "view.nwcContainer": "NWC コンテナーを読み取り中", + "view.metadata": "RVT メタデータを読み取り中", + "view.partitions": "RVT ストリームを展開中 · {completed}/{total}", + "view.records": "要素レコードを読み取り中 · {completed}/{total} ブロック", + "view.geometry": "ジオメトリ · {completed}/{total} ブロック", + "view.blocks": "モデルブロックをデコード中 · {completed}/{total} パス", + "view.paramCount": "パラメータを読み取り中 · {completed}/{total} MiB", + "view.decodeFound": "見つかったブロックをデコード中", + "view.wallGeometry": "壁のジオメトリを復元中", + "view.decodeGeometry": "ジオメトリブロックをデコード中", + "view.seekGeometry": "追加のジオメトリブロックを検索中", + "view.properties": "名前とプロパティを照合中 · {completed}/{total} ブロック", + "view.buildModel": "Revit モデルを組み立て中 · {completed}/{total} レコード", + "view.linkTypes": "要素とタイプを関連付け中", + "view.modelValues": "モデルの値を復元中", + "view.derivedProperties": "派生プロパティを計算中", + "view.phasesLevels": "フェーズとレベルを照合中", + "view.systemNames": "名前とシステムデータを確定中", + "view.resolveRefs": "要素への参照を解決中", + "view.unitsCoordinates": "単位と座標を確定中", + "view.prepareScene": "3D 表示用にモデルを準備中", + "view.rvtScene": "RVT シーンを作成中 · {completed}/{total} 要素", + "view.nwcGeometry": "NWC の構造とジオメトリをデコード中", + "view.nwcProperties": "NWC のプロパティとビューを読み取り中", + "view.nwcScene": "NWC の 3D シーンを作成中", + "view.check": "ファイルを確認中", + "view.checkBytes": "ファイルを確認中 · {completed} MiB 読み取り済み", + "view.prepare": "ビューアーを準備中", + "view.preparePages": "ページを準備中 · {completed} 三角形", + "view.openPages": "ビューアーを開いています · {completed} ページ", + "view.pageTriangles": "ページを作成中 · {completed}/{total} 三角形", + "view.pageOverview": "概要を作成中 · レベル {level} · {completed}/{total} ページ", + "view.pageProperties": "要素プロパティを準備中 · {completed}/{total}", + "view.readErrors": "読み取り時にエラーが発生しました。一部の要素が欠落している可能性があります。", + "view.readWarnings": "読み取り時に警告が発生しました。シーンが不完全な可能性があります。", + "view.failed": "モデルを開けませんでした。{detail}", + "view.canceled": "モデルを開く処理をキャンセルしました。", + "view.pageFailed": "ビューアーページを準備できませんでした。", + "view.storage": "モデルの一時データを保存する空き容量が不足しています。ディスクの空き容量を増やして再試行してください。", + "view.memory": "モデルの処理中にブラウザーのメモリが不足しました。", + "view.noGeometry": "ファイルに表示できるジオメトリがありません。", + "view.badTriangles": "ページの三角形の数がエンジンの結果と一致しません。", + "view.pageStorage": "モデルの一時ページを保存する空き容量が不足しています。", + }, + 'ko': { + ...formatNames, + "phase.r22-layout": "Revit 2022 데이터 구조로 정규화 중", + "phase.quantities": "수량 계산 중", + "phase.wide-model": "넓은 ID를 사용하는 모델 읽는 중", + "view.profileMissing": "이 빌드에는 선택한 메모리 프로필이 없습니다.", + "view.scratchFailed": "임시 모델 데이터에 접근할 수 없습니다.", + "view.rangeRead": "요청한 파일 범위를 읽을 수 없습니다.", + "view.outOfRange": "요청한 데이터가 파일 끝을 벗어났습니다.", + "siteTitle": "IOExtend — BIM 도구", + "language": "언어", + "auto": "자동", + "navigation": "BIM 도구", + "view": "뷰어", + "export": "내보내기", + "downgrade": "Revit 버전", + "openingProgress": "예상 모델 열기 진행률", + "cancel": "취소", + "drop": "모델 끌어 놓기", + "supported": "지원 형식", + "chooseFile": "파일 선택", + "privacy": "파일은 현재 기기에서 처리됩니다.", + "replaceModel": "다른 모델 열기", + "viewerTitle": "3D 모델 뷰어", + "sourceFile": "원본 파일", + "operationPrivacy": "브라우저가 현재 기기에서 파일을 처리합니다.", + "exportFormats": "내보내기 형식", + "selectMain": "주요 형식 선택", + "formatsEmpty": "원본 파일을 선택하면 사용할 수 있는 형식이 표시됩니다.", + "optionalFormats": "추가 모델 데이터", + "optionalHint": "일부 형식은 원본 모델에 해당 데이터가 있어야 합니다.", + "targetVersion": "대상 Revit 버전", + "downgradeNote": "실험적 기능입니다. 최신 버전에만 있는 일부 데이터는 사본에 포함되지 않을 수 있습니다.", + "operationProgress": "처리 진행률", + "results": "결과", + "exportTitle": "모델 내보내기", + "exportDescription": "모델을 저장할 형식을 하나 이상 선택하세요.", + "exportAction": "내보내기", + "downgradeTitle": "Revit 버전 낮추기", + "downgradeDescription": "이전 버전의 Revit에 맞는 모델 사본을 만듭니다.", + "downgradeAction": "사본 만들기", + "save": "다운로드", + "diagnostics": "처리 세부 정보", + "saveReport": "보고서 다운로드", + "dropHere": "여기에 모델 끌어 놓기", + "chooseAnother": "다른 파일 선택", + "chooseVersion": "버전 선택", + "versionError": "버전을 확인할 수 없습니다. RVT 또는 RFA 파일이 Revit에서 열리는지 확인하세요.", + "versionProbe": "메타데이터에서 Revit 버전 확인 중…", + "detectedVersion": "원본 파일 · Revit {year}.", + "noEarlierVersion": "원본 파일 · Revit {year}. 이 파일에 사용할 수 있는 이전 버전이 없습니다.", + "chooseSourceRvt": "원본 RVT 또는 RFA 파일을 선택하세요.", + "emptyFile": "빈 파일은 사용할 수 없습니다.", + "badFormat": "지원되는 파일 형식을 선택하세요.", + "workerFailed": "처리를 시작할 수 없습니다.", + "workerResult": "결과를 받을 수 없습니다.", + "revitCopy": "Revit 사본", + "done": "완료되었습니다. 파일을 다운로드할 수 있습니다.", + "partlyDone": "총 {total}개 중 {done}개가 완료되었습니다. 아래에서 세부 정보를 확인하세요.", + "failed": "처리에 실패했습니다. 아래에서 세부 정보를 확인하세요.", + "operationCanceled": "처리를 취소했습니다.", + "oneFile": "원본 파일을 하나만 놓으세요.", + "elapsed": "경과 {elapsed}", + "operationTime": "경과 {elapsed} · 현재 단계 {stageTime}", + "count": "{total}개 중 {completed}개", + "stagePercent": "현재 단계 {percent}% · {count}", + "step": "{total}단계 중 {step}단계", + "readBytes": "원본 읽기 (다시 읽기 포함) {size}", + "writtenBytes": "기록됨 {size}", + "batchCount": "형식 {total}개 중 {done}개 처리됨", + "chooseRvtNwc": "RVT 또는 NWC 파일을 선택하세요.", + "loadKernel": "모델 엔진 로드 중…", + "view.fallback": "단일 스레드 모드로 다시 여는 중", + "oneViewerFile": "RVT 또는 NWC 파일을 하나만 놓으세요.", + "sourceReadFailed": "원본 파일을 읽을 수 없습니다.", + "invalidOperation": "원본 파일과 선택한 형식을 확인하세요.", + "invalidTarget": "이 파일에 대상 버전을 사용할 수 없습니다.", + "profileFailed": "Revit {year} 프로필을 로드할 수 없습니다.", + "missingOutput": "엔진에서 출력 파일을 만들지 못했습니다.", + "emptyOutput": "엔진이 빈 출력 파일을 만들었습니다.", + "operationMemory": "엔진의 WebAssembly 메모리가 부족합니다.", + "processFailed": "파일을 처리할 수 없습니다.", + "phase.prepare": "처리 준비 중", + "phase.runtime": "처리기 로드 중", + "phase.metadata": "Revit 메타데이터 읽는 중", + "phase.profile": "대상 버전 프로필 로드 중", + "phase.plan": "원본과 대상 구조 비교 중", + "phase.rewrite": "대상 버전에 맞게 모델 변환 중", + "phase.write": "결과 기록 중", + "phase.verify": "저장된 사본 확인 중", + "phase.report": "버전 변환 보고서 작성 중", + "phase.decode": "모델 읽기 및 디코딩 중", + "phase.class-schema": "Revit 클래스 스키마 읽는 중", + "phase.partitions": "모델 파티션 읽는 중", + "phase.element-records": "요소 레코드 읽는 중", + "phase.element-blocks": "요소 데이터 디코딩 중", + "phase.parameter-stream": "매개변수 읽는 중", + "phase.recover-geometry": "형상 복원 중", + "phase.geometry-blocks": "형상 블록 읽는 중", + "phase.element-properties": "요소 속성 수집 중", + "phase.build-model": "모델 조립 중", + "phase.finalize-model": "모델 관계 해석 중", + "phase.complete": "내보낼 형상 준비 중", + "phase.meshes": "메시 생성 중", + "phase.encode": "내보내기 파일 생성 중", + "phase.download": "다운로드 준비 중", + "unit.streams": "스트림", + "unit.blocks": "블록", + "unit.passes": "패스", + "unit.records": "레코드", + "unit.elements": "요소", + "format.ifcParameters": "Revit 매개변수가 포함된 IFC", + "format.compact": "간결한 JSON", + "format.full": "전체 JSON", + "format.html": "독립 실행형 3D 뷰어", + "format.htmlLegacy": "기존 Navisworks HTML", + "format.nwc": "Navisworks 캐시", + "format.pdfPlan": "평면도 PDF", + "format.pdf": "시트 PDF", + "format.pdfViews": "모든 뷰 PDF", + "format.sheets": "시트 목록", + "format.json": "속성과 트리 JSON", + "format.viewpointsBcf": "BCF 2.1 관측점", + "format.viewpointsXml": "Navisworks 관측점 XML", + "format.sets": "Navisworks 세트 XML", + "format.grids": "그리드 XML", + "format.clashBcf": "BCF 2.1 간섭", + "format.clashXml": "Navisworks 간섭 XML", + "format.clashHtml": "간섭 보고서 HTML", + "view.nwcContainer": "NWC 컨테이너 읽는 중", + "view.metadata": "RVT 메타데이터 읽는 중", + "view.partitions": "RVT 스트림 압축 해제 중 · {completed}/{total}", + "view.records": "요소 레코드 읽는 중 · {completed}/{total} 블록", + "view.geometry": "형상 · {completed}/{total} 블록", + "view.blocks": "모델 블록 디코딩 중 · {completed}/{total} 패스", + "view.paramCount": "매개변수 읽는 중 · {completed}/{total} MiB", + "view.decodeFound": "복구된 블록 디코딩 중", + "view.wallGeometry": "벽 형상 복원 중", + "view.decodeGeometry": "형상 블록 디코딩 중", + "view.seekGeometry": "추가 형상 블록 검색 중", + "view.properties": "이름과 속성 연결 중 · {completed}/{total} 블록", + "view.buildModel": "Revit 모델 조립 중 · {completed}/{total} 레코드", + "view.linkTypes": "요소와 유형 연결 중", + "view.modelValues": "모델 값 복원 중", + "view.derivedProperties": "파생 속성 계산 중", + "view.phasesLevels": "단계와 레벨 연결 중", + "view.systemNames": "이름과 시스템 데이터 확인 중", + "view.resolveRefs": "요소 참조 해석 중", + "view.unitsCoordinates": "단위와 좌표 확인 중", + "view.prepareScene": "3D용 모델 준비 중", + "view.rvtScene": "RVT 장면 생성 중 · {completed}/{total} 요소", + "view.nwcGeometry": "NWC 구조와 형상 디코딩 중", + "view.nwcProperties": "NWC 속성과 뷰 읽는 중", + "view.nwcScene": "NWC 3D 장면 생성 중", + "view.check": "파일 확인 중", + "view.checkBytes": "파일 확인 중 · {completed} MiB 읽음", + "view.prepare": "뷰어 준비 중", + "view.preparePages": "페이지 준비 중 · 삼각형 {completed}개", + "view.openPages": "뷰어 여는 중 · 페이지 {completed}개", + "view.pageTriangles": "페이지 생성 중 · 삼각형 {completed}/{total}개", + "view.pageOverview": "개요 생성 중 · 레벨 {level} · {completed}/{total} 페이지", + "view.pageProperties": "요소 속성 준비 중 · {completed}/{total}", + "view.readErrors": "읽는 중 오류가 발생했습니다. 일부 요소가 누락되었을 수 있습니다.", + "view.readWarnings": "읽는 중 경고가 발생했습니다. 장면이 불완전할 수 있습니다.", + "view.failed": "모델을 열 수 없습니다. {detail}", + "view.canceled": "모델 열기를 취소했습니다.", + "view.pageFailed": "뷰어 페이지를 준비할 수 없습니다.", + "view.storage": "임시 모델 데이터를 저장할 공간이 부족합니다. 디스크 공간을 확보하고 다시 시도하세요.", + "view.memory": "모델을 처리하는 동안 브라우저 메모리가 부족해졌습니다.", + "view.noGeometry": "파일에 표시할 형상이 없습니다.", + "view.badTriangles": "페이지의 삼각형 수가 엔진 결과와 다릅니다.", + "view.pageStorage": "임시 모델 페이지를 저장할 공간이 부족합니다.", + }, + 'zh-Hans': { + ...formatNames, + "phase.r22-layout": "正在规范化 Revit 2022 结构", + "phase.quantities": "正在计算工程量", + "phase.wide-model": "正在读取使用宽位标识符的模型", + "view.profileMissing": "此构建不包含选定的内存配置。", + "view.scratchFailed": "无法访问模型临时数据。", + "view.rangeRead": "无法读取所请求的文件范围。", + "view.outOfRange": "所请求的数据超出文件末尾。", + "siteTitle": "IOExtend — BIM 工具", + "language": "语言", + "auto": "自动", + "navigation": "BIM 工具", + "view": "查看器", + "export": "导出", + "downgrade": "Revit 版本", + "openingProgress": "模型打开进度估算", + "cancel": "取消", + "drop": "拖放模型", + "supported": "支持的格式", + "chooseFile": "选择文件", + "privacy": "文件在您的设备上处理。", + "replaceModel": "打开其他模型", + "viewerTitle": "3D 模型查看器", + "sourceFile": "源文件", + "operationPrivacy": "浏览器在此设备上处理文件。", + "exportFormats": "导出格式", + "selectMain": "选择主要格式", + "formatsEmpty": "选择源文件后即可查看可用格式。", + "optionalFormats": "其他模型数据", + "optionalHint": "某些格式要求源模型包含相关数据。", + "targetVersion": "目标 Revit 版本", + "downgradeNote": "实验功能。较新版本特有的部分数据可能无法在副本中使用。", + "operationProgress": "处理进度", + "results": "结果", + "exportTitle": "导出模型", + "exportDescription": "选择一种或多种格式保存模型。", + "exportAction": "导出", + "downgradeTitle": "降低 Revit 版本", + "downgradeDescription": "创建适用于较早 Revit 版本的模型副本。", + "downgradeAction": "创建副本", + "save": "下载", + "diagnostics": "处理详情", + "saveReport": "下载报告", + "dropHere": "将模型拖到这里", + "chooseAnother": "选择其他文件", + "chooseVersion": "选择版本", + "versionError": "无法识别版本。请检查 RVT 或 RFA 文件能否在 Revit 中打开。", + "versionProbe": "正在从元数据检测 Revit 版本…", + "detectedVersion": "源文件 · Revit {year}。", + "noEarlierVersion": "源文件 · Revit {year}。此文件没有可用的较早版本。", + "chooseSourceRvt": "选择源 RVT 或 RFA 文件。", + "emptyFile": "文件不能为空。", + "badFormat": "选择支持的文件格式。", + "workerFailed": "无法启动处理。", + "workerResult": "无法接收结果。", + "revitCopy": "Revit 副本", + "done": "完成,可下载结果文件。", + "partlyDone": "已完成 {done}/{total} 项。详情见下方。", + "failed": "处理失败。详情见下方。", + "operationCanceled": "处理已取消。", + "oneFile": "请拖放一个源文件。", + "elapsed": "已用时 {elapsed}", + "operationTime": "已用时 {elapsed} · 本阶段 {stageTime}", + "count": "{completed}/{total}", + "stagePercent": "阶段进度 {percent}% · {count}", + "step": "第 {step}/{total} 阶段", + "readBytes": "源文件读取量(含重复读取){size}", + "writtenBytes": "已写入 {size}", + "batchCount": "已处理 {done}/{total} 种格式", + "chooseRvtNwc": "选择 RVT 或 NWC 文件。", + "loadKernel": "正在加载模型引擎…", + "view.fallback": "正在以单线程模式重新打开", + "oneViewerFile": "请拖放一个 RVT 或 NWC 文件。", + "sourceReadFailed": "无法读取源文件。", + "invalidOperation": "请检查源文件及所选格式。", + "invalidTarget": "此文件无法使用目标版本。", + "profileFailed": "无法加载 Revit {year} 配置文件。", + "missingOutput": "引擎未生成输出文件。", + "emptyOutput": "引擎生成了空的输出文件。", + "operationMemory": "引擎耗尽了 WebAssembly 内存。", + "processFailed": "无法处理文件。", + "phase.prepare": "正在准备处理", + "phase.runtime": "正在加载处理程序", + "phase.metadata": "正在读取 Revit 元数据", + "phase.profile": "正在加载目标版本配置文件", + "phase.plan": "正在比较源版本和目标版本的结构", + "phase.rewrite": "正在将模型转换为目标版本", + "phase.write": "正在写入结果", + "phase.verify": "正在校验已保存的副本", + "phase.report": "正在生成版本降级报告", + "phase.decode": "正在读取并解析模型", + "phase.class-schema": "正在读取 Revit 类结构", + "phase.partitions": "正在读取模型分区", + "phase.element-records": "正在读取图元记录", + "phase.element-blocks": "正在解析图元数据", + "phase.parameter-stream": "正在读取参数", + "phase.recover-geometry": "正在恢复几何图形", + "phase.geometry-blocks": "正在读取几何块", + "phase.element-properties": "正在收集图元属性", + "phase.build-model": "正在组装模型", + "phase.finalize-model": "正在解析模型关联", + "phase.complete": "正在准备导出几何图形", + "phase.meshes": "正在生成网格", + "phase.encode": "正在生成导出文件", + "phase.download": "正在准备下载", + "unit.streams": "流", + "unit.blocks": "块", + "unit.passes": "轮次", + "unit.records": "记录", + "unit.elements": "图元", + "format.ifcParameters": "包含 Revit 参数的 IFC", + "format.compact": "精简 JSON", + "format.full": "完整 JSON", + "format.html": "独立 3D 查看器", + "format.htmlLegacy": "旧版 Navisworks HTML", + "format.nwc": "Navisworks 缓存", + "format.pdfPlan": "平面图 PDF", + "format.pdf": "图纸 PDF", + "format.pdfViews": "所有视图 PDF", + "format.sheets": "图纸列表", + "format.json": "属性和模型树 JSON", + "format.viewpointsBcf": "BCF 2.1 视点", + "format.viewpointsXml": "Navisworks 视点 XML", + "format.sets": "Navisworks 集 XML", + "format.grids": "轴网 XML", + "format.clashBcf": "BCF 2.1 碰撞", + "format.clashXml": "Navisworks 碰撞 XML", + "format.clashHtml": "碰撞报告 HTML", + "view.nwcContainer": "正在读取 NWC 容器", + "view.metadata": "正在读取 RVT 元数据", + "view.partitions": "正在解压 RVT 流 · {completed}/{total}", + "view.records": "正在读取图元记录 · {completed}/{total} 块", + "view.geometry": "几何图形 · {completed}/{total} 块", + "view.blocks": "正在解析模型块 · {completed}/{total} 轮", + "view.paramCount": "正在读取参数 · {completed}/{total} MiB", + "view.decodeFound": "正在解析找回的块", + "view.wallGeometry": "正在恢复墙体几何图形", + "view.decodeGeometry": "正在解析几何块", + "view.seekGeometry": "正在查找其他几何块", + "view.properties": "正在匹配名称和属性 · {completed}/{total} 块", + "view.buildModel": "正在组装 Revit 模型 · {completed}/{total} 条记录", + "view.linkTypes": "正在连接图元和类型", + "view.modelValues": "正在恢复模型数值", + "view.derivedProperties": "正在计算派生属性", + "view.phasesLevels": "正在匹配阶段和标高", + "view.systemNames": "正在解析名称和系统数据", + "view.resolveRefs": "正在解析图元引用", + "view.unitsCoordinates": "正在解析单位和坐标", + "view.prepareScene": "正在准备模型以生成 3D 场景", + "view.rvtScene": "正在构建 RVT 场景 · {completed}/{total} 个图元", + "view.nwcGeometry": "正在解析 NWC 结构和几何图形", + "view.nwcProperties": "正在读取 NWC 属性和视图", + "view.nwcScene": "正在构建 NWC 3D 场景", + "view.check": "正在检查文件", + "view.checkBytes": "正在检查文件 · 已读取 {completed} MiB", + "view.prepare": "正在准备查看器", + "view.preparePages": "正在准备分页 · {completed} 个三角形", + "view.openPages": "正在打开查看器 · {completed} 页", + "view.pageTriangles": "正在生成分页 · {completed}/{total} 个三角形", + "view.pageOverview": "正在生成概览 · 层级 {level} · {completed}/{total} 页", + "view.pageProperties": "正在准备图元属性 · {completed}/{total}", + "view.readErrors": "读取时发生错误,可能缺少一些图元。", + "view.readWarnings": "读取时出现警告,场景可能不完整。", + "view.failed": "无法打开模型。{detail}", + "view.canceled": "已取消打开模型。", + "view.pageFailed": "无法准备查看器页面。", + "view.storage": "模型临时数据的存储空间不足。请释放磁盘空间后重试。", + "view.memory": "处理模型时浏览器内存不足。", + "view.noGeometry": "文件中没有可显示的几何图形。", + "view.badTriangles": "分页中的三角形数量与引擎结果不符。", + "view.pageStorage": "模型临时分页的存储空间不足。", + }, + 'zh-Hant': { + ...formatNames, + "phase.r22-layout": "正在正規化 Revit 2022 結構", + "phase.quantities": "正在計算工程量", + "phase.wide-model": "正在讀取使用寬位識別碼的模型", + "view.profileMissing": "此組建不包含選取的記憶體設定。", + "view.scratchFailed": "無法存取模型暫存資料。", + "view.rangeRead": "無法讀取所要求的檔案範圍。", + "view.outOfRange": "所要求的資料超出檔案結尾。", + "siteTitle": "IOExtend — BIM 工具", + "language": "語言", + "auto": "自動", + "navigation": "BIM 工具", + "view": "檢視器", + "export": "匯出", + "downgrade": "Revit 版本", + "openingProgress": "模型開啟進度估算", + "cancel": "取消", + "drop": "拖放模型", + "supported": "支援的格式", + "chooseFile": "選擇檔案", + "privacy": "檔案在您的裝置上處理。", + "replaceModel": "開啟其他模型", + "viewerTitle": "3D 模型檢視器", + "sourceFile": "來源檔案", + "operationPrivacy": "瀏覽器會在這部裝置上處理檔案。", + "exportFormats": "匯出格式", + "selectMain": "選取主要格式", + "formatsEmpty": "選擇來源檔案後即可查看可用格式。", + "optionalFormats": "其他模型資料", + "optionalHint": "某些格式要求來源模型包含對應資料。", + "targetVersion": "目標 Revit 版本", + "downgradeNote": "實驗功能。較新版本特有的部分資料可能無法在副本中使用。", + "operationProgress": "處理進度", + "results": "結果", + "exportTitle": "匯出模型", + "exportDescription": "選擇一種或多種格式儲存模型。", + "exportAction": "匯出", + "downgradeTitle": "降低 Revit 版本", + "downgradeDescription": "建立適用於較早 Revit 版本的模型副本。", + "downgradeAction": "建立副本", + "save": "下載", + "diagnostics": "處理詳情", + "saveReport": "下載報告", + "dropHere": "將模型拖到這裡", + "chooseAnother": "選擇其他檔案", + "chooseVersion": "選擇版本", + "versionError": "無法辨識版本。請檢查 RVT 或 RFA 檔案是否能在 Revit 中開啟。", + "versionProbe": "正在從中繼資料偵測 Revit 版本…", + "detectedVersion": "來源檔案 · Revit {year}。", + "noEarlierVersion": "來源檔案 · Revit {year}。此檔案沒有可用的較早版本。", + "chooseSourceRvt": "選擇來源 RVT 或 RFA 檔案。", + "emptyFile": "檔案不能為空。", + "badFormat": "選擇支援的檔案格式。", + "workerFailed": "無法開始處理。", + "workerResult": "無法接收結果。", + "revitCopy": "Revit 副本", + "done": "完成,可下載結果檔案。", + "partlyDone": "已完成 {done}/{total} 項。詳情見下方。", + "failed": "處理失敗。詳情見下方。", + "operationCanceled": "處理已取消。", + "oneFile": "請拖放單一來源檔案。", + "elapsed": "已用時 {elapsed}", + "operationTime": "已用時 {elapsed} · 本階段 {stageTime}", + "count": "{completed}/{total}", + "stagePercent": "階段進度 {percent}% · {count}", + "step": "第 {step}/{total} 階段", + "readBytes": "來源檔案讀取量(含重複讀取){size}", + "writtenBytes": "已寫入 {size}", + "batchCount": "已處理 {done}/{total} 種格式", + "chooseRvtNwc": "選擇 RVT 或 NWC 檔案。", + "loadKernel": "正在載入模型引擎…", + "view.fallback": "正在以單執行緒模式重新開啟", + "oneViewerFile": "請拖放單一 RVT 或 NWC 檔案。", + "sourceReadFailed": "無法讀取來源檔案。", + "invalidOperation": "請檢查來源檔案及選取的格式。", + "invalidTarget": "此檔案無法使用目標版本。", + "profileFailed": "無法載入 Revit {year} 設定檔。", + "missingOutput": "引擎未產生輸出檔案。", + "emptyOutput": "引擎產生了空的輸出檔案。", + "operationMemory": "引擎用盡了 WebAssembly 記憶體。", + "processFailed": "無法處理檔案。", + "phase.prepare": "正在準備處理", + "phase.runtime": "正在載入處理程式", + "phase.metadata": "正在讀取 Revit 中繼資料", + "phase.profile": "正在載入目標版本設定檔", + "phase.plan": "正在比較來源版本與目標版本的結構", + "phase.rewrite": "正在將模型轉換為目標版本", + "phase.write": "正在寫入結果", + "phase.verify": "正在驗證已儲存的副本", + "phase.report": "正在產生版本降級報告", + "phase.decode": "正在讀取並解析模型", + "phase.class-schema": "正在讀取 Revit 類別結構", + "phase.partitions": "正在讀取模型分割區", + "phase.element-records": "正在讀取圖元記錄", + "phase.element-blocks": "正在解析圖元資料", + "phase.parameter-stream": "正在讀取參數", + "phase.recover-geometry": "正在復原幾何圖形", + "phase.geometry-blocks": "正在讀取幾何區塊", + "phase.element-properties": "正在收集圖元屬性", + "phase.build-model": "正在組裝模型", + "phase.finalize-model": "正在解析模型關聯", + "phase.complete": "正在準備匯出幾何圖形", + "phase.meshes": "正在產生網格", + "phase.encode": "正在產生匯出檔案", + "phase.download": "正在準備下載", + "unit.streams": "串流", + "unit.blocks": "區塊", + "unit.passes": "輪次", + "unit.records": "記錄", + "unit.elements": "圖元", + "format.ifcParameters": "包含 Revit 參數的 IFC", + "format.compact": "精簡 JSON", + "format.full": "完整 JSON", + "format.html": "獨立 3D 檢視器", + "format.htmlLegacy": "舊版 Navisworks HTML", + "format.nwc": "Navisworks 快取", + "format.pdfPlan": "平面圖 PDF", + "format.pdf": "圖紙 PDF", + "format.pdfViews": "所有視圖 PDF", + "format.sheets": "圖紙清單", + "format.json": "屬性與模型樹 JSON", + "format.viewpointsBcf": "BCF 2.1 視點", + "format.viewpointsXml": "Navisworks 視點 XML", + "format.sets": "Navisworks 集合 XML", + "format.grids": "軸網 XML", + "format.clashBcf": "BCF 2.1 碰撞", + "format.clashXml": "Navisworks 碰撞 XML", + "format.clashHtml": "碰撞報告 HTML", + "view.nwcContainer": "正在讀取 NWC 容器", + "view.metadata": "正在讀取 RVT 中繼資料", + "view.partitions": "正在解壓縮 RVT 串流 · {completed}/{total}", + "view.records": "正在讀取圖元記錄 · {completed}/{total} 區塊", + "view.geometry": "幾何圖形 · {completed}/{total} 區塊", + "view.blocks": "正在解析模型區塊 · {completed}/{total} 輪", + "view.paramCount": "正在讀取參數 · {completed}/{total} MiB", + "view.decodeFound": "正在解析找回的區塊", + "view.wallGeometry": "正在復原牆體幾何圖形", + "view.decodeGeometry": "正在解析幾何區塊", + "view.seekGeometry": "正在尋找其他幾何區塊", + "view.properties": "正在比對名稱和屬性 · {completed}/{total} 區塊", + "view.buildModel": "正在組裝 Revit 模型 · {completed}/{total} 筆記錄", + "view.linkTypes": "正在連結圖元和類型", + "view.modelValues": "正在復原模型數值", + "view.derivedProperties": "正在計算衍生屬性", + "view.phasesLevels": "正在比對階段和樓層", + "view.systemNames": "正在解析名稱和系統資料", + "view.resolveRefs": "正在解析圖元參照", + "view.unitsCoordinates": "正在解析單位和座標", + "view.prepareScene": "正在準備模型以建立 3D 場景", + "view.rvtScene": "正在建立 RVT 場景 · {completed}/{total} 個圖元", + "view.nwcGeometry": "正在解析 NWC 結構與幾何圖形", + "view.nwcProperties": "正在讀取 NWC 屬性與視圖", + "view.nwcScene": "正在建立 NWC 3D 場景", + "view.check": "正在檢查檔案", + "view.checkBytes": "正在檢查檔案 · 已讀取 {completed} MiB", + "view.prepare": "正在準備檢視器", + "view.preparePages": "正在準備分頁 · {completed} 個三角形", + "view.openPages": "正在開啟檢視器 · {completed} 頁", + "view.pageTriangles": "正在建立分頁 · {completed}/{total} 個三角形", + "view.pageOverview": "正在建立概覽 · 層級 {level} · {completed}/{total} 頁", + "view.pageProperties": "正在準備圖元屬性 · {completed}/{total}", + "view.readErrors": "讀取時發生錯誤,可能缺少部分圖元。", + "view.readWarnings": "讀取時出現警告,場景可能不完整。", + "view.failed": "無法開啟模型。{detail}", + "view.canceled": "已取消開啟模型。", + "view.pageFailed": "無法準備檢視器頁面。", + "view.storage": "模型暫存資料的儲存空間不足。請釋出磁碟空間後再試一次。", + "view.memory": "處理模型時瀏覽器記憶體不足。", + "view.noGeometry": "檔案中沒有可顯示的幾何圖形。", + "view.badTriangles": "分頁中的三角形數量與引擎結果不符。", + "view.pageStorage": "模型暫存分頁的儲存空間不足。", + }, +}; diff --git a/site/wwwroot/viewer-theme.js b/site/wwwroot/viewer-theme.js new file mode 100644 index 0000000..26a7096 --- /dev/null +++ b/site/wwwroot/viewer-theme.js @@ -0,0 +1,17 @@ +export const viewerTheme = ` + :root { + --panel: #191e27f5; + --border: #3e4a5d; + --button: #242e3c; + --button-hover: #33465b; + --accent: #146b88; + --accent-text: #a5f3fc; + --text: #edf3fa; + --text-dim: #aebaca; + } + .ioviewer-floating { border-radius: 4px; } + .ioviewer-rail-button, .ioviewer-tool { border-radius: 3px; } + .ioviewer-rail-button.active, .ioviewer-tool.active { + box-shadow: inset 0 -2px #08465b; + } +`; diff --git a/tools/NativeHtmlExport/NativeHtmlExport.csproj b/tools/NativeHtmlExport/NativeHtmlExport.csproj new file mode 100644 index 0000000..9c04382 --- /dev/null +++ b/tools/NativeHtmlExport/NativeHtmlExport.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + enable + true + + + + + + diff --git a/tools/NativeHtmlExport/Program.cs b/tools/NativeHtmlExport/Program.cs new file mode 100644 index 0000000..5cba714 --- /dev/null +++ b/tools/NativeHtmlExport/Program.cs @@ -0,0 +1,47 @@ +using System.Diagnostics; +using System.Text.Json; +using IOScene; +using IOViewer.Exporters; +using RvtIO.Scene; + +if (args.Length != 2) +{ + Console.Error.WriteLine("Usage: NativeHtmlExport "); + return 2; +} +if (File.Exists(args[1])) +{ + Console.Error.WriteLine($"Output already exists: {args[1]}"); + return 1; +} + +var elapsed = Stopwatch.StartNew(); +var result = RvtSceneReader.Read(args[0]); +var readMs = elapsed.ElapsedMilliseconds; +var errors = result.Diagnostics.Where(d => d.Severity == SceneSeverity.Error).ToArray(); +if (errors.Length > 0) +{ + foreach (var error in errors) + Console.Error.WriteLine(error); + return 1; +} + +var output = new FileStream(args[1], FileMode.CreateNew, FileAccess.Write, FileShare.None); +try +{ + using (output) + HtmlViewerExporter.Export(result.Document, output); +} +catch +{ + File.Delete(args[1]); + throw; +} + +var exportMs = elapsed.ElapsedMilliseconds; +Console.WriteLine(JsonSerializer.Serialize(new +{ + readMs, exportMs, elements = result.Document.Elements.Count, + instances = result.Document.Instances.Count, geometries = result.Document.Geometries.Count, +})); +return 0;