feat: 3d模型

This commit is contained in:
2025-12-09 17:13:20 +08:00
parent 5f603bc69d
commit 358639a8ac
492 changed files with 74670 additions and 190 deletions
@@ -0,0 +1,429 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Form,
Input,
Select,
InputNumber,
Row,
Col,
Divider,
message,
} from 'antd';
import {
createModel,
updateModel,
ThreeDModelVO,
ThreeDModelDTO,
ModelTypeMap,
} from '@/services/threeDModel';
import { ordersApi } from '@/services/orders';
interface ModelFormModalProps {
visible: boolean;
isEdit: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onSuccess: (modelId: number) => void;
}
interface TourismOption {
id: number;
name: string;
}
const ModelFormModal: React.FC<ModelFormModalProps> = ({
visible,
isEdit,
model,
onCancel,
onSuccess,
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = React.useState(false);
const [tourismList, setTourismList] = useState<TourismOption[]>([]);
const [tourismLoading, setTourismLoading] = useState(false);
// 加载景区列表
useEffect(() => {
if (visible) {
loadTourismList();
}
}, [visible]);
const loadTourismList = async () => {
setTourismLoading(true);
try {
const res = await ordersApi.tourism({ current: 1, pageSize: 1000 });
const list = (res.data || []).map((item: any) => ({
id: item.id,
name: item.name || item.tourismName,
}));
setTourismList(list);
} catch (error) {
console.error('加载景区列表失败:', error);
} finally {
setTourismLoading(false);
}
};
// 重置表单
useEffect(() => {
if (visible) {
if (isEdit && model) {
form.setFieldsValue({
modelName: model.modelName,
modelType: model.modelType,
description: model.description,
tourismId: model.tourismId,
tourismName: model.tourismName,
sourceType: model.sourceType,
// 位置参数
offsetLongitude: model.position?.longitude || 0,
offsetLatitude: model.position?.latitude || 0,
offsetHeight: model.position?.height || 0,
// 变换参数
scale: model.transform?.scale || 1,
rotationX: model.transform?.rotationX || 0,
rotationY: model.transform?.rotationY || 0,
rotationZ: model.transform?.rotationZ || 0,
// 渲染参数
maxScreenSpaceError: model.style?.maximumScreenSpaceError || 16,
maxMemoryUsage: model.style?.maximumMemoryUsage || 512,
skipLod: model.style?.skipLevelOfDetail ? 1 : 0,
preferLeaves: model.style?.preferLeaves ? 1 : 0,
status: model.status,
});
} else {
form.resetFields();
// 使用高清晰度默认配置
form.setFieldsValue({
modelType: 1,
modelFormat: '3dtiles',
sourceType: 'dji_terra',
// 位置调整 - 默认不偏移,模型会自动定位
offsetLongitude: 0,
offsetLatitude: 0,
offsetHeight: 0,
// 变换参数 - 默认不变换
scale: 1,
rotationX: 0,
rotationY: 0,
rotationZ: 0,
// 渲染配置 - 使用高清晰度配置(类似大疆司空)
maxScreenSpaceError: 1, // 1-2=高清,16=较模糊
maxMemoryUsage: 2048, // 2GB内存保证清晰度
skipLod: 0, // 0=不跳过,更清晰
preferLeaves: 1, // 1=优先叶子节点
status: 1,
});
}
}
}, [visible, isEdit, model, form]);
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
const dto: ThreeDModelDTO = {
...values,
id: isEdit ? model?.id : undefined,
};
let modelId: number;
if (isEdit) {
await updateModel(dto);
modelId = model!.id;
message.success('更新成功');
} else {
const res = await createModel(dto);
modelId = res.datas;
message.success('创建成功');
}
onSuccess(modelId);
} catch (error: any) {
if (error.errorFields) {
// 表单验证错误
return;
}
message.error(error.message || '操作失败');
} finally {
setLoading(false);
}
};
return (
<Modal
title={isEdit ? '编辑模型' : '新建模型'}
open={visible}
onCancel={onCancel}
onOk={handleSubmit}
confirmLoading={loading}
width={720}
destroyOnClose
>
<Form form={form} layout="vertical">
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="modelName"
label="模型名称"
rules={[{ required: true, message: '请输入模型名称' }]}
>
<Input placeholder="请输入模型名称" maxLength={100} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
name="modelType"
label="模型类型"
rules={[{ required: true, message: '请选择模型类型' }]}
>
<Select placeholder="请选择模型类型">
{Object.entries(ModelTypeMap).map(([key, value]) => (
<Select.Option key={key} value={Number(key)}>
{value}
</Select.Option>
))}
</Select>
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="sourceType" label="来源类型">
<Select placeholder="请选择来源类型">
<Select.Option value="dji_terra">大疆建图</Select.Option>
<Select.Option value="cesium_ion">Cesium Ion</Select.Option>
<Select.Option value="custom">自定义</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="tourismId" label="关联景区">
<Select
placeholder="请选择关联景区"
allowClear
showSearch
loading={tourismLoading}
optionFilterProp="children"
onChange={(value, option: any) => {
// 同时设置景区名称
form.setFieldValue('tourismName', option?.children || '');
}}
>
{tourismList.map((item) => (
<Select.Option key={item.id} value={item.id}>
{item.name}
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item name="tourismName" hidden>
<Input />
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="status" label="状态">
<Select placeholder="请选择状态">
<Select.Option value={1}>启用</Select.Option>
<Select.Option value={0}>禁用</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item name="description" label="模型描述">
<Input.TextArea placeholder="请输入模型描述" rows={2} maxLength={500} />
</Form.Item>
<Divider orientation="left">位置调整(通常保持默认0,模型会自动定位)</Divider>
<Row gutter={16}>
<Col span={8}>
<Form.Item
name="offsetLongitude"
label="经度偏移(度)"
tooltip="正值向东偏移,负值向西偏移。范围: -180 ~ 180"
>
<InputNumber
style={{ width: '100%' }}
min={-180}
max={180}
step={0.0001}
precision={6}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
name="offsetLatitude"
label="纬度偏移(度)"
tooltip="正值向北偏移,负值向南偏移。范围: -90 ~ 90"
>
<InputNumber
style={{ width: '100%' }}
min={-90}
max={90}
step={0.0001}
precision={6}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
name="offsetHeight"
label="高度偏移(米)"
tooltip="正值向上抬升,负值向下沉降。大疆建图模型通常需要设置 -500 ~ -2000 米才能贴地"
>
<InputNumber
style={{ width: '100%' }}
min={-10000}
max={10000}
step={10}
precision={0}
placeholder="0"
/>
</Form.Item>
</Col>
</Row>
<Divider orientation="left">变换参数(通常保持默认,除非模型方向不正确)</Divider>
<Row gutter={16}>
<Col span={6}>
<Form.Item
name="scale"
label="缩放比例"
tooltip="1=原始大小,0.5=缩小一半,2=放大一倍"
>
<InputNumber
style={{ width: '100%' }}
min={0.01}
max={100}
step={0.1}
precision={2}
placeholder="1.0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationX"
label="X轴旋转(弧度)"
tooltip="俯仰角旋转。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationY"
label="Y轴旋转(弧度)"
tooltip="翻滚角旋转。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationZ"
label="Z轴旋转(弧度)"
tooltip="航向角旋转(朝向)。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
</Row>
<Divider orientation="left">渲染配置(核心清晰度设置)</Divider>
<Row gutter={16}>
<Col span={6}>
<Form.Item
name="maxScreenSpaceError"
label="LOD精度"
tooltip="【核心参数】值越小越清晰:1-2=高清(类似大疆司空),8=中等,16=较低,32+=模糊。推荐:1-4"
>
<InputNumber
style={{ width: '100%' }}
min={1}
max={128}
step={1}
placeholder="1"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="maxMemoryUsage"
label="最大内存(MB)"
tooltip="显存/内存限制,越大越能加载高清瓦片。推荐:1024-2048MB"
>
<InputNumber
style={{ width: '100%' }}
min={256}
max={8192}
step={256}
placeholder="2048"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="skipLod"
label="跳过LOD"
tooltip="否=更清晰(逐级加载),是=更快但可能模糊"
>
<Select>
<Select.Option value={0}>否(更清晰)</Select.Option>
<Select.Option value={1}>是(更快)</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="preferLeaves"
label="优先叶子节点"
tooltip="是=优先加载最精细的瓦片(推荐)"
>
<Select>
<Select.Option value={1}>是(推荐)</Select.Option>
<Select.Option value={0}>否</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
</Form>
</Modal>
);
};
export default ModelFormModal;
@@ -0,0 +1,174 @@
.previewContainer {
// 高度调整控制面板
.heightControl {
margin-bottom: 16px;
padding: 16px;
background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
border: 1px solid #91d5ff;
border-radius: 8px;
.heightControlTitle {
font-size: 14px;
font-weight: 500;
color: #1890ff;
margin-bottom: 12px;
}
.modelHeightInfo {
display: flex;
gap: 24px;
margin-bottom: 16px;
padding: 12px 16px;
background: #fff;
border-radius: 6px;
border: 1px solid #d9d9d9;
.heightInfoItem {
display: flex;
align-items: center;
gap: 8px;
.label {
color: #666;
font-size: 13px;
}
.value {
font-weight: 600;
color: #ff4d4f;
font-size: 15px;
}
.suggestedValue {
font-weight: 600;
color: #52c41a;
font-size: 15px;
}
}
}
.heightControlContent {
display: flex;
align-items: center;
gap: 24px;
.sliderWrapper {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
.sliderLabel {
font-size: 12px;
color: #666;
white-space: nowrap;
}
:global {
.ant-slider {
margin: 10px 0;
}
.ant-slider-mark-text {
color: #666;
font-size: 11px;
}
}
}
.heightInputGroup {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
}
.heightTip {
margin-top: 12px;
font-size: 12px;
color: #666;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.6);
border-radius: 4px;
strong {
color: #1890ff;
font-size: 14px;
}
}
}
.viewerContainer {
position: relative;
width: 100%;
height: 500px;
background: #1a1a2e;
border-radius: 8px;
overflow: hidden;
.cesiumViewer {
width: 100%;
height: 500px;
:global {
.cesium-widget,
.cesium-widget canvas {
width: 100% !important;
height: 100% !important;
}
}
}
.loadingOverlay,
.errorOverlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.7);
z-index: 10;
:global {
.ant-spin-text {
color: #fff;
margin-top: 16px;
}
}
}
.errorOverlay {
background: rgba(0, 0, 0, 0.85);
:global {
.ant-alert {
max-width: 400px;
}
}
}
}
.urlInfo {
margin-top: 12px;
padding: 8px 12px;
background: #fafafa;
border-radius: 4px;
display: flex;
align-items: center;
gap: 8px;
}
}
// 隐藏Cesium默认UI
:global {
.cesium-viewer-bottom {
display: none !important;
}
.cesium-viewer-toolbar {
display: none !important;
}
}
@@ -0,0 +1,423 @@
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message } from 'antd';
import { ThreeDModelVO, updateModel } from '@/services/threeDModel';
import styles from './ModelPreviewModal.less';
const { Text } = Typography;
interface ModelPreviewModalProps {
visible: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onHeightUpdated?: () => void; // 高度更新后的回调,用于刷新列表
}
// 动态导入Cesium
let Cesium: any = null;
const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
visible,
model,
onCancel,
onHeightUpdated,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const tilesetRef = useRef<any>(null);
const originalCenterRef = useRef<any>(null); // 保存模型原始中心点
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [initialized, setInitialized] = useState(false);
// 高度调整状态
const [heightOffset, setHeightOffset] = useState<number>(0);
const [saving, setSaving] = useState(false);
const [modelHeight, setModelHeight] = useState<number | null>(null); // 模型原始高度
const [suggestedOffset, setSuggestedOffset] = useState<number>(0); // 建议的偏移值
// 清理函数
const cleanup = useCallback(() => {
if (tilesetRef.current) {
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
try {
viewerRef.current.scene.primitives.remove(tilesetRef.current);
} catch (e) {
console.warn('Failed to remove tileset:', e);
}
}
tilesetRef.current = null;
}
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
try {
viewerRef.current.destroy();
} catch (e) {
console.warn('Failed to destroy viewer:', e);
}
viewerRef.current = null;
}
originalCenterRef.current = null;
setInitialized(false);
}, []);
// 实时调整模型高度
const adjustHeight = useCallback((offset: number) => {
if (!tilesetRef.current || !Cesium || !originalCenterRef.current) return;
const tileset = tilesetRef.current;
const originalCenter = originalCenterRef.current;
// 计算新的中心点位置
const cartographic = Cesium.Cartographic.fromCartesian(originalCenter);
const newHeight = cartographic.height + offset;
const newCenter = Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
newHeight
);
// 计算平移量
const translation = Cesium.Cartesian3.subtract(
newCenter,
originalCenter,
new Cesium.Cartesian3()
);
// 应用变换矩阵
tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
// 请求重新渲染
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.scene.requestRender();
}
}, []);
// 高度偏移变化时实时调整
useEffect(() => {
if (initialized && tilesetRef.current) {
adjustHeight(heightOffset);
}
}, [heightOffset, initialized, adjustHeight]);
// 保存高度偏移到数据库
const saveHeightOffset = async () => {
if (!model) return;
setSaving(true);
try {
await updateModel({
id: model.id,
modelName: model.modelName,
offsetHeight: heightOffset,
});
message.success(`高度偏移已保存: ${heightOffset}米`);
onHeightUpdated?.();
} catch (err: any) {
message.error('保存失败: ' + (err.message || '未知错误'));
} finally {
setSaving(false);
}
};
// 初始化Viewer和加载模型
const initViewer = useCallback(async () => {
if (!model?.tilesetUrl || !containerRef.current) return;
// 先清理旧的
cleanup();
setLoading(true);
setError(null);
// 初始化高度偏移为模型当前配置的值
const initialHeight = model.position?.height || 0;
setHeightOffset(initialHeight);
try {
// 动态加载Cesium
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
}
if (!containerRef.current) {
throw new Error('容器未就绪');
}
// 创建Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
scene3DOnly: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
});
viewerRef.current = viewer;
// 隐藏版权信息
const creditContainer = viewer.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
}
// 添加影像图层
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
});
viewer.imageryLayers.addImageryProvider(arcgisImagery);
// 加载3D Tiles模型 - 预览时使用高质量设置
const tileset = await Cesium.Cesium3DTileset.fromUrl(model.tilesetUrl, {
maximumScreenSpaceError: 1,
maximumMemoryUsage: 2048,
skipLevelOfDetail: false,
preferLeaves: true,
dynamicScreenSpaceError: false,
immediatelyLoadDesiredLevelOfDetail: true,
loadSiblings: true,
});
tilesetRef.current = tileset;
viewer.scene.primitives.add(tileset);
// 保存原始中心点(用于高度调整计算)
originalCenterRef.current = Cesium.Cartesian3.clone(tileset.boundingSphere.center);
// 计算模型的WGS84高度,并给出建议的偏移值
const cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
const heightInMeters = cartographic.height;
setModelHeight(Math.round(heightInMeters));
// 建议的偏移值:取负值让模型下降到地面
// 保留一点高度(约50米)避免模型陷入地面
const suggested = -Math.round(heightInMeters) + 50;
setSuggestedOffset(suggested);
console.log(`模型高度: ${heightInMeters.toFixed(2)}米, 建议偏移: ${suggested}米`);
// 如果有初始高度偏移,立即应用
if (initialHeight !== 0) {
adjustHeight(initialHeight);
}
// 强制刷新viewer尺寸
viewer.resize();
// 飞到模型位置
try {
await viewer.flyTo(tileset, {
duration: 1.5,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (flyError) {
console.warn('flyTo failed, trying zoomTo:', flyError);
await viewer.zoomTo(tileset);
}
// 再次刷新
setTimeout(() => {
if (viewer && !viewer.isDestroyed()) {
viewer.resize();
}
}, 100);
setInitialized(true);
setLoading(false);
} catch (err: any) {
console.error('加载模型失败:', err);
setError(err.message || '加载模型失败');
setLoading(false);
}
}, [model?.tilesetUrl, model?.position?.height, cleanup, adjustHeight]);
// 当弹窗打开时初始化
useEffect(() => {
if (visible && model?.tilesetUrl) {
// 延迟初始化,确保DOM已渲染
const timer = setTimeout(() => {
initViewer();
}, 100);
return () => clearTimeout(timer);
}
}, [visible, model?.tilesetUrl, initViewer]);
// 当弹窗关闭时清理
useEffect(() => {
if (!visible) {
cleanup();
setLoading(false);
setError(null);
setHeightOffset(0);
setModelHeight(null);
setSuggestedOffset(0);
}
}, [visible, cleanup]);
// 组件卸载时清理
useEffect(() => {
return () => {
cleanup();
};
}, [cleanup]);
return (
<Modal
title={`模型预览 - ${model?.modelName || ''}`}
open={visible}
onCancel={onCancel}
width={1100}
footer={null}
destroyOnClose={false}
afterClose={cleanup}
>
<div className={styles.previewContainer}>
{/* 模型信息 */}
{model && (
<Descriptions size="small" column={4} style={{ marginBottom: 16 }}>
<Descriptions.Item label="模型类型">
<Tag color="blue">{model.modelTypeName}</Tag>
</Descriptions.Item>
<Descriptions.Item label="文件数量">{model.fileCount}</Descriptions.Item>
<Descriptions.Item label="文件大小">{model.totalSizeFormat}</Descriptions.Item>
<Descriptions.Item label="来源">{model.sourceType}</Descriptions.Item>
</Descriptions>
)}
{/* 高度调整控制面板 */}
{initialized && (
<div className={styles.heightControl}>
<div className={styles.heightControlTitle}>
<span>🎚️ 高度调整(模型在空中飘着?向下调整;模型陷入地面?向上调整)</span>
</div>
{/* 模型高度信息 */}
{modelHeight !== null && (
<div className={styles.modelHeightInfo}>
<div className={styles.heightInfoItem}>
<span className={styles.label}>模型原始高度:</span>
<span className={styles.value}>{modelHeight} 米</span>
</div>
<div className={styles.heightInfoItem}>
<span className={styles.label}>建议偏移值:</span>
<span className={styles.suggestedValue}>{suggestedOffset} 米</span>
<Button
type="link"
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
</Button>
</div>
</div>
)}
<div className={styles.heightControlContent}>
<div className={styles.sliderWrapper}>
<span className={styles.sliderLabel}>下沉 ↓</span>
<Slider
min={-5000}
max={5000}
step={10}
value={heightOffset}
onChange={(val) => setHeightOffset(val)}
tooltip={{ formatter: (val) => `${val}米` }}
marks={{
'-5000': '-5km',
'-2000': '-2km',
'-1000': '-1km',
0: '0',
1000: '+1km',
2000: '+2km',
5000: '+5km',
}}
style={{ flex: 1 }}
/>
<span className={styles.sliderLabel}>↑ 抬升</span>
</div>
<div className={styles.heightInputGroup}>
<InputNumber
value={heightOffset}
onChange={(val) => setHeightOffset(val || 0)}
step={10}
addonAfter="米"
style={{ width: 120 }}
/>
<Space>
<Button size="small" onClick={() => setHeightOffset(0)}>
重置为0
</Button>
<Button
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
</Button>
<Button
type="primary"
size="small"
loading={saving}
onClick={saveHeightOffset}
>
保存高度
</Button>
</Space>
</div>
</div>
<div className={styles.heightTip}>
当前高度偏移: <strong>{heightOffset}</strong> 米。调整到合适位置后点击"保存高度",地图仪表盘加载时会自动应用此设置。
</div>
</div>
)}
{/* 预览区域 */}
<div className={styles.viewerContainer}>
{loading && (
<div className={styles.loadingOverlay}>
<Spin size="large" tip="正在加载模型..." />
</div>
)}
{error && (
<div className={styles.errorOverlay}>
<Alert
message="加载失败"
description={error}
type="error"
showIcon
/>
</div>
)}
<div ref={containerRef} className={styles.cesiumViewer} />
</div>
{/* URL信息 */}
{model?.tilesetUrl && (
<div className={styles.urlInfo}>
<Text type="secondary">模型URL: </Text>
<Text copyable ellipsis style={{ maxWidth: 800 }}>
{model.tilesetUrl}
</Text>
</div>
)}
</div>
</Modal>
);
};
export default ModelPreviewModal;
@@ -0,0 +1,109 @@
.uploadContainer {
min-height: 300px;
.selectArea {
.folderSelector {
border: 2px dashed #d9d9d9;
border-radius: 8px;
padding: 40px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
&:hover {
border-color: #1890ff;
background: #f0f7ff;
}
.folderLabel {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
cursor: pointer;
.labelText {
display: flex;
flex-direction: column;
gap: 4px;
}
}
}
}
.statsBar {
background: #fafafa;
padding: 12px 16px;
border-radius: 4px;
margin-bottom: 16px;
}
.fileList {
border: 1px solid #f0f0f0;
border-radius: 4px;
overflow: hidden;
:global {
.ant-list-item {
padding: 8px 12px;
border-bottom: 1px solid #f0f0f0;
&:last-child {
border-bottom: none;
}
}
}
.fileItem {
display: flex;
justify-content: space-between;
align-items: center;
&.pending {
background: #fff;
}
&.uploading {
background: #e6f7ff;
}
&.success {
background: #f6ffed;
}
&.error {
background: #fff2f0;
}
.fileInfo {
display: flex;
justify-content: space-between;
align-items: center;
flex: 1;
margin-right: 16px;
min-width: 0;
}
}
}
}
// 自定义滚动条
.fileList :global(.ant-list) {
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: #f0f0f0;
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: #d9d9d9;
border-radius: 3px;
&:hover {
background: #bfbfbf;
}
}
}
@@ -0,0 +1,407 @@
import React, { useState, useCallback, useRef } from 'react';
import {
Modal,
Upload,
Button,
Progress,
List,
Typography,
Space,
Alert,
message,
Spin,
Tag,
Result,
} from 'antd';
import {
InboxOutlined,
FileOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
LoadingOutlined,
FolderOpenOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import {
uploadSingleFile,
completeUpload,
ThreeDModelVO,
} from '@/services/threeDModel';
import styles from './ModelUploadModal.less';
const { Dragger } = Upload;
const { Text, Paragraph } = Typography;
interface ModelUploadModalProps {
visible: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onComplete: () => void;
}
interface FileUploadItem {
file: File;
relativePath: string;
status: 'pending' | 'uploading' | 'success' | 'error';
progress: number;
url?: string;
error?: string;
}
const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
visible,
model,
onCancel,
onComplete,
}) => {
const [fileList, setFileList] = useState<FileUploadItem[]>([]);
const [uploading, setUploading] = useState(false);
const [uploadComplete, setUploadComplete] = useState(false);
const [overallProgress, setOverallProgress] = useState(0);
const abortRef = useRef(false);
// 重置状态
const resetState = () => {
setFileList([]);
setUploading(false);
setUploadComplete(false);
setOverallProgress(0);
abortRef.current = false;
};
// 处理文件夹选择
const handleFolderSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0) return;
const items: FileUploadItem[] = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
// webkitRelativePath 包含完整的相对路径
const relativePath = (file as any).webkitRelativePath || file.name;
items.push({
file,
relativePath,
status: 'pending',
progress: 0,
});
}
// 检查是否包含tileset.json
const hasTileset = items.some(
(item) =>
item.relativePath.endsWith('tileset.json') &&
!item.relativePath.includes('/Block/')
);
if (!hasTileset) {
message.warning('未检测到根目录下的tileset.json文件,请确保选择了正确的3D Tiles文件夹');
}
setFileList(items);
setUploadComplete(false);
}, []);
// 开始上传
const handleUpload = async () => {
if (!model?.id || fileList.length === 0) {
message.error('请先选择文件');
return;
}
setUploading(true);
abortRef.current = false;
let successCount = 0;
let failCount = 0;
// 更新文件列表
const updateFileStatus = (
index: number,
status: FileUploadItem['status'],
progress: number,
url?: string,
error?: string
) => {
setFileList((prev) => {
const newList = [...prev];
newList[index] = { ...newList[index], status, progress, url, error };
return newList;
});
};
// 逐个上传文件
for (let i = 0; i < fileList.length; i++) {
if (abortRef.current) break;
const item = fileList[i];
updateFileStatus(i, 'uploading', 0);
try {
const result = await uploadSingleFile(
model.id,
item.file,
item.relativePath,
(percent) => {
updateFileStatus(i, 'uploading', percent);
}
);
if (result.resp_code === 0) {
updateFileStatus(i, 'success', 100, result.datas);
successCount++;
} else {
throw new Error(result.resp_msg || '上传失败');
}
} catch (error: any) {
updateFileStatus(i, 'error', 0, undefined, error.message);
failCount++;
}
// 更新总进度
setOverallProgress(Math.round(((i + 1) / fileList.length) * 100));
}
// 如果全部成功,调用完成接口
if (successCount === fileList.length) {
try {
await completeUpload(model.id);
message.success('所有文件上传完成!');
setUploadComplete(true);
} catch (error) {
message.error('更新状态失败');
}
} else if (failCount > 0) {
message.warning(`上传完成,成功 ${successCount} 个,失败 ${failCount} 个`);
}
setUploading(false);
};
// 取消上传
const handleAbort = () => {
abortRef.current = true;
message.info('正在取消上传...');
};
// 关闭弹窗
const handleClose = () => {
if (uploading) {
Modal.confirm({
title: '确定要取消上传吗?',
content: '取消后已上传的文件将保留',
onOk: () => {
handleAbort();
setTimeout(() => {
resetState();
onCancel();
}, 500);
},
});
} else {
if (uploadComplete) {
onComplete();
} else {
onCancel();
}
resetState();
}
};
// 统计信息
const stats = {
total: fileList.length,
success: fileList.filter((f) => f.status === 'success').length,
error: fileList.filter((f) => f.status === 'error').length,
pending: fileList.filter((f) => f.status === 'pending').length,
uploading: fileList.filter((f) => f.status === 'uploading').length,
totalSize: fileList.reduce((sum, f) => sum + f.file.size, 0),
};
const formatSize = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
return (
<Modal
title={`上传模型文件 - ${model?.modelName || ''}`}
open={visible}
onCancel={handleClose}
width={800}
footer={
uploadComplete ? (
<Button type="primary" onClick={handleClose}>
完成
</Button>
) : (
<Space>
<Button onClick={handleClose}>{uploading ? '取消' : '关闭'}</Button>
{!uploading && fileList.length > 0 && (
<Button type="primary" onClick={handleUpload}>
开始上传
</Button>
)}
{uploading && (
<Button danger onClick={handleAbort}>
停止上传
</Button>
)}
</Space>
)
}
destroyOnClose
>
<div className={styles.uploadContainer}>
{uploadComplete ? (
<Result
status="success"
title="上传完成"
subTitle={`成功上传 ${stats.success} 个文件,共 ${formatSize(stats.totalSize)}`}
/>
) : (
<>
{/* 文件选择区域 */}
{fileList.length === 0 && (
<div className={styles.selectArea}>
<Alert
message="请选择3D Tiles模型文件夹"
description="选择大疆建图输出的 terra_b3dms 文件夹,包含 tileset.json 和所有 .b3dm 文件"
type="info"
showIcon
style={{ marginBottom: 16 }}
/>
<div className={styles.folderSelector}>
<input
type="file"
id="folderInput"
/* @ts-ignore */
webkitdirectory=""
directory=""
multiple
onChange={handleFolderSelect}
style={{ display: 'none' }}
/>
<label htmlFor="folderInput" className={styles.folderLabel}>
<FolderOpenOutlined style={{ fontSize: 48, color: '#1890ff' }} />
<div className={styles.labelText}>
<Text strong>点击选择文件夹</Text>
<Text type="secondary">或将文件夹拖放到此处</Text>
</div>
</label>
</div>
</div>
)}
{/* 文件列表 */}
{fileList.length > 0 && (
<>
{/* 统计信息 */}
<div className={styles.statsBar}>
<Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
<Text>共 {stats.total} 个文件</Text>
<Text>总大小 {formatSize(stats.totalSize)}</Text>
{stats.success > 0 && (
<Text type="success">成功 {stats.success}</Text>
)}
{stats.error > 0 && <Text type="danger">失败 {stats.error}</Text>}
{stats.uploading > 0 && (
<Text type="warning">上传中 {stats.uploading}</Text>
)}
</Space>
</div>
{/* 总进度 */}
{uploading && (
<Progress
percent={overallProgress}
status="active"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
style={{ marginBottom: 16 }}
/>
)}
{/* 文件列表 */}
<div className={styles.fileList}>
<List
size="small"
dataSource={fileList}
renderItem={(item, index) => (
<List.Item
className={`${styles.fileItem} ${styles[item.status]}`}
>
<div className={styles.fileInfo}>
<Space>
{item.status === 'pending' && <FileOutlined />}
{item.status === 'uploading' && (
<LoadingOutlined spin />
)}
{item.status === 'success' && (
<CheckCircleOutlined style={{ color: '#52c41a' }} />
)}
{item.status === 'error' && (
<CloseCircleOutlined style={{ color: '#ff4d4f' }} />
)}
<Text
ellipsis={{ tooltip: item.relativePath }}
style={{ maxWidth: 400 }}
>
{item.relativePath}
</Text>
</Space>
<Text type="secondary" style={{ fontSize: 12 }}>
{formatSize(item.file.size)}
</Text>
</div>
{item.status === 'uploading' && (
<Progress
percent={item.progress}
size="small"
style={{ width: 100 }}
/>
)}
{item.status === 'error' && (
<Text type="danger" style={{ fontSize: 12 }}>
{item.error}
</Text>
)}
</List.Item>
)}
style={{ maxHeight: 400, overflow: 'auto' }}
/>
</div>
{/* 重新选择 */}
{!uploading && (
<div style={{ marginTop: 16, textAlign: 'center' }}>
<input
type="file"
id="folderInputReset"
/* @ts-ignore */
webkitdirectory=""
directory=""
multiple
onChange={handleFolderSelect}
style={{ display: 'none' }}
/>
<label htmlFor="folderInputReset">
<Button type="link">重新选择文件夹</Button>
</label>
</div>
)}
</>
)}
</>
)}
</div>
</Modal>
);
};
export default ModelUploadModal;