FieldView для Linux — просмотр полей через OpenGL 1.x

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

FieldView показывает распределение поля, которое счётное ядро записало в файл поля (.ex, .tf, .AMP, .FAZ …) во время или после расчёта: рельеф или цветовую карту значения в узлах сетки, слой распределения ε (у X-ядра — также концентрации N, потерь Y и поля B плазмы) и границы блоков задания. Что за величина лежит в файле и как она получена — вывод поля ядром, поля H-ядра, поля X-ядра.

Эта страница описывает сборку не под Windows (Linux). В Windows-сборке вместо неё работает новый FieldView на Qt RHI — apps/fieldview_rhi. Выбор делает src/CMakeLists.txt: вне Windows подключается apps/fieldview, в Windows — apps/fieldview_rhi.

Linux-версия — это код FieldView прежней (MFC) версии из src/fieldview, скомпилированный без изменений поверх слоя совместимости, и небольшая Qt-оболочка src/fieldview. Рисование идёт старым OpenGL (glBegin/glEnd, матрицы, без шейдеров): контекст даёт QOpenGLWidget (виджет-хозяин вида OpenGL), а вызовы wgl* — заглушки (OpenGL в слое совместимости).

Чем Linux-версия отличается от FieldView на Qt RHI:

Linux (apps/fieldview) Windows (apps/fieldview_rhi)
Код MFC-версия без изменений + слой совместимости написан заново на Qt 6
Вывод OpenGL 1.x, совместимый профиль 2.1 Qt RHI (D3D11/OpenGL), шейдеры
Файл поля один кадр, перечитывается при изменении кадр, история тактов, серии .frames
Топология перечитывается с каждым кадром, сетка не сверяется с файлом поля перечитывается при изменении, сетка сверяется
Шкала 20 цветов или плавная смесь крайних несколько палитр
Анимация, GIF нет есть

Форматы файлов у обеих версий одни и те же: файл поля, файл топологии .tt.

Состав

Файл Роль
src/fieldview/fldviewdoc.h/.cpp CFldViewDoc — документ: чтение файла поля, единицы, синхронизация с ядром
src/fieldview/fldviewview.h/.cpp CFldViewView — вид: настройки, подготовка данных, сцена OpenGL, все команды; функции строки состояния PutTrace, PutStatistics; окно свойств GetPropDialog()
src/fieldview/tmcblocktpl.h/.cpp CTmcBlockTpl — файл топологии .tt: список блоков, сетки ε, N, Y, B
src/fieldview/tmcboundarytpl.h/.cpp CTmcBoundaryTpl — границы одного блока: полосы вдоль контура, размерные линии
src/fieldview/tmctopsize.h/.cpp CTmcTopSize — размерная линия
src/fieldview/tmcgltext.h CTmcGLText — надпись в точке сцены (реализация для Linux — apps/fieldview/tmcgltext_qt.cpp)
src/fieldview/tmcdialogpropet.h/.cpp CTMCDialogPropet — окно свойств «Parameters»
src/fieldview/tmcdialogplace.h/.cpp вкладка «Place» — область показа, углы, оси
src/fieldview/tmcdialogtopology.h/.cpp вкладка «Topology» — границы блоков
src/fieldview/tmcdialogeps.h/.cpp вкладка «Eps» — слой ε
src/fieldview/tmcdialogfield.h/.cpp вкладка «Field» — поле
src/fieldview/colorleveldlg.h/.cpp CColorLevelDlg — окно уровней цвета (значение поля для каждого из 20 цветов)
src/fieldview/tmcasetcolor.h/.cpp CTmcASetColor — окно «Auto color»: правка и автоподбор 20 цветов шкалы
src/fieldview/mainfrm.h/.cpp CMainFrame — рамка; в Linux нужна ради строки состояния
src/fieldview/fldview.h сообщения вкладок WM_USERAPPLY_PROP*, класс приложения MFC (не создаётся)
src/fieldview/resource.h номера окон, элементов и команд (команды)
src/fieldview/stdafx.h заголовки MFC (здесь — слоя совместимости)
apps/fieldview/main.cpp точка входа fieldview
apps/fieldview/mainwindow.h/.cpp MainWindow — меню, панель, строка состояния, окна документов MDI
apps/fieldview/tmcgltext_qt.cpp методы CTmcGLText через QImage и glDrawPixels
apps/fieldview/dialogs/dialog_registry.cpp, dialogs/*.ui разметка окон, порождённая из ресурса FldView.rc
apps/fieldview/testtools/*.cpp тестовые программы (ниже)

В сборку не входят (только шапка в файле): fldview.cpp (приложение MFC и окно «О программе»), childfrm.h/.cpp (дочернее окно MDI), stdafx.cpp, tmcgltext.cpp (растр надписей средствами GDI) и tmcrth_blocklist1.h/.cpp (пустой наследник CTmcRTH_BlockList, подключающий заголовок по абсолютному пути чужой машины).

Сборка

apps/fieldview/CMakeLists.txt собирает четыре цели:

Цель Состав Зависимости
fieldview_core (библиотека) fldviewdoc.cpp, tmcblocktpl.cpp, tmcboundarytpl.cpp, tmctopsize.cpp — без Qt-интерфейса слой совместимости tmc_platform
fieldview_view (библиотека) вид, рамка, окно свойств и его вкладки, окна цветов, tmcgltext_qt.cpp fieldview_core, tmc_gui_common, GL, GLU
fieldview_gui (библиотека) mainwindow.cpp, dialog_registry.cpp, dialogs/*.ui, ресурсы значков fieldview_view, Qt Widgets
fieldview (программа) main.cpp fieldview_gui

Код из src/libs, src/kernels, src/viewers компилируется с -fpermissive -w. Тестовые программы fieldview_doccheck, fieldview_shot, fieldview_uitest в поставку не входят.

Документ

CFldViewDoc — один открытый файл поля. Оболочка создаёт его вместе с видом при открытии файла; у документа один вид.

Чтение (ReadData): прежние данные сбрасываются, файл открывается в двоичном режиме, разбираются строки заголовка, выделяется память и читаются значения. Формат — файл поля.

Чтение файла поля

  1. ReadDataParameters читает 10 строк заголовка строго по порядку: #TMC_GraphicsOutputFieldFile, _nT, _Time (с), _Delta (м), _Xmin, _Ymin (м), _Accuracy, _LongUnit (имя и длина единицы в метрах), _TimeUnit (имя и длительность в секундах), _nX, _nY. Каждая строка сверяется по началу с признаком из tmcgrviw.h; число читается sscanf. Несовпадение или конец файла — ошибка «bad data file».
  2. InitAllocationArray требует nX≥2, nY≥2 и выделяет nXnY чисел double.
  3. ReadDataArray читает значения: Accuracy 4 — float, 8 — double, иначе ошибка «abnormal accuracy». Строки идут снизу вверх; после каждой строки из nX значений пропускаются 2 байта (CR LF) без проверки. Узел (j,i) — значение номер inX+j, его координаты x=xmin+jΔ, y=ymin+iΔ.

Текст ошибки остаётся в cError; вид показывает его вместо сцены.

Единицы подписей. Координаты и время в подписях и строке состояния делятся на длину единицы из _LongUnit и _TimeUnit и подписываются её именем (например, «mm», «ns»).

Синхронизация с ядром. Протокол тот же, что у новой версии (протокол синхронизации): ядро, записав кадр, снимает с файла атрибут ARCHIVE; FieldView прочитав кадр, ставит его.

  • IsFileRead() = TRUE, если атрибуты файла равны ровно FILE_ATTRIBUTE_ARCHIVE.
  • SetSynchronizationFlag() уменьшает счётчик видов, ещё не прочитавших кадр; при нуле ставит ARCHIVE — разрешение ядру писать следующий кадр.
  • Деструктор документа возвращает файлу атрибут NORMAL.

В Linux атрибута ARCHIVE нет, его смысл повторяет слой совместимости: «снять» признак — значит записать в расширенный атрибут файла user.tmc_read_stamp время его последнего изменения; признак считается снятым, пока файл с тех пор не менялся. Если файловая система расширенных атрибутов не поддерживает, признак всегда «взведён» (подводные камни).

Вид

CFldViewView — всё остальное: настройки, подготовка данных и рисование.

Жизненный цикл.

  1. Конструктор задаёт значения по умолчанию, шкалы из 20 цветов поля и ε, цвета границ и создаёт (не показывая) окно уровней цвета.
  2. OnInitialUpdate — его вызывает MfcGLWidget::initializeGL, когда контекст OpenGL уже создан: чтение настроек, GL_Init, таймер 50 мс, ReadData.
  3. Таймер 1 каждые 50 мс вызывает UpdateAllViews → OnUpdate: если IsFileRead() = FALSE, кадр перечитывается (ReadData), сцена перерисовывается и ставится флаг синхронизации; при ошибке чтения — пауза 1 с.
  4. Двойной щелчок: пределы шкал поля и ε подбираются заново, файл перечитывается.
  5. Деструктор закрывает OpenGL и освобождает данные.

Подготовка данных (ReadData → PrepareData). Флаг bReadBusy на время перестройки массивов запрещает рисование и повторное чтение (таймер и двойной щелчок могут прийти во время чтения).

  1. Документ перечитывает файл. Если чтение удалось, вид освобождает свои данные и заново читает файл топологии (ReadTpl); если нет — данные вида не трогаются. (Статический признак «данные уже читались» в ReadData никогда не становится TRUE, поэтому другая ветка функции не выполняется.)
  2. Область показа [xmin,xmax]×[ymin,ymax] — в метрах от узла (0, 0) сетки: вся сетка, если включена автообласть, иначе заданная, ограниченная сеткой. nX, nY вида — число узлов в области.
  3. Автопределы шкалы поля: минимум и максимум значений в области; в режиме «по модулю» — zmax=max|z|, zmin=−zmax.
  4. Узлы переводятся в координаты сцены: массивы pdSurfaceX, pdSurfaceY, pdSurface.
  5. Слой ε (PrepareTpl), границы блоков (PrepareBoundaryTpl) и размерные линии (PrepareBoundTplSize) — топология.
  6. 20 уровней для окна уровней цвета: от середины шкалы до zmax с шагом (zmax−zmin)/38.

Сцена

DrawScene при каждой перерисовке:

  1. включает смешивание (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), очищает буферы цвета и глубины чёрным;
  2. ставит матрицу: сдвиг (tx,ty,tz), поворот на углы αX, αY, αZ (градусы) вокруг X, затем Y, затем Z;
  3. рисует по порядку: поле (DrawField), слой ε (DrawEps), границы блоков (DrawTopology), оси (DrawAxies), размеры области и оси Z шкал (DrawAxiesSize), размерные линии блоков (DrawSize);
  4. glFinish, смена буферов.

Перспектива (GL_Resize): угол обзора 30°, ближняя и дальняя плоскости 3 и 7, пропорции — по окну. По умолчанию сдвиг (−0,25; −0,25; −4,5), углы 0.

У поля, слоя ε и границ свой режим 2D/3D:

Слой 2D 3D
поле цветовая карта в плоскости, сетка линий на высоте 0,01 рельеф: высота узла — значение по шкале
ε цветовая карта рельеф по шкале ε
границы полосы на высоте 0,02, контуры на 0,03 призмы высотой от −0,25 до 0,25

Поверхность — четырёхугольник на ячейку сетки с цветами в вершинах (OpenGL интерполирует цвет внутри). Сетка линий рисуется цветами шкалы, а поверх поверхности — белым с непрозрачностью 0,8. Маркер «значение в точке» — треугольники между узлами слева, сверху и самой точкой (и т. п.), цвет — дополнение до 1 цвета шкалы.

Координаты сцены

Точка области показа переводится в координаты сцены линейно:

X=kx·2,5(x−xminxmax−xmin−0,4),Y=ky·2,5(y−yminymax−ymin−0,4),(1)

то есть область занимает [−1; 1,5] по каждой оси при k=1. При включённой пропорциональности меньшая сторона сжимается: kx=Δx/Δy, ky=1, если область уже по X, и наоборот.

Высота — по шкале поля или ε:

Z=2(z−zminzmax−zmin−0,5)∈[−1; 1].(2)

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

Шкала поля — 20 цветов pscSurfaceColor[0..19] (0 — низ шкалы). По высоте сцены Z∈[−1,1] цвет выбирается так (SetColor):

  • обычный режим: доля шкалы u=(Z+1)/2; в режиме «по модулю» u=|Z| (шкала симметрична, поэтому |Z|=|z|/zmax);
  • 20 ступеней: цвет номер int(19u);
  • плавная шкала («256 Resolution»): линейная смесь цветов 0 и 19 с долей u;
  • непрозрачность — nBlend/100.

Шкала слоя ε — отдельные 20 цветов, номер int(10+10Z), непрозрачность nBlend_Eps/100. Цвета по умолчанию: поле — от синего через зелёный и красный к жёлтому и белому; ε — от бирюзово-зелёного внизу к жёлтому вверху. Шкалы меняются на вкладках Field и Eps и в окне «Auto color» (уровни цвета).

Топология

Файл топологии .tt ищется рядом с файлом поля: путь без последнего расширения плюс .tt (SetTplFileName). Он читается, только если включено хоть что-то из «границы (контур или заливка)» и «слой ε (сетка или поверхность)». Формат — файл топологии.

CTmcBlockTpl::Read: признак формата, #BlockListBegin, список блоков (CTmcRTH_BlockList::Load), заголовок сетки (nT, Time, Delta, Xmin, Ymin, nX, nY — без точности и единиц), сетка ε (nXnY чисел double, после строки 2 байта). Если за ней есть ещё три сетки того же размера — это N (м⁻³), Y, B (Тл) X-ядра (единицы плазмы), HasPlasma() = 1, и становятся доступны команды выбора величины слоя: ε, N, Y, B (nEpsType 0–3). Без сеток плазмы любая выбранная величина показывается как ε.

Слой ε (PrepareTpl): из выбранной сетки вырезается та же область, что у поля (номер узла сетки — по шагу поля и числу узлов сетки топологии по X); автопределы — минимум и максимум в области; значения переводятся в высоты сцены.

Границы блоков (CTmcBoundaryTpl::SetBlockList). Для каждого блока списка строятся полосы — четырёхугольники шириной в шаг сетки Δ вдоль контура — и размерные линии; затем всё сдвигается на привязку блока (x0,y0):

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

У круга Xmin/Xmax записи — внутренний и внешний радиусы (м), Ymin/Ymax — углы φ0, φ1 (рад). Внешняя дуга радиуса R делится на

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

отрезков с шагом угла (φ1−φ0)/(n−1). Привязка рисуется двумя линиями: (0,y0)–(x0,y0) и (0,0)–(0,y0). Входы нумеруются по порядку блоков: «Inp 1», «Inp 2» …; подпись ставится в центре полосы входа.

Отбор видимого. Область показа расширяется на 1,1Δ. Полоса берётся, если хотя бы одна её вершина внутри и её тип включён флажками (ε, металл, магнитная стенка, поглотитель, входы). Размерная линия берётся, если внутри оба конца и длина больше 2Δ; её длина подписывается в единицах длины файла поля. Цвет полосы — по типу блока, непрозрачность — nBlendTopology.

Настройки

Все настройки показа хранятся в ini-файле программы (имя приложения FldView; где лежит файл — настройки программы), раздел #TMC_GraphicsOutputFieldFile. Вид читает их в OnInitialUpdate и пишет (WriteIniFile) после каждой команды. Значения — числа через пробел.

Ключ Содержимое
#TMC_GraphOutFld_DrFl общий флажок, пропорциональность
#TMC_GraphOutFld_DrFlSurface, _DrFlLine, _Fl23D, _Blend поверхность, сетка, 2D/3D, непрозрачность поля
#TMC_GraphOutFld_FlXSize, _FlYSize, _FlZSize автообласть по X, Y, автопределы Z поля
#TMC_GraphOutFld_Xmin … _Zmax область показа (м от узла (0, 0)) и пределы шкалы поля
#TMC_GraphOutFld_XAngle, _YAngle, _ZAngle углы сцены, градусы
#TMC_GraphOutFld_XTranslate, _YTranslate, _ZTranslate сдвиг сцены
#TMC_GraphOutFld_DrFlAxies, _ColorAxies, _FontAxies, _FontNameAxies, _Dr_FlAxiesSize оси: флажок, цвет (R G B), шрифт, размеры X/Y и оси Z
#TMC_GraphOutFld_ColorZField, _ColorZEps 20 цветов шкал поля и ε (COLORREF числами)
#TMC_GraphOutFld_Topology, _TopologyColor_EpsMetMagInp 12 флажков топологии; 5 цветов границ
#TMC_GraphOutFld_EpsParam, _EpsType параметры слоя ε; величина слоя 0–3
#TMC_GraphOutFld_ColorResolution, _DrawFieldModulFlag плавная шкала; поле по модулю
#TMC_GraphOutFld_PropertyPageNumber последняя вкладка окна свойств
#INIWND положение окна (пишет рамка MFC-версии)

Команда «Default» (ID_VIEW_DEFAULT12) возвращает значения по умолчанию: всё в 2D, сетка линий поля без поверхности, вся сетка, автопределы, углы 0, слой ε выключен, границы блоков (контур и заливка) и все их типы включены.

Окно свойств

Окно «Parameters» (CTMCDialogPropet, одно на программу — GetPropDialog()) открывается командой ID_VIEW_PARAMETERS или правым щелчком по сцене. Вид заполняет вкладки своими значениями (OnViewParameters), по OK забирает их все, пересчитывает сцену и сохраняет настройки. Кнопка «Применить» вкладки посылает виду своё сообщение; WPARAM и LPARAM не используются, вид берёт значения из той же вкладки:

Вкладка Сообщение Содержимое
Place WM_USERAPPLY_PROPPLACE область показа (в единицах длины файла, с учётом привязки сетки), автообласть X/Y, углы X и Y, сдвиг X и Y, оси (флажок, цвет, шрифт), размеры X/Y, пропорциональность; единицы — только показ
Topology WM_USERAPPLY_PROPTOPOL флажки типов границ, контур/заливка, 2D/3D, непрозрачность, цвета пяти типов, размеры блоков и привязки
Eps WM_USERAPPLY_PROPEPS 20 цветов, 2D/3D, непрозрачность, сетка/поверхность, автопределы и пределы, ось Z
Field WM_USERAPPLY_PROPFIELD 20 цветов, плавная шкала, 2D/3D, непрозрачность, сетка/поверхность, автопределы и пределы, ось Z, «по модулю»

Непрозрачность ограничивается видом диапазоном 0–100 %. Любое изменение элемента вкладки помечает её изменённой. Набор вкладок в слое совместимости — страницы свойств, обмен значениями — DDX/DDV.

Уровни цвета и автоподбор

Окно уровней цвета (CColorLevelDlg, команда ID_FIELD_L) — немодальное: 20 образцов цвета шкалы поля и рядом значение поля для каждого уровня. Значения заполняет вид в PrepareData: уровень k — zmid+k(zmax−zmin)/38, zmid=(zmin+zmax)/2. Введённые в окне числа виду не возвращаются. Окно закрывается сообщением WM_COLOR_LEVEL_DIALOG_BYE, которое оно посылает виду.

Окно «Auto color» (CTmcASetColor, кнопки вкладок Field и Eps) работает с копией шкалы; по OK копия переписывается в шкалу вкладки. Выбираются два уровня n1<n2 (не ближе 2):

  • «Change» — цвет уровня из окна выбора цвета;
  • «Auto set» — линейная интерполяция RGB между уровнями: цвета n1+1…n2−1 получают cn1+kd, d=(cn2−cn1)/(n2−n1) — целочисленно по каждой составляющей; концы не меняются;
  • «Auto set Red/Green/Blue» — то же, но выбранная составляющая поднимается к 256 в середине интервала (шаг 2(256−cn1)/(n2−n1) на первой половине, 2(cn2−256)/(n2−n1) — на второй).

Надписи в сцене

CTmcGLText рисует строку в точке сцены (x,y,z) — подписи осей, размеров, входов. Интерфейс общий (tmcgltext.h): SetFont (описание шрифта LOGFONT), SetColor (запоминает цвет), DrawString (рисует текущим цветом OpenGL), DrawInputNum («Inp n» запомненным цветом).

В Linux реализация — apps/fieldview/tmcgltext_qt.cpp:

  1. glRasterPos3f(x, y, z); если позиция вне области вывода — строка не рисуется;
  2. шрифт Qt строится по LOGFONT: высота lfHeight в пикселях, ширина знака — растяжением 100·lfWidth/средняя ширина знака (10–400 %);
  3. строка растрируется в QImage белым по прозрачному, маска покрытия переводится в RGBA с текущим цветом OpenGL (прозрачность = покрытие × альфа цвета);
  4. начало растра сдвигается на 2 пикселя вниз, вывод — glDrawPixels со смешиванием.

В MFC-версии (tmcgltext.cpp, в сборку не входит) растр строился средствами GDI и выводился glBitmap.

Оболочка Qt

main.cpp вызывает MfcGLWidget::setupSurfaceFormat() до создания QApplication — иначе старый код рисования получил бы профиль «ядро» и ничего бы не нарисовал; задаёт имя приложения FldView (раздел настроек, как у MFC-версии), показывает MainWindow и открывает файл из первого аргумента командной строки.

MainWindow:

  • строит меню (File, Edit, View с подменю Topology, Eps, Field, Zoom, Rotate, Translate, Change Xmax/Xmin, Change Ymax/Ymin, Window, Help) и панель из 35 кнопок по таблицам с подписями и клавишами из ресурсов MFC-версии;
  • создаёт рамку CMainFrame, привязывает её строку состояния к строке состояния Qt и ставит её главным окном приложения — так PutTrace (левая часть: границы области и шаг или значение в точке) и PutStatistics (правая часть: «nT = …; t = …») пишут в окно Qt;
  • открывает файл (openDocument): документ CFldViewDoc::TmcCreate(), вид CFldViewView::TmcCreate(), виджет MfcGLWidget в развёрнутом подокне MDI. Чтение файла и GL_Init выполняет OnInitialUpdate вида, когда Qt создаст контекст OpenGL;
  • направляет команды: сначала виду активного окна через карту сообщений, затем себе; таймер 200 мс опрашивает обработчики ON_UPDATE_COMMAND_UI вида и переносит отметки и доступность на меню и кнопки. Без открытого документа доступны только New, Open, Exit, About.

Команды

Номера команд — resource.h, обработчики — карта сообщений CFldViewView:

Группа Команды Действие
Повороты ID_ROTATE_*, ID_ROTATEXN/XV/YN/YV/ZN/ZV, движение мыши с нажатой левой кнопкой шаг 2° вокруг X, Y, Z
Сдвиг сцены ID_TRANSLATE_* шаг 0,04 единицы сцены
Сдвиг области ID_STRELK*, ID_TRANSLATEDATA* на шаг сетки; в режиме «значение в точке» двигается точка
Масштаб ID_VIEW_ZOOM_P/M, _PX/_MX, _PY/_MY область вдвое уже (не уже 2 шагов) или шире (шире сетки — вся сетка)
Слои ID_FLAGDRAWLINE*, ID_FLAGDRAWSURFACE*, ID_DIMENSION23SWITCH* (поле, …EPS, …TOP) сетка, поверхность, 2D/3D
Границы ID_VIEW_TOPOLOGY_BOUNDARY_EPS/METAL/MAGNETIC/INPUT/ABSORBER типы видимых границ
Размеры ID_VIEW_FIELD_SIZE, ID_VIEW_EPS_SIZE, ID_VIEW_TOPOLOGY_DIMENSIONS_*, ID_VIEW_TOPOLOGY_SIZE_* оси Z шкал, размер области по X/Y, размеры блоков и привязки
Поле ID_FIELD_VALUE, ID_FIELD_MODUL, ID_FIELD_L значение в точке, по модулю, окно уровней
Слой ε ID_EPS_TYPE_EPS/N/Y/B величина слоя; N, Y, B — только при сетках плазмы
Прочее ID_VIEW_PROPORTIONALLY, ID_VIEW_DEFAULT12, ID_VIEW_PARAMETERS пропорции, значения по умолчанию, окно свойств

Двойной щелчок — перечитать файл и подобрать шкалы заново; правый щелчок — окно свойств.

Разметки диалогов

Окна MFC-версии описаны в ресурсе FldView.rc. Сценарий tools/rc2ui.py порождает из него разметки Qt dialogs/IDD_*.ui и dialog_registry.cpp — таблицу, по которой слой совместимости строит элементы окна по номеру IDD_* и находит элементы по номерам IDC_* (ресурсы .rc → диалоги Qt). Порождённые файлы руками не правятся. Окна: «О программе», вкладки Topology, Place, Eps, Field, «Auto color» (IDD_DIALOGBARCOLORH), «Value for color level» (IDD_DIALOGBARCOLORH1).

Тестовые программы

Программа Запуск Что делает
fieldview_doccheck fieldview_doccheck <файл поля> читает файл документом без графики и печатает путь, nX, nY, шаг, такт и время, xmin, ymin. Код 0 — прочитан, 1 — ошибка (текст напечатан), 2 — файл не задан
fieldview_shot fieldview_shot <out.png> [файл поля] [ширина] [высота] [команда] снимает главное окно (по умолчанию 1130 × 700) с открытым файлом и, если задано, окном: parameters, level, about, номер команды, autocolor; printpdf — печать вида в PDF; --dialogs [папка] — снимки всех окон. Нужен настоящий экран (xcb): без него у OpenGL нет буфера кадра
fieldview_uitest fieldview_uitest [файл поля] [секунд на шаг] открывает файл, выполняет все доступные команды, меняет размер окна, щёлкает мышью; модальные окна закрываются таймером. Сторож на SIGALRM печатает зависший шаг и стек и выходит с кодом 2; код 3 — мышь осталась захваченной

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

  • Ошибка чтения файла поля не показывается. CFldViewView::ReadData переносит ошибку документа в вид только при удачном чтении. Если файл не открылся или повреждён, на экране остаётся прежний кадр (при открытии — пустая сцена) без текста ошибки. Текст «Error : …» появляется лишь для ошибок самого вида (топология, область показа).
  • Ошибка топологии гасит всю сцену. Если файл .tt нужен (включены границы или слой ε), но не найден или повреждён, ошибка ставится виду — и вместо поля выводится её текст. Выключите границы и слой ε на вкладках Topology и Eps.
  • Включение слоя ε или границ вступает в силу после следующего чтения кадра (таймер или двойной щелчок): файл .tt читается только в ReadData.
  • Сетка .tt не сверяется с сеткой файла поля. Слой ε берёт область по шагу и размерам поля, а шаг строки — по nX топологии. Если файлы от разных расчётов, слой будет сдвинут или чтение выйдет за массив.
  • Автоматическое обновление и файловая система. На файловой системе без расширенных атрибутов (например, раздел Windows, подключённый в /mnt) признак ARCHIVE всегда «взведён»: IsFileRead() = TRUE, новые кадры ядра не подхватываются — только двойным щелчком. Ядро при этом не ждёт FieldView.
  • CR LF между строками значений не проверяются. Текстовый вывод поля или повреждённый файл читается как числа без ошибки.
  • Дуга круга длиннее сектора на один отрезок: шаг угла (φ1−φ0)/(n−1), а отрезков n (в новой версии исправлено).
  • Блоки плазмы (RECT_STAT_N и т. п.) границ не получают — их видно только в слое N/Y/B.
  • Файл топологии ищется только как .tt в нижнем регистре (Linux различает регистр).
  • Окно уровней цвета только показывает значения: правка чисел в нём шкалу не меняет.

FieldView for Linux — viewing fields with OpenGL 1.x

Purpose and place in the package

FieldView shows the field distribution that a compute kernel has written to a field file (.ex, .tf, .AMP, .FAZ …) during or after a computation: a relief or a color map of the value at the grid nodes, a layer of the ε distribution (for the X kernel also of the plasma electron density N, losses Y and field B) and the boundaries of the task file blocks. What quantity is in the file and how it was obtained — field output by the kernel, H kernel fields, X kernel fields.

This page describes the non-Windows build (Linux). In the Windows build it is replaced by the new FieldView on Qt RHI — apps/fieldview_rhi. The choice is made by src/CMakeLists.txt: outside Windows apps/fieldview is included, on Windows — apps/fieldview_rhi.

The Linux version is the FieldView code of the former (MFC) version from src/fieldview, compiled without changes on top of the compatibility layer, plus a small Qt shell src/fieldview. Drawing uses old OpenGL (glBegin/glEnd, matrices, no shaders): the context is provided by QOpenGLWidget (OpenGL view host widget), and the wgl* calls are stubs (OpenGL in the compatibility layer).

How the Linux version differs from FieldView on Qt RHI:

Linux (apps/fieldview) Windows (apps/fieldview_rhi)
Code MFC version without changes + compatibility layer rewritten on Qt 6
Rendering OpenGL 1.x, 2.1 compatibility profile Qt RHI (D3D11/OpenGL), shaders
Field file one frame, re-read on change frame, time-step history, .frames series
Topology re-read with every frame, the grid is not checked against the field file re-read on change, the grid is checked
Color scale 20 colors or a smooth blend of the end colors several palettes
Animation, GIF no yes

The file formats are the same in both versions: field file, topology file .tt.

Contents

File Role
src/fieldview/fldviewdoc.h/.cpp CFldViewDoc — document: reading the field file, units, synchronization with the kernel
src/fieldview/fldviewview.h/.cpp CFldViewView — view: settings, data preparation, the OpenGL scene, all commands; status bar functions PutTrace, PutStatistics; property window GetPropDialog()
src/fieldview/tmcblocktpl.h/.cpp CTmcBlockTpl — the topology file .tt: list of blocks, grids of ε, N, Y, B
src/fieldview/tmcboundarytpl.h/.cpp CTmcBoundaryTpl — boundaries of one block: bands along the contour, dimension lines
src/fieldview/tmctopsize.h/.cpp CTmcTopSize — a dimension line
src/fieldview/tmcgltext.h CTmcGLText — a label at a point of the scene (Linux implementation — apps/fieldview/tmcgltext_qt.cpp)
src/fieldview/tmcdialogpropet.h/.cpp CTMCDialogPropet — the "Parameters" property window
src/fieldview/tmcdialogplace.h/.cpp the "Place" tab — display region, angles, axes
src/fieldview/tmcdialogtopology.h/.cpp the "Topology" tab — block boundaries
src/fieldview/tmcdialogeps.h/.cpp the "Eps" tab — the ε layer
src/fieldview/tmcdialogfield.h/.cpp the "Field" tab — the field
src/fieldview/colorleveldlg.h/.cpp CColorLevelDlg — color level window (the field value for each of the 20 colors)
src/fieldview/tmcasetcolor.h/.cpp CTmcASetColor — the "Auto color" window: editing and automatic selection of the 20 scale colors
src/fieldview/mainfrm.h/.cpp CMainFrame — the frame; on Linux it is needed for the status bar
src/fieldview/fldview.h tab messages WM_USERAPPLY_PROP*, MFC application class (not created)
src/fieldview/resource.h numbers of windows, controls and commands (commands)
src/fieldview/stdafx.h MFC headers (here — of the compatibility layer)
apps/fieldview/main.cpp fieldview entry point
apps/fieldview/mainwindow.h/.cpp MainWindow — menu, toolbar, status bar, MDI document windows
apps/fieldview/tmcgltext_qt.cpp CTmcGLText methods through QImage and glDrawPixels
apps/fieldview/dialogs/dialog_registry.cpp, dialogs/*.ui window layouts generated from the FldView.rc resource
apps/fieldview/testtools/*.cpp test programs (below)

Not included in the build (only a header in the file): fldview.cpp (the MFC application and the About dialog), childfrm.h/.cpp (MDI child window), stdafx.cpp, tmcgltext.cpp (label raster by GDI means) and tmcrth_blocklist1.h/.cpp (an empty descendant of CTmcRTH_BlockList that includes a header by an absolute path on someone else's machine).

Build

apps/fieldview/CMakeLists.txt builds four targets:

Target Contents Dependencies
fieldview_core (library) fldviewdoc.cpp, tmcblocktpl.cpp, tmcboundarytpl.cpp, tmctopsize.cpp — without the Qt interface compatibility layer tmc_platform
fieldview_view (library) view, frame, property window and its tabs, color windows, tmcgltext_qt.cpp fieldview_core, tmc_gui_common, GL, GLU
fieldview_gui (library) mainwindow.cpp, dialog_registry.cpp, dialogs/*.ui, icon resources fieldview_view, Qt Widgets
fieldview (program) main.cpp fieldview_gui

The code from src/libs, src/kernels, src/viewers is compiled with -fpermissive -w. The test programs fieldview_doccheck, fieldview_shot, fieldview_uitest are not included in the distribution.

Document

CFldViewDoc is one open field file. The shell creates it together with the view when a file is opened; the document has one view.

Reading (ReadData): the previous data are discarded, the file is opened in binary mode, the header lines are parsed, memory is allocated and the values are read. Format — field file.

Reading the field file

  1. ReadDataParameters reads the 10 header lines strictly in order: #TMC_GraphicsOutputFieldFile, _nT, _Time (s), _Delta (m), _Xmin, _Ymin (m), _Accuracy, _LongUnit (name and length of the unit in meters), _TimeUnit (name and duration in seconds), _nX, _nY. Each line is compared by its beginning with the tag from tmcgrviw.h; the number is read by sscanf. A mismatch or end of file is the error "bad data file".
  2. InitAllocationArray requires nX≥2, nY≥2 and allocates nXnY double numbers.
  3. ReadDataArray reads the values: Accuracy 4 — float, 8 — double, otherwise the error "abnormal accuracy". Rows go from bottom to top; after each row of nX values 2 bytes (CR LF) are skipped without checking. Node (j,i) is value number inX+j, its coordinates are x=xmin+jΔ, y=ymin+iΔ.

The error text remains in cError; the view shows it instead of the scene.

Label units. Coordinates and time in the labels and the status bar are divided by the length of the unit from _LongUnit and _TimeUnit and labeled with its name (for example, "mm", "ns").

Synchronization with the kernel. The protocol is the same as in the new version (synchronization protocol): the kernel, having written a frame, clears the ARCHIVE attribute of the file; FieldView, having read the frame, sets it.

  • IsFileRead() = TRUE if the file attributes are exactly FILE_ATTRIBUTE_ARCHIVE.
  • SetSynchronizationFlag() decrements the counter of views that have not yet read the frame; at zero it sets ARCHIVE — permission for the kernel to write the next frame.
  • The document destructor gives the file back the NORMAL attribute.

Linux has no ARCHIVE attribute; its meaning is reproduced by the compatibility layer: to "clear" the flag means to write the time of the file's last modification into the extended file attribute user.tmc_read_stamp; the flag is considered cleared as long as the file has not changed since then. If the file system does not support extended attributes, the flag is always "set" (pitfalls).

View

CFldViewView is everything else: settings, data preparation and drawing.

Life cycle.

  1. The constructor sets the default values, the 20-color scales of the field and ε, the boundary colors, and creates (without showing) the color level window.
  2. OnInitialUpdate — called by MfcGLWidget::initializeGL when the OpenGL context has already been created: reading the settings, GL_Init, a 50 ms timer, ReadData.
  3. Timer 1 calls UpdateAllViews → OnUpdate every 50 ms: if IsFileRead() = FALSE, the frame is re-read (ReadData), the scene is redrawn and the synchronization flag is set; on a read error — a 1 s pause.
  4. Double click: the limits of the field and ε scales are fitted again, the file is re-read.
  5. The destructor closes OpenGL and frees the data.

Data preparation (ReadData → PrepareData). The bReadBusy flag forbids drawing and repeated reading while the arrays are being rebuilt (the timer and a double click may arrive during reading).

  1. The document re-reads the file. If reading succeeded, the view frees its data and reads the topology file anew (ReadTpl); if not, the view data are left untouched. (The static flag "data have already been read" in ReadData never becomes TRUE, so the other branch of the function is never executed.)
  2. The display region [xmin,xmax]×[ymin,ymax] is in meters from node (0, 0) of the grid: the whole grid if the automatic region is on, otherwise the specified one, limited by the grid. nX, nY of the view are the number of nodes in the region.
  3. Automatic limits of the field scale: the minimum and maximum of the values in the region; in "modulus" mode — zmax=max|z|, zmin=−zmax.
  4. The nodes are converted to scene coordinates: the arrays pdSurfaceX, pdSurfaceY, pdSurface.
  5. The ε layer (PrepareTpl), block boundaries (PrepareBoundaryTpl) and dimension lines (PrepareBoundTplSize) — topology.
  6. 20 levels for the color level window: from the middle of the scale to zmax with the step (zmax−zmin)/38.

Scene

DrawScene on every redraw:

  1. enables blending (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), clears the color and depth buffers to black;
  2. sets the matrix: translation (tx,ty,tz), rotation by the angles αX, αY, αZ (degrees) about X, then Y, then Z;
  3. draws in order: the field (DrawField), the ε layer (DrawEps), block boundaries (DrawTopology), axes (DrawAxies), region dimensions and the Z axes of the scales (DrawAxiesSize), block dimension lines (DrawSize);
  4. glFinish, buffer swap.

Perspective (GL_Resize): field of view 30°, near and far planes 3 and 7, aspect ratio from the window. By default the translation is (−0,25; −0,25; −4,5), the angles are 0.

The field, the ε layer and the boundaries each have their own 2D/3D mode:

Layer 2D 3D
field color map in the plane, line grid at height 0.01 relief: node height is the value on the scale
ε color map relief on the ε scale
boundaries bands at height 0.02, contours at 0.03 prisms with height from −0,25 to 0,25

The surface is one quadrilateral per grid cell with colors at the vertices (OpenGL interpolates the color inside). The line grid is drawn in the scale colors, and on top of the surface — in white with opacity 0.8. The "value at a point" marker is triangles between the nodes on the left, at the top and the point itself (and so on); its color is the complement to 1 of the scale color.

Scene coordinates

A point of the display region is converted to scene coordinates linearly:

X=kx·2,5(x−xminxmax−xmin−0,4),Y=ky·2,5(y−yminymax−ymin−0,4),(1)

that is, the region occupies [−1; 1,5] along each axis at k=1. With proportional mode enabled, the shorter side is compressed: kx=Δx/Δy, ky=1 if the region is narrower in X, and vice versa.

Height — on the field or ε scale:

Z=2(z−zminzmax−zmin−0,5)∈[−1; 1].(2)

Color scale

The field scale is 20 colors pscSurfaceColor[0..19] (0 is the bottom of the scale). From the scene height Z∈[−1,1] the color is chosen as follows (SetColor):

  • normal mode: the scale fraction u=(Z+1)/2; in "modulus" mode u=|Z| (the scale is symmetric, so |Z|=|z|/zmax);
  • 20 steps: color number int(19u);
  • smooth scale ("256 Resolution"): a linear blend of colors 0 and 19 with the fraction u;
  • opacity — nBlend/100.

The scale of the ε layer is a separate set of 20 colors, number int(10+10Z), opacity nBlend_Eps/100. Default colors: field — from blue through green and red to yellow and white; ε — from turquoise green at the bottom to yellow at the top. The scales are changed on the Field and Eps tabs and in the "Auto color" window (color levels).

Topology

The topology file .tt is looked up next to the field file: the path without the last extension plus .tt (SetTplFileName). It is read only if at least one of "boundaries (contour or fill)" and "ε layer (grid or surface)" is enabled. Format — topology file.

CTmcBlockTpl::Read: format tag, #BlockListBegin, list of blocks (CTmcRTH_BlockList::Load), grid header (nT, Time, Delta, Xmin, Ymin, nX, nY — without precision and units), the ε grid (nXnY double numbers, 2 bytes after each row). If it is followed by three more grids of the same size, these are N (m⁻³), Y, B (T) of the X kernel (plasma units), HasPlasma() = 1, and the commands for choosing the layer quantity become available: ε, N, Y, B (nEpsType 0–3). Without plasma grids any chosen quantity is shown as ε.

The ε layer (PrepareTpl): the same region as for the field is cut out of the chosen grid (the grid node number — from the field step and the number of nodes of the topology grid in X); automatic limits — the minimum and maximum in the region; the values are converted into scene heights.

Block boundaries (CTmcBoundaryTpl::SetBlockList). For each block of the list, bands — quadrilaterals one grid step Δ wide along the contour — and dimension lines are built; then everything is shifted by the block anchor (x0,y0):

Block kind Bands Dimensions
RECT_STAT, RECT_MOVE, FILE, FILE_N/_B/_Y (as ε) 4 sides of the rectangle, each widened by ±Δ/2 height, width
POLYGON_STAT, POLYGON_MOVE one band per side, stretched along the larger projection; the closing side — only for an ε block lengths of all sides
CIRCLE_STAT, CIRCLE_MOVE outer arc; with an inner radius >Δ — two radial segments and the inner arc radii
INPUT_X band along the Y axis: x∈[−Δ/2,Δ/2] aperture
INPUT_Y band along the X axis: y∈[−Δ/2,Δ/2] aperture
others (including *_STAT_N/_B/_Y) none none

For a circle, Xmin/Xmax of the record are the inner and outer radii (m), Ymin/Ymax are the angles φ0, φ1 (rad). The outer arc of radius R is divided into

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

segments with the angle step (φ1−φ0)/(n−1). The anchor is drawn with two lines: (0,y0)–(x0,y0) and (0,0)–(0,y0). Ports are numbered in block order: "Inp 1", "Inp 2" …; the label is placed at the center of the port band.

Selecting what is visible. The display region is expanded by 1,1Δ. A band is taken if at least one of its vertices is inside and its type is enabled by the check boxes (ε, metal, magnetic wall, absorber, ports). A dimension line is taken if both its ends are inside and its length is greater than 2Δ; its length is labeled in the length units of the field file. The band color is by the type of the block, the opacity is nBlendTopology.

Settings

All display settings are stored in the ini file of the program (application name FldView; where the file is located — program settings), section #TMC_GraphicsOutputFieldFile. The view reads them in OnInitialUpdate and writes them (WriteIniFile) after every command. The values are numbers separated by spaces.

Key Contents
#TMC_GraphOutFld_DrFl common flag, proportional mode
#TMC_GraphOutFld_DrFlSurface, _DrFlLine, _Fl23D, _Blend surface, grid, 2D/3D, field opacity
#TMC_GraphOutFld_FlXSize, _FlYSize, _FlZSize automatic region in X, Y, automatic Z limits of the field
#TMC_GraphOutFld_Xmin … _Zmax display region (m from node (0, 0)) and field scale limits
#TMC_GraphOutFld_XAngle, _YAngle, _ZAngle scene angles, degrees
#TMC_GraphOutFld_XTranslate, _YTranslate, _ZTranslate scene translation
#TMC_GraphOutFld_DrFlAxies, _ColorAxies, _FontAxies, _FontNameAxies, _Dr_FlAxiesSize axes: flag, color (R G B), font, X/Y dimensions and the Z axis
#TMC_GraphOutFld_ColorZField, _ColorZEps 20 colors of the field and ε scales (COLORREF as numbers)
#TMC_GraphOutFld_Topology, _TopologyColor_EpsMetMagInp 12 topology flags; 5 boundary colors
#TMC_GraphOutFld_EpsParam, _EpsType parameters of the ε layer; layer quantity 0–3
#TMC_GraphOutFld_ColorResolution, _DrawFieldModulFlag smooth scale; field by modulus
#TMC_GraphOutFld_PropertyPageNumber last tab of the property window
#INIWND window position (written by the frame of the MFC version)

The "Default" command (ID_VIEW_DEFAULT12) restores the default values: everything in 2D, the field line grid without the surface, the whole grid, automatic limits, angles 0, the ε layer off, block boundaries (contour and fill) and all their types on.

Property window

The "Parameters" window (CTMCDialogPropet, one per program — GetPropDialog()) is opened by the ID_VIEW_PARAMETERS command or by a right click on the scene. The view fills the tabs with its values (OnViewParameters), on OK takes them all back, recomputes the scene and saves the settings. The "Apply" button of a tab sends the view its own message; WPARAM and LPARAM are not used, the view takes the values from the same tab:

Tab Message Contents
Place WM_USERAPPLY_PROPPLACE display region (in the length units of the file, taking the grid anchor into account), automatic region X/Y, angles X and Y, translation X and Y, axes (flag, color, font), X/Y dimensions, proportional mode; units — display only
Topology WM_USERAPPLY_PROPTOPOL flags of boundary types, contour/fill, 2D/3D, opacity, colors of the five types, block and anchor dimensions
Eps WM_USERAPPLY_PROPEPS 20 colors, 2D/3D, opacity, grid/surface, automatic limits and limits, Z axis
Field WM_USERAPPLY_PROPFIELD 20 colors, smooth scale, 2D/3D, opacity, grid/surface, automatic limits and limits, Z axis, "by modulus"

The view limits the opacity to the range 0–100 %. Any change of a control of a tab marks it as modified. The set of tabs in the compatibility layer — property pages, value exchange — DDX/DDV.

Color levels and automatic selection

The color level window (CColorLevelDlg, the ID_FIELD_L command) is modeless: 20 color samples of the field scale and next to them the field value for each level. The values are filled in by the view in PrepareData: level k — zmid+k(zmax−zmin)/38, zmid=(zmin+zmax)/2. Numbers entered in the window are not returned to the view. The window is closed by the WM_COLOR_LEVEL_DIALOG_BYE message, which it sends to the view.

The "Auto color" window (CTmcASetColor, buttons of the Field and Eps tabs) works with a copy of the scale; on OK the copy is written into the scale of the tab. Two levels n1<n2 are selected (no closer than 2):

  • "Change" — the level color from the color picker;
  • "Auto set" — linear RGB interpolation between the levels: colors n1+1…n2−1 get cn1+kd, d=(cn2−cn1)/(n2−n1) — in integers for each component; the ends are not changed;
  • "Auto set Red/Green/Blue" — the same, but the selected component rises toward 256 in the middle of the interval (step 2(256−cn1)/(n2−n1) in the first half, 2(cn2−256)/(n2−n1) — in the second).

Labels in the scene

CTmcGLText draws a string at a scene point (x,y,z) — labels of axes, dimensions, ports. The interface is common (tmcgltext.h): SetFont (a LOGFONT font description), SetColor (remembers the color), DrawString (draws in the current OpenGL color), DrawInputNum ("Inp n" in the remembered color).

On Linux the implementation is apps/fieldview/tmcgltext_qt.cpp:

  1. glRasterPos3f(x, y, z); if the position is outside the viewport, the string is not drawn;
  2. the Qt font is built from the LOGFONT: height lfHeight in pixels, character width — by stretching 100·lfWidth/average character width (10–400 %);
  3. the string is rasterized into a QImage as white on transparent, and the coverage mask is converted to RGBA with the current OpenGL color (transparency = coverage × color alpha);
  4. the raster origin is shifted 2 pixels down, output is by glDrawPixels with blending.

In the MFC version (tmcgltext.cpp, not included in the build) the raster was built by GDI means and output with glBitmap.

Qt shell

main.cpp calls MfcGLWidget::setupSurfaceFormat() before QApplication is created — otherwise the old drawing code would get the "core" profile and would draw nothing; it sets the application name FldView (the settings section, as in the MFC version), shows MainWindow and opens the file from the first command-line argument.

MainWindow:

  • builds the menu (File, Edit, View with the submenus Topology, Eps, Field, Zoom, Rotate, Translate, Change Xmax/Xmin, Change Ymax/Ymin, Window, Help) and a toolbar of 35 buttons from tables with captions and shortcuts from the MFC version resources;
  • creates the CMainFrame frame, binds its status bar to the Qt status bar and makes it the main window of the application — so that PutTrace (left part: region bounds and step, or the value at a point) and PutStatistics (right part: "nT = …; t = …") write to the Qt window;
  • opens a file (openDocument): the document CFldViewDoc::TmcCreate(), the view CFldViewView::TmcCreate(), the widget MfcGLWidget in a maximized MDI subwindow. Reading the file and GL_Init are performed by OnInitialUpdate of the view once Qt has created the OpenGL context;
  • dispatches commands: first to the view of the active window through the message map, then to itself; a 200 ms timer polls the ON_UPDATE_COMMAND_UI handlers of the view and transfers check marks and availability to the menu and the buttons. Without an open document only New, Open, Exit, About are available.

Commands

Command numbers — resource.h, handlers — the message map of CFldViewView:

Group Commands Action
Rotation ID_ROTATE_*, ID_ROTATEXN/XV/YN/YV/ZN/ZV, mouse movement with the left button pressed step of 2° about X, Y, Z
Scene translation ID_TRANSLATE_* step of 0.04 scene units
Region shift ID_STRELK*, ID_TRANSLATEDATA* by one grid step; in "value at a point" mode the point moves
Zoom ID_VIEW_ZOOM_P/M, _PX/_MX, _PY/_MY region twice as narrow (not narrower than 2 steps) or twice as wide (wider than the grid — the whole grid)
Layers ID_FLAGDRAWLINE*, ID_FLAGDRAWSURFACE*, ID_DIMENSION23SWITCH* (field, …EPS, …TOP) grid, surface, 2D/3D
Boundaries ID_VIEW_TOPOLOGY_BOUNDARY_EPS/METAL/MAGNETIC/INPUT/ABSORBER types of visible boundaries
Dimensions ID_VIEW_FIELD_SIZE, ID_VIEW_EPS_SIZE, ID_VIEW_TOPOLOGY_DIMENSIONS_*, ID_VIEW_TOPOLOGY_SIZE_* Z axes of the scales, region size in X/Y, block and anchor dimensions
Field ID_FIELD_VALUE, ID_FIELD_MODUL, ID_FIELD_L value at a point, by modulus, level window
ε layer ID_EPS_TYPE_EPS/N/Y/B layer quantity; N, Y, B — only with plasma grids
Other ID_VIEW_PROPORTIONALLY, ID_VIEW_DEFAULT12, ID_VIEW_PARAMETERS proportions, default values, property window

Double click — re-read the file and fit the scales again; right click — the property window.

Dialog layouts

The windows of the MFC version are described in the FldView.rc resource. The script tools/rc2ui.py generates from it the Qt layouts dialogs/IDD_*.ui and dialog_registry.cpp — the table by which the compatibility layer builds the controls of a window by its IDD_* number and finds controls by their IDC_* numbers (.rc resources → Qt dialogs). The generated files are not edited by hand. Windows: About, the Topology, Place, Eps, Field tabs, "Auto color" (IDD_DIALOGBARCOLORH), "Value for color level" (IDD_DIALOGBARCOLORH1).

Test programs

Program Invocation What it does
fieldview_doccheck fieldview_doccheck <field file> reads the file with the document without graphics and prints the path, nX, nY, step, time step and time, xmin, ymin. Code 0 — read, 1 — error (the text is printed), 2 — no file given
fieldview_shot fieldview_shot <out.png> [field file] [width] [height] [command] captures the main window (1130 × 700 by default) with the file open and, if given, a window: parameters, level, about, a command number, autocolor; printpdf — printing the view to PDF; --dialogs [folder] — screenshots of all windows. A real display (xcb) is required: without it OpenGL has no framebuffer
fieldview_uitest fieldview_uitest [field file] [seconds per step] opens the file, executes all available commands, resizes the window, clicks the mouse; modal windows are closed by a timer. A SIGALRM watchdog prints the hung step and the stack and exits with code 2; code 3 — the mouse remained captured

Typical errors and pitfalls

  • A field file read error is not shown. CFldViewView::ReadData transfers the document error to the view only on a successful read. If the file did not open or is corrupted, the previous frame remains on the screen (on opening — an empty scene) without an error text. The text "Error : …" appears only for errors of the view itself (topology, display region).
  • A topology error blanks the whole scene. If the .tt file is needed (boundaries or the ε layer are enabled) but is not found or is corrupted, the error is set on the view — and its text is output instead of the field. Turn off the boundaries and the ε layer on the Topology and Eps tabs.
  • Enabling the ε layer or the boundaries takes effect after the next read of a frame (timer or double click): the .tt file is read only in ReadData.
  • The .tt grid is not checked against the grid of the field file. The ε layer takes the region from the step and sizes of the field, and the row stride from the nX of the topology. If the files come from different computations, the layer will be shifted or reading will go beyond the array.
  • Automatic update and the file system. On a file system without extended attributes (for example, a Windows partition mounted under /mnt) the ARCHIVE flag is always "set": IsFileRead() = TRUE, new kernel frames are not picked up — only by a double click. The kernel then does not wait for FieldView.
  • The CR LF between rows of values is not checked. A text field output or a corrupted file is read as numbers without an error.
  • The circle arc is one segment longer than the sector: the angle step is (φ1−φ0)/(n−1), but there are n segments (fixed in the new version).
  • Plasma blocks (RECT_STAT_N and so on) get no boundaries — they are visible only in the N/Y/B layer.
  • The topology file is looked up only as .tt in lower case (Linux is case-sensitive).
  • The color level window only shows values: editing the numbers in it does not change the scale.