Add DICOM UPP registration workspace

This commit is contained in:
Codex
2026-05-28 11:58:59 +08:00
parent 07df6ce446
commit cb18aabb4d
19 changed files with 5644 additions and 1 deletions

View File

@@ -0,0 +1,4 @@
.env
__pycache__/
*.pyc
.pytest_cache/

View File

@@ -0,0 +1,18 @@
PGHOST=192.168.3.3
PGPORT=5432
PGUSER=his_user
PGPASSWORD=change_me
PGDATABASE=pacs_db
PACS_TABLE=pacs_dicom_files
PACS_SUMMARY_TABLE=pacs_dicom_study_summaries
PACS_ANNOTATION_TABLE=pacs_dicom_series_annotations
UPP_ASSET_TABLE=upp_exam_assets
UPP_STL_TABLE=upp_stl_files
REGISTRATION_TABLE=dicom_upp_registrations
REGISTRATION_WEB_USER=admin
REGISTRATION_WEB_PASSWORD=123456
PACS_VIEWER_URL=http://127.0.0.1:8107
RELATION_VIEWER_URL=http://127.0.0.1:8108
PACS_PROCESSED_ROOT=/home/wkmgc/Desktop/Data_Disk_1/PACS数据/DICOM数据/已处理_DICOM数据

View File

@@ -0,0 +1,17 @@
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
RUN apt-get update \
&& apt-get install -y --no-install-recommends postgresql-client \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY . /app
EXPOSE 8109
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8109"]

View File

@@ -0,0 +1,21 @@
# DICOM_and_UPP 配准工作台
用于在浏览器中人工核对 DICOM 序列与 UPP STL 模型的配准关系。页面会读取 PACS DICOM、UPP STL 资产和 DICOM 阅片分类结果,配准位姿单独写入 `dicom_upp_registrations` 表。
默认端口:
- 本机:`http://127.0.0.1:8109/`
- 局域网:`http://192.168.3.11:8109/`
登录:
- 账号:`admin`
- 密码:`123456`
启动:
```bash
docker compose up -d --build
```
当前保存内容包括 CT 号、DICOM 序列 UID、重建算法模型、STL family/文件选择、位姿 transform、可选分割/备注、锁定状态和更新人。

1059
DICOM_and_UPP配准/app.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,14 @@
name: dicom-upp-registration
services:
dicom-upp-registration:
build:
context: .
container_name: dicom-upp-registration
restart: unless-stopped
env_file:
- .env
ports:
- "8109:8109"
volumes:
- /home/wkmgc/Desktop:/home/wkmgc/Desktop:ro

View File

@@ -0,0 +1,5 @@
fastapi==0.116.1
uvicorn[standard]==0.35.0
pydicom==2.4.5
numpy>=2.0
pillow>=11.0

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,179 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>DICOM / UPP 配准工作台</title>
<link rel="stylesheet" href="/static/styles.css" />
<script type="importmap">
{
"imports": {
"three": "/static/vendor/three.module.min.js"
}
}
</script>
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="brand-mark"></span>
<div>
<h1>DICOM / UPP 配准工作台</h1>
<p id="brandSubtitle">DICOM 序列、STL family 与人工位姿锁定</p>
</div>
</div>
<div class="top-actions">
<button id="relationBtn" class="dark-btn accent" type="button">数据库关联</button>
<button id="viewerBtn" class="dark-btn" type="button">阅片系统</button>
<span id="dbStatus" class="status-pill">数据库</span>
<button id="refreshBtn" class="dark-btn" type="button">刷新</button>
<span id="userBadge" class="user-badge">未登录</span>
<button id="logoutBtn" class="dark-btn" type="button">退出</button>
</div>
</header>
<div id="topLoading" class="top-loading hidden"><span></span></div>
<main class="workspace">
<aside class="left-rail">
<section class="panel search-panel">
<div class="panel-head">
<h2>匹配检查</h2>
<span id="caseCount">0</span>
</div>
<input id="caseSearch" class="search-input" placeholder="搜索 CT号 / 姓名 / 模型" />
<div id="caseList" class="case-list"></div>
</section>
<section class="panel stacked-panel">
<div class="panel-head">
<h2>DICOM序列</h2>
<span id="seriesCount">0</span>
</div>
<div id="seriesList" class="series-list"></div>
</section>
<section class="panel stacked-panel">
<div class="panel-head">
<h2>STL模型</h2>
<span id="stlCount">0</span>
</div>
<div class="segmented small">
<button id="modeFile" class="active" type="button">单独</button>
<button id="modeFamily" type="button">Family</button>
</div>
<div id="familyRail" class="chip-rail"></div>
<div id="stlList" class="stl-list"></div>
</section>
<section class="panel registration-panel">
<div class="panel-head">
<h2>交互配准</h2>
<span id="saveState">未保存</span>
</div>
<div class="pose-grid" id="poseGrid"></div>
<textarea id="registrationNotes" class="notes" rows="2" placeholder="配准备注"></textarea>
<div class="action-grid">
<button id="resetPoseBtn" class="dark-btn" type="button">重置位姿</button>
<button id="saveRegistrationBtn" class="primary-btn" type="button">保存配准</button>
<button id="lockRegistrationBtn" class="warn-btn" type="button">保存并上锁</button>
<button id="unlockRegistrationBtn" class="dark-btn" type="button">解锁</button>
<button id="exportStlBtn" class="dark-btn" type="button">导出STL</button>
</div>
</section>
</aside>
<section class="viewer-shell">
<section class="panel hero-strip">
<div>
<h2 id="activeTitle">未选择 CT</h2>
<p id="activeMeta">从左侧选择一个 DICOM + STL 匹配检查</p>
</div>
<div class="hero-tags" id="activeTags"></div>
</section>
<section class="viewer-grid">
<article class="viewport-card dicom-card">
<div class="viewport-head">
<div>
<h3>DICOM</h3>
<span id="dicomMeta">未选择序列</span>
</div>
<div class="tool-row">
<select id="planeSelect">
<option value="axial">轴位</option>
<option value="sagittal">矢状位</option>
<option value="coronal">冠状位</option>
</select>
<select id="windowSelect">
<option value="default">默认</option>
<option value="soft">软组织</option>
<option value="bone">骨窗</option>
<option value="contrast">高对比</option>
</select>
</div>
</div>
<div class="image-stage" id="dicomStage">
<img id="dicomImage" alt="DICOM切片" />
<div id="dicomEmpty" class="empty-state">等待选择 DICOM 序列</div>
</div>
<div class="slice-row">
<input id="sliceSlider" type="range" min="0" max="0" value="0" />
<span id="sliceLabel">0 / 0</span>
</div>
</article>
<article class="viewport-card">
<div class="viewport-head">
<div>
<h3>STL拼接后</h3>
<span id="stlMeta">未加载模型</span>
</div>
<button id="fitStlBtn" class="icon-btn" title="重置三维视角" type="button">复位</button>
</div>
<div id="stlViewport" class="three-stage"></div>
</article>
<article class="viewport-card fusion-card">
<div class="viewport-head">
<div>
<h3>STL和DICOM融合</h3>
<span id="fusionMeta">位姿未保存</span>
</div>
<button id="fitFusionBtn" class="icon-btn" title="重置融合视角" type="button">复位</button>
</div>
<div id="fusionViewport" class="three-stage"></div>
</article>
<article class="viewport-card segmentation-card">
<div class="viewport-head">
<div>
<h3>DICOM分割</h3>
<span id="segmentationMeta">基于当前可见 STL 的预览</span>
</div>
<button id="toggleMaskBtn" class="icon-btn" title="显示或隐藏分割预览" type="button">显示</button>
</div>
<div class="segmentation-stage">
<img id="segmentationImage" alt="DICOM分割预览" />
<canvas id="maskCanvas"></canvas>
<div id="segmentationEmpty" class="empty-state">选择序列和 STL 后显示叠加预览</div>
</div>
</article>
</section>
</section>
</main>
<div id="loginOverlay" class="login-overlay">
<form id="loginForm" class="login-panel">
<span class="brand-mark"></span>
<h2>DICOM / UPP 配准工作台</h2>
<p>登录后进行 DICOM 与 STL 配准</p>
<input id="username" class="search-input" autocomplete="username" placeholder="账号" />
<input id="password" class="search-input" type="password" autocomplete="current-password" placeholder="密码" />
<button class="primary-btn" type="submit">登录</button>
<span id="loginError" class="error-line"></span>
</form>
</div>
<script type="module" src="/static/app.js"></script>
</body>
</html>

View File

@@ -0,0 +1,722 @@
:root {
color-scheme: dark;
--bg: #070b10;
--panel: #101720;
--panel-2: #0b1118;
--panel-3: #070b10;
--line: #243344;
--line-strong: #3a5773;
--text: #eaf2fb;
--muted: #93a8c0;
--blue: #3378f6;
--cyan: #17d6c1;
--green: #21c58a;
--amber: #efb84d;
--red: #fb7185;
--shadow: 0 18px 44px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
overflow: hidden;
background:
linear-gradient(90deg, rgba(51, 120, 246, 0.07) 1px, transparent 1px),
linear-gradient(180deg, rgba(23, 214, 193, 0.055) 1px, transparent 1px),
radial-gradient(circle at 16% 0%, rgba(23, 214, 193, 0.12), transparent 27%),
var(--bg);
background-size: 80px 80px, 80px 80px, auto;
color: var(--text);
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
letter-spacing: 0;
}
button,
input,
select,
textarea {
font: inherit;
}
button {
cursor: pointer;
}
.hidden {
display: none !important;
}
.topbar {
height: 66px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background: rgba(7, 11, 16, 0.93);
}
.brand,
.top-actions {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 30px;
height: 30px;
flex: 0 0 auto;
border-radius: 8px;
background: linear-gradient(135deg, var(--cyan), var(--blue));
box-shadow: 0 0 24px rgba(23, 214, 193, 0.24);
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.2;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 12px;
}
.top-actions {
justify-content: flex-end;
gap: 9px;
}
.top-loading {
position: fixed;
top: 66px;
left: 0;
right: 0;
z-index: 20;
height: 3px;
overflow: hidden;
background: rgba(36, 51, 68, 0.75);
}
.top-loading span {
position: absolute;
inset-block: 0;
width: 34%;
border-radius: 999px;
background: linear-gradient(90deg, transparent, var(--cyan), var(--blue), transparent);
animation: loading-sweep 1.15s ease-in-out infinite;
}
@keyframes loading-sweep {
from {
transform: translateX(-110%);
}
to {
transform: translateX(320%);
}
}
.dark-btn,
.primary-btn,
.warn-btn,
.icon-btn {
min-height: 34px;
border: 1px solid rgba(147, 168, 192, 0.36);
border-radius: 8px;
background: linear-gradient(180deg, rgba(24, 36, 52, 0.96), rgba(10, 17, 25, 0.96));
color: var(--text);
font-weight: 700;
}
.dark-btn {
padding: 0 13px;
}
.dark-btn.accent {
border-color: rgba(23, 214, 193, 0.62);
color: #bffbf2;
background: linear-gradient(180deg, rgba(15, 57, 66, 0.96), rgba(8, 27, 37, 0.96));
}
.primary-btn {
padding: 0 14px;
border-color: rgba(51, 120, 246, 0.8);
background: var(--blue);
color: white;
}
.warn-btn {
padding: 0 14px;
border-color: rgba(239, 184, 77, 0.6);
background: rgba(239, 184, 77, 0.14);
color: #ffe1a6;
}
.icon-btn {
height: 32px;
padding: 0 12px;
font-size: 12px;
}
.dark-btn:hover,
.icon-btn:hover {
border-color: rgba(51, 120, 246, 0.84);
background: #172334;
}
.user-badge {
max-width: 150px;
overflow: hidden;
color: var(--muted);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.status-pill {
min-width: 90px;
height: 30px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 12px;
font-weight: 800;
white-space: nowrap;
}
.status-pill.online {
border-color: rgba(33, 197, 138, 0.48);
color: #a8f4d6;
background: rgba(33, 197, 138, 0.08);
}
.status-pill.offline {
border-color: rgba(251, 113, 133, 0.5);
color: #fecdd3;
background: rgba(251, 113, 133, 0.08);
}
.workspace {
height: calc(100vh - 66px);
display: grid;
grid-template-columns: 410px minmax(0, 1fr);
gap: 12px;
padding: 12px;
}
.left-rail {
min-height: 0;
display: grid;
grid-template-rows: 210px minmax(160px, 0.82fr) minmax(250px, 1.12fr) minmax(300px, 0.9fr);
gap: 10px;
overflow: hidden;
}
.viewer-shell {
min-height: 0;
display: grid;
grid-template-rows: auto minmax(0, 1fr);
gap: 10px;
}
.panel,
.viewport-card {
min-width: 0;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(16, 23, 32, 0.92);
box-shadow: var(--shadow);
}
.search-panel,
.stacked-panel,
.registration-panel,
.hero-strip {
padding: 12px;
}
.stacked-panel {
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.panel-head,
.viewport-head,
.hero-strip {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.panel-head h2,
.viewport-head h3,
.hero-strip h2 {
margin: 0;
font-size: 15px;
}
.panel-head span,
.viewport-head span,
.hero-strip p {
color: var(--muted);
font-size: 12px;
}
.hero-strip p {
margin: 4px 0 0;
}
.search-input,
.notes,
.tool-row select {
width: 100%;
border: 1px solid var(--line);
border-radius: 8px;
outline: 0;
background: #080d14;
color: var(--text);
}
.search-input {
height: 38px;
margin-top: 10px;
padding: 0 12px;
}
.notes {
min-height: 42px;
resize: vertical;
padding: 8px 10px;
}
.search-input:focus,
.notes:focus,
.tool-row select:focus {
border-color: rgba(51, 120, 246, 0.72);
}
.case-list,
.series-list,
.stl-list {
min-height: 0;
overflow: auto;
scrollbar-width: thin;
}
.case-list {
height: 138px;
margin-top: 10px;
}
.series-list,
.stl-list {
flex: 1 1 auto;
height: auto;
margin-top: 10px;
}
.case-card,
.series-card,
.stl-row {
width: 100%;
display: grid;
gap: 6px;
margin-bottom: 8px;
padding: 10px;
border: 1px solid transparent;
border-radius: 8px;
background: #0b1118;
color: var(--text);
text-align: left;
}
.case-card.active,
.series-card.active,
.stl-row.active {
border-color: rgba(23, 214, 193, 0.8);
background: rgba(18, 37, 46, 0.92);
}
.case-card strong,
.series-card strong,
.stl-row strong {
overflow: hidden;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.case-card span,
.case-card small,
.series-card span,
.series-card small,
.stl-row span,
.stl-row small {
overflow: hidden;
color: var(--muted);
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.tag-line,
.hero-tags,
.chip-rail {
display: flex;
gap: 6px;
overflow-x: auto;
padding-bottom: 2px;
scrollbar-width: thin;
}
.stacked-panel .chip-rail {
flex: 0 0 auto;
min-height: 30px;
margin-top: 8px;
}
.tag,
.chip {
flex: 0 0 auto;
max-width: 132px;
padding: 2px 7px;
overflow: hidden;
border: 1px solid rgba(23, 214, 193, 0.42);
border-radius: 999px;
color: #bffbf2;
background: rgba(23, 214, 193, 0.08);
font-size: 11px;
font-style: normal;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag.warn {
border-color: rgba(239, 184, 77, 0.55);
color: #ffe1a6;
background: rgba(239, 184, 77, 0.09);
}
.tag.locked {
border-color: rgba(51, 120, 246, 0.56);
color: #cfe0ff;
background: rgba(51, 120, 246, 0.11);
}
.chip {
cursor: pointer;
}
.chip.active {
border-color: var(--cyan);
background: rgba(23, 214, 193, 0.18);
}
.segmented {
display: flex;
gap: 6px;
padding: 4px;
border: 1px solid var(--line);
border-radius: 8px;
background: #080d14;
}
.segmented.small {
margin-top: 10px;
}
.segmented button {
flex: 1;
height: 28px;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--muted);
font-weight: 800;
}
.segmented button.active {
background: var(--blue);
color: white;
}
.stl-row {
grid-template-columns: 18px minmax(0, 1fr) auto;
align-items: center;
}
.stl-row input {
margin: 0;
}
.registration-panel {
display: grid;
gap: 10px;
min-height: 0;
overflow: auto;
}
.pose-grid {
display: grid;
gap: 7px;
}
.pose-control {
display: grid;
grid-template-columns: 70px minmax(0, 1fr) 72px;
align-items: center;
gap: 8px;
}
.pose-control label {
color: var(--muted);
font-size: 12px;
}
.pose-control input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.pose-control input[type="number"] {
width: 72px;
height: 28px;
border: 1px solid var(--line);
border-radius: 7px;
background: #080d14;
color: var(--text);
text-align: right;
}
.flip-row {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px;
}
.flip-row button {
height: 28px;
border: 1px solid var(--line);
border-radius: 7px;
background: #080d14;
color: var(--muted);
font-weight: 800;
}
.flip-row button.active {
border-color: rgba(23, 214, 193, 0.72);
color: #bffbf2;
background: rgba(23, 214, 193, 0.13);
}
.action-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.viewer-grid {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.05fr);
grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
gap: 10px;
}
.viewport-card {
min-height: 0;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
overflow: hidden;
}
.fusion-card,
.segmentation-card {
grid-template-rows: auto minmax(0, 1fr);
}
.viewport-head {
min-height: 52px;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
background: rgba(11, 17, 24, 0.86);
}
.tool-row {
display: flex;
gap: 8px;
}
.tool-row select {
width: 94px;
height: 32px;
padding: 0 8px;
}
.image-stage,
.segmentation-stage,
.three-stage {
position: relative;
min-height: 0;
overflow: hidden;
background: #000;
}
.image-stage,
.segmentation-stage {
display: grid;
place-items: center;
}
.image-stage img,
.segmentation-stage img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
image-rendering: auto;
}
.segmentation-stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.empty-state {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
color: rgba(234, 242, 251, 0.44);
font-size: 13px;
font-weight: 800;
text-align: center;
}
.slice-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 72px;
gap: 10px;
align-items: center;
height: 42px;
padding: 0 12px;
border-top: 1px solid var(--line);
background: rgba(11, 17, 24, 0.86);
}
.slice-row input {
width: 100%;
accent-color: var(--cyan);
}
.slice-row span {
color: var(--muted);
font-size: 12px;
text-align: right;
}
.login-overlay {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: rgba(7, 11, 16, 0.78);
backdrop-filter: blur(8px);
}
.login-panel {
width: min(390px, calc(100vw - 32px));
display: grid;
gap: 12px;
padding: 24px;
border: 1px solid var(--line-strong);
border-radius: 8px;
background: rgba(16, 23, 32, 0.96);
box-shadow: var(--shadow);
}
.login-panel h2 {
margin: 0;
font-size: 18px;
}
.login-panel p {
margin: 0;
color: var(--muted);
font-size: 13px;
}
.login-panel .search-input {
margin-top: 0;
}
.error-line {
min-height: 18px;
color: #fecdd3;
font-size: 12px;
}
@media (max-width: 1320px) {
.workspace {
grid-template-columns: 360px minmax(0, 1fr);
}
.viewer-grid {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: repeat(4, minmax(360px, 1fr));
overflow: auto;
}
}
@media (max-width: 900px) {
body {
overflow: auto;
}
.topbar,
.workspace {
height: auto;
}
.topbar,
.workspace,
.left-rail,
.viewer-shell {
display: grid;
grid-template-columns: 1fr;
}
.top-actions {
flex-wrap: wrap;
justify-content: start;
}
.left-rail {
grid-template-rows: auto;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,421 @@
import {
BufferAttribute,
BufferGeometry,
Color,
FileLoader,
Float32BufferAttribute,
Loader,
Vector3,
SRGBColorSpace
} from 'three';
/**
* A loader for the STL format, as created by Solidworks and other CAD programs.
*
* Supports both binary and ASCII encoded files. The loader returns a non-indexed buffer geometry.
*
* Limitations:
* - Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
* - There is perhaps some question as to how valid it is to always assume little-endian-ness.
* - ASCII decoding assumes file is UTF-8.
*
* ```js
* const loader = new STLLoader();
* const geometry = await loader.loadAsync( './models/stl/slotted_disk.stl' )
* scene.add( new THREE.Mesh( geometry ) );
* ```
* For binary STLs geometry might contain colors for vertices. To use it:
* ```js
* // use the same code to load STL as above
* if ( geometry.hasColors ) {
* material = new THREE.MeshPhongMaterial( { opacity: geometry.alpha, vertexColors: true } );
* }
* const mesh = new THREE.Mesh( geometry, material );
* ```
* For ASCII STLs containing multiple solids, each solid is assigned to a different group.
* Groups can be used to assign a different color by defining an array of materials with the same length of
* geometry.groups and passing it to the Mesh constructor:
*
* ```js
* const materials = [];
* const nGeometryGroups = geometry.groups.length;
*
* for ( let i = 0; i < nGeometryGroups; i ++ ) {
* const material = new THREE.MeshPhongMaterial( { color: colorMap[ i ], wireframe: false } );
* materials.push( material );
* }
*
* const mesh = new THREE.Mesh(geometry, materials);
* ```
*
* @augments Loader
* @three_import import { STLLoader } from 'three/addons/loaders/STLLoader.js';
*/
class STLLoader extends Loader {
/**
* Constructs a new STL loader.
*
* @param {LoadingManager} [manager] - The loading manager.
*/
constructor( manager ) {
super( manager );
}
/**
* Starts loading from the given URL and passes the loaded STL asset
* to the `onLoad()` callback.
*
* @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
* @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
* @param {onProgressCallback} onProgress - Executed while the loading is in progress.
* @param {onErrorCallback} onError - Executed when errors occur.
*/
load( url, onLoad, onProgress, onError ) {
const scope = this;
const loader = new FileLoader( this.manager );
loader.setPath( this.path );
loader.setResponseType( 'arraybuffer' );
loader.setRequestHeader( this.requestHeader );
loader.setWithCredentials( this.withCredentials );
loader.load( url, function ( text ) {
try {
onLoad( scope.parse( text ) );
} catch ( e ) {
if ( onError ) {
onError( e );
} else {
console.error( e );
}
scope.manager.itemError( url );
}
}, onProgress, onError );
}
/**
* Parses the given STL data and returns the resulting geometry.
*
* @param {ArrayBuffer} data - The raw STL data as an array buffer.
* @return {BufferGeometry} The parsed geometry.
*/
parse( data ) {
function isBinary( data ) {
const reader = new DataView( data );
const face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 );
const n_faces = reader.getUint32( 80, true );
const expect = 80 + ( 32 / 8 ) + ( n_faces * face_size );
if ( expect === reader.byteLength ) {
return true;
}
// An ASCII STL data must begin with 'solid ' as the first six bytes.
// However, ASCII STLs lacking the SPACE after the 'd' are known to be
// plentiful. So, check the first 5 bytes for 'solid'.
// Several encodings, such as UTF-8, precede the text with up to 5 bytes:
// https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
// Search for "solid" to start anywhere after those prefixes.
// US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
const solid = [ 115, 111, 108, 105, 100 ];
for ( let off = 0; off < 5; off ++ ) {
// If "solid" text is matched to the current offset, declare it to be an ASCII STL.
if ( matchDataViewAt( solid, reader, off ) ) return false;
}
// Couldn't find "solid" text at the beginning; it is binary STL.
return true;
}
function matchDataViewAt( query, reader, offset ) {
// Check if each byte in query matches the corresponding byte from the current offset
for ( let i = 0, il = query.length; i < il; i ++ ) {
if ( query[ i ] !== reader.getUint8( offset + i ) ) return false;
}
return true;
}
function parseBinary( data ) {
const reader = new DataView( data );
const faces = reader.getUint32( 80, true );
let r, g, b, hasColors = false, colors;
let defaultR, defaultG, defaultB, alpha;
// process STL header
// check for default color in header ("COLOR=rgba" sequence).
for ( let index = 0; index < 80 - 10; index ++ ) {
if ( ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ ) &&
( reader.getUint8( index + 4 ) == 0x52 /*'R'*/ ) &&
( reader.getUint8( index + 5 ) == 0x3D /*'='*/ ) ) {
hasColors = true;
colors = new Float32Array( faces * 3 * 3 );
defaultR = reader.getUint8( index + 6 ) / 255;
defaultG = reader.getUint8( index + 7 ) / 255;
defaultB = reader.getUint8( index + 8 ) / 255;
alpha = reader.getUint8( index + 9 ) / 255;
}
}
const dataOffset = 84;
const faceLength = 12 * 4 + 2;
const geometry = new BufferGeometry();
const vertices = new Float32Array( faces * 3 * 3 );
const normals = new Float32Array( faces * 3 * 3 );
const color = new Color();
for ( let face = 0; face < faces; face ++ ) {
const start = dataOffset + face * faceLength;
const normalX = reader.getFloat32( start, true );
const normalY = reader.getFloat32( start + 4, true );
const normalZ = reader.getFloat32( start + 8, true );
if ( hasColors ) {
const packedColor = reader.getUint16( start + 48, true );
if ( ( packedColor & 0x8000 ) === 0 ) {
// facet has its own unique color
r = ( packedColor & 0x1F ) / 31;
g = ( ( packedColor >> 5 ) & 0x1F ) / 31;
b = ( ( packedColor >> 10 ) & 0x1F ) / 31;
} else {
r = defaultR;
g = defaultG;
b = defaultB;
}
}
for ( let i = 1; i <= 3; i ++ ) {
const vertexstart = start + i * 12;
const componentIdx = ( face * 3 * 3 ) + ( ( i - 1 ) * 3 );
vertices[ componentIdx ] = reader.getFloat32( vertexstart, true );
vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true );
vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true );
normals[ componentIdx ] = normalX;
normals[ componentIdx + 1 ] = normalY;
normals[ componentIdx + 2 ] = normalZ;
if ( hasColors ) {
color.setRGB( r, g, b, SRGBColorSpace );
colors[ componentIdx ] = color.r;
colors[ componentIdx + 1 ] = color.g;
colors[ componentIdx + 2 ] = color.b;
}
}
}
geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
if ( hasColors ) {
geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
geometry.hasColors = true;
geometry.alpha = alpha;
}
return geometry;
}
function parseASCII( data ) {
const geometry = new BufferGeometry();
const patternSolid = /solid([\s\S]*?)endsolid/g;
const patternFace = /facet([\s\S]*?)endfacet/g;
const patternName = /solid\s(.+)/;
let faceCounter = 0;
const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
const patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
const patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
const vertices = [];
const normals = [];
const groupNames = [];
const normal = new Vector3();
let result;
let groupCount = 0;
let startVertex = 0;
let endVertex = 0;
while ( ( result = patternSolid.exec( data ) ) !== null ) {
startVertex = endVertex;
const solid = result[ 0 ];
const name = ( result = patternName.exec( solid ) ) !== null ? result[ 1 ] : '';
groupNames.push( name );
while ( ( result = patternFace.exec( solid ) ) !== null ) {
let vertexCountPerFace = 0;
let normalCountPerFace = 0;
const text = result[ 0 ];
while ( ( result = patternNormal.exec( text ) ) !== null ) {
normal.x = parseFloat( result[ 1 ] );
normal.y = parseFloat( result[ 2 ] );
normal.z = parseFloat( result[ 3 ] );
normalCountPerFace ++;
}
while ( ( result = patternVertex.exec( text ) ) !== null ) {
vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
normals.push( normal.x, normal.y, normal.z );
vertexCountPerFace ++;
endVertex ++;
}
// every face have to own ONE valid normal
if ( normalCountPerFace !== 1 ) {
console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
}
// each face have to own THREE valid vertices
if ( vertexCountPerFace !== 3 ) {
console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
}
faceCounter ++;
}
const start = startVertex;
const count = endVertex - startVertex;
geometry.userData.groupNames = groupNames;
geometry.addGroup( start, count, groupCount );
groupCount ++;
}
geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
return geometry;
}
function ensureString( buffer ) {
if ( typeof buffer !== 'string' ) {
return new TextDecoder().decode( buffer );
}
return buffer;
}
function ensureBinary( buffer ) {
if ( typeof buffer === 'string' ) {
const array_buffer = new Uint8Array( buffer.length );
for ( let i = 0; i < buffer.length; i ++ ) {
array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
}
return array_buffer.buffer || array_buffer;
} else {
return buffer;
}
}
// start
const binData = ensureBinary( data );
return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
}
}
export { STLLoader };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long