You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nmWTAI-Platform/Src/nmNum/nmPlot/nmObjBase.cpp

423 lines
16 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <QPainter>
#include "nmObjBase.h"
#include "ZxRenderView.h"
#include "ZxPlot.h"
#include "nmObjPolygonOutline.h"
#include "nmPlotView.h"
#include <QPointer>
#include <QScopedValueRollback>
#include <QUndoStack>
#include <QUuid>
#include <QtCore/qnumeric.h>
ZX_DEFINE_DYNAMIC(nObjBase, nmObjBase)
namespace {
// 只保存点集编辑涉及的几何,不复制图元的业务属性。
struct Geometry
{
// 从已提交的图元上取模型坐标和边类型,供命令回放。
explicit Geometry(nmObjBase* object) : points(object->getAllValues())
{
if (nmObjPolygonOutline* outline = qobject_cast<nmObjPolygonOutline*>(object)) {
flowTypes = outline->m_vFlowTypeList;
}
}
QVector<QPointF> points; ///< 图元点集的模型坐标。
QVector<int> flowTypes; ///< 多边形边界各边的流动类型,按顶点下标对应。
};
// 以模型坐标和稳定标识记录编辑,支持删除恢复后继续撤销此前的拖动。
class nmGeometryCommand : public QUndoCommand
{
public:
// 保存编辑前后的几何,以及单点插入在新点集中的下标。
nmGeometryCommand(nmObjBase* object, const Geometry& before, const Geometry& after,
int insertedPointIndex, QUndoCommand* group)
: QUndoCommand(group), m_plot(object->getPlot()), m_id(object->historyId()),
m_before(before), m_after(after), m_insertedPointIndex(insertedPointIndex),
m_mergedEdgeType(0), m_initialRedo(true)
{
}
// 恢复本次编辑之前的几何。
virtual void undo() override { apply(m_after, m_before); }
// 重新应用编辑结果,跳过入栈时自动触发的首次调用。
virtual void redo() override
{
if (m_initialRedo) {
m_initialRedo = false;
} else {
apply(m_before, m_after);
}
}
private:
// 分量已被另外编辑时,从撤销和恢复两侧同时移除这项修改。
static void applyCoordinateChange(qreal& current, qreal& from, qreal& to)
{
if (from == to) return;
if (current == from) {
current = to;
} else {
from = current;
to = current;
}
}
// 对同一节点的 X、Y 分别回放,保留其他坐标的后续修改。
void applyCoordinateChanges(QVector<QPointF>& points, Geometry& source, Geometry& target)
{
for (int i = 0; i < points.size(); ++i) {
QPointF& from = source.points[i];
QPointF& to = target.points[i];
QPointF& current = points[i];
applyCoordinateChange(current.rx(), from.rx(), to.rx());
applyCoordinateChange(current.ry(), from.ry(), to.ry());
}
}
// 只增删插入的点及新边。合并边若被改过,两段都继承当前类型。
void applyPointInsertion(nmObjBase* object, QVector<QPointF>& points,
Geometry& source, const Geometry& target)
{
const int index = m_insertedPointIndex;
const bool inserting = points.size() < target.points.size();
nmObjPolygonOutline* outline = qobject_cast<nmObjPolygonOutline*>(object);
if (outline != nullptr) {
// 旧数据可能缺少少量边类型,按当前点数补齐再修改对应的一条边。
const int defaultType = NM_OIL_RESERVOIR_OUTLINE_TYPE::OIL_Reservoir_Outline_No_Flow;
QVector<int>& types = outline->m_vFlowTypeList;
if (types.size() > points.size()) types.resize(points.size());
while (types.size() < points.size()) types.append(defaultType);
const int precedingIndex = (index + types.size() - 1) % types.size();
const int mergedType = types.at(precedingIndex);
if (inserting) {
const int splitType = mergedType == m_mergedEdgeType
? target.flowTypes.value(index, mergedType) : mergedType;
types.insert(index, splitType);
} else {
m_mergedEdgeType = mergedType;
if (source.flowTypes.size() <= index) source.flowTypes.resize(index + 1);
source.flowTypes[index] = types.at(index);
types.remove(index);
}
}
if (inserting) {
points.insert(index, target.points.at(index));
} else {
source.points[index] = points.at(index);
points.remove(index);
}
}
// 写入模型坐标并通知绑定器,避免回放时再次生成历史。
void apply(Geometry& source, Geometry& target)
{
nmObjBase* object = nmObjBase::findHistoryObject(m_plot.data(), m_id);
if (object == nullptr) return;
const QVector<QPointF> current = object->getAllValues();
if (current.size() != source.points.size()) return;
QVector<QPointF> points = current;
if (m_insertedPointIndex >= 0) {
applyPointInsertion(object, points, source, target);
} else if (source.points.size() == target.points.size()) {
applyCoordinateChanges(points, source, target);
} else {
// 保留非单点插入工况下的整组几何恢复。
points = target.points;
if (nmObjPolygonOutline* outline = qobject_cast<nmObjPolygonOutline*>(object)) {
outline->m_vFlowTypeList = target.flowTypes;
}
}
if (points == current) return;
object->applyHistoryPointValues(points);
// 直接写模型坐标不会走边界的场景坐标提交入口,需单独通知边界绑定。
const int signalIndex = object->metaObject()->indexOfSignal("sigOutlinePointsChanged()");
if (signalIndex >= 0) {
QMetaObject::invokeMethod(object, "sigOutlinePointsChanged", Qt::DirectConnection);
}
}
QPointer<ZxPlot> m_plot; ///< 原画布的弱引用,画布销毁后回放自然结束。
QString m_id; ///< 在原画布内查找图元的会话标识。
Geometry m_before; ///< 编辑提交前的几何状态。
Geometry m_after; ///< 编辑提交后的几何状态。
int m_insertedPointIndex; ///< 双击插入的节点下标,其他编辑为 -1。
int m_mergedEdgeType; ///< 撤销插点时合并边的类型,供恢复时识别后续修改。
bool m_initialRedo; ///< 区分入栈时的首次回调和用户主动重做。
};
// 以提交前后的模型坐标记录地图编辑,供场景拖动和属性输入共用。
bool recordGeometryEdit(nmObjBase* object, const Geometry& before, int insertedPointIndex)
{
const Geometry after(object);
if (before.points == after.points && before.flowTypes == after.flowTypes) return false;
nmPlotView* view = qobject_cast<nmPlotView*>(object->getView());
if (view != nullptr && view->mapEditHistory() != nullptr && object->getPlot() != nullptr) {
const bool singleInsertion = !before.points.isEmpty() &&
after.points.size() == before.points.size() + 1 &&
insertedPointIndex >= 0 && insertedPointIndex < after.points.size();
QUndoCommand* group = view->mapGeometryEditGroup();
QUndoCommand* command = new nmGeometryCommand(object, before, after,
singleInsertion ? insertedPointIndex : -1, group);
if (group == nullptr) view->mapEditHistory()->push(command);
}
return true;
}
} // namespace
nmObjBase::nmObjBase()
: m_bApplyingGeometryHistory(false)
{
}
nmObjBase::nmObjBase(const QString& sName, \
ZxSubAxisX* pAxisX, \
ZxSubAxisY* pAxisY)
: m_bApplyingGeometryHistory(false)
{
}
nmObjBase::~nmObjBase()
{
}
void nmObjBase::paintBack(QPainter* painter, const ZxPaintParam& param)
{
ZxObjBase::paintBack(painter, param);
}
void nmObjBase::afterCreated()
{
}
void nmObjBase::setPen(QPen pen)
{
const bool changed = getPen() != pen;
ZxObjBase::setPen(pen);
if (changed) emit sigMapPenChanged();
}
void nmObjBase::removeData()
{
}
bool nmObjBase::moveNodeToPosition(int index, const QPointF& position)
{
QVector<QPointF> positions = getAllPos();
if (index < 0 || index >= positions.size()) return false;
positions[index] = position;
return commitPointPositions(positions);
}
bool nmObjBase::commitPointCoordinate(int index, Qt::Orientation axis, double value)
{
QVector<QPointF> points = getAllValues();
if (index < 0 || index >= points.size()) return false;
QPointF& point = points[index];
if (axis == Qt::Horizontal) {
point.setX(value);
} else {
point.setY(value);
}
return commitPointValues(points);
}
bool nmObjBase::commitPointValues(const QVector<QPointF>& values)
{
foreach (const QPointF& point, values) {
if (!qIsFinite(point.x()) || !qIsFinite(point.y())) return false;
}
const Geometry before(this);
if (values == before.points) return false;
setAllValues(values);
return recordGeometryEdit(this, before, -1);
}
void nmObjBase::applyHistoryPointValues(const QVector<QPointF>& values)
{
QScopedValueRollback<bool> historyScope(m_bApplyingGeometryHistory);
m_bApplyingGeometryHistory = true;
setAllValues(values);
}
QString nmObjBase::historyId()
{
QString id = property("nmMapHistoryId").toString();
if (id.isEmpty()) {
id = QUuid::createUuid().toString();
setHistoryId(id);
}
return id;
}
void nmObjBase::setHistoryId(const QString& id)
{
setProperty("nmMapHistoryId", id);
}
nmObjBase* nmObjBase::findHistoryObject(ZxPlot* plot, const QString& id)
{
if (plot == nullptr || id.isEmpty()) return nullptr;
for (int i = 0; i < plot->getObjCount(); ++i) {
nmObjBase* object = qobject_cast<nmObjBase*>(plot->getObjByIndex(i));
if (object != nullptr && object->property("nmMapHistoryId").toString() == id) {
return object;
}
}
return nullptr;
}
bool nmObjBase::commitPointPositions(const QVector<QPointF>& positions, int insertedPointIndex)
{
foreach (const QPointF& point, positions) {
if (!qIsFinite(point.x()) || !qIsFinite(point.y())) return false;
}
const Geometry before(this);
if (getAllPos() == positions) return false;
// 走图元的场景坐标提交入口,保留多边形边界插点时的分边规则。
setAllPos(positions);
return recordGeometryEdit(this, before, insertedPointIndex);
}
void nmObjBase::paintNodeHandle(QPainter* painter, const QPointF& pt,
int nPixelSize, const QColor& borderColor,
const QColor& fillColor)
{
if (painter == nullptr || nPixelSize < 2) {
return;
}
// 先转换节点中心,再临时取消地图变换;框的大小和线宽不随缩放变化。
// combinedTransform 不包含设备像素比,Qt 继续负责高 DPI 下的逻辑像素映射。
const QPointF screenPos = painter->combinedTransform().map(pt);
if (!qIsFinite(screenPos.x()) || !qIsFinite(screenPos.y())) {
return;
}
painter->save();
painter->resetTransform();
painter->setRenderHint(QPainter::Antialiasing, false);
QPen pen(borderColor);
pen.setWidthF(1.0);
painter->setPen(pen);
painter->setBrush(fillColor.isValid() ? QBrush(fillColor) : QBrush(Qt::NoBrush));
// 关闭抗锯齿时,Qt 已将 1 像素边线落到像素格内,只需对左上角取整。
// 不再额外加半像素,避免栅格化后节点框向右下偏离折线交点。
// 路径宽高扣除边线,使可见外框仍为 nPixelSize 像素。
const qreal left = qRound(screenPos.x() - nPixelSize * 0.5);
const qreal top = qRound(screenPos.y() - nPixelSize * 0.5);
painter->drawRect(QRectF(left, top, nPixelSize - 1, nPixelSize - 1));
painter->restore();
}
void nmObjBase::paintSelectedNodeHandles(QPainter* painter, const QVector<QPointF>& points,
int firstIndex) const
{
if (!isSelected()) {
return;
}
for (int i = firstIndex; i < points.count(); ++i) {
const bool active = m_oHitOption == OHO_Point && m_nHitIndex == i;
const QColor nodeColor = active ? QColor(Qt::red) : QColor(0, 0, 128);
paintNodeHandle(painter, points[i], 5, nodeColor, active ? nodeColor : QColor());
}
}
bool nmObjBase::hitTestPolylineInPixels(const QPointF& pt, bool closed,
int& nOption, int& nSubIndex,
bool includeSelectedInterior)
{
nOption = -1;
nSubIndex = -1;
// 保留框架对对象可交互状态的检查,几何命中范围由下面的像素距离统一决定。
if (!ZxObjBase::_runHitTest(pt, nOption, nSubIndex) ||
m_pAxisX == nullptr || m_pAxisY == nullptr) {
return false;
}
ZxRenderView* view = getView();
if (view == nullptr) {
return false;
}
// 使用对象所属地图的变换,不依赖全局活动视图;缩放、平移后直接查询最新位置。
const QPointF mousePos = view->mapFromScene(pt);
if (!qIsFinite(mousePos.x()) || !qIsFinite(mousePos.y())) {
return false;
}
QVector<QPointF> points = getPosOf(m_vecPoints);
const qreal nodeRadius = NodeHitRadiusPixels;
const qreal segmentRadius = OutlineHitRadiusPixels;
qreal nearestDistanceSquared = nodeRadius * nodeRadius;
int nearestIndex = -1;
for (int i = 0; i < points.count(); ++i) {
points[i] = view->mapFromScene(points[i]);
const QPointF delta = mousePos - points[i];
const qreal distanceSquared = delta.x() * delta.x() + delta.y() * delta.y();
if (qIsFinite(distanceSquared) && distanceSquared <= nearestDistanceSquared &&
(nearestIndex < 0 || distanceSquared < nearestDistanceSquared)) {
nearestIndex = i;
nearestDistanceSquared = distanceSquared;
}
}
if (nearestIndex >= 0) {
nOption = OHO_Point;
nSubIndex = nearestIndex;
return true;
}
// 节点全部未命中后才判断线段;默认只命中边线,内部拖动由调用方显式开启。
// 相等距离保留首项,靠近多个节点或交叉线段时不会随遍历覆盖而改变结果。
if (points.count() < 2) {
return false;
}
nearestDistanceSquared = segmentRadius * segmentRadius;
const int segmentCount = closed ? points.count() : points.count() - 1;
zxGmyBase geometry;
for (int i = 0; i < segmentCount; ++i) {
const QPointF& start = points[i];
const QPointF& end = points[(i + 1) % points.count()];
if (!qIsFinite(start.x()) || !qIsFinite(start.y()) ||
!qIsFinite(end.x()) || !qIsFinite(end.y()) || start == end) {
// 重复端点已参与上面的节点命中,零长度线段不再参与投影计算。
continue;
}
double ratio = 0.0;
const qreal distanceSquared = geometry.pointSegmentDistanceSquared2D(mousePos, start, end, ratio);
if (qIsFinite(distanceSquared) && distanceSquared <= nearestDistanceSquared &&
(nearestIndex < 0 || distanceSquared < nearestDistanceSquared)) {
nearestIndex = i;
nearestDistanceSquared = distanceSquared;
}
}
if (nearestIndex >= 0) {
nOption = OHO_Bound;
nSubIndex = nearestIndex;
return true;
}
if (includeSelectedInterior && closed && isSelected() && points.count() >= 3) {
// 点和边优先;未选中时不抢占内部其他图元,保留边界的既有选择规则。
QPainterPath path;
for (int i = 0; i < points.count(); ++i) {
if (!qIsFinite(points[i].x()) || !qIsFinite(points[i].y())) return false;
if (i == 0) path.moveTo(points[i]);
else path.lineTo(points[i]);
}
path.closeSubpath();
if (path.contains(mousePos)) {
nOption = OHO_Inner;
nSubIndex = 0;
return true;
}
}
return false;
}