mirror of
https://github.com/yeicor-3d/yet-another-cad-viewer.git
synced 2025-12-19 22:24:17 +01:00
Compare commits
210 Commits
feature/py
...
a7dcf780e1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7dcf780e1 | ||
|
|
134342064b | ||
|
|
4b4d63b289 | ||
|
|
58f7453b0b | ||
|
|
07cec00b1a | ||
|
|
4ed83e32a4 | ||
|
|
ea1cd46d22 | ||
|
|
8092075422 | ||
|
|
65cc7144fa | ||
|
|
3ca1544fc0 | ||
|
|
d63e274bb6 | ||
|
|
617f83f6f1 | ||
|
|
76df2f5ca5 | ||
|
|
b7f26dbfcb | ||
|
|
4c4c8c766c | ||
|
|
1c414d920d | ||
|
|
6dba535906 | ||
|
|
eaf09203da | ||
|
|
2393080240 | ||
|
|
df890b798c | ||
|
|
cde0e6137b | ||
|
|
8a8cc8e5a8 | ||
|
|
7863611a51 | ||
|
|
367fa1b4e4 | ||
|
|
7b553b635b | ||
|
|
24cf291cdd | ||
|
|
9c133a6d50 | ||
|
|
d44ea072d5 | ||
|
|
014622ffaa | ||
|
|
23b50c38ca | ||
|
|
8154ac9502 | ||
|
|
aaac6d4245 | ||
|
|
91f5084532 | ||
|
|
e957e0a937 | ||
|
|
e480d297e8 | ||
|
|
4439647faa | ||
|
|
4f2c9eda11 | ||
|
|
ad8e75d1da | ||
|
|
14022f170c | ||
|
|
6302fc023c | ||
|
|
3685ed13c0 | ||
|
|
b2c815daf7 | ||
|
|
630bb7d90b | ||
|
|
aa2c2e570b | ||
|
|
5855458ff0 | ||
|
|
41170118c3 | ||
|
|
efa689bfe4 | ||
|
|
971a791617 | ||
|
|
1d1228e044 | ||
|
|
55ba73a635 | ||
|
|
b51135ba39 | ||
|
|
95755f6ad3 | ||
|
|
82efea0786 | ||
|
|
0a66e62575 | ||
|
|
4f6bdbe1ad | ||
|
|
92d09d52d3 | ||
|
|
d012d68cfc | ||
|
|
496df80e26 | ||
|
|
8df15a9cad | ||
|
|
03eac030c4 | ||
|
|
8f49a5deee | ||
|
|
070488f8c6 | ||
|
|
44fb50869e | ||
|
|
c8e1ba5f07 | ||
|
|
cb2e09a6c2 | ||
|
|
daf9fb16f7 | ||
|
|
98bc0407b3 | ||
|
|
57bcd52944 | ||
|
|
ce03ea001d | ||
|
|
b6a2bde5e1 | ||
|
|
9079ccc0b3 | ||
|
|
aed7680d48 | ||
|
|
6fc4f922fd | ||
|
|
e5ee7a45be | ||
|
|
c9c3fe5bd9 | ||
|
|
cc39079c70 | ||
|
|
a52e503e81 | ||
|
|
dd5c4253a7 | ||
|
|
209b40e9a7 | ||
|
|
96c5c8a63f | ||
|
|
0aa761dcf4 | ||
|
|
be9f3994a8 | ||
|
|
ed1296f858 | ||
|
|
1c908bdfba | ||
|
|
7434652379 | ||
|
|
f59e3048d4 | ||
|
|
ed2431f7da | ||
|
|
c4d47afe69 | ||
|
|
ec91ab90f2 | ||
|
|
3f573c75cc | ||
|
|
4eee767afb | ||
|
|
3f9ec31799 | ||
|
|
54a22b1499 | ||
|
|
438d315b53 | ||
|
|
0cc6d81e9e | ||
|
|
2468aeed08 | ||
|
|
a8ec19e2d4 | ||
|
|
741a658b01 | ||
|
|
19663354cc | ||
|
|
e5f2246ff1 | ||
|
|
4cb8a65582 | ||
|
|
fc737583fd | ||
|
|
37ddf9ab63 | ||
|
|
5977172096 | ||
|
|
888239d898 | ||
|
|
fdfc5cdcad | ||
|
|
e2707ac8db | ||
|
|
f0a55efff1 | ||
|
|
71e95ec393 | ||
|
|
454a7249cd | ||
|
|
1501f8c3b5 | ||
|
|
32d34d9ec4 | ||
|
|
9b3b679631 | ||
|
|
dd389f34a3 | ||
|
|
21cdaf2c33 | ||
|
|
ace4d5aa5e | ||
|
|
289677a4ac | ||
|
|
a97c2807d8 | ||
|
|
629aa939ca | ||
|
|
e21fa7d680 | ||
|
|
3933d4842b | ||
|
|
95ffb769e2 | ||
|
|
16627a3cd4 | ||
|
|
0e1f6b7aa0 | ||
|
|
0ff8776a12 | ||
|
|
64e9e26da1 | ||
|
|
7eaba92057 | ||
|
|
6a0aa265b6 | ||
|
|
fbf2f3e9a1 | ||
|
|
74491fc867 | ||
|
|
cc0b087cf7 | ||
|
|
fcacf8172d | ||
|
|
0c93a7e05d | ||
|
|
e50e3c7f09 | ||
|
|
9f76df8668 | ||
|
|
6c7f7382f6 | ||
|
|
c7aee20aac | ||
|
|
8598f7f75e | ||
|
|
7a8ff04cc7 | ||
|
|
ac8bf8cb06 | ||
|
|
7a425e3ccc | ||
|
|
ff3c3d6f2f | ||
|
|
8792ab7139 | ||
|
|
291e3c726d | ||
|
|
be400fde29 | ||
|
|
32fb3230bb | ||
|
|
a63175dc3a | ||
|
|
3c013de8ba | ||
|
|
a659b0561f | ||
|
|
ccd48bcae3 | ||
|
|
1a9cac08cd | ||
|
|
3fb07300b8 | ||
|
|
938c554919 | ||
|
|
5308ececae | ||
|
|
64e2622954 | ||
|
|
2e8b8bd65f | ||
|
|
854de26695 | ||
|
|
e0503983f1 | ||
|
|
021cfd89a1 | ||
|
|
9d96effb30 | ||
|
|
dff2d36b44 | ||
|
|
810647276b | ||
|
|
a54b91f704 | ||
|
|
099726035a | ||
|
|
c383b8573a | ||
|
|
f1c0a21699 | ||
|
|
8df0401fef | ||
|
|
2c7adf8188 | ||
|
|
d2b1b3b952 | ||
|
|
db3bbf2d32 | ||
|
|
1d6230ef1e | ||
|
|
7d22ca465e | ||
|
|
7c38ccc522 | ||
|
|
06a95d4875 | ||
|
|
56fc556c0f | ||
|
|
fe54f48ad7 | ||
|
|
c47f961b0d | ||
|
|
f86b714c08 | ||
|
|
2ae7c86f8d | ||
|
|
0908216bfc | ||
|
|
7871a5070d | ||
|
|
5173f00d29 | ||
|
|
c2ef910783 | ||
|
|
5a5f948224 | ||
|
|
dbeae5632e | ||
|
|
59116e4a1a | ||
|
|
0be0103c3c | ||
|
|
d6deef9e7f | ||
|
|
ad956762f4 | ||
|
|
a4acd2f3d3 | ||
|
|
c877fef490 | ||
|
|
0855a9c6c7 | ||
|
|
657b34d098 | ||
|
|
ad83f1c937 | ||
|
|
38be4c638b | ||
|
|
63f2b716d6 | ||
|
|
9e70a3998d | ||
|
|
c7c4adc250 | ||
|
|
393decd876 | ||
|
|
111f417905 | ||
|
|
7296b15a67 | ||
|
|
88190b0d1e | ||
|
|
f2a607bb00 | ||
|
|
0b6ed2fc34 | ||
|
|
d1e5658e07 | ||
|
|
3545785cae | ||
|
|
1df938b067 | ||
|
|
42ae6384f0 | ||
|
|
b10b228fcc | ||
|
|
ffaf6f26ba |
28
.github/workflows/build.yml
vendored
28
.github/workflows/build.yml
vendored
@@ -14,15 +14,15 @@ jobs:
|
|||||||
name: "Build frontend"
|
name: "Build frontend"
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with:
|
with:
|
||||||
ref: "${{ inputs.ref }}"
|
ref: "${{ inputs.ref }}"
|
||||||
- uses: "actions/setup-node@v4"
|
- uses: "actions/setup-node@v6"
|
||||||
with:
|
with:
|
||||||
cache: "yarn"
|
cache: "yarn"
|
||||||
- run: "yarn install"
|
- run: "yarn install"
|
||||||
- run: "yarn build"
|
- run: "yarn build"
|
||||||
- uses: "actions/upload-artifact@v4"
|
- uses: "actions/upload-artifact@v6"
|
||||||
with:
|
with:
|
||||||
name: "frontend"
|
name: "frontend"
|
||||||
path: "dist"
|
path: "dist"
|
||||||
@@ -32,13 +32,13 @@ jobs:
|
|||||||
name: "Build backend"
|
name: "Build backend"
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with:
|
with:
|
||||||
ref: "${{ inputs.ref }}"
|
ref: "${{ inputs.ref }}"
|
||||||
- run: "pipx install poetry"
|
- run: "pipx install poetry"
|
||||||
- uses: "actions/setup-python@v5"
|
- uses: "actions/setup-python@v6"
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.14"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- run: "poetry lock"
|
- run: "poetry lock"
|
||||||
- run: "poetry install"
|
- run: "poetry install"
|
||||||
@@ -48,18 +48,18 @@ jobs:
|
|||||||
name: "Build logo"
|
name: "Build logo"
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with:
|
with:
|
||||||
ref: "${{ inputs.ref }}"
|
ref: "${{ inputs.ref }}"
|
||||||
- run: "pipx install poetry"
|
- run: "pipx install poetry"
|
||||||
- uses: "actions/setup-python@v5"
|
- uses: "actions/setup-python@v6"
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.14"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- run: "poetry lock"
|
- run: "poetry lock"
|
||||||
- run: "poetry install"
|
- run: "poetry install"
|
||||||
- run: "poetry run python yacv_server/logo.py"
|
- run: "poetry run python yacv_server/logo.py"
|
||||||
- uses: "actions/upload-artifact@v4"
|
- uses: "actions/upload-artifact@v6"
|
||||||
with:
|
with:
|
||||||
name: "logo"
|
name: "logo"
|
||||||
path: "assets/logo_build"
|
path: "assets/logo_build"
|
||||||
@@ -69,18 +69,18 @@ jobs:
|
|||||||
name: "Build example"
|
name: "Build example"
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with:
|
with:
|
||||||
ref: "${{ inputs.ref }}"
|
ref: "${{ inputs.ref }}"
|
||||||
- run: "pipx install poetry"
|
- run: "pipx install poetry"
|
||||||
- uses: "actions/setup-python@v5"
|
- uses: "actions/setup-python@v6"
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.14"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- run: "poetry lock"
|
- run: "poetry lock"
|
||||||
- run: "poetry install"
|
- run: "poetry install"
|
||||||
- run: "YACV_DISABLE_SERVER=true poetry run python example/object.py"
|
- run: "YACV_DISABLE_SERVER=true poetry run python example/object.py"
|
||||||
- uses: "actions/upload-artifact@v4"
|
- uses: "actions/upload-artifact@v6"
|
||||||
with:
|
with:
|
||||||
name: "example"
|
name: "example"
|
||||||
path: "export"
|
path: "export"
|
||||||
|
|||||||
22
.github/workflows/deploy1.yml
vendored
22
.github/workflows/deploy1.yml
vendored
@@ -12,32 +12,37 @@ jobs:
|
|||||||
|
|
||||||
update-versions:
|
update-versions:
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
|
outputs:
|
||||||
|
skip: "${{ steps.check_recursive.outputs.skip || 'false' }}" # Default to false if not set
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with: # Ensure we are not in a detached HEAD state
|
with: # Ensure we are not in a detached HEAD state
|
||||||
ref: "master"
|
ref: "master"
|
||||||
|
token: "${{ secrets.GH_PAT }}"
|
||||||
# Check that the tag commit is the latest master commit
|
# Check that the tag commit is the latest master commit
|
||||||
- run: |
|
- id: check_recursive
|
||||||
|
run: |
|
||||||
git fetch --tags
|
git fetch --tags
|
||||||
tag_commit=$(git rev-parse ${{ github.ref }})
|
tag_commit=$(git rev-parse ${{ github.ref }})
|
||||||
master_commit=$(git rev-parse master)
|
master_commit=$(git rev-parse master)
|
||||||
if [ "$tag_commit" != "$master_commit" ]; then
|
if [ "$tag_commit" != "$master_commit" ]; then
|
||||||
echo "The tag commit ($tag_commit) is not the latest master commit ($master_commit)"
|
echo "::warning ::The tag commit $tag_commit does not match the latest master commit $master_commit. This is probably a recursive tag push that will be ignored."
|
||||||
exit 1
|
echo "skip=true" >> $GITHUB_OUTPUT
|
||||||
fi
|
fi
|
||||||
- run: "echo 'CLEAN_VERSION=${{ github.ref }}' | sed 's,refs/tags/v,,g' >> $GITHUB_ENV"
|
- run: "echo 'CLEAN_VERSION=${{ github.ref }}' | sed 's,refs/tags/v,,g' >> $GITHUB_ENV"
|
||||||
# Write the new version to package.json
|
# Write the new version to package.json
|
||||||
- uses: "actions/setup-node@v4"
|
- uses: "actions/setup-node@v6"
|
||||||
- run: "yarn version --new-version $CLEAN_VERSION --no-git-tag-version"
|
- run: "yarn version --new-version $CLEAN_VERSION --no-git-tag-version"
|
||||||
# Write the new version to pyproject.toml
|
# Write the new version to pyproject.toml
|
||||||
- run: "pipx install poetry"
|
- run: "pipx install poetry"
|
||||||
- uses: "actions/setup-python@v5"
|
- uses: "actions/setup-python@v6"
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.14"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- run: "poetry version $CLEAN_VERSION"
|
- run: "poetry version $CLEAN_VERSION"
|
||||||
# Commit the changes and move the tag!
|
# Commit the changes and move the tag!
|
||||||
- run: |
|
- if: "steps.check_recursive.outputs.skip != 'true'"
|
||||||
|
run: |
|
||||||
git config --global user.email "yeicor@users.noreply.github.com"
|
git config --global user.email "yeicor@users.noreply.github.com"
|
||||||
git config --global user.name "Yeicor"
|
git config --global user.name "Yeicor"
|
||||||
if git commit -am "Automatically update version to $CLEAN_VERSION"; then
|
if git commit -am "Automatically update version to $CLEAN_VERSION"; then
|
||||||
@@ -53,6 +58,7 @@ jobs:
|
|||||||
|
|
||||||
deploy: # Makes sure all artifacts are updated and use the new version for the next deployment steps
|
deploy: # Makes sure all artifacts are updated and use the new version for the next deployment steps
|
||||||
needs: "update-versions"
|
needs: "update-versions"
|
||||||
|
if: "needs.update-versions.outputs.skip != 'true'" # Only run if the update-versions job did not skip
|
||||||
uses: "./.github/workflows/deploy2.yml"
|
uses: "./.github/workflows/deploy2.yml"
|
||||||
secrets: "inherit" # Inherit the secrets from the parent workflow
|
secrets: "inherit" # Inherit the secrets from the parent workflow
|
||||||
with:
|
with:
|
||||||
|
|||||||
12
.github/workflows/deploy2.yml
vendored
12
.github/workflows/deploy2.yml
vendored
@@ -32,12 +32,12 @@ jobs:
|
|||||||
name: "github-pages"
|
name: "github-pages"
|
||||||
url: "${{ steps.deployment.outputs.page_url }}"
|
url: "${{ steps.deployment.outputs.page_url }}"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/download-artifact@v4"
|
- uses: "actions/download-artifact@v7"
|
||||||
with: # Downloads all artifacts from the build job
|
with: # Downloads all artifacts from the build job
|
||||||
path: "./public"
|
path: "./public"
|
||||||
merge-multiple: true
|
merge-multiple: true
|
||||||
- uses: "actions/configure-pages@v5"
|
- uses: "actions/configure-pages@v5"
|
||||||
- uses: "actions/upload-pages-artifact@v3"
|
- uses: "actions/upload-pages-artifact@v4"
|
||||||
with:
|
with:
|
||||||
path: 'public'
|
path: 'public'
|
||||||
- id: "deployment"
|
- id: "deployment"
|
||||||
@@ -54,16 +54,16 @@ jobs:
|
|||||||
needs: "rebuild"
|
needs: "rebuild"
|
||||||
runs-on: "ubuntu-latest"
|
runs-on: "ubuntu-latest"
|
||||||
steps:
|
steps:
|
||||||
- uses: "actions/checkout@v4"
|
- uses: "actions/checkout@v6"
|
||||||
with:
|
with:
|
||||||
ref: "${{ inputs.ref }}"
|
ref: "${{ inputs.ref }}"
|
||||||
- uses: "actions/setup-node@v4"
|
- uses: "actions/setup-node@v6"
|
||||||
with:
|
with:
|
||||||
cache: "yarn"
|
cache: "yarn"
|
||||||
- run: "pipx install poetry"
|
- run: "pipx install poetry"
|
||||||
- uses: "actions/setup-python@v5"
|
- uses: "actions/setup-python@v6"
|
||||||
with:
|
with:
|
||||||
python-version: "3.12"
|
python-version: "3.14"
|
||||||
cache: "poetry"
|
cache: "poetry"
|
||||||
- run: "poetry install"
|
- run: "poetry install"
|
||||||
- run: "poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }}"
|
- run: "poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }}"
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -11,3 +11,4 @@
|
|||||||
|
|
||||||
*.iml
|
*.iml
|
||||||
venv/
|
venv/
|
||||||
|
__pycache__/
|
||||||
|
|||||||
15
CONTRIBUTING.md
Normal file
15
CONTRIBUTING.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# Contributing to Yet Another CAD Viewer
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to this project!
|
||||||
|
|
||||||
|
## How to contribute
|
||||||
|
|
||||||
|
- For **non-trivial changes** or new features, please [open an issue](https://github.com/yeicor-3d/yet-another-cad-viewer/issues) first to discuss your idea before submitting a pull request.
|
||||||
|
- For **small fixes** (such as typo corrections or minor improvements), feel free to submit a pull request directly.
|
||||||
|
|
||||||
|
## Pull requests
|
||||||
|
|
||||||
|
- Make sure your changes are clear and concise.
|
||||||
|
- Describe what your pull request does and reference any related issues.
|
||||||
|
|
||||||
|
We appreciate your help in improving this project!
|
||||||
14
README.md
14
README.md
@@ -10,20 +10,22 @@ in a web browser.
|
|||||||
- All [GLTF 2.0](https://www.khronos.org/gltf/) features (textures, PBR materials, animations...).
|
- All [GLTF 2.0](https://www.khronos.org/gltf/) features (textures, PBR materials, animations...).
|
||||||
- All [model-viewer](https://modelviewer.dev/) features (smooth controls, augmented reality...).
|
- All [model-viewer](https://modelviewer.dev/) features (smooth controls, augmented reality...).
|
||||||
- Load multiple models at once, load external models and even images as quads.
|
- Load multiple models at once, load external models and even images as quads.
|
||||||
- Control clipping planes and transparency of each model.
|
- Control clipping planes, transparency, edge/vertex sizes and explode each model.
|
||||||
- View and interact with topological entities: faces, edges, vertices and locations.
|
- View and interact with topological entities: faces, edges, vertices and locations.
|
||||||
- Select any entity and measure bounding box size and distances.
|
- Select any entity and measure bounding box size and distances.
|
||||||
- Hot reloading while editing the CAD model (using the `yacv-server` package).
|
- Hot reloading while editing the CAD model (using the `yacv-server` package).
|
||||||
- Fully-featured static deployment: just upload the viewer and models to your server.
|
- Fully-featured static deployment: just upload the viewer and models to your server.
|
||||||
|
- Build123d playground! Code and build your model fully inside the
|
||||||
|
browser: [demo](https://yeicor-3d.github.io/yet-another-cad-viewer/#pg_code=https://raw.githubusercontent.com/gumyr/build123d/refs/heads/dev/examples/toy_truck.py).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
The [example](example) is a fully working project that shows how to use the viewer.
|
The [example](example) is a fully working project that shows how to use the viewer.
|
||||||
|
|
||||||
You can play with the latest
|
You can play with the latest
|
||||||
demo [here](https://yeicor-3d.github.io/yet-another-cad-viewer/?preload=logo.glb&preload=logo_hl.glb&preload=fox.glb&preload=img.jpg.glb&preload=location.glb)
|
demo [here](https://yeicor-3d.github.io/yet-another-cad-viewer/?preload=logo.glb&preload=logo_hl.glb&preload=logo_hl_tex.glb&preload=fox.glb&preload=img.glb&preload=location.glb)
|
||||||
(or
|
(or
|
||||||
[without animation](https://yeicor-3d.github.io/yet-another-cad-viewer/?autoplay=false&preload=logo.glb&preload=logo_hl.glb&preload=fox.glb&preload=img.jpg.glb&preload=location.glb)).
|
[without animation](https://yeicor-3d.github.io/yet-another-cad-viewer/?autoplay=false&preload=logo.glb&preload=logo_hl.glb&preload=logo_hl_tex.glb&preload=fox.glb&preload=img.glb&preload=location.glb)).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -32,4 +34,8 @@ demo [here](https://yeicor-3d.github.io/yet-another-cad-viewer/?preload=logo.glb
|
|||||||
- [cq-studio](https://github.com/ccazabon/cq-studio) provides an alternative workflow that detects file changes instead
|
- [cq-studio](https://github.com/ccazabon/cq-studio) provides an alternative workflow that detects file changes instead
|
||||||
of relying on an interactive environment like Jupyter for hot-reloading.
|
of relying on an interactive environment like Jupyter for hot-reloading.
|
||||||
Uses the same backend and frontend behind the scenes.
|
Uses the same backend and frontend behind the scenes.
|
||||||
- [build123d-docker](https://github.com/derhuerst/build123d-docker/pkgs/container/build123d) provides docker images for Yet Another CAD Viewer and other projects, with automatic updates.
|
- [build123d-docker](https://github.com/derhuerst/build123d-docker/pkgs/container/build123d) provides docker images for
|
||||||
|
Yet Another CAD Viewer and other projects, with automatic updates.
|
||||||
|
- [OCP.wasm](https://github.com/yeicor/OCP.wasm/) ports OCP (OpenCASCADE for Python) and supporting libraries to
|
||||||
|
WebAssembly, enabling full in-browser CAD model generation and manipulation. This powers the build123d playground
|
||||||
|
provided by this viewer.
|
||||||
|
|||||||
@@ -809,9 +809,9 @@ The above copyright notice and this permission notice shall be included in all c
|
|||||||
|
|
||||||
The following npm packages may be included in this product:
|
The following npm packages may be included in this product:
|
||||||
|
|
||||||
- @img/sharp-linux-x64@0.33.5
|
- @img/sharp-linux-x64@0.34.3
|
||||||
- @img/sharp-linuxmusl-x64@0.33.5
|
- @img/sharp-linuxmusl-x64@0.34.3
|
||||||
- sharp@0.33.5
|
- sharp@0.34.3
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
|
|
||||||
@@ -1011,7 +1011,7 @@ third-party archives.
|
|||||||
|
|
||||||
The following npm package may be included in this product:
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
- typescript@5.8.3
|
- typescript@5.9.2
|
||||||
|
|
||||||
This package contains the following license:
|
This package contains the following license:
|
||||||
|
|
||||||
@@ -1504,6 +1504,16 @@ SOFTWARE.
|
|||||||
|
|
||||||
-----------
|
-----------
|
||||||
|
|
||||||
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
|
- tanmayo7lock@1.0.18
|
||||||
|
|
||||||
|
This package contains the following license:
|
||||||
|
|
||||||
|
ISC
|
||||||
|
|
||||||
|
-----------
|
||||||
|
|
||||||
The following npm package may be included in this product:
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
- picocolors@1.1.1
|
- picocolors@1.1.1
|
||||||
@@ -1530,8 +1540,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|||||||
|
|
||||||
The following npm packages may be included in this product:
|
The following npm packages may be included in this product:
|
||||||
|
|
||||||
- @img/sharp-libvips-linux-x64@1.0.4
|
- @img/sharp-libvips-linux-x64@1.2.0
|
||||||
- @img/sharp-libvips-linuxmusl-x64@1.0.4
|
- @img/sharp-libvips-linuxmusl-x64@1.2.0
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
|
|
||||||
@@ -1543,7 +1553,7 @@ The following npm packages may be included in this product:
|
|||||||
|
|
||||||
- @babel/helper-string-parser@7.27.1
|
- @babel/helper-string-parser@7.27.1
|
||||||
- @babel/helper-validator-identifier@7.27.1
|
- @babel/helper-validator-identifier@7.27.1
|
||||||
- @babel/types@7.28.1
|
- @babel/types@7.28.2
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
|
|
||||||
@@ -1814,7 +1824,7 @@ SOFTWARE.
|
|||||||
|
|
||||||
The following npm package may be included in this product:
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
- pyodide@0.28.0
|
- pyodide@0.28.1
|
||||||
|
|
||||||
This package contains the following license:
|
This package contains the following license:
|
||||||
|
|
||||||
@@ -1908,7 +1918,7 @@ THE SOFTWARE.
|
|||||||
|
|
||||||
The following npm package may be included in this product:
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
- three@0.178.0
|
- three@0.179.1
|
||||||
|
|
||||||
This package contains the following license:
|
This package contains the following license:
|
||||||
|
|
||||||
@@ -2028,7 +2038,7 @@ SOFTWARE.
|
|||||||
|
|
||||||
The following npm package may be included in this product:
|
The following npm package may be included in this product:
|
||||||
|
|
||||||
- vuetify@3.9.0
|
- vuetify@3.9.4
|
||||||
|
|
||||||
This package contains the following license:
|
This package contains the following license:
|
||||||
|
|
||||||
@@ -2058,16 +2068,16 @@ THE SOFTWARE.
|
|||||||
|
|
||||||
The following npm packages may be included in this product:
|
The following npm packages may be included in this product:
|
||||||
|
|
||||||
- @vue/compiler-core@3.5.17
|
- @vue/compiler-core@3.5.18
|
||||||
- @vue/compiler-dom@3.5.17
|
- @vue/compiler-dom@3.5.18
|
||||||
- @vue/compiler-sfc@3.5.17
|
- @vue/compiler-sfc@3.5.18
|
||||||
- @vue/compiler-ssr@3.5.17
|
- @vue/compiler-ssr@3.5.18
|
||||||
- @vue/reactivity@3.5.17
|
- @vue/reactivity@3.5.18
|
||||||
- @vue/runtime-core@3.5.17
|
- @vue/runtime-core@3.5.18
|
||||||
- @vue/runtime-dom@3.5.17
|
- @vue/runtime-dom@3.5.18
|
||||||
- @vue/server-renderer@3.5.17
|
- @vue/server-renderer@3.5.18
|
||||||
- @vue/shared@3.5.17
|
- @vue/shared@3.5.18
|
||||||
- vue@3.5.17
|
- vue@3.5.18
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
|
|
||||||
@@ -2128,7 +2138,7 @@ SOFTWARE.
|
|||||||
The following npm packages may be included in this product:
|
The following npm packages may be included in this product:
|
||||||
|
|
||||||
- ndarray-lanczos@0.3.0
|
- ndarray-lanczos@0.3.0
|
||||||
- ndarray-pixels@4.1.0
|
- ndarray-pixels@5.0.1
|
||||||
- property-graph@3.0.0
|
- property-graph@3.0.0
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
@@ -2159,9 +2169,9 @@ SOFTWARE.
|
|||||||
|
|
||||||
The following npm packages may be included in this product:
|
The following npm packages may be included in this product:
|
||||||
|
|
||||||
- @gltf-transform/core@4.2.0
|
- @gltf-transform/core@4.2.1
|
||||||
- @gltf-transform/extensions@4.2.0
|
- @gltf-transform/extensions@4.2.1
|
||||||
- @gltf-transform/functions@4.2.0
|
- @gltf-transform/functions@4.2.1
|
||||||
|
|
||||||
These packages each contain the following license:
|
These packages each contain the following license:
|
||||||
|
|
||||||
|
|||||||
@@ -51,9 +51,10 @@ async function onModelUpdateRequest(event: NetworkUpdateEvent) {
|
|||||||
for (let modelIndex in event.models) {
|
for (let modelIndex in event.models) {
|
||||||
let isLast = parseInt(modelIndex) === event.models.length - 1;
|
let isLast = parseInt(modelIndex) === event.models.length - 1;
|
||||||
let model = event.models[modelIndex];
|
let model = event.models[modelIndex];
|
||||||
|
if (!model) continue;
|
||||||
tools.value?.removeObjectSelections(model.name);
|
tools.value?.removeObjectSelections(model.name);
|
||||||
try {
|
try {
|
||||||
let loadHelpers = (await settings()).loadHelpers;
|
let loadHelpers = (await settings).loadHelpers;
|
||||||
if (!model.isRemove) {
|
if (!model.isRemove) {
|
||||||
doc = await SceneMgr.loadModel(sceneUrl, doc, model.name, model.url, isLast && loadHelpers, isLast);
|
doc = await SceneMgr.loadModel(sceneUrl, doc, model.name, model.url, isLast && loadHelpers, isLast);
|
||||||
} else {
|
} else {
|
||||||
@@ -83,7 +84,7 @@ networkMgr.addEventListener('update-early',
|
|||||||
networkMgr.addEventListener('update', (e) => onModelUpdateRequest(e as NetworkUpdateEvent));
|
networkMgr.addEventListener('update', (e) => onModelUpdateRequest(e as NetworkUpdateEvent));
|
||||||
let preloadingModels = ref<Array<string>>([]);
|
let preloadingModels = ref<Array<string>>([]);
|
||||||
(async () => { // Start loading all configured models ASAP
|
(async () => { // Start loading all configured models ASAP
|
||||||
let sett = await settings();
|
let sett = await settings;
|
||||||
if (sett.preload.length > 0) {
|
if (sett.preload.length > 0) {
|
||||||
watch(viewer, (newViewer) => {
|
watch(viewer, (newViewer) => {
|
||||||
if (newViewer) {
|
if (newViewer) {
|
||||||
@@ -108,6 +109,28 @@ async function loadModelManual() {
|
|||||||
const modelUrl = prompt("For an improved experience in viewing CAD/GLTF models with automatic updates, it's recommended to use the official yacv_server Python package. This ensures seamless serving of models and automatic updates.\n\nOtherwise, enter the URL of the model to load:");
|
const modelUrl = prompt("For an improved experience in viewing CAD/GLTF models with automatic updates, it's recommended to use the official yacv_server Python package. This ensures seamless serving of models and automatic updates.\n\nOtherwise, enter the URL of the model to load:");
|
||||||
if (modelUrl) await networkMgr.load(modelUrl);
|
if (modelUrl) await networkMgr.load(modelUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function loadDemoModels() {
|
||||||
|
for (let name of ['fox.glb', 'img.glb', 'location.glb', 'logo.glb', 'logo_hl.glb', 'logo_hl_tex.glb']) {
|
||||||
|
networkMgr.load(`https://yeicor-3d.github.io/yet-another-cad-viewer/${name}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect dropped .glb files and load them manually
|
||||||
|
document.body.addEventListener("dragover", e => {
|
||||||
|
e.preventDefault(); // Allow drop
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.addEventListener("drop", async e => {
|
||||||
|
e.preventDefault();
|
||||||
|
const file = e.dataTransfer?.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
const ext = file.name.split('.').pop()?.toLowerCase();
|
||||||
|
if (ext === 'glb' || ext === 'gltf') {
|
||||||
|
await networkMgr.load(file);
|
||||||
|
}
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -122,9 +145,8 @@ async function loadModelManual() {
|
|||||||
<v-btn @click="() => tools?.openPlayground()" class="mx-auto d-block my-4">
|
<v-btn @click="() => tools?.openPlayground()" class="mx-auto d-block my-4">
|
||||||
<svg-icon :path="mdiScriptTextPlay" type="mdi"/> Open playground...
|
<svg-icon :path="mdiScriptTextPlay" type="mdi"/> Open playground...
|
||||||
</v-btn>
|
</v-btn>
|
||||||
<v-btn @click="networkMgr.load('https://yeicor-3d.github.io/yet-another-cad-viewer/logo.glb')"
|
<v-btn @click="loadDemoModels" class="mx-auto d-block my-4">
|
||||||
class="mx-auto d-block my-4">
|
<svg-icon :path="mdiCube" type="mdi"/> Load demo models...
|
||||||
<svg-icon :path="mdiCube" type="mdi"/> Load demo model...
|
|
||||||
</v-btn>
|
</v-btn>
|
||||||
<v-btn @click="loadModelManual" class="mx-auto d-block my-4">
|
<v-btn @click="loadModelManual" class="mx-auto d-block my-4">
|
||||||
<svg-icon :path="mdiPlus" type="mdi"/> Load model manually...
|
<svg-icon :path="mdiPlus" type="mdi"/> Load model manually...
|
||||||
@@ -132,7 +154,9 @@ async function loadModelManual() {
|
|||||||
<span v-if="preloadingModels.length > 0" class="d-block text-center my-16">
|
<span v-if="preloadingModels.length > 0" class="d-block text-center my-16">
|
||||||
<span class="d-block text-center text-h6">Still trying to load the following:</span>
|
<span class="d-block text-center text-h6">Still trying to load the following:</span>
|
||||||
<span class="d-block text-center" v-for="(model, index) in preloadingModels" :key="index">
|
<span class="d-block text-center" v-for="(model, index) in preloadingModels" :key="index">
|
||||||
{{ model }}<span v-if="index < preloadingModels.length - 1">, </span>
|
<template v-if="model !== undefined">
|
||||||
|
{{ model }}<span v-if="index < preloadingModels.length - 1">, </span>
|
||||||
|
</template>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
@@ -169,4 +193,4 @@ html, body {
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
overflow: hidden !important;
|
overflow: hidden !important;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,75 +1,88 @@
|
|||||||
import {BufferAttribute, InterleavedBufferAttribute, Vector3} from 'three';
|
import { BufferAttribute, InterleavedBufferAttribute, Vector3 } from "three";
|
||||||
import type {MObject3D} from "../tools/Selection.vue";
|
import type { MObject3D } from "../tools/Selection.vue";
|
||||||
import type {ModelScene} from '@google/model-viewer/lib/three-components/ModelScene';
|
import type { ModelScene } from "@google/model-viewer/lib/three-components/ModelScene";
|
||||||
import type {SelectionInfo} from "../tools/selection";
|
import type { SelectionInfo } from "../tools/selection";
|
||||||
|
|
||||||
|
function getCenterAndVertexList(
|
||||||
function getCenterAndVertexList(selInfo: SelectionInfo, scene: ModelScene): {
|
selInfo: SelectionInfo,
|
||||||
center: Vector3,
|
scene: ModelScene,
|
||||||
vertices: Array<Vector3>
|
): {
|
||||||
|
center: Vector3;
|
||||||
|
vertices: Array<Vector3>;
|
||||||
} {
|
} {
|
||||||
let pos: BufferAttribute | InterleavedBufferAttribute = selInfo.object.geometry.getAttribute('position');
|
if (!selInfo.object?.geometry) {
|
||||||
let ind: BufferAttribute | null = selInfo.object.geometry.index;
|
throw new Error("selInfo.object or geometry is undefined");
|
||||||
if (ind === null) {
|
}
|
||||||
ind = new BufferAttribute(new Uint16Array(pos.count), 1);
|
let pos = selInfo.object.geometry.getAttribute("position");
|
||||||
for (let i = 0; i < pos.count; i++) {
|
let ind = selInfo.object.geometry.index;
|
||||||
ind.array[i] = i;
|
if (ind === null) {
|
||||||
}
|
ind = new BufferAttribute(new Uint16Array(pos.count), 1);
|
||||||
|
for (let i = 0; i < pos.count; i++) {
|
||||||
|
ind.array[i] = i;
|
||||||
}
|
}
|
||||||
let center = new Vector3();
|
}
|
||||||
let vertices = [];
|
let center = new Vector3();
|
||||||
for (let i = selInfo.indices[0]; i < selInfo.indices[1]; i++) {
|
let vertices = [];
|
||||||
let index = ind.getX(i)
|
for (let i = selInfo.indices[0]; i < selInfo.indices[1]; i++) {
|
||||||
let vertex = new Vector3(pos.getX(index), pos.getY(index), pos.getZ(index));
|
let index = ind.getX(i);
|
||||||
vertex = scene.target.worldToLocal(selInfo.object.localToWorld(vertex));
|
let vertex = new Vector3(pos.getX(index), pos.getY(index), pos.getZ(index));
|
||||||
center.add(vertex);
|
vertex = scene.target.worldToLocal(selInfo.object.localToWorld(vertex));
|
||||||
vertices.push(vertex);
|
center.add(vertex);
|
||||||
}
|
vertices.push(vertex);
|
||||||
center = center.divideScalar(selInfo.indices[1] - selInfo.indices[0]);
|
}
|
||||||
return {center, vertices};
|
center = center.divideScalar(selInfo.indices[1] - selInfo.indices[0]);
|
||||||
|
return { center, vertices };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Given two THREE.Object3D objects, returns their closest and farthest vertices, and the geometric centers.
|
* Given two THREE.Object3D objects, returns their closest and farthest vertices, and the geometric centers.
|
||||||
* All of them are approximated and should not be used for precise calculations.
|
* All of them are approximated and should not be used for precise calculations.
|
||||||
*/
|
*/
|
||||||
export function distances(a: SelectionInfo, b: SelectionInfo, scene: ModelScene): {
|
export function distances(
|
||||||
min: Array<Vector3>,
|
a: SelectionInfo,
|
||||||
center: Array<Vector3>,
|
b: SelectionInfo,
|
||||||
max: Array<Vector3>
|
scene: ModelScene,
|
||||||
|
): {
|
||||||
|
min: Array<Vector3>;
|
||||||
|
center: Array<Vector3>;
|
||||||
|
max: Array<Vector3>;
|
||||||
} {
|
} {
|
||||||
// Simplify this problem (approximate) by using the distance between each of their vertices.
|
// Simplify this problem (approximate) by using the distance between each of their vertices.
|
||||||
// Find the center of each object.
|
// Find the center of each object.
|
||||||
let {center: aCenter, vertices: aVertices} = getCenterAndVertexList(a, scene);
|
let { center: aCenter, vertices: aVertices } = getCenterAndVertexList(a, scene);
|
||||||
let {center: bCenter, vertices: bVertices} = getCenterAndVertexList(b, scene);
|
let { center: bCenter, vertices: bVertices } = getCenterAndVertexList(b, scene);
|
||||||
|
|
||||||
// Find the closest and farthest vertices.
|
// Find the closest and farthest vertices.
|
||||||
// TODO: Compute actual min and max distances between the two objects.
|
// TODO: Compute actual min and max distances between the two objects.
|
||||||
// FIXME: Really slow... (use a BVH or something)
|
// FIXME: Really slow... (use a BVH or something)
|
||||||
let minDistance = Infinity;
|
let minDistance = Infinity;
|
||||||
let minDistanceVertices = [new Vector3(), new Vector3()];
|
let minDistanceVertices = [new Vector3(), new Vector3()];
|
||||||
let maxDistance = -Infinity;
|
let maxDistance = -Infinity;
|
||||||
let maxDistanceVertices = [new Vector3(), new Vector3()];
|
let maxDistanceVertices = [new Vector3(), new Vector3()];
|
||||||
for (let i = 0; i < aVertices.length; i++) {
|
for (let i = 0; i < aVertices.length; i++) {
|
||||||
for (let j = 0; j < bVertices.length; j++) {
|
for (let j = 0; j < bVertices.length; j++) {
|
||||||
let distance = aVertices[i].distanceTo(bVertices[j]);
|
const aVertex = aVertices[i];
|
||||||
if (distance < minDistance) {
|
const bVertex = bVertices[j];
|
||||||
minDistance = distance;
|
if (aVertex && bVertex) {
|
||||||
minDistanceVertices[0] = aVertices[i];
|
let distance = aVertex.distanceTo(bVertex);
|
||||||
minDistanceVertices[1] = bVertices[j];
|
if (distance < minDistance) {
|
||||||
}
|
minDistance = distance;
|
||||||
if (distance > maxDistance) {
|
minDistanceVertices[0] = aVertex;
|
||||||
maxDistance = distance;
|
minDistanceVertices[1] = bVertex;
|
||||||
maxDistanceVertices[0] = aVertices[i];
|
|
||||||
maxDistanceVertices[1] = bVertices[j];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if (distance > maxDistance) {
|
||||||
|
maxDistance = distance;
|
||||||
|
maxDistanceVertices[0] = aVertex;
|
||||||
|
maxDistanceVertices[1] = bVertex;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Return the results.
|
// Return the results.
|
||||||
return {
|
return {
|
||||||
min: minDistanceVertices,
|
min: minDistanceVertices,
|
||||||
center: [aCenter, bCenter],
|
center: [aCenter, bCenter],
|
||||||
max: maxDistanceVertices
|
max: maxDistanceVertices,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import {Buffer, Document, Scene, type Transform, WebIO} from "@gltf-transform/core";
|
import { Buffer, Document, Scene, type Transform, WebIO } from "@gltf-transform/core";
|
||||||
import {mergeDocuments, unpartition} from "@gltf-transform/functions";
|
import { mergeDocuments, unpartition } from "@gltf-transform/functions";
|
||||||
|
import { retrieveFile } from "../tools/upload-file.ts";
|
||||||
|
|
||||||
let io = new WebIO();
|
let io = new WebIO();
|
||||||
export let extrasNameKey = "__yacv_name";
|
export let extrasNameKey = "__yacv_name";
|
||||||
export let extrasNameValueHelpers = "__helpers";
|
export let extrasNameValueHelpers = "__helpers";
|
||||||
|
|
||||||
// @ts-expect-error
|
// @ts-expect-error
|
||||||
let isSmallBuild = typeof __YACV_SMALL_BUILD__ !== 'undefined' && __YACV_SMALL_BUILD__;
|
let isSmallBuild = typeof __YACV_SMALL_BUILD__ !== "undefined" && __YACV_SMALL_BUILD__;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads a GLB model from a URL and adds it to the document or replaces it if the names match.
|
* Loads a GLB model from a URL and adds it to the document or replaces it if the names match.
|
||||||
@@ -15,106 +16,148 @@ let isSmallBuild = typeof __YACV_SMALL_BUILD__ !== 'undefined' && __YACV_SMALL_B
|
|||||||
*
|
*
|
||||||
* Remember to call mergeFinalize after all models have been merged (slower required operations).
|
* Remember to call mergeFinalize after all models have been merged (slower required operations).
|
||||||
*/
|
*/
|
||||||
export async function mergePartial(url: string, name: string, document: Document, networkFinished: () => void = () => {
|
export async function mergePartial(
|
||||||
}): Promise<Document> {
|
url: string | Blob,
|
||||||
// Fetch the complete document from the network
|
name: string,
|
||||||
// This could be done at the same time as the document is being processed, but I wanted better metrics
|
document: Document,
|
||||||
let response = await fetch(url);
|
networkFinished: () => void = () => {},
|
||||||
let buffer = await response.arrayBuffer();
|
): Promise<Document> {
|
||||||
networkFinished();
|
// Fetch the complete document from the network
|
||||||
|
// This could be done at the same time as the document is being processed, but I wanted better metrics
|
||||||
|
let response = await fetchOrRead(url);
|
||||||
|
let buffer = await response.arrayBuffer();
|
||||||
|
networkFinished();
|
||||||
|
|
||||||
// Load the new document
|
// Load the new document
|
||||||
let newDoc = null;
|
let newDoc = null;
|
||||||
let alreadyTried: { [name: string]: boolean } = {}
|
let alreadyTried: { [name: string]: boolean } = {};
|
||||||
while (newDoc == null) { // Retry adding extensions as required until the document is loaded
|
while (newDoc == null) {
|
||||||
try { // Try to load fast if no extensions are used
|
// Retry adding extensions as required until the document is loaded
|
||||||
newDoc = await io.readBinary(new Uint8Array(buffer));
|
try {
|
||||||
} catch (e) { // Fallback to wait for download and register big extensions
|
// Try to load fast if no extensions are used
|
||||||
if (!isSmallBuild && e instanceof Error && e.message.toLowerCase().includes("khr_draco_mesh_compression")) {
|
newDoc = await io.readBinary(new Uint8Array(buffer));
|
||||||
if (alreadyTried["draco"]) throw e; else alreadyTried["draco"] = true;
|
} catch (e) {
|
||||||
// WARNING: Draco decompression on web is really slow for non-trivial models! (it should work?)
|
// Fallback to wait for download and register big extensions
|
||||||
let {KHRDracoMeshCompression} = await import("@gltf-transform/extensions")
|
if (!isSmallBuild && e instanceof Error && e.message.toLowerCase().includes("khr_draco_mesh_compression")) {
|
||||||
// @ts-expect-error
|
if (alreadyTried["draco"]) throw e;
|
||||||
let dracoDecoderWeb = await import("three/examples/jsm/libs/draco/draco_decoder.js");
|
else alreadyTried["draco"] = true;
|
||||||
// @ts-expect-error
|
// WARNING: Draco decompression on web is really slow for non-trivial models! (it should work?)
|
||||||
let dracoEncoderWeb = await import("three/examples/jsm/libs/draco/draco_encoder.js");
|
let { KHRDracoMeshCompression } = await import("@gltf-transform/extensions");
|
||||||
io.registerExtensions([KHRDracoMeshCompression])
|
// @ts-expect-error
|
||||||
.registerDependencies({
|
let dracoDecoderWeb = await import("three/examples/jsm/libs/draco/draco_decoder.js");
|
||||||
'draco3d.decoder': await dracoDecoderWeb.default({}),
|
// @ts-expect-error
|
||||||
'draco3d.encoder': await dracoEncoderWeb.default({})
|
let dracoEncoderWeb = await import("three/examples/jsm/libs/draco/draco_encoder.js");
|
||||||
});
|
io.registerExtensions([KHRDracoMeshCompression]).registerDependencies({
|
||||||
} else if (!isSmallBuild && e instanceof Error && e.message.toLowerCase().includes("ext_texture_webp")) {
|
"draco3d.decoder": await dracoDecoderWeb.default({}),
|
||||||
if (alreadyTried["webp"]) throw e; else alreadyTried["webp"] = true;
|
"draco3d.encoder": await dracoEncoderWeb.default({}),
|
||||||
let {EXTTextureWebP} = await import("@gltf-transform/extensions")
|
});
|
||||||
io.registerExtensions([EXTTextureWebP]);
|
} else if (!isSmallBuild && e instanceof Error && e.message.toLowerCase().includes("ext_texture_webp")) {
|
||||||
} else { // TODO: Add more extensions as required
|
if (alreadyTried["webp"]) throw e;
|
||||||
throw e;
|
else alreadyTried["webp"] = true;
|
||||||
}
|
let { EXTTextureWebP } = await import("@gltf-transform/extensions");
|
||||||
}
|
io.registerExtensions([EXTTextureWebP]);
|
||||||
|
} else {
|
||||||
|
// TODO: Add more extensions as required
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Remove any previous model with the same name
|
// Remove any previous model with the same name
|
||||||
await document.transform(dropByName(name));
|
await document.transform(dropByName(name));
|
||||||
|
|
||||||
// Ensure consistent names
|
// Ensure consistent names
|
||||||
// noinspection TypeScriptValidateJSTypes
|
// noinspection TypeScriptValidateJSTypes
|
||||||
await newDoc.transform(setNames(name));
|
await newDoc.transform(setNames(name));
|
||||||
|
|
||||||
// Merge the new document into the current one
|
// Merge the new document into the current one
|
||||||
mergeDocuments(document, newDoc);
|
mergeDocuments(document, newDoc);
|
||||||
return document;
|
return document;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function mergeFinalize(document: Document): Promise<Document> {
|
export async function mergeFinalize(document: Document): Promise<Document> {
|
||||||
// Single scene & buffer required before loading & rendering
|
// Single scene & buffer required before loading & rendering
|
||||||
return await document.transform(mergeScenes(), unpartition());
|
return await document.transform(mergeScenes(), unpartition());
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function toBuffer(doc: Document): Promise<Uint8Array> {
|
export async function toBuffer(doc: Document): Promise<Uint8Array> {
|
||||||
return io.writeBinary(doc);
|
return io.writeBinary(doc);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function removeModel(name: string, document: Document): Promise<Document> {
|
export async function removeModel(name: string, document: Document): Promise<Document> {
|
||||||
return await document.transform(dropByName(name));
|
return await document.transform(dropByName(name));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Given a parsed GLTF document and a name, it forces the names of all elements to be identified by the name (or derivatives) */
|
/** Given a parsed GLTF document and a name, it forces the names of all elements to be identified by the name (or derivatives) */
|
||||||
function setNames(name: string): Transform {
|
function setNames(name: string): Transform {
|
||||||
return (doc: Document) => {
|
return (doc: Document) => {
|
||||||
// Do this automatically for all elements changing any name
|
// Do this automatically for all elements changing any name
|
||||||
for (let elem of doc.getGraph().listEdges().map(e => e.getChild())) {
|
for (let elem of doc
|
||||||
if (!elem.getExtras()) elem.setExtras({});
|
.getGraph()
|
||||||
elem.getExtras()[extrasNameKey] = name;
|
.listEdges()
|
||||||
}
|
.map((e) => e.getChild())) {
|
||||||
return doc;
|
if (!elem.getExtras()) elem.setExtras({});
|
||||||
|
elem.getExtras()[extrasNameKey] = name;
|
||||||
}
|
}
|
||||||
|
return doc;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Ensures that all elements with the given name are removed from the document */
|
/** Ensures that all elements with the given name are removed from the document */
|
||||||
function dropByName(name: string): Transform {
|
function dropByName(name: string): Transform {
|
||||||
return (doc: Document) => {
|
return (doc: Document) => {
|
||||||
for (let elem of doc.getGraph().listEdges().map(e => e.getChild())) {
|
for (let elem of doc
|
||||||
if (elem.getExtras() == null || elem instanceof Scene || elem instanceof Buffer) continue;
|
.getGraph()
|
||||||
if ((elem.getExtras()[extrasNameKey]?.toString() ?? "") == name) {
|
.listEdges()
|
||||||
elem.dispose();
|
.map((e) => e.getChild())) {
|
||||||
}
|
if (elem.getExtras() == null || elem instanceof Scene || elem instanceof Buffer) continue;
|
||||||
}
|
if ((elem.getExtras()[extrasNameKey]?.toString() ?? "") == name) {
|
||||||
return doc;
|
elem.dispose();
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
return doc;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** Merges all scenes in the document into a single default scene */
|
/** Merges all scenes in the document into a single default scene */
|
||||||
function mergeScenes(): Transform {
|
function mergeScenes(): Transform {
|
||||||
return (doc: Document) => {
|
return (doc: Document) => {
|
||||||
let root = doc.getRoot();
|
let root = doc.getRoot();
|
||||||
let scene = root.getDefaultScene() ?? root.listScenes()[0];
|
let scene = root.getDefaultScene() ?? root.listScenes()[0];
|
||||||
for (let dropScene of root.listScenes()) {
|
if (!scene) {
|
||||||
if (dropScene === scene) continue;
|
throw new Error("No scene found in GLTF document");
|
||||||
for (let node of dropScene.listChildren()) {
|
|
||||||
scene.addChild(node);
|
|
||||||
}
|
|
||||||
dropScene.dispose();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
for (let dropScene of root.listScenes()) {
|
||||||
|
if (dropScene === scene) continue;
|
||||||
|
for (let node of dropScene.listChildren()) {
|
||||||
|
scene.addChild(node);
|
||||||
|
}
|
||||||
|
dropScene.dispose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetches a URL or reads it if it is a Blob URL */
|
||||||
|
async function fetchOrRead(url: string | Blob) {
|
||||||
|
if (url instanceof Blob) {
|
||||||
|
// Use the FileReader API as fetch does not support Blob URLs
|
||||||
|
return new Promise<Response>((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onloadend = (event: ProgressEvent<FileReader>) => {
|
||||||
|
if (event.target && event.target.result) {
|
||||||
|
resolve(new Response(event.target.result));
|
||||||
|
} else {
|
||||||
|
reject(new Error("Failed to read Blob URL: " + url));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = (error) => {
|
||||||
|
reject(new Error("Error reading Blob URL: " + url + " - " + error));
|
||||||
|
};
|
||||||
|
// Read the Blob URL as an ArrayBuffer
|
||||||
|
reader.readAsArrayBuffer(new Blob([url]));
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Fetch the URL
|
||||||
|
return retrieveFile(url);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,79 +1,112 @@
|
|||||||
// noinspection JSVoidFunctionReturnValueUsed,JSUnresolvedReference
|
// noinspection JSVoidFunctionReturnValueUsed,JSUnresolvedReference
|
||||||
|
|
||||||
import {Document, type TypedArray} from '@gltf-transform/core'
|
import { Document, type TypedArray } from "@gltf-transform/core";
|
||||||
import {Vector2} from "three/src/math/Vector2.js"
|
import { Vector2 } from "three/src/math/Vector2.js";
|
||||||
import {Vector3} from "three/src/math/Vector3.js"
|
import { Vector3 } from "three/src/math/Vector3.js";
|
||||||
import {Matrix4} from "three/src/math/Matrix4.js"
|
import { Matrix4 } from "three/src/math/Matrix4.js";
|
||||||
|
|
||||||
|
|
||||||
/** Exports the colors used for the axes, primary and secondary. They match the orientation gizmo. */
|
/** Exports the colors used for the axes, primary and secondary. They match the orientation gizmo. */
|
||||||
export const AxesColors = {
|
export const AxesColors = {
|
||||||
x: [[247, 60, 60], [148, 36, 36]],
|
x: [
|
||||||
z: [[108, 203, 38], [65, 122, 23]],
|
[247, 60, 60],
|
||||||
y: [[23, 140, 240], [14, 84, 144]]
|
[148, 36, 36],
|
||||||
}
|
],
|
||||||
|
z: [
|
||||||
|
[108, 203, 38],
|
||||||
|
[65, 122, 23],
|
||||||
|
],
|
||||||
|
y: [
|
||||||
|
[23, 140, 240],
|
||||||
|
[14, 84, 144],
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
function buildSimpleGltf(doc: Document, rawPositions: number[], rawIndices: number[], rawColors: number[] | null, transform: Matrix4, name: string = '__helper', mode: number = WebGL2RenderingContext.LINES) {
|
function buildSimpleGltf(
|
||||||
const buffer = doc.getRoot().listBuffers()[0] ?? doc.createBuffer(name + 'Buffer')
|
doc: Document,
|
||||||
const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0] ?? doc.createScene(name + 'Scene')
|
rawPositions: number[],
|
||||||
const positions = doc.createAccessor(name + 'Position')
|
rawIndices: number[],
|
||||||
.setArray(new Float32Array(rawPositions) as TypedArray)
|
rawColors: number[] | null,
|
||||||
.setType('VEC3')
|
transform: Matrix4,
|
||||||
.setBuffer(buffer)
|
name: string = "__helper",
|
||||||
const indices = doc.createAccessor(name + 'Indices')
|
mode: number = WebGL2RenderingContext.LINES,
|
||||||
.setArray(new Uint32Array(rawIndices) as TypedArray)
|
) {
|
||||||
.setType('SCALAR')
|
const buffer = doc.getRoot().listBuffers()[0] ?? doc.createBuffer(name + "Buffer");
|
||||||
.setBuffer(buffer)
|
const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0] ?? doc.createScene(name + "Scene");
|
||||||
let colors = null;
|
if (!scene) throw new Error("Scene is undefined");
|
||||||
if (rawColors) {
|
if (!rawPositions) throw new Error("rawPositions is undefined");
|
||||||
colors = doc.createAccessor(name + 'Color')
|
const positions = doc
|
||||||
.setArray(new Float32Array(rawColors) as TypedArray)
|
.createAccessor(name + "Position")
|
||||||
.setType('VEC4')
|
.setArray(new Float32Array(rawPositions) as TypedArray)
|
||||||
.setBuffer(buffer);
|
.setType("VEC3")
|
||||||
}
|
.setBuffer(buffer);
|
||||||
const material = doc.createMaterial(name + 'Material')
|
const indices = doc
|
||||||
.setAlphaMode('OPAQUE')
|
.createAccessor(name + "Indices")
|
||||||
const geometry = doc.createPrimitive()
|
.setArray(new Uint32Array(rawIndices) as TypedArray)
|
||||||
.setIndices(indices)
|
.setType("SCALAR")
|
||||||
.setAttribute('POSITION', positions)
|
.setBuffer(buffer);
|
||||||
.setMode(mode as any)
|
let colors = null;
|
||||||
.setMaterial(material)
|
if (rawColors) {
|
||||||
if (rawColors) {
|
colors = doc
|
||||||
geometry.setAttribute('COLOR_0', colors)
|
.createAccessor(name + "Color")
|
||||||
}
|
.setArray(new Float32Array(rawColors) as TypedArray)
|
||||||
if (mode == WebGL2RenderingContext.TRIANGLES) {
|
.setType("VEC4")
|
||||||
geometry.setExtras({face_triangles_end: [rawIndices.length / 6, rawIndices.length * 2 / 6, rawIndices.length * 3 / 6, rawIndices.length * 4 / 6, rawIndices.length * 5 / 6, rawIndices.length]})
|
.setBuffer(buffer);
|
||||||
} else if (mode == WebGL2RenderingContext.LINES) {
|
}
|
||||||
geometry.setExtras({edge_points_end: [rawIndices.length / 3, rawIndices.length * 2 / 3, rawIndices.length]})
|
const material = doc.createMaterial(name + "Material").setAlphaMode("OPAQUE");
|
||||||
}
|
const geometry = doc
|
||||||
const mesh = doc.createMesh(name + 'Mesh').addPrimitive(geometry)
|
.createPrimitive()
|
||||||
const node = doc.createNode(name + 'Node').setMesh(mesh).setMatrix(transform.elements as any)
|
.setIndices(indices)
|
||||||
scene.addChild(node)
|
.setAttribute("POSITION", positions)
|
||||||
|
.setMode(mode as any)
|
||||||
|
.setMaterial(material);
|
||||||
|
if (rawColors) {
|
||||||
|
geometry.setAttribute("COLOR_0", colors);
|
||||||
|
}
|
||||||
|
if (mode == WebGL2RenderingContext.TRIANGLES) {
|
||||||
|
geometry.setExtras({
|
||||||
|
face_triangles_end: [
|
||||||
|
rawIndices.length / 6,
|
||||||
|
(rawIndices.length * 2) / 6,
|
||||||
|
(rawIndices.length * 3) / 6,
|
||||||
|
(rawIndices.length * 4) / 6,
|
||||||
|
(rawIndices.length * 5) / 6,
|
||||||
|
rawIndices.length,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
} else if (mode == WebGL2RenderingContext.LINES) {
|
||||||
|
geometry.setExtras({ edge_points_end: [rawIndices.length / 3, (rawIndices.length * 2) / 3, rawIndices.length] });
|
||||||
|
}
|
||||||
|
const mesh = doc.createMesh(name + "Mesh").addPrimitive(geometry);
|
||||||
|
const node = doc
|
||||||
|
.createNode(name + "Node")
|
||||||
|
.setMesh(mesh)
|
||||||
|
.setMatrix(transform.elements as any);
|
||||||
|
scene.addChild(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new Axes helper as a GLTF model, useful for debugging positions and orientations.
|
* Create a new Axes helper as a GLTF model, useful for debugging positions and orientations.
|
||||||
*/
|
*/
|
||||||
export function newAxes(doc: Document, size: Vector3, transform: Matrix4) {
|
export function newAxes(doc: Document, size: Vector3, transform: Matrix4) {
|
||||||
let rawIndices = [0, 1, 2, 3, 4, 5];
|
let rawIndices = [0, 1, 2, 3, 4, 5];
|
||||||
let rawPositions = [
|
let rawPositions = [0, 0, 0, size.x, 0, 0, 0, 0, 0, 0, size.y, 0, 0, 0, 0, 0, 0, -size.z];
|
||||||
0, 0, 0, size.x, 0, 0,
|
let rawColors = [
|
||||||
0, 0, 0, 0, size.y, 0,
|
...(AxesColors.x[0] ?? [255, 0, 0]),
|
||||||
0, 0, 0, 0, 0, -size.z,
|
255,
|
||||||
];
|
...(AxesColors.x[1] ?? [255, 0, 0]),
|
||||||
let rawColors = [
|
255,
|
||||||
...(AxesColors.x[0]), 255, ...(AxesColors.x[1]), 255,
|
...(AxesColors.y[0] ?? [0, 255, 0]),
|
||||||
...(AxesColors.y[0]), 255, ...(AxesColors.y[1]), 255,
|
255,
|
||||||
...(AxesColors.z[0]), 255, ...(AxesColors.z[1]), 255
|
...(AxesColors.y[1] ?? [0, 255, 0]),
|
||||||
].map(x => x / 255.0);
|
255,
|
||||||
// Axes at (0, 0, 0)
|
...(AxesColors.z[0] ?? [0, 0, 255]),
|
||||||
buildSimpleGltf(doc, rawPositions, rawIndices, rawColors, new Matrix4(), '__helper_axes');
|
255,
|
||||||
buildSimpleGltf(doc, [0, 0, 0], [0], [1, 1, 1, 1], new Matrix4(), '__helper_axes', WebGL2RenderingContext.POINTS);
|
...(AxesColors.z[1] ?? [0, 0, 255]),
|
||||||
// Axes at center
|
255,
|
||||||
if (new Matrix4() != transform) {
|
].map((x) => x / 255.0);
|
||||||
buildSimpleGltf(doc, rawPositions, rawIndices, rawColors, transform, '__helper_axes_center');
|
// Axes at (0, 0, 0)
|
||||||
buildSimpleGltf(doc, [0, 0, 0], [0], [1, 1, 1, 1], transform, '__helper_axes_center', WebGL2RenderingContext.POINTS);
|
buildSimpleGltf(doc, rawPositions, rawIndices, rawColors, new Matrix4(), "__helper_axes");
|
||||||
}
|
buildSimpleGltf(doc, [0, 0, 0], [0], [1, 1, 1, 1], new Matrix4(), "__helper_axes", WebGL2RenderingContext.POINTS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -83,61 +116,61 @@ export function newAxes(doc: Document, size: Vector3, transform: Matrix4) {
|
|||||||
* This ensures that only the back of the grid is always visible, regardless of the camera position.
|
* This ensures that only the back of the grid is always visible, regardless of the camera position.
|
||||||
*/
|
*/
|
||||||
export function newGridBox(doc: Document, size: Vector3, baseTransform: Matrix4, divisions = 10) {
|
export function newGridBox(doc: Document, size: Vector3, baseTransform: Matrix4, divisions = 10) {
|
||||||
// Create transformed positions for the inner faces of the box
|
// Create transformed positions for the inner faces of the box
|
||||||
let allPositions: number[] = [];
|
let allPositions: number[] = [];
|
||||||
let allIndices: number[] = [];
|
let allIndices: number[] = [];
|
||||||
for (let axis of [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, -1)]) {
|
for (let axis of [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, -1)]) {
|
||||||
for (let positive of [1, -1]) {
|
for (let positive of [1, -1]) {
|
||||||
let offset = axis.clone().multiply(size.clone().multiplyScalar(0.5 * positive));
|
let offset = axis.clone().multiply(size.clone().multiplyScalar(0.5 * positive));
|
||||||
let translation = new Matrix4().makeTranslation(offset.x, offset.y, offset.z)
|
let translation = new Matrix4().makeTranslation(offset.x, offset.y, offset.z);
|
||||||
let rotation = new Matrix4().lookAt(new Vector3(), offset, new Vector3(0, 1, 0))
|
let rotation = new Matrix4().lookAt(new Vector3(), offset, new Vector3(0, 1, 0));
|
||||||
let size2 = new Vector2();
|
let size2 = new Vector2();
|
||||||
if (axis.x) size2.set(size.z, size.y);
|
if (axis.x) size2.set(size.z, size.y);
|
||||||
if (axis.y) size2.set(size.x, size.z);
|
if (axis.y) size2.set(size.x, size.z);
|
||||||
if (axis.z) size2.set(size.x, size.y);
|
if (axis.z) size2.set(size.x, size.y);
|
||||||
let transform = new Matrix4().multiply(translation).multiply(rotation);
|
let transform = new Matrix4().multiply(translation).multiply(rotation);
|
||||||
let [rawPositions, rawIndices] = newGridPlane(size2, divisions);
|
let [rawPositions, rawIndices] = newGridPlane(size2, divisions);
|
||||||
let baseIndex = allPositions.length / 3;
|
let baseIndex = allPositions.length / 3;
|
||||||
for (let i of rawIndices) {
|
for (let i of rawIndices) {
|
||||||
allIndices.push(i + baseIndex);
|
allIndices.push(i + baseIndex);
|
||||||
}
|
}
|
||||||
// Apply transform to the positions before adding them to the list
|
// Apply transform to the positions before adding them to the list
|
||||||
for (let i = 0; i < rawPositions.length; i += 3) {
|
for (let i = 0; i < rawPositions.length; i += 3) {
|
||||||
let pos = new Vector3(rawPositions[i], rawPositions[i + 1], rawPositions[i + 2]);
|
let pos = new Vector3(rawPositions[i], rawPositions[i + 1], rawPositions[i + 2]);
|
||||||
pos.applyMatrix4(transform);
|
pos.applyMatrix4(transform);
|
||||||
allPositions.push(pos.x, pos.y, pos.z);
|
allPositions.push(pos.x, pos.y, pos.z);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let colors = new Array(allPositions.length / 3 * 4).fill(1);
|
}
|
||||||
buildSimpleGltf(doc, allPositions, allIndices, colors, baseTransform, '__helper_grid', WebGL2RenderingContext.TRIANGLES);
|
let colors = new Array((allPositions.length / 3) * 4).fill(1);
|
||||||
|
buildSimpleGltf(doc, allPositions, allIndices, colors, baseTransform, "__helper_grid", WebGL2RenderingContext.TRIANGLES);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function newGridPlane(size: Vector2, divisions = 10, divisionWidth = 0.002): [number[], number[]] {
|
export function newGridPlane(size: Vector2, divisions = 10, divisionWidth = 0.002): [number[], number[]] {
|
||||||
const rawPositions = [];
|
const rawPositions = [];
|
||||||
const rawIndices = [];
|
const rawIndices = [];
|
||||||
// Build the grid as triangles
|
// Build the grid as triangles
|
||||||
for (let i = 0; i <= divisions; i++) {
|
for (let i = 0; i <= divisions; i++) {
|
||||||
const x = -size.x / 2 + size.x * i / divisions;
|
const x = -size.x / 2 + (size.x * i) / divisions;
|
||||||
const y = -size.y / 2 + size.y * i / divisions;
|
const y = -size.y / 2 + (size.y * i) / divisions;
|
||||||
|
|
||||||
// Vertical quad (two triangles)
|
// Vertical quad (two triangles)
|
||||||
rawPositions.push(x - divisionWidth * size.x / 2, -size.y / 2, 0);
|
rawPositions.push(x - (divisionWidth * size.x) / 2, -size.y / 2, 0);
|
||||||
rawPositions.push(x + divisionWidth * size.x / 2, -size.y / 2, 0);
|
rawPositions.push(x + (divisionWidth * size.x) / 2, -size.y / 2, 0);
|
||||||
rawPositions.push(x + divisionWidth * size.x / 2, size.y / 2, 0);
|
rawPositions.push(x + (divisionWidth * size.x) / 2, size.y / 2, 0);
|
||||||
rawPositions.push(x - divisionWidth * size.x / 2, size.y / 2, 0);
|
rawPositions.push(x - (divisionWidth * size.x) / 2, size.y / 2, 0);
|
||||||
const baseIndex = i * 4;
|
const baseIndex = i * 4;
|
||||||
rawIndices.push(baseIndex, baseIndex + 1, baseIndex + 2);
|
rawIndices.push(baseIndex, baseIndex + 1, baseIndex + 2);
|
||||||
rawIndices.push(baseIndex, baseIndex + 2, baseIndex + 3);
|
rawIndices.push(baseIndex, baseIndex + 2, baseIndex + 3);
|
||||||
|
|
||||||
// Horizontal quad (two triangles)
|
// Horizontal quad (two triangles)
|
||||||
rawPositions.push(-size.x / 2, y - divisionWidth * size.y / 2, 0);
|
rawPositions.push(-size.x / 2, y - (divisionWidth * size.y) / 2, 0);
|
||||||
rawPositions.push(size.x / 2, y - divisionWidth * size.y / 2, 0);
|
rawPositions.push(size.x / 2, y - (divisionWidth * size.y) / 2, 0);
|
||||||
rawPositions.push(size.x / 2, y + divisionWidth * size.y / 2, 0);
|
rawPositions.push(size.x / 2, y + (divisionWidth * size.y) / 2, 0);
|
||||||
rawPositions.push(-size.x / 2, y + divisionWidth * size.y / 2, 0);
|
rawPositions.push(-size.x / 2, y + (divisionWidth * size.y) / 2, 0);
|
||||||
const baseIndex2 = (divisions + 1 + i) * 4;
|
const baseIndex2 = (divisions + 1 + i) * 4;
|
||||||
rawIndices.push(baseIndex2, baseIndex2 + 1, baseIndex2 + 2);
|
rawIndices.push(baseIndex2, baseIndex2 + 1, baseIndex2 + 2);
|
||||||
rawIndices.push(baseIndex2, baseIndex2 + 2, baseIndex2 + 3);
|
rawIndices.push(baseIndex2, baseIndex2 + 2, baseIndex2 + 3);
|
||||||
}
|
}
|
||||||
return [rawPositions, rawIndices];
|
return [rawPositions, rawIndices];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ const batchTimeout = 250; // ms
|
|||||||
|
|
||||||
export class NetworkUpdateEventModel {
|
export class NetworkUpdateEventModel {
|
||||||
name: string;
|
name: string;
|
||||||
url: string;
|
url: string | Blob;
|
||||||
// TODO: Detect and manage instances of the same object (same hash, different name)
|
// TODO: Detect and manage instances of the same object (same hash, different name)
|
||||||
hash: string | null;
|
hash: string | null;
|
||||||
isRemove: boolean | null; // This is null for a shutdown event
|
isRemove: boolean | null; // This is null for a shutdown event
|
||||||
|
|
||||||
constructor(name: string, url: string, hash: string | null, isRemove: boolean | null) {
|
constructor(name: string, url: string | Blob, hash: string | null, isRemove: boolean | null) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.url = url;
|
this.url = url;
|
||||||
this.hash = hash;
|
this.hash = hash;
|
||||||
@@ -42,18 +42,37 @@ export class NetworkManager extends EventTarget {
|
|||||||
*
|
*
|
||||||
* Updates will be emitted as "update" events, including the download URL and the model name.
|
* Updates will be emitted as "update" events, including the download URL and the model name.
|
||||||
*/
|
*/
|
||||||
async load(url: string) {
|
async load(url: string | Blob) {
|
||||||
if (url.startsWith("dev+") || url.startsWith("dev ")) {
|
if (!(url instanceof Blob) && (url.startsWith("dev+") || url.startsWith("dev "))) {
|
||||||
let baseUrl = new URL(url.slice(4));
|
let baseUrl = new URL(url.slice(4));
|
||||||
baseUrl.searchParams.set("api_updates", "true");
|
baseUrl.searchParams.set("api_updates", "true");
|
||||||
await this.monitorDevServer(baseUrl);
|
await this.monitorDevServer(baseUrl);
|
||||||
} else {
|
} else {
|
||||||
// Get the last part of the URL as the "name" of the model
|
let name;
|
||||||
let name = url.split("/").pop();
|
let hash = null;
|
||||||
name = name?.split(".")[0] || `unknown-${Math.random()}`;
|
if (url instanceof Blob) {
|
||||||
// Use a head request to get the hash of the file
|
if (url instanceof File) name = (url as File).name
|
||||||
let response = await fetch(url, {method: "HEAD"});
|
else name = `blob-${Math.random()}`;
|
||||||
let hash = response.headers.get("etag");
|
name = name.replace('.glb', '').replace('.gltf', '');
|
||||||
|
} else {
|
||||||
|
// If there is a #name parameter in the URL, use it as the name
|
||||||
|
let hashParams: URLSearchParams
|
||||||
|
try {
|
||||||
|
let urlObj = new URL(url, window.location.href);
|
||||||
|
hashParams = new URLSearchParams(urlObj.hash.slice(1));
|
||||||
|
} catch (e) {
|
||||||
|
hashParams = new URLSearchParams();
|
||||||
|
}
|
||||||
|
if (hashParams.has("name")) {
|
||||||
|
name = hashParams.get("name") || `unknown-${Math.random()}`;
|
||||||
|
} else { // Default to the last part of the URL as the "name" of the model
|
||||||
|
name = url.split("/").pop();
|
||||||
|
}
|
||||||
|
name = name?.split(".")[0] || `unknown-${Math.random()}`;
|
||||||
|
// Use a head request to get the hash of the file
|
||||||
|
let response = await fetch(url, {method: "HEAD"});
|
||||||
|
hash = response.headers.get("etag");
|
||||||
|
}
|
||||||
// Only trigger an update if the hash has changed
|
// Only trigger an update if the hash has changed
|
||||||
this.foundModel(name, hash, url, false);
|
this.foundModel(name, hash, url, false);
|
||||||
}
|
}
|
||||||
@@ -61,7 +80,7 @@ export class NetworkManager extends EventTarget {
|
|||||||
|
|
||||||
private async monitorDevServer(url: URL, stop: () => boolean = () => false) {
|
private async monitorDevServer(url: URL, stop: () => boolean = () => false) {
|
||||||
while (!stop()) {
|
while (!stop()) {
|
||||||
let monitorEveryMs = (await settings()).monitorEveryMs;
|
let monitorEveryMs = (await settings).monitorEveryMs;
|
||||||
try {
|
try {
|
||||||
// WARNING: This will spam the console logs with failed requests when the server is down
|
// WARNING: This will spam the console logs with failed requests when the server is down
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
@@ -92,7 +111,7 @@ export class NetworkManager extends EventTarget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private foundModel(name: string, hash: string | null, url: string, isRemove: boolean | null, disconnect: () => void = () => {
|
private foundModel(name: string, hash: string | null, url: string | Blob, isRemove: boolean | null, disconnect: () => void = () => {
|
||||||
}) {
|
}) {
|
||||||
// console.debug("Found model", name, "with hash", hash, "at", url, "isRemove", isRemove);
|
// console.debug("Found model", name, "with hash", hash, "at", url, "isRemove", isRemove);
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {Matrix4} from "three/src/math/Matrix4.js"
|
|||||||
/** This class helps manage SceneManagerData. All methods are static to support reactivity... */
|
/** This class helps manage SceneManagerData. All methods are static to support reactivity... */
|
||||||
export class SceneMgr {
|
export class SceneMgr {
|
||||||
/** Loads a GLB model from a URL and adds it to the viewer or replaces it if the names match */
|
/** Loads a GLB model from a URL and adds it to the viewer or replaces it if the names match */
|
||||||
static async loadModel(sceneUrl: Ref<string>, document: Document, name: string, url: string, updateHelpers: boolean = true, reloadScene: boolean = true): Promise<Document> {
|
static async loadModel(sceneUrl: Ref<string>, document: Document, name: string, url: string | Blob, updateHelpers: boolean = true, reloadScene: boolean = true): Promise<Document> {
|
||||||
let loadStart = performance.now();
|
let loadStart = performance.now();
|
||||||
let loadNetworkEnd: number;
|
let loadNetworkEnd: number;
|
||||||
|
|
||||||
@@ -99,8 +99,10 @@ export class SceneMgr {
|
|||||||
let transform = (new Matrix4()).makeTranslation(bb.getCenter(new Vector3()));
|
let transform = (new Matrix4()).makeTranslation(bb.getCenter(new Vector3()));
|
||||||
newAxes(helpersDoc, bb.getSize(new Vector3()).multiplyScalar(0.5), transform);
|
newAxes(helpersDoc, bb.getSize(new Vector3()).multiplyScalar(0.5), transform);
|
||||||
newGridBox(helpersDoc, bb.getSize(new Vector3()), transform);
|
newGridBox(helpersDoc, bb.getSize(new Vector3()), transform);
|
||||||
let helpersUrl = URL.createObjectURL(new Blob([await toBuffer(helpersDoc)]));
|
let helpersUrl = URL.createObjectURL(new Blob([await toBuffer(helpersDoc) as ArrayBufferView<ArrayBuffer>]));
|
||||||
return await SceneMgr.loadModel(sceneUrl, document, extrasNameValueHelpers, helpersUrl, false, reloadScene);
|
let newDocument = await SceneMgr.loadModel(sceneUrl, document, extrasNameValueHelpers, helpersUrl, false, reloadScene);
|
||||||
|
URL.revokeObjectURL(helpersUrl);
|
||||||
|
return newDocument;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Serializes the current document into a GLB and updates the viewerSrc */
|
/** Serializes the current document into a GLB and updates the viewerSrc */
|
||||||
@@ -110,8 +112,9 @@ export class SceneMgr {
|
|||||||
|
|
||||||
// Serialize the document into a GLB and update the viewerSrc
|
// Serialize the document into a GLB and update the viewerSrc
|
||||||
let buffer = await toBuffer(document);
|
let buffer = await toBuffer(document);
|
||||||
let blob = new Blob([buffer], {type: 'model/gltf-binary'});
|
let blob = new Blob([buffer as ArrayBufferView<ArrayBuffer>], {type: 'model/gltf-binary'});
|
||||||
console.debug("Showing current doc", document, "with", buffer.length, "total bytes");
|
console.debug("Showing current doc", document, "with", buffer.length, "total bytes");
|
||||||
|
if (sceneUrl.value.startsWith("blob:")) URL.revokeObjectURL(sceneUrl.value);
|
||||||
sceneUrl.value = URL.createObjectURL(blob);
|
sceneUrl.value = URL.createObjectURL(blob);
|
||||||
|
|
||||||
return document;
|
return document;
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
// These are the default values for the settings, which are overridden below
|
// These are the default values for the settings, which are overridden below
|
||||||
import {ungzip} from "pako";
|
import {ungzip} from "pako";
|
||||||
import {b66Decode} from "../tools/b66.ts";
|
import {b64UrlDecode} from "../tools/b64.ts";
|
||||||
|
import {retrieveFile} from "../tools/upload-file.ts";
|
||||||
|
|
||||||
let settingsCache: any = null;
|
const firstTimeNames: Array<string> = []; // Needed for array values, which clear the array when overridden
|
||||||
|
export const settings = (async () => {
|
||||||
export async function settings() {
|
|
||||||
if (settingsCache !== null) return settingsCache;
|
|
||||||
let settings = {
|
let settings = {
|
||||||
preload: [
|
preload: [
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -15,7 +14,7 @@ export async function settings() {
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
// new URL('../../assets/logo_build/location.glb', import.meta.url).href,
|
// new URL('../../assets/logo_build/location.glb', import.meta.url).href,
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
// new URL('../../assets/logo_build/img.jpg.glb', import.meta.url).href,
|
// new URL('../../assets/logo_build/img.glb', import.meta.url).href,
|
||||||
// Websocket URLs automatically listen for new models from the python backend
|
// Websocket URLs automatically listen for new models from the python backend
|
||||||
'<auto>', // Get the default preload URL if not overridden
|
'<auto>', // Get the default preload URL if not overridden
|
||||||
],
|
],
|
||||||
@@ -44,7 +43,6 @@ export async function settings() {
|
|||||||
|
|
||||||
// Playground settings
|
// Playground settings
|
||||||
pg_code: "", // Automatically loaded and executed code for the playground
|
pg_code: "", // Automatically loaded and executed code for the playground
|
||||||
pg_code_url: "", // URL to load the code from (overrides pg_code)
|
|
||||||
pg_opacity_loading: -1, // Opacity of the code during first load and run (< 0 is 0.0 if preload and 0.9 if not)
|
pg_opacity_loading: -1, // Opacity of the code during first load and run (< 0 is 0.0 if preload and 0.9 if not)
|
||||||
pg_opacity_loaded: 0.9, // Opacity of the code after it has been run for the first time
|
pg_opacity_loaded: 0.9, // Opacity of the code after it has been run for the first time
|
||||||
};
|
};
|
||||||
@@ -62,24 +60,15 @@ export async function settings() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Grab the code from the URL if it is set
|
|
||||||
if (settings.pg_code_url.length > 0) {
|
|
||||||
// If the code URL is set, override the code
|
|
||||||
try {
|
|
||||||
const response = await fetch(settings.pg_code_url);
|
|
||||||
if (response.ok) {
|
|
||||||
settings.pg_code = await response.text();
|
|
||||||
} else {
|
|
||||||
console.warn("Failed to load code from URL:", settings.pg_code_url);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error fetching code from URL:", settings.pg_code_url, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the default preload URL if not overridden (requires a fetch that is avoided if possible)
|
// Get the default preload URL if not overridden (requires a fetch that is avoided if possible)
|
||||||
for (let i = 0; i < settings.preload.length; i++) {
|
for (let i = 0; i < settings.preload.length; i++) {
|
||||||
let url = settings.preload[i];
|
let url = settings.preload[i];
|
||||||
|
// Ignore empty preload URLs to allow overriding default auto behavior
|
||||||
|
if (url === '') {
|
||||||
|
settings.preload = settings.preload.slice(0, i).concat(settings.preload.slice(i + 1));
|
||||||
|
continue; // Skip this preload URL
|
||||||
|
}
|
||||||
|
// Handle special <auto> preload URL
|
||||||
if (url === '<auto>') {
|
if (url === '<auto>') {
|
||||||
if (settings.pg_code != "") { // <auto> means no preload URL if code is set
|
if (settings.pg_code != "") { // <auto> means no preload URL if code is set
|
||||||
settings.preload = settings.preload.slice(0, i).concat(settings.preload.slice(i + 1));
|
settings.preload = settings.preload.slice(0, i).concat(settings.preload.slice(i + 1));
|
||||||
@@ -96,27 +85,30 @@ export async function settings() {
|
|||||||
url = "dev+http://localhost:32323";
|
url = "dev+http://localhost:32323";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
settings.preload[i] = url;
|
settings.preload[i] = url ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-decompress the code and other playground settings
|
// Auto-decompress the code and other playground settings
|
||||||
if (settings.pg_code.length > 0) {
|
if (settings.pg_code.length > 0) {
|
||||||
|
// pg_code has a few possible formats: URL, base64url+gzipped, or raw code (try them in that order)
|
||||||
try {
|
try {
|
||||||
settings.pg_code = ungzip(b66Decode(settings.pg_code), {to: 'string'});
|
new URL(settings.pg_code); // Check if it's a valid absolute URL
|
||||||
} catch (error) {
|
settings.pg_code = await (await retrieveFile(settings.pg_code)).text();
|
||||||
console.warn("Failed to decompress code (assuming raw code):", error);
|
} catch (error1) { // Not a valid URL, try base64url+gzipped
|
||||||
|
try {
|
||||||
|
settings.pg_code = ungzip(b64UrlDecode(settings.pg_code), {to: 'string'});
|
||||||
|
} catch (error2) { // Not base64url+gzipped, assume it's raw code
|
||||||
|
console.log("pg_code is not a URL (", error1, ") or base64url+gzipped (", error2, "), using it as raw code:", settings.pg_code);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (settings.pg_opacity_loading < 0) {
|
if (settings.pg_opacity_loading < 0) {
|
||||||
// If the opacity is not set, use 0.0 if preload is set, otherwise 0.9
|
// If the opacity is not set, use 0.0 if preload is set, otherwise 0.9
|
||||||
settings.pg_opacity_loading = settings.preload.length > 0 ? 0.0 : 0.9;
|
settings.pg_opacity_loading = settings.preload.length > 0 ? 0.0 : 0.9;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
settingsCache = settings;
|
|
||||||
return settings;
|
return settings;
|
||||||
}
|
})()
|
||||||
|
|
||||||
const firstTimeNames: Array<string> = []; // Needed for array values, which clear the array when overridden
|
|
||||||
function parseSetting(name: string, value: string, settings: any): any {
|
function parseSetting(name: string, value: string, settings: any): any {
|
||||||
let arrayElem = name.endsWith(".0")
|
let arrayElem = name.endsWith(".0")
|
||||||
if (arrayElem) name = name.slice(0, -2);
|
if (arrayElem) name = name.slice(0, -2);
|
||||||
|
|||||||
@@ -13,9 +13,10 @@ import {
|
|||||||
} from "vuetify/lib/components/index.mjs";
|
} from "vuetify/lib/components/index.mjs";
|
||||||
import {extrasNameKey, extrasNameValueHelpers} from "../misc/gltf";
|
import {extrasNameKey, extrasNameValueHelpers} from "../misc/gltf";
|
||||||
import {Mesh} from "@gltf-transform/core";
|
import {Mesh} from "@gltf-transform/core";
|
||||||
import {ref, watch} from "vue";
|
import {nextTick, ref, watch} from "vue";
|
||||||
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
|
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
|
||||||
import {
|
import {
|
||||||
|
mdiArrowExpand,
|
||||||
mdiCircleOpacity,
|
mdiCircleOpacity,
|
||||||
mdiCube,
|
mdiCube,
|
||||||
mdiDelete,
|
mdiDelete,
|
||||||
@@ -44,7 +45,7 @@ const props = defineProps<{
|
|||||||
}>();
|
}>();
|
||||||
const emit = defineEmits<{ remove: [] }>()
|
const emit = defineEmits<{ remove: [] }>()
|
||||||
|
|
||||||
let modelName = props.meshes[0].getExtras()[extrasNameKey] // + " blah blah blah blah blag blah blah blah"
|
let modelName = props.meshes[0]?.getExtras()?.[extrasNameKey] // + " blah blah blah blah blag blah blah blah"
|
||||||
|
|
||||||
// Count the number of faces, edges and vertices
|
// Count the number of faces, edges and vertices
|
||||||
let faceCount = ref(-1);
|
let faceCount = ref(-1);
|
||||||
@@ -58,9 +59,14 @@ const clipPlaneY = ref(1);
|
|||||||
const clipPlaneSwappedY = ref(false);
|
const clipPlaneSwappedY = ref(false);
|
||||||
const clipPlaneZ = ref(1);
|
const clipPlaneZ = ref(1);
|
||||||
const clipPlaneSwappedZ = ref(false);
|
const clipPlaneSwappedZ = ref(false);
|
||||||
|
|
||||||
const edgeWidth = ref(0);
|
const edgeWidth = ref(0);
|
||||||
|
const explodeStrength = ref(0);
|
||||||
|
const explodeSwapped = ref(false);
|
||||||
|
|
||||||
|
// Load the settings for the default edge width
|
||||||
(async () => {
|
(async () => {
|
||||||
let s = await settings();
|
let s = await settings;
|
||||||
edgeWidth.value = s.edgeWidth;
|
edgeWidth.value = s.edgeWidth;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -163,9 +169,9 @@ function onClipPlanesChange() {
|
|||||||
new Plane(new Vector3(0, -1, 0), offsetY).applyMatrix4(rotSceneMatrix),
|
new Plane(new Vector3(0, -1, 0), offsetY).applyMatrix4(rotSceneMatrix),
|
||||||
new Plane(new Vector3(0, 0, 1), -offsetZ).applyMatrix4(rotSceneMatrix),
|
new Plane(new Vector3(0, 0, 1), -offsetZ).applyMatrix4(rotSceneMatrix),
|
||||||
];
|
];
|
||||||
if (clipPlaneSwappedX.value) planes[0].negate();
|
if (clipPlaneSwappedX.value) planes[0]?.negate();
|
||||||
if (clipPlaneSwappedY.value) planes[1].negate();
|
if (clipPlaneSwappedY.value) planes[1]?.negate();
|
||||||
if (clipPlaneSwappedZ.value) planes[2].negate();
|
if (clipPlaneSwappedZ.value) planes[2]?.negate();
|
||||||
if (!enabledZ) planes.pop();
|
if (!enabledZ) planes.pop();
|
||||||
if (!enabledY) planes.splice(1, 1);
|
if (!enabledY) planes.splice(1, 1);
|
||||||
if (!enabledX) planes.shift();
|
if (!enabledX) planes.shift();
|
||||||
@@ -246,6 +252,76 @@ function onEdgeWidthChange(newEdgeWidth: number) {
|
|||||||
|
|
||||||
watch(edgeWidth, onEdgeWidthChange);
|
watch(edgeWidth, onEdgeWidthChange);
|
||||||
|
|
||||||
|
// Explode the model
|
||||||
|
function onExplodeChange(newExplodeStrength: number) {
|
||||||
|
let scene = props.viewer?.scene;
|
||||||
|
let sceneModel = (scene as any)?._model;
|
||||||
|
if (!scene || !sceneModel) return;
|
||||||
|
|
||||||
|
// Get direction and size of the explosion in a first pass
|
||||||
|
const meBbox = new Box3();
|
||||||
|
const othersBbox = new Box3();
|
||||||
|
sceneModel.traverse((child: MObject3D) => {
|
||||||
|
if (child == sceneModel) return; // Skip the scene itself
|
||||||
|
const isMe = child.userData[extrasNameKey] === modelName;
|
||||||
|
if ((child.type === 'Mesh' || child.type === 'SkinnedMesh' ||
|
||||||
|
child.type === 'Line' || child.type === 'LineSegments' ||
|
||||||
|
child.type === 'Points') && !child.userData.noHit) {
|
||||||
|
if (isMe) {
|
||||||
|
meBbox.expandByObject(child);
|
||||||
|
} else if (!isMe && child.userData[extrasNameKey]) {
|
||||||
|
othersBbox.expandByObject(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const modelSize = new Vector3();
|
||||||
|
meBbox.getSize(modelSize);
|
||||||
|
const maxDimension = Math.max(modelSize.x, modelSize.y, modelSize.z);
|
||||||
|
const pushDirection = new Vector3().subVectors(meBbox.getCenter(new Vector3()), othersBbox.getCenter(new Vector3())).normalize();
|
||||||
|
|
||||||
|
|
||||||
|
// Use absolute value for strength calculation
|
||||||
|
let strength = Math.abs(newExplodeStrength);
|
||||||
|
if (explodeSwapped.value) strength = -strength;
|
||||||
|
|
||||||
|
// Apply explosion
|
||||||
|
sceneModel.traverse((child: MObject3D) => {
|
||||||
|
if (child.userData[extrasNameKey] === modelName) {
|
||||||
|
if ((child.type === 'Mesh' || child.type === 'SkinnedMesh' ||
|
||||||
|
child.type === 'Line' || child.type === 'LineSegments' ||
|
||||||
|
child.type === 'Points')) {
|
||||||
|
|
||||||
|
// Handle zero vector case (if object is at origin)
|
||||||
|
const direction = pushDirection.clone();
|
||||||
|
if (direction.lengthSq() < 0.0001) {
|
||||||
|
direction.set(0, 1, 0);
|
||||||
|
console.warn("Explode direction was zero, using (0, 1, 0) instead");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate new position based on model size
|
||||||
|
const factor = strength * maxDimension;
|
||||||
|
const newPosition = new Vector3().add(direction.multiplyScalar(factor));
|
||||||
|
|
||||||
|
// Apply new position
|
||||||
|
child.position.copy(newPosition);
|
||||||
|
|
||||||
|
// Update related objects (back is automatically updated)
|
||||||
|
if (child.userData.niceLine) {
|
||||||
|
child.userData.niceLine.position.copy(newPosition);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
scene.queueRender();
|
||||||
|
onClipPlanesChange();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add watchers for explode variables
|
||||||
|
watch(explodeStrength, (newVal) => onExplodeChange(newVal));
|
||||||
|
watch(explodeSwapped, () => onExplodeChange(explodeStrength.value));
|
||||||
|
|
||||||
|
|
||||||
function onModelLoad() {
|
function onModelLoad() {
|
||||||
let scene = props.viewer?.scene;
|
let scene = props.viewer?.scene;
|
||||||
let sceneModel = (scene as any)?._model;
|
let sceneModel = (scene as any)?._model;
|
||||||
@@ -312,15 +388,17 @@ function onModelLoad() {
|
|||||||
|
|
||||||
// Furthermore...
|
// Furthermore...
|
||||||
// Enabled features may have been reset after a reload
|
// Enabled features may have been reset after a reload
|
||||||
onEnabledFeaturesChange(enabledFeatures.value)
|
onEnabledFeaturesChange(enabledFeatures.value);
|
||||||
// Opacity may have been reset after a reload
|
// Opacity may have been reset after a reload
|
||||||
onOpacityChange(opacity.value)
|
onOpacityChange(opacity.value);
|
||||||
// Wireframe may have been reset after a reload
|
// Wireframe may have been reset after a reload
|
||||||
onWireframeChange(wireframe.value)
|
onWireframeChange(wireframe.value);
|
||||||
// Clip planes may have been reset after a reload
|
// Clip planes may have been reset after a reload
|
||||||
onClipPlanesChange()
|
onClipPlanesChange();
|
||||||
// Edge width may have been reset after a reload
|
// Edge width may have been reset after a reload
|
||||||
onEdgeWidthChange(edgeWidth.value)
|
onEdgeWidthChange(edgeWidth.value);
|
||||||
|
// Explode may have been reset after a reload
|
||||||
|
if (explodeStrength.value > 0) nextTick(() => onExplodeChange(explodeStrength.value));
|
||||||
|
|
||||||
scene.queueRender()
|
scene.queueRender()
|
||||||
}
|
}
|
||||||
@@ -370,6 +448,21 @@ if (props.viewer) onViewerReady(props.viewer); else watch((() => props.viewer) a
|
|||||||
<v-checkbox-btn v-model="wireframe" falseIcon="mdi-triangle" trueIcon="mdi-triangle-outline"></v-checkbox-btn>
|
<v-checkbox-btn v-model="wireframe" falseIcon="mdi-triangle" trueIcon="mdi-triangle-outline"></v-checkbox-btn>
|
||||||
</template>
|
</template>
|
||||||
</v-slider>
|
</v-slider>
|
||||||
|
<v-slider v-model="explodeStrength" hide-details max="1" min="0">
|
||||||
|
<template v-slot:prepend>
|
||||||
|
<v-tooltip activator="parent">Explode model</v-tooltip>
|
||||||
|
<svg-icon :path="mdiArrowExpand" type="mdi"></svg-icon>
|
||||||
|
</template>
|
||||||
|
<template v-slot:append>
|
||||||
|
<v-tooltip activator="parent">Swap explode direction (may go crazy)</v-tooltip>
|
||||||
|
<v-checkbox-btn v-model="explodeSwapped" falseIcon="mdi-checkbox-blank-outline"
|
||||||
|
trueIcon="mdi-checkbox-marked-outline">
|
||||||
|
<template v-slot:label>
|
||||||
|
<svg-icon :path="mdiSwapHorizontal" type="mdi"></svg-icon>
|
||||||
|
</template>
|
||||||
|
</v-checkbox-btn>
|
||||||
|
</template>
|
||||||
|
</v-slider>
|
||||||
<v-slider v-if="edgeCount > 0 || vertexCount > 0" v-model="edgeWidth" hide-details max="1" min="0">
|
<v-slider v-if="edgeCount > 0 || vertexCount > 0" v-model="edgeWidth" hide-details max="1" min="0">
|
||||||
<template v-slot:prepend>
|
<template v-slot:prepend>
|
||||||
<v-tooltip activator="parent">Edge and vertex sizes</v-tooltip>
|
<v-tooltip activator="parent">Edge and vertex sizes</v-tooltip>
|
||||||
@@ -482,4 +575,4 @@ if (props.viewer) onViewerReady(props.viewer); else watch((() => props.viewer) a
|
|||||||
.mdi-triangle-outline { /* HACK: mdi is not fully imported, only required icons... */
|
.mdi-triangle-outline { /* HACK: mdi is not fully imported, only required icons... */
|
||||||
background-image: url('data:image/svg+xml;charset=UTF-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 2L1 21h22M12 6l7.53 13H4.47"/></svg>');
|
background-image: url('data:image/svg+xml;charset=UTF-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M12 2L1 21h22M12 6l7.53 13H4.47"/></svg>');
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ function meshesList(sceneDocument: Document): Array<Array<Mesh>> {
|
|||||||
// Grouped by shared name
|
// Grouped by shared name
|
||||||
return sceneDocument.getRoot().listMeshes().reduce((acc, mesh) => {
|
return sceneDocument.getRoot().listMeshes().reduce((acc, mesh) => {
|
||||||
let name = mesh.getExtras()[extrasNameKey]?.toString() ?? 'Unnamed';
|
let name = mesh.getExtras()[extrasNameKey]?.toString() ?? 'Unnamed';
|
||||||
let group = acc.find((group) => meshName(group[0]) === name);
|
let group = acc.find((group) => group[0] && meshName(group[0]) === name);
|
||||||
if (group) {
|
if (group) {
|
||||||
group.push(mesh);
|
group.push(mesh);
|
||||||
} else {
|
} else {
|
||||||
@@ -43,9 +43,9 @@ defineExpose({findModel})
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<v-expansion-panels v-for="meshes in meshesList(sceneDocument)" :key="meshName(meshes[0])"
|
<v-expansion-panels v-for="meshes in meshesList(sceneDocument)" :key="meshes[0] ? meshName(meshes[0]) : 'unnamed'"
|
||||||
v-model="expandedNames as any" multiple>
|
v-model="expandedNames as any" multiple>
|
||||||
<model :meshes="meshes" :viewer="props.viewer" @remove="onRemove(meshes[0])"/>
|
<model :meshes="meshes" :viewer="props.viewer" @remove="meshes[0] ? onRemove(meshes[0]) : undefined"/>
|
||||||
</v-expansion-panels>
|
</v-expansion-panels>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -4,24 +4,36 @@ import {VueMonacoEditor} from '@guolao/vue-monaco-editor'
|
|||||||
import {nextTick, onMounted, ref, shallowRef} from "vue";
|
import {nextTick, onMounted, ref, shallowRef} from "vue";
|
||||||
import Loading from "../misc/Loading.vue";
|
import Loading from "../misc/Loading.vue";
|
||||||
import {newPyodideWorker} from "./pyodide-worker-api.ts";
|
import {newPyodideWorker} from "./pyodide-worker-api.ts";
|
||||||
import {mdiCircleOpacity, mdiClose, mdiContentSave, mdiFolderOpen, mdiPlay, mdiReload, mdiShare} from "@mdi/js";
|
import {
|
||||||
|
mdiBroom,
|
||||||
|
mdiCircleOpacity,
|
||||||
|
mdiClose,
|
||||||
|
mdiContentSave,
|
||||||
|
mdiFolderOpen,
|
||||||
|
mdiPlay,
|
||||||
|
mdiReload,
|
||||||
|
mdiShare,
|
||||||
|
mdiUpload
|
||||||
|
} from "@mdi/js";
|
||||||
import {VBtn, VCard, VCardText, VSlider, VSpacer, VToolbar, VToolbarTitle, VTooltip} from "vuetify/components";
|
import {VBtn, VCard, VCardText, VSlider, VSpacer, VToolbar, VToolbarTitle, VTooltip} from "vuetify/components";
|
||||||
// @ts-expect-error
|
// @ts-expect-error
|
||||||
import SvgIcon from '@jamescoyle/vue-icon';
|
import SvgIcon from '@jamescoyle/vue-icon';
|
||||||
import {version as pyodideVersion} from "pyodide";
|
import {version as pyodideVersion} from "pyodide";
|
||||||
import {gzip} from 'pako';
|
import {gzip} from 'pako';
|
||||||
import {b66Encode} from "./b66.ts";
|
import {b64UrlEncode} from "./b64.ts";
|
||||||
import {Base64} from 'js-base64'; // More compatible with binary data from python...
|
import {Base64} from 'js-base64'; // More compatible with binary data from python...
|
||||||
import {NetworkUpdateEvent, NetworkUpdateEventModel} from "../misc/network.ts";
|
import {NetworkUpdateEvent, NetworkUpdateEventModel} from "../misc/network.ts";
|
||||||
import {settings} from "../misc/settings.ts";
|
import {settings} from "../misc/settings.ts";
|
||||||
|
// @ts-expect-error
|
||||||
|
import playgroundStartupCode from './PlaygroundStartup.py?raw';
|
||||||
|
import {uploadFile} from "./upload-file.ts";
|
||||||
|
|
||||||
const props = defineProps<{ initialCode: string }>();
|
const model = defineModel<{ code: string, firstTime: boolean }>({required: true}); // Initial code should only be set on first load!
|
||||||
const emit = defineEmits<{ close: [], updateModel: [NetworkUpdateEvent] }>()
|
const emit = defineEmits<{ close: [], updateModel: [NetworkUpdateEvent] }>()
|
||||||
|
|
||||||
// ============ LOAD MONACO EDITOR ============
|
// ============ LOAD MONACO EDITOR ============
|
||||||
setupMonaco() // Must be called before using the editor
|
setupMonaco() // Must be called before using the editor
|
||||||
|
|
||||||
const code = ref(props.initialCode); // TODO: Default code as input (and autorun!)
|
|
||||||
const outputText = ref(``);
|
const outputText = ref(``);
|
||||||
|
|
||||||
function output(text: string) {
|
function output(text: string) {
|
||||||
@@ -49,35 +61,32 @@ const MONACO_EDITOR_OPTIONS = {
|
|||||||
const editorTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? `vs-dark` : `vs`
|
const editorTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? `vs-dark` : `vs`
|
||||||
const editor = shallowRef()
|
const editor = shallowRef()
|
||||||
const handleMount = (editorInstance: typeof VueMonacoEditor) => (editor.value = editorInstance)
|
const handleMount = (editorInstance: typeof VueMonacoEditor) => (editor.value = editorInstance)
|
||||||
const opacity = ref(0.9); // Opacity for the editor
|
const opacity = ref(0.9); // Opacity for the editor (overriden when settings are loaded)
|
||||||
|
|
||||||
// ============ LOAD PYODIDE (ASYNC) ============
|
// ============ LOAD PYODIDE (ASYNC) ============
|
||||||
let pyodideWorker: ReturnType<typeof newPyodideWorker> | null = (import.meta as any).hot?.data?.pyodideWorker || null;
|
let pyodideWorker: ReturnType<typeof newPyodideWorker> | null = (import.meta as any).hot?.data?.pyodideWorker || null;
|
||||||
const running = ref(true);
|
const running = ref(true);
|
||||||
|
|
||||||
async function setupPyodide() {
|
async function setupPyodide(first: boolean, loadSnapshot: Uint8Array | undefined = undefined) {
|
||||||
running.value = true;
|
running.value = true;
|
||||||
if (opacity.value == 0.0) opacity.value = 0.9; // User doesn't know how to show code again, reset after reopening
|
if (opacity.value == 0.0 && !first) opacity.value = 0.9; // User doesn't know how to show code again, reset after reopening
|
||||||
if (pyodideWorker === null) {
|
if (pyodideWorker === null) {
|
||||||
output("Creating new Pyodide worker...\n");
|
output("Creating new Pyodide worker...\n");
|
||||||
pyodideWorker = newPyodideWorker({
|
pyodideWorker = newPyodideWorker(Object.assign({
|
||||||
indexURL: `https://cdn.jsdelivr.net/pyodide/v${pyodideVersion}/full/`, // FIXME: Local deployment?
|
// Note: python wheels are downloaded from the CDN, as we can't know which ones are needed in advance to bundle them
|
||||||
|
// Furthermore, this lets us use the latest version of all wheels including ocp-specific ones without app updates
|
||||||
|
indexURL: `https://cdn.jsdelivr.net/pyodide/v${pyodideVersion}/full/`,
|
||||||
packages: ["micropip", "sqlite3"], // Faster load if done here
|
packages: ["micropip", "sqlite3"], // Faster load if done here
|
||||||
});
|
// _makeSnapshot: true, // Enable snapshotting for faster startup (still experimental: breaks loading any packages)
|
||||||
|
}, (loadSnapshot ? {_loadSnapshot: loadSnapshot} : {}))); // Load snapshot if provided
|
||||||
if ((import.meta as any).hot) (import.meta as any).hot.data.pyodideWorker = pyodideWorker
|
if ((import.meta as any).hot) (import.meta as any).hot.data.pyodideWorker = pyodideWorker
|
||||||
} else {
|
} else {
|
||||||
output("Reusing existing Pyodide instance...\n");
|
output("Reusing existing Pyodide instance...\n");
|
||||||
}
|
}
|
||||||
output("Preloading packages...\n");
|
output("Preloading packages...\n");
|
||||||
await pyodideWorker.asyncRun(`import micropip, asyncio
|
await pyodideWorker.asyncRun(playgroundStartupCode, output, output); // Also import yacv_server and mock ocp_vscode here for faster custom code execution
|
||||||
micropip.set_index_urls(["https://yeicor.github.io/OCP.wasm", "https://pypi.org/simple"])
|
|
||||||
await (micropip.install("lib3mf"))
|
|
||||||
micropip.add_mock_package("py-lib3mf", "2.4.1", modules={"py_lib3mf": 'from lib3mf import *'})
|
|
||||||
await (micropip.install(["https://files.pythonhosted.org/packages/67/25/80be117f39ff5652a4fdbd761b061123c5425e379f4b0a5ece4353215d86/yacv_server-0.10.0a4-py3-none-any.whl"]))
|
|
||||||
from yacv_server import *
|
|
||||||
micropip.add_mock_package("ocp-vscode", "2.8.9", modules={"ocp_vscode": 'from yacv_server import *'})`, output, output); // Also import yacv_server and mock ocp_vscode here for faster custom code execution
|
|
||||||
running.value = false; // Indicate that Pyodide is ready
|
running.value = false; // Indicate that Pyodide is ready
|
||||||
output("Pyodide worker initialized.\n");
|
output("Pyodide worker ready.\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runCode() {
|
async function runCode() {
|
||||||
@@ -92,7 +101,7 @@ async function runCode() {
|
|||||||
output("Running code...\n");
|
output("Running code...\n");
|
||||||
try {
|
try {
|
||||||
running.value = true;
|
running.value = true;
|
||||||
await pyodideWorker.asyncRun(code.value, output, (msg: string) => {
|
await pyodideWorker.asyncRun(model.value.code, output, (msg: string) => {
|
||||||
// Detect models printed to console (since http server is not available in pyodide)
|
// Detect models printed to console (since http server is not available in pyodide)
|
||||||
if (msg.startsWith(yacvServerModelPrefix)) {
|
if (msg.startsWith(yacvServerModelPrefix)) {
|
||||||
const modelData = msg.slice(yacvServerModelPrefix.length);
|
const modelData = msg.slice(yacvServerModelPrefix.length);
|
||||||
@@ -102,8 +111,9 @@ async function runCode() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
output(`Error running initial code: ${e}\n`);
|
output(`Error running code: ${e}\n`);
|
||||||
} finally {
|
} finally {
|
||||||
|
output("Code execution finished.\n");
|
||||||
running.value = false; // Indicate that Pyodide is ready
|
running.value = false; // Indicate that Pyodide is ready
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -132,9 +142,13 @@ function onModelData(modelData: string) {
|
|||||||
const binaryData = Base64.toUint8Array(modelData.slice(i + 1)); // Extract the base64 part
|
const binaryData = Base64.toUint8Array(modelData.slice(i + 1)); // Extract the base64 part
|
||||||
console.assert(binaryData.slice(0, 4).toString() == "103,108,84,70", // Ugly...
|
console.assert(binaryData.slice(0, 4).toString() == "103,108,84,70", // Ugly...
|
||||||
"Invalid GLTF binary data received: " + binaryData.slice(0, 4).toString());
|
"Invalid GLTF binary data received: " + binaryData.slice(0, 4).toString());
|
||||||
|
// - Save for upload and share link feature
|
||||||
|
builtModelsGlb[modelMetadata.name] = binaryData;
|
||||||
// - Create a Blob from the binary data to be used as a URL
|
// - Create a Blob from the binary data to be used as a URL
|
||||||
const blob = new Blob([binaryData], {type: 'model/gltf-binary'});
|
const blob = new Blob([binaryData as ArrayBufferView<ArrayBuffer>], {type: 'model/gltf-binary'});
|
||||||
modelMetadata.url = URL.createObjectURL(blob); // Set the hacked URL in the model metadata
|
modelMetadata.url = URL.createObjectURL(blob); // Set the hacked URL in the model metadata XXX: revoked on App.vue
|
||||||
|
} else {
|
||||||
|
delete builtModelsGlb[modelMetadata.name]; // Remove from built models if it's a remove request
|
||||||
}
|
}
|
||||||
// - Emit the event with the model metadata and URL
|
// - Emit the event with the model metadata and URL
|
||||||
let networkUpdateEvent = new NetworkUpdateEvent([modelMetadata], () => {
|
let networkUpdateEvent = new NetworkUpdateEvent([modelMetadata], () => {
|
||||||
@@ -142,22 +156,33 @@ function onModelData(modelData: string) {
|
|||||||
emit('updateModel', networkUpdateEvent);
|
emit('updateModel', networkUpdateEvent);
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetWorker() {
|
function resetWorker(loadSnapshot: Uint8Array | undefined = undefined) {
|
||||||
if (pyodideWorker) {
|
if (pyodideWorker) {
|
||||||
pyodideWorker.terminate(); // Terminate existing worker
|
pyodideWorker.terminate(); // Terminate existing worker
|
||||||
pyodideWorker = null; // Reset worker reference
|
pyodideWorker = null; // Reset worker reference
|
||||||
}
|
}
|
||||||
outputText.value = ``; // Clear output text
|
outputText.value = ``; // Clear output text
|
||||||
setupPyodide(); // Reinitialize Pyodide
|
setupPyodide(false, loadSnapshot); // Reinitialize Pyodide
|
||||||
}
|
}
|
||||||
|
|
||||||
function shareLink() {
|
function shareLinkCommon(added: Record<string, Array<string> | string>, forgotten: Array<string>) {
|
||||||
const baseUrl = window.location
|
const baseUrl = window.location
|
||||||
const urlParams = new URLSearchParams(baseUrl.hash.slice(1)); // Keep all previous URL parameters
|
const searchParams = new URLSearchParams(baseUrl.search);
|
||||||
urlParams.set('pg_code', b66Encode(gzip(code.value, {level: 9}))); // Compress and encode the code
|
for (const k of forgotten) searchParams.delete(k);
|
||||||
const shareUrl = `${baseUrl.origin}${baseUrl.pathname}${baseUrl.search}#${urlParams.toString()}`; // Prefer hash to GET (bigger limits)
|
const hashParams = new URLSearchParams(baseUrl.hash.slice(1)); // Keep all previous URL parameters
|
||||||
|
for (const k of forgotten) hashParams.delete(k);
|
||||||
|
for (const k in added) {
|
||||||
|
if (Array.isArray(added[k])) {
|
||||||
|
for (const v of added[k]) {
|
||||||
|
hashParams.append(k, v); // Prefer hash to GET
|
||||||
|
}
|
||||||
|
} else if (typeof added[k] === 'string') {
|
||||||
|
hashParams.set(k, added[k]); // Prefer hash to GET
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const shareUrl = `${baseUrl.origin}${baseUrl.pathname}?${searchParams}#${hashParams}`;
|
||||||
output(`Share link ready: ${shareUrl}\n`)
|
output(`Share link ready: ${shareUrl}\n`)
|
||||||
if (!navigator.clipboard) {
|
if (navigator.clipboard?.writeText === undefined) {
|
||||||
output("Clipboard API not available. Please copy the link manually.\n");
|
output("Clipboard API not available. Please copy the link manually.\n");
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
@@ -167,6 +192,37 @@ function shareLink() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function shareLink() {
|
||||||
|
shareLinkCommon({'pg_code': b64UrlEncode(gzip(model.value.code, {level: 9}))}, ['pg_code']);
|
||||||
|
}
|
||||||
|
|
||||||
|
const builtModelsGlb: Record<string, Uint8Array> = {}; // Store built models to support uploading
|
||||||
|
async function uploadAndShareLink() {
|
||||||
|
try {
|
||||||
|
output("Uploading files...\n");
|
||||||
|
|
||||||
|
// Upload code.py
|
||||||
|
const codeBlob = new Blob([model.value.code], {type: 'text/x-python'});
|
||||||
|
const newParams: Record<string, string | Array<string>> = {
|
||||||
|
'pg_code': await uploadFile('code.py', new Uint8Array(await codeBlob.arrayBuffer()))
|
||||||
|
};
|
||||||
|
|
||||||
|
// Upload all models
|
||||||
|
newParams['preload'] = []
|
||||||
|
for (const name in builtModelsGlb) {
|
||||||
|
const glb: any = builtModelsGlb[name];
|
||||||
|
const url = await uploadFile(name + '.glb', glb)
|
||||||
|
newParams['preload'].push(url); // Add to preload list
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build share URL
|
||||||
|
return shareLinkCommon(newParams, ['pg_code'])
|
||||||
|
} catch (e) {
|
||||||
|
output(`Error uploading/sharing files: ${e}. Falling back to private share link.\n`);
|
||||||
|
return shareLink(); // Fallback to private share link if upload fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function saveSnapshot() {
|
function saveSnapshot() {
|
||||||
throw new Error("Not implemented yet!"); // TODO: Implement snapshot saving
|
throw new Error("Not implemented yet!"); // TODO: Implement snapshot saving
|
||||||
}
|
}
|
||||||
@@ -175,27 +231,28 @@ function loadSnapshot() {
|
|||||||
throw new Error("Not implemented yet!"); // TODO: Implement snapshot loading
|
throw new Error("Not implemented yet!"); // TODO: Implement snapshot loading
|
||||||
}
|
}
|
||||||
|
|
||||||
const reused = (import.meta as any).hot?.data?.pyodideWorker !== undefined;
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const sett = await settings()
|
const sett = await settings
|
||||||
if (!reused) opacity.value = sett.pg_opacity_loading
|
if (model.value.firstTime) opacity.value = sett.pg_opacity_loading
|
||||||
await setupPyodide()
|
await setupPyodide(true);
|
||||||
if (props.initialCode != "" && !reused) await runCode();
|
if (model.value.firstTime) {
|
||||||
if (!reused) opacity.value = sett.pg_opacity_loaded
|
await runCode();
|
||||||
|
opacity.value = sett.pg_opacity_loaded
|
||||||
|
model.value.firstTime = false
|
||||||
|
}
|
||||||
})()
|
})()
|
||||||
|
|
||||||
// Add keyboard shortcuts
|
// Add keyboard shortcuts
|
||||||
const editorRef = ref<HTMLElement | null>(null);
|
const editorRef = ref<HTMLElement | null>(null);
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
if (editorRef.value) {
|
if (editorRef.value) {
|
||||||
console.log(editorRef.value)
|
|
||||||
editorRef.value.addEventListener('keydown', (event: Event) => {
|
editorRef.value.addEventListener('keydown', (event: Event) => {
|
||||||
if (!(event instanceof KeyboardEvent)) return; // Ensure event is a KeyboardEvent
|
if (!(event instanceof KeyboardEvent)) return; // Ensure event is a KeyboardEvent
|
||||||
if (event.key === 'Enter' && event.ctrlKey) {
|
if (event.key === 'F10') { // Run code on F10
|
||||||
event.preventDefault(); // Prevent default behavior of Enter key
|
event.preventDefault(); // Prevent default behavior of the key
|
||||||
runCode(); // Run code on Ctrl+Enter
|
runCode();
|
||||||
} else if (event.key === 'Escape') {
|
} else if (event.key === 'Escape') { // Close on Escape key
|
||||||
emit('close'); // Close on Escape key
|
emit('close');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -218,38 +275,48 @@ onMounted(() => {
|
|||||||
location="bottom">Opacity of the editor (0 = hidden, 1 = fully visible)</v-tooltip>
|
location="bottom">Opacity of the editor (0 = hidden, 1 = fully visible)</v-tooltip>
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<span style="margin-right: -8px;"><!-- This span is only needed to force tooltip to work while button is disabled -->
|
<span style="padding-left: 12px; width: 48px;"><!-- This span is only needed to force tooltip to work while button is disabled -->
|
||||||
<v-btn icon disabled @click="saveSnapshot()">
|
<v-btn icon disabled @click="saveSnapshot()">
|
||||||
<svg-icon :path="mdiContentSave" type="mdi"/>
|
<svg-icon :path="mdiContentSave" type="mdi"/>
|
||||||
</v-btn>
|
</v-btn>
|
||||||
<v-tooltip activator="parent"
|
<v-tooltip activator="parent"
|
||||||
location="bottom">Save current state to a snapshot for fast startup (WIP)</v-tooltip>
|
location="bottom">Save current state to a snapshot for fast startup (WIP)</v-tooltip>
|
||||||
</span>
|
</span>
|
||||||
<span style="margin-left: -8px"><!-- This span is only needed to force tooltip to work while button is disabled -->
|
<span style="padding-right: 12px; width: 48px;"><!-- This span is only needed to force tooltip to work while button is disabled -->
|
||||||
<v-btn icon disabled @click="loadSnapshot()">
|
<v-btn icon disabled @click="loadSnapshot()">
|
||||||
<svg-icon :path="mdiFolderOpen" type="mdi"/>
|
<svg-icon :path="mdiFolderOpen" type="mdi"/>
|
||||||
</v-btn>
|
</v-btn>
|
||||||
<v-tooltip activator="parent" location="bottom">Load snapshot for fast startup (WIP)</v-tooltip>
|
<v-tooltip activator="parent" location="bottom">Load snapshot for fast startup (WIP)</v-tooltip>
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
<v-btn icon @click="resetWorker()">
|
<v-btn icon @click="shareLink()" style="padding-left: 12px;">
|
||||||
|
<svg-icon :path="mdiShare" type="mdi"/>
|
||||||
|
<v-tooltip activator="parent" location="bottom">Share link that automatically runs the code.<br/>Only people
|
||||||
|
with the link can see the code.
|
||||||
|
</v-tooltip>
|
||||||
|
</v-btn>
|
||||||
|
|
||||||
|
<v-btn icon @click="uploadAndShareLink()" style="padding-right: 12px">
|
||||||
|
<svg-icon :path="mdiShare" type="mdi" style="position: absolute; scale: 75%; top: 6px;"/>
|
||||||
|
<svg-icon :path="mdiUpload" type="mdi" style="position: absolute; scale: 75%; bottom: 6px;"/>
|
||||||
|
<v-tooltip activator="parent" location="bottom">Uploads all models and code and then shares a link to them.<br/>Useful
|
||||||
|
to view the models while the playground loads, but uses third-party storage.
|
||||||
|
</v-tooltip>
|
||||||
|
</v-btn>
|
||||||
|
|
||||||
|
<v-btn icon @click="resetWorker()" style="padding-left: 12px;">
|
||||||
<svg-icon :path="mdiReload" type="mdi"/>
|
<svg-icon :path="mdiReload" type="mdi"/>
|
||||||
<v-tooltip activator="parent" location="bottom">Reset Pyodide worker (this forgets all previous state and will
|
<v-tooltip activator="parent" location="bottom">Reset Pyodide worker (this forgets all previous state and will
|
||||||
take a little while)
|
take a little while)
|
||||||
</v-tooltip>
|
</v-tooltip>
|
||||||
</v-btn>
|
</v-btn>
|
||||||
|
|
||||||
<v-btn icon @click="runCode()" :disabled="running">
|
<v-btn icon @click="runCode()" :disabled="running" style="padding-right: 12px">
|
||||||
<svg-icon :path="mdiPlay" type="mdi"/>
|
<svg-icon :path="mdiPlay" type="mdi"/>
|
||||||
<Loading v-if="running" style="position: absolute; top: -16%; left: -16%"/><!-- Ugly positioning -->
|
<Loading v-if="running" style="position: absolute; top: -16%; left: -28%"/><!-- Ugly positioning -->
|
||||||
<v-tooltip activator="parent" location="bottom">Run code</v-tooltip>
|
<v-tooltip activator="parent" location="bottom">Run code</v-tooltip>
|
||||||
</v-btn>
|
</v-btn>
|
||||||
|
|
||||||
<v-btn icon @click="shareLink()">
|
|
||||||
<svg-icon :path="mdiShare" type="mdi"/>
|
|
||||||
<v-tooltip activator="parent" location="bottom">Share link that auto-runs the code</v-tooltip>
|
|
||||||
</v-btn>
|
|
||||||
|
|
||||||
<v-btn icon @click="emit('close')">
|
<v-btn icon @click="emit('close')">
|
||||||
<svg-icon :path="mdiClose" type="mdi"/>
|
<svg-icon :path="mdiClose" type="mdi"/>
|
||||||
<v-tooltip activator="parent" location="bottom">Close (Pyodide remains loaded)</v-tooltip>
|
<v-tooltip activator="parent" location="bottom">Close (Pyodide remains loaded)</v-tooltip>
|
||||||
@@ -259,11 +326,17 @@ onMounted(() => {
|
|||||||
<!-- Only show content if opacity is greater than 0 -->
|
<!-- Only show content if opacity is greater than 0 -->
|
||||||
<div class="playground-container">
|
<div class="playground-container">
|
||||||
<div class="playground-editor" ref="editorRef">
|
<div class="playground-editor" ref="editorRef">
|
||||||
<VueMonacoEditor v-model:value="code" :theme="editorTheme" :options="MONACO_EDITOR_OPTIONS"
|
<VueMonacoEditor v-model:value="model.code" :theme="editorTheme" :options="MONACO_EDITOR_OPTIONS"
|
||||||
language="python" @mount="handleMount"/>
|
language="python" @mount="handleMount"/>
|
||||||
</div>
|
</div>
|
||||||
<div class="playground-console">
|
<div class="playground-console">
|
||||||
<h3>Console Output</h3>
|
<h3 style="display:flex; align-items: center; justify-content: space-between; margin: 0;">
|
||||||
|
Console Output
|
||||||
|
<v-spacer></v-spacer>
|
||||||
|
<v-btn @click="outputText = ''">
|
||||||
|
<svg-icon :path="mdiBroom" type="mdi" class="h-"/>
|
||||||
|
</v-btn>
|
||||||
|
</h3>
|
||||||
<pre>{{ outputText }}</pre> <!-- Placeholder for console output -->
|
<pre>{{ outputText }}</pre> <!-- Placeholder for console output -->
|
||||||
<Loading v-if="running"/>
|
<Loading v-if="running"/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
24
frontend/tools/PlaygroundStartup.py
Normal file
24
frontend/tools/PlaygroundStartup.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import micropip
|
||||||
|
|
||||||
|
# Prioritize the OCP.wasm package repository for finding the ported dependencies.
|
||||||
|
micropip.set_index_urls(["https://yeicor.github.io/OCP.wasm", "https://pypi.org/simple"])
|
||||||
|
|
||||||
|
# For build123d < 0.10.0, we need to install the mock the py-lib3mf package (before the main install).
|
||||||
|
await micropip.install("lib3mf")
|
||||||
|
micropip.add_mock_package("py-lib3mf", "2.4.1", modules={"py_lib3mf": 'from lib3mf import *'})
|
||||||
|
|
||||||
|
# Install the yacv_server package, which is the main server for the OCP.wasm playground; and also preinstalls build123d.
|
||||||
|
await micropip.install("yacv_server", pre=True)
|
||||||
|
|
||||||
|
# Preimport the yacv_server package to ensure it is available in the global scope, and mock the ocp_vscode package.
|
||||||
|
from yacv_server import *
|
||||||
|
|
||||||
|
micropip.add_mock_package("ocp-vscode", "2.8.9", modules={"ocp_vscode": 'from yacv_server import *'})
|
||||||
|
show_object = show
|
||||||
|
|
||||||
|
# Preinstall the font-fetcher package and install its hook to automatically download any requested font.
|
||||||
|
await micropip.install("font-fetcher", pre=True)
|
||||||
|
|
||||||
|
from font_fetcher.ocp import install_ocp_font_hook
|
||||||
|
|
||||||
|
install_ocp_font_hook()
|
||||||
@@ -213,7 +213,7 @@ function toggleSelection() {
|
|||||||
function toggleOpenNextSelection() {
|
function toggleOpenNextSelection() {
|
||||||
openNextSelection.value = [
|
openNextSelection.value = [
|
||||||
!openNextSelection.value[0],
|
!openNextSelection.value[0],
|
||||||
openNextSelection.value[0] ? openNextSelection.value[1] : selectionEnabled.value
|
openNextSelection.value[0] ? (openNextSelection.value[1] ?? false) : selectionEnabled.value
|
||||||
];
|
];
|
||||||
if (openNextSelection.value[0]) {
|
if (openNextSelection.value[0]) {
|
||||||
// Reuse selection code to identify the model
|
// Reuse selection code to identify the model
|
||||||
@@ -330,14 +330,20 @@ function updateBoundingBox() {
|
|||||||
// Only draw one edge per axis, the 2nd closest one to the camera
|
// Only draw one edge per axis, the 2nd closest one to the camera
|
||||||
for (let edgeI in edgesByAxis) {
|
for (let edgeI in edgesByAxis) {
|
||||||
let axisEdges = edgesByAxis[edgeI];
|
let axisEdges = edgesByAxis[edgeI];
|
||||||
let edge: Array<number> = axisEdges[0];
|
if (!axisEdges || axisEdges.length === 0) continue;
|
||||||
|
let edge: Array<number> = axisEdges[0] ?? [];
|
||||||
for (let i = 0; i < 2; i++) { // Find the 2nd closest one by running twice dropping the first
|
for (let i = 0; i < 2; i++) { // Find the 2nd closest one by running twice dropping the first
|
||||||
edge = axisEdges[0];
|
if (!axisEdges || axisEdges.length === 0) break;
|
||||||
|
edge = axisEdges[0] ?? [];
|
||||||
let edgeDist = Infinity;
|
let edgeDist = Infinity;
|
||||||
let cameraPos: Vector3 = props.viewer?.scene?.camera?.position ?? new Vector3();
|
let cameraPos: Vector3 = props.viewer?.scene?.camera?.position ?? new Vector3();
|
||||||
for (let testEdge of axisEdges) {
|
for (let testEdge of axisEdges) {
|
||||||
let from = new Vector3(...corners[testEdge[0]]);
|
if (!testEdge || testEdge.length < 2) continue;
|
||||||
let to = new Vector3(...corners[testEdge[1]]);
|
let cornerA = corners[testEdge[0] ?? 0];
|
||||||
|
let cornerB = corners[testEdge[1] ?? 0];
|
||||||
|
if (!cornerA || !cornerB) continue;
|
||||||
|
let from = new Vector3(...cornerA);
|
||||||
|
let to = new Vector3(...cornerB);
|
||||||
let mid = from.clone().add(to).multiplyScalar(0.5);
|
let mid = from.clone().add(to).multiplyScalar(0.5);
|
||||||
let newDist = cameraPos.distanceTo(mid);
|
let newDist = cameraPos.distanceTo(mid);
|
||||||
if (newDist < edgeDist) {
|
if (newDist < edgeDist) {
|
||||||
@@ -347,11 +353,16 @@ function updateBoundingBox() {
|
|||||||
}
|
}
|
||||||
axisEdges = axisEdges.filter((e) => e !== edge);
|
axisEdges = axisEdges.filter((e) => e !== edge);
|
||||||
}
|
}
|
||||||
let from = new Vector3(...corners[edge[0]]);
|
if (!edge || edge.length < 2) continue;
|
||||||
let to = new Vector3(...corners[edge[1]]);
|
let cornerA = corners[edge[0] ?? 0];
|
||||||
|
let cornerB = corners[edge[1] ?? 0];
|
||||||
|
if (!cornerA || !cornerB) continue;
|
||||||
|
let from = new Vector3(...cornerA);
|
||||||
|
let to = new Vector3(...cornerB);
|
||||||
let length = to.clone().sub(from).length();
|
let length = to.clone().sub(from).length();
|
||||||
if (length < 0.05) continue; // Skip very small edges (e.g. a single point)
|
if (length < 0.05) continue; // Skip very small edges (e.g. a single point)
|
||||||
let color = [AxesColors.x, AxesColors.y, AxesColors.z][edgeI][1]; // Secondary colors
|
let colorArray = [AxesColors.x, AxesColors.y, AxesColors.z][parseInt(edgeI)];
|
||||||
|
let color = colorArray ? colorArray[1] : [255, 255, 255]; // Secondary colors
|
||||||
let lineCacheKey = JSON.stringify([from, to]);
|
let lineCacheKey = JSON.stringify([from, to]);
|
||||||
let matchingLine = boundingBoxLines[lineCacheKey];
|
let matchingLine = boundingBoxLines[lineCacheKey];
|
||||||
if (matchingLine) {
|
if (matchingLine) {
|
||||||
@@ -359,7 +370,7 @@ function updateBoundingBox() {
|
|||||||
} else {
|
} else {
|
||||||
let newLineId = props.viewer?.addLine3D(from, to,
|
let newLineId = props.viewer?.addLine3D(from, to,
|
||||||
length.toFixed(1) + "mm", {
|
length.toFixed(1) + "mm", {
|
||||||
"stroke": "rgb(" + color.join(',') + ")",
|
"stroke": "rgb(" + (color ?? [255, 255, 255]).join(',') + ")",
|
||||||
"stroke-width": "2"
|
"stroke-width": "2"
|
||||||
});
|
});
|
||||||
if (newLineId) {
|
if (newLineId) {
|
||||||
@@ -410,10 +421,17 @@ function updateDistances() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add lines (if not already added)
|
// Add lines (if not already added)
|
||||||
let {min, center, max} = distances(selected.value[0], selected.value[1], props.viewer?.scene);
|
if (!selected.value[0] || !selected.value[1] || !props.viewer?.scene) return;
|
||||||
ensureLine(max[0], max[1], max[1].distanceTo(max[0]).toFixed(1) + "mm", "orange");
|
let {min, center, max} = distances(selected.value[0], selected.value[1], props.viewer.scene);
|
||||||
ensureLine(center[0], center[1], center[1].distanceTo(center[0]).toFixed(1) + "mm", "green");
|
if (max[0] && max[1]) {
|
||||||
ensureLine(min[0], min[1], min[1].distanceTo(min[0]).toFixed(1) + "mm", "cyan");
|
ensureLine(max[0], max[1], max[1].distanceTo(max[0]).toFixed(1) + "mm", "orange");
|
||||||
|
}
|
||||||
|
if (center[0] && center[1]) {
|
||||||
|
ensureLine(center[0], center[1], center[1].distanceTo(center[0]).toFixed(1) + "mm", "green");
|
||||||
|
}
|
||||||
|
if (min[0] && min[1]) {
|
||||||
|
ensureLine(min[0], min[1], min[1].distanceTo(min[0]).toFixed(1) + "mm", "cyan");
|
||||||
|
}
|
||||||
|
|
||||||
// Remove the lines that are no longer needed
|
// Remove the lines that are no longer needed
|
||||||
for (let lineLocator of distanceLinesToRemove) {
|
for (let lineLocator of distanceLinesToRemove) {
|
||||||
@@ -504,4 +522,4 @@ window.addEventListener('keydown', (event) => {
|
|||||||
top: -12px;
|
top: -12px;
|
||||||
width: calc(100% - 48px);
|
width: calc(100% - 48px);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ import SvgIcon from '@jamescoyle/vue-icon';
|
|||||||
import type {ModelViewerElement} from '@google/model-viewer';
|
import type {ModelViewerElement} from '@google/model-viewer';
|
||||||
import Loading from "../misc/Loading.vue";
|
import Loading from "../misc/Loading.vue";
|
||||||
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
|
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
|
||||||
import {defineAsyncComponent, ref, type Ref} from "vue";
|
import {defineAsyncComponent, ref} from "vue";
|
||||||
import type {SelectionInfo} from "./selection";
|
import type {SelectionInfo} from "./selection";
|
||||||
import {settings} from "../misc/settings.ts";
|
import {settings} from "../misc/settings.ts";
|
||||||
import type {NetworkUpdateEvent} from "../misc/network.ts";
|
import type {NetworkUpdateEvent} from "../misc/network.ts";
|
||||||
@@ -59,12 +59,14 @@ const emit = defineEmits<{ findModel: [string], updateModel: [NetworkUpdateEvent
|
|||||||
|
|
||||||
const sett = ref<any | null>(null);
|
const sett = ref<any | null>(null);
|
||||||
const showPlaygroundDialog = ref(false);
|
const showPlaygroundDialog = ref(false);
|
||||||
|
const pg_model = ref({code: '# Loading...', firstTime: false});
|
||||||
(async () => {
|
(async () => {
|
||||||
sett.value = await settings();
|
sett.value = await settings;
|
||||||
showPlaygroundDialog.value = sett.value.pg_code != "";
|
pg_model.value = {code: sett.value.pg_code, firstTime: true};
|
||||||
|
showPlaygroundDialog.value = pg_model.value.code != "";
|
||||||
})();
|
})();
|
||||||
|
|
||||||
let selection: Ref<Array<SelectionInfo>> = ref([]);
|
let selection = ref<Array<SelectionInfo>>([]);
|
||||||
let selectionFaceCount = () => selection.value.filter((s) => s.kind == 'face').length
|
let selectionFaceCount = () => selection.value.filter((s) => s.kind == 'face').length
|
||||||
let selectionEdgeCount = () => selection.value.filter((s) => s.kind == 'edge').length
|
let selectionEdgeCount = () => selection.value.filter((s) => s.kind == 'edge').length
|
||||||
let selectionVertexCount = () => selection.value.filter((s) => s.kind == "vertex").length
|
let selectionVertexCount = () => selection.value.filter((s) => s.kind == "vertex").length
|
||||||
@@ -126,6 +128,7 @@ async function downloadSceneGlb() {
|
|||||||
link.download = file.name;
|
link.download = file.name;
|
||||||
link.href = URL.createObjectURL(file);
|
link.href = URL.createObjectURL(file);
|
||||||
link.click();
|
link.click();
|
||||||
|
URL.revokeObjectURL(link.href);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openGithub() {
|
async function openGithub() {
|
||||||
@@ -193,7 +196,7 @@ document.addEventListener('keydown', (event) => {
|
|||||||
</template>
|
</template>
|
||||||
<template v-slot:default="{ isActive }">
|
<template v-slot:default="{ isActive }">
|
||||||
<if-not-small-build>
|
<if-not-small-build>
|
||||||
<playground-dialog-content v-if="sett != null" :initial-code="sett.pg_code" @close="isActive.value = false"
|
<playground-dialog-content v-if="sett != null" v-model="pg_model" @close="isActive.value = false"
|
||||||
@update-model="(event: NetworkUpdateEvent) => emit('updateModel', event)"/>
|
@update-model="(event: NetworkUpdateEvent) => emit('updateModel', event)"/>
|
||||||
</if-not-small-build>
|
</if-not-small-build>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
21
frontend/tools/b64.ts
Normal file
21
frontend/tools/b64.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
export function b64UrlEncode(data: Uint8Array): string {
|
||||||
|
const base64 = btoa(String.fromCharCode(...data));
|
||||||
|
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function b64UrlDecode(encoded: string): Uint8Array {
|
||||||
|
// Replace URL-safe characters with standard base64 characters
|
||||||
|
let base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
// Add padding if necessary
|
||||||
|
const padding = base64.length % 4;
|
||||||
|
if (padding) {
|
||||||
|
base64 += '='.repeat(4 - padding);
|
||||||
|
}
|
||||||
|
// Decode the base64 string to a byte array
|
||||||
|
const binaryString = atob(base64);
|
||||||
|
const byteArray = new Uint8Array(binaryString.length);
|
||||||
|
for (let i = 0; i < binaryString.length; i++) {
|
||||||
|
byteArray[i] = binaryString.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return byteArray;
|
||||||
|
}
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
// B66 encoding and decoding functions for compact url query parameter values. https://gist.github.com/danneu/6755394
|
|
||||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_~";
|
|
||||||
|
|
||||||
export function b66Encode(data: Uint8Array): string {
|
|
||||||
let result = "";
|
|
||||||
let bits = 0;
|
|
||||||
let value = 0;
|
|
||||||
|
|
||||||
for (let byte of data) {
|
|
||||||
value = (value << 8) | byte;
|
|
||||||
bits += 8;
|
|
||||||
|
|
||||||
while (bits >= 6) {
|
|
||||||
bits -= 6;
|
|
||||||
result += alphabet[(value >> bits) & 0x3F];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bits > 0) {
|
|
||||||
result += alphabet[(value << (6 - bits)) & 0x3F];
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function b66Decode(encoded: string): Uint8Array {
|
|
||||||
let result = [];
|
|
||||||
let bits = 0;
|
|
||||||
let value = 0;
|
|
||||||
|
|
||||||
for (let char of encoded) {
|
|
||||||
const index = alphabet.indexOf(char);
|
|
||||||
if (index === -1) {
|
|
||||||
throw new Error(`Invalid character '${char}' in B66 encoded string.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
value = (value << 6) | index;
|
|
||||||
bits += 6;
|
|
||||||
|
|
||||||
while (bits >= 8) {
|
|
||||||
bits -= 8;
|
|
||||||
result.push((value >> bits) & 0xFF);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bits > 0) {
|
|
||||||
// If there are leftover bits, they should not be present in a valid B66 encoding.
|
|
||||||
if (value << (8 - bits)) {
|
|
||||||
throw new Error("Invalid B66 encoding: leftover bits.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Uint8Array(result);
|
|
||||||
}
|
|
||||||
@@ -12,8 +12,8 @@ import htmlWorker from "monaco-editor/esm/vs/language/html/html.worker?worker"
|
|||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker"
|
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker"
|
||||||
|
|
||||||
self.MonacoEnvironment = {
|
(self as any).MonacoEnvironment = {
|
||||||
getWorker(_, label) {
|
getWorker(_: any, label: string) {
|
||||||
if (label === "json") {
|
if (label === "json") {
|
||||||
return new jsonWorker()
|
return new jsonWorker()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,44 @@
|
|||||||
import type {loadPyodide} from "pyodide";
|
import type {loadPyodide} from "pyodide";
|
||||||
|
import type {MessageEventDataIn} from "./pyodide-worker.ts";
|
||||||
|
|
||||||
|
let requestId = 0;
|
||||||
|
|
||||||
/** Simple API for the Pyodide worker. */
|
/** Simple API for the Pyodide worker. */
|
||||||
export function newPyodideWorker(initOpts: Parameters<typeof loadPyodide>[0]) {
|
export function newPyodideWorker(initOpts: Parameters<typeof loadPyodide>[0]) {
|
||||||
let worker = new Worker(new URL('./pyodide-worker.ts', import.meta.url), {type: "module"});
|
let worker = new Worker(new URL('./pyodide-worker.ts', import.meta.url), {type: "module"});
|
||||||
worker.postMessage(initOpts);
|
worker.postMessage(initOpts);
|
||||||
return {
|
const commonRequestResponse = (event: MessageEventDataIn, stdout?: (msg: string) => void, stderr?: (msg: string) => void) => {
|
||||||
asyncRun: (code: String, stdout: (msg: string) => void, stderr: (msg: string) => void) => new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
worker.addEventListener("message", function listener(event) {
|
worker.addEventListener("message", function listener(event: MessageEvent) {
|
||||||
if (event.data?.stdout) {
|
if (stdout && event.data?.stdout) {
|
||||||
stdout(event.data.stdout);
|
stdout(event.data.stdout); // No clue if associated with this request, but we handle it anyway.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (event.data?.stderr) {
|
if (stderr && event.data?.stderr) {
|
||||||
stderr(event.data.stderr);
|
stderr(event.data.stderr); // No clue if associated with this request, but we handle it anyway.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Result or error.
|
if (event.data?.id !== event.data.id) return; // Ignore messages that are not for this request.
|
||||||
worker.removeEventListener("message", listener);
|
|
||||||
if (event.data?.error) {
|
if (event.data?.error) {
|
||||||
|
worker.removeEventListener("message", listener);
|
||||||
reject(event.data.error);
|
reject(event.data.error);
|
||||||
|
} else if (event.data?.hasOwnProperty("result")) {
|
||||||
|
worker.removeEventListener("message", listener);
|
||||||
|
resolve(event.data.result);
|
||||||
} else {
|
} else {
|
||||||
resolve(event.data?.result);
|
throw new Error("Unexpected message from worker: " + JSON.stringify(event.data));
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
worker.postMessage(code);
|
worker.postMessage(event);
|
||||||
}),
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
asyncRun: (code: string, stdout: (msg: string) => void, stderr: (msg: string) => void) =>
|
||||||
|
commonRequestResponse({type: "asyncRun", id: requestId++, code}, stdout, stderr),
|
||||||
|
mkdirTree: (path: string) => commonRequestResponse({type: "mkdirTree", id: requestId++, path}),
|
||||||
|
writeFile: (path: string, content: string) =>
|
||||||
|
commonRequestResponse({type: "writeFile", id: requestId++, path, content}),
|
||||||
|
makeSnapshot: () => commonRequestResponse({type: "makeSnapshot", id: requestId++}),
|
||||||
terminate: () => worker.terminate()
|
terminate: () => worker.terminate()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {loadPyodide, type PyodideInterface} from "pyodide";
|
import {loadPyodide, type PyodideAPI} from "pyodide";
|
||||||
|
|
||||||
let myLoadPyodide = (initOpts: Parameters<typeof loadPyodide>[0]) => loadPyodide({
|
let myLoadPyodide = (initOpts: Parameters<typeof loadPyodide>[0]) => loadPyodide({
|
||||||
...initOpts,
|
...initOpts,
|
||||||
@@ -10,24 +10,74 @@ let myLoadPyodide = (initOpts: Parameters<typeof loadPyodide>[0]) => loadPyodide
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let pyodideReadyPromise: Promise<PyodideInterface> | null = null;
|
let pyodideReadyPromise: Promise<PyodideAPI> | null = null;
|
||||||
|
|
||||||
self.onmessage = async (event: MessageEvent<any>) => {
|
export type MessageEventDataIn = {
|
||||||
|
type: 'asyncRun';
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
} | {
|
||||||
|
type: 'mkdirTree';
|
||||||
|
id: number;
|
||||||
|
path: string;
|
||||||
|
} | {
|
||||||
|
type: 'writeFile';
|
||||||
|
id: number;
|
||||||
|
path: string;
|
||||||
|
content: string;
|
||||||
|
} | {
|
||||||
|
type: 'makeSnapshot';
|
||||||
|
id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.onmessage = async (event: MessageEvent<MessageEventDataIn>) => {
|
||||||
if (!pyodideReadyPromise) { // First message is always the init message
|
if (!pyodideReadyPromise) { // First message is always the init message
|
||||||
// If we haven't loaded Pyodide yet, do so now.
|
// If we haven't loaded Pyodide yet, do so now.
|
||||||
// This is a singleton, so we only load it once.
|
// This is a singleton, so we only load it once.
|
||||||
pyodideReadyPromise = myLoadPyodide(event.data as Parameters<typeof loadPyodide>[0]);
|
pyodideReadyPromise = myLoadPyodide(event.data as Parameters<typeof loadPyodide>[0]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// All other messages are code to run.
|
if (event.data.type === 'mkdirTree') {
|
||||||
let code = event.data as string;
|
// Create a directory tree in the Pyodide filesystem.
|
||||||
// make sure loading is done
|
const pyodide = await pyodideReadyPromise;
|
||||||
const pyodide = await pyodideReadyPromise;
|
try {
|
||||||
// Now load any packages we need, run the code, and send the result back.
|
await pyodide.FS.mkdirTree(event.data.path);
|
||||||
await pyodide.loadPackagesFromImports(code);
|
self.postMessage({id: event.data.id, result: true});
|
||||||
try {
|
} catch (error: any) {
|
||||||
self.postMessage({result: await pyodide.runPythonAsync(code)});
|
self.postMessage({id: event.data.id, error: error.message});
|
||||||
} catch (error: any) {
|
}
|
||||||
self.postMessage({error: error.message});
|
return;
|
||||||
|
} else if (event.data.type === 'writeFile') {
|
||||||
|
// Write a file to the Pyodide filesystem.
|
||||||
|
const pyodide = await pyodideReadyPromise;
|
||||||
|
try {
|
||||||
|
await pyodide.FS.writeFile(event.data.path, event.data.content);
|
||||||
|
self.postMessage({id: event.data.id, result: true});
|
||||||
|
} catch (error: any) {
|
||||||
|
self.postMessage({id: event.data.id, error: error.message});
|
||||||
|
}
|
||||||
|
} else if (event.data.type === 'asyncRun') {
|
||||||
|
let code = event.data.code;
|
||||||
|
// make sure loading is done
|
||||||
|
const pyodide = await pyodideReadyPromise;
|
||||||
|
// Now load any packages we need, run the code, and send the result back.
|
||||||
|
await pyodide.loadPackagesFromImports(code);
|
||||||
|
try {
|
||||||
|
self.postMessage({id: event.data.id, result: await pyodide.runPythonAsync(code)});
|
||||||
|
} catch (error: any) {
|
||||||
|
self.postMessage({id: event.data.id, error: error.message});
|
||||||
|
}
|
||||||
|
} else if (event.data.type === 'makeSnapshot') {
|
||||||
|
// Take a snapshot of the current Pyodide filesystem.
|
||||||
|
const pyodide = await pyodideReadyPromise;
|
||||||
|
try {
|
||||||
|
const snapshot = pyodide.makeMemorySnapshot();
|
||||||
|
self.postMessage({id: event.data.id, result: snapshot});
|
||||||
|
} catch (error: any) {
|
||||||
|
self.postMessage({id: event.data.id, error: error.message});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error("Unknown message type:", (event.data as any)?.type);
|
||||||
|
self.postMessage({id: (event.data as any)?.id, error: "Unknown message type: " + (event.data as any)?.type});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,163 +1,182 @@
|
|||||||
// Model management from the graphics side
|
// Model management from the graphics side
|
||||||
|
|
||||||
import type {MObject3D} from "./Selection.vue";
|
import type { MObject3D } from "./Selection.vue";
|
||||||
import type {Intersection} from "three";
|
import type { Intersection } from "three";
|
||||||
import {Box3} from "three";
|
import { Box3 } from "three";
|
||||||
import {extrasNameKey} from "../misc/gltf";
|
import { extrasNameKey } from "../misc/gltf";
|
||||||
|
|
||||||
/** Information about a single item in the selection */
|
/** Information about a single item in the selection */
|
||||||
export class SelectionInfo {
|
export class SelectionInfo {
|
||||||
/** The object which was (partially) selected */
|
/** The object which was (partially) selected */
|
||||||
object: MObject3D
|
object: MObject3D;
|
||||||
/** The type of the selection */
|
/** The type of the selection */
|
||||||
kind: 'face' | 'edge' | 'vertex'
|
kind: "face" | "edge" | "vertex";
|
||||||
/** Start and end indices of the primitives in the geometry */
|
/** Start and end indices of the primitives in the geometry */
|
||||||
indices: [number, number]
|
indices: [number, number];
|
||||||
|
|
||||||
constructor(object: MObject3D, kind: 'face' | 'edge' | 'vertex', indices: [number, number]) {
|
constructor(object: MObject3D, kind: "face" | "edge" | "vertex", indices: [number, number]) {
|
||||||
this.object = object;
|
this.object = object;
|
||||||
this.kind = kind;
|
this.kind = kind;
|
||||||
this.indices = indices;
|
this.indices = indices;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getObjectName() {
|
public getObjectName() {
|
||||||
return this.object.userData[extrasNameKey];
|
return this.object.userData[extrasNameKey];
|
||||||
}
|
}
|
||||||
|
|
||||||
public matches(object: MObject3D) {
|
public matches(object: MObject3D) {
|
||||||
return this.getObjectName() === object.userData[extrasNameKey] &&
|
return (
|
||||||
(this.kind === 'face' && (object.type === 'Mesh' || object.type === 'SkinnedMesh') ||
|
this.getObjectName() === object.userData[extrasNameKey] &&
|
||||||
this.kind === 'edge' && (object.type === 'Line' || object.type === 'LineSegments') ||
|
((this.kind === "face" && (object.type === "Mesh" || object.type === "SkinnedMesh")) ||
|
||||||
this.kind === 'vertex' && object.type === 'Points')
|
(this.kind === "edge" && (object.type === "Line" || object.type === "LineSegments")) ||
|
||||||
}
|
(this.kind === "vertex" && object.type === "Points"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public getKey() {
|
public getKey() {
|
||||||
return this.object.uuid + this.kind + this.indices[0].toFixed() + this.indices[1].toFixed();
|
return this.object.uuid + this.kind + this.indices[0].toFixed() + this.indices[1].toFixed();
|
||||||
}
|
}
|
||||||
|
|
||||||
public getBox(): Box3 {
|
public getBox(): Box3 {
|
||||||
let index = this.object.geometry.index || {getX: (i: number) => i};
|
let index = this.object.geometry.index || { getX: (i: number) => i };
|
||||||
let pos = this.object.geometry.getAttribute('position');
|
let pos = this.object.geometry.getAttribute("position");
|
||||||
let min = [Infinity, Infinity, Infinity];
|
let min = [Infinity, Infinity, Infinity];
|
||||||
let max = [-Infinity, -Infinity, -Infinity];
|
let max = [-Infinity, -Infinity, -Infinity];
|
||||||
for (let i = this.indices[0]; i < this.indices[1]; i++) {
|
for (let i = this.indices[0]; i < this.indices[1]; i++) {
|
||||||
let vertIndex = index!.getX(i);
|
let vertIndex = index!.getX(i);
|
||||||
let x = pos.getX(vertIndex);
|
let x = pos.getX(vertIndex);
|
||||||
let y = pos.getY(vertIndex);
|
let y = pos.getY(vertIndex);
|
||||||
let z = pos.getZ(vertIndex);
|
let z = pos.getZ(vertIndex);
|
||||||
min[0] = Math.min(min[0], x);
|
min[0] = Math.min(min[0] ?? Infinity, x);
|
||||||
min[1] = Math.min(min[1], y);
|
min[1] = Math.min(min[1] ?? Infinity, y);
|
||||||
min[2] = Math.min(min[2], z);
|
min[2] = Math.min(min[2] ?? Infinity, z);
|
||||||
max[0] = Math.max(max[0], x);
|
max[0] = Math.max(max[0] ?? -Infinity, x);
|
||||||
max[1] = Math.max(max[1], y);
|
max[1] = Math.max(max[1] ?? -Infinity, y);
|
||||||
max[2] = Math.max(max[2], z);
|
max[2] = Math.max(max[2] ?? -Infinity, z);
|
||||||
}
|
|
||||||
return new Box3().setFromArray([...min, ...max]);
|
|
||||||
}
|
}
|
||||||
|
return new Box3().setFromArray([...min, ...max]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hitToSelectionInfo(hit: Intersection<MObject3D>): SelectionInfo | null {
|
export function hitToSelectionInfo(hit: Intersection<MObject3D>): SelectionInfo | null {
|
||||||
let kind = hit.object.type;
|
let kind = hit.object.type;
|
||||||
if (kind == 'Mesh' || kind == 'SkinnedMesh') {
|
if (kind == "Mesh" || kind == "SkinnedMesh") {
|
||||||
let indices = hitFaceTriangleIndices(hit);
|
let indices = hitFaceTriangleIndices(hit);
|
||||||
if (indices === null) return null;
|
if (indices === null) return null;
|
||||||
return new SelectionInfo(hit.object, 'face', indices);
|
return new SelectionInfo(hit.object, "face", indices);
|
||||||
} else if (kind == 'Line' || kind == 'LineSegments') {
|
} else if (kind == "Line" || kind == "LineSegments") {
|
||||||
// Select raw lines, not the wide meshes representing them
|
// Select raw lines, not the wide meshes representing them
|
||||||
// This is because the indices refer to the raw lines, not the wide meshes
|
// This is because the indices refer to the raw lines, not the wide meshes
|
||||||
// Furthermore, this allows better "fuzzy" raycasting logic
|
// Furthermore, this allows better "fuzzy" raycasting logic
|
||||||
let indices = hitEdgePointIndices(hit);
|
let indices = hitEdgePointIndices(hit);
|
||||||
if (indices === null) return null;
|
if (indices === null) return null;
|
||||||
return new SelectionInfo(hit.object, 'edge', indices);
|
return new SelectionInfo(hit.object, "edge", indices);
|
||||||
} else if (kind == 'Points') {
|
} else if (kind == "Points") {
|
||||||
if (hit.index === undefined) return null;
|
if (hit.index === undefined) return null;
|
||||||
return new SelectionInfo(hit.object, 'vertex', [hit.index, hit.index + 1]);
|
return new SelectionInfo(hit.object, "vertex", [hit.index, hit.index + 1]);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hitFaceTriangleIndices(hit: Intersection<MObject3D>): [number, number] | null {
|
function hitFaceTriangleIndices(hit: Intersection<MObject3D>): [number, number] | null {
|
||||||
let faceTrianglesEnd = hit?.object?.geometry?.userData?.face_triangles_end;
|
let faceTrianglesEnd = hit?.object?.geometry?.userData?.face_triangles_end;
|
||||||
if (!hit.faceIndex) return null;
|
if (!hit.faceIndex) return null;
|
||||||
if (!faceTrianglesEnd) { // Fallback to selecting the whole imported mesh
|
if (!faceTrianglesEnd) {
|
||||||
//console.log("No face_triangles_end found, selecting the whole mesh");
|
// Fallback to selecting the whole imported mesh
|
||||||
return [0, (hit.object.geometry.index ?? hit.object.geometry.attributes.position).count];
|
//console.log("No face_triangles_end found, selecting the whole mesh");
|
||||||
} else { // Normal CAD model
|
return [0, (hit.object.geometry.index ?? hit.object.geometry.attributes.position)?.count ?? 0];
|
||||||
let rawIndex = hit.faceIndex * 3; // Faces are triangles with 3 indices
|
} else {
|
||||||
for (let i = 0; i < faceTrianglesEnd.length; i++) {
|
// Normal CAD model
|
||||||
let faceSwapIndex = faceTrianglesEnd[i]
|
let rawIndex = hit.faceIndex * 3; // Faces are triangles with 3 indices
|
||||||
if (rawIndex < faceSwapIndex) {
|
for (let i = 0; i < faceTrianglesEnd.length; i++) {
|
||||||
let start = i === 0 ? 0 : faceTrianglesEnd[i - 1];
|
let faceSwapIndex = faceTrianglesEnd[i];
|
||||||
return [start, faceTrianglesEnd[i]];
|
if (rawIndex < faceSwapIndex) {
|
||||||
}
|
let start = i === 0 ? 0 : faceTrianglesEnd[i - 1];
|
||||||
}
|
return [start, faceTrianglesEnd[i]];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null;
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function hitEdgePointIndices(hit: Intersection<MObject3D>): [number, number] | null {
|
function hitEdgePointIndices(hit: Intersection<MObject3D>): [number, number] | null {
|
||||||
let edgePointsEnd = hit?.object?.geometry?.userData?.edge_points_end;
|
let edgePointsEnd = hit?.object?.geometry?.userData?.edge_points_end;
|
||||||
if (!edgePointsEnd || hit.index === undefined) return null;
|
if (!edgePointsEnd || hit.index === undefined) return null;
|
||||||
let rawIndex = hit.index; // Faces are triangles with 3 indices
|
let rawIndex = hit.index; // Faces are triangles with 3 indices
|
||||||
for (let i = 0; i < edgePointsEnd.length; i++) {
|
for (let i = 0; i < edgePointsEnd.length; i++) {
|
||||||
let edgeSwapIndex = edgePointsEnd[i]
|
let edgeSwapIndex = edgePointsEnd[i];
|
||||||
if (rawIndex < edgeSwapIndex) {
|
if (rawIndex < edgeSwapIndex) {
|
||||||
let start = i === 0 ? 0 : edgePointsEnd[i - 1];
|
let start = i === 0 ? 0 : edgePointsEnd[i - 1];
|
||||||
return [start, edgePointsEnd[i]];
|
return [start, edgePointsEnd[i]];
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return null;
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function applyColor(selInfo: SelectionInfo, colorAttribute: any, color: [number, number, number, number]): [number, number, number, number] {
|
function applyColor(
|
||||||
let index = selInfo.object.geometry.index
|
selInfo: SelectionInfo,
|
||||||
let prevColor: [number, number, number, number] | null = null;
|
colorAttribute: any,
|
||||||
if (colorAttribute !== undefined) {
|
color: [number, number, number, number],
|
||||||
for (let i = selInfo.indices[0]; i < selInfo.indices[1]; i++) {
|
): [number, number, number, number] {
|
||||||
let vertIndex = index!.getX(i);
|
let index = selInfo.object.geometry.index;
|
||||||
if (prevColor === null) prevColor = [colorAttribute.getX(vertIndex), colorAttribute.getY(vertIndex), colorAttribute.getZ(vertIndex), colorAttribute.getW(vertIndex)];
|
let prevColor: [number, number, number, number] | null = null;
|
||||||
colorAttribute.setXYZW(vertIndex, color[0], color[1], color[2], color[3]);
|
if (colorAttribute !== undefined) {
|
||||||
}
|
for (let i = selInfo.indices[0]; i < selInfo.indices[1]; i++) {
|
||||||
colorAttribute.needsUpdate = true;
|
let vertIndex = index!.getX(i);
|
||||||
if (selInfo.object.userData.niceLine !== undefined) {
|
if (prevColor === null)
|
||||||
// Need to update the color of the nice line as well
|
prevColor = [
|
||||||
let indexAttribute = selInfo.object.geometry.index!!;
|
colorAttribute.getX(vertIndex),
|
||||||
let allNewColors = [];
|
colorAttribute.getY(vertIndex),
|
||||||
for (let i = 0; i < indexAttribute.count; i++) {
|
colorAttribute.getZ(vertIndex),
|
||||||
if (indexAttribute.getX(i) >= selInfo.indices[0] && indexAttribute.getX(i) < selInfo.indices[1]) {
|
colorAttribute.getW(vertIndex),
|
||||||
allNewColors.push(color[0], color[1], color[2]);
|
];
|
||||||
} else {
|
colorAttribute.setXYZW(vertIndex, color[0], color[1], color[2], color[3]);
|
||||||
allNewColors.push(colorAttribute.getX(indexAttribute.getX(i)), colorAttribute.getY(indexAttribute.getX(i)), colorAttribute.getZ(indexAttribute.getX(i)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
selInfo.object.userData.niceLine.geometry.setColors(allNewColors);
|
|
||||||
for (let attribute of Object.values(selInfo.object.userData.niceLine.geometry.attributes)) {
|
|
||||||
(attribute as any).needsUpdate = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else { // Fallback to tinting the whole mesh for imported models
|
|
||||||
//console.log("No color attribute found, tinting the whole mesh")
|
|
||||||
let tmpPrevColor = selInfo.object.material.color;
|
|
||||||
prevColor = [tmpPrevColor.r, tmpPrevColor.g, tmpPrevColor.b, 1];
|
|
||||||
selInfo.object.material.color.setRGB(color[0], color[1], color[2]);
|
|
||||||
selInfo.object.material.needsUpdate = true;
|
|
||||||
}
|
}
|
||||||
return prevColor!;
|
colorAttribute.needsUpdate = true;
|
||||||
|
if (selInfo.object.userData.niceLine !== undefined) {
|
||||||
|
// Need to update the color of the nice line as well
|
||||||
|
let indexAttribute = selInfo.object.geometry.index!!;
|
||||||
|
let allNewColors = [];
|
||||||
|
for (let i = 0; i < indexAttribute.count; i++) {
|
||||||
|
if (indexAttribute.getX(i) >= selInfo.indices[0] && indexAttribute.getX(i) < selInfo.indices[1]) {
|
||||||
|
allNewColors.push(color[0], color[1], color[2]);
|
||||||
|
} else {
|
||||||
|
allNewColors.push(
|
||||||
|
colorAttribute.getX(indexAttribute.getX(i)),
|
||||||
|
colorAttribute.getY(indexAttribute.getX(i)),
|
||||||
|
colorAttribute.getZ(indexAttribute.getX(i)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selInfo.object.userData.niceLine.geometry.setColors(allNewColors);
|
||||||
|
for (let attribute of Object.values(selInfo.object.userData.niceLine.geometry.attributes)) {
|
||||||
|
(attribute as any).needsUpdate = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback to tinting the whole mesh for imported models
|
||||||
|
//console.log("No color attribute found, tinting the whole mesh")
|
||||||
|
let tmpPrevColor = selInfo.object.material.color;
|
||||||
|
prevColor = [tmpPrevColor.r, tmpPrevColor.g, tmpPrevColor.b, 1];
|
||||||
|
selInfo.object.material.color.setRGB(color[0], color[1], color[2]);
|
||||||
|
selInfo.object.material.needsUpdate = true;
|
||||||
|
}
|
||||||
|
return prevColor!;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function highlight(selInfo: SelectionInfo): void {
|
export function highlight(selInfo: SelectionInfo): void {
|
||||||
// Update the color of all the triangles in the face
|
// Update the color of all the triangles in the face
|
||||||
let geometry = selInfo.object.geometry;
|
let geometry = selInfo.object.geometry;
|
||||||
let colorAttr = selInfo.object.geometry.getAttribute('color');
|
let colorAttr = selInfo.object.geometry.getAttribute("color");
|
||||||
geometry.userData.savedColor = geometry.userData.savedColor || {};
|
geometry.userData.savedColor = geometry.userData.savedColor || {};
|
||||||
geometry.userData.savedColor[selInfo.getKey()] = applyColor(selInfo, colorAttr, [1.0, 0.0, 0.0, 1.0]);
|
geometry.userData.savedColor[selInfo.getKey()] = applyColor(selInfo, colorAttr, [1.0, 0.0, 0.0, 1.0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function highlightUndo(selInfo: SelectionInfo): void {
|
export function highlightUndo(selInfo: SelectionInfo): void {
|
||||||
// Update the color of all the triangles in the face
|
// Update the color of all the triangles in the face
|
||||||
let geometry = selInfo.object.geometry;
|
let geometry = selInfo.object.geometry;
|
||||||
let colorAttr = selInfo.object.geometry.getAttribute('color');
|
let colorAttr = selInfo.object.geometry.getAttribute("color");
|
||||||
let savedColor = geometry.userData.savedColor[selInfo.getKey()];
|
let savedColor = geometry.userData.savedColor[selInfo.getKey()];
|
||||||
applyColor(selInfo, colorAttr, savedColor);
|
applyColor(selInfo, colorAttr, savedColor);
|
||||||
delete geometry.userData.savedColor[selInfo.getKey()];
|
delete geometry.userData.savedColor[selInfo.getKey()];
|
||||||
}
|
}
|
||||||
|
|||||||
91
frontend/tools/upload-file.ts
Normal file
91
frontend/tools/upload-file.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
//@ts-expect-error
|
||||||
|
import encryptCode from "tanmayo7lock?raw";
|
||||||
|
|
||||||
|
function encrypt(msg: string, secret: string = "hudfhgd8fghdfgh3uhuifdgh"): string {
|
||||||
|
let exports: any = {};
|
||||||
|
eval(encryptCode.replace("exports.encrypt = encrypt;", "exports.LargeDataCrypto = LargeDataCrypto;\nexports.encrypt = encrypt;"));
|
||||||
|
return exports.LargeDataCrypto.encrypt(msg, secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function check(lockerName: string) {
|
||||||
|
const fileUrl = `https://vouz-backend.onrender.com/api/check_key`;
|
||||||
|
const response = await fetch(fileUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({name: encrypt(lockerName), key: encrypt(lockerName)}),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`Failed to get file URL: ${response.status} ${response.statusText} -- ${await response.text()}`);
|
||||||
|
const status = await response.json();
|
||||||
|
return {response, status};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadFile(name: string, data: Uint8Array): Promise<string> {
|
||||||
|
// "Free" storage, let's see how long it lasts...
|
||||||
|
// Create a locker
|
||||||
|
const lockerUrl = `https://vouz-backend.onrender.com/api/locker`
|
||||||
|
const lockerName = `yacv-pg-${name}-${Date.now()}`; // Unique locker name
|
||||||
|
let responsePromise = fetch(lockerUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({name: encrypt(lockerName), passkey: encrypt(lockerName)}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// The previous request never answers 🤮
|
||||||
|
responsePromise.then((response) => console.warn(`Locker creation response: ${response.status} ${response.statusText} -- ${response.headers.get('Content-Type')}`));
|
||||||
|
// Instead, poll the check endpoint until the locker is created
|
||||||
|
let i: number;
|
||||||
|
for (i = 0; i < 10; i++) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 250)); // Wait a bit before checking
|
||||||
|
try {
|
||||||
|
let {status} = await check(lockerName);
|
||||||
|
if (status && status.data && status.data.length == 0) break // Locker is created
|
||||||
|
} catch (e) { // Ignore errors, they will be thrown later
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (i >= 10) throw new Error(`Failed to create locker after 10 attempts: ${lockerName}`);
|
||||||
|
|
||||||
|
// Upload file to the locker
|
||||||
|
const uploadUrl = `https://vouz-backend.onrender.com/api/upload`;
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', new Blob([data as ArrayBufferView<ArrayBuffer>], {type: 'application/octet-stream'}), name);
|
||||||
|
formData.append("name", encrypt(lockerName));
|
||||||
|
formData.append("passkey", encrypt(lockerName));
|
||||||
|
const response = await fetch(uploadUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
})
|
||||||
|
if (!response.ok) throw new Error(`Failed to upload file: ${response.status} ${response.statusText} -- ${await response.text()}`);
|
||||||
|
|
||||||
|
// Fake URL for retrieveFile to work
|
||||||
|
return "https://vouz.tech#name=" + encodeURIComponent(name) + "&locker=" + encodeURIComponent(lockerName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Given any URL, it retrieves the file, with custom code for the vouz.tech locker. */
|
||||||
|
export async function retrieveFile(url: string): Promise<Response> {
|
||||||
|
let realUrl = url;// Normal fetch if the URL is not a vouz.tech locker URL
|
||||||
|
if (url.indexOf("https://vouz.tech#") !== -1) { // Check if the URL is a vouz.tech locker URL
|
||||||
|
// Parse the URL to get the locker name and file name
|
||||||
|
const urlObj = new URL(url);
|
||||||
|
const hashParams = new URLSearchParams(urlObj.hash.slice(1)); // Remove the leading '#'
|
||||||
|
const lockerName = hashParams.get('locker') || (() => {
|
||||||
|
throw new Error("Locker name not found in URL hash")
|
||||||
|
})();
|
||||||
|
const name = hashParams.get('name') || (() => {
|
||||||
|
throw new Error("File name not found in URL hash")
|
||||||
|
})();
|
||||||
|
// Get the URL of the uploaded file
|
||||||
|
let {status} = await check(lockerName);
|
||||||
|
if (!status || !status.data || status.data.length == 0 || !status.data[0].url) {
|
||||||
|
throw new Error(`No file URL found in response: ${JSON.stringify(status)}`);
|
||||||
|
}
|
||||||
|
console.debug("File access requested successfully, URL:", status.data[0].url);
|
||||||
|
realUrl = "https://corsproxy.io/?url=" + status.data[0].url + "#name=" + encodeURIComponent(name) + "&locker=" + encodeURIComponent(lockerName);
|
||||||
|
}
|
||||||
|
return await fetch(realUrl);
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ const renderer = ref<Renderer | null>(null);
|
|||||||
const controls = ref<SmoothControls | null>(null);
|
const controls = ref<SmoothControls | null>(null);
|
||||||
|
|
||||||
const sett = ref<any | null>(null);
|
const sett = ref<any | null>(null);
|
||||||
(async () => sett.value = await settings())();
|
(async () => sett.value = await settings)();
|
||||||
|
|
||||||
let lastCameraTargetPosition: Vector3 | undefined = undefined;
|
let lastCameraTargetPosition: Vector3 | undefined = undefined;
|
||||||
let lastCameraZoom: number | undefined = undefined;
|
let lastCameraZoom: number | undefined = undefined;
|
||||||
@@ -161,9 +161,9 @@ function addLine3D(p1: Vector3, p2: Vector3, centerText?: string, lineAttrs: { [
|
|||||||
function removeLine3D(id: number): boolean {
|
function removeLine3D(id: number): boolean {
|
||||||
if (!scene.value || !(id in lines.value)) return false;
|
if (!scene.value || !(id in lines.value)) return false;
|
||||||
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_start'}));
|
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_start'}));
|
||||||
lines.value[id].startHotspot.parentElement?.remove()
|
lines.value[id]?.startHotspot.parentElement?.remove()
|
||||||
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_end'}));
|
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_end'}));
|
||||||
lines.value[id].endHotspot.parentElement?.remove()
|
lines.value[id]?.endHotspot.parentElement?.remove()
|
||||||
delete lines.value[id];
|
delete lines.value[id];
|
||||||
scene.value.queueRender() // Needed to update the hotspots
|
scene.value.queueRender() // Needed to update the hotspots
|
||||||
return true;
|
return true;
|
||||||
@@ -175,17 +175,17 @@ function onCameraChangeLine(lineId: number) {
|
|||||||
if (!(lineId in lines.value) || !(elem.value)) return // Silently ignore (not updated yet)
|
if (!(lineId in lines.value) || !(elem.value)) return // Silently ignore (not updated yet)
|
||||||
// Update start and end 2D positions
|
// Update start and end 2D positions
|
||||||
let {x: xB, y: yB} = elem.value.getBoundingClientRect();
|
let {x: xB, y: yB} = elem.value.getBoundingClientRect();
|
||||||
let {x, y} = lines.value[lineId].startHotspot.getBoundingClientRect();
|
let {x, y} = lines.value[lineId]?.startHotspot.getBoundingClientRect() ?? {x: 0, y: 0};
|
||||||
lines.value[lineId].start2D = [x - xB, y - yB];
|
if (lines.value[lineId]) lines.value[lineId].start2D = [x - xB, y - yB];
|
||||||
let {x: x2, y: y2} = lines.value[lineId].endHotspot.getBoundingClientRect();
|
let {x: x2, y: y2} = lines.value[lineId]?.endHotspot.getBoundingClientRect() ?? {x: 0, y: 0};
|
||||||
lines.value[lineId].end2D = [x2 - xB, y2 - yB];
|
if (lines.value[lineId]) lines.value[lineId].end2D = [x2 - xB, y2 - yB];
|
||||||
|
|
||||||
// Update the center text size if needed
|
// Update the center text size if needed
|
||||||
if (svg.value && lines.value[lineId].centerText && lines.value[lineId].centerTextSize[0] === 0) {
|
if (svg.value && lines.value[lineId]?.centerText && lines.value[lineId]?.centerTextSize[0] === 0) {
|
||||||
let text = svg.value.getElementsByClassName('line' + lineId + '_text')[0] as SVGTextElement | undefined;
|
let text = svg.value.getElementsByClassName('line' + lineId + '_text')[0] as SVGTextElement | undefined;
|
||||||
if (text) {
|
if (text) {
|
||||||
let bbox = text.getBBox();
|
let bbox = text.getBBox();
|
||||||
lines.value[lineId].centerTextSize = [bbox.width, bbox.height];
|
if (lines.value[lineId]) lines.value[lineId].centerTextSize = [bbox.width, bbox.height];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,76 +1,96 @@
|
|||||||
import {ModelViewerElement} from '@google/model-viewer';
|
import { ModelViewerElement } from "@google/model-viewer";
|
||||||
import {$scene} from "@google/model-viewer/lib/model-viewer-base";
|
import { $scene } from "@google/model-viewer/lib/model-viewer-base";
|
||||||
import {settings} from "../misc/settings.ts";
|
import { settings } from "../misc/settings.ts";
|
||||||
|
|
||||||
export let currentSceneRotation = 0; // radians, 0 is the default rotation
|
export let currentSceneRotation = 0; // radians, 0 is the default rotation
|
||||||
|
|
||||||
export async function setupLighting(modelViewer: ModelViewerElement) {
|
export async function setupLighting(modelViewer: ModelViewerElement) {
|
||||||
modelViewer[$scene].environmentIntensity = (await settings()).environmentIntensity;
|
modelViewer[$scene].environmentIntensity = (await settings).environmentIntensity;
|
||||||
// Code is mostly copied from the example at: https://modelviewer.dev/examples/stagingandcameras/#turnSkybox
|
// Code is mostly copied from the example at: https://modelviewer.dev/examples/stagingandcameras/#turnSkybox
|
||||||
let lastX: number;
|
let lastX: number;
|
||||||
let panning = false;
|
let panning = false;
|
||||||
let radiansPerPixel: number;
|
let radiansPerPixel: number;
|
||||||
|
|
||||||
const startPan = () => {
|
const startPan = () => {
|
||||||
const orbit = modelViewer.getCameraOrbit();
|
const orbit = modelViewer.getCameraOrbit();
|
||||||
const {radius} = orbit;
|
const { radius } = orbit;
|
||||||
radiansPerPixel = -1 * radius / modelViewer.getBoundingClientRect().height;
|
radiansPerPixel = (-1 * radius) / modelViewer.getBoundingClientRect().height;
|
||||||
modelViewer.interactionPrompt = 'none';
|
modelViewer.interactionPrompt = "none";
|
||||||
};
|
};
|
||||||
|
|
||||||
const updatePan = (thisX: number) => {
|
const updatePan = (thisX: number) => {
|
||||||
const delta = (thisX - lastX) * radiansPerPixel;
|
const delta = (thisX - lastX) * radiansPerPixel;
|
||||||
lastX = thisX;
|
lastX = thisX;
|
||||||
currentSceneRotation += delta;
|
currentSceneRotation += delta;
|
||||||
const orbit = modelViewer.getCameraOrbit();
|
const orbit = modelViewer.getCameraOrbit();
|
||||||
orbit.theta += delta;
|
orbit.theta += delta;
|
||||||
modelViewer.cameraOrbit = orbit.toString();
|
modelViewer.cameraOrbit = orbit.toString();
|
||||||
modelViewer.resetTurntableRotation(currentSceneRotation);
|
modelViewer.resetTurntableRotation(currentSceneRotation);
|
||||||
modelViewer.jumpCameraToGoal();
|
modelViewer.jumpCameraToGoal();
|
||||||
}
|
};
|
||||||
|
|
||||||
modelViewer.addEventListener('mousedown', (event) => {
|
modelViewer.addEventListener(
|
||||||
panning = event.metaKey || event.shiftKey;
|
"mousedown",
|
||||||
if (!panning)
|
(event) => {
|
||||||
return;
|
panning = event.metaKey || event.shiftKey;
|
||||||
|
if (!panning) return;
|
||||||
|
|
||||||
lastX = event.clientX;
|
lastX = event.clientX;
|
||||||
startPan();
|
startPan();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
}, true);
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
modelViewer.addEventListener('touchstart', (event) => {
|
modelViewer.addEventListener(
|
||||||
const {targetTouches, touches} = event;
|
"touchstart",
|
||||||
panning = targetTouches.length === 2 && targetTouches.length === touches.length;
|
(event) => {
|
||||||
if (!panning)
|
const { targetTouches, touches } = event;
|
||||||
return;
|
panning = targetTouches.length === 2 && targetTouches.length === touches.length;
|
||||||
|
if (!panning) return;
|
||||||
|
|
||||||
lastX = 0.5 * (targetTouches[0].clientX + targetTouches[1].clientX);
|
lastX = 0.5 * ((targetTouches[0]?.clientX ?? 0) + (targetTouches[1]?.clientX ?? 0));
|
||||||
startPan();
|
startPan();
|
||||||
}, true);
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
document.addEventListener('mousemove', (event) => {
|
document.addEventListener(
|
||||||
if (!panning)
|
"mousemove",
|
||||||
return;
|
(event) => {
|
||||||
|
if (!panning) return;
|
||||||
|
|
||||||
updatePan(event.clientX);
|
updatePan(event.clientX);
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
}, true);
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
modelViewer.addEventListener('touchmove', (event) => {
|
modelViewer.addEventListener(
|
||||||
if (!panning || event.targetTouches.length !== 2)
|
"touchmove",
|
||||||
return;
|
(event) => {
|
||||||
|
if (!panning || event.targetTouches.length !== 2) return;
|
||||||
|
|
||||||
const {targetTouches} = event;
|
const { targetTouches } = event;
|
||||||
const thisX = 0.5 * (targetTouches[0].clientX + targetTouches[1].clientX);
|
const thisX = 0.5 * ((targetTouches[0]?.clientX ?? 0) + (targetTouches[1]?.clientX ?? 0));
|
||||||
updatePan(thisX);
|
updatePan(thisX);
|
||||||
}, true);
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
document.addEventListener('mouseup', (event) => {
|
document.addEventListener(
|
||||||
panning = false;
|
"mouseup",
|
||||||
}, true);
|
(event) => {
|
||||||
|
panning = false;
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
modelViewer.addEventListener('touchend', (event) => {
|
modelViewer.addEventListener(
|
||||||
panning = false;
|
"touchend",
|
||||||
}, true);
|
(event) => {
|
||||||
}
|
panning = false;
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
17
package.json
17
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "yet-another-cad-viewer",
|
"name": "yet-another-cad-viewer",
|
||||||
"version": "0.9.7",
|
"version": "0.10.11",
|
||||||
"description": "",
|
"description": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"private": true,
|
"private": true,
|
||||||
@@ -24,10 +24,11 @@
|
|||||||
"@mdi/js": "^7.4.47",
|
"@mdi/js": "^7.4.47",
|
||||||
"@mdi/svg": "^7.4.47",
|
"@mdi/svg": "^7.4.47",
|
||||||
"js-base64": "^3.7.7",
|
"js-base64": "^3.7.7",
|
||||||
"monaco-editor": "^0.52.2",
|
"monaco-editor": "^0.55.0",
|
||||||
"pako": "^2.1.0",
|
"pako": "^2.1.0",
|
||||||
"pyodide": "^0.28.0",
|
"pyodide": "^0.29.0",
|
||||||
"three": "^0.178.0",
|
"tanmayo7lock": "^1.0.18",
|
||||||
|
"three": "^0.182.0",
|
||||||
"three-mesh-bvh": "^0.9.0",
|
"three-mesh-bvh": "^0.9.0",
|
||||||
"three-orientation-gizmo": "git+https://github.com/jrj2211/three-orientation-gizmo.git",
|
"three-orientation-gizmo": "git+https://github.com/jrj2211/three-orientation-gizmo.git",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
@@ -35,18 +36,18 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tsconfig/node20": "^20.1.4",
|
"@tsconfig/node20": "^20.1.4",
|
||||||
"@types/node": "^22.9.3",
|
"@types/node": "^24.0.0",
|
||||||
"@types/pako": "^2.0.3",
|
"@types/pako": "^2.0.3",
|
||||||
"@types/three": "^0.178.0",
|
"@types/three": "^0.182.0",
|
||||||
"@vitejs/plugin-vue": "^6.0.0",
|
"@vitejs/plugin-vue": "^6.0.0",
|
||||||
"@vitejs/plugin-vue-jsx": "^5.0.0",
|
"@vitejs/plugin-vue-jsx": "^5.0.0",
|
||||||
"@vue/tsconfig": "^0.7.0",
|
"@vue/tsconfig": "^0.8.0",
|
||||||
"buffer": "^5.5.0||^6.0.0",
|
"buffer": "^5.5.0||^6.0.0",
|
||||||
"commander": "^14.0.0",
|
"commander": "^14.0.0",
|
||||||
"generate-license-file": "^4.0.0",
|
"generate-license-file": "^4.0.0",
|
||||||
"npm-run-all2": "^8.0.0",
|
"npm-run-all2": "^8.0.0",
|
||||||
"terser": "^5.36.0",
|
"terser": "^5.36.0",
|
||||||
"typescript": "~5.8.0",
|
"typescript": "^5.9.2",
|
||||||
"vite": "^7.0.0",
|
"vite": "^7.0.0",
|
||||||
"vite-plugin-static-copy": "^3.1.1",
|
"vite-plugin-static-copy": "^3.1.1",
|
||||||
"vue-tsc": "^3.0.0"
|
"vue-tsc": "^3.0.0"
|
||||||
|
|||||||
1596
poetry.lock
generated
1596
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
|
|||||||
|
|
||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
name = "yacv-server"
|
name = "yacv-server"
|
||||||
version = "0.10.0-alpha.4"
|
version = "0.10.11"
|
||||||
description = "Yet Another CAD Viewer (server)"
|
description = "Yet Another CAD Viewer (server)"
|
||||||
authors = ["Yeicor <4929005+Yeicor@users.noreply.github.com>"]
|
authors = ["Yeicor <4929005+Yeicor@users.noreply.github.com>"]
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
@@ -20,15 +20,15 @@ build_frontend = "rm -rf yacv_server/frontend || true && yarn install && YACV_SM
|
|||||||
build_backend = "poetry build --format wheel"
|
build_backend = "poetry build --format wheel"
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
[tool.poetry.dependencies]
|
||||||
python = ">=3.10,<3.13" # Due to vtk transitive dependency of build123d -> cadquery-ocp -> vtk
|
python = ">=3.14,<3.15" # Due to vtk transitive dependency of build123d -> cadquery-ocp -> vtk
|
||||||
|
|
||||||
# CAD
|
# CAD
|
||||||
build123d = ">=0.9,<0.10"
|
build123d = ">=0.10,<0.11"
|
||||||
|
|
||||||
# Misc
|
# Misc
|
||||||
pygltflib = "^1.16.2"
|
pygltflib = "^1.16.2"
|
||||||
pillow = ">=10.2,<12.0"
|
pillow = ">=12,<12.1"
|
||||||
poetry-core = "==2.1.3"
|
poetry-core = "==2.2.1"
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
taskipy = "^1.14.1"
|
taskipy = "^1.14.1"
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ export default defineConfig({
|
|||||||
__APP_VERSION__: JSON.stringify(version),
|
__APP_VERSION__: JSON.stringify(version),
|
||||||
__APP_GIT_SHA__: JSON.stringify(execSync('git rev-parse HEAD').toString().trim()),
|
__APP_GIT_SHA__: JSON.stringify(execSync('git rev-parse HEAD').toString().trim()),
|
||||||
__APP_GIT_DIRTY__: JSON.stringify(execSync('git diff --quiet || echo dirty').toString().trim()),
|
__APP_GIT_DIRTY__: JSON.stringify(execSync('git diff --quiet || echo dirty').toString().trim()),
|
||||||
__YACV_SMALL_BUILD__: JSON.stringify(wantsSmallBuild),
|
__YACV_SMALL_BUILD__: JSON.stringify(wantsSmallBuild)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ def image_to_gltf(source: str | bytes, center: any, width: Optional[float] = Non
|
|||||||
# Handle arguments
|
# Handle arguments
|
||||||
if name is None:
|
if name is None:
|
||||||
if isinstance(source, str):
|
if isinstance(source, str):
|
||||||
name = os.path.basename(source)
|
name, _ = os.path.splitext(os.path.basename(source))
|
||||||
else:
|
else:
|
||||||
hasher = hashlib.md5()
|
hasher = hashlib.md5()
|
||||||
hasher.update(source)
|
hasher.update(source)
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ class HTTPHandler(SimpleHTTPRequestHandler):
|
|||||||
path = super().translate_path(path)
|
path = super().translate_path(path)
|
||||||
path = os.path.realpath(path) # Avoid symlink hacks
|
path = os.path.realpath(path) # Avoid symlink hacks
|
||||||
if self.directory: # Ensure proper subdirectory
|
if self.directory: # Ensure proper subdirectory
|
||||||
base = os.path.abspath(self.directory)
|
base = os.path.realpath(self.directory)
|
||||||
if not os.path.abspath(path).startswith(base):
|
if not path.startswith(base):
|
||||||
self.send_error(HTTPStatus.FORBIDDEN, "Path is not in the frontend directory")
|
self.send_error(HTTPStatus.FORBIDDEN, "Path is not in the frontend directory")
|
||||||
return ''
|
return ''
|
||||||
return path
|
return path
|
||||||
|
|||||||
@@ -141,7 +141,6 @@ class YACV:
|
|||||||
"""Initializes the YACV server"""
|
"""Initializes the YACV server"""
|
||||||
raw_protocol = os.getenv('YACV_PROTOCOL', 'http' if sys.platform != 'emscripten' else 'stderr').upper()
|
raw_protocol = os.getenv('YACV_PROTOCOL', 'http' if sys.platform != 'emscripten' else 'stderr').upper()
|
||||||
self.protocol = YACVProtocol[raw_protocol] if raw_protocol in YACVProtocol.__members__ else YACVProtocol.HTTP
|
self.protocol = YACVProtocol[raw_protocol] if raw_protocol in YACVProtocol.__members__ else YACVProtocol.HTTP
|
||||||
self.protocol = YACVProtocol.STDERR
|
|
||||||
self.server_thread = None
|
self.server_thread = None
|
||||||
self.server = None
|
self.server = None
|
||||||
self.startup_complete = threading.Event()
|
self.startup_complete = threading.Event()
|
||||||
|
|||||||
Reference in New Issue
Block a user