Оболочка счётных ядер H и X
Назначение и место в пакете
Счётные ядра PlanarRT_H (волны H-поляризации) и PlanarRT_X (волны E-поляризации с
подмагниченной плазмой) — это две программы с окном. Каждая открывает задание .tpl,
по очереди считает его шаги #STEP и пишет выходные файлы (сигналы на портах .t,
S-матрицу .s, поле, топологию, данные ДН). Сам расчёт во времени выполняет расчётный
объект ядра CTmcRTHRectNode (страницы kernel-h и kernel-x),
а чтение задания — библиотека TMCIndan.
Оболочка ядра — всё, что находится между пользователем (или командной строкой) и расчётным объектом:
- точка входа
main(), разбор ключей/Ar,/Arb,/d,/Time,/GPU,/CPU; - главное окно Qt: меню, панель инструментов, строка состояния с полосой хода расчёта;
- документ
CPlanRT_HDoc(задание, номер шага, запуск расчёта в отдельном потоке, коды возврата) и видCPlanRT_HView(обработчики команд меню, настройки программы); - окна Statistics, Block, «Calculation time», форматов вывода, мелодий оповещения;
- запуск программ просмотра (TMCROS, TMCGROUT, FieldView, TMC_DN) и редактора TPL Designer;
- консольный режим и код возврата процесса;
- тестовые программы без участия человека.
Документ, вид и диалоги взяты из Windows-версии (каталог src/kernels/planarrt_h) и
компилируются без правок поверх слоя совместимости; главное окно и точка
входа написаны на Qt 6 (apps/planarrt_common). Общий путь данных пакета описан в
разделе теории (задание → препроцессор → ядро → файлы → вьюверы).
main.cpp ── ключи командной строки, настройки, выбор CPU/GPU
│
▼
MainWindow (Qt) ── меню / панель / строка состояния / окна заданий (MDI)
│ dispatch(id) через карту сообщений вида
▼
CPlanRT_HView ── команды Run, View, Config, Edit; настройки программы
│
▼
CPlanRT_HDoc ── задание .tpl, номер шага, поток расчёта, коды возврата
│ AfxBeginThread(RunAllGlobal / RunStepGlobal) → CWinThread поверх QThread
▼
CTmcRTHRectNode ── чтение шага (TMCIndan), сетка, расчёт во времени, вывод
│ PutTrace / PutStatistics → CMainFrame::m_wndStatusBar → очередь событий Qt
▼
строка состояния и полоса хода главного окна
Состав
Пути — от src/.
| Файл | Роль |
|---|---|
apps/planarrt_common/main.cpp |
точка входа обеих программ: настройки, ключи, главное окно, пакетный режим, код возврата |
apps/planarrt_common/mainwindow.h, .cpp |
главное окно Qt: меню и панель из ресурсов Windows-версии, строка состояния, полоса хода, закрытие во время расчёта, запуск TPL Designer |
apps/planarrt_common/mainframe.cpp |
рамка CMainFrame для кода ядра: строка состояния, указатель на рамку, положение окна |
apps/planarrt_common/planrt_prelude.h |
преамбула целей H и X: прослойки CDocument/CScrollView, недостающие функции Windows, связь ядра с Qt-слоем |
apps/planarrt_common/planrt_compat.cpp |
реализация недостающего: WIN.INI, GetTickCount, обработчики закрытия, перехват PostMessage |
apps/planarrt_common/planrt_app.h |
сведения, которыми различаются программы H и X |
apps/planarrt_common/runcheck.cpp, screenshot.cpp, blocktest.cpp |
тестовые программы (в поставку не входят) |
apps/planarrt_h/app_info.cpp, apps/planarrt_x/app_info.cpp |
имя программы, подписи окна и «About», подключение ресурсов |
apps/planarrt_h/dialogs/dialog_registry.cpp (и то же у X) |
таблица «номер окна → разметка», «номер элемента → имя» для слоя совместимости |
src/kernels/planarrt_h/planrt_hdoc.h, .cpp |
документ: шаги, поток расчёта, остановка, коды возврата, запуск внешних программ |
src/kernels/planarrt_h/planrt_hview.h, .cpp |
вид: обработчики меню, доступность команд, настройки программы |
src/kernels/planarrt_h/tmcdialogstatistics.* |
окно Statistics |
src/kernels/planarrt_h/tmcdialogcalctime.* |
окно «Calculation time» |
src/kernels/planarrt_h/tmcrth_dialogblock.* |
окно Block (описание блока) |
src/kernels/planarrt_h/tmcrth_dialogformatoutfile.* |
окно форматов чисел в выходных файлах |
src/kernels/planarrt_h/tmcsoundmel1.*, tmcsoundeffprop.* |
страницы мелодий оповещения |
src/kernels/planarrt_h/tmcerrormessage.* |
пустой диалог, в программе не используется |
src/kernels/planarrt_h/resource.h |
номера окон, элементов и команд |
src/kernels/planarrt_h/mainfrm.h, planrt_h.h, stdafx.h |
объявления рамки и приложения MFC, общий заголовок |
src/kernels/planarrt_h/childfrm.*, mainfrm.cpp, planrt_h.cpp, stdafx.cpp |
не входят в сборку: окна MFC-версии, заменены оболочкой Qt (см. legacy) |
Глобальные функции, которыми пользуется оболочка, но которые принадлежат ядру:
pl_iofor.cpp (флаги режима, форматы вывода, коды возврата, консоль) и pl_glfun.cpp
(функции потоков RunAllGlobal/RunStepGlobal, строка состояния, звук) — они описаны на
странице kernel-h.
Сборка H и X из одной оболочки
Обе программы собираются из одних и тех же файлов apps/planarrt_common. Различается:
| Что | PlanarRT_H | PlanarRT_X |
|---|---|---|
| Исходники Windows-версии (документ, вид, диалоги, ядро) | src/kernels/planarrt_h |
src/kernels/planarrt_x (своя копия) |
| Макросы препроцессора | — | ELECTRON_Q___, ELECTRON_M___, CTMCRTH_INDANBLCK_FILEY, CTMCRTH_INDANBLCK_RECTSTATY, CTMCRTH_INDANBLCK_CIRCSTATY, CTMCRTH_INDANBLCK_POLYGSTTY — только на целях planarrt_x_* (apps/planarrt_x/CMakeLists.txt) |
Сведения TmcPlanRtAppInfo (app_info.cpp) |
«PlanarRT_H», «Planar RT H analyzer», «Version 4.1» | «PlanarRT_X», «Planar RT X-mode analyzer», «Version 1.0» |
| Ресурсы Qt (значки) и разметка окон | planarrt_h.qrc, dialogs/*.ui, TmcInstallDialogs_planarrt_h |
planarrt_x.qrc, свои .ui, TmcInstallDialogs_planarrt_x |
| Файл настроек | PlanarRT_H |
PlanarRT_X |
Макросы X-моды задаются только в свойствах целей X, а не в общих заголовках: иначе они
изменили бы H-ядро и вьюверы. Имена классов оболочки X те же (CPlanRT_HDoc,
CPlanRT_HView, раздел настроек «PlanRT_H Config»): программа X — это та же оболочка,
собранная с другим ядром. Различие внутри оболочки по существу одно — оценка памяти в окне
Statistics (у X узел хранит больше величин).
Цели CMake каждой программы (на примере H):
| Цель | Что входит |
|---|---|
planarrt_h_ttos |
S-матрица и многочастотная обработка (общие файлы вьювера TMCROS) |
planarrt_h_core |
ядро, документ, вид, диалоги, pl_iofor, pl_glfun, planrt_compat.cpp, mainframe.cpp; без Qt |
planarrt_h_gui |
mainwindow.cpp, app_info.cpp, dialog_registry.cpp, .ui, .qrc |
planarrt_h |
main.cpp; в Windows — оконная программа без своей консоли |
planarrt_h_runcheck, planarrt_h_shot, planarrt_h_blocktest |
тестовые программы |
Преамбула оболочки
Каждый файл целей planarrt_* компилируется с ключом -include planrt_prelude.h. Преамбула
сама включает общую преамбулу tmc_win_prelude.h (CMake схлопывает два одинаковых ключа
-include) и добавляет то, чего нет в слое совместимости:
- Прослойки базовых классов. Документ ядра переопределяет
OnCloseDocumentиCanCloseFrame, вид —OnClose, и вызывает из них реализацию базового класса. В слое совместимости таких методов нет, поэтому макросы#define CDocument TmcPlanRtDocumentи#define CScrollView TmcPlanRtScrollViewподставляют пустые прослойки с поведением MFC по умолчанию. Заголовкиgui_common(они объявляютMfcViewWidget::setView(CScrollView*)) включаются при снятой подмене:#undef CScrollView…#define CScrollView TmcPlanRtScrollView— так сделано вmain.cpp,mainwindow.cppи тестовых программах. - WIN.INI (
GetProfileStringс пятью доводами) — вне Windows всегда отдаёт значение по умолчанию; на современной Windows результат тот же. GetTickCount,GetCurrentProcess,DuplicateHandle— для ожидания потока вStopAndWait. Дескриптор потока в слое совместимости — указатель на объектCWinThread, поэтому «копия дескриптора» — тот же указатель.GetVersionExвне Windows сообщает «NT 6.1»: звуковой код выбирает веткуBeep.- Связь с Qt-слоем:
TmcPlanRtSetCloseHandler(закрыть главное окно по просьбе ядра) иTmcPlanRtSetMessageBoxHandler. В Windows-сборкеplanrt_compat.cppставит перехватPostMessageслоя совместимости:WM_CLOSEглавному окну превращается в вызов обработчика закрытия.
От main() до окна
main() (apps/planarrt_common/main.cpp) заменяет InitInstance/ExitInstance
MFC-версии. Порядок действий:
tmcui::secureDllSearch()— DLL не ищутся в папке задания (см. gui-common).QApplication; имя программы —TmcPlanRtApp().appName;CWinApp::SetAppNameвыбирает файл настроек программы (настройки).- Тема оформления (
theme::setProgram,theme::apply). seedViewerDefaults()— заменяет в настройках негодные программы просмотра и редактор (см. программы просмотра).tmcApplyComputeSettings(ключи)— выбор CPU/GPU до первого расчёта:/CPUснимает переменнуюTMC_GPU; при/GPUпеременная не трогается (ключ ядро читает само); иначе берётсяTMC_GPU, заданная снаружи, или настройка «Config → Compute (GPU)» (страница gpu).- Командная строка собирается заново (доводы с пробелами — в кавычках) и передаётся
Set_CommandLine_Flags— тот же разбор ключей, что в MFC-версии (см. ключи). - Создаётся и показывается
MainWindow; в Windows его адрес регистрируетсяSetRunMainWnd— по нему ядро закроет окно после пакетного расчёта. - Файл задания — первый довод, не являющийся ключом. В пакетном режиме (Windows) задание должно быть указано, существовать и иметь путь, переводимый в кодовую страницу Windows; иначе — сообщение в консоль, код возврата 1, выход без окон.
MainWindow::openDocument(задание)(см. открытие задания).app.exec()— цикл событий. В Windowsmain()возвращаетGetRunExitCode()(см. коды возврата), вне Windows — код цикла событий.
Ключи командной строки
Ключ — отдельное слово вне кавычек. В Windows ключ начинается с / или -, вне Windows —
только с - (с / начинается любой полный путь). Буквы ключа — в любом регистре.
| Ключ | Действие | Где разбирается |
|---|---|---|
/Ar |
автозапуск: открыть задание и посчитать все шаги; при успехе окно закрывается, при ошибке остаётся открытым | Set_CommandLine_Flags (pl_iofor.cpp) |
/Arb |
то же, пакетный режим: окно закрывается после любого исхода, без вопроса при закрытии, без звука | там же |
/d |
демонстрационный режим: как /Arb плюс вывод поля и запуск просмотрщика поля |
там же |
/Time |
после команды Run отчёт о времени этапов сохраняется рядом с .tpl |
там же (IsKeyTimeInCommandLine) |
/GPU, /GPU:n |
расчёт на видеокарте (n — номер карты) |
ядро (tmcgpuh.h), tmcApplyComputeSettings |
/CPU |
расчёт на процессоре, независимо от /GPU, TMC_GPU и настройки |
там же |
При автозапуске Set_CommandLine_Flags сразу ставит код возврата 3 («остановлено»): если
окно закроют до конца расчёта, процесс вернёт 3.
Главное окно
MainWindow повторяет окно Windows-версии: те же пункты меню в том же порядке (ресурс
IDR_PLANRTTYPE), та же панель (IDR_MAINFRAME TOOLBAR), три панели строки состояния,
многодокументный режим (QMdiArea). Каждое открытое задание — запись TmcPlanRtWindow:
документ, вид, виджет-хозяин вида MfcViewWidget и подокно MDI.
Конструктор окна:
TmcPlanRtInstallResources()— значки и разметка диалогов (явный вызов: иначе компоновщик выбросил бы инициализаторы статической библиотеки).- Обработчики для кода ядра: однострочные сообщения библиотек (
tmc_set_message_handler), окно с вопросом (TmcQtMessageBox), закрытие по просьбе ядра (TmcQtCloseFrame). - Меню, панель, строка состояния.
- Рамка
CMainFrame: её строка состоянияm_wndStatusBarполучает хозяинаTmcStatusHost; рамка становитсяAfxGetApp()->m_pMainWnd— через неё код ядра пишет в строку состояния (обмен). - Таймер 200 мс →
updateCommandStates(); запоминание положения окна; сторож захвата мыши.
Выполнение команды (dispatch(id)). Каждый пункт меню и кнопка — QAction с номером
команды из resource.h. По нажатию:
- печать (
ID_FILE_PRINT…) выполняет само окно — вид рисует себя на принтер своимOnDraw(печать); - перед
ID_RUN_RUNиID_RUN_STARTSTEPготовится полоса хода (prepareProgress); ID_EDIT_EDITоткрывает задание в TPL Designer, если он найден;- команда передаётся карте сообщений вида (
TmcBuildMessageMap→map.call(id)) — это обработчики Windows-версии; - если вид её не знает — команды окна: New, Open, Close, Exit, About.
Доступность команд (updateCommandStates, по таймеру и перед показом меню): без
открытого задания доступны только New, Open, Exit, About; иначе доступность и отметки
задают обработчики ON_UPDATE_COMMAND_UI вида (tmccmd::updateActions,
обновление команд); команда без обработчика (Save, Undo,
Cut, Copy, Paste) недоступна.
Индикаторы программ (updateViewerIndicators). Кнопки New (TPL Designer), Output
(TMCROS), Field (FieldView), S-matrix (TMCGROUT), Directional Pattern (TMC_DN) получают
зелёный значок, пока соответствующая программа запущена (theme::programRunning), иначе —
обычный. Переключатели Topology, Field, Synchronization, Sound, AutoRun показывают
состояние отметкой, цвет индикатора задаёт тема (оформление).
Открытие задания
MainWindow::openDocument(path):
- Путь приводится к абсолютному и проверяется
tmcui::pathFitsCodePage: расчётный код работает с путями в кодовой странице Windows, и путь с другими буквами открыл бы не тот файл (проверка пути). Такой путь не открывается. - Папка задания делается текущей — туда препроцессор пишет временный файл.
- Создаются документ (
CPlanRT_HDoc::TmcCreate(), путь и заголовок) и вид (CPlanRT_HView::TmcCreate(),m_pDocument), виджет-хозяин и развёрнутое подокно MDI. У подокна снимается сочетание Ctrl+F4 (в программе это Config → Field). - Задание добавляется в список недавних (последние файлы).
widget->initialUpdate()→CPlanRT_HView::OnInitialUpdate(): - программы по умолчанию (OnConfigSetup), затем сохранённые настройки; - тип системы для звука (ReadSystemType); -ReadData()— чтение первого шага: документ вызываетCTmcRTHRectNode::ReadData(путь, nStep)(препроцессор, параметры, блоки); номер шага и сообщение ядра — в строку состояния; - в режиме/d— запись настроек и включение вывода поля; - при автозапуске (/Ar,/Arb,/d) —OnRunAll(): расчёт стартует сразу; - запись настроек.
Документ и шаги задания
CPlanRT_HDoc хранит номер текущего шага nStep (от 1) и владеет расчётным объектом
cRectNode. Флаг volatile BOOL bIsReadData имеет два смысла: «документ занят чтением или
расчётом» и «расчёт может продолжаться». Stop() сбрасывает его из главного потока, и цикл
расчёта выходит на ближайшей проверке; cRectNode.Stop() останавливает цикл по тактам
внутри шага.
| Команда | Метод документа | Что делает |
|---|---|---|
| Run (F5) | RunAll (в потоке) |
все шаги от текущего до последнего (цикл) |
| Run Step (F8) | RunStep (в потоке) |
только текущий шаг; при ошибке — нули S-матрицы шага в .s |
| Load first step (Shift+F5) | SetFirstStep + ReadData |
шаг 1 |
| Load Step (Shift+F8) | ReadData |
перечитать текущий шаг |
| Skip Step (Ctrl+F6) | SkipStep + ReadData |
следующий шаг, если он есть (число шагов — препроцессором, GetNStepMax) |
| Back Step (Alt+F6) | BackStep + ReadData |
предыдущий шаг, не меньше 1 |
| Stop (Alt+F5) | Stop |
просьба остановиться, без ожидания |
Перед сменой шага вид вызывает OnRunStop(). Во время расчёта команды Run, Load, Skip,
Back, File → Close недоступны, Stop — доступна (OnUpdateRun*).
Запуск расчётного потока
Обработчики OnRunAll и OnRunStartstep вида:
pThread = AfxBeginThread( RunAllGlobal | RunStepGlobal, pDoc,
THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED );
pDoc->SetRunThreadHandle( pThread->m_hThread ); // для ожидания при закрытии
pThread->ResumeThread();
Поток создаётся приостановленным, чтобы документ успел запомнить его дескриптор до начала
работы. RunAllGlobal/RunStepGlobal (pl_glfun.cpp) ещё раз проверяют, что документ не
занят, и вызывают RunAll()/RunStep(). CWinThread и AfxBeginThread реализованы в слое
совместимости поверх QThread (потоки): расчёт идёт в своём потоке,
интерфейс — в главном, порядок вычислений тот же, что в Windows-версии.
Из расчётного потока к интерфейсу идут только текст строки состояния (через очередь
событий, ниже) и просьба закрыть окно. Окна с вопросом из расчётного потока
не показываются: TmcQtMessageBox в чужом потоке пишет текст в поток предупреждений Qt и
отвечает «Да»/«OK», как пакетный режим.
Цикл «Run» по шагам
RunAll() — обёртка: начало замера времени, вызов RunAll1() в try, конец замера,
отчёт /Time, итог для пакетного режима. Исключение из расчёта (CException,
std::bad_alloc — нехватка памяти, любое другое) не роняет программу: сообщение в консоль и
строку состояния, код возврата 2.
RunAll1():
- Сбросить предупреждение прошлого запуска (
SetRunWarning("")). - Узнать число шагов
Nпрепроцессором (GetNStepMax; время — в долю «препроцессор»). Ошибка препроцессора илиN < nStep— код 1, конец. - Для
i = nStep … N: - проверить флаг остановки → код 3; -cRectNode.ReadData(путь, i); ошибка задания → код 1, конец; - проверить флаг остановки → код 3; -cRectNode.RunStep(); - ошибка расчёта шага не прерывает свип: S-матрица шага записывается в.sнулями (PutSmatrixZero), сообщение с номером шага и частотой — в консоль и строку состояния, шаг запоминается (первые 10 — в итоговое сообщение), расчёт идёт со следующего шага; - проверить флаг остановки → код 3. - Были шаги с ошибкой → итоговое сообщение «Calculated with errors at K step(s): …», код 2.
- Иначе предупреждение расчёта (если было) повторяется в строке состояния — его затёрли сообщения следующих шагов; код 0.
Проверки данных задания и расчёта (в том числе недопустимые значения материалов) выполняет
ядро; оболочка лишь получает признак ошибки IsError() и текст GetErrorMessage().
После RunAll1() при ключе /Time отчёт сохраняется под именем по умолчанию рядом с .tpl.
При автозапуске: ConsoleReportResult() и PostRunClose() — при /Ar только после кода 0,
при /Arb и /d — всегда.
Обмен с интерфейсом: строка состояния
Код ядра пишет ход расчёта функциями pl_glfun.cpp:
| Функция | Панель | Содержание |
|---|---|---|
PutTrace |
0 | этапы: «Read Data», «Load prepr», «Start step k», ошибки, предупреждения |
PutStatistics |
1 | «nTmax N» в начале шага, «nT:k;…» на тактах, сведения о блоках |
PutSinchronizFlag |
2 | что выводится: топология, поле, синхронизация |
Все три обращаются к ((CMainFrame*)AfxGetApp()->m_pMainWnd)->m_wndStatusBar.SetPaneText(...).
В Qt-версии у строки состояния рамки хозяин TmcStatusHost: метод hostSetStatusText
вызывает слот MainWindow::setStatusPane через QMetaObject::invokeMethod(...,
Qt::QueuedConnection). Так текст из расчётного потока попадает в главный поток через
очередь событий — виджеты из чужого потока не трогаются. setStatusPane сначала
разбирает исходный английский текст для полосы хода, затем показывает перевод
(tmci18n::translate, перевод).
Полоса хода расчёта
Слева в строке состояния — подпись этапа и тонкая полоса. Перед Run окно запоминает первый
шаг s₁ и последний s_N (prepareProgress; число шагов спрашивается у препроцессора
заранее, в главном потоке: во время расчёта препроцессор повторно не вызывают). Этап
определяется по сообщениям ядра:
| Сообщение | Этап |
|---|---|
| панель 0, начинается с «Read» | чтение задания |
| панель 0, содержит «prepr» | препроцессор |
| панель 1, «nX:» или «nNumNode» | построение блоков |
| панель 1, «nTmax N» | подготовка сетки, запоминается |
| панель 1, «nT:k;…» | расчёт, запоминается такт |
На этапе расчёта доля всего прогона
где — текущий шаг документа. Процент не уменьшается. На этапах подготовки процентов нет: подпись «Подготовка: …», полоса стоит на уже набранной доле. При нескольких шагах впереди пишется «Шаг s из s_N · ».
Когда расчёт закончился (IsRun() ложно) и полоса дошла до 99 % и выше, подпись показывает
итог: «Готово с ошибками» (код возврата 2), «Готово, есть предупреждения» (GetRunWarning()
не пуст — например, незатухший отклик), иначе «Готово». Цвет подписи задаёт свойство
state (run, ok, warn, err) в теме оформления.
Остановка и безопасное закрытие
- Stop (
OnRunStop→CPlanRT_HDoc::Stop) только просит расчёт остановиться. - Закрытие окна (
MainWindow::closeEvent→stopAllAndConfirm): если какой-то документ считает и это не/Arb— вопрос «Идёт расчёт. Остановить и закрыть?»; «Нет» — окно остаётся. Затем для каждого документаStopAndWait(): 1.SetRunClosing()— после этого расчётный поток не шлётWM_CLOSE(иначе вложенное закрытие разрушило бы документ, пока первое ещё ждёт поток); 2.Stop(); 3. ожидание потокаMsgWaitForMultipleObjects(…, 100 мс)с разбором событий между порциями — расчётный поток в это время может дописывать строку состояния через очередь событий; каждые 30 с — сообщение «Waiting for the calculation thread to stop...». Ожидание не ограничено по времени: документ не разрушается, пока его поток работает. - Документы и виды удаляет деструктор
MainWindow; перед этим у виджетов снимается вид (setView(nullptr)), чтобы виджет не обратился к удалённому виду.
Консольный режим и коды возврата
Программа собрана как оконная (без своей консоли). При /Ar, /Arb, /d функция
ConsolePrint пишет строки с префиксом [имя программы] в перенаправленный stdout
(файл, канал) или в консоль родительского процесса (AttachConsole); без автозапуска ничего
не пишется. Сообщения: «File: …», «Steps: N», «Step k of N: start/done», «ERROR in .tpl …»,
«ERROR in calculation (step k of N, f): …», «STOPPED …», «WARNING: …» и итог
ConsoleReportResult:
| Код | Константа | Итог в консоли | Когда |
|---|---|---|---|
| 0 | TMC_EXIT_OK |
RESULT 0: OK - all steps are calculated |
все шаги посчитаны |
| 1 | TMC_EXIT_TPL_ERROR |
RESULT 1: ERROR in .tpl file - calculation is not done |
нет файла, путь вне кодовой страницы, ошибка препроцессора, нет шагов, ошибка данных шага |
| 2 | TMC_EXIT_CALC_ERROR |
RESULT 2: ERROR during calculation |
ошибка расчёта хотя бы одного шага, исключение |
| 3 | TMC_EXIT_ABORTED |
RESULT 3: STOPPED - calculation is not finished |
остановлено пользователем или окно закрыто до конца |
Закрытие после пакетного расчёта (Windows): PostRunClose() → ::PostMessage(главное окно,
WM_CLOSE). В Qt-версии PostMessage слоя совместимости перехвачен planrt_compat.cpp:
WM_CLOSE → TmcPostFrameClose → TmcQtCloseFrame → в очереди главного потока
MainWindow::closeFromKernel() → close() → обычное безопасное закрытие.
После цикла событий main() возвращает GetRunExitCode().
Настройки программы
Настройки хранятся в разделе «PlanRT_H Config» (макрос PLANRT_H_RAZDEL_INI, общий для H и
X; файл настроек у каждой программы свой). Читает их OnInitialUpdate вида, пишет
WriteFile после каждого изменения.
| Ключ | Значение |
|---|---|
ExternEditorName |
внешний редактор задания |
ExternViewerName |
просмотр сигналов на портах (TMCROS) |
ExternFieldViewerName |
просмотр поля (FieldView) |
ExternSmatrixViewerName |
просмотр S-матрицы (TMCGROUT) |
ExternDirectPatViewerName |
просмотр ДН (TMC_DN) |
BackGroundColor |
цвет фона вида, десятичное COLORREF |
OutputFormatnT, OutputFormatdT, OutputFormatnB, OutputFormatdInp, OutputFormatdOut, OutputFormatdOutField |
форматы printf в выходных файлах: номер такта, время, номер блока, вход, выход, поле |
OutputSinchrFlagdOutField, OutputFlagdOutField |
флаги синхронизации и вывода поля, 0/1 |
SoundEffectsFlag |
27 целых: флаг звука, длительность тона двух мелодий (мс), 12 нот первой и 12 нот второй |
MainFrameSizeAndPlace__1 |
положение окна left right top bottom (пишет CMainFrame::OnDestroy) |
Форматы по умолчанию — %9d, %15.7g, %4d, %15.7g, %15.7g, пусто. Неверный формат
(нужно одно преобразование d i u x o или g e f, ширина и точность не длиннее 2 цифр)
функции Set*Format заменяют форматом по умолчанию, и вид сообщает об этом.
Флаги топологии, поля и синхронизации — это состояние вывода расчётного объекта
(CTmcRTH_IndanOutput); переключатели панели меняют его через документ
(OnOffFieldOutput, OnOffSinchronizationFieldOutput) и сразу сохраняют.
Программы просмотра и TPL Designer
Значения по умолчанию. Встроенные в документ значения («winword.exe») не годятся; поэтому:
seedViewerDefaults()вmain()для каждого просмотрщика заменяет пустое значение, «winword»/«notepad» или путь к несуществующему файлу путём к программе пакета из папки ядра (tmcros,fieldview,tmcgrout,tmc_dn), если она там есть и её путь переводится в кодовую страницу без потерь. В Windows то же для редактора: TPL Designer из папки ядра, иначеnotepad.exeиз системной папки.OnConfigSetup()(и команда Config → Setup) подставляет имена программ пакета (TMCROS.EXE,FLDVIEW.EXE,TMCGROUT.EXE,TMC_DN.EXE,NOTEPAD.EXE) там, где значение пустое.
Запуск (RunViewer, RunViewerField, RunViewerSmatrix, RunViewerDirectPattern,
RunExeFile). Если выходного файла ещё нет, создаётся пустой. Командная строка —
"программа" "файл", рабочая папка — папка задания, дескрипторы не наследуются
(CreatProc). В Windows программа, заданная без папки, ищется по полному пути
(TmcFindProgram): папка ядра, системная папка, папка Windows, «App Paths» реестра, PATH
— но не текущая папка (папка задания); старое имя FLDVIEW.EXE заменяется на
FieldView.exe. Не удалось запустить — сообщение и окно выбора программы.
TPL Designer. File → New и первая кнопка панели запускают TPL Designer для нового
задания; Edit → Edit (Alt+F7) — для открытого .tpl (TplDesigner задание.tpl). Путь
(tplDesignerPath): настройка %APPDATA%/TMC_Suite_Qt/Paths.ini, папка ядра и соседние
папки, пути установщика из HKCU\Software\TMC Suite; не найден — один раз спросить и
запомнить. Внешний редактор из Config → Editor остаётся запасным путём для Edit → Edit.
Меню и обработчики вида
| Меню | Пункты (номер в resource.h) |
Обработчик вида |
|---|---|---|
| File | New (TPL Designer), Open, Close, Save As, Print…, Exit | окно / OnFileSaveAs (копирует .tpl побайтно) |
| Edit | Edit (Alt+F7) | TPL Designer / OnEditEdit |
| View | Output, Field and topology, Statistics, S-matrix, Directional Pattern | OnViewOutput, OnViewField1, OnViewStatistics, OnConfigSmatrix, OnViewDirectionalpattern |
| Run | Run, Load first step, Run Step, Load Step, Skip Step, Back Step, Stop | OnRunAll, OnRunRestartall, OnRunStartstep, OnRunRestartstep, OnRunSkipstep, OnRunBackstep, OnRunStop |
| Config | Compute (GPU), язык, Editor, Viewer → 4 программы, Color → BackGround, Format → OutputDataFile, Topology, Field, Synchronization, Directional Pattern, Sound → On/Off, Melody, AutoRun, Setup | окно (Compute, язык) / OnConfig*, OnViewTopology, OnViewField |
Условия доступности: Field and topology — при включённых выводе поля и топологии;
Synchronization — при включённом выводе поля; Directional Pattern — если в задании есть
контур интегрирования поля (bIsFieldDistr(), теория — ДН).
Topology (запись файла топологии) и Statistics во время расчёта не выполняются: окно
сообщает, что нужно остановить расчёт (их данные пишет расчётный поток).
Окна Statistics и Calc. time
Statistics (CTmcDialogStatistics, Shift+F4). Вид копирует в окно номер шага, сообщение
ядра, параметры и топологию шага, указатели на описание вывода и замер времени документа;
PrepareData() пересчитывает величины в единицы задания:
| Поле | Формула |
|---|---|
| длина волны | |
| размер области в длинах волн | , до 0,001 |
| шагов сетки на длину волны | |
| число узлов | (как считает ядро; double, может превышать ) |
| шаг по времени | |
| шагов по времени на период | |
| длина окна времени | тактов и периодов |
| ошибка фазовой скорости (Tolerance) | , %, |
| память, МБ | память блоков + (байт на узел) |
Ошибка фазовой скорости — численная дисперсия Rt-сетки на частоте шага
(теория, шаг по времени).
Байт на узел: в H-ядре 4 величины _real на узел (×3, если поле для ДН интегрируется в
памяти); в X-ядре 12 величин плюс 2 при интегрировании.
Кнопки: «Prev.»/«Next» закрывают окно с nFlagStep = −1/1; вид меняет шаг, читает его
данные и открывает окно снова. «View block list» — окно Block (CTmcRTH_DialogBlock)
для каждого блока по очереди: тип, номер, точки (до 10), границы (смысл зависит от типа:
X/Y, R/φ, X/T), выражения eps, Vx, Vy, W, память блока; Next/Previous листают, OK и Close
заканчивают. «Calc. time...» — окно Calculation time (CTmcDialogCalcTime): отчёт
CTmcCalcTiming::BuildReport() по этапам (препроцессор, подготовка, расчёт, запись на диск,
постобработка) моноширинным шрифтом, «Refresh» перестраивает, «Export» сохраняет в .txt.
Окно открывается только при остановленном расчёте: оно копирует топологию и читает данные
шага, которые во время расчёта меняет расчётный поток. В старых версиях программы вызов
окна мог закрывать приложение (см. ISSUES.md); в этой версии код обработчика проверяет
IsRun() до копирования данных, а сценарий «Statistics → View block list → Next»
проверяется тестовой программой blocktest.
Прочие диалоги
- Форматы вывода (
CTmcRTH_DialogFormatOutFile): шесть строк формата; кнопка «Set default» возвращает форматы по умолчанию и открывает окно снова. Её номерIDOKDefaultFormat= 2 совпадает сIDCANCEL. - Мелодии (
CTmcSoundEffPropиз двухCTmcSoundMel1): «Step finish calculation» и «All finish calculation»; в каждой 12 позиций, нота 0…11 — тоны 262…494 Гц, 12 — конец мелодии; длительность тона 1…60000 мс. В пакетном режиме/Arbзвук не подаётся. - «About» — общее окно gui-common с подписями из
TmcPlanRtAppInfoи строкой модели расчётаGetModel(). CTmcErrorMessage— пустой класс на разметке «About», в программе не создаётся.
Разметка окон — файлы .ui, порождённые из ресурса Windows-версии; dialog_registry.cpp
регистрирует функции разметки по номеру окна и имена элементов по номеру
(ресурсы → диалоги Qt).
Тестовые программы
В поставку не входят; собираются для H и X.
| Программа | Запуск | Что делает | Код выхода |
|---|---|---|---|
planarrt_*_runcheck |
<задание.tpl> [шаг] |
без окон: создаёт рамку и документ, переходит к шагу, ReadData, RunStep в главном потоке, печатает сообщение ядра и выходные файлы с размерами |
0 — «Error:no», 1 — ошибка ядра, 2 — нет доводов |
planarrt_*_shot |
<файл.png> [задание] [ширина] [высота] или --dialogs [папка] |
снимок главного окна (по умолчанию 1130×700) или всех диалогов (снимки); работает с QT_QPA_PLATFORM=offscreen |
0 |
planarrt_*_blocktest |
<задание.tpl> [число Next] |
открывает задание, вызывает Statistics, нажимает «View block list» и «Next» (по умолчанию 8 раз) таймером | 0 — пройден, 3 — нет пункта Statistics, 4 — дольше 60 с |
runcheck отделяет ошибки расчёта от ошибок интерфейса: расчёт вызывается тем же
CPlanRT_HDoc::RunStep(), что и в программе.
Подводные камни
- Порядок подмены
CScrollView. Заголовокgui_common, включённый при действующем#define CScrollView TmcPlanRtScrollView, объявитsetViewс другим типом — программа не скомпонуется. - Состояние только через флаг.
bIsReadData— единственная синхронизация документа и потока. Методы, читающие данные шага (Statistics, Topology,prepareProgress), вызываются только при!IsRun(). - Ошибка шага не прерывает Run. S-матрица такого шага — нули в
.s, код возврата 2; ошибки задания (ReadData) прерывают расчёт с кодом 1. /Arпри ошибке не закрывает окно — процесс не завершится сам; в сценариях нужен/Arb.- Закрытие подокна задания (File → Close, кнопка подокна) не удаляет документ: он
остаётся в
m_documentsдо выхода из программы и останавливается вcloseEvent. OnRunAllбез потока. ЕслиAfxBeginThreadвернул NULL, обработчик выходит, не сбросив флаг видаbIsReadData; повторный Run в этом окне игнорируется.- Вне Windows код возврата процесса — код цикла событий Qt, а не
GetRunExitCode(); главное окно для закрытия после автозапуска регистрируется (SetRunMainWnd) только в Windows. CloseAndExit()иCPlanRT_HView::Stop()ждут активным опросом без сна; в Qt-оболочке не вызываются.
Связь с другими модулями
- Слой совместимости —
CDocument,CScrollView,CDialog, потоки, настройки. - Общий слой интерфейса — виджет-хозяин вида, тема, перевод, печать.
- Ядро H, ядро X — расчётный объект,
pl_iofor,pl_glfun. - TMCIndan — чтение задания, вывод.
- Расчёт на видеокарте —
/GPU,TMC_GPU, окно Compute. - Теория: метод, точность, ДН, S-матрица.
Отличия оболочки ядра X
Каталог src/kernels/planarrt_x содержит собственную копию файлов оболочки. По тексту
кода они почти совпадают с файлами ядра H:
Файл (src/kernels/planarrt_x/) |
Отличие от planarrt_h |
|---|---|
planrt_hdoc.h, .cpp, planrt_hview.h, tmcdialogcalctime.*, tmcrth_dialogblock.*, tmcrth_dialogformatoutfile.*, tmcsoundmel1.*, tmcsoundeffprop.*, tmcerrormessage.*, resource.h, mainfrm.h, planrt_h.h, stdafx.h, tmcdialogstatistics.h |
код тот же байт в байт |
planrt_hview.cpp |
код тот же; различаются только пробелы в двух пустых строках |
tmcdialogstatistics.cpp |
оценка памяти узлов в окне Statistics (ниже) |
planrt_h.cpp (вне сборки) |
раздел реестра PlanarRT_X, страница справки kernels\planar_rt_x.html |
childfrm.*, mainfrm.cpp, stdafx.cpp (вне сборки) |
нет |
Поведение оболочки X отличается от H не текстом этих файлов, а тем, с чем они собраны:
- Расчётный объект.
CPlanRT_HDocвладеетCTmcRTHRectNodeиз каталогаplanarrt_x: интерфейс, которым пользуется оболочка (ReadData,RunStep,Stop,GetParam,GetTopology,GetOutput,GetTiming,GetNStepMax…), тот же, а схема узла и обход сетки — ядра X (kernel-x, теория — узел X-ядра). Функцииpl_iofor.cppиpl_glfun.cppв каталоге X — того же текста, что у H. - Макросы X-моды. Все файлы цели
planarrt_x_core(документ, вид, диалоги, ядро) компилируются с шестью макросамиPLANRT_X_DEFS(см. сборку H и X); в коде оболочки нет ветвей#ifdefпо этим макросам. - Ресурсы.
resource.hX совпадает с H, поэтому номера окон, элементов и команд, меню и обработчики вида у программ одинаковы. Разметка окон (apps/planarrt_x/dialogs/*.ui) отличается от H только окном «About»: «Planar RT X analyzer Version 1.0», «Copyright © 2005 Tamic_soft group». Функция установки разметки —TmcInstallDialogs_planarrt_x, ресурсы Qt —planarrt_x.qrcсо своими значками. - Сведения о программе (
apps/planarrt_x/app_info.cpp): имя и файл настроекPlanarRT_X, заголовок «Planar RT X-mode analyzer», фильтр «Planar RT X analyzer Files (*.tpl)», пункт «&About PlanRT_X...». Раздел внутри файла настроек тот же — «PlanRT_H Config» (настройки).
Память в окне Statistics. Оценка, МБ:
где — память блоков по списку блоков (GetnMemoryAll), — число блоков,
= sizeof(CTmcRTHNodeDiel), — байт на узел (_real = double, 8 байт):
| Ядро | без интегрирования поля в памяти | при интегрировании (bIsItegratedInMemory) |
|---|---|---|
| H | ||
| X |
В X — 12 величин на узел (по комментарию в коде — 6 напряжений и 6 проводимостей) и ещё 2 квадратуры поля при интегрировании для ДН. Остальные величины окна, в том числе ошибка фазовой скорости (Tolerance), считаются по тем же формулам, что в H (окно Statistics).
Окно Block для блоков плазмы. CTmcRTH_DialogBlock::PrepareData подписывает поля границ
только для RECT_STAT, RECT_MOVE, FILE (Xmin/Xmax/Ymin/Ymax), CIRCLE_STAT,
CIRCLE_MOVE (Rmin/Rmax/FImin/FImax) и INPUT_X, INPUT_Y. Блоки плазмы и проводимости,
которые читает ядро X (*_STAT_N, *_STAT_B, *_STAT_Y, *_STAT_S, FILE_N, FILE_B,
FILE_Y), в эти сравнения не входят: подписи границ пустые, Ymin и Ymax равны 0, Xmin и
Xmax показываются без подписи. В поле выражения eps у таких блоков стоит выражение их
величины: концентрации N (м⁻³), поля B (Тл), величины Y или проводимости σ (См/м) для
*_STAT_S (единицы плазмы).
Shell of the H and X compute kernels
Purpose and place in the package
The compute kernels PlanarRT_H (H-polarization waves) and PlanarRT_X (E-polarization waves with
magnetized plasma) are two windowed programs. Each opens a .tpl task file,
computes its #STEP steps one after another and writes the output files (port signals .t,
the S-matrix .s, field, topology, RP data). The time-domain computation itself is performed by the computation
object of the kernel CTmcRTHRectNode (pages kernel-h and kernel-x),
and the task file is read by the TMCIndan library.
The kernel shell is everything that lies between the user (or the command line) and the computation object:
- the entry point
main(), parsing of the/Ar,/Arb,/d,/Time,/GPU,/CPUoptions; - the Qt main window: menu, toolbar, status bar with a computation progress bar;
- the document
CPlanRT_HDoc(task file, step number, running the computation in a separate thread, exit codes) and the viewCPlanRT_HView(menu command handlers, program settings); - the Statistics, Block and "Calculation time" windows, output formats, notification melodies;
- launching the viewers (TMCROS, TMCGROUT, FieldView, TMC_DN) and the TPL Designer editor;
- console mode and the process exit code;
- test programs that run without human involvement.
The document, view and dialogs are taken from the Windows version (directory src/kernels/planarrt_h) and
are compiled without edits on top of the compatibility layer; the main window and the entry
point are written in Qt 6 (apps/planarrt_common). The overall data path of the package is described in
the theory section (task file → preprocessor → kernel → files → viewers).
main.cpp ── command-line options, settings, CPU/GPU selection
│
▼
MainWindow (Qt) ── menu / toolbar / status bar / task windows (MDI)
│ dispatch(id) through the message map of the view
▼
CPlanRT_HView ── Run, View, Config, Edit commands; program settings
│
▼
CPlanRT_HDoc ── .tpl task file, step number, computation thread, exit codes
│ AfxBeginThread(RunAllGlobal / RunStepGlobal) → CWinThread on top of QThread
▼
CTmcRTHRectNode ── reading a step (TMCIndan), grid, time-domain computation, output
│ PutTrace / PutStatistics → CMainFrame::m_wndStatusBar → Qt event queue
▼
status bar and progress bar of the main window
Contents
Paths are relative to src/.
| File | Role |
|---|---|
apps/planarrt_common/main.cpp |
entry point of both programs: settings, options, main window, batch mode, exit code |
apps/planarrt_common/mainwindow.h, .cpp |
Qt main window: menu and toolbar from the Windows version resources, status bar, progress bar, closing during a computation, launching TPL Designer |
apps/planarrt_common/mainframe.cpp |
the CMainFrame frame for the kernel code: status bar, pointer to the frame, window position |
apps/planarrt_common/planrt_prelude.h |
prelude of the H and X targets: CDocument/CScrollView shims, missing Windows functions, link between the kernel and the Qt layer |
apps/planarrt_common/planrt_compat.cpp |
implementation of what is missing: WIN.INI, GetTickCount, close handlers, interception of PostMessage |
apps/planarrt_common/planrt_app.h |
information that distinguishes the H and X programs |
apps/planarrt_common/runcheck.cpp, screenshot.cpp, blocktest.cpp |
test programs (not included in the distribution) |
apps/planarrt_h/app_info.cpp, apps/planarrt_x/app_info.cpp |
program name, window and "About" captions, resource registration |
apps/planarrt_h/dialogs/dialog_registry.cpp (and the same for X) |
"window number → layout" and "control number → name" tables for the compatibility layer |
src/kernels/planarrt_h/planrt_hdoc.h, .cpp |
document: steps, computation thread, stopping, exit codes, launching external programs |
src/kernels/planarrt_h/planrt_hview.h, .cpp |
view: menu handlers, command availability, program settings |
src/kernels/planarrt_h/tmcdialogstatistics.* |
Statistics window |
src/kernels/planarrt_h/tmcdialogcalctime.* |
"Calculation time" window |
src/kernels/planarrt_h/tmcrth_dialogblock.* |
Block window (block description) |
src/kernels/planarrt_h/tmcrth_dialogformatoutfile.* |
window of number formats in the output files |
src/kernels/planarrt_h/tmcsoundmel1.*, tmcsoundeffprop.* |
notification melody pages |
src/kernels/planarrt_h/tmcerrormessage.* |
empty dialog, not used in the program |
src/kernels/planarrt_h/resource.h |
numbers of windows, controls and commands |
src/kernels/planarrt_h/mainfrm.h, planrt_h.h, stdafx.h |
declarations of the MFC frame and application, common header |
src/kernels/planarrt_h/childfrm.*, mainfrm.cpp, planrt_h.cpp, stdafx.cpp |
not included in the build: windows of the MFC version, replaced by the Qt shell (see legacy) |
Global functions used by the shell but belonging to the kernel:
pl_iofor.cpp (mode flags, output formats, exit codes, console) and pl_glfun.cpp
(thread functions RunAllGlobal/RunStepGlobal, status bar, sound) — they are described on
the kernel-h page.
Building H and X from one shell
Both programs are built from the same files of apps/planarrt_common. What differs:
| What | PlanarRT_H | PlanarRT_X |
|---|---|---|
| Windows version sources (document, view, dialogs, kernel) | src/kernels/planarrt_h |
src/kernels/planarrt_x (its own copy) |
| Preprocessor macros | — | ELECTRON_Q___, ELECTRON_M___, CTMCRTH_INDANBLCK_FILEY, CTMCRTH_INDANBLCK_RECTSTATY, CTMCRTH_INDANBLCK_CIRCSTATY, CTMCRTH_INDANBLCK_POLYGSTTY — only on the planarrt_x_* targets (apps/planarrt_x/CMakeLists.txt) |
TmcPlanRtAppInfo information (app_info.cpp) |
"PlanarRT_H", "Planar RT H analyzer", "Version 4.1" | "PlanarRT_X", "Planar RT X-mode analyzer", "Version 1.0" |
| Qt resources (icons) and window layouts | planarrt_h.qrc, dialogs/*.ui, TmcInstallDialogs_planarrt_h |
planarrt_x.qrc, its own .ui, TmcInstallDialogs_planarrt_x |
| Settings file | PlanarRT_H |
PlanarRT_X |
The X-mode macros are set only in the properties of the X targets, not in the common headers: otherwise they
would change the H kernel and the viewers. The class names of the X shell are the same (CPlanRT_HDoc,
CPlanRT_HView, settings section "PlanRT_H Config"): the X program is the same shell
built with a different kernel. In substance there is only one difference inside the shell — the memory estimate in the
Statistics window (an X node stores more quantities).
CMake targets of each program (H as an example):
| Target | What it contains |
|---|---|
planarrt_h_ttos |
S-matrix and multi-frequency processing (common files of the TMCROS viewer) |
planarrt_h_core |
kernel, document, view, dialogs, pl_iofor, pl_glfun, planrt_compat.cpp, mainframe.cpp; no Qt |
planarrt_h_gui |
mainwindow.cpp, app_info.cpp, dialog_registry.cpp, .ui, .qrc |
planarrt_h |
main.cpp; on Windows — a GUI program without its own console |
planarrt_h_runcheck, planarrt_h_shot, planarrt_h_blocktest |
test programs |
Shell prelude
Every file of the planarrt_* targets is compiled with the option -include planrt_prelude.h. The prelude
itself includes the common prelude tmc_win_prelude.h (CMake collapses two identical
-include options) and adds what is missing in the compatibility layer:
- Base class shims. The kernel document overrides
OnCloseDocumentandCanCloseFrame, the view overridesOnClose, and they call the base class implementation from them. The compatibility layer has no such methods, so the macros#define CDocument TmcPlanRtDocumentand#define CScrollView TmcPlanRtScrollViewsubstitute empty shims with the default MFC behavior. Thegui_commonheaders (they declareMfcViewWidget::setView(CScrollView*)) are included with the substitution removed:#undef CScrollView…#define CScrollView TmcPlanRtScrollView— this is done inmain.cpp,mainwindow.cppand the test programs. - WIN.INI (
GetProfileStringwith five arguments) — outside Windows always returns the default value; on modern Windows the result is the same. GetTickCount,GetCurrentProcess,DuplicateHandle— for waiting for the thread inStopAndWait. A thread handle in the compatibility layer is a pointer to theCWinThreadobject, so the "duplicate handle" is the same pointer.GetVersionExoutside Windows reports "NT 6.1": the sound code chooses theBeepbranch.- Link to the Qt layer:
TmcPlanRtSetCloseHandler(close the main window at the kernel's request) andTmcPlanRtSetMessageBoxHandler. In the Windows build,planrt_compat.cppinstalls an interception ofPostMessageof the compatibility layer:WM_CLOSEsent to the main window is turned into a call to the close handler.
From main() to the window
main() (apps/planarrt_common/main.cpp) replaces InitInstance/ExitInstance of the
MFC version. Order of actions:
tmcui::secureDllSearch()— DLLs are not searched for in the task file folder (see gui-common).QApplication; the program name isTmcPlanRtApp().appName;CWinApp::SetAppNameselects the program settings file (settings).- Theme (
theme::setProgram,theme::apply). seedViewerDefaults()— replaces unusable viewers and editor in the settings (see viewers).tmcApplyComputeSettings(options)— CPU/GPU selection before the first computation:/CPUunsets theTMC_GPUvariable; with/GPUthe variable is left untouched (the kernel reads the option itself); otherwiseTMC_GPUset from outside is used, or the "Config → Compute (GPU)" setting (page gpu).- The command line is reassembled (arguments with spaces are quoted) and passed to
Set_CommandLine_Flags— the same option parsing as in the MFC version (see options). MainWindowis created and shown; on Windows its address is registered withSetRunMainWnd— through it the kernel closes the window after a batch computation.- The task file is the first argument that is not an option. In batch mode (Windows) the task file must be given, must exist and must have a path convertible to the Windows code page; otherwise — a message to the console, exit code 1, exit without windows.
MainWindow::openDocument(task)(see opening a task file).app.exec()— the event loop. On Windowsmain()returnsGetRunExitCode()(see exit codes), outside Windows — the event loop code.
Command-line options
An option is a separate word outside quotes. On Windows an option starts with / or -, outside Windows —
only with - (any full path starts with /). The option letters may be in any case.
| Option | Action | Where it is parsed |
|---|---|---|
/Ar |
autorun: open the task file and compute all steps; on success the window closes, on error it stays open | Set_CommandLine_Flags (pl_iofor.cpp) |
/Arb |
the same, batch mode: the window closes after any outcome, without a question on closing, without sound | same place |
/d |
demonstration mode: like /Arb plus field output and launching the field viewer |
same place |
/Time |
after the Run command, the report on the time of the stages is saved next to the .tpl |
same place (IsKeyTimeInCommandLine) |
/GPU, /GPU:n |
GPU computing (n is the card number) |
kernel (tmcgpuh.h), tmcApplyComputeSettings |
/CPU |
computing on the CPU, regardless of /GPU, TMC_GPU and the setting |
same place |
On autorun, Set_CommandLine_Flags immediately sets exit code 3 ("stopped"): if the
window is closed before the computation ends, the process returns 3.
Main window
MainWindow reproduces the window of the Windows version: the same menu items in the same order (resource
IDR_PLANRTTYPE), the same toolbar (IDR_MAINFRAME TOOLBAR), three status bar panes,
multiple-document mode (QMdiArea). Each open task file is a TmcPlanRtWindow record:
document, view, the view host widget MfcViewWidget and an MDI subwindow.
Window constructor:
TmcPlanRtInstallResources()— icons and dialog layouts (an explicit call: otherwise the linker would discard the initializers of the static library).- Handlers for the kernel code: single-line library messages (
tmc_set_message_handler), question box (TmcQtMessageBox), closing at the kernel's request (TmcQtCloseFrame). - Menu, toolbar, status bar.
- The
CMainFrameframe: its status barm_wndStatusBargets the hostTmcStatusHost; the frame becomesAfxGetApp()->m_pMainWnd— through it the kernel code writes to the status bar (exchange). - A 200 ms timer →
updateCommandStates(); remembering the window position; a mouse capture watchdog.
Executing a command (dispatch(id)). Each menu item and button is a QAction with the command
number from resource.h. When triggered:
- printing (
ID_FILE_PRINT…) is performed by the window itself — the view draws itself to the printer with itsOnDraw(printing); - before
ID_RUN_RUNandID_RUN_STARTSTEPthe progress bar is prepared (prepareProgress); ID_EDIT_EDITopens the task file in TPL Designer if it is found;- the command is passed to the message map of the view (
TmcBuildMessageMap→map.call(id)) — these are the handlers of the Windows version; - if the view does not know it — window commands: New, Open, Close, Exit, About.
Command availability (updateCommandStates, on the timer and before a menu is shown): without
an open task file only New, Open, Exit, About are available; otherwise availability and check marks
are set by the ON_UPDATE_COMMAND_UI handlers of the view (tmccmd::updateActions,
command update); a command without a handler (Save, Undo,
Cut, Copy, Paste) is unavailable.
Program indicators (updateViewerIndicators). The New (TPL Designer), Output
(TMCROS), Field (FieldView), S-matrix (TMCGROUT), Directional Pattern (TMC_DN) buttons get
a green icon while the corresponding program is running (theme::programRunning), otherwise the
normal one. The Topology, Field, Synchronization, Sound, AutoRun toggles show their
state with a check mark; the indicator color is set by the theme (appearance).
Opening a task file
MainWindow::openDocument(path):
- The path is made absolute and checked by
tmcui::pathFitsCodePage: the computational code works with paths in the Windows code page, and a path with other letters would open the wrong file (path check). Such a path is not opened. - The task file folder is made current — the preprocessor writes its temporary file there.
- The document (
CPlanRT_HDoc::TmcCreate(), path and title) and the view (CPlanRT_HView::TmcCreate(),m_pDocument), the host widget and a maximized MDI subwindow are created. The Ctrl+F4 shortcut is removed from the subwindow (in the program it is Config → Field). - The task file is added to the recent list (recent files).
widget->initialUpdate()→CPlanRT_HView::OnInitialUpdate(): - default programs (OnConfigSetup), then the saved settings; - system type for sound (ReadSystemType); -ReadData()— reading the first step: the document callsCTmcRTHRectNode::ReadData(path, nStep)(preprocessor, parameters, blocks); the step number and the kernel message go to the status bar; - in/dmode — writing the settings and enabling field output; - on autorun (/Ar,/Arb,/d) —OnRunAll(): the computation starts immediately; - writing the settings.
Document and task steps
CPlanRT_HDoc stores the current step number nStep (from 1) and owns the computation object
cRectNode. The flag volatile BOOL bIsReadData has two meanings: "the document is busy reading or
computing" and "the computation may continue". Stop() clears it from the main thread, and the computation
loop exits at the nearest check; cRectNode.Stop() stops the time-step loop
inside a step.
| Command | Document method | What it does |
|---|---|---|
| Run (F5) | RunAll (in a thread) |
all steps from the current one to the last (loop) |
| Run Step (F8) | RunStep (in a thread) |
only the current step; on error — zeros of the step's S-matrix in .s |
| Load first step (Shift+F5) | SetFirstStep + ReadData |
step 1 |
| Load Step (Shift+F8) | ReadData |
re-read the current step |
| Skip Step (Ctrl+F6) | SkipStep + ReadData |
the next step, if there is one (number of steps — from the preprocessor, GetNStepMax) |
| Back Step (Alt+F6) | BackStep + ReadData |
the previous step, not less than 1 |
| Stop (Alt+F5) | Stop |
a request to stop, without waiting |
Before changing the step the view calls OnRunStop(). During a computation the Run, Load, Skip,
Back, File → Close commands are unavailable, Stop is available (OnUpdateRun*).
Starting the computation thread
The OnRunAll and OnRunStartstep handlers of the view:
pThread = AfxBeginThread( RunAllGlobal | RunStepGlobal, pDoc,
THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED );
pDoc->SetRunThreadHandle( pThread->m_hThread ); // for waiting on close
pThread->ResumeThread();
The thread is created suspended so that the document can store its handle before it starts
working. RunAllGlobal/RunStepGlobal (pl_glfun.cpp) check once more that the document is not
busy and call RunAll()/RunStep(). CWinThread and AfxBeginThread are implemented in the
compatibility layer on top of QThread (threads): the computation runs in its own thread,
the interface in the main one, and the order of computations is the same as in the Windows version.
From the computation thread only the status bar text (through the event
queue, below) and the request to close the window go to the interface. Question boxes from the computation thread
are not shown: TmcQtMessageBox in a foreign thread writes the text to the Qt warning stream and
answers "Yes"/"OK", as in batch mode.
The "Run" loop over steps
RunAll() is a wrapper: start of timing, call of RunAll1() inside try, end of timing,
the /Time report, the result for batch mode. An exception from the computation (CException,
std::bad_alloc — out of memory, any other) does not crash the program: a message to the console and
the status bar, exit code 2.
RunAll1():
- Clear the warning of the previous run (
SetRunWarning("")). - Get the number of steps
Nfrom the preprocessor (GetNStepMax; the time goes into the "preprocessor" share). A preprocessor error orN < nStep— code 1, end. - For
i = nStep … N: - check the stop flag → code 3; -cRectNode.ReadData(path, i); a task file error → code 1, end; - check the stop flag → code 3; -cRectNode.RunStep(); - a computation error in a step does not interrupt the sweep: the step's S-matrix is written to.sas zeros (PutSmatrixZero), a message with the step number and frequency goes to the console and the status bar, the step is remembered (the first 10 go into the final message), and the computation continues from the next step; - check the stop flag → code 3. - If there were steps with errors → final message "Calculated with errors at K step(s): …", code 2.
- Otherwise the computation warning (if any) is repeated in the status bar — it was overwritten by the messages of the following steps; code 0.
Checks of the task file data and of the computation (including invalid material values) are performed by
the kernel; the shell only receives the error flag IsError() and the text GetErrorMessage().
After RunAll1(), with the /Time option the report is saved under the default name next to the .tpl.
On autorun: ConsoleReportResult() and PostRunClose() — with /Ar only after code 0,
with /Arb and /d — always.
Exchange with the interface: the status bar
The kernel code writes the progress of the computation with the functions of pl_glfun.cpp:
| Function | Pane | Contents |
|---|---|---|
PutTrace |
0 | stages: "Read Data", "Load prepr", "Start step k", errors, warnings |
PutStatistics |
1 | "nTmax N" at the start of a step, "nT:k;…" on the time steps, information about blocks |
PutSinchronizFlag |
2 | what is being output: topology, field, synchronization |
All three call ((CMainFrame*)AfxGetApp()->m_pMainWnd)->m_wndStatusBar.SetPaneText(...).
In the Qt version the status bar of the frame has the host TmcStatusHost: the method hostSetStatusText
calls the slot MainWindow::setStatusPane through QMetaObject::invokeMethod(...,
Qt::QueuedConnection). In this way the text from the computation thread reaches the main thread through
the event queue — widgets are not touched from a foreign thread. setStatusPane first
parses the original English text for the progress bar, then shows the translation
(tmci18n::translate, translation).
Computation progress bar
On the left of the status bar there is a stage caption and a thin bar. Before Run the window remembers the first
step s₁ and the last one s_N (prepareProgress; the number of steps is requested from the preprocessor
in advance, in the main thread: the preprocessor is not called again during the computation). The stage
is determined from the kernel messages:
| Message | Stage |
|---|---|
| pane 0, starts with "Read" | reading the task file |
| pane 0, contains "prepr" | preprocessor |
| pane 1, "nX:" or "nNumNode" | building the blocks |
| pane 1, "nTmax N" | preparing the grid, is remembered |
| pane 1, "nT:k;…" | computation, the time step is remembered |
At the computation stage, the fraction of the whole run is
where is the current step of the document. The percentage never decreases. At the preparation stages there are no percentages: the caption is "Preparing: …", and the bar stays at the fraction already reached. When there are several steps ahead, "Step s of s_N · " is prefixed.
When the computation has finished (IsRun() is false) and the bar has reached 99 % or more, the caption shows
the result: "Done with errors" (exit code 2), "Done, with warnings" (GetRunWarning()
is not empty — for example, a response that has not decayed), otherwise "Done". The caption color is set by the
state property (run, ok, warn, err) in the theme.
Stopping and safe closing
- Stop (
OnRunStop→CPlanRT_HDoc::Stop) only asks the computation to stop. - Closing the window (
MainWindow::closeEvent→stopAllAndConfirm): if some document is computing and this is not/Arb— the question "Computation in progress. Stop and close?"; "No" — the window stays. ThenStopAndWait()for each document: 1.SetRunClosing()— after this the computation thread does not sendWM_CLOSE(otherwise a nested close would destroy the document while the first one is still waiting for the thread); 2.Stop(); 3. waiting for the thread withMsgWaitForMultipleObjects(…, 100 ms), processing events between portions — the computation thread may meanwhile still be writing to the status bar through the event queue; every 30 s — the message "Waiting for the calculation thread to stop...". The wait has no time limit: the document is not destroyed while its thread is running. - Documents and views are deleted by the
MainWindowdestructor; before that the view is detached from the widgets (setView(nullptr)), so that a widget does not access a deleted view.
Console mode and exit codes
The program is built as a GUI program (without its own console). With /Ar, /Arb, /d the function
ConsolePrint writes lines prefixed with [program name] to the redirected stdout
(file, pipe) or to the console of the parent process (AttachConsole); without autorun nothing
is written. Messages: "File: …", "Steps: N", "Step k of N: start/done", "ERROR in .tpl …",
"ERROR in calculation (step k of N, f): …", "STOPPED …", "WARNING: …" and the result of
ConsoleReportResult:
| Code | Constant | Result in the console | When |
|---|---|---|---|
| 0 | TMC_EXIT_OK |
RESULT 0: OK - all steps are calculated |
all steps are computed |
| 1 | TMC_EXIT_TPL_ERROR |
RESULT 1: ERROR in .tpl file - calculation is not done |
no file, path outside the code page, preprocessor error, no steps, error in step data |
| 2 | TMC_EXIT_CALC_ERROR |
RESULT 2: ERROR during calculation |
computation error in at least one step, exception |
| 3 | TMC_EXIT_ABORTED |
RESULT 3: STOPPED - calculation is not finished |
stopped by the user or the window was closed before the end |
Closing after a batch computation (Windows): PostRunClose() → ::PostMessage(main window,
WM_CLOSE). In the Qt version PostMessage of the compatibility layer is intercepted by planrt_compat.cpp:
WM_CLOSE → TmcPostFrameClose → TmcQtCloseFrame → in the main thread queue
MainWindow::closeFromKernel() → close() → the usual safe closing.
After the event loop main() returns GetRunExitCode().
Program settings
The settings are stored in the "PlanRT_H Config" section (macro PLANRT_H_RAZDEL_INI, common to H and
X; each program has its own settings file). They are read by OnInitialUpdate of the view and written by
WriteFile after each change.
| Key | Value |
|---|---|
ExternEditorName |
external task file editor |
ExternViewerName |
viewer of port signals (TMCROS) |
ExternFieldViewerName |
field viewer (FieldView) |
ExternSmatrixViewerName |
S-matrix viewer (TMCGROUT) |
ExternDirectPatViewerName |
RP viewer (TMC_DN) |
BackGroundColor |
background color of the view, decimal COLORREF |
OutputFormatnT, OutputFormatdT, OutputFormatnB, OutputFormatdInp, OutputFormatdOut, OutputFormatdOutField |
printf formats in the output files: time step number, time, block number, input, output, field |
OutputSinchrFlagdOutField, OutputFlagdOutField |
synchronization and field output flags, 0/1 |
SoundEffectsFlag |
27 integers: sound flag, tone duration of the two melodies (ms), 12 notes of the first and 12 notes of the second |
MainFrameSizeAndPlace__1 |
window position left right top bottom (written by CMainFrame::OnDestroy) |
The default formats are %9d, %15.7g, %4d, %15.7g, %15.7g, empty. An invalid format
(exactly one conversion d i u x o or g e f is required, width and precision no longer than 2 digits)
is replaced by the Set*Format functions with the default format, and the view reports this.
The topology, field and synchronization flags are the output state of the computation object
(CTmcRTH_IndanOutput); the toolbar toggles change it through the document
(OnOffFieldOutput, OnOffSinchronizationFieldOutput) and save it immediately.
Viewers and TPL Designer
Default values. The values built into the document ("winword.exe") are unusable; therefore:
seedViewerDefaults()inmain()replaces, for each viewer, an empty value, "winword"/"notepad" or a path to a nonexistent file with the path to the package program from the kernel folder (tmcros,fieldview,tmcgrout,tmc_dn), if it is there and its path converts to the code page without loss. On Windows the same is done for the editor: TPL Designer from the kernel folder, otherwisenotepad.exefrom the system folder.OnConfigSetup()(and the Config → Setup command) substitutes the names of the package programs (TMCROS.EXE,FLDVIEW.EXE,TMCGROUT.EXE,TMC_DN.EXE,NOTEPAD.EXE) where the value is empty.
Launching (RunViewer, RunViewerField, RunViewerSmatrix, RunViewerDirectPattern,
RunExeFile). If the output file does not exist yet, an empty one is created. The command line is
"program" "file", the working folder is the task file folder, handles are not inherited
(CreatProc). On Windows a program given without a folder is looked up by full path
(TmcFindProgram): kernel folder, system folder, Windows folder, the registry "App Paths", PATH
— but not the current folder (the task file folder); the old name FLDVIEW.EXE is replaced with
FieldView.exe. If the launch fails — a message and a program selection window.
TPL Designer. File → New and the first toolbar button launch TPL Designer for a new
task file; Edit → Edit (Alt+F7) — for the open .tpl (TplDesigner task.tpl). The path
(tplDesignerPath): the setting %APPDATA%/TMC_Suite_Qt/Paths.ini, the kernel folder and neighboring
folders, installer paths from HKCU\Software\TMC Suite; if not found — ask once and
remember. The external editor from Config → Editor remains a fallback for Edit → Edit.
Menu and view handlers
| Menu | Items (number in resource.h) |
View handler |
|---|---|---|
| File | New (TPL Designer), Open, Close, Save As, Print…, Exit | window / OnFileSaveAs (copies the .tpl byte for byte) |
| Edit | Edit (Alt+F7) | TPL Designer / OnEditEdit |
| View | Output, Field and topology, Statistics, S-matrix, Directional Pattern | OnViewOutput, OnViewField1, OnViewStatistics, OnConfigSmatrix, OnViewDirectionalpattern |
| Run | Run, Load first step, Run Step, Load Step, Skip Step, Back Step, Stop | OnRunAll, OnRunRestartall, OnRunStartstep, OnRunRestartstep, OnRunSkipstep, OnRunBackstep, OnRunStop |
| Config | Compute (GPU), Language, Editor, Viewer → 4 programs, Color → BackGround, Format → OutputDataFile, Topology, Field, Synchronization, Directional Pattern, Sound → On/Off, Melody, AutoRun, Setup | window (Compute, Language) / OnConfig*, OnViewTopology, OnViewField |
Availability conditions: Field and topology — when field and topology output are enabled;
Synchronization — when field output is enabled; Directional Pattern — if the task file has a
field integration contour (bIsFieldDistr(), theory — RP).
Topology (writing the topology file) and Statistics are not performed during a computation: the window
reports that the computation must be stopped (their data are written by the computation thread).
Statistics and Calc. time windows
Statistics (CTmcDialogStatistics, Shift+F4). The view copies into the window the step number, the kernel
message, the parameters and topology of the step, pointers to the output description and the timing of the document;
PrepareData() converts the quantities into task file units:
| Field | Formula |
|---|---|
| wavelength | |
| region size in wavelengths | , to 0.001 |
| grid steps per wavelength | |
| number of nodes | (as the kernel counts; double, may exceed ) |
| time step | |
| time steps per period | |
| length of the time window | time steps and periods |
| phase velocity error (Tolerance) | , %, |
| memory, MB | block memory + (bytes per node) |
The phase velocity error is the numerical dispersion of the Rt-grid at the frequency of the step
(theory, time step).
Bytes per node: in the H kernel 4 _real quantities per node (×3 if the field for the RP is integrated in
memory); in the X kernel 12 quantities plus 2 when integrating.
Buttons: "Prev."/"Next" close the window with nFlagStep = −1/1; the view changes the step, reads its
data and opens the window again. "View block list" — the Block window (CTmcRTH_DialogBlock)
for each block in turn: type, number, points (up to 10), bounds (the meaning depends on the type:
X/Y, R/φ, X/T), the eps, Vx, Vy, W expressions, block memory; Next/Previous page through, OK and Close
finish. "Calc. time..." — the Calculation time window (CTmcDialogCalcTime): the report of
CTmcCalcTiming::BuildReport() by stages (preprocessor, preparation, computation, writing to disk,
post-processing) in a monospaced font, "Refresh" rebuilds it, "Export" saves it to .txt.
The window opens only when the computation is stopped: it copies the topology and reads the data of the
step, which the computation thread changes during a computation. In old versions of the program calling the
window could close the application (see ISSUES.md); in this version the handler code checks
IsRun() before copying the data, and the scenario "Statistics → View block list → Next"
is checked by the test program blocktest.
Other dialogs
- Output formats (
CTmcRTH_DialogFormatOutFile): six format strings; the "Set default" button restores the default formats and opens the window again. Its numberIDOKDefaultFormat= 2 coincides withIDCANCEL. - Melodies (
CTmcSoundEffPropof twoCTmcSoundMel1): "Step finish calculation" and "All finish calculation"; each has 12 positions, note 0…11 — tones 262…494 Hz, 12 — end of the melody; tone duration 1…60000 ms. In batch mode/Arbno sound is played. - "About" — the common window of gui-common with captions from
TmcPlanRtAppInfoand the computation model lineGetModel(). CTmcErrorMessage— an empty class on the "About" layout, not created in the program.
The window layouts are .ui files generated from the Windows version resource; dialog_registry.cpp
registers the layout functions by window number and the control names by number
(resources → Qt dialogs).
Test programs
Not included in the distribution; built for H and X.
| Program | Invocation | What it does | Exit code |
|---|---|---|---|
planarrt_*_runcheck |
<task.tpl> [step] |
without windows: creates the frame and the document, goes to the step, ReadData, RunStep in the main thread, prints the kernel message and the output files with their sizes |
0 — "Error:no", 1 — kernel error, 2 — no arguments |
planarrt_*_shot |
<file.png> [task] [width] [height] or --dialogs [folder] |
screenshot of the main window (1130×700 by default) or of all dialogs (screenshots); works with QT_QPA_PLATFORM=offscreen |
0 |
planarrt_*_blocktest |
<task.tpl> [number of Next] |
opens the task file, calls Statistics, presses "View block list" and "Next" (8 times by default) on a timer | 0 — passed, 3 — no Statistics item, 4 — longer than 60 s |
runcheck separates computation errors from interface errors: the computation is invoked by the same
CPlanRT_HDoc::RunStep() as in the program.
Pitfalls
- Order of the
CScrollViewsubstitution. Agui_commonheader included while#define CScrollView TmcPlanRtScrollViewis in effect declaressetViewwith a different type — the program will not link. - State only through the flag.
bIsReadDatais the only synchronization between the document and the thread. Methods that read step data (Statistics, Topology,prepareProgress) are called only when!IsRun(). - A step error does not interrupt Run. The S-matrix of such a step is zeros in
.s, exit code 2; task file errors (ReadData) interrupt the computation with code 1. /Ardoes not close the window on error — the process will not terminate by itself; scripts need/Arb.- Closing the task subwindow (File → Close, the subwindow button) does not delete the document: it
stays in
m_documentsuntil the program exits and is stopped incloseEvent. OnRunAllwithout a thread. IfAfxBeginThreadreturned NULL, the handler exits without clearing the view flagbIsReadData; a repeated Run in this window is ignored.- Outside Windows the process exit code is the Qt event loop code, not
GetRunExitCode(); the main window for closing after autorun is registered (SetRunMainWnd) only on Windows. CloseAndExit()andCPlanRT_HView::Stop()wait by busy polling without sleeping; in the Qt shell they are not called.
Links to other modules
- Compatibility layer —
CDocument,CScrollView,CDialog, threads, settings. - Common interface layer — view host widget, theme, translation, printing.
- Kernel H, kernel X — computation object,
pl_iofor,pl_glfun. - TMCIndan — task file reading, output.
- GPU computing —
/GPU,TMC_GPU, the Compute window. - Theory: method, accuracy, RP, S-matrix.
Differences of the X kernel shell
The directory src/kernels/planarrt_x contains its own copy of the shell files. In terms of code
text they almost coincide with the files of the H kernel:
File (src/kernels/planarrt_x/) |
Difference from planarrt_h |
|---|---|
planrt_hdoc.h, .cpp, planrt_hview.h, tmcdialogcalctime.*, tmcrth_dialogblock.*, tmcrth_dialogformatoutfile.*, tmcsoundmel1.*, tmcsoundeffprop.*, tmcerrormessage.*, resource.h, mainfrm.h, planrt_h.h, stdafx.h, tmcdialogstatistics.h |
the code is identical byte for byte |
planrt_hview.cpp |
the code is the same; only the whitespace in two empty lines differs |
tmcdialogstatistics.cpp |
estimate of node memory in the Statistics window (below) |
planrt_h.cpp (outside the build) |
registry section PlanarRT_X, help page kernels\planar_rt_x.html |
childfrm.*, mainfrm.cpp, stdafx.cpp (outside the build) |
none |
The behavior of the X shell differs from H not in the text of these files but in what they are built with:
- Computation object.
CPlanRT_HDocownsCTmcRTHRectNodefrom theplanarrt_xdirectory: the interface used by the shell (ReadData,RunStep,Stop,GetParam,GetTopology,GetOutput,GetTiming,GetNStepMax…) is the same, while the node circuit and the grid traversal are those of the X kernel (kernel-x, theory — node of the X kernel). The functions ofpl_iofor.cppandpl_glfun.cppin the X directory have the same text as those of H. - X-mode macros. All files of the
planarrt_x_coretarget (document, view, dialogs, kernel) are compiled with the six macrosPLANRT_X_DEFS(see building H and X); the shell code has no#ifdefbranches on these macros. - Resources.
resource.hof X coincides with H, so the numbers of windows, controls and commands, the menus and the view handlers are the same in both programs. The window layouts (apps/planarrt_x/dialogs/*.ui) differ from H only in the "About" window: "Planar RT X analyzer Version 1.0", "Copyright © 2005 Tamic_soft group". The layout installation function isTmcInstallDialogs_planarrt_x, the Qt resources areplanarrt_x.qrcwith its own icons. - Program information (
apps/planarrt_x/app_info.cpp): name and settings filePlanarRT_X, title "Planar RT X-mode analyzer", filter "Planar RT X analyzer Files (*.tpl)", item "&About PlanRT_X...". The section inside the settings file is the same — "PlanRT_H Config" (settings).
Memory in the Statistics window. The estimate, MB:
where is the block memory over the block list (GetnMemoryAll), is the number of blocks,
= sizeof(CTmcRTHNodeDiel), is bytes per node (_real = double, 8 bytes):
| Kernel | without in-memory field integration | with integration (bIsItegratedInMemory) |
|---|---|---|
| H | ||
| X |
In X there are 12 quantities per node (according to the comment in the code — 6 voltages and 6 conductances) plus 2 field quadratures when integrating for the RP. The other quantities of the window, including the phase velocity error (Tolerance), are computed by the same formulas as in H (Statistics window).
Block window for plasma blocks. CTmcRTH_DialogBlock::PrepareData labels the bound fields
only for RECT_STAT, RECT_MOVE, FILE (Xmin/Xmax/Ymin/Ymax), CIRCLE_STAT,
CIRCLE_MOVE (Rmin/Rmax/FImin/FImax) and INPUT_X, INPUT_Y. The plasma and conductivity blocks
read by the X kernel (*_STAT_N, *_STAT_B, *_STAT_Y, *_STAT_S, FILE_N, FILE_B,
FILE_Y) are not covered by these comparisons: the bound labels are empty, Ymin and Ymax are 0, Xmin and
Xmax are shown without a label. The eps expression field of such blocks contains the expression of their
quantity: electron density N (m⁻³), field B (T), the quantity Y or the conductivity σ (S/m) for
*_STAT_S (plasma units).