FieldView — просмотр полей (Qt 6, вывод через Qt RHI)

Назначение и место в пакете

FieldView (fieldview.exe) показывает поле, посчитанное счётными ядрами PlanarRT_H и PlanarRT_X, по тактам расчёта: рельефом (3D) или цветной картой (2D), вместе с топологией модели (диэлектрик, металл, магнитные стенки, поглотитель, входы, плазма), слоем ε и — для X-ядра — сетками плазмы N, Y, B. Программа ничего не считает физически: она читает файлы, которые пишет ядро, и рисует их.

Место в пакете — последнее звено цепочки задание → препроцессор → ядро → файлы → вьюверы:

 задание .tpl ── ядро H/X ──┬── <имя>.ex / .ey / .hz …  кадры поля (FIELDS)
                            ├── <имя>.tt                топология и сетка ε (TOPOLOGY)
                            └── <ДН>.AMP / .FAZ         амплитуда и фаза (FIELD_DISTRIBUTION)
                                        │
                                        ▼
                                   FieldView  ── картинки, печать, GIF, серия тактов .ex.frames

FieldView может работать вместе с идущим расчётом: ядро после каждого кадра ждёт, пока FieldView его прочитает, а FieldView показывает каждый новый кадр сразу и запоминает такты для последующего проигрывания (синхронизация).

Модуль — каталог src/fieldview. Это самостоятельная программа на чистом Qt 6 (без слоя совместимости MFC); логика чтения файлов, окна данных, пределов и топологии перенесена из прежнего FieldView 4.1 (MFC + OpenGL 1.x) без изменения смысла, а вывод переписан на Qt RHI: на Windows — Direct3D 11, при его отсутствии — программный Direct3D 11 (WARP) или OpenGL. Сборка не под Windows (прежний вывод OpenGL 1.x) описана отдельно: FieldView для Linux.

Что видит пользователь — в руководстве пользователя (FieldView); здесь — устройство кода.

Состав модуля

Файл Роль
src/main.cpp точка входа: оформление, выбор графического интерфейса, главное окно, файлы из командной строки
src/core/fieldfile.h/.cpp файл поля: заголовок, значения, размах; серия тактов FieldSeries (ниже)
src/core/textscan.h LineReader, scanDouble, scanInt, scanWordDouble — разбор строк как fgets/sscanf, без локали
src/core/topology.h/.cpp файл топологии TopologyFile, полосы границ BlockBoundary, отбор видимого (ниже)
src/core/palette.h/.cpp шкалы «Волна», «Свечение», 20 цветов; цвета материалов (ниже)
src/core/gifwriter.h/.cpp кодировщик анимированного GIF (ниже)
src/app/fielddocument.h/.cpp FieldDocument — документ: такты, история, кэш, топология, синхронизация с ядром (ниже)
src/app/fieldpane.h/.cpp FieldPane — окно документа: окно данных, пределы Z, слои, геометрия, надписи, команды (ниже)
src/app/viewsettings.h/.cpp ViewSettings — настройки вида по слоям, чтение и запись (ниже)
src/app/startup.h/.cpp выбор графического интерфейса, имена приложения, место настроек (ниже)
src/app/theme.h/.cpp цвета, шрифты, таблица стилей (ниже)
src/render/scenedata.h SceneData, GridLayer, SceneLabel, Sprite — что рисовать (ниже)
src/render/fieldrhiview.h/.cpp FieldRhiView (QRhiWidget) — вывод сцены, камера, мышь (ниже)
src/ui/mainwindow.h/.cpp MainWindow — окна документов (MDI), меню, панели, строка состояния, печать, экспорт (ниже)
src/ui/parametersdialog.h/.cpp окно «Параметры вида» (ниже)
src/ui/autocolordialog.h/.cpp окно «Цвета уровней» (ниже)
src/ui/icons.h/.cpp значки команд и программы
shaders/*.vert, shaders/*.frag шейдеры GLSL 440 (ниже)
resources/ встроенные шрифты Inter и JetBrains Mono (SIL OFL 1.1), значки оформления
tools/fieldview_shot.cpp программа самопроверки — снимок окна в PNG (ниже)

Сборка (CMakeLists.txt): статическая библиотека fieldview_app (весь код, кроме точек входа), программы fieldview и fieldview_shot. Шейдеры собирает qt_add_shaders (инструмент qsb) в ресурсы :/fieldview/shaders/*.qsb сразу для HLSL 5.0 (Direct3D), GLSL 300 es / 330 (OpenGL), SPIR-V (Vulkan) и MSL (Metal). Значки панели берутся из resources/icons/toolbar/fieldview/ пакета (если их нет — рисуются простые значки), значок программы — из resources/icons/app/.

Архитектура

Данные идут в одну сторону — от файла к экрану:

 файлы ядра          FieldDocument            FieldPane                 FieldRhiView         MainWindow
 ───────────         ──────────────           ──────────                ────────────         ──────────
 .ex / .frames ──▶  такты (память/диск) ──▶  окно данных, пределы Z ──▶ буферы видеокарты ──▶ подокно MDI,
 .tt           ──▶  топология, границы  ──▶  слои, геометрия, надписи  шейдеры, кадр         меню, панели,
                    таймер 50 мс, история     SceneData + Sprite[5]     мышь → сигналы        строка состояния
Класс Создаёт Владеет Живёт
MainWindow main() область MDI, команды, принтер всё время работы
FieldDocument MainWindow::openFile() такты, кэш, топологию, таймер, фоновый поток пока открыто хоть одно окно этого файла (std::shared_ptr)
FieldPane MainWindow::openFile(), «Новое окно» SceneData, картинки Sprite, копию ViewSettings, вид до закрытия подокна (WA_DeleteOnClose)
FieldRhiView FieldPane ресурсы видеокарты как окно документа

Один файл открывается одним документом; команда «Новое окно» создаёт второе окно того же документа со своими настройками вида. Повторное открытие того же файла активирует уже открытое окно.

Потоки. Всё работает в потоке интерфейса, кроме одного фонового потока документа: для серии тактов он один раз читает все кадры и считает их размах (для шкалы «по всем тактам»). Поток получает копию оглавления серии и общий флаг отмены; результат возвращается в поток интерфейса через очередь событий Qt и применяется, только если документ ещё жив. При открытии другого файла и при уничтожении документа поток отменяется и документ ждёт его завершения.

Перестройка сцены. Окно документа пересчитывает только то, что изменилось, а вид перезаливает в видеопамять только данные с изменившимся номером версии:

Событие Что пересчитывается
новый такт (проигрывание, кадр от ядра) значения поля; пределы Z; если пределы изменились или включено «значение в точке» — геометрия и шкала
поворот, масштаб колесом, сдвиг мышью только камера и картинка надписей
любая команда вида, окно «Параметры» окно данных, значения, слой ε, геометрия, сведения, шкалы
размер окна сведения, шкалы, надписи

Файл поля

Кадры поля ядро пишет функцией PutField (см. вывод H-ядра), если в секции #OUTPUT задания есть FIELDS. Имя файла — базовое имя из FILE с расширением .ex (а также .ey, .hz, .em; .tf — имя старых сборок). Файлы .AMP/.FAZ (амплитуда и фаза поля на частоте, FIELD_DISTRIBUTION) имеют тот же формат (TMCIndan). FieldView разбирает все эти файлы одинаково — как одно скалярное значение в каждом узле сетки. Что это за величина: у H-ядра — напряжение узла U, пропорциональное Ez (поля H-ядра); у X-ядра — напряжение узла, равное компоненте Hz (поля X-ядра). Узлы и их нумерация — сетка метода.

Формат (общий список форматов — форматы файлов):

#TMC_GraphicsOutputFieldFile FormVer2.0 2000 CRLF
#TMCGROFLD_nT <int> CRLF               номер такта
#TMCGROFLD_Time <double> CRLF          модельное время, с
#TMCGROFLD_Delta <double> CRLF         шаг сетки Δ, м
#TMCGROFLD_Xmin <double> CRLF          координата узла (0, 0), м
#TMCGROFLD_Ymin <double> CRLF
#TMCGROFLD_Accuracy <4|8> CRLF         байт на значение: float или double
#TMCGROFLD_LongUnit <имя> <м> CRLF     единица длины для подписей
#TMCGROFLD_TimeUnit <имя> <с> CRLF     единица времени для подписей
#TMCGROFLD_nX <int> CRLF
#TMCGROFLD_nY <int>
затем nY раз:  CRLF + nX двоичных значений (порядок байт машины)

Строки заголовка сверяются по началу и строго по порядку; числа читаются как sscanf("%d")/sscanf("%lg"), но по правилам локали «C» (textscan.h) — системная локаль с запятой их не ломает. Если число не разобрано, остаётся значение по умолчанию (как у sscanf). Затем проверяются условия Windows-версии: nX ≥ 2, nY ≥ 2, Accuracy = 4 или 8. Объём значений:

Nбайт=nYnXa+2(nY−1),(1)

где a — Accuracy: пара CR LF стоит перед каждой строкой значений, первая из них завершает строку nY. Строки идут снизу вверх (строка i — узлы с y=ymin+iΔ), в строке — слева направо; узел (j,i) — значение номер inX+j.

Декодирование (decodeFieldValues):

  1. Если данных меньше Nбайт — ошибка «when read data file».
  2. На местах разделителей проверяются байты CR LF. Если их нет — это текстовый вывод поля (ядро пишет числа текстом, если задан формат вывода поля) или повреждённый файл: ошибка «no CR LF after data row …». Текстовые файлы FieldView не читает.
  3. Каждое значение переводится во float (так оно уходит в видеопамять); по желанию вызывающего сохраняется и копия в исходной точности (double) — для «значения в точке».
  4. Размах кадра — минимум, максимум и максимум модуля — считается по исходным числам и только по конечным: nan и inf пересчитываются в nonFinite и в шкалу не входят (иначе один nan делает шкалу и рельеф пустыми). Сами значения в кадре остаются как есть.

Тексты ошибок совпадают с FieldView 4.1: «bad data file», «bad data file nX = … < 2», «abnormal accuracy […], but must be 4 or 8», «can't open data file {…}».

Серия тактов .ex.frames

Серия — не формат ядра: это подряд записанные кадры того же формата, каждый байт в байт как у ядра. Её записывает сам FieldView (команда «Сохранить такты серией…»), один файл .ex — серия из одного кадра. FieldSeries::open один раз проходит файл:

  1. в окне 4 КБ от текущего места проверяет признак первой строки и разбирает заголовок;
  2. запоминает смещения начала кадра и начала значений, пропускает значения по размеру из заголовка;
  3. после кадра допускает до двух байт CR/LF (одиночный .ex может ими кончаться).

Хвост, не похожий на кадр, и недописанный последний кадр (запись ещё идёт) отбрасываются; кадры с сеткой, отличной от первого, пропускаются. Значения читаются по требованию (readFrame), каждый раз заново открывая файл, — поэтому копию оглавления можно читать из фонового потока.

При записи серии (FieldDocument::saveSeries) заголовок каждого кадра пишется так же, как у ядра (числа — 6 значащих цифр, %lg), значения — во float (Accuracy 4); запись атомарная (QSaveFile).

Файл топологии .tt

Ядро пишет его по строке TOPOLOGY; секции #OUTPUT (см. вывод H-ядра). FieldView ищет .tt рядом с файлом поля и с тем же именем: путь без последнего расширения (у серии — без .frames и расширения кадра) плюс .tt в любом регистре. Если открыть сам .tt, документ берёт файл поля с тем же именем (.ex, .ey, .hz, .em, .tf, их серии, .AMP, .FAZ — первый найденный).

#TMC_TopologyOutputFile FormVer2.0 2000
#BlockListBegin
<вид блока>                    "RECT_STAT ", "INPUT_X ", "CIRCLE_STAT_N " …
<выражение ε или тип>          "METAL" …
<строка 3> <строка 4> <строка 5>
x0 xMax xMin y0 yMax yMin nBlock nMemory nType nXY
x y                            nXY строк — вершины многоугольника
… (следующие блоки)
#BlockListEnd
#TMCGROFLD_nT, _Time, _Delta, _Xmin, _Ymin, _nX, _nY     (без Accuracy)
сетка ε:  nY раз — nX значений double + 2 байта
у X-ядра далее ещё три сетки того же вида: N, Y, B

Запись с nBlock = 0 блоком не считается. Если после сетки ε данных на три сетки нет, плазмы нет (hasPlasma() = false). Слой ε показывает выбранную сетку: 0 — ε, 1 — N (м⁻³), 2 — Y, 3 — B (Тл) (единицы плазмы); без плазмы любая выбранная величина показывается как ε, и подписи тоже «ε».

Проверка соответствия (FieldDocument::topologyMismatch). Топология используется (слой ε и контуры блоков), только если её сетка совпадает с сеткой файла поля: равны nX, nY, а Δ, xmin, ymin совпадают с допуском 10−6max(|Δполя|,|Δtt|) — оба заголовка ядро пишет одним форматом, допуск покрывает только округление записи. Иначе в сведениях о такте появляется причина («файл топологии … от другого расчёта: сетка … вместо …»), а поле рисуется без топологии. Файл топологии перечитывается при открытии, при двойном щелчке и при каждом кадре от ядра, если изменились время файла или шаг сетки поля.

Границы блоков

Из списка блоков buildBoundaries строит для каждого блока полосы границы — четырёхугольники шириной в шаг сетки Δ вдоль контура (в 3D — призмы), размерные линии и привязку. Логика и порядок проверок — как в CTmcBoundaryTpl FieldView 4.1:

Вид блока Полосы Размеры
RECT_STAT, RECT_MOVE, FILE (как ε) четыре стороны прямоугольника [xmin,xmax]×[ymin,ymax], каждая расширена на ±Δ/2 высота (по левой стороне), ширина (по верхней)
POLYGON_STAT, POLYGON_MOVE по полосе на сторону; полоса вытянута вдоль большей проекции стороны; замыкающая сторона — только у блока ε длины всех сторон, включая замыкающую
CIRCLE_STAT, CIRCLE_MOVE внешняя дуга; при внутреннем радиусе >Δ — два радиальных отрезка и внутренняя дуга внешний радиус; внутренний (если >Δ)
INPUT_X полоса вдоль оси Y: x∈[−Δ/2,Δ/2], y∈[xmin,xmax] записи апертура
INPUT_Y полоса вдоль оси X: x∈[xmin,xmax], y∈[−Δ/2,Δ/2] апертура
RECT_STAT_N/_B/_Y, POLYGON_STAT_N/_B/_Y, CIRCLE_STAT_N/_B/_Y, FILE_N/_B/_Y контуры плазмы (тип «плазма», многоугольник всегда замкнут; FILE_* — прямоугольник) — нет в FieldView 4.1 нет

У круга поля записи означают: xMin/xMax — внутренний и внешний радиусы, yMin/yMax — начальный и конечный углы φ0, φ1 (рад). Дуга радиуса R делится на

n=max(int(R(φ1−φ0)Δ+0,5)+1, 2)(2)

точек и n−1 отрезков, каждый — прямоугольник по координатам концов. (В FieldView 4.1 рисовалось n отрезков, и дуга выходила за сектор на один отрезок.) Затем все полосы и размеры сдвигаются на привязку блока (x0,y0); привязка сама рисуется двумя размерными линиями от начала координат. Входы нумеруются по порядку блоков: «Inp 1», «Inp 2» …; надпись ставится в центре первой полосы входа.

Отбор видимого (visibleTopology, visibleSizes): область показа расширяется на 1,1Δ; полоса берётся, если хотя бы одна её вершина внутри; размерная линия — если внутри оба конца и длина больше 2Δ. Типы фильтруются флажками «Границы» (ε, металл, магнитная стенка, поглотитель, входы, плазма).

Документ и синхронизация с ядром

FieldDocument — открытый файл со всем, что к нему прилагается. Такты документа — список Slot: заголовок, где лежат значения и известен ли размах.

Источник Где значения Сколько тактов
одиночный файл (.ex, .tf, .AMP …) в памяти (Slot::mem) один; при слежении с запоминанием — история: каждый новый кадр дописывается
серия .frames на диске; прочитанные — в кэше все кадры серии

История тактов. Кадр от ядра (или перечитанный файл) с той же сеткой и другим номером такта или временем дописывается; с тем же тактом — заменяет последний; с другой сеткой — история сбрасывается. Без запоминания остаётся один такт. Объём истории ограничен 1 ГБ (4 байта на узел такта); сверх него отбрасываются самые старые такты, последний остаётся всегда. «Забыть такты» оставляет только последний.

Кэш серии. Такт серии читается при первом обращении и кладётся в кэш не больше 256 МБ; при переполнении вытесняются такты, которые дольше всего не запрашивались.

Точность. Значения тактов хранятся во float; значения в исходной точности файла есть только у последнего прочитанного кадра одиночного файла — по ним «значение в точке» показывает число без потери точности.

Протокол синхронизации

Протокол — тот же, что у FieldView 4.1 и ядра (CTmcRTHRectNode::IsFieldFileRead), через атрибут «архивный» (ARCHIVE) файла поля:

 ядро                                              FieldView (таймер 50 мс)
 ────                                              ────────────────────────
 ждёт, пока у файла не станет ARCHIVE  ◀───────┐
   (до 500 × 50 мс = 25 с на кадр)             │
 fopen("wb") — при отказе повтор через 10 мс   │   бит ARCHIVE снят?  нет → ждать
 пишет кадр, снимает ARCHIVE (NORMAL)  ───────▶│   да → читать файл целиком без права
                                               │        записи для других (FILE_SHARE_READ)
                                               └── ставит ARCHIVE
  • Новым кадром считается снятый бит ARCHIVE (проверяется только этот бит: у сжатых файлов и файлов облачных папок есть лишние биты атрибутов, и сравнение атрибутов целиком перечитывало бы кадр каждые 50 мс).
  • Пока FieldView читает, файл открыт без FILE_SHARE_WRITE: fopen ядра получает отказ и повторяет попытку — FieldView всегда читает законченный кадр.
  • После ошибки чтения пропускаются 20 опросов (~1 с), бит ARCHIVE ставится в любом случае.
  • При открытии одиночного файла документ ставит ARCHIVE, при уничтожении документа (если слежение включено) — возвращает NORMAL, как FieldView 4.1.
  • «Следить за расчётом» выключает таймер — тогда FieldView не ставит ARCHIVE, и ядро после 25 с ожидания перестаёт ждать (до следующего чтения).
  • Серию .frames FieldView отслеживает по размеру и времени изменения файла: новые кадры добавляются в конец списка.
  • На системах без атрибута ARCHIVE одиночный файл отслеживается так же — по времени и размеру.

Файл читается целиком в память, поэтому одиночный файл поля больше 2 ГБ не читается (понятная ошибка с размером файла).

Окно документа

FieldPane переводит такт, топологию и настройки в SceneData (перенос PrepareData/PrepareTpl/PrepareBoundaryTpl FieldView 4.1) и выполняет команды вида. Картинки поверх сцены (Sprite): 0 — надписи, 1 — сведения о такте, 2 — шкала поля, 3 — шкала ε, 4 — сообщение посреди вида (файла ещё нет, ошибка чтения, ошибка окна данных, все слои выключены).

Окно данных

Окно данных — показываемая часть сетки, [xmin,xmax]×[ymin,ymax] в метрах от узла (0, 0). «Масштаб» (Zoom) в FieldView меняет именно его, а не камеру.

  1. «Вся область» по оси — окно от 0 до (n−1)Δ. Иначе края упорядочиваются и обрезаются по сетке; если левый край лежит дальше последнего узла (настройки от другого, большего файла), показывается весь файл.
  2. Края переводятся в номера узлов: j=⌊x/Δ+10−9⌋ (добавка защищает от x=kΔ, дающего при делении k−10−16), с ограничением сеткой. Меньше двух узлов по оси — ошибка «number of point along X axies < 2».
  3. Прореживание. Если узлов окна по стороне больше kMaxSceneSide = 4096 (буферы и индексы видеокарты 32-битные), показывается каждый k-й узел, k=⌈(n−1)/(4096−1)⌉; значения не усредняются. Сведения о такте сообщают об этом.
  4. Края привязываются к узлам: xmin=j0Δ, xmax=j1Δ — иначе после масштаба поле и топология расходились бы на долю ячейки.
  5. Пропорции: при «Пропорционально» меньшая сторона окна получает долю kx=(xmax−xmin)/(ymax−ymin) (или ky наоборот), иначе kx=ky=1.

Координаты сцены (как XtoGLWinCoord FieldView 4.1, но с центром в нуле):

X=2,5kx(x−xminxmax−xmin−12),Y=2,5ky(y−yminymax−ymin−12).(3)

Команды: «Увеличить» делает окно вокруг центра вдвое уже (не уже 2Δ), «Уменьшить» — вдвое шире (шире сетки — весь файл); стрелки сдвигают окно на Δ, а в режиме «значение в точке» — саму точку на узел.

Значение в точке (Field → Value, Shift + щелчок): точка привязывается к ближайшему узлу сцены (округление, не усечение), не крайнему; метка — ромб на четырёх соседних узлах и штрих над узлом. Число берётся из исходных значений, если они есть, иначе из float. Shift + щелчок находит точку плоскости z=0 под курсором (pickGround) и переводит её обратно в метры.

Пределы Z и выбор шкалы

Пределы [zmin,zmax] шкалы поля (updateFieldRange):

  1. Размах показанного: при всей сетке — размах кадра, иначе — по значениям окна данных (только конечные числа).
  2. Накопление (как dZmin/dZmax FieldView 4.1): по умолчанию пределы растут по всем показанным тактам; для всей сетки к ним добавляется размах уже прочитанных тактов документа (у серии — всех, посчитанных в фоне). Флажок «Пределы по текущему такту» берёт размах только текущего такта. Накопление сбрасывается при смене окна данных, режима модуля, автоматических пределов или шкалы, двойном щелчке, «Виде по умолчанию».
  3. Шкала «Авто»: «Свечение», если минимум ≥0, иначе «Волна». В режиме «Модуль» — «Свечение» (или «20 цветов», если она выбрана).
  4. Пределы при автоматическом режиме (g — «контраст», 1…100):
Случай zmin zmax
данных нет −1 1
поле всюду ноль (max|v|< FLT_MIN) −1 («Волна», «Модуль») или 0 1
«Модуль» или «Волна» −max|v|/g max|v|/g
«Свечение» min(0,vmin)/g vmax/g
«20 цветов» vmin/g vmax/g

Ручные пределы берутся как заданы (в режиме «Модуль» — симметрично по большему модулю). Вырожденный диапазон расширяется до z±max(10−6|z|,FLT\_MIN).

  1. Нормировка для шейдера: h=vk+off, где
k=2zmax−zmin,off=−2zminzmax−zmin−1,(4)

так что zmin↦h=−1, zmax↦h=1. Высота точки рельефа в сцене — h, умноженное на «высоту рельефа» (0,05…10).

Слой ε (N, Y, B) берёт пределы по значениям окна данных (без накопления по тактам); вырожденный диапазон расширяется на max(1,|z|)·10−6; шкала «Авто» у него — всегда «Свечение».

Уровни цвета (панель «Уровни цвета»): уровень i=0…19 начинается со значения zmin+i19(zmax−zmin) (в режиме модуля — i19zmax).

Цветовые шкалы

Шкала превращает число t∈[0,1] в цвет. Для поля t=(h+1)/2, в режиме модуля $t = \lvert h\rvert $; значения вне пределов получают крайний цвет.

Шкала Назначение Опорные цвета (снизу вверх)
«Волна» знакопеременное поле: −max — светло-фиолетовый, 0 — почти чёрный, +max — светлый циан #f1e8ff #d7bdff #9b6cf0 #4a3590 #131a28 #0f4f45 #1a9a83 #34e3c4 #c4f7ee
«Свечение» неотрицательные величины: модуль поля, амплитуда, ε, N, Y, B #0a0e16 #1b2550 #3a3384 #7a55d6 #b07cff #34e3c4 #ffcf5c #fff3d6
«20 цветов уровней» пользовательская, как в FieldView 4.1 20 цветов из настроек

Опорные цвета «Волны» и «Свечения» стоят равномерно; между соседними цвет интерполируется линейно в пространстве OKLab — светлота растёт монотонно, и картинка читается даже в оттенках серого:

p=t(n−1),i=min(⌊p⌋,n−2),f=p−i,Lab(t)=(1−f)Lab(ci)+fLab(ci+1).(5)

Перевод sRGB → OKLab: каналы линеаризуются (c≤0,04045: c/12,92, иначе ((c+0,055)/1,055)2,4), умножаются на матрицу 3×3 в пространство LMS, из каждой компоненты берётся кубический корень, затем вторая матрица 3×3 даёт L,a,b. Обратный перевод — в обратном порядке, с обрезкой каналов до [0, 1]. Коэффициенты матриц — в palette.cpp.

«20 цветов» интерполируются линейно по каналам sRGB: p=19t, между цветами ⌊p⌋ и ⌊p⌋+1. Флажок «Плавная шкала» выключен — 20 ступеней: t→⌊19t⌋/19 (в шейдере).

Исходные цвета FieldView 4.1 (classicFieldColors): уровни i=0…6 — (100, 35i, 255−35i); 7…13 — (35(i−7), 255−35(i−7), 150); 14…17 — (255, min(255,83(i−14)), 100); 18 — жёлтый, 19 — белый. Для слоя ε (classicEpsColors): цвет 19−i — (max(0,255−10i), 255, min(255,10i)).

Для видеокарты шкала записывается текстурой 256×1 RGBA8 (scaleImage); точка x — это t=x/255. Шейдер берёт цвет в центре текселя: u=(255t+0,5)/256.

Цвета материалов топологии по умолчанию (defaultTopologyColor): ε — #b07cff, металл — #9fb0c8, магнитная стенка — #6c7d97, вход — #34e3c4, поглотитель — #3a4a6b, плазма — #ffcf5c. Заливка полупрозрачна по материалу (множители непрозрачности 0,30 / 0,92 / 0,85 / 0,95 / 0,35 / 0,30), чтобы поле под диэлектриком, плазмой и поглотителем было видно.

Сцена

SceneData — всё, что вид рисует за кадр; заполняет FieldPane, читает FieldRhiView.

  • Два слоя сетки (GridLayer): поле и слой ε. Слой — значения узлов окна данных (shared_ptr: при всей сетке — без копии, общая память с кадром), правило высоты (k, off), режим цвета, число ступеней, высота рельефа, непрозрачность, шкала, цвет каркаса. Сетка сцены: узел (j,i) — точка (x0+sxj/(nX−1), y0+syi/(nY−1)), где x0=−1,25kx, sx=2,5kx.
  • Цветная геометрия — треугольники и отрезки, по 7 чисел на вершину (x,y,z,r,g,b,a): полосы топологии (в 3D — призмы от −0,25 до 0,25, в 2D — на высоте 0,02, контуры на 0,03), размерные линии со стрелками, оси X, Y, Z, размеры окна, шкалы Z, метка «значения в точке».
  • Надписи (SceneLabel) — точка сцены, текст, цвет, выравнивание. Каждый раз при изменении камеры они проецируются в пиксели окна и рисуются QPainter в одну картинку с тёмной обводкой.
  • Картинки поверх сцены (Sprite) — готовые изображения в пикселях окна (до 8).
  • Габариты boundX, boundY, boundZ — для подбора расстояния камеры.

Каждая часть несёт номер версии; вид перезаливает в видеопамять только изменившееся.

Камера

Матрица «сцена → отсечение» (FieldRhiView::viewProjection):

  1. Перспектива с углом обзора 30° по вертикали (gluPerspective(30, …) FieldView 4.1).
  2. Расстояние камеры подбирается так, чтобы сцена при виде по умолчанию (поворот a=−20°, наклон θ=−55°) целиком помещалась в окне любой формы. С τ=tg15°, габаритами sx,sy,hz и отношением сторон окна A:
hx=|cosa|sx2+|sina|sy2,hy0=|sina|sx2+|cosa|sy2,hy=max(hy0, hy0|cosθ|+hz|sinθ|),(6)
d=1,2max(hxτA, hyτ)+0,3,dкам=max(0,05, d−tz).(7)
  1. Ближняя и дальняя плоскости — вокруг сферы радиуса r=0,5sx2+sy2+4hz2·zoom+0,6: max(0,01,(dкам−r)/2) и dкам+r+2.
  2. Вид: сдвиг (panxdτA+tx, panydτ+ty, −dкам), затем повороты вокруг X, Y, Z (порядок glRotatef FieldView 4.1) и масштаб zoom.

Перед выводом матрица умножается на clipSpaceCorrMatrix() интерфейса (у Direct3D и OpenGL разные соглашения по глубине и оси Y). Мышь: левая кнопка — поворот (0,4° на точку: вокруг Z по горизонтали, вокруг X по вертикали, X ограничен ±180°), правая или средняя — сдвиг, колесо — масштаб (1,0015Δ, Δ — угол колеса в 1/8°, масштаб 0,05…50), щелчок правой кнопкой — «Параметры», двойной щелчок — пределы Z заново и перечитать файл.

Вывод через Qt RHI

FieldRhiView — наследник QRhiWidget: встраивается как обычный виджет в окно MDI и умеет синхронно отдать кадр (grabFramebuffer) — на этом стоят печать, сохранение картинки, экспорт GIF и самопроверка.

Выбор графического интерфейса (chooseGraphicsApi, при запуске, для всех окон):

  1. Источник — переменная окружения FIELDVIEW_RHI или ключи --rhi d3d11|d3d12|opengl|vulkan (--rhi=…), --warp; распознанные ключи удаляются из списка файлов.
  2. opengl/gl и vulkan принимаются без проверки.
  3. d3d12 — если объект RHI с Direct3D 12 создаётся.
  4. Иначе (и если нет --warp) — Direct3D 11, если создаётся.
  5. Иначе — программный Direct3D 11 (WARP: нет видеокарты с Direct3D 11 — сервер, удалённый рабочий стол).
  6. Иначе — OpenGL.

Проверка — пробное создание и удаление объекта QRhi. Выбранный интерфейс и частота кадров показываются справа в строке состояния.

Ресурсы (buildPipelines, rebuildGrid):

Ресурс Когда создаётся Содержимое
координаты узлов (u, v) при смене размера сетки u=j/(nX−1), v=i/(nY−1), неизменяемый буфер
значения поля, значения ε при смене размера сетки; заливка — при смене такта float на узел
индексы треугольников при смене размера сетки два треугольника на ячейку: (ii,ii+1,ii+1+nX), (ii,ii+1+nX,ii+nX)
индексы каркаса при смене размера сетки вдоль линии — все узлы (линия идёт по рельефу); линии — через шаг: не больше ~120 по стороне поверх заливки, ~1000 без неё
текстуры шкал один раз; заливка — при смене шкалы 256×1 RGBA8
буферы цветной геометрии при росте объёма вершины по 7 float
текстуры картинок при смене размера картинки RGBA8, предумноженная альфа

Конвейеров пять: заливка сетки (треугольники, тест и запись глубины), каркас сетки (линии, тест глубины без записи), цветные треугольники, цветные линии, картинки (без глубины). Смешивание у всех — для предумноженной альфы: c=csrc+(1−αsrc)cdst. Сглаживание — 4 отсчёта на точку. Кадр (render): заливка изменившихся данных, затем поле, слой ε, цветные треугольники, цветные линии, картинки.

Шейдеры

Шейдеры написаны один раз на GLSL 440 (shaders/) и переводятся qsb для каждого интерфейса; загружаются из ресурсов :/fieldview/shaders/<имя>.qsb.

Шейдер Что делает
grid.vert Слой сетки. Вход — (u, v) узла и значение v. Считает h=vk+off; цвет t=(h+1)/2 или $\lvert h\rvert $, обрезанный до [0, 1]; при L ступенях — t=min(⌊t(L−1)⌋,L−1)/(L−1). Позиция: (x0+usx, y0+vsy, clamp(h,±1,0001)·m+zlift), где m — высота рельефа (0 в 2D). Передаёт t и позицию во фрагментный шейдер.
grid.frag Цвет — из текстуры шкалы в точке t или постоянный (каркас поверх заливки). При рельефе затеняет склоны: нормаль n — по производным позиции, яркость ×(1−0,35(1−|nz|)) — ровное поле не темнеет. Умножает на непрозрачность слоя и выдаёт предумноженный цвет.
color.vert Цветная геометрия: позиция × матрица, цвет вершины дальше.
color.frag Выдаёт цвет вершины с предумноженной альфой.
sprite.vert Картинка поверх сцены: координаты — пиксели окна, ортографическая матрица.
sprite.frag Цвет из текстуры картинки (уже с предумноженной альфой).

Буфер констант слоя сетки (GridUniforms, std140, 144 байта): mvp (матрица), rect (x0,y0,sx,sy), map (k, off, режим цвета, ступени), misc (высота рельефа, подъём, непрозрачность, «цвет по шкале»), color (цвет каркаса), extra (сила затенения склонов: 0,35 у заливки рельефа, иначе 0). Подъём: в 3D у каркаса — 0,004max(0,3,m) над рельефом, в 2D — zlift слоя (+0,01 у каркаса); слой ε в 2D лежит на 0,002 выше поля.

Анимация по времени и запись GIF

Такты. Окно документа показывает один такт; ползунок и команды «Пуск/пауза», «Предыдущий», «Следующий», «Первый», «Последний» переключают их. Проигрывание идёт по таймеру (Qt::PreciseTimer, интервал max(10,1000/fps) мс) по кругу. Если показан последний такт, окно следует за расчётом: новый кадр от ядра показывается сразу (если не идёт проигрывание). При проигрывании пересчитываются только значения и сведения о такте — геометрия и шкала, только если изменились пределы.

Экспорт (MainWindow::exportFrames): для каждого выбранного такта (с, по, каждый k-й) окно показывает такт, снимает кадр grabImage(), приводит его к заданной ширине и пишет кадром GIF или файлом <имя>_0001.png. Задержка кадра GIF — max(2,⌊100/fps⌋) сотых секунды. Проигрывание останавливается, потом восстанавливается показанный такт.

Кодировщик GIF (GifWriter, GIF89a, без сторонних библиотек):

  1. Заголовок: логический экран размера первого кадра, без общей палитры; блок NETSCAPE2.0 — повтор бесконечно.
  2. Кадр: цвета сводятся к ключам 5-6-5 бит, по гистограмме выбираются 256 самых частых; каждому ключу кадра — ближайший цвет палитры по расстоянию 2Δr2+4Δg2+3Δb2. Сглаживания (dither) нет — шкалы плавные, анимация не «шумит».
  3. Блок управления (задержка, без прозрачности), описание кадра с местной палитрой 256 цветов.
  4. Индексы точек сжимаются LZW: начальная длина кода 9 бит (код очистки 256, конца — 257), длина растёт до 12 бит; при заполнении таблицы (4096 кодов) пишется код очистки. Коды упаковываются младшими битами вперёд в подблоки по 255 байт.
  5. close() дописывает завершающий байт ;.

Настройки вида

ViewSettings — флаги и величины CFldViewView FieldView 4.1, сгруппированные по слоям: поле (FieldLayerSettings), слой ε (EpsLayerSettings), топология, окно данных и оси, камера, «значение в точке», вкладка окна «Параметры», скорость проигрывания. Каждое окно документа хранит свою копию; новое окно берёт сохранённые, каждая команда сохраняет текущие (save()).

Хранение — QSettings, раздел «TMC_GraphicsOutputFieldFile», имена ключей — из FieldView 4.1 (TMC_GraphOutFld_Field, …_EpsParam, …_Topology, …_Place, …_Camera и др.); слой записывается строкой из 10 чисел, цвета — строкой #rrggbb через пробел. На Windows это INI-файл %APPDATA%\TMC_Suite_Qt\FieldView.ini; при первом запуске в него переносятся настройки из реестра прежних версий (HKCU\Software\TMC Suite\FieldView). При чтении значения проверяются: непрозрачность 0…100, шкала 0…3, высота рельефа 0,05…10, контраст 1…100, масштаб 0,05…50, скорость 1…60; нечисловые пределы включают автоматические, нечисловое окно данных — «Вся область».

Значения по умолчанию: поле — рельеф с заливкой и каркасом, шкала «Авто», плавно; слой ε выключен (непрозрачность 80 %, «Свечение»); топология объёмная; камера наклонена (−55°, 0°, −20°). «Вид по умолчанию» сохраняет цвета шкал и материалов, величину слоя ε, скорость и вкладку.

Главное окно и команды

MainWindow — окна документов в области MDI, меню «Файл», «Правка», «Вид», «Такты», «Окно», «Справка», основная панель (порядок и группы — как у FieldView 4.1), панель тактов (ползунок, «контраст ×», параметры, экспорт), строка состояния (сообщение, слежение, «nT = …; t = …», интерфейс и кадр/с) и панель «Уровни цвета».

Команды — объекты QAction, их имена — идентификаторы команд FieldView 4.1 (ID_FILE_OPEN, ID_FLAGDRAWLINE, ID_VIEW_ZOOM_P …) плюс новые (ID_ANIM_*, ID_SYNC_*, ID_FIELD_SCALE_*, ID_EXPORT_ANIMATION …). Команда окна документа (cmd) выполняется над активным окном и описывается тремя функциями: действие, флажок, доступность; updateActions() пересчитывает флажки и доступность после каждой команды и смены активного окна. Команды программы (appCmd) доступны всегда. По имени команду находит action(id) — им пользуется программа снимков.

Файлы: «Открыть…» (несколько файлов), перетаскивание в окно, список последних (7), запуск без файла открывает первый существующий из списка. Печать — картинка вида по размеру страницы и строка с именем файла, nT и t. «Руководство пользователя» ищет файл руководства рядом с программой и до 6 папок выше, иначе открывает сайт.

Диалоги

«Параметры вида» (ParametersDialog, Alt+P, щелчок правой кнопкой по виду) — четыре вкладки, кнопки «ОК», «Отмена», «Применить». Окно работает с копией настроек; «Применить» передаёт их окну документа сразу, «ОК» — после закрытия.

Вкладка Содержимое
«Размещение» оси X и Y: «Вся область», min, max (в единицах длины файла, в координатах задания — с учётом xmin, ymin файла), поворот, сдвиг, размерная линия; оси и надписи (цвет, шрифт); камера (поворот Z, сдвиг Z, масштаб); единицы файла; «Пропорционально»
«Топология» типы блоков и их цвета, «Цвета по умолчанию»; контуры, заливка; 2D/3D; размеры блоков и привязки; непрозрачность
«ε и плазма» заливка, сетка, 2D/3D, непрозрачность; шкала, «Цвета уровней…», «По умолчанию»; пределы Z; величина ε/N/Y/B (N, Y, B — только при плазме); предупреждение, если слой недоступен
«Поле» то же + «Модуль поля», «Высота рельефа», «Авто по текущему такту»

Числа вводятся по правилам локали «C» (точка, допускается порядок e). Пересчёт краёв окна: в окне — xокна=(x+xmin,файла)/L, в настройках — x=xокнаL−xmin,файла, где L — единица длины файла в метрах.

«Цвета уровней» (AutoColorDialog) — правка 20 цветов шкалы «20 цветов уровней». Два столбца переключателей выбирают два уровня n1<n2; «Изменить…» — цвет отмеченного уровня; кнопки «Авто…» заполняют уровни между ними целочисленными шагами, как FieldView 4.1:

  • «Авто» — линейно: dc=⌊(cn2−cn1)/(n2−n1)⌋ по каждому каналу;
  • «через красный/зелёный/синий» — выбранный канал до середины растёт с шагом ⌊2(256−cn1)/(n2−n1)⌋, после середины спадает с шагом ⌊2(cn2−256)/(n2−n1)⌋; каналы обрезаются до 0…255.

Уровни ближе двух друг к другу не заполняются. Новые кнопки заполняют все 20 цветов из «Волны», «Свечения» или исходных цветов FieldView 4.1.

«Экспорт анимации» — формат (GIF или PNG), с такта, по такт, каждый k-й, кадров в секунду, ширина (запись). «О программе» — общее окно пакета (при сборке с TMC_FV_COMMON_ABOUT) или собственное окно FieldView.

Оформление

Пространство имён theme (своё у FieldView): цвета тёмного оформления пакета (фон #0a0e16, поверхности, линии, текст, акценты #34e3c4, #b07cff, #ffcf5c), встроенные шрифты Inter и JetBrains Mono, стиль Fusion, палитра Qt и таблица стилей виджетов. Цвета записаны константами — каталог программы собирается сам по себе.

Программа снимков fieldview_shot

Самопроверка без участия человека: открывает файл в настоящем главном окне, выполняет команды по именам и записывает снимок в PNG.

fieldview_shot <файл поля> <снимок.png> [ключи]
Ключ Действие
--size WxH размер главного окна
--action ID (много раз) выполнить команду
--frame N показать такт N (с 1)
--scene-only снимок только сцены
--dialog params0…params3 / autocolor снимок окна «Параметры» (вкладка) или «Цвета уровней»
--levels показать панель «Уровни цвета»
--wait MS пауза перед снимком (1500)
--live SEC следить за расчётом SEC секунд
--save-series PATH записать такты серией
--gain K контраст шкалы поля
--all-actions выполнить все команды дважды (кроме открывающих окна выбора файла, печати и т. п.)
--export-gif PATH, --export-step K записать GIF (15 кадр/с, ширина 720)
--play SEC проигрывать такты SEC секунд (30 кадр/с) и сообщить скорость
--keep-settings не очищать настройки «FieldView Shot»
--place X0,X1,Y0,Y1, --probe X,Y окно данных и точка, м от начала сетки
--open2 FILE открыть второй файл и снимать его
--print-pdf PATH напечатать вид в PDF кодом команды «Печать»
--dump вывести пределы шкал, уровни, сведения о сцене и ошибках
--rhi …, --warp графический интерфейс

Настройки берутся из отдельного раздела «FieldView Shot» и очищаются перед запуском. Сцена RHI в снимок окна (QWidget::grab) не попадает, поэтому дорисовывается снимком кадра вида. Переменные окружения SHOT_GRAB_EACH и SHOT_TRACE включают снимок кадра после каждой команды и печать видимости окна и панелей. Код возврата: 0 — снимок записан, 2 — мало аргументов, 3 — снимок не записан.

Типичные ошибки и подводные камни

  • Текстовый файл поля не читается. Если в задании задан текстовый формат вывода поля, ядро пишет числа текстом; FieldView требует двоичные значения и сообщает «no CR LF after data row …».
  • Топология не показывается. .tt ищется только с тем же именем, что у файла поля. У .AMP/.FAZ имя задаёт FIELD_DISTRIBUTION, а у .tt — FILE: при разных именах топологии у амплитуды нет. .tt от другого расчёта (другие nX, nY, Δ, xmin, ymin) не используется — причина видна в сведениях о такте.
  • Файл поля от 2 ГБ не читается: одиночный кадр читается в память целиком.
  • Большая сетка прорежена. При окне больше 4096 узлов по стороне показан каждый k-й узел; мелкие детали видны только после уменьшения окна данных.
  • nan/inf в поле не входят в шкалу; сведения о такте сообщают их число.
  • Точность. В видеопамять и в серию .frames значения идут во float; число «значения в точке» в исходной точности есть только у последнего прочитанного кадра одиночного файла.
  • Закрытие FieldView при расчёте с синхронизацией возвращает файлу атрибут NORMAL; ядро ждёт чтения кадра до 25 с, затем продолжает без ожидания.
  • Накопленные пределы. По умолчанию шкала растёт по всем показанным тактам: после выброса поле выглядит бледным. Помогают двойной щелчок (пределы заново), «Пределы по текущему такту» или «контраст ×».
  • Окно данных из настроек. Окно сохраняется в метрах от начала сетки и применяется к следующему открытому файлу; если оно лежит за краем меньшей сетки, показывается весь файл.
  • В коде объявлен, но не определён метод FieldPane::updateLabels(); поле SceneData::labelsVersion не используется. Комментарий в начале viewsettings.h говорит о хранении в реестре — на Windows настройки хранятся в INI-файле (настройки).

FieldView — field viewer (Qt 6, rendering via Qt RHI)

Purpose and place in the package

FieldView (fieldview.exe) displays the field computed by the compute kernels PlanarRT_H and PlanarRT_X, time step by time step: as a relief (3D) or as a colour map (2D), together with the model topology (dielectric, metal, magnetic walls, absorber, ports, plasma), the ε layer and — for the X kernel — the plasma grids N, Y, B. The program does no physics of its own: it reads the files written by the kernel and draws them.

Its place in the package is the last link of the chain task file → preprocessor → kernel → files → viewers:

 task file .tpl ── kernel H/X ──┬── <name>.ex / .ey / .hz …  field frames (FIELDS)
                                ├── <name>.tt                topology and ε grid (TOPOLOGY)
                                └── <RP>.AMP / .FAZ          amplitude and phase (FIELD_DISTRIBUTION)
                                            │
                                            ▼
                                       FieldView  ── images, printing, GIF, time-step series .ex.frames

FieldView can work alongside a running computation: after each frame the kernel waits until FieldView has read it, and FieldView shows every new frame immediately and remembers the time steps for later playback (synchronization).

The module is the directory src/fieldview. It is a standalone program in pure Qt 6 (without the MFC compatibility layer); the logic for reading files, the data window, limits and topology has been carried over from the former FieldView 4.1 (MFC + OpenGL 1.x) without changing its meaning, while rendering has been rewritten on Qt RHI: on Windows — Direct3D 11, and if that is unavailable, software Direct3D 11 (WARP) or OpenGL. The non-Windows build (the former OpenGL 1.x rendering) is described separately: FieldView for Linux.

What the user sees is described in the user manual (FieldView); this page covers how the code is organized.

Module contents

File Role
src/main.cpp entry point: styling, choice of graphics API, main window, files from the command line
src/core/fieldfile.h/.cpp field file: header, values, range; time-step series FieldSeries (below)
src/core/textscan.h LineReader, scanDouble, scanInt, scanWordDouble — line parsing like fgets/sscanf, locale-independent
src/core/topology.h/.cpp topology file TopologyFile, boundary strips BlockBoundary, visibility culling (below)
src/core/palette.h/.cpp "Wave", "Glow" and 20-colour scales; material colours (below)
src/core/gifwriter.h/.cpp animated GIF encoder (below)
src/app/fielddocument.h/.cpp FieldDocument — the document: time steps, history, cache, topology, synchronization with the kernel (below)
src/app/fieldpane.h/.cpp FieldPane — the document window: data window, Z limits, layers, geometry, labels, commands (below)
src/app/viewsettings.h/.cpp ViewSettings — per-layer view settings, reading and writing (below)
src/app/startup.h/.cpp choice of graphics API, application names, settings location (below)
src/app/theme.h/.cpp colours, fonts, style sheet (below)
src/render/scenedata.h SceneData, GridLayer, SceneLabel, Sprite — what to draw (below)
src/render/fieldrhiview.h/.cpp FieldRhiView (QRhiWidget) — scene rendering, camera, mouse (below)
src/ui/mainwindow.h/.cpp MainWindow — document windows (MDI), menus, toolbars, status bar, printing, export (below)
src/ui/parametersdialog.h/.cpp the "View parameters" window (below)
src/ui/autocolordialog.h/.cpp the "Level colours" window (below)
src/ui/icons.h/.cpp command and program icons
shaders/*.vert, shaders/*.frag GLSL 440 shaders (below)
resources/ embedded Inter and JetBrains Mono fonts (SIL OFL 1.1), styling icons
tools/fieldview_shot.cpp self-test program — window snapshot to PNG (below)

Build (CMakeLists.txt): the static library fieldview_app (all code except the entry points), the programs fieldview and fieldview_shot. The shaders are compiled by qt_add_shaders (the qsb tool) into the resources :/fieldview/shaders/*.qsb for HLSL 5.0 (Direct3D), GLSL 300 es / 330 (OpenGL), SPIR-V (Vulkan) and MSL (Metal) at once. Toolbar icons are taken from the package's resources/icons/toolbar/fieldview/ (if they are missing, simple icons are drawn), and the program icon from resources/icons/app/.

Architecture

Data flows in one direction — from the file to the screen:

 kernel files        FieldDocument            FieldPane                 FieldRhiView         MainWindow
 ────────────        ──────────────           ──────────                ────────────         ──────────
 .ex / .frames ──▶  time steps (RAM/disk) ──▶ data window, Z limits ──▶ GPU buffers      ──▶ MDI subwindow,
 .tt           ──▶  topology, boundaries  ──▶ layers, geometry, labels  shaders, frame        menus, toolbars,
                    50 ms timer, history      SceneData + Sprite[5]     mouse → signals       status bar
Class Created by Owns Lifetime
MainWindow main() MDI area, commands, printer the whole session
FieldDocument MainWindow::openFile() time steps, cache, topology, timer, background thread while at least one window of this file is open (std::shared_ptr)
FieldPane MainWindow::openFile(), "New window" SceneData, Sprite images, a copy of ViewSettings, the view until the subwindow is closed (WA_DeleteOnClose)
FieldRhiView FieldPane GPU resources same as the document window

A file is opened as one document; the "New window" command creates a second window of the same document with its own view settings. Opening the same file again activates the window that is already open.

Threads. Everything runs in the GUI thread except one background thread per document: for a time-step series it reads all frames once and computes their range (for the "over all time steps" scale). The thread receives a copy of the series index and a shared cancellation flag; the result is returned to the GUI thread via the Qt event queue and is applied only if the document is still alive. When another file is opened and when the document is destroyed, the thread is cancelled and the document waits for it to finish.

Scene rebuilding. The document window recomputes only what has changed, and the view re-uploads to video memory only the data whose version number has changed:

Event What is recomputed
new time step (playback, frame from the kernel) field values; Z limits; if the limits changed or "value at point" is on — geometry and scale
rotation, wheel zoom, mouse pan only the camera and the label image
any view command, the "Parameters" window data window, values, ε layer, geometry, info, scales
window size info, scales, labels

Field file

The kernel writes field frames with the PutField function (see H-kernel output) if the task's #OUTPUT section contains FIELDS. The file name is the base name from FILE with the extension .ex (and also .ey, .hz, .em; .tf is the name used by old builds). The .AMP/.FAZ files (field amplitude and phase at a frequency, FIELD_DISTRIBUTION) have the same format (TMCIndan). FieldView parses all these files the same way — as one scalar value at each grid node. What this quantity is: for the H kernel — the node voltage U, proportional to Ez (H-kernel fields); for the X kernel — the node voltage equal to the Hz component (X-kernel fields). Nodes and their numbering — the method's grid.

Format (the full list of formats — file formats):

#TMC_GraphicsOutputFieldFile FormVer2.0 2000 CRLF
#TMCGROFLD_nT <int> CRLF               time step number
#TMCGROFLD_Time <double> CRLF          model time, s
#TMCGROFLD_Delta <double> CRLF         grid step Δ, m
#TMCGROFLD_Xmin <double> CRLF          coordinate of node (0, 0), m
#TMCGROFLD_Ymin <double> CRLF
#TMCGROFLD_Accuracy <4|8> CRLF         bytes per value: float or double
#TMCGROFLD_LongUnit <name> <m> CRLF    length unit for captions
#TMCGROFLD_TimeUnit <name> <s> CRLF    time unit for captions
#TMCGROFLD_nX <int> CRLF
#TMCGROFLD_nY <int>
then nY times:  CRLF + nX binary values (machine byte order)

Header lines are matched by their beginning and strictly in order; numbers are read like sscanf("%d")/sscanf("%lg"), but under the rules of the "C" locale (textscan.h) — a system locale with a decimal comma does not break them. If a number cannot be parsed, the default value remains (as with sscanf). Then the conditions of the Windows version are checked: nX ≥ 2, nY ≥ 2, Accuracy = 4 or 8. Size of the values:

Nbytes=nYnXa+2(nY−1),(1)

where a is Accuracy: a CR LF pair comes before each row of values, and the first of them terminates the nY line. Rows go from bottom to top (row i holds the nodes with y=ymin+iΔ), and within a row from left to right; node (j,i) is value number inX+j.

Decoding (decodeFieldValues):

  1. If there is less data than Nbytes — error "when read data file".
  2. CR LF bytes are checked at the separator positions. If they are missing, this is a text field output (the kernel writes numbers as text if a field output format is set) or a corrupted file: error "no CR LF after data row …". FieldView does not read text files.
  3. Each value is converted to float (this is how it goes to video memory); at the caller's request, a copy in the original precision (double) is also kept — for "value at point".
  4. The frame range — minimum, maximum and maximum magnitude — is computed from the original numbers and from finite ones only: nan and inf are counted in nonFinite and do not enter the scale (otherwise a single nan would make the scale and the relief empty). The values themselves remain in the frame as they are.

The error messages are the same as in FieldView 4.1: "bad data file", "bad data file nX = … < 2", "abnormal accuracy […], but must be 4 or 8", "can't open data file {…}".

Time-step series .ex.frames

A series is not a kernel format: it is frames of the same format written back to back, each byte for byte like the kernel's. It is written by FieldView itself (the "Save time steps as a series…" command); a single .ex file is a series of one frame. FieldSeries::open passes through the file once:

  1. within a 4 KB window from the current position it checks the first-line signature and parses the header;
  2. it remembers the offsets of the frame start and of the values start, and skips the values by the size given in the header;
  3. after a frame it allows up to two CR/LF bytes (a single .ex may end with them).

A tail that does not look like a frame and an incomplete last frame (still being written) are discarded; frames whose grid differs from the first one are skipped. Values are read on demand (readFrame), reopening the file each time — this is why a copy of the index can be read from the background thread.

When a series is written (FieldDocument::saveSeries), the header of each frame is written the same way as by the kernel (numbers with 6 significant digits, %lg), the values as float (Accuracy 4); the write is atomic (QSaveFile).

Topology file .tt

The kernel writes it for the TOPOLOGY; line of the #OUTPUT section (see H-kernel output). FieldView looks for the .tt next to the field file and with the same name: the path without the last extension (for a series — without .frames and the frame extension) plus .tt in any letter case. If the .tt itself is opened, the document takes the field file with the same name (.ex, .ey, .hz, .em, .tf, their series, .AMP, .FAZ — the first one found).

#TMC_TopologyOutputFile FormVer2.0 2000
#BlockListBegin
<block kind>                   "RECT_STAT ", "INPUT_X ", "CIRCLE_STAT_N " …
<ε expression or type>         "METAL" …
<line 3> <line 4> <line 5>
x0 xMax xMin y0 yMax yMin nBlock nMemory nType nXY
x y                            nXY lines — polygon vertices
… (next blocks)
#BlockListEnd
#TMCGROFLD_nT, _Time, _Delta, _Xmin, _Ymin, _nX, _nY     (no Accuracy)
ε grid:  nY times — nX double values + 2 bytes
for the X kernel, three more grids of the same kind follow: N, Y, B

A record with nBlock = 0 is not considered a block. If there is not enough data for three grids after the ε grid, there is no plasma (hasPlasma() = false). The ε layer shows the selected grid: 0 — ε, 1 — N (m⁻³), 2 — Y, 3 — B (T) (plasma units); without plasma any selected quantity is shown as ε, and the captions also say "ε".

Consistency check (FieldDocument::topologyMismatch). The topology is used (the ε layer and the block contours) only if its grid matches the grid of the field file: equal nX, nY, and Δ, xmin, ymin agree within the tolerance 10−6max(|Δfield|,|Δtt|) — the kernel writes both headers in the same format, so the tolerance covers only write rounding. Otherwise the time-step info shows the reason ("topology file … from a different computation: grid … instead of …"), and the field is drawn without topology. The topology file is re-read on opening, on a double click and on every frame from the kernel if the file time or the field grid step has changed.

Block boundaries

From the block list, buildBoundaries builds for each block its boundary strips — quadrilaterals one grid step Δ wide along the contour (prisms in 3D), dimension lines and the anchor. The logic and the order of checks are as in CTmcBoundaryTpl of FieldView 4.1:

Block kind Strips Dimensions
RECT_STAT, RECT_MOVE, FILE (as ε) four sides of the rectangle [xmin,xmax]×[ymin,ymax], each widened by ±Δ/2 height (along the left side), width (along the top side)
POLYGON_STAT, POLYGON_MOVE one strip per side; the strip is stretched along the larger projection of the side; the closing side only for an ε block lengths of all sides, including the closing one
CIRCLE_STAT, CIRCLE_MOVE outer arc; for an inner radius >Δ — two radial segments and an inner arc outer radius; inner radius (if >Δ)
INPUT_X strip along the Y axis: x∈[−Δ/2,Δ/2], y∈[xmin,xmax] of the record aperture
INPUT_Y strip along the X axis: x∈[xmin,xmax], y∈[−Δ/2,Δ/2] aperture
RECT_STAT_N/_B/_Y, POLYGON_STAT_N/_B/_Y, CIRCLE_STAT_N/_B/_Y, FILE_N/_B/_Y plasma contours (type "plasma", the polygon is always closed; FILE_* is a rectangle) — not in FieldView 4.1 none

For a circle the record fields mean: xMin/xMax — inner and outer radii, yMin/yMax — start and end angles φ0, φ1 (rad). An arc of radius R is divided into

n=max(int(R(φ1−φ0)Δ+0,5)+1, 2)(2)

points and n−1 segments, each a rectangle built from the end coordinates. (FieldView 4.1 drew n segments, and the arc extended one segment beyond the sector.) Then all strips and dimensions are shifted by the block anchor (x0,y0); the anchor itself is drawn as two dimension lines from the origin. Ports are numbered in block order: "Inp 1", "Inp 2" …; the label is placed at the centre of the port's first strip.

Visibility culling (visibleTopology, visibleSizes): the display area is widened by 1,1Δ; a strip is taken if at least one of its vertices is inside; a dimension line — if both ends are inside and its length exceeds 2Δ. Types are filtered by the "Boundaries" check boxes (ε, metal, magnetic wall, absorber, ports, plasma).

Document and synchronization with the kernel

FieldDocument is an open file with everything that comes with it. The document's time steps are a list of Slot: a header, where the values are stored and whether the range is known.

Source Where the values are How many time steps
single file (.ex, .tf, .AMP …) in memory (Slot::mem) one; when following with recording — a history: every new frame is appended
.frames series on disk; the ones already read — in the cache all frames of the series

Time-step history. A frame from the kernel (or a re-read file) with the same grid and a different time-step number or time is appended; with the same time step it replaces the last one; with a different grid the history is reset. Without recording, a single time step remains. The history size is limited to 1 GB (4 bytes per node per time step); beyond that the oldest time steps are discarded, and the last one always remains. "Forget time steps" keeps only the last one.

Series cache. A time step of a series is read on first access and put into a cache of at most 256 MB; when it overflows, the time steps that have not been requested for the longest time are evicted.

Precision. Time-step values are stored as float; values in the original precision of the file exist only for the last frame read from a single file — from them "value at point" shows the number without loss of precision.

Synchronization protocol

The protocol is the same as in FieldView 4.1 and the kernel (CTmcRTHRectNode::IsFieldFileRead): it uses the ARCHIVE attribute of the field file:

 kernel                                            FieldView (50 ms timer)
 ──────                                            ───────────────────────
 waits until the file has ARCHIVE      ◀───────┐
   (up to 500 × 50 ms = 25 s per frame)        │
 fopen("wb") — on failure retry in 10 ms       │   ARCHIVE bit cleared?  no → wait
 writes the frame, clears ARCHIVE (NORMAL) ───▶│   yes → read the whole file, denying
                                               │         write access to others (FILE_SHARE_READ)
                                               └── sets ARCHIVE
  • A new frame is signalled by a cleared ARCHIVE bit (only this bit is checked: compressed files and files in cloud folders carry extra attribute bits, and comparing the attributes as a whole would re-read the frame every 50 ms).
  • While FieldView is reading, the file is open without FILE_SHARE_WRITE: the kernel's fopen is refused and retries — FieldView always reads a complete frame.
  • After a read error, 20 polls (~1 s) are skipped; the ARCHIVE bit is set in any case.
  • When a single file is opened, the document sets ARCHIVE; when the document is destroyed (if following is on), it restores NORMAL, as FieldView 4.1 does.
  • "Follow computation" turns the timer off — FieldView then does not set ARCHIVE, and after 25 s of waiting the kernel stops waiting (until the next read).
  • FieldView tracks a .frames series by file size and modification time: new frames are appended to the end of the list.
  • On systems without the ARCHIVE attribute a single file is tracked in the same way — by time and size.

The file is read into memory in full, so a single field file larger than 2 GB cannot be read (a clear error giving the file size).

Document window

FieldPane turns the time step, the topology and the settings into SceneData (a port of PrepareData/PrepareTpl/PrepareBoundaryTpl of FieldView 4.1) and executes the view commands. Images on top of the scene (Sprite): 0 — labels, 1 — time-step info, 2 — field scale, 3 — ε scale, 4 — message in the middle of the view (no file yet, read error, data window error, all layers turned off).

Data window

The data window is the displayed part of the grid, [xmin,xmax]×[ymin,ymax] in metres from node (0, 0). "Zoom" in FieldView changes exactly this window, not the camera.

  1. "Whole area" along an axis — a window from 0 to (n−1)Δ. Otherwise the edges are ordered and clipped to the grid; if the left edge lies beyond the last node (settings from another, larger file), the whole file is shown.
  2. The edges are converted into node numbers: j=⌊x/Δ+10−9⌋ (the increment protects against x=kΔ, which gives k−10−16 when divided), clamped to the grid. Fewer than two nodes along an axis — error "number of point along X axies < 2".
  3. Decimation. If the window has more than kMaxSceneSide = 4096 nodes along a side (GPU buffers and indices are 32-bit), every k-th node is shown, k=⌈(n−1)/(4096−1)⌉; values are not averaged. The time-step info reports this.
  4. The edges are snapped to nodes: xmin=j0Δ, xmax=j1Δ — otherwise after zooming the field and the topology would be offset by a fraction of a cell.
  5. Proportions: with "Proportional", the shorter side of the window gets the share kx=(xmax−xmin)/(ymax−ymin) (or ky the other way round), otherwise kx=ky=1.

Scene coordinates (as in XtoGLWinCoord of FieldView 4.1, but centred at zero):

X=2,5kx(x−xminxmax−xmin−12),Y=2,5ky(y−yminymax−ymin−12).(3)

Commands: "Zoom in" makes the window around the centre half as wide (but not narrower than 2Δ), "Zoom out" — twice as wide (wider than the grid means the whole file); the arrow keys shift the window by Δ, and in "value at point" mode they move the point itself by one node.

Value at point (Field → Value, Shift + click): the point is snapped to the nearest scene node (rounding, not truncation) that is not on the edge; the marker is a rhombus on the four neighbouring nodes and a tick above the node. The number is taken from the original values if they exist, otherwise from the float values. Shift + click finds the point of the plane z=0 under the cursor (pickGround) and converts it back to metres.

Z limits and scale selection

Limits [zmin,zmax] of the field scale (updateFieldRange):

  1. The range of what is shown: for the whole grid — the frame range, otherwise — over the values of the data window (finite numbers only).
  2. Accumulation (as dZmin/dZmax of FieldView 4.1): by default the limits grow over all time steps shown; for the whole grid, the range of the time steps of the document already read is added (for a series — of all of them, computed in the background). The "Limits from current time step" check box takes the range of the current time step only. Accumulation is reset when the data window, the magnitude mode, automatic limits or the scale change, on a double click, and on "Default view".
  3. "Auto" scale: "Glow" if the minimum is ≥0, otherwise "Wave". In "Magnitude" mode — "Glow" (or "20 colours" if it is selected).
  4. Limits in automatic mode (g — "contrast", 1…100):
Case zmin zmax
no data −1 1
field is zero everywhere (max|v|< FLT_MIN) −1 ("Wave", "Magnitude") or 0 1
"Magnitude" or "Wave" −max|v|/g max|v|/g
"Glow" min(0,vmin)/g vmax/g
"20 colours" vmin/g vmax/g

Manual limits are taken as given (in "Magnitude" mode — symmetrically about the larger magnitude). A degenerate range is widened to z±max(10−6|z|,FLT\_MIN).

  1. Normalization for the shader: h=vk+off, where
k=2zmax−zmin,off=−2zminzmax−zmin−1,(4)

so that zmin↦h=−1, zmax↦h=1. The height of a relief point in the scene is h multiplied by the "relief height" (0.05…10).

The ε (N, Y, B) layer takes its limits from the values of the data window (without accumulation over time steps); a degenerate range is widened by max(1,|z|)·10−6; its "Auto" scale is always "Glow".

Colour levels (the "Colour levels" panel): level i=0…19 starts at the value zmin+i19(zmax−zmin) (in magnitude mode — i19zmax).

Colour scales

A scale turns a number t∈[0,1] into a colour. For the field t=(h+1)/2, in magnitude mode $t = \lvert h\rvert $; values outside the limits get the end colour.

Scale Purpose Reference colours (bottom to top)
"Wave" sign-alternating field: −max — light violet, 0 — almost black, +max — light cyan #f1e8ff #d7bdff #9b6cf0 #4a3590 #131a28 #0f4f45 #1a9a83 #34e3c4 #c4f7ee
"Glow" non-negative quantities: field magnitude, amplitude, ε, N, Y, B #0a0e16 #1b2550 #3a3384 #7a55d6 #b07cff #34e3c4 #ffcf5c #fff3d6
"20 level colours" user-defined, as in FieldView 4.1 20 colours from the settings

The reference colours of "Wave" and "Glow" are evenly spaced; between neighbours the colour is interpolated linearly in OKLab space — lightness increases monotonically, and the picture remains readable even in greyscale:

p=t(n−1),i=min(⌊p⌋,n−2),f=p−i,Lab(t)=(1−f)Lab(ci)+fLab(ci+1).(5)

sRGB → OKLab conversion: the channels are linearized (c≤0,04045: c/12,92, otherwise ((c+0,055)/1,055)2,4), multiplied by a 3×3 matrix into LMS space, the cube root of each component is taken, and then a second 3×3 matrix gives L,a,b. The inverse conversion runs in reverse order, with the channels clipped to [0, 1]. The matrix coefficients are in palette.cpp.

"20 colours" are interpolated linearly over the sRGB channels: p=19t, between colours ⌊p⌋ and ⌊p⌋+1. With the "Smooth scale" check box off — 20 steps: t→⌊19t⌋/19 (in the shader).

Original FieldView 4.1 colours (classicFieldColors): levels i=0…6 — (100, 35i, 255−35i); 7…13 — (35(i−7), 255−35(i−7), 150); 14…17 — (255, min(255,83(i−14)), 100); 18 — yellow, 19 — white. For the ε layer (classicEpsColors): colour 19−i is (max(0,255−10i), 255, min(255,10i)).

For the GPU the scale is written as a 256×1 RGBA8 texture (scaleImage); point x corresponds to t=x/255. The shader samples the colour at the texel centre: u=(255t+0,5)/256.

Default material colours of the topology (defaultTopologyColor): ε — #b07cff, metal — #9fb0c8, magnetic wall — #6c7d97, port — #34e3c4, absorber — #3a4a6b, plasma — #ffcf5c. The fill is semi-transparent depending on the material (opacity factors 0.30 / 0.92 / 0.85 / 0.95 / 0.35 / 0.30), so that the field under the dielectric, the plasma and the absorber remains visible.

Scene

SceneData is everything the view draws in a frame; it is filled by FieldPane and read by FieldRhiView.

  • Two grid layers (GridLayer): the field and the ε layer. A layer holds the node values of the data window (shared_ptr: for the whole grid — no copy, memory shared with the frame), the height rule (k, off), colour mode, number of steps, relief height, opacity, scale, wireframe colour. Scene grid: node (j,i) is the point (x0+sxj/(nX−1), y0+syi/(nY−1)), where x0=−1,25kx, sx=2,5kx.
  • Coloured geometry — triangles and line segments, 7 numbers per vertex (x,y,z,r,g,b,a): topology strips (in 3D — prisms from −0.25 to 0.25, in 2D — at height 0.02, contours at 0.03), dimension lines with arrows, the X, Y, Z axes, window dimensions, Z scales, the "value at point" marker.
  • Labels (SceneLabel) — a scene point, text, colour, alignment. Each time the camera changes they are projected into window pixels and drawn with QPainter into a single image with a dark outline.
  • Images on top of the scene (Sprite) — ready-made images in window pixels (up to 8).
  • Extents boundX, boundY, boundZ — for choosing the camera distance.

Each part carries a version number; the view re-uploads to video memory only what has changed.

Camera

The "scene → clip space" matrix (FieldRhiView::viewProjection):

  1. Perspective with a vertical field of view of 30° (gluPerspective(30, …) of FieldView 4.1).
  2. The camera distance is chosen so that, in the default view (rotation a=−20°, tilt θ=−55°), the scene fits entirely into a window of any shape. With τ=tg15°, extents sx,sy,hz and window aspect ratio A:
hx=|cosa|sx2+|sina|sy2,hy0=|sina|sx2+|cosa|sy2,hy=max(hy0, hy0|cosθ|+hz|sinθ|),(6)
d=1,2max(hxτA, hyτ)+0,3,dcam=max(0,05, d−tz).(7)
  1. The near and far planes enclose a sphere of radius r=0,5sx2+sy2+4hz2·zoom+0,6: max(0,01,(dcam−r)/2) and dcam+r+2.
  2. View: translation (panxdτA+tx, panydτ+ty, −dcam), then rotations about X, Y, Z (the glRotatef order of FieldView 4.1) and scaling by zoom.

Before rendering, the matrix is multiplied by the API's clipSpaceCorrMatrix() (Direct3D and OpenGL have different conventions for depth and for the Y axis). Mouse: left button — rotation (0.4° per pixel: about Z horizontally, about X vertically, X limited to ±180°), right or middle button — pan, wheel — zoom (1,0015Δ, Δ — wheel angle in 1/8°, zoom 0.05…50), right click — "Parameters", double click — recompute the Z limits and re-read the file.

Rendering via Qt RHI

FieldRhiView is a descendant of QRhiWidget: it is embedded as an ordinary widget into an MDI window and can return a frame synchronously (grabFramebuffer) — printing, image saving, GIF export and the self-test all rely on this.

Choice of graphics API (chooseGraphicsApi, at startup, for all windows):

  1. Source — the FIELDVIEW_RHI environment variable or the switches --rhi d3d11|d3d12|opengl|vulkan (--rhi=…), --warp; recognized switches are removed from the file list.
  2. opengl/gl and vulkan are accepted without a check.
  3. d3d12 — if an RHI object with Direct3D 12 can be created.
  4. Otherwise (and if there is no --warp) — Direct3D 11, if it can be created.
  5. Otherwise — software Direct3D 11 (WARP: no graphics card with Direct3D 11 — a server, a remote desktop).
  6. Otherwise — OpenGL.

The check is a trial creation and deletion of a QRhi object. The selected API and the frame rate are shown on the right of the status bar.

Resources (buildPipelines, rebuildGrid):

Resource When it is created Contents
node coordinates (u, v) when the grid size changes u=j/(nX−1), v=i/(nY−1), immutable buffer
field values, ε values when the grid size changes; upload — when the time step changes float per node
triangle indices when the grid size changes two triangles per cell: (ii,ii+1,ii+1+nX), (ii,ii+1+nX,ii+nX)
wireframe indices when the grid size changes along a line — all nodes (the line follows the relief); lines are spaced out: at most ~120 per side over the fill, ~1000 without it
scale textures once; upload — when the scale changes 256×1 RGBA8
coloured geometry buffers when the volume grows vertices of 7 float each
image textures when the image size changes RGBA8, premultiplied alpha

There are five pipelines: grid fill (triangles, depth test and write), grid wireframe (lines, depth test without write), coloured triangles, coloured lines, images (no depth). All of them blend for premultiplied alpha: c=csrc+(1−αsrc)cdst. Antialiasing — 4 samples per pixel. A frame (render): upload of changed data, then the field, the ε layer, coloured triangles, coloured lines, images.

Shaders

The shaders are written once in GLSL 440 (shaders/) and translated by qsb for each API; they are loaded from the resources :/fieldview/shaders/<name>.qsb.

Shader What it does
grid.vert Grid layer. Input — the node's (u, v) and the value v. Computes h=vk+off; colour t=(h+1)/2 or $\lvert h\rvert $, clipped to [0, 1]; with L steps — t=min(⌊t(L−1)⌋,L−1)/(L−1). Position: (x0+usx, y0+vsy, clamp(h,±1,0001)·m+zlift), where m is the relief height (0 in 2D). Passes t and the position to the fragment shader.
grid.frag Colour — from the scale texture at t or a constant one (wireframe over the fill). With relief it shades the slopes: the normal n is taken from the position derivatives, brightness ×(1−0,35(1−|nz|)) — a flat field does not darken. Multiplies by the layer opacity and outputs a premultiplied colour.
color.vert Coloured geometry: position × matrix, vertex colour passed on.
color.frag Outputs the vertex colour with premultiplied alpha.
sprite.vert Image on top of the scene: coordinates are window pixels, orthographic matrix.
sprite.frag Colour from the image texture (already premultiplied).

Constant buffer of the grid layer (GridUniforms, std140, 144 bytes): mvp (matrix), rect (x0,y0,sx,sy), map (k, off, colour mode, steps), misc (relief height, lift, opacity, "colour from scale"), color (wireframe colour), extra (slope shading strength: 0.35 for the relief fill, 0 otherwise). Lift: in 3D for the wireframe — 0,004max(0,3,m) above the relief, in 2D — the layer's zlift (+0.01 for the wireframe); in 2D the ε layer lies 0.002 above the field.

Time animation and GIF recording

Time steps. The document window shows one time step; the slider and the commands "Play/pause", "Previous", "Next", "First", "Last" switch between them. Playback runs on a timer (Qt::PreciseTimer, interval max(10,1000/fps) ms) in a loop. If the last time step is shown, the window follows the computation: a new frame from the kernel is shown immediately (unless playback is running). During playback only the values and the time-step info are recomputed — the geometry and the scale only if the limits have changed.

Export (MainWindow::exportFrames): for each selected time step (from, to, every k-th) the window shows the time step, grabs a frame with grabImage(), scales it to the given width and writes it as a GIF frame or as a file <name>_0001.png. The GIF frame delay is max(2,⌊100/fps⌋) hundredths of a second. Playback is stopped, and afterwards the time step that was shown is restored.

GIF encoder (GifWriter, GIF89a, no third-party libraries):

  1. Header: a logical screen the size of the first frame, no global palette; a NETSCAPE2.0 block — infinite looping.
  2. Frame: colours are reduced to 5-6-5-bit keys, and the 256 most frequent are chosen from the histogram; each key of the frame is mapped to the nearest palette colour by the distance 2Δr2+4Δg2+3Δb2. There is no dithering — the scales are smooth, so the animation does not "flicker".
  3. Graphic control block (delay, no transparency), image descriptor with a local palette of 256 colours.
  4. Pixel indices are compressed with LZW: initial code length 9 bits (clear code 256, end code 257), the length grows up to 12 bits; when the table is full (4096 codes), a clear code is written. Codes are packed least-significant bit first into sub-blocks of 255 bytes.
  5. close() appends the trailing byte ;.

View settings

ViewSettings — the flags and values of CFldViewView of FieldView 4.1, grouped by layer: field (FieldLayerSettings), ε layer (EpsLayerSettings), topology, data window and axes, camera, "value at point", tab of the "Parameters" window, playback speed. Each document window keeps its own copy; a new window takes the saved ones, and every command saves the current ones (save()).

Storage — QSettings, section "TMC_GraphicsOutputFieldFile", key names from FieldView 4.1 (TMC_GraphOutFld_Field, …_EpsParam, …_Topology, …_Place, …_Camera etc.); a layer is written as a string of 10 numbers, colours as a space-separated string of #rrggbb values. On Windows this is the INI file %APPDATA%\TMC_Suite_Qt\FieldView.ini; on first launch the settings from the registry of earlier versions (HKCU\Software\TMC Suite\FieldView) are migrated into it. On reading, the values are validated: opacity 0…100, scale 0…3, relief height 0.05…10, contrast 1…100, zoom 0.05…50, speed 1…60; non-numeric limits switch to automatic ones, a non-numeric data window to "Whole area".

Defaults: field — relief with fill and wireframe, "Auto" scale, smooth; ε layer off (opacity 80 %, "Glow"); topology in 3D; camera tilted (−55°, 0°, −20°). "Default view" keeps the scale and material colours, the ε-layer quantity, the speed and the tab.

Main window and commands

MainWindow — document windows in the MDI area, the menus "File", "Edit", "View", "Time steps", "Window", "Help", the main toolbar (order and groups as in FieldView 4.1), the time-step toolbar (slider, "contrast ×", parameters, export), the status bar (message, following, "nT = …; t = …", graphics API and frames per second) and the "Colour levels" panel.

Commands are QAction objects; their names are the command identifiers of FieldView 4.1 (ID_FILE_OPEN, ID_FLAGDRAWLINE, ID_VIEW_ZOOM_P …) plus new ones (ID_ANIM_*, ID_SYNC_*, ID_FIELD_SCALE_*, ID_EXPORT_ANIMATION …). A document-window command (cmd) acts on the active window and is described by three functions: action, check state, availability; updateActions() recomputes the check states and availability after each command and after a change of the active window. Application commands (appCmd) are always available. A command is found by name with action(id) — the snapshot program uses it.

Files: "Open…" (several files), drag and drop into the window, recent-file list (7); launching without a file opens the first existing one from the list. Printing — the view image scaled to the page size and a line with the file name, nT and t. "User manual" looks for the manual file next to the program and up to 6 folders above it, otherwise it opens the website.

Dialogs

"View parameters" (ParametersDialog, Alt+P, right click on the view) — four tabs, buttons "OK", "Cancel", "Apply". The window works on a copy of the settings; "Apply" passes them to the document window immediately, "OK" — after closing.

Tab Contents
"Placement" X and Y axes: "Whole area", min, max (in the file's length units, in task coordinates — taking the file's xmin, ymin into account), rotation, shift, dimension line; axes and labels (colour, font); camera (Z rotation, Z shift, zoom); file units; "Proportional"
"Topology" block types and their colours, "Default colours"; contours, fill; 2D/3D; block dimensions and anchors; opacity
"ε and plasma" fill, grid, 2D/3D, opacity; scale, "Level colours…", "Default"; Z limits; ε/N/Y/B quantity (N, Y, B — only with plasma); a warning if the layer is unavailable
"Field" the same + "Field magnitude", "Relief height", "Auto from current time step"

Numbers are entered under the rules of the "C" locale (decimal point, an e exponent is allowed). Conversion of the window edges: in the window — xwindow=(x+xmin,file)/L, in the settings — x=xwindowL−xmin,file, where L is the file's length unit in metres.

"Level colours" (AutoColorDialog) — editing the 20 colours of the "20 level colours" scale. Two columns of radio buttons select two levels n1<n2; "Change…" sets the colour of the marked level; the "Auto…" buttons fill the levels between them in integer steps, as FieldView 4.1 does:

  • "Auto" — linearly: dc=⌊(cn2−cn1)/(n2−n1)⌋ for each channel;
  • "via red/green/blue" — the selected channel increases up to the middle with the step ⌊2(256−cn1)/(n2−n1)⌋, and after the middle decreases with the step ⌊2(cn2−256)/(n2−n1)⌋; the channels are clipped to 0…255.

Levels closer than two to each other are not filled. New buttons fill all 20 colours from "Wave", "Glow" or the original FieldView 4.1 colours.

"Export animation" — format (GIF or PNG), from time step, to time step, every k-th, frames per second, width (recording). "About" — the common About dialog of the package (when built with TMC_FV_COMMON_ABOUT) or FieldView's own window.

Styling

The theme namespace (FieldView's own): the colours of the package's dark theme (background #0a0e16, surfaces, lines, text, accents #34e3c4, #b07cff, #ffcf5c), the embedded Inter and JetBrains Mono fonts, the Fusion style, the Qt palette and the widget style sheet. The colours are written as constants — the program directory builds on its own.

Snapshot program fieldview_shot

A self-test without human involvement: it opens a file in the real main window, executes commands by name and writes a snapshot to PNG.

fieldview_shot <field file> <snapshot.png> [switches]
Switch Action
--size WxH main window size
--action ID (repeatable) execute a command
--frame N show time step N (from 1)
--scene-only snapshot of the scene only
--dialog params0…params3 / autocolor snapshot of the "Parameters" window (tab) or of "Level colours"
--levels show the "Colour levels" panel
--wait MS pause before the snapshot (1500)
--live SEC follow the computation for SEC seconds
--save-series PATH write the time steps as a series
--gain K contrast of the field scale
--all-actions execute all commands twice (except those that open a file selection dialog, printing, etc.)
--export-gif PATH, --export-step K write a GIF (15 frames/s, width 720)
--play SEC play the time steps for SEC seconds (30 frames/s) and report the speed
--keep-settings do not clear the "FieldView Shot" settings
--place X0,X1,Y0,Y1, --probe X,Y data window and point, m from the grid origin
--open2 FILE open a second file and take snapshots of it
--print-pdf PATH print the view to PDF using the code of the "Print" command
--dump output the scale limits, levels, scene info and errors
--rhi …, --warp graphics API

The settings are taken from a separate section "FieldView Shot" and are cleared before the run. The RHI scene does not get into a window snapshot (QWidget::grab), so it is drawn in from a snapshot of the view's frame. The environment variables SHOT_GRAB_EACH and SHOT_TRACE enable a frame snapshot after each command and printing of the visibility of the window and panels. Exit code: 0 — snapshot written, 2 — too few arguments, 3 — snapshot not written.

Typical errors and pitfalls

  • A text field file cannot be read. If a text field output format is set in the task, the kernel writes numbers as text; FieldView requires binary values and reports "no CR LF after data row …".
  • The topology is not shown. A .tt is looked up only under the same name as the field file. For .AMP/.FAZ the name is given by FIELD_DISTRIBUTION, while for .tt it is given by FILE: with different names the amplitude has no topology. A .tt from a different computation (different nX, nY, Δ, xmin, ymin) is not used — the reason is shown in the time-step info.
  • A field file of 2 GB or more cannot be read: a single frame is read into memory in full.
  • A large grid is decimated. With a window of more than 4096 nodes per side, every k-th node is shown; fine details are visible only after shrinking the data window.
  • nan/inf in the field do not enter the scale; the time-step info reports their count.
  • Precision. Values go to video memory and to a .frames series as float; the "value at point" number in the original precision exists only for the last frame read from a single file.
  • Closing FieldView during a synchronized computation restores the NORMAL attribute of the file; the kernel waits up to 25 s for the frame to be read, then continues without waiting.
  • Accumulated limits. By default the scale grows over all time steps shown: after an outlier the field looks pale. A double click (recompute the limits), "Limits from current time step" or "contrast ×" help.
  • Data window from the settings. The window is saved in metres from the grid origin and applied to the next file opened; if it lies beyond the edge of a smaller grid, the whole file is shown.
  • The method FieldPane::updateLabels() is declared in the code but not defined; the field SceneData::labelsVersion is not used. The comment at the beginning of viewsettings.h mentions storage in the registry — on Windows the settings are stored in an INI file (settings).