FieldView для Linux — просмотр полей через OpenGL 1.x
Назначение и место в пакете
FieldView показывает распределение поля, которое счётное ядро записало в файл поля
(.ex, .tf, .AMP, .FAZ …) во время или после расчёта: рельеф или цветовую карту
значения в узлах сетки, слой распределения (у X-ядра — также концентрации
, потерь и поля плазмы) и границы блоков задания. Что за величина лежит в
файле и как она получена — вывод поля ядром,
поля 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: список блоков, сетки , , , |
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): прежние данные сбрасываются, файл открывается в двоичном
режиме, разбираются строки заголовка, выделяется память и читаются значения. Формат —
файл поля.
Чтение файла поля
ReadDataParametersчитает 10 строк заголовка строго по порядку:#TMC_GraphicsOutputFieldFile,_nT,_Time(с),_Delta(м),_Xmin,_Ymin(м),_Accuracy,_LongUnit(имя и длина единицы в метрах),_TimeUnit(имя и длительность в секундах),_nX,_nY. Каждая строка сверяется по началу с признаком изtmcgrviw.h; число читаетсяsscanf. Несовпадение или конец файла — ошибка «bad data file».InitAllocationArrayтребует , и выделяет чиселdouble.ReadDataArrayчитает значения:Accuracy4 —float, 8 —double, иначе ошибка «abnormal accuracy». Строки идут снизу вверх; после каждой строки из значений пропускаются 2 байта (CR LF) без проверки. Узел — значение номер , его координаты , .
Текст ошибки остаётся в cError; вид показывает его вместо сцены.
Единицы подписей. Координаты и время в подписях и строке состояния делятся на длину
единицы из _LongUnit и _TimeUnit и подписываются её именем (например, «mm», «ns»).
Синхронизация с ядром. Протокол тот же, что у новой версии (протокол синхронизации): ядро, записав кадр, снимает с файла атрибут ARCHIVE; FieldView прочитав кадр, ставит его.
IsFileRead()= TRUE, если атрибуты файла равны ровноFILE_ATTRIBUTE_ARCHIVE.SetSynchronizationFlag()уменьшает счётчик видов, ещё не прочитавших кадр; при нуле ставит ARCHIVE — разрешение ядру писать следующий кадр.- Деструктор документа возвращает файлу атрибут NORMAL.
В Linux атрибута ARCHIVE нет, его смысл повторяет слой совместимости: «снять» признак —
значит записать в расширенный атрибут файла user.tmc_read_stamp время его последнего
изменения; признак считается снятым, пока файл с тех пор не менялся. Если файловая
система расширенных атрибутов не поддерживает, признак всегда «взведён»
(подводные камни).
Вид
CFldViewView — всё остальное: настройки, подготовка данных и рисование.
Жизненный цикл.
- Конструктор задаёт значения по умолчанию, шкалы из 20 цветов поля и , цвета границ и создаёт (не показывая) окно уровней цвета.
OnInitialUpdate— его вызываетMfcGLWidget::initializeGL, когда контекст OpenGL уже создан: чтение настроек,GL_Init, таймер 50 мс,ReadData.- Таймер 1 каждые 50 мс вызывает
UpdateAllViews→OnUpdate: еслиIsFileRead()= FALSE, кадр перечитывается (ReadData), сцена перерисовывается и ставится флаг синхронизации; при ошибке чтения — пауза 1 с. - Двойной щелчок: пределы шкал поля и подбираются заново, файл перечитывается.
- Деструктор закрывает OpenGL и освобождает данные.
Подготовка данных (ReadData → PrepareData). Флаг bReadBusy на время
перестройки массивов запрещает рисование и повторное чтение (таймер и двойной щелчок
могут прийти во время чтения).
- Документ перечитывает файл. Если чтение удалось, вид освобождает свои данные и
заново читает файл топологии (
ReadTpl); если нет — данные вида не трогаются. (Статический признак «данные уже читались» вReadDataникогда не становится TRUE, поэтому другая ветка функции не выполняется.) - Область показа — в метрах от узла (0, 0) сетки: вся сетка, если включена автообласть, иначе заданная, ограниченная сеткой. , вида — число узлов в области.
- Автопределы шкалы поля: минимум и максимум значений в области; в режиме «по модулю» — , .
- Узлы переводятся в координаты сцены: массивы
pdSurfaceX,pdSurfaceY,pdSurface. - Слой (
PrepareTpl), границы блоков (PrepareBoundaryTpl) и размерные линии (PrepareBoundTplSize) — топология. - 20 уровней для окна уровней цвета: от середины шкалы до с шагом .
Сцена
DrawScene при каждой перерисовке:
- включает смешивание (
GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), очищает буферы цвета и глубины чёрным; - ставит матрицу: сдвиг , поворот на углы , , (градусы) вокруг X, затем Y, затем Z;
- рисует по порядку: поле (
DrawField), слой (DrawEps), границы блоков (DrawTopology), оси (DrawAxies), размеры области и оси Z шкал (DrawAxiesSize), размерные линии блоков (DrawSize); glFinish, смена буферов.
Перспектива (GL_Resize): угол обзора 30°, ближняя и дальняя плоскости 3 и 7, пропорции —
по окну. По умолчанию сдвиг , углы 0.
У поля, слоя и границ свой режим 2D/3D:
| Слой | 2D | 3D |
|---|---|---|
| поле | цветовая карта в плоскости, сетка линий на высоте 0,01 | рельеф: высота узла — значение по шкале |
| цветовая карта | рельеф по шкале | |
| границы | полосы на высоте 0,02, контуры на 0,03 | призмы высотой от до |
Поверхность — четырёхугольник на ячейку сетки с цветами в вершинах (OpenGL интерполирует цвет внутри). Сетка линий рисуется цветами шкалы, а поверх поверхности — белым с непрозрачностью 0,8. Маркер «значение в точке» — треугольники между узлами слева, сверху и самой точкой (и т. п.), цвет — дополнение до 1 цвета шкалы.
Координаты сцены
Точка области показа переводится в координаты сцены линейно:
то есть область занимает по каждой оси при . При включённой пропорциональности меньшая сторона сжимается: , , если область уже по X, и наоборот.
Высота — по шкале поля или :
Цветовая шкала
Шкала поля — 20 цветов pscSurfaceColor[0..19] (0 — низ шкалы). По высоте сцены
цвет выбирается так (SetColor):
- обычный режим: доля шкалы ; в режиме «по модулю» (шкала симметрична, поэтому );
- 20 ступеней: цвет номер ;
- плавная шкала («256 Resolution»): линейная смесь цветов 0 и 19 с долей ;
- непрозрачность —
nBlend/100.
Шкала слоя — отдельные 20 цветов, номер ,
непрозрачность nBlend_Eps/100. Цвета по умолчанию: поле — от синего через зелёный и
красный к жёлтому и белому; — от бирюзово-зелёного внизу к жёлтому вверху. Шкалы меняются на
вкладках Field и Eps и в окне «Auto color» (уровни цвета).
Топология
Файл топологии .tt ищется рядом с файлом поля: путь без последнего расширения плюс
.tt (SetTplFileName). Он читается, только если включено хоть что-то из «границы
(контур или заливка)» и «слой (сетка или поверхность)». Формат —
файл топологии.
CTmcBlockTpl::Read: признак формата, #BlockListBegin, список блоков
(CTmcRTH_BlockList::Load), заголовок сетки (nT, Time, Delta, Xmin, Ymin, nX,
nY — без точности и единиц), сетка ( чисел double, после строки 2
байта). Если за ней есть ещё три сетки того же размера — это (м⁻³), , (Тл)
X-ядра (единицы плазмы), HasPlasma() = 1, и становятся
доступны команды выбора величины слоя: , , , (nEpsType 0–3). Без
сеток плазмы любая выбранная величина показывается как .
Слой (PrepareTpl): из выбранной сетки вырезается та же область, что у
поля (номер узла сетки — по шагу поля и числу узлов сетки топологии по X);
автопределы — минимум и максимум в области; значения переводятся в высоты сцены.
Границы блоков (CTmcBoundaryTpl::SetBlockList). Для каждого блока списка строятся
полосы — четырёхугольники шириной в шаг сетки вдоль контура — и размерные линии;
затем всё сдвигается на привязку блока :
| Вид блока | Полосы | Размеры |
|---|---|---|
RECT_STAT, RECT_MOVE, FILE, FILE_N/_B/_Y (как ) |
4 стороны прямоугольника, каждая расширена на | высота, ширина |
POLYGON_STAT, POLYGON_MOVE |
по полосе на сторону, вытянута вдоль большей проекции; замыкающая сторона — только у блока | длины всех сторон |
CIRCLE_STAT, CIRCLE_MOVE |
внешняя дуга; при внутреннем радиусе — два радиальных отрезка и внутренняя дуга | радиусы |
INPUT_X |
полоса вдоль оси Y: | апертура |
INPUT_Y |
полоса вдоль оси X: | апертура |
остальные (в том числе *_STAT_N/_B/_Y) |
нет | нет |
У круга Xmin/Xmax записи — внутренний и внешний радиусы (м), Ymin/Ymax — углы
, (рад). Внешняя дуга радиуса делится на
отрезков с шагом угла . Привязка рисуется двумя линиями: – и –. Входы нумеруются по порядку блоков: «Inp 1», «Inp 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: уровень — ,
. Введённые в окне числа виду не
возвращаются. Окно закрывается сообщением WM_COLOR_LEVEL_DIALOG_BYE, которое оно
посылает виду.
Окно «Auto color» (CTmcASetColor, кнопки вкладок Field и Eps) работает с копией
шкалы; по OK копия переписывается в шкалу вкладки. Выбираются два уровня
(не ближе 2):
- «Change» — цвет уровня из окна выбора цвета;
- «Auto set» — линейная интерполяция RGB между уровнями: цвета получают , — целочисленно по каждой составляющей; концы не меняются;
- «Auto set Red/Green/Blue» — то же, но выбранная составляющая поднимается к 256 в середине интервала (шаг на первой половине, — на второй).
Надписи в сцене
CTmcGLText рисует строку в точке сцены — подписи осей, размеров, входов.
Интерфейс общий (tmcgltext.h): SetFont (описание шрифта LOGFONT), SetColor
(запоминает цвет), DrawString (рисует текущим цветом OpenGL), DrawInputNum
(«Inp n» запомненным цветом).
В Linux реализация — apps/fieldview/tmcgltext_qt.cpp:
glRasterPos3f(x, y, z); если позиция вне области вывода — строка не рисуется;- шрифт Qt строится по
LOGFONT: высотаlfHeightв пикселях, ширина знака — растяжениемlfWidth/средняя ширина знака (10–400 %); - строка растрируется в
QImageбелым по прозрачному, маска покрытия переводится в RGBA с текущим цветом OpenGL (прозрачность = покрытие альфа цвета); - начало растра сдвигается на 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 <файл поля> |
читает файл документом без графики и печатает путь, , , шаг, такт и время, , . Код 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не сверяется с сеткой файла поля. Слой берёт область по шагу и размерам поля, а шаг строки — по топологии. Если файлы от разных расчётов, слой будет сдвинут или чтение выйдет за массив. - Автоматическое обновление и файловая система. На файловой системе без расширенных
атрибутов (например, раздел Windows, подключённый в
/mnt) признак ARCHIVE всегда «взведён»:IsFileRead()= TRUE, новые кадры ядра не подхватываются — только двойным щелчком. Ядро при этом не ждёт FieldView. - CR LF между строками значений не проверяются. Текстовый вывод поля или повреждённый файл читается как числа без ошибки.
- Дуга круга длиннее сектора на один отрезок: шаг угла , а отрезков (в новой версии исправлено).
- Блоки плазмы (
RECT_STAT_Nи т. п.) границ не получают — их видно только в слое //. - Файл топологии ищется только как
.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
, losses and field ) 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 , , , |
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
ReadDataParametersreads 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 fromtmcgrviw.h; the number is read bysscanf. A mismatch or end of file is the error "bad data file".InitAllocationArrayrequires , and allocatesdoublenumbers.ReadDataArrayreads the values:Accuracy4 —float, 8 —double, otherwise the error "abnormal accuracy". Rows go from bottom to top; after each row of values 2 bytes (CR LF) are skipped without checking. Node is value number , its coordinates are , .
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 exactlyFILE_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.
- 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.
OnInitialUpdate— called byMfcGLWidget::initializeGLwhen the OpenGL context has already been created: reading the settings,GL_Init, a 50 ms timer,ReadData.- Timer 1 calls
UpdateAllViews→OnUpdateevery 50 ms: ifIsFileRead()= 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. - Double click: the limits of the field and scales are fitted again, the file is re-read.
- 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).
- 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" inReadDatanever becomes TRUE, so the other branch of the function is never executed.) - The display region 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. , of the view are the number of nodes in the region.
- Automatic limits of the field scale: the minimum and maximum of the values in the region; in "modulus" mode — , .
- The nodes are converted to scene coordinates: the arrays
pdSurfaceX,pdSurfaceY,pdSurface. - The layer (
PrepareTpl), block boundaries (PrepareBoundaryTpl) and dimension lines (PrepareBoundTplSize) — topology. - 20 levels for the color level window: from the middle of the scale to with the step .
Scene
DrawScene on every redraw:
- enables blending (
GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), clears the color and depth buffers to black; - sets the matrix: translation , rotation by the angles , , (degrees) about X, then Y, then Z;
- 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); 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 , 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 to |
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:
that is, the region occupies along each axis at . With proportional mode enabled, the shorter side is compressed: , if the region is narrower in X, and vice versa.
Height — on the field or scale:
Color scale
The field scale is 20 colors pscSurfaceColor[0..19] (0 is the bottom of the scale). From the scene height
the color is chosen as follows (SetColor):
- normal mode: the scale fraction ; in "modulus" mode (the scale is symmetric, so );
- 20 steps: color number ;
- smooth scale ("256 Resolution"): a linear blend of colors 0 and 19 with the fraction ;
- opacity —
nBlend/100.
The scale of the layer is a separate set of 20 colors, number ,
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 ( double numbers, 2
bytes after each row). If it is followed by three more grids of the same size, these are (m⁻³), , (T)
of the X kernel (plasma units), HasPlasma() = 1, and the commands for choosing
the layer quantity become available: , , , (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 :
| Block kind | Bands | Dimensions |
|---|---|---|
RECT_STAT, RECT_MOVE, FILE, FILE_N/_B/_Y (as ) |
4 sides of the rectangle, each widened by | 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: | aperture |
INPUT_Y |
band along the X axis: | 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
, (rad). The outer arc of radius is divided into
segments with the angle step . The anchor is drawn with two lines: – and –. 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 . 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
; 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 — ,
. 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 are selected
(no closer than 2):
- "Change" — the level color from the color picker;
- "Auto set" — linear RGB interpolation between the levels: colors get , — 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 in the first half, — in the second).
Labels in the scene
CTmcGLText draws a string at a scene point — 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:
glRasterPos3f(x, y, z); if the position is outside the viewport, the string is not drawn;- the Qt font is built from the
LOGFONT: heightlfHeightin pixels, character width — by stretchinglfWidth/average character width (10–400 %); - the string is rasterized into a
QImageas white on transparent, and the coverage mask is converted to RGBA with the current OpenGL color (transparency = coverage color alpha); - the raster origin is shifted 2 pixels down, output is by
glDrawPixelswith 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
CMainFrameframe, binds its status bar to the Qt status bar and makes it the main window of the application — so thatPutTrace(left part: region bounds and step, or the value at a point) andPutStatistics(right part: "nT = …; t = …") write to the Qt window; - opens a file (
openDocument): the documentCFldViewDoc::TmcCreate(), the viewCFldViewView::TmcCreate(), the widgetMfcGLWidgetin a maximized MDI subwindow. Reading the file andGL_Initare performed byOnInitialUpdateof 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_UIhandlers 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, , , step, time step and time, , . 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::ReadDatatransfers 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
.ttfile 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
.ttfile is read only inReadData. - The
.ttgrid 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 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 , but there are segments (fixed in the new version).
- Plasma blocks (
RECT_STAT_Nand so on) get no boundaries — they are visible only in the // layer. - The topology file is looked up only as
.ttin lower case (Linux is case-sensitive). - The color level window only shows values: editing the numbers in it does not change the scale.