feat(nmNum): 支持三维模型导入、显示及计算结果视图恢复

- 新增独立三维数据构建、校验和 VTK/VTU 文件导入入口
- 新增可取消的后台导入任务和三维模型场景控制器
- 增加切片工具菜单及右键导入、返回操作
- 支持节点和单元标量着色、缺失值处理及无属性模型显示
- 保留并恢复计算结果图层、相机和显示状态
feature/PEBI-Region-Average-Pressure-20261102
lh 3 weeks ago
parent 645c98f512
commit 03ceb5e1b3

@ -0,0 +1,89 @@
#ifndef NMVOLUMEDATA_H
#define NMVOLUMEDATA_H
#include "nmData_global.h"
#include <QSharedPointer>
#include <QStringList>
#include <QVector>
#include <vtkSmartPointer.h>
#include <vtkType.h>
class vtkUnstructuredGrid;
class nmVolumeDataBuilder;
class nmVolumeDataRenderAdapter;
/** @brief 三维属性的存储关联;不包含任何求解器或 PEBI 业务约定。 */
enum NM_VOLUME_PROPERTY_ASSOCIATION
{
NM_VolumeProperty_CellData = 0,
NM_VolumeProperty_PointData
};
/** @brief 已校验的单分量属性描述;范围只统计有限值,名称不推断单位。 */
struct NM_DATA_EXPORT nmVolumePropertyDescriptor
{
QString m_sPropertyId; ///< 关联类型与原数组名组成的稳定身份。
QString m_sArrayName; ///< 文件中的原始名称,以 UTF-8 交给 VTK。
NM_VOLUME_PROPERTY_ASSOCIATION m_eAssociation; ///< 数组关联到单元或节点。
double m_dMinimum; ///< 全模型范围内的最小有限属性值。
double m_dMaximum; ///< 全模型范围内的最大有限属性值,常量时等于最小值。
};
/**
* @brief 与数据来源无关的只读三维体网格。
* Builder 独立复制并校验后才发布;UI 只能查询元数据,渲染适配器可以共享
* 已冻结的数组,但任何下游均不得修改共享几何和数组。
*/
class NM_DATA_EXPORT nmVolumeData
{
public:
/** @brief 释放当前数据对象独占的网格容器及冻结数组引用。 */
~nmVolumeData();
/** @brief 返回本次发布的唯一数据 ID;重复导入同一文件也生成新身份。 */
QString getDataId() const;
/** @brief 返回可选来源名称;文件导入使用文件名,求解器可提供业务名称。 */
QString getSourceName() const;
/** @brief 返回已校验三维网格的节点数量。 */
vtkIdType getPointCount() const;
/** @brief 返回已校验三维网格的体单元数量。 */
vtkIdType getCellCount() const;
/** @brief 复制 X/Y/Z 最小、最大边界;空输出指针不执行操作。 */
void getBounds(double dBounds[6]) const;
/** @brief 返回只读属性目录,顺序为单元属性在前、节点属性在后。 */
const QVector<nmVolumePropertyDescriptor>& getProperties() const;
/** @brief 按稳定 ID 查找只读描述;不存在时返回 nullptr。 */
const nmVolumePropertyDescriptor* findProperty(const QString& sPropertyId) const;
/** @brief 返回默认着色属性 ID;没有合法标量时返回空字符串。 */
QString getInitialPropertyId() const;
/** @brief 返回被跳过属性等非致命诊断,不影响合法几何发布。 */
QStringList getDiagnostics() const;
private:
/** @brief 只允许 Builder 创建待校验对象,普通调用者不能发布半成品。 */
nmVolumeData();
Q_DISABLE_COPY(nmVolumeData)
friend class nmVolumeDataBuilder;
friend class nmVolumeDataRenderAdapter;
vtkSmartPointer<vtkUnstructuredGrid> m_pGrid; ///< 发布后不再写入。
QString m_sDataId; ///< 本次发布唯一 UUID,与路径及界面索引无关。
QString m_sSourceName; ///< 仅供显示的来源名称,不用于读取或身份比较。
QString m_sInitialPropertyId; ///< 构建时按活动标量优先级选定的默认属性。
QVector<nmVolumePropertyDescriptor> m_vecProperties; ///< 发布后不可修改的属性目录。
QStringList m_listDiagnostics; ///< 被跳过的数组等非致命诊断。
double m_dBounds[6]; ///< 有限且三轴非零跨度的原始网格边界。
};
/** @brief 导入过程的非所有权回调;实现必须允许工作线程调用。 */
class NM_DATA_EXPORT nmVolumeImportFeedback
{
public:
/** @brief 支持通过反馈接口销毁具体回调实现。 */
virtual ~nmVolumeImportFeedback() {}
/** @brief 返回线程安全的取消状态;读取、校验和复制循环均需检查。 */
virtual bool isCanceled() const = 0;
/** @brief 报告 0~100 的加载进度;不得在此直接操作界面对象。 */
virtual void reportProgress(int nPercent) = 0;
};
#endif // NMVOLUMEDATA_H

@ -0,0 +1,19 @@
#ifndef NMVOLUMEDATABUILDER_H
#define NMVOLUMEDATABUILDER_H
#include "nmVolumeData.h"
/** @brief 文件导入和未来三维求解器共用的发布入口,不保留输入对象的可写别名。 */
class NM_DATA_EXPORT nmVolumeDataBuilder
{
public:
/**
* @brief 完整复制、校验后返回只读数据;失败或取消返回空指针。
* @note 调用期间输入网格必须由调用方独占,不能被其他线程修改。
*/
static QSharedPointer<const nmVolumeData> buildFromGrid(
vtkUnstructuredGrid* pGrid, const QString& sSourceName = QString(),
QString* pError = nullptr, nmVolumeImportFeedback* pFeedback = nullptr);
};
#endif // NMVOLUMEDATABUILDER_H

@ -0,0 +1,22 @@
#ifndef NMVOLUMEDATAIMPORTER_H
#define NMVOLUMEDATAIMPORTER_H
#include "nmVolumeData.h"
/** @brief 单文件三维导入器;同步执行,界面通过独立工作线程调用。 */
class NM_DATA_EXPORT nmVolumeDataImporter
{
public:
/**
* @brief 读取单个 .vtk/.vtu 文件并发布完整只读数据。
* @param sFilePath 支持 Qt 本地路径,包括可读取的中文文件名。
* @param pError 可选失败说明;成功时清空,取消时返回取消说明。
* @param pFeedback 可选取消/进度接口,调用期间必须始终有效。
* @return 成功返回完整数据,文件损坏、类型不支持或取消均返回空指针。
*/
static QSharedPointer<const nmVolumeData> loadFile(
const QString& sFilePath, QString* pError = nullptr,
nmVolumeImportFeedback* pFeedback = nullptr);
};
#endif // NMVOLUMEDATAIMPORTER_H

@ -0,0 +1,26 @@
#ifndef NMVOLUMEDATARENDERADAPTER_H
#define NMVOLUMEDATARENDERADAPTER_H
#include "nmVolumeData.h"
class vtkAlgorithmOutput;
class vtkTrivialProducer;
/** @brief 将只读数据接入渲染管线;独占容器、共享冻结数组,不执行几何变换。 */
class NM_DATA_EXPORT nmVolumeDataRenderAdapter
{
public:
/** @brief 保持数据强引用并建立独立渲染容器;空数据对应空输出端口。 */
explicit nmVolumeDataRenderAdapter(const QSharedPointer<const nmVolumeData>& pData);
/** @brief 先断开输出,再释放适配器持有的数据和 VTK 引用。 */
~nmVolumeDataRenderAdapter();
/** @brief 返回非所有权输出端口;下游不得经此反查并修改共享数组。 */
vtkAlgorithmOutput* getOutputPort() const;
private:
Q_DISABLE_COPY(nmVolumeDataRenderAdapter)
QSharedPointer<const nmVolumeData> m_pData; ///< 保证共享数组存活的只读数据强引用。
vtkSmartPointer<vtkUnstructuredGrid> m_pGrid; ///< 独立容器,几何和属性引用已冻结数据。
vtkSmartPointer<vtkTrivialProducer> m_pProducer; ///< 适配器独占的 VTK 管线入口。
};
#endif // NMVOLUMEDATARENDERADAPTER_H

@ -28,6 +28,8 @@ public:
bool setPrimaryViewBounds(const double dBounds[6]);
/** @brief 清除主内容边界,使相机操作重新使用全部可见 Prop。 */
void clearPrimaryViewBounds();
/** @brief 复制显式设置的主模型边界;未设置时返回 false,不回退到可见图层。 */
bool getPrimaryViewBounds(double dBounds[6]) const;
/** @brief 恢复透视投影并适配主内容或当前可见边界。 */
bool resetCamera();

@ -0,0 +1,30 @@
#ifndef NMVTKVIEWSTATE_H
#define NMVTKVIEWSTATE_H
#include "nmRender_global.h"
#include <vtkSmartPointer.h>
class vtkCamera;
class nmWxVTKRenderContainerWidget;
/** @brief 可复制的视图快照;只由渲染容器写入,不保存可能悬空的拾取 Actor。 */
class NM_RENDER_EXPORT nmVTKViewState
{
public:
/** @brief 初始化为尚未捕获的无效状态。 */
nmVTKViewState();
/** @brief 释放独立相机副本的引用,不影响实际 Renderer。 */
~nmVTKViewState();
/** @brief 判断是否已从有效容器捕获视图。 */
bool isValid() const;
private:
friend class nmWxVTKRenderContainerWidget;
vtkSmartPointer<vtkCamera> m_pCamera; ///< 独立冻结的相机副本,含投影及裁剪范围。
bool m_bHasBounds; ///< 是否存在业务主模型边界。
double m_dBounds[6]; ///< 主模型边界副本,用于恢复适配视图的行为。
bool m_bHasRotationCenter; ///< 是否存在独立于相机焦点的旋转中心。
double m_dRotationCenter[3]; ///< 已捕获的世界坐标旋转中心。
bool m_bMarkerVisible; ///< 旋转中心标记的用户显隐偏好。
};
#endif // NMVTKVIEWSTATE_H

@ -3,6 +3,7 @@
#include "nmRender_global.h"
#include "nmVTKViewCommandController.h"
#include "nmVTKViewState.h"
#include <QSize>
#include <QWidget>
@ -100,6 +101,12 @@ public:
* 供业务层批量替换几何时使用,调用方应在整批更新结束后统一 renderView。
*/
bool fitTopViewWithoutRender();
/** @brief 适配透视等轴视图但不 Render,由外部场景切换统一提交。 */
bool fitIsometricViewWithoutRender();
/** @brief 捕获相机、主边界、独立旋转中心及标记;失败不修改输出状态。 */
bool captureViewState(nmVTKViewState& oState) const;
/** @brief 恢复完整视图,不 Render;调用者另行绑定当前几何的拾取目标。 */
bool restoreViewState(const nmVTKViewState& oState);
/** @brief 将独立旋转中心设为主内容或可见边界中心,不立即渲染。 */
bool resetRotationCenterWithoutRender();
/** @brief 切换到 VTK 页面并提交一次渲染。 */

@ -44,6 +44,11 @@ public:
QString* pError = nullptr);
/** @brief 解除管线和快照引用并隐藏结果图层,不销毁 Scene。 */
void clear();
/**
* @brief 不渲染地挂起/恢复全部自有图层,保留快照、筛选及各图层实际显隐。
* @note 挂起期间 setSnapshot 仍可事务绑定,但不设置相机、拾取目标或 Render。
*/
void setSuspended(bool bSuspended);
/**
* @brief 缓存 QVTK 视口尺寸并更新色标二维布局,不主动 Render。

@ -0,0 +1,50 @@
#ifndef NMVOLUMEIMPORTTASK_H
#define NMVOLUMEIMPORTTASK_H
#include "nmSubWxs_global.h"
#include "nmVolumeData.h"
#include <QAtomicInt>
#include <QThread>
/**
* @brief 每个结果窗口独占的导入任务。
* 工作线程只操作局部 Reader 和数据候选,不访问 QWidget、Renderer 或 Manager。
* 结果只允许在 finished 后读取;取消标志是唯一由两个线程同时访问的成员。
*/
class NM_SUB_WXS_EXPORT nmVolumeImportTask : public QThread, public nmVolumeImportFeedback
{
Q_OBJECT
public:
/** @brief 保存输入路径,线程由调用方显式 start;父对象通常为结果窗口。 */
explicit nmVolumeImportTask(const QString& sFilePath, QObject* pParent = nullptr);
/** @brief 请求取消并等待安全退出,禁止释放仍运行的 VTK 代码资源。 */
virtual ~nmVolumeImportTask();
/** @brief 原子请求取消,可由 GUI 线程调用,不阻塞等待 Reader。 */
void requestCancel();
/** @brief 线程安全查询取消标记,供导入器的处理循环调用。 */
virtual bool isCanceled() const;
/** @brief 工作线程发出单调去重的进度信号,GUI 使用队列连接接收。 */
virtual void reportProgress(int nPercent);
/** @brief 仅在线程结束且未取消时返回结果,否则返回空指针。 */
QSharedPointer<const nmVolumeData> getResult() const;
/** @brief 在线程结束后返回错误文本;运行期间不读取跨线程字符串。 */
QString getError() const;
signals:
/** @brief 已完成的加载百分比,不包含 GUI 场景提交耗时。 */
void progressChanged(int nPercent);
protected:
/** @brief 工作线程入口,构建局部候选;取消后丢弃候选而不发布。 */
virtual void run();
private:
Q_DISABLE_COPY(nmVolumeImportTask)
QString m_sFilePath; ///< 创建时固定的输入路径,运行期间不再改写。
mutable QAtomicInt m_nCancelRequested; ///< GUI 写入、工作线程读取的原子取消标志。
QSharedPointer<const nmVolumeData> m_pResult; ///< 工作线程写入,finished 后 GUI 才读取。
QString m_sError; ///< 工作线程写入的失败原因,finished 后读取。
int m_nLastProgress; ///< 仅工作线程写入,减少重复的队列事件。
};
#endif // NMVOLUMEIMPORTTASK_H

@ -0,0 +1,51 @@
#ifndef NMVOLUMESCENECONTROLLER_H
#define NMVOLUMESCENECONTROLLER_H
#include "nmSubWxs_global.h"
#include "nmVolumeData.h"
class nmWxVTKRenderContainerWidget;
class nmVolumeSceneControllerPrivate;
/**
* @brief 外部三维模型的独立场景控制器。
* setData 只准备隐藏候选,不移动相机、不 Render;窗口完成数据源事务时再调用
* activate。控制器清理仅移除自身图层,不清空容器的其他业务图层。
*/
class NM_SUB_WXS_EXPORT nmVolumeSceneController
{
public:
/** @param pContainer 非所有权容器,必须比本控制器存活更久且位于 GUI 线程。 */
explicit nmVolumeSceneController(nmWxVTKRenderContainerWidget* pContainer);
/** @brief 仅删除仍归本控制器所有的图层,然后释放数据和适配器。 */
~nmVolumeSceneController();
/** @brief 事务式准备隐藏场景;失败保留旧数据、相机和图层,成功后需 activate。 */
bool setData(const QSharedPointer<const nmVolumeData>& pData, QString* pError = nullptr);
/** @brief 显示已准备模型,设置边界和拾取目标;是否适配相机由调用者决定。 */
void activate(bool bFitCamera);
/** @brief 只隐藏本控制器图层,保留数据及显示设置,不主动渲染。 */
void hide();
/** @brief 解除当前模型引用并移除自有图层,不主动 Render。 */
void clear();
/** @brief 数据及所有已注册图层均有效时返回 true。 */
bool hasData() const;
/** @brief 按稳定 ID 原子切换着色属性;失败保留原属性,成功至多 Render 一次。 */
bool applyProperty(const QString& sPropertyId, QString* pError = nullptr);
/** @brief 更新色标响应式布局,不触发渲染,供容器 Resize 通知使用。 */
void setViewportSize(int nWidth, int nHeight);
/** @brief 保存色标显隐偏好;无标量时始终隐藏,重复设置不渲染。 */
void setScalarBarVisible(bool bVisible);
/** @brief 保存三维坐标框显隐偏好;重复设置不渲染。 */
void setScaleGridVisible(bool bVisible);
/** @brief 返回色标显隐偏好,供 QAction 同步勾选状态。 */
bool isScalarBarVisible() const;
/** @brief 返回三维坐标框显隐偏好,供 QAction 同步勾选状态。 */
bool isScaleGridVisible() const;
/** @brief 返回当前模型是否选中了可用于着色的合法属性。 */
bool hasScalarProperty() const;
private:
Q_DISABLE_COPY(nmVolumeSceneController)
nmVolumeSceneControllerPrivate* m_pPrivate; ///< 独占的场景状态,仅 GUI 线程访问。
};
#endif // NMVOLUMESCENECONTROLLER_H

@ -23,6 +23,7 @@ class QToolBar;
class iUnitGroup;
class nmDataAnalyzeManager;
class nmWxPebiResultRegionState;
class nmWxPebiVolumeState;
class nmPebiResultSceneController;
class nmPebiResultSnapshot;
class nmWxPebiResultControlBar;
@ -126,8 +127,23 @@ public:
nmDataAnalyzeManager* getDataManager() const;
/** @brief 合并重入请求并读取 Manager 最新结果状态。 */
void synchronizeFromDataManager();
/**
* @brief 异步导入单个外部三维文件;也供未来文件拖放入口复用。
* @return 已启动任务返回 true;忙碌或路径为空返回 false,当前画面不变。
*/
bool importVolumeFile(const QString& sFilePath);
/** @brief 返回当前是否正在显示外部三维数据,而非正式计算结果。 */
bool isImportedVolumeMode() const;
private slots:
/** @brief 从切片菜单选择文件,再启动可取消后台导入。 */
void onImportVolumeRequested();
/** @brief 原子标记取消;不等待或强行终止 Reader。 */
void onCancelVolumeImport();
/** @brief 在线程结束后准备候选场景,成功才提交外部模型画面。 */
void onVolumeImportFinished();
/** @brief 返回仍有效的原结果或最新结果;绑定失败保留外部模型。 */
void onReturnToCalculationResult();
/** @brief 响应快照身份、存在性或新鲜度变化,不响应结果井选择。 */
void onPebiResultStateChanged();
/** @brief Manager 析构时不再读取其成员,直接停止播放并清理场景。 */
@ -179,6 +195,10 @@ private:
void refreshStatusBar();
/** @brief 断开当前 Manager 的两个连接,不访问已经析构的对象。 */
void disconnectDataManager();
/** @brief 汇总播放、导出、绘制和导入任务状态,判定是否允许开始导入。 */
bool canImportVolume() const;
/** @brief 同步切片菜单及外部模式下的业务动作,不触发渲染。 */
void synchronizeVolumeActions();
/** @brief 创建区域图层和临时交互样式,并冻结当前 pressure 显示身份。 */
bool startRegionPressureDrawing();
/** @brief 解除临时交互、观察者和控制条锁,不修改已准备的统计区域。 */
@ -219,6 +239,7 @@ private:
QAction* m_pRegionPressureAction; ///< 绘制区域或显示压力统计的共享动作。
nmWxPebiResultRegionState* m_pRegionState; ///< 独占区域交互、计算和面板状态。
nmWxPebiVolumeState* m_pVolumeState; ///< 独占外部模式、导入线程及待恢复视图状态。
/** @brief Manager 最近一次通知后观察到的快照强引用。 */
QSharedPointer<const nmPebiResultSnapshot> m_pObservedSnapshot;

@ -0,0 +1,33 @@
#include "nmVolumeData.h"
#include <vtkUnstructuredGrid.h>
nmVolumeData::nmVolumeData()
: m_pGrid(vtkSmartPointer<vtkUnstructuredGrid>::New())
{
for(int nIndex = 0; nIndex < 6; ++nIndex) m_dBounds[nIndex] = 0.0;
}
nmVolumeData::~nmVolumeData() {}
QString nmVolumeData::getDataId() const { return m_sDataId; }
QString nmVolumeData::getSourceName() const { return m_sSourceName; }
vtkIdType nmVolumeData::getPointCount() const { return m_pGrid->GetNumberOfPoints(); }
vtkIdType nmVolumeData::getCellCount() const { return m_pGrid->GetNumberOfCells(); }
void nmVolumeData::getBounds(double dBounds[6]) const
{
if(dBounds != nullptr) {
for(int nIndex = 0; nIndex < 6; ++nIndex) dBounds[nIndex] = m_dBounds[nIndex];
}
}
const QVector<nmVolumePropertyDescriptor>& nmVolumeData::getProperties() const
{
return m_vecProperties;
}
const nmVolumePropertyDescriptor* nmVolumeData::findProperty(const QString& sPropertyId) const
{
for(int nIndex = 0; nIndex < m_vecProperties.size(); ++nIndex) {
if(m_vecProperties[nIndex].m_sPropertyId == sPropertyId) return &m_vecProperties[nIndex];
}
return nullptr;
}
QString nmVolumeData::getInitialPropertyId() const { return m_sInitialPropertyId; }
QStringList nmVolumeData::getDiagnostics() const { return m_listDiagnostics; }

@ -0,0 +1,233 @@
#include "nmVolumeDataBuilder.h"
#include <QCoreApplication>
#include <QMap>
#include <QUuid>
#include <limits>
#include <new>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkCellType.h>
#include <vtkDataArray.h>
#include <vtkDoubleArray.h>
#include <vtkIdTypeArray.h>
#include <vtkMath.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnstructuredGrid.h>
namespace {
// 固定文本标记供 Qt 4 lupdate 提取;运行期通过统一上下文翻译。
static const char* const s_pVolumeTranslationMarkers[] = {
QT_TRANSLATE_NOOP("nmVolumeData", "Not enough memory to import the volume mesh."),
QT_TRANSLATE_NOOP("nmVolumeData", "Only linear tetrahedron, voxel, hexahedron, wedge and pyramid volume cells are supported."),
QT_TRANSLATE_NOOP("nmVolumeData", "Skipped invalid scalar array: %1"),
QT_TRANSLATE_NOOP("nmVolumeData", "Skipped scalar array without finite values: %1"),
QT_TRANSLATE_NOOP("nmVolumeData", "The file contains no volume mesh."),
QT_TRANSLATE_NOOP("nmVolumeData", "The mesh connectivity is invalid."),
QT_TRANSLATE_NOOP("nmVolumeData", "The mesh contains an invalid point index."),
QT_TRANSLATE_NOOP("nmVolumeData", "The mesh contains non-finite coordinates."),
QT_TRANSLATE_NOOP("nmVolumeData", "The mesh contains repeated cell vertices."),
QT_TRANSLATE_NOOP("nmVolumeData", "The mesh must have a finite extent in all three directions."),
QT_TRANSLATE_NOOP("nmVolumeData", "Volume import canceled.")
};
/** @brief 数据层使用固定翻译上下文,避免依赖界面类。 */
QString volumeText(const char* pText)
{
Q_UNUSED(s_pVolumeTranslationMarkers);
return QCoreApplication::translate("nmVolumeData", pText);
}
/** @brief 可选反馈的取消查询,适用于所有较长的校验和属性复制循环。 */
bool canceled(nmVolumeImportFeedback* pFeedback)
{
return pFeedback != nullptr && pFeedback->isCanceled();
}
/** @brief 返回首版支持体单元的固定顶点数;零值表示明确不支持。 */
int expectedPointCount(int nCellType)
{
switch(nCellType) {
case VTK_TETRA: return 4;
case VTK_VOXEL: case VTK_HEXAHEDRON: return 8;
case VTK_WEDGE: return 6;
case VTK_PYRAMID: return 5;
default: return 0;
}
}
}
QSharedPointer<const nmVolumeData> nmVolumeDataBuilder::buildFromGrid(
vtkUnstructuredGrid* pGrid, const QString& sSourceName,
QString* pError, nmVolumeImportFeedback* pFeedback)
{
if(pError != nullptr) pError->clear();
QString sError;
try {
do {
if(canceled(pFeedback)) break;
if(pGrid == nullptr || pGrid->GetNumberOfPoints() <= 0 ||
pGrid->GetNumberOfCells() <= 0) {
sError = volumeText("The file contains no volume mesh.");
break;
}
const vtkIdType nPointCount = pGrid->GetNumberOfPoints();
const vtkIdType nCellCount = pGrid->GetNumberOfCells();
vtkCellArray* pCells = pGrid->GetCells();
vtkUnsignedCharArray* pTypes = pGrid->GetCellTypesArray();
vtkIdTypeArray* pLocations = pGrid->GetCellLocationsArray();
vtkIdTypeArray* pConnectivity = pCells == nullptr ? nullptr : pCells->GetData();
if(pConnectivity == nullptr || pTypes == nullptr || pLocations == nullptr ||
pTypes->GetNumberOfTuples() != nCellCount ||
pLocations->GetNumberOfTuples() != nCellCount ||
pTypes->GetNumberOfComponents() != 1 ||
pLocations->GetNumberOfComponents() != 1 ||
pConnectivity->GetNumberOfComponents() != 1) {
sError = volumeText("The mesh connectivity is invalid.");
break;
}
// 先按原始连接数组边界校验,再调用 VTK 的复制/渲染 API,避免非法索引被解引用。
vtkIdType nOffset = 0;
const vtkIdType nConnectivitySize = pConnectivity->GetNumberOfTuples();
for(vtkIdType nCell = 0; nCell < nCellCount; ++nCell) {
if((nCell % 4096) == 0 && canceled(pFeedback)) break;
const int nExpected = expectedPointCount(pTypes->GetValue(nCell));
if(nExpected == 0) {
sError = volumeText("Only linear tetrahedron, voxel, hexahedron, wedge and pyramid volume cells are supported.");
break;
}
if(nOffset >= nConnectivitySize || pLocations->GetValue(nCell) != nOffset ||
pConnectivity->GetValue(nOffset) != nExpected ||
nConnectivitySize - nOffset - 1 < nExpected) {
sError = volumeText("The mesh connectivity is invalid.");
break;
}
for(int nLocal = 0; nLocal < nExpected; ++nLocal) {
const vtkIdType nPoint = pConnectivity->GetValue(nOffset + 1 + nLocal);
if(nPoint < 0 || nPoint >= nPointCount) {
sError = volumeText("The mesh contains an invalid point index.");
break;
}
// 固定线性体单元中重复顶点通常表示损坏或退化拓扑。
for(int nPrevious = 0; nPrevious < nLocal; ++nPrevious) {
if(nPoint == pConnectivity->GetValue(nOffset + 1 + nPrevious)) {
sError = volumeText("The mesh contains repeated cell vertices.");
break;
}
}
if(!sError.isEmpty()) break;
}
if(!sError.isEmpty()) break;
nOffset += nExpected + 1;
}
if(canceled(pFeedback) || !sError.isEmpty()) break;
if(nOffset != nConnectivitySize) {
sError = volumeText("The mesh connectivity is invalid.");
break;
}
for(vtkIdType nPoint = 0; nPoint < nPointCount; ++nPoint) {
if((nPoint % 4096) == 0 && canceled(pFeedback)) break;
double dPoint[3];
pGrid->GetPoint(nPoint, dPoint);
if(!vtkMath::IsFinite(dPoint[0]) || !vtkMath::IsFinite(dPoint[1]) ||
!vtkMath::IsFinite(dPoint[2])) {
sError = volumeText("The mesh contains non-finite coordinates.");
break;
}
}
if(canceled(pFeedback) || !sError.isEmpty()) break;
QSharedPointer<nmVolumeData> pCandidate(new nmVolumeData);
pGrid->GetBounds(pCandidate->m_dBounds);
for(int nAxis = 0; nAxis < 3; ++nAxis) {
const double dLength = pCandidate->m_dBounds[nAxis * 2 + 1] -
pCandidate->m_dBounds[nAxis * 2];
if(!vtkMath::IsFinite(dLength) || dLength <= 0.0) {
sError = volumeText("The mesh must have a finite extent in all three directions.");
break;
}
}
if(!sError.isEmpty()) break;
if(pFeedback != nullptr) pFeedback->reportProgress(65);
// 只复制几何拓扑;属性逐项规范化,避免复制无效数组和多分量大载荷。
vtkSmartPointer<vtkUnstructuredGrid> pStructure = vtkSmartPointer<vtkUnstructuredGrid>::New();
pStructure->CopyStructure(pGrid);
pCandidate->m_pGrid->DeepCopy(pStructure);
QString sActiveProperty;
for(int nAssociation = 0; nAssociation < 2 && !canceled(pFeedback); ++nAssociation) {
vtkDataSetAttributes* pSource = nAssociation == 0
? static_cast<vtkDataSetAttributes*>(pGrid->GetCellData())
: static_cast<vtkDataSetAttributes*>(pGrid->GetPointData());
vtkDataSetAttributes* pTarget = nAssociation == 0
? static_cast<vtkDataSetAttributes*>(pCandidate->m_pGrid->GetCellData())
: static_cast<vtkDataSetAttributes*>(pCandidate->m_pGrid->GetPointData());
const vtkIdType nTupleCount = nAssociation == 0 ? nCellCount : nPointCount;
QMap<QString, int> mapNameCounts;
for(int nArray = 0; nArray < pSource->GetNumberOfArrays(); ++nArray) {
const char* pName = pSource->GetArrayName(nArray);
if(pName != nullptr) ++mapNameCounts[QString::fromUtf8(pName)];
}
for(int nArray = 0; nArray < pSource->GetNumberOfArrays() && !canceled(pFeedback); ++nArray) {
vtkDataArray* pArray = pSource->GetArray(nArray);
const char* pName = pSource->GetArrayName(nArray);
const QString sName = pName == nullptr ? QString() : QString::fromUtf8(pName);
if(pArray == nullptr || sName.isEmpty() || mapNameCounts.value(sName) != 1 ||
pArray->GetNumberOfComponents() != 1 || pArray->GetNumberOfTuples() != nTupleCount) {
pCandidate->m_listDiagnostics.append(volumeText("Skipped invalid scalar array: %1").arg(sName));
continue;
}
vtkSmartPointer<vtkDoubleArray> pValues = vtkSmartPointer<vtkDoubleArray>::New();
pValues->SetName(sName.toUtf8().constData());
pValues->SetNumberOfTuples(nTupleCount);
double dMinimum = VTK_DOUBLE_MAX;
double dMaximum = -VTK_DOUBLE_MAX;
for(vtkIdType nTuple = 0; nTuple < nTupleCount; ++nTuple) {
if((nTuple % 4096) == 0 && canceled(pFeedback)) break;
double dValue = pArray->GetComponent(nTuple, 0);
if(vtkMath::IsFinite(dValue)) {
dMinimum = qMin(dMinimum, dValue);
dMaximum = qMax(dMaximum, dValue);
} else {
dValue = std::numeric_limits<double>::quiet_NaN();
}
pValues->SetValue(nTuple, dValue);
}
if(canceled(pFeedback)) break;
if(dMinimum > dMaximum) {
pCandidate->m_listDiagnostics.append(volumeText("Skipped scalar array without finite values: %1").arg(sName));
continue;
}
nmVolumePropertyDescriptor oProperty;
oProperty.m_eAssociation = nAssociation == 0 ? NM_VolumeProperty_CellData : NM_VolumeProperty_PointData;
oProperty.m_sArrayName = sName;
oProperty.m_sPropertyId = (nAssociation == 0 ? QString::fromLatin1("cell:") : QString::fromLatin1("point:")) + sName;
oProperty.m_dMinimum = dMinimum;
oProperty.m_dMaximum = dMaximum;
pCandidate->m_vecProperties.append(oProperty);
pTarget->AddArray(pValues);
if(pArray == pSource->GetScalars() && sActiveProperty.isEmpty()) sActiveProperty = oProperty.m_sPropertyId;
// 提前生成范围缓存;GUI 绑定时不再扫描整份标量。
double dCachedRange[2];
pValues->GetRange(dCachedRange);
}
if(pFeedback != nullptr) pFeedback->reportProgress(80 + nAssociation * 15);
}
if(canceled(pFeedback)) break;
pCandidate->m_sInitialPropertyId = sActiveProperty;
if(sActiveProperty.isEmpty() && !pCandidate->m_vecProperties.isEmpty()) {
pCandidate->m_sInitialPropertyId = pCandidate->m_vecProperties.first().m_sPropertyId;
}
pCandidate->m_sDataId = QUuid::createUuid().toString();
pCandidate->m_sSourceName = sSourceName;
if(pFeedback != nullptr) pFeedback->reportProgress(100);
return pCandidate;
} while(false);
} catch(const std::bad_alloc&) {
sError = volumeText("Not enough memory to import the volume mesh.");
}
if(pError != nullptr) {
*pError = canceled(pFeedback) ? volumeText("Volume import canceled.") : sError;
}
return QSharedPointer<const nmVolumeData>();
}

@ -0,0 +1,152 @@
#include "nmVolumeDataImporter.h"
#include "nmVolumeDataBuilder.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTemporaryFile>
#include <new>
#include <vtkAlgorithm.h>
#include <vtkCallbackCommand.h>
#include <vtkCommand.h>
#include <vtkErrorCode.h>
#include <vtkUnstructuredGrid.h>
#include <vtkUnstructuredGridReader.h>
#include <vtkXMLUnstructuredGridReader.h>
namespace {
// 固定文本标记供 Qt 4 lupdate 提取;运行期通过统一上下文翻译。
static const char* const s_pVolumeTranslationMarkers[] = {
QT_TRANSLATE_NOOP("nmVolumeData", "Not enough memory to import the volume mesh."),
QT_TRANSLATE_NOOP("nmVolumeData", "Select a .vtk or .vtu volume mesh file."),
QT_TRANSLATE_NOOP("nmVolumeData", "The temporary directory path cannot be read by VTK."),
QT_TRANSLATE_NOOP("nmVolumeData", "The volume mesh file is empty or cannot be opened."),
QT_TRANSLATE_NOOP("nmVolumeData", "Unable to create a temporary file for this path."),
QT_TRANSLATE_NOOP("nmVolumeData", "Unable to read the volume mesh file."),
QT_TRANSLATE_NOOP("nmVolumeData", "VTK could not read the volume mesh: %1"),
QT_TRANSLATE_NOOP("nmVolumeData", "Volume import canceled.")
};
QString importText(const char* pText)
{
Q_UNUSED(s_pVolumeTranslationMarkers);
return QCoreApplication::translate("nmVolumeData", pText);
}
struct ReaderState
{
nmVolumeImportFeedback* m_pFeedback; ///< 非所有权反馈接口,生命周期覆盖 Reader。
bool m_bFailed; ///< 任一 ErrorEvent 都使本次候选永久失败。
QString m_sDetail; ///< VTK 原始诊断,仅用作错误详情显示。
};
/** @brief 在读取线程内处理 VTK 错误和进度;回调绝不访问 GUI。 */
void handleReaderEvent(vtkObject* pCaller, unsigned long nEvent,
void* pClientData, void* pCallData)
{
ReaderState* pState = static_cast<ReaderState*>(pClientData);
if(nEvent == vtkCommand::ErrorEvent) {
pState->m_bFailed = true;
if(pCallData != nullptr) pState->m_sDetail = QString::fromLocal8Bit(static_cast<const char*>(pCallData)).trimmed();
}
vtkAlgorithm* pAlgorithm = vtkAlgorithm::SafeDownCast(pCaller);
if(pAlgorithm != nullptr && pState->m_pFeedback != nullptr) {
if(pState->m_pFeedback->isCanceled()) pAlgorithm->AbortExecuteOn();
if(nEvent == vtkCommand::ProgressEvent) {
pState->m_pFeedback->reportProgress(10 + qBound(0, int(pAlgorithm->GetProgress() * 45.0), 45));
}
}
}
}
QSharedPointer<const nmVolumeData> nmVolumeDataImporter::loadFile(
const QString& sFilePath, QString* pError, nmVolumeImportFeedback* pFeedback)
{
if(pError != nullptr) pError->clear();
QString sError;
try {
do {
const QFileInfo oFileInfo(sFilePath);
const QString sSuffix = oFileInfo.suffix().toLower();
if(sSuffix != QLatin1String("vtk") && sSuffix != QLatin1String("vtu")) {
sError = importText("Select a .vtk or .vtu volume mesh file.");
break;
}
QFile oSource(sFilePath);
if(!oSource.open(QIODevice::ReadOnly) || oSource.size() == 0) {
sError = importText("The volume mesh file is empty or cannot be opened.");
break;
}
// VTK 7.1 的文件流使用本地窄字符串。不可往返的路径通过 Qt 复制到临时
// 文件,保持二进制内容不变,并以流式复制避免额外占用整文件内存。
QString sReaderPath = oFileInfo.absoluteFilePath();
QTemporaryFile oTemporary(QDir::tempPath() + QLatin1String("/nm_volume_XXXXXX.") + sSuffix);
QByteArray aReaderPath = QFile::encodeName(sReaderPath);
if(QFile::decodeName(aReaderPath) != sReaderPath) {
if(!oTemporary.open()) {
sError = importText("Unable to create a temporary file for this path.");
break;
}
while(!oSource.atEnd() && !(pFeedback != nullptr && pFeedback->isCanceled())) {
const QByteArray aChunk = oSource.read(1024 * 1024);
if(aChunk.isEmpty() || oTemporary.write(aChunk) != aChunk.size()) {
sError = importText("Unable to read the volume mesh file.");
break;
}
}
if(!oTemporary.flush()) sError = importText("Unable to read the volume mesh file.");
sReaderPath = oTemporary.fileName();
oTemporary.close();
aReaderPath = QFile::encodeName(sReaderPath);
if(QFile::decodeName(aReaderPath) != sReaderPath) sError = importText("The temporary directory path cannot be read by VTK.");
}
if(!sError.isEmpty() || (pFeedback != nullptr && pFeedback->isCanceled())) break;
ReaderState oState;
oState.m_pFeedback = pFeedback;
oState.m_bFailed = false;
vtkSmartPointer<vtkCallbackCommand> pObserver = vtkSmartPointer<vtkCallbackCommand>::New();
pObserver->SetClientData(&oState);
pObserver->SetCallback(handleReaderEvent);
vtkSmartPointer<vtkAlgorithm> pReader;
vtkSmartPointer<vtkUnstructuredGrid> pGrid;
if(sSuffix == QLatin1String("vtk")) {
vtkSmartPointer<vtkUnstructuredGridReader> pLegacy = vtkSmartPointer<vtkUnstructuredGridReader>::New();
pReader = pLegacy;
pLegacy->SetFileName(aReaderPath.constData());
pLegacy->ReadAllScalarsOn();
pLegacy->ReadAllFieldsOn();
} else {
vtkSmartPointer<vtkXMLUnstructuredGridReader> pXml = vtkSmartPointer<vtkXMLUnstructuredGridReader>::New();
pReader = pXml;
pXml->SetFileName(aReaderPath.constData());
}
pReader->AddObserver(vtkCommand::ErrorEvent, pObserver);
pReader->AddObserver(vtkCommand::ProgressEvent, pObserver);
pReader->UpdateInformation();
vtkXMLUnstructuredGridReader* pXml = vtkXMLUnstructuredGridReader::SafeDownCast(pReader);
if(pXml != nullptr && !oState.m_bFailed) {
for(int nIndex = 0; nIndex < pXml->GetNumberOfPointArrays(); ++nIndex) pXml->SetPointArrayStatus(pXml->GetPointArrayName(nIndex), 1);
for(int nIndex = 0; nIndex < pXml->GetNumberOfCellArrays(); ++nIndex) pXml->SetCellArrayStatus(pXml->GetCellArrayName(nIndex), 1);
}
if(!oState.m_bFailed && !(pFeedback != nullptr && pFeedback->isCanceled())) pReader->Update();
// 观察者引用的是栈状态;必须在状态离开作用域前解除回调。
pReader->RemoveObservers(vtkCommand::ErrorEvent, pObserver);
pReader->RemoveObservers(vtkCommand::ProgressEvent, pObserver);
pObserver->SetClientData(nullptr);
if(pFeedback != nullptr && pFeedback->isCanceled()) break;
if(oState.m_bFailed || pReader->GetErrorCode() != vtkErrorCode::NoError) {
sError = importText("VTK could not read the volume mesh: %1").arg(oState.m_sDetail);
break;
}
pGrid = vtkUnstructuredGrid::SafeDownCast(pReader->GetOutputDataObject(0));
return nmVolumeDataBuilder::buildFromGrid(pGrid, oFileInfo.fileName(), pError, pFeedback);
} while(false);
} catch(const std::bad_alloc&) {
sError = importText("Not enough memory to import the volume mesh.");
}
if(pError != nullptr) {
*pError = pFeedback != nullptr && pFeedback->isCanceled()
? importText("Volume import canceled.") : sError;
}
return QSharedPointer<const nmVolumeData>();
}

@ -0,0 +1,22 @@
#include "nmVolumeDataRenderAdapter.h"
#include <vtkTrivialProducer.h>
#include <vtkUnstructuredGrid.h>
nmVolumeDataRenderAdapter::nmVolumeDataRenderAdapter(const QSharedPointer<const nmVolumeData>& pData)
: m_pData(pData),
m_pGrid(vtkSmartPointer<vtkUnstructuredGrid>::New()),
m_pProducer(vtkSmartPointer<vtkTrivialProducer>::New())
{
if(!m_pData.isNull()) {
m_pGrid->ShallowCopy(m_pData->m_pGrid);
m_pProducer->SetOutput(m_pGrid);
}
}
nmVolumeDataRenderAdapter::~nmVolumeDataRenderAdapter()
{
m_pProducer->SetOutput(nullptr);
}
vtkAlgorithmOutput* nmVolumeDataRenderAdapter::getOutputPort() const
{
return m_pData.isNull() ? nullptr : m_pProducer->GetOutputPort();
}

@ -89,6 +89,13 @@ void nmVTKCameraController::clearPrimaryViewBounds()
}
}
bool nmVTKCameraController::getPrimaryViewBounds(double dBounds[6]) const
{
if(!m_bHasPrimaryViewBounds || dBounds == nullptr) return false;
for(int nIndex = 0; nIndex < 6; ++nIndex) dBounds[nIndex] = m_dPrimaryViewBounds[nIndex];
return true;
}
bool nmVTKCameraController::resetCamera()
{
Q_ASSERT(isCameraGuiThread());

@ -0,0 +1,11 @@
#include "nmVTKViewState.h"
#include <vtkCamera.h>
nmVTKViewState::nmVTKViewState()
: m_bHasBounds(false), m_bHasRotationCenter(false), m_bMarkerVisible(false)
{
for(int nIndex = 0; nIndex < 6; ++nIndex) m_dBounds[nIndex] = 0.0;
for(int nIndex = 0; nIndex < 3; ++nIndex) m_dRotationCenter[nIndex] = 0.0;
}
nmVTKViewState::~nmVTKViewState() {}
bool nmVTKViewState::isValid() const { return m_pCamera != nullptr; }

@ -29,6 +29,7 @@ VTK_MODULE_INIT(vtkRenderingFreeType)
VTK_MODULE_INIT(vtkInteractionStyle)
#include <vtkRenderer.h>
#include <vtkCamera.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
@ -450,6 +451,43 @@ bool nmWxVTKRenderContainerWidget::resetRotationCenterWithoutRender()
return resetRotationCenterStateWithoutRender();
}
bool nmWxVTKRenderContainerWidget::fitIsometricViewWithoutRender()
{
Q_ASSERT(isGuiThread());
cancelRotationCenterPicking();
return isGuiThread() && m_pCameraController != nullptr && m_pCameraController->setIsometricView();
}
bool nmWxVTKRenderContainerWidget::captureViewState(nmVTKViewState& oState) const
{
if(!isGuiThread() || m_pRenderer == nullptr || m_pCameraController == nullptr) return false;
nmVTKViewState oCandidate;
oCandidate.m_pCamera = vtkSmartPointer<vtkCamera>::New();
oCandidate.m_pCamera->DeepCopy(m_pRenderer->GetActiveCamera());
oCandidate.m_bHasBounds = m_pCameraController->getPrimaryViewBounds(oCandidate.m_dBounds);
oCandidate.m_bHasRotationCenter = m_pCameraController->getRotationCenter(oCandidate.m_dRotationCenter);
oCandidate.m_bMarkerVisible = m_bRotationCenterMarkerVisible;
oState = oCandidate;
return true;
}
bool nmWxVTKRenderContainerWidget::restoreViewState(const nmVTKViewState& oState)
{
if(!isGuiThread() || !oState.isValid() || m_pCameraController == nullptr) return false;
cancelRotationCenterPicking();
m_pRenderer->GetActiveCamera()->DeepCopy(oState.m_pCamera);
if(oState.m_bHasBounds) m_pCameraController->setPrimaryViewBounds(oState.m_dBounds);
else m_pCameraController->clearPrimaryViewBounds();
if(oState.m_bHasRotationCenter) {
m_pCameraController->setRotationCenter(oState.m_dRotationCenter[0], oState.m_dRotationCenter[1], oState.m_dRotationCenter[2]);
} else m_pCameraController->clearRotationCenter();
m_bRotationCenterMarkerVisible = oState.m_bMarkerVisible;
m_pViewCommandController->setRotationCenterMarkerVisible(m_bRotationCenterMarkerVisible);
synchronizeRotationCenterMarker();
updateRotationCenterMarkerVisibility();
return true;
}
void nmWxVTKRenderContainerWidget::showReadyState()
{
Q_ASSERT(isGuiThread());

@ -240,8 +240,10 @@ public:
m_bCurrentSingleValueMode(false),
m_bScalarBarVisible(true),
m_bScaleGridVisible(false),
m_bWellNamesVisible(true)
m_bWellNamesVisible(true),
m_bSuspended(false)
{
for(int nIndex = 0; nIndex < 4; ++nIndex) m_bSavedLayerVisibility[nIndex] = false;
m_dBusinessRange[0] = 0.0;
m_dBusinessRange[1] = 0.0;
m_dDisplayRange[0] = 0.0;
@ -602,9 +604,17 @@ public:
void applyLayerVisibility(bool bHasData)
{
synchronizeLayerPointers();
// 挂起期间的新快照只更新待恢复显隐,不能把隐藏的 PEBI 图层重新显示出来。
m_bSavedLayerVisibility[0] = bHasData;
m_bSavedLayerVisibility[1] = bHasData && m_bScalarBarVisible;
m_bSavedLayerVisibility[2] = bHasData && m_bScaleGridVisible;
m_bSavedLayerVisibility[3] = bHasData && m_bWellNamesVisible;
// 挂起只改变 Actor 显隐,必须保留新快照的标量着色,供恢复时直接显示。
const bool bHasScalars = bHasData;
bHasData = bHasData && !m_bSuspended;
if(m_pMeshLayer != nullptr) {
applyMeshDisplayModeWithoutRender();
m_pMeshLayer->setScalarVisibility(bHasData);
m_pMeshLayer->setScalarVisibility(bHasScalars);
// 彩色结果网格是有效快照的主内容,不提供独立隐藏状态。
m_pMeshLayer->setVisible(bHasData);
}
@ -621,7 +631,7 @@ public:
m_pWellLayer->setVisible(
bHasData && m_bWellNamesVisible);
}
if(m_pContainer != nullptr) {
if(m_pContainer != nullptr && !m_bSuspended) {
m_pContainer->setRotationCenterPickTarget(
bHasData && m_pMeshLayer != nullptr
? m_pMeshLayer->getActor() : nullptr);
@ -636,7 +646,7 @@ public:
}
if(m_pAdapter == nullptr || m_pSnapshot.isNull()) {
m_pMeshLayer->clearInput();
m_pContainer->clearPrimaryViewBounds();
if(!m_bSuspended) m_pContainer->clearPrimaryViewBounds();
if(m_pScalarBarLayer != nullptr) {
m_pScalarBarLayer->setLookupTable(nullptr);
m_pScalarBarLayer->setTitle(QString());
@ -658,7 +668,7 @@ public:
bGridRestored = m_pScaleGridLayer->setBounds(
m_dBounds[0], m_dBounds[1],
m_dBounds[2], m_dBounds[3], m_dBounds[4]);
bBoundsRestored = m_pContainer->setPrimaryViewBounds(m_dBounds);
bBoundsRestored = m_bSuspended || m_pContainer->setPrimaryViewBounds(m_dBounds);
}
if(m_pScalarBarLayer != nullptr) {
m_pScalarBarLayer->setLookupTable(
@ -672,7 +682,7 @@ public:
{
// Scene 可能已由外部清空;先按稳定 ID 解除所有悬空观察指针。
synchronizeLayerPointers();
if(m_pContainer != nullptr) {
if(m_pContainer != nullptr && !m_bSuspended) {
m_pContainer->setRotationCenterPickTarget(nullptr);
m_pContainer->clearPrimaryViewBounds();
}
@ -790,6 +800,8 @@ public:
bool m_bScalarBarVisible;
bool m_bScaleGridVisible;
bool m_bWellNamesVisible;
bool m_bSuspended; ///< 外部三维模式挂起标志,仅 GUI 线程写入。
bool m_bSavedLayerVisibility[4]; ///< 挂起前 Mesh/ScalarBar/Grid/Well 的实际显隐。
};
nmPebiResultSceneController::nmPebiResultSceneController(
@ -969,7 +981,7 @@ bool nmPebiResultSceneController::setSnapshot(
bool bCommitted = m_pPrivate->m_pScaleGridLayer->setBounds(
dBounds[0], dBounds[1], dBounds[2],
dBounds[3], dBounds[4]) &&
m_pPrivate->m_pContainer->setPrimaryViewBounds(dBounds) &&
(m_pPrivate->m_bSuspended || m_pPrivate->m_pContainer->setPrimaryViewBounds(dBounds)) &&
m_pPrivate->bindMeshAdapter(
pCandidateAdapter, oDisplayCandidate.m_pLookupTable,
nmPebiResultFilterSettings());
@ -1022,15 +1034,15 @@ bool nmPebiResultSceneController::setSnapshot(
// Mapper 已不再引用旧 Producer,此时才允许释放旧 Adapter。
delete pPreviousAdapter;
const bool bViewFitted =
const bool bViewFitted = m_pPrivate->m_bSuspended ||
m_pPrivate->m_pContainer->fitTopViewWithoutRender();
const bool bCenterReset =
const bool bCenterReset = m_pPrivate->m_bSuspended ||
m_pPrivate->m_pContainer->resetRotationCenterWithoutRender();
Q_ASSERT(bViewFitted && bCenterReset);
Q_UNUSED(bViewFitted);
Q_UNUSED(bCenterReset);
// showReadyState 是本提交路径唯一的 Render 入口。
m_pPrivate->m_pContainer->showReadyState();
if(!m_pPrivate->m_bSuspended) m_pPrivate->m_pContainer->showReadyState();
// 候选管线、相机和首次 Render 已完整提交,最后才发布新绑定序号。
++m_pPrivate->m_nSnapshotBindingRevision;
return true;
@ -1433,7 +1445,7 @@ void nmPebiResultSceneController::setScalarBarVisible(bool bVisible)
m_pPrivate->m_bScalarBarVisible = bVisible;
const bool bHasData = hasSnapshot();
m_pPrivate->applyLayerVisibility(bHasData);
if(bHasData) {
if(bHasData && !m_pPrivate->m_bSuspended) {
m_pPrivate->m_pContainer->renderView();
}
}
@ -1451,7 +1463,7 @@ void nmPebiResultSceneController::setScaleGridVisible(bool bVisible)
m_pPrivate->m_bScaleGridVisible = bVisible;
const bool bHasData = hasSnapshot();
m_pPrivate->applyLayerVisibility(bHasData);
if(bHasData) {
if(bHasData && !m_pPrivate->m_bSuspended) {
m_pPrivate->m_pContainer->renderView();
}
}
@ -1469,7 +1481,7 @@ void nmPebiResultSceneController::setWellNamesVisible(bool bVisible)
m_pPrivate->m_bWellNamesVisible = bVisible;
const bool bHasData = hasSnapshot();
m_pPrivate->applyLayerVisibility(bHasData);
if(bHasData) {
if(bHasData && !m_pPrivate->m_bSuspended) {
m_pPrivate->m_pContainer->renderView();
}
}
@ -1623,3 +1635,28 @@ bool nmPebiResultSceneController::areWellNamesVisible() const
{
return m_pPrivate != nullptr && m_pPrivate->m_bWellNamesVisible;
}
void nmPebiResultSceneController::setSuspended(bool bSuspended)
{
Q_ASSERT(isResultSceneGuiThread());
if(!isResultSceneGuiThread() || m_pPrivate->m_bSuspended == bSuspended) return;
m_pPrivate->synchronizeLayerPointers();
nmVTKRenderLayer* pLayers[4] = {
m_pPrivate->m_pMeshLayer, m_pPrivate->m_pScalarBarLayer,
m_pPrivate->m_pScaleGridLayer, m_pPrivate->m_pWellLayer
};
for(int nIndex = 0; nIndex < 4; ++nIndex) {
if(pLayers[nIndex] == nullptr) continue;
if(bSuspended) {
m_pPrivate->m_bSavedLayerVisibility[nIndex] = pLayers[nIndex]->isVisible();
pLayers[nIndex]->setVisible(false);
} else {
pLayers[nIndex]->setVisible(hasSnapshot() && m_pPrivate->m_bSavedLayerVisibility[nIndex]);
}
}
m_pPrivate->m_bSuspended = bSuspended;
if(!bSuspended && m_pPrivate->m_pContainer != nullptr && hasSnapshot()) {
m_pPrivate->m_pContainer->setPrimaryViewBounds(m_pPrivate->m_dBounds);
m_pPrivate->m_pContainer->setRotationCenterPickTarget(m_pPrivate->m_pMeshLayer->getActor());
}
}

@ -0,0 +1,39 @@
#include "nmVolumeImportTask.h"
#include "nmVolumeDataImporter.h"
nmVolumeImportTask::nmVolumeImportTask(const QString& sFilePath, QObject* pParent)
: QThread(pParent), m_sFilePath(sFilePath), m_nCancelRequested(0), m_nLastProgress(-1)
{
}
nmVolumeImportTask::~nmVolumeImportTask()
{
// 析构是最后一道生命周期保护,不允许销毁仍在执行 VTK 代码的线程。
requestCancel();
wait();
}
void nmVolumeImportTask::requestCancel() { m_nCancelRequested.fetchAndStoreRelease(1); }
bool nmVolumeImportTask::isCanceled() const { return m_nCancelRequested.fetchAndAddAcquire(0) != 0; }
void nmVolumeImportTask::reportProgress(int nPercent)
{
nPercent = qBound(0, nPercent, 100);
if(nPercent > m_nLastProgress) {
m_nLastProgress = nPercent;
emit progressChanged(nPercent);
}
}
void nmVolumeImportTask::run()
{
try {
m_pResult = nmVolumeDataImporter::loadFile(m_sFilePath, &m_sError, this);
} catch(...) {
// C++ 异常不得越过 QThread::run 边界,否则一次导入可能终止整个进程。
m_pResult.clear();
m_sError = tr("An unexpected error occurred while importing the volume mesh.");
}
if(isCanceled()) m_pResult.clear();
}
QSharedPointer<const nmVolumeData> nmVolumeImportTask::getResult() const
{
return isFinished() && !isCanceled() ? m_pResult : QSharedPointer<const nmVolumeData>();
}
QString nmVolumeImportTask::getError() const { return isFinished() ? m_sError : QString(); }

@ -0,0 +1,274 @@
#include "nmVolumeSceneController.h"
#include "nmVolumeDataRenderAdapter.h"
#include "nmWxVTKRenderContainerWidget.h"
#include "nmVTKBoundsGridLayer.h"
#include "nmVTKMeshLayer.h"
#include "nmVTKScalarBarLayer.h"
#include "nmVTKScene.h"
#include <QCoreApplication>
#include <QScopedPointer>
#include <QThread>
#include <QUuid>
#include <cmath>
#include <new>
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkDataSetMapper.h>
#include <vtkLookupTable.h>
#include <vtkMath.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
namespace {
// 固定文本标记供 Qt 4 lupdate 提取;运行期通过统一上下文翻译。
static const char* const s_pVolumeTranslationMarkers[] = {
QT_TRANSLATE_NOOP("nmVolumeSceneController", " (Cell)"),
QT_TRANSLATE_NOOP("nmVolumeSceneController", " (Point)"),
QT_TRANSLATE_NOOP("nmVolumeSceneController", "Not enough memory to display the volume mesh."),
QT_TRANSLATE_NOOP("nmVolumeSceneController", "Unable to bind the volume scalar property.")
};
/** @brief Renderer 和 Mapper 只允许所属 GUI 线程操作。 */
bool isVolumeGuiThread()
{
return QCoreApplication::instance() == nullptr ||
QCoreApplication::instance()->thread() == QThread::currentThread();
}
/** @brief 返回与业务窗口解耦的三维场景翻译文本。 */
QString sceneText(const char* pText)
{
Q_UNUSED(s_pVolumeTranslationMarkers);
return QCoreApplication::translate("nmVolumeSceneController", pText);
}
}
class nmVolumeSceneControllerPrivate
{
public:
/** @brief 初始化未挂载图层的空场景,构造本身不改动画面。 */
explicit nmVolumeSceneControllerPrivate(nmWxVTKRenderContainerWidget* pContainer)
: m_pContainer(pContainer), m_pAdapter(nullptr), m_pMesh(nullptr),
m_pScalarBar(nullptr), m_pBounds(nullptr), m_bVisible(false),
m_bScalarBarVisible(true), m_bScaleGridVisible(false) {}
/** @brief 仅移除仍具有相同对象身份的图层,防止误删外部同 ID 图层。 */
~nmVolumeSceneControllerPrivate()
{
// Scene 拥有图层,先解除 Mapper 对适配器的引用,再释放数据。
nmVTKScene* pScene = m_pContainer == nullptr ? nullptr : m_pContainer->getScene();
if(pScene != nullptr) {
if(m_pMesh != nullptr && pScene->getLayer(m_sMeshId) == m_pMesh) pScene->removeLayer(m_sMeshId);
if(m_pScalarBar != nullptr && pScene->getLayer(m_sScalarBarId) == m_pScalarBar) pScene->removeLayer(m_sScalarBarId);
if(m_pBounds != nullptr && pScene->getLayer(m_sBoundsId) == m_pBounds) pScene->removeLayer(m_sBoundsId);
}
delete m_pAdapter;
}
/** @brief 通过 Scene 登记验证观察指针,绝不解引用被外部清理的图层。 */
bool isIntact() const
{
nmVTKScene* pScene = m_pContainer == nullptr ? nullptr : m_pContainer->getScene();
return !m_pData.isNull() && pScene != nullptr && m_pMesh != nullptr &&
m_pScalarBar != nullptr && m_pBounds != nullptr &&
pScene->getLayer(m_sMeshId) == m_pMesh &&
pScene->getLayer(m_sScalarBarId) == m_pScalarBar &&
pScene->getLayer(m_sBoundsId) == m_pBounds;
}
/** @brief 将模型可见状态与各覆盖层偏好合成,不触发 Render。 */
void updateVisibility()
{
if(!isIntact()) return;
m_pMesh->setVisible(m_bVisible);
m_pScalarBar->setVisible(m_bVisible && m_bScalarBarVisible && !m_sPropertyId.isEmpty());
m_pBounds->setVisible(m_bVisible && m_bScaleGridVisible);
}
/** @brief 完整验证候选 LUT 和属性后提交 Mapper,失败时保持旧绑定。 */
bool bindProperty(const QString& sPropertyId)
{
const nmVolumePropertyDescriptor* pProperty = m_pData->findProperty(sPropertyId);
if(pProperty == nullptr) return false;
double dMinimum = pProperty->m_dMinimum;
double dMaximum = pProperty->m_dMaximum;
const bool bConstant = dMinimum == dMaximum;
if(bConstant) {
// LUT 需要严格递增区间;色标仍显示真实常量值,不能伪造业务范围。
const double dPadding = qMax(1.0, std::fabs(dMinimum)) * 1e-6;
dMaximum += dPadding;
if(!vtkMath::IsFinite(dMaximum)) {
dMaximum = dMinimum;
dMinimum -= dPadding;
}
}
vtkSmartPointer<vtkLookupTable> pTable = vtkSmartPointer<vtkLookupTable>::New();
pTable->SetNumberOfTableValues(256);
pTable->SetHueRange(0.67, 0.0);
pTable->SetTableRange(dMinimum, dMaximum);
pTable->SetNanColor(0.65, 0.65, 0.65, 1.0);
pTable->Build();
const nmVTKMeshLayer::ScalarAssociation eAssociation =
pProperty->m_eAssociation == NM_VolumeProperty_CellData
? nmVTKMeshLayer::ScalarAssociation_CellData : nmVTKMeshLayer::ScalarAssociation_PointData;
if(!m_pMesh->setInputConnection(m_pAdapter->getOutputPort(), pProperty->m_sArrayName, eAssociation, pTable)) return false;
m_pMesh->setScalarVisibility(true);
QString sTitle = pProperty->m_sArrayName;
const QString sOtherId = (pProperty->m_eAssociation == NM_VolumeProperty_CellData
? QString::fromLatin1("point:") : QString::fromLatin1("cell:")) + sTitle;
if(m_pData->findProperty(sOtherId) != nullptr) {
sTitle += pProperty->m_eAssociation == NM_VolumeProperty_CellData
? sceneText(" (Cell)") : sceneText(" (Point)");
}
m_pScalarBar->setTitle(sTitle);
m_pScalarBar->setLookupTable(pTable);
m_pScalarBar->setConstantValueLabel(bConstant, QString::number(pProperty->m_dMinimum, 'g', 8));
m_pScalarBar->setNumberOfLabels(bConstant ? 0 : m_pScalarBar->getResponsiveLabelCount());
m_sPropertyId = sPropertyId;
return true;
}
nmWxVTKRenderContainerWidget* m_pContainer; ///< 非所有权,生命周期长于控制器。
QSharedPointer<const nmVolumeData> m_pData; ///< 当前完整只读三维数据强引用。
nmVolumeDataRenderAdapter* m_pAdapter; ///< 本状态独占的渲染管线适配器。
nmVTKMeshLayer* m_pMesh; ///< Scene 所有的主模型图层,仅作非所有权观察。
nmVTKScalarBarLayer* m_pScalarBar; ///< Scene 所有的色标图层。
nmVTKBoundsGridLayer* m_pBounds; ///< Scene 所有的三维坐标框图层。
QString m_sMeshId; ///< 主模型图层稳定 ID,带本次候选唯一前缀。
QString m_sScalarBarId; ///< 色标图层稳定 ID。
QString m_sBoundsId; ///< 三维坐标框图层稳定 ID。
QString m_sPropertyId; ///< 最后成功绑定的属性 ID,纯几何时为空。
bool m_bVisible; ///< 是否已由窗口事务激活,而非尚在准备的隐藏候选。
bool m_bScalarBarVisible; ///< 当前三维模型的独立色标偏好。
bool m_bScaleGridVisible; ///< 当前三维模型的独立坐标框偏好。
};
nmVolumeSceneController::nmVolumeSceneController(nmWxVTKRenderContainerWidget* pContainer)
: m_pPrivate(new nmVolumeSceneControllerPrivate(pContainer)) {}
nmVolumeSceneController::~nmVolumeSceneController()
{
if(m_pPrivate->m_bVisible && m_pPrivate->m_pContainer != nullptr) {
m_pPrivate->m_pContainer->setRotationCenterPickTarget(nullptr);
}
delete m_pPrivate;
}
bool nmVolumeSceneController::setData(const QSharedPointer<const nmVolumeData>& pData, QString* pError)
{
Q_ASSERT(isVolumeGuiThread());
if(pError != nullptr) pError->clear();
if(!isVolumeGuiThread() || pData.isNull() || m_pPrivate->m_pContainer == nullptr) return false;
try {
QScopedPointer<nmVolumeSceneControllerPrivate> pCandidate(new nmVolumeSceneControllerPrivate(m_pPrivate->m_pContainer));
pCandidate->m_pData = pData;
pCandidate->m_pAdapter = new nmVolumeDataRenderAdapter(pData);
// 每次候选使用独立 ID,旧场景直到候选全部准备成功才释放。
const QString sPrefix = QString::fromLatin1("nm.volume.") + QUuid::createUuid().toString();
pCandidate->m_sMeshId = sPrefix + QLatin1String(".mesh");
pCandidate->m_sScalarBarId = sPrefix + QLatin1String(".scalar");
pCandidate->m_sBoundsId = sPrefix + QLatin1String(".bounds");
nmVTKScene* pScene = pCandidate->m_pContainer->getScene();
if(pScene == nullptr) return false;
QScopedPointer<nmVTKMeshLayer> pMesh(new nmVTKMeshLayer(pCandidate->m_sMeshId));
pMesh->setVisible(false);
if(!pScene->addLayer(pMesh.data())) return false;
pCandidate->m_pMesh = pMesh.take();
QScopedPointer<nmVTKScalarBarLayer> pScalarBar(new nmVTKScalarBarLayer(pCandidate->m_sScalarBarId));
pScalarBar->setVisible(false);
if(!pScene->addLayer(pScalarBar.data())) return false;
pCandidate->m_pScalarBar = pScalarBar.take();
QScopedPointer<nmVTKBoundsGridLayer> pBounds(new nmVTKBoundsGridLayer(pCandidate->m_sBoundsId));
pBounds->setVisible(false);
if(!pScene->addLayer(pBounds.data())) return false;
pCandidate->m_pBounds = pBounds.take();
double dBounds[6];
pData->getBounds(dBounds);
pCandidate->m_pBounds->setCamera(pCandidate->m_pContainer->getRenderer()->GetActiveCamera());
pCandidate->m_pBounds->setMode(nmVTKBoundsGridLayer::Mode_Box3D);
if(!pCandidate->m_pBounds->setBounds(dBounds[0], dBounds[1], dBounds[2], dBounds[3], dBounds[4], dBounds[5])) return false;
pCandidate->m_pMesh->setDisplayMode(nmVTKMeshLayer::DisplayMode_SurfaceWithEdges);
pCandidate->m_pMesh->getActor()->GetProperty()->SetEdgeColor(0.0, 0.0, 0.0);
pCandidate->m_pMesh->getActor()->GetProperty()->SetColor(0.65, 0.65, 0.65);
if(pData->getInitialPropertyId().isEmpty()) {
if(!pCandidate->m_pMesh->setInputConnection(pCandidate->m_pAdapter->getOutputPort())) return false;
pCandidate->m_pMesh->setScalarVisibility(false);
} else if(!pCandidate->bindProperty(pData->getInitialPropertyId())) {
if(pError != nullptr) *pError = sceneText("Unable to bind the volume scalar property.");
return false;
}
const QSize oSize = pCandidate->m_pContainer->getViewportSize();
pCandidate->m_pScalarBar->setViewportSize(oSize.width(), oSize.height());
// 从此不再存在失败分支。先解除旧拾取引用,再销毁旧 Actor。
if(m_pPrivate->m_bVisible) m_pPrivate->m_pContainer->setRotationCenterPickTarget(nullptr);
delete m_pPrivate;
m_pPrivate = pCandidate.take();
return true;
} catch(const std::bad_alloc&) {
if(pError != nullptr) *pError = sceneText("Not enough memory to display the volume mesh.");
return false;
}
}
void nmVolumeSceneController::activate(bool bFitCamera)
{
if(!hasData()) return;
double dBounds[6];
m_pPrivate->m_pData->getBounds(dBounds);
m_pPrivate->m_bVisible = true;
m_pPrivate->updateVisibility();
m_pPrivate->m_pContainer->setPrimaryViewBounds(dBounds);
m_pPrivate->m_pContainer->setRotationCenterPickTarget(m_pPrivate->m_pMesh->getActor());
if(bFitCamera) {
m_pPrivate->m_pContainer->fitIsometricViewWithoutRender();
m_pPrivate->m_pContainer->resetRotationCenterWithoutRender();
}
}
void nmVolumeSceneController::hide()
{
if(!isVolumeGuiThread()) return;
m_pPrivate->m_bVisible = false;
m_pPrivate->updateVisibility();
}
void nmVolumeSceneController::clear()
{
if(!isVolumeGuiThread()) return;
nmWxVTKRenderContainerWidget* pContainer = m_pPrivate->m_pContainer;
QScopedPointer<nmVolumeSceneControllerPrivate> pEmpty(new nmVolumeSceneControllerPrivate(pContainer));
if(m_pPrivate->m_bVisible) {
pContainer->setRotationCenterPickTarget(nullptr);
pContainer->clearPrimaryViewBounds();
}
delete m_pPrivate;
m_pPrivate = pEmpty.take();
}
bool nmVolumeSceneController::hasData() const { return isVolumeGuiThread() && m_pPrivate->isIntact(); }
bool nmVolumeSceneController::applyProperty(const QString& sPropertyId, QString* pError)
{
if(pError != nullptr) pError->clear();
if(!hasData()) return false;
if(sPropertyId == m_pPrivate->m_sPropertyId) return true;
if(!m_pPrivate->bindProperty(sPropertyId)) {
if(pError != nullptr) *pError = sceneText("Unable to bind the volume scalar property.");
return false;
}
m_pPrivate->updateVisibility();
if(m_pPrivate->m_bVisible) m_pPrivate->m_pContainer->renderView();
return true;
}
void nmVolumeSceneController::setViewportSize(int nWidth, int nHeight)
{
if(hasData()) m_pPrivate->m_pScalarBar->setViewportSize(nWidth, nHeight);
}
void nmVolumeSceneController::setScalarBarVisible(bool bVisible)
{
if(!isVolumeGuiThread()) return;
if(m_pPrivate->m_bScalarBarVisible == bVisible) return;
m_pPrivate->m_bScalarBarVisible = bVisible;
m_pPrivate->updateVisibility();
if(hasData() && m_pPrivate->m_bVisible) m_pPrivate->m_pContainer->renderView();
}
void nmVolumeSceneController::setScaleGridVisible(bool bVisible)
{
if(!isVolumeGuiThread()) return;
if(m_pPrivate->m_bScaleGridVisible == bVisible) return;
m_pPrivate->m_bScaleGridVisible = bVisible;
m_pPrivate->updateVisibility();
if(hasData() && m_pPrivate->m_bVisible) m_pPrivate->m_pContainer->renderView();
}
bool nmVolumeSceneController::isScalarBarVisible() const { return m_pPrivate->m_bScalarBarVisible; }
bool nmVolumeSceneController::isScaleGridVisible() const { return m_pPrivate->m_bScaleGridVisible; }
bool nmVolumeSceneController::hasScalarProperty() const { return hasData() && !m_pPrivate->m_sPropertyId.isEmpty(); }

@ -1,4 +1,13 @@
#include "nmWxPebiResultViewWidget.h"
#include "nmVolumeImportTask.h"
#include "nmVolumeSceneController.h"
#include "nmVTKViewState.h"
#include <QFileDialog>
#include <QToolButton>
#include <QPainter>
#include <QPixmap>
#include <QPolygon>
#include <QPen>
#include "iUnitGroup.h"
#include "iUnitHelper.h"
@ -803,6 +812,30 @@ bool nmWxPebiResultFilterSettingsDlg::convertUnitValue(
return true;
}
/** @brief 外部三维模式的窗口私有状态,所有成员仅由 GUI 线程管理。 */
class nmWxPebiVolumeState
{
public:
/** @brief 初始化为空模式;控制器在通用渲染容器创建后绑定。 */
nmWxPebiVolumeState()
: m_pController(nullptr), m_pTask(nullptr), m_pProgress(nullptr),
m_pImportAction(nullptr), m_pReturnAction(nullptr), m_pButton(nullptr),
m_bImported(false), m_bPendingSync(false), m_bRegionVisible(false),
m_bRegionDialogVisible(false) {}
nmVolumeSceneController* m_pController; ///< 窗口独占,必须在渲染容器之前析构。
nmVolumeImportTask* m_pTask; ///< 当前唯一导入线程,结束后才允许读取结果。
QProgressDialog* m_pProgress; ///< 临时进度框,窗口对象树拥有。
QAction* m_pImportAction; ///< 按钮菜单和右键菜单共享的导入动作。
QAction* m_pReturnAction; ///< 仅外部模型模式启用的返回动作。
QToolButton* m_pButton; ///< 唯一新增的常驻切片工具按钮。
nmVTKViewState m_oSavedView; ///< 第一次进入外部模式前捕获的计算结果视图。
nmVTKViewCommandController::ViewCommands m_eSavedCommands; ///< 原结果提供的视图命令能力。
bool m_bImported; ///< 当前画面是否为外部三维模型。
bool m_bPendingSync; ///< 外部模式期间发生 Manager 变化,返回时重新读取。
bool m_bRegionVisible; ///< 原区域轮廓的实际可见状态。
bool m_bRegionDialogVisible; ///< 原区域统计面板是否可见。
};
nmWxPebiResultViewWidget::nmWxPebiResultViewWidget(
nmDataAnalyzeManager* pDataManager,
QWidget* pParent)
@ -818,6 +851,7 @@ nmWxPebiResultViewWidget::nmWxPebiResultViewWidget(
m_pFilterAction(nullptr),
m_pRegionPressureAction(nullptr),
m_pRegionState(new nmWxPebiResultRegionState),
m_pVolumeState(new nmWxPebiVolumeState),
m_bObservedSnapshotCurrent(false),
m_bObservedStateValid(false),
m_bSynchronizing(false),
@ -829,6 +863,16 @@ nmWxPebiResultViewWidget::nmWxPebiResultViewWidget(
nmWxPebiResultViewWidget::~nmWxPebiResultViewWidget()
{
// 先取消并断开队列回调,等待线程退出后才能释放窗口和相关 DLL 对象。
if(m_pVolumeState->m_pTask != nullptr) {
disconnect(m_pVolumeState->m_pTask, nullptr, this, nullptr);
m_pVolumeState->m_pTask->requestCancel();
m_pVolumeState->m_pTask->wait();
delete m_pVolumeState->m_pTask;
}
delete m_pVolumeState->m_pController;
delete m_pVolumeState;
m_pVolumeState = nullptr;
disconnectDataManager();
destroyRegionPressureState();
if(m_pControlBar != nullptr) {
@ -862,8 +906,21 @@ void nmWxPebiResultViewWidget::setDataManager(
return;
}
if(m_pVolumeState->m_pTask != nullptr) m_pVolumeState->m_pTask->requestCancel();
disconnectDataManager();
clearSceneAndControls(tr("No result data."));
if(isImportedVolumeMode()) {
// 分析上下文换绑时丢弃旧计算结果,但保留用户正在检查的外部模型。
clearRegionPressureSelection(false);
m_pSceneController->clear();
m_pDisplayedSnapshot.clear();
m_sDisplayedSnapshotId.clear();
m_pVolumeState->m_oSavedView = nmVTKViewState();
m_pVolumeState->m_bRegionVisible = false;
m_pVolumeState->m_bRegionDialogVisible = false;
m_pVolumeState->m_bPendingSync = true;
} else {
clearSceneAndControls(tr("No result data."));
}
m_pDataManager = pDataManager;
if(!m_pDataManager.isNull()) {
connect(m_pDataManager.data(), SIGNAL(sigPebiResultStateChanged()),
@ -913,6 +970,10 @@ void nmWxPebiResultViewWidget::onDataManagerDestroyed(QObject* pObject)
Q_UNUSED(pObject);
// destroyed() 到达时 QPointer 可能已经清空,槽内绝不再读取 Manager。
m_pDataManager = nullptr;
if(isImportedVolumeMode()) {
m_pVolumeState->m_bPendingSync = true;
return;
}
if(m_bSynchronizing) {
// 极端嵌套事件下不得在快照提交栈内递归清场,退出当前事务后再读空状态。
m_bSyncPending = true;
@ -930,6 +991,9 @@ void nmWxPebiResultViewWidget::appendContextMenuActions(QMenu* pMenu)
if(pMenu == nullptr) {
return;
}
pMenu->addAction(m_pVolumeState->m_pImportAction);
pMenu->addAction(m_pVolumeState->m_pReturnAction);
pMenu->addSeparator();
pMenu->addAction(m_pFilterAction);
pMenu->addAction(m_pRegionPressureAction);
pMenu->addSeparator();
@ -968,6 +1032,7 @@ void nmWxPebiResultViewWidget::onViewportSizeChanged(
int nWidth,
int nHeight)
{
if(m_pVolumeState->m_pController != nullptr) m_pVolumeState->m_pController->setViewportSize(nWidth, nHeight);
if(m_pSceneController != nullptr) {
// SceneController 缓存尺寸,即使当前尚未创建结果色标也不会丢失。
m_pSceneController->setViewportSize(nWidth, nHeight);
@ -976,6 +1041,7 @@ void nmWxPebiResultViewWidget::onViewportSizeChanged(
void nmWxPebiResultViewWidget::onShowFilterSettings()
{
if(isImportedVolumeMode()) return;
nmPebiResultPlaybackController* pPlaybackController =
m_pControlBar == nullptr ? nullptr :
m_pControlBar->getPlaybackController();
@ -998,6 +1064,7 @@ void nmWxPebiResultViewWidget::onShowFilterSettings()
void nmWxPebiResultViewWidget::onRegionPressureStatisticsTriggered()
{
if(isImportedVolumeMode()) return;
if(m_pRegionState == nullptr || m_pControlBar == nullptr) {
return;
}
@ -1223,6 +1290,7 @@ void nmWxPebiResultViewWidget::processPendingRegionInteractionEvent()
void nmWxPebiResultViewWidget::onResultDisplayStateChanged()
{
if(isImportedVolumeMode()) return;
if(m_pRegionState != nullptr && m_pSceneController != nullptr &&
m_pRegionState->m_eState ==
nmWxPebiResultRegionState::State_Completed) {
@ -1251,6 +1319,7 @@ void nmWxPebiResultViewWidget::onCloseRegionPressureStatistics()
void nmWxPebiResultViewWidget::onExportAnimationRequested()
{
if(isImportedVolumeMode()) return;
nmPebiResultPlaybackController* pPlaybackController =
m_pControlBar == nullptr ? nullptr :
m_pControlBar->getPlaybackController();
@ -1426,6 +1495,10 @@ void nmWxPebiResultViewWidget::onExportAnimationRequested()
void nmWxPebiResultViewWidget::onScalarBarToggled(bool bVisible)
{
if(isImportedVolumeMode()) {
m_pVolumeState->m_pController->setScalarBarVisible(bVisible);
return;
}
if(m_pControlBar != nullptr &&
m_pControlBar->isExternalInteractionLocked()) {
synchronizeBusinessActions();
@ -1438,6 +1511,10 @@ void nmWxPebiResultViewWidget::onScalarBarToggled(bool bVisible)
void nmWxPebiResultViewWidget::onScaleGridToggled(bool bVisible)
{
if(isImportedVolumeMode()) {
m_pVolumeState->m_pController->setScaleGridVisible(bVisible);
return;
}
if(m_pControlBar != nullptr &&
m_pControlBar->isExternalInteractionLocked()) {
synchronizeBusinessActions();
@ -1450,6 +1527,7 @@ void nmWxPebiResultViewWidget::onScaleGridToggled(bool bVisible)
void nmWxPebiResultViewWidget::onWellNamesToggled(bool bVisible)
{
if(isImportedVolumeMode()) return;
if(m_pControlBar != nullptr &&
m_pControlBar->isExternalInteractionLocked()) {
synchronizeBusinessActions();
@ -1489,6 +1567,7 @@ void nmWxPebiResultViewWidget::createUi()
nmVTKViewCommandController::ViewCommand_Print |
nmVTKViewCommandController::ViewCommand_PrintPreview);
m_pSceneController = new nmPebiResultSceneController(m_pRenderContainer);
m_pVolumeState->m_pController = new nmVolumeSceneController(m_pRenderContainer);
connect(m_pRenderContainer, SIGNAL(viewportSizeChanged(int,int)),
this, SLOT(onViewportSizeChanged(int,int)));
const QSize oInitialViewportSize =
@ -1567,6 +1646,39 @@ void nmWxPebiResultViewWidget::createUi()
if(pCopyAction != nullptr) m_pToolBar->addAction(pCopyAction);
}
// 只增加一个常驻按钮。小图标直接绘制,避免部署时丢失额外资源文件。
QPixmap oSliceIcon(32, 32);
oSliceIcon.fill(Qt::transparent);
{
QPainter oPainter(&oSliceIcon);
oPainter.setRenderHint(QPainter::Antialiasing);
oPainter.setPen(QPen(QColor(65, 85, 105), 1.5));
oPainter.drawRect(7, 5, 18, 22);
oPainter.setBrush(QColor(60, 155, 215, 160));
QPolygon oPlane;
oPlane << QPoint(3, 20) << QPoint(20, 11) << QPoint(29, 14) << QPoint(12, 24);
oPainter.drawPolygon(oPlane);
}
m_pVolumeState->m_pButton = new QToolButton(m_pToolBar);
m_pVolumeState->m_pButton->setObjectName(QLatin1String("volumeSliceButton"));
m_pVolumeState->m_pButton->setIcon(QIcon(oSliceIcon));
m_pVolumeState->m_pButton->setIconSize(m_pToolBar->iconSize());
m_pVolumeState->m_pButton->setText(tr("Slice"));
m_pVolumeState->m_pButton->setToolTip(tr("Slice"));
m_pVolumeState->m_pButton->setAutoRaise(true);
m_pVolumeState->m_pButton->setPopupMode(QToolButton::InstantPopup);
QMenu* pSliceMenu = new QMenu(m_pVolumeState->m_pButton);
m_pVolumeState->m_pImportAction = new QAction(tr("Import 3D Model..."), this);
m_pVolumeState->m_pImportAction->setObjectName(QLatin1String("importVolumeAction"));
m_pVolumeState->m_pReturnAction = new QAction(tr("Return to Calculation Result"), this);
m_pVolumeState->m_pReturnAction->setObjectName(QLatin1String("returnCalculationAction"));
pSliceMenu->addAction(m_pVolumeState->m_pImportAction);
pSliceMenu->addAction(m_pVolumeState->m_pReturnAction);
m_pVolumeState->m_pButton->setMenu(pSliceMenu);
m_pToolBar->addWidget(m_pVolumeState->m_pButton);
connect(m_pVolumeState->m_pImportAction, SIGNAL(triggered()), this, SLOT(onImportVolumeRequested()));
connect(m_pVolumeState->m_pReturnAction, SIGNAL(triggered()), this, SLOT(onReturnToCalculationResult()));
connect(m_pScalarBarAction, SIGNAL(toggled(bool)),
this, SLOT(onScalarBarToggled(bool)));
connect(m_pScaleGridAction, SIGNAL(toggled(bool)),
@ -1612,6 +1724,11 @@ void nmWxPebiResultViewWidget::createUi()
void nmWxPebiResultViewWidget::synchronizeOnce()
{
if(isImportedVolumeMode()) {
// 正式结果变化不能抢占正在查看的外部模型;返回时读取 Manager 最新快照。
m_pVolumeState->m_bPendingSync = true;
return;
}
if(m_pDataManager.isNull()) {
if(m_bObservedStateValid && m_pObservedSnapshot.isNull()) {
return;
@ -2210,6 +2327,8 @@ void nmWxPebiResultViewWidget::rememberObservedState(
void nmWxPebiResultViewWidget::synchronizeBusinessActions()
{
synchronizeVolumeActions();
if(isImportedVolumeMode()) return;
if(m_pSceneController == nullptr) {
return;
}
@ -2274,6 +2393,12 @@ void nmWxPebiResultViewWidget::synchronizeBusinessActions()
void nmWxPebiResultViewWidget::refreshStatusBar()
{
if(isImportedVolumeMode()) {
m_pStatusLabel->setStyleSheet("QLabel { color: #a32626; background: #fdecec; }");
m_pStatusLabel->setText(m_sOperationError);
m_pStatusLabel->setVisible(!m_sOperationError.isEmpty());
return;
}
if(m_pStatusLabel == nullptr || m_pSceneController == nullptr ||
!m_pSceneController->hasSnapshot()) {
if(m_pStatusLabel != nullptr) {
@ -2310,3 +2435,187 @@ void nmWxPebiResultViewWidget::disconnectDataManager()
}
m_pDataManager = nullptr;
}
bool nmWxPebiResultViewWidget::isImportedVolumeMode() const
{
return m_pVolumeState != nullptr && m_pVolumeState->m_bImported;
}
bool nmWxPebiResultViewWidget::canImportVolume() const
{
if(m_pVolumeState == nullptr || m_pVolumeState->m_pTask != nullptr ||
m_pControlBar == nullptr || m_pControlBar->isExportInProgress() ||
isRegionPressureDrawing()) return false;
nmPebiResultPlaybackController* pPlayback = m_pControlBar->getPlaybackController();
return (pPlayback == nullptr || !pPlayback->isPlaying()) &&
(isImportedVolumeMode() || !m_pControlBar->isExternalInteractionLocked());
}
void nmWxPebiResultViewWidget::synchronizeVolumeActions()
{
if(m_pVolumeState == nullptr || m_pVolumeState->m_pImportAction == nullptr) return;
m_pVolumeState->m_pImportAction->setEnabled(canImportVolume());
m_pVolumeState->m_pImportAction->setText(isImportedVolumeMode()
? tr("Replace 3D Model...") : tr("Import 3D Model..."));
m_pVolumeState->m_pReturnAction->setEnabled(isImportedVolumeMode() && m_pVolumeState->m_pTask == nullptr);
if(!isImportedVolumeMode()) return;
nmVolumeSceneController* pVolume = m_pVolumeState->m_pController;
setActionCheckedWithoutSignal(m_pScalarBarAction, pVolume->isScalarBarVisible());
setActionCheckedWithoutSignal(m_pScaleGridAction, pVolume->isScaleGridVisible());
m_pScalarBarAction->setEnabled(pVolume->hasScalarProperty());
m_pScaleGridAction->setEnabled(pVolume->hasData());
m_pWellNamesAction->setEnabled(false);
m_pFilterAction->setEnabled(false);
m_pRegionPressureAction->setEnabled(false);
m_pControlBar->getExportAnimationAction()->setEnabled(false);
}
void nmWxPebiResultViewWidget::onImportVolumeRequested()
{
if(!canImportVolume()) return;
const QString sFilePath = QFileDialog::getOpenFileName(this, tr("Import 3D Model"),
QString(), tr("VTK Volume Mesh (*.vtk *.vtu)"));
if(!sFilePath.isEmpty()) importVolumeFile(sFilePath);
}
bool nmWxPebiResultViewWidget::importVolumeFile(const QString& sFilePath)
{
if(!isResultViewGuiThread() || sFilePath.isEmpty() || !canImportVolume()) return false;
m_pVolumeState->m_pTask = new nmVolumeImportTask(sFilePath, this);
m_pVolumeState->m_pProgress = new QProgressDialog(tr("Loading 3D model..."), tr("Cancel"), 0, 100, this);
m_pVolumeState->m_pProgress->setObjectName(QLatin1String("volumeImportProgress"));
m_pVolumeState->m_pProgress->setWindowModality(Qt::WindowModal);
m_pVolumeState->m_pProgress->setMinimumDuration(0);
m_pVolumeState->m_pProgress->setAutoClose(false);
m_pVolumeState->m_pProgress->setAutoReset(false);
connect(m_pVolumeState->m_pProgress, SIGNAL(canceled()), this, SLOT(onCancelVolumeImport()));
connect(m_pVolumeState->m_pTask, SIGNAL(progressChanged(int)),
m_pVolumeState->m_pProgress, SLOT(setValue(int)), Qt::QueuedConnection);
connect(m_pVolumeState->m_pTask, SIGNAL(finished()),
this, SLOT(onVolumeImportFinished()), Qt::QueuedConnection);
m_pVolumeState->m_pProgress->show();
synchronizeBusinessActions();
m_pVolumeState->m_pTask->start();
return true;
}
void nmWxPebiResultViewWidget::onCancelVolumeImport()
{
if(m_pVolumeState->m_pTask != nullptr) m_pVolumeState->m_pTask->requestCancel();
}
void nmWxPebiResultViewWidget::onVolumeImportFinished()
{
nmVolumeImportTask* pTask = m_pVolumeState->m_pTask;
if(pTask == nullptr || sender() != pTask) return;
// finished 发出后仍等待线程完全退出,确保结果和字符串已不再被工作线程改写。
pTask->wait();
const bool bCanceled = pTask->isCanceled();
const QSharedPointer<const nmVolumeData> pData = pTask->getResult();
QString sError = pTask->getError();
disconnect(pTask, nullptr, nullptr, nullptr);
delete pTask;
m_pVolumeState->m_pTask = nullptr;
// 模态进度更新可能嵌套处理 Qt 事件;延迟删除,避免在 setValue 栈内析构。
m_pVolumeState->m_pProgress->hide();
m_pVolumeState->m_pProgress->deleteLater();
m_pVolumeState->m_pProgress = nullptr;
if(bCanceled) {
synchronizeBusinessActions();
return;
}
nmVTKViewState oPreviousView;
m_pRenderContainer->captureViewState(oPreviousView);
if(pData.isNull() || !m_pVolumeState->m_pController->setData(pData, &sError)) {
m_sOperationError = sError.isEmpty() ? tr("Unable to display the 3D model.") : sError;
synchronizeBusinessActions();
// 空结果页也应显示导入错误,而不是把错误藏在不可见的旧结果状态中。
m_pStatusLabel->setStyleSheet("QLabel { color: #a32626; background: #fdecec; }");
m_pStatusLabel->setText(m_sOperationError);
m_pStatusLabel->show();
return;
}
if(!isImportedVolumeMode()) {
m_pVolumeState->m_oSavedView = oPreviousView;
m_pVolumeState->m_eSavedCommands = m_pRenderContainer->getViewCommandController()->getCapabilities();
m_pControlBar->stopPlayback();
stopRegionPressureDrawing();
// 区域图层由 Scene 所有;先核实对象身份,避免访问已被外部清理的观察指针。
nmVTKScene* pScene = m_pRenderContainer->getScene();
const bool bHasRegionLayer = pScene != nullptr && m_pRegionState->m_pLayer != nullptr &&
pScene->getLayer(QString::fromLatin1(PEBI_REGION_PRESSURE_LAYER_ID)) == m_pRegionState->m_pLayer;
m_pVolumeState->m_bRegionVisible = bHasRegionLayer && m_pRegionState->m_pLayer->isVisible();
m_pVolumeState->m_bRegionDialogVisible = m_pRegionState->m_pDialog != nullptr && m_pRegionState->m_pDialog->isVisible();
if(bHasRegionLayer) m_pRegionState->m_pLayer->setVisible(false);
if(m_pRegionState->m_pDialog != nullptr) m_pRegionState->m_pDialog->hide();
m_pSceneController->setSuspended(true);
}
m_pRenderContainer->setViewCommandCapabilities(m_pVolumeState->m_eSavedCommands |
nmVTKViewCommandController::ViewCommand_Right |
nmVTKViewCommandController::ViewCommand_Isometric);
m_pVolumeState->m_bImported = true;
m_pControlBar->setExternalInteractionLocked(true);
m_pControlBar->hide();
m_pRenderContainer->restoreDefaultInteraction();
m_pVolumeState->m_pController->activate(true);
m_sOperationError.clear();
synchronizeBusinessActions();
refreshStatusBar();
m_pRenderContainer->showReadyState();
}
void nmWxPebiResultViewWidget::onReturnToCalculationResult()
{
if(!isImportedVolumeMode() || m_pVolumeState->m_pTask != nullptr) return;
const QSharedPointer<const nmPebiResultSnapshot> pLatest = m_pDataManager.isNull()
? QSharedPointer<const nmPebiResultSnapshot>() : m_pDataManager->getPebiResultSnapshot();
const bool bSameSnapshot = !pLatest.isNull() && pLatest == m_pDisplayedSnapshot &&
pLatest->getSnapshotId() == m_sDisplayedSnapshotId && m_pSceneController->hasSnapshot();
if(!pLatest.isNull() && !bSameSnapshot) {
QString sError;
// PEBI 仍处于挂起状态,候选绑定既不显示图层,也不移动当前三维相机。
if(!m_pSceneController->setSnapshot(pLatest, &sError)) {
m_sOperationError = tr("Unable to return to the latest calculation result: %1").arg(sError);
refreshStatusBar();
return;
}
}
m_pVolumeState->m_pController->hide();
m_pRenderContainer->setRotationCenterPickTarget(nullptr);
m_pVolumeState->m_bImported = false;
m_pRenderContainer->setViewCommandCapabilities(m_pVolumeState->m_eSavedCommands);
if(pLatest.isNull()) {
m_pSceneController->setSuspended(false);
m_pVolumeState->m_pController->clear();
clearSceneAndControls(tr("No result data."));
} else {
if(!bSameSnapshot) clearRegionPressureSelection(false);
m_pSceneController->setSuspended(false);
if(bSameSnapshot) {
m_pRenderContainer->restoreViewState(m_pVolumeState->m_oSavedView);
nmVTKScene* pScene = m_pRenderContainer->getScene();
if(pScene != nullptr && m_pRegionState->m_pLayer != nullptr &&
pScene->getLayer(QString::fromLatin1(PEBI_REGION_PRESSURE_LAYER_ID)) == m_pRegionState->m_pLayer) {
m_pRegionState->m_pLayer->setVisible(m_pVolumeState->m_bRegionVisible);
}
if(m_pVolumeState->m_bRegionDialogVisible && m_pRegionState->m_pDialog != nullptr) m_pRegionState->m_pDialog->show();
} else {
m_pRenderContainer->fitTopViewWithoutRender();
m_pRenderContainer->resetRotationCenterWithoutRender();
}
m_pVolumeState->m_pController->clear();
m_pDisplayedSnapshot = pLatest;
m_sDisplayedSnapshotId = pLatest->getSnapshotId();
rememberObservedState(pLatest, m_sDisplayedSnapshotId, m_pDataManager->isPebiResultSnapshotCurrent());
m_sBindingError.clear();
m_sOperationError.clear();
m_pRenderContainer->showReadyState();
}
m_pVolumeState->m_bPendingSync = false;
m_pVolumeState->m_oSavedView = nmVTKViewState();
m_pControlBar->setExternalInteractionLocked(false);
m_pControlBar->show();
m_pControlBar->synchronizeFromScene();
synchronizeBusinessActions();
refreshStatusBar();
}

@ -32,6 +32,7 @@ SOURCES += $${wtSrc}/nmNum/nmRender/nmVTKCameraController.cpp \
$${wtSrc}/nmNum/nmRender/nmVTKScalarBarLayer.cpp \
$${wtSrc}/nmNum/nmRender/nmVTKScene.cpp \
$${wtSrc}/nmNum/nmRender/nmVTKViewCommandController.cpp \
$${wtSrc}/nmNum/nmRender/nmVTKViewState.cpp \
$${wtSrc}/nmNum/nmRender/nmWxVTKRenderContainerWidget.cpp
HEADERS += $${wtInclude}/nmNum/nmRender/nmRender_global.h \
@ -52,4 +53,5 @@ HEADERS += $${wtInclude}/nmNum/nmRender/nmRender_global.h \
$${wtInclude}/nmNum/nmRender/nmVTKScalarBarLayer.h \
$${wtInclude}/nmNum/nmRender/nmVTKScene.h \
$${wtInclude}/nmNum/nmRender/nmVTKViewCommandController.h \
$${wtInclude}/nmNum/nmRender/nmVTKViewState.h \
$${wtInclude}/nmNum/nmRender/nmWxVTKRenderContainerWidget.h

Loading…
Cancel
Save