## **MeasurePlugin**

## 功能说明

MeasurePlugin 是新版测量插件，用于在空间中测量距离和面积。相比经典版 [PanoMeasurePlugin](https://open.realsee.cn/docs/dnalogel/measure/PanoMeasurePlugin)，新版测量插件提供了更简洁的 API 和更好的用户体验。

:::tip 插件对比
关于 MeasurePlugin 和 PanoMeasurePlugin 的详细对比，请参阅 [使用说明](https://open.realsee.cn/docs/dnalogel/measure)。
:::

## 快速开始

### 安装

```bash
npm install @realsee/dnalogel
```

### 初始化

通过 Five plugins 方式初始化：

```ts twoslash
// @noErrors
import { MeasurePlugin } from '@realsee/dnalogel'
import { Five } from '@realsee/five'

const five = new Five({
  plugins: [
    [MeasurePlugin, 'measurePlugin', { unit: 'm' }]
  ]
})

const measurePlugin = five.plugins.measurePlugin as ReturnType<typeof MeasurePlugin>
```

也可以自己初始化：

```ts twoslash
// @noErrors
// ---cut---
import { MeasurePlugin } from '@realsee/dnalogel'

const measurePlugin = MeasurePlugin(five, { unit: 'm' })
```

### 配置项

```ts twoslash
// @noErrors
import type { MeasurePlugin } from '@realsee/dnalogel'

type MeasurePluginConfig = Parameters<typeof MeasurePlugin>[1]
// ---cut---
const config: MeasurePluginConfig = {
  // 测量单位：'m' (米) | 'ft' (英尺) | 'mm' (毫米)
  unit: 'm',
  // 是否显示长度标签，默认 true
  lengthEnable: true,
  // 长度测量的小数位数，默认 2
  precision: 2,
}
```

## 基础用法

### 开始测量

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.measure()
```

### 结束测量

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.endMeasure()
```

### 撤销上一步

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.undo()
```

### 取消本次测量

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.cancel()
```

### 清空所有测量

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.clear()
```

### 销毁插件

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.dispose()
```

## 配置方法

### 切换单位

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.setUnit('ft') // 切换到英尺
measurePlugin.setUnit('m')  // 切换到米
measurePlugin.setUnit('mm') // 切换到毫米
```

### 设置精度

```ts twoslash
// @noErrors
// ---cut---
// 设置长度测量的小数位数
measurePlugin.setPrecision(3)
```

### 显示/隐藏长度标签

```ts twoslash
// @noErrors
// ---cut---
measurePlugin.setLengthEnable(false) // 隐藏长度标签
measurePlugin.setLengthEnable(true)  // 显示长度标签
```

## 事件监听

### measureEnd 事件

:::info 重要
`measureEnd` 事件是 MeasurePlugin 的核心事件，在每次测量结束时触发。通过监听此事件，您可以获取测量点坐标并进行自定义计算。
:::

#### 事件参数

| 参数 | 类型 | 说明 |
|------|------|------|
| reason | `MeasureEndReason` | 测量结束的原因 |
| points | `THREE.Vector3[]` | 测量点坐标数组 |

#### MeasureEndReason 枚举

| 值 | 说明 |
|----|------|
| `'enter'` | 按 Enter 键完成 |
| `'escape'` | 按 Esc 键取消 |
| `'polygon'` | 自动完成多边形（首尾点重合） |
| `'mode_change'` | 模式改变导致结束 |
| `'pano_move'` | 全景移动导致结束 |
| `'floor_change'` | 楼层改变导致结束 |
| `'points_insufficient'` | 点数不足（少于2个点） |
| `'external'` | 外部调用 `endMeasure()` 结束 |

### 完整使用示例

以下示例展示了如何监听 `measureEnd` 事件并计算测量结果（包括线段长度和多边形面积）：

```tsx twoslash
// @noErrors
import { useEffect } from 'react'
import * as THREE from 'three'
import { unsafe__useFiveInstance } from '@realsee/five/react'
import { Util, validatePolygon } from '@realsee/dnalogel'
import type { MeasurePlugin } from '@realsee/dnalogel'

// 获取测量控制器类型
type MeasureController = ReturnType<typeof MeasurePlugin>
// 测量结束原因类型
type MeasureEndReason = Parameters<Parameters<MeasureController['on']>[1]>[0]

// 从 Util 中获取工具函数
const { getGeometryInfo, generatePolygonGeometry } = Util
const { transformUnit, transformUnitSquare } = Util.sculpt

/**
 * 计算测量结果（线段长度和多边形面积）
 * @param points 测量点数组
 * @param unit 单位 'm' | 'ft' | 'mm'
 * @param precision 精度（小数位数）
 */
function calculateMeasurement(points: THREE.Vector3[], unit: 'm' | 'ft' | 'mm' = 'm', precision: number = 2) {
  if (points.length < 2) {
    return { lineLengths: [], totalLength: null, area: null, isPolygon: false }
  }

  // 计算每条线段的长度
  const lineLengths: string[] = []
  let totalLengthValue = 0

  for (let i = 1; i < points.length; i++) {
    const p0 = points[i - 1]
    const p1 = points[i]
    const distance = p0.distanceTo(p1)
    totalLengthValue += distance
    const lengthStr = transformUnit(distance, unit, precision)
    if (lengthStr) {
      lineLengths.push(lengthStr)
    }
  }

  const totalLength = transformUnit(totalLengthValue, unit, precision)

  // 检查是否为多边形（首尾点重合且点数>=3）
  const isPolygon = validatePolygon(points)
  let area: string | undefined = undefined

  if (isPolygon) {
    // 生成多边形几何体并计算面积
    const geometry = generatePolygonGeometry(points)
    if (geometry) {
      const geometryInfo = getGeometryInfo(geometry)
      if (geometryInfo) {
        area = transformUnitSquare(geometryInfo.area, unit)
      }
    }
  }

  return { lineLengths, totalLength, area, isPolygon }
}

const MeasurePluginUsage = () => {
  const five = unsafe__useFiveInstance()
  const measurePlugin = five.plugins.measurePlugin as MeasureController

  useEffect(() => {
    // 监听测量结束事件
    const handleMeasureEnd = (reason: MeasureEndReason, points: THREE.Vector3[]) => {
      console.log('=== 测量结束 ===')
      console.log('结束原因:', reason)
      console.log('测量点:', points.map((p) => `(${p.x.toFixed(3)}, ${p.y.toFixed(3)}, ${p.z.toFixed(3)})`))

      // 计算测量结果
      const result = calculateMeasurement(points, 'm', 2)

      console.log('--- 计算结果 ---')
      console.log('是否为多边形:', result.isPolygon)
      console.log('各线段长度:', result.lineLengths)
      console.log('总长度:', result.totalLength)
      if (result.area) {
        console.log('面积:', result.area)
      }
      console.log('================')
    }

    measurePlugin.on('measureEnd', handleMeasureEnd)

    return () => {
      measurePlugin.off('measureEnd', handleMeasureEnd)
    }
  }, [measurePlugin])

  return (
    <div>
      <button onClick={() => measurePlugin.measure()}>开始测量</button>
      <button onClick={() => measurePlugin.endMeasure()}>结束测量</button>
      <button onClick={() => measurePlugin.clear()}>清空</button>
      <button onClick={() => measurePlugin.undo()}>撤销</button>
      <button onClick={() => measurePlugin.dispose()}>关闭</button>
    </div>
  )
}

export default MeasurePluginUsage
```

## 面积计算说明

:::warning 重要提示
MeasurePlugin 本身不直接返回面积值。要获取多边形面积，您需要使用 `Util` 中提供的工具函数进行计算。
:::

### 计算流程

1. **验证多边形**：使用 `validatePolygon(points)` 检查点集是否构成有效多边形
2. **生成几何体**：使用 `generatePolygonGeometry(points)` 生成 THREE.BufferGeometry
3. **计算面积**：使用 `getGeometryInfo(geometry)` 获取面积信息
4. **格式化输出**：使用 `transformUnitSquare(area, unit)` 转换为带单位的字符串

### 工具函数说明

| 函数 | 说明 |
|------|------|
| `validatePolygon(points)` | 验证点集是否构成有效多边形（首尾点重合、不共线、共面） |
| `generatePolygonGeometry(points)` | 根据多边形顶点生成 BufferGeometry |
| `getGeometryInfo(geometry)` | 获取几何体信息，包括面积和中心点 |
| `transformUnit(value, unit, precision)` | 将长度值转换为带单位的字符串 |
| `transformUnitSquare(value, unit)` | 将面积值转换为带单位的字符串 |

### 代码示例

```ts twoslash
// @noErrors
import * as THREE from 'three'
import { Util, validatePolygon } from '@realsee/dnalogel'

const { getGeometryInfo, generatePolygonGeometry } = Util
const { transformUnitSquare } = Util.sculpt

// 假设这是测量得到的点
const points: THREE.Vector3[] = [
  new THREE.Vector3(0, 0, 0),
  new THREE.Vector3(1, 0, 0),
  new THREE.Vector3(1, 0, 1),
  new THREE.Vector3(0, 0, 1),
  new THREE.Vector3(0, 0, 0), // 闭合点
]

// 1. 验证是否为多边形
if (validatePolygon(points)) {
  // 2. 生成几何体
  const geometry = generatePolygonGeometry(points)

  if (geometry) {
    // 3. 获取面积信息
    const geometryInfo = getGeometryInfo(geometry)

    if (geometryInfo) {
      // 4. 格式化输出
      const areaString = transformUnitSquare(geometryInfo.area, 'm')
      console.log('面积:', areaString) // 输出: "1.00m²"
    }
  }
}
```

## 快捷键

| 快捷键 | 功能 |
|--------|------|
| `Enter` | 完成当前测量 |
| `Esc` | 取消当前测量 |
| `Ctrl/Cmd + Z` | 撤销上一个点 |
| `Delete` / `Backspace` | 删除选中的测量 |
| `Shift + Click` | 在显示直角三角形辅助线时，选择垂直点而非射线交点 |

## 类型导出

```ts twoslash
// @noErrors
import type { MeasurePlugin, MeasureEndReason, MeasurePluginEventMap, MeasurePluginConfig } from '@realsee/dnalogel'
```

```ts
// MeasurePluginConfig
type MeasurePluginConfig = {
  unit: 'm' | 'ft' | 'mm'
  lengthEnable?: boolean
  precision?: number
}

// MeasureEndReason
type MeasureEndReason = 
  | 'enter'
  | 'escape'
  | 'polygon'
  | 'mode_change'
  | 'pano_move'
  | 'floor_change'
  | 'points_insufficient'
  | 'external'

// MeasurePluginEventMap
type MeasurePluginEventMap = {
  measureEnd: (reason: MeasureEndReason, points: THREE.Vector3[]) => void
  undo: () => void
}
```

网页版本：https://open.realsee.cn/docs/dnalogel/measure/MeasurePlugin
文档索引：https://open.realsee.cn/docs.md
