Commit aa2ed718 authored by Matthias Betz's avatar Matthias Betz
Browse files

initial release

parent 6edaad85
Showing with 10742 additions and 84 deletions
+10742 -84
// eslint-disable-next-line import/no-extraneous-dependencies
// const sharedLib = require('eslint-config-airbnb-typescript/lib/shared.js');
module.exports = {
root: true,
extends: ['@vcsuite/eslint-config/vue-ts'],
env: {
node: true,
},
rules: {
'no-restricted-syntax': 'off',
},
overrides: [
{
files: ['*.ts', '*.vue'],
parserOptions: {
project: ['./tsconfig.json', './tests/tsconfig.json'],
},
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
},
},
],
ignorePatterns: ['dist/', 'node_modules/'],
};
.gitignore 0 → 100644
# Created by https://www.toptal.com/developers/gitignore/api/vue,vuejs,visualstudiocode,node
# Edit at https://www.toptal.com/developers/gitignore?templates=vue,vuejs,visualstudiocode,node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### Vue ###
# gitignore template for Vue.js projects
#
# Recommended template: Node.gitignore
# TODO: where does this rule come from?
docs/_book
# TODO: where does this rule come from?
test/
### Vuejs ###
# Recommended template: Node.gitignore
dist/
npm-debug.log
yarn-error.log
# End of https://www.toptal.com/developers/gitignore/api/vue,vuejs,visualstudiocode,node
.npmrc 0 → 100644
registry=https://registry.npmjs.org
dist/
plugin-assets/
public/
test-report.xml
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# test output
.nyc_output
coverage
# static output
docs
# index.html (prettier does not take modern html 5 rules that closing tags for void elements should be avoided)
assets/index.html
# v1.0.0
Initial Release
\ No newline at end of file
# SmartVillages2
## Plugin Configuration
## Getting started
The plugin has two configuration properties that can be configured in the plugin configuration of the map.
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
The converter service can be found [here](https://transfer.hft-stuttgart.de/gitlab/lgl/smartvillages2-converter).
The instructions property can be a link to a pdf or html or anything else.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://transfer.hft-stuttgart.de/gitlab/lgl/smartvillages2.git
git branch -M master
git push -uf origin master
```
## Integrate with your tools
- [ ] [Set up project integrations](https://transfer.hft-stuttgart.de/gitlab/lgl/smartvillages2/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
"plugins": [
{
"name": "smartvillages2",
"entry": "plugins/smartvillages2/index.js?mapVersion=5.1.8",
"convertLink": "<Link to the converter service>",
"instructions": "<Link to a instructions document>"
}
],
```
\ No newline at end of file
This diff is collapsed.
{
"name": "smartvillages2",
"version": "1.0.0",
"description": "Plugin des SmartVillages2 Projekts",
"type": "module",
"main": "src/index.js",
"scripts": {
"prepublishOnly": "vcmplugin build",
"build": "vcmplugin build",
"bundle": "vcmplugin bundle",
"start": "vcmplugin serve",
"preview": "vcmplugin preview",
"buildStagingApp": "vcmplugin buildStagingApp",
"lint:js": "eslint . --ext .vue,.js,.cjs,.mjs,.ts,.cts,.mts",
"lint:prettier": "prettier --check .",
"lint": "npm run lint:js && npm run lint:prettier",
"format": "prettier --write --list-different . && npm run lint:js -- --fix",
"test": "vitest",
"coverage": "vitest run --coverage"
},
"author": "Matthias Betz <matthias.betz@hft-stuttgart.de>",
"license": "AGPLv3",
"keywords": [
"vcmap",
"plugin"
],
"files": [
"src/",
"dist/",
"plugin-assets/",
"LICENSE.md",
"README.md",
"CHANGELOG.md"
],
"exports": {
".": "src/index.js",
"./dist": "./dist/index.js"
},
"eslintIgnore": [
"node_modules",
"dist",
"plugin-assets"
],
"eslintConfig": {
"root": true,
"extends": "@vcsuite/eslint-config/vue"
},
"prettier": "@vcsuite/eslint-config/prettier.js",
"dependencies": {
"three": "^0.169.0"
},
"peerDependencies": {
"@vcmap-cesium/engine": "^4.0.3",
"@vcmap/core": "^5.3.0",
"@vcmap/ui": "^5.2.4",
"ol": "^7.5.2"
},
"devDependencies": {
"@vcmap/plugin-cli": "^3.1.2",
"@vcsuite/eslint-config": "^3.0.7",
"@vitest/coverage-v8": "^1.6.0",
"jest-canvas-mock": "^2.5.2",
"jsdom": "^24.1.0",
"resize-observer-polyfill": "^1.5.1",
"vitest": "^1.6.0"
},
"mapVersion": "^5.0"
}
import { ToolboxType, WindowSlot, NotificationType } from '@vcmap/ui';
import { Cesium3DTileStyle, Math as CMath, ConstantProperty, Transforms, HeadingPitchRoll, Cesium3DTileset } from '@vcmap-cesium/engine';
import { AbstractInteraction, EventType } from '@vcmap/core';
import { name, version, mapVersion } from '../package.json';
import BIMOptions, { windowId } from './upload.vue';
import objectList, {} from './objectList.vue';
let url;
let model;
let conditions = [[true, true]];
let activeMouseEvent;
let currentMousePosition;
let heightDif = 0;
const hpRollMap = new Map();
let placedModels = [];
let hpRoll;
let app;
const hidingFeatures = [];
const hidingListener = function(tile) {
let allHidden = true;
for (const featureToHide of hidingFeatures) {
if (featureToHide.loops < 3) {
allHidden = false;
const feature = tile.content.getFeature(featureToHide.id);
if (feature !== undefined) {
app.maps.activeMap.layerCollection.globalHider.addFeature("manual", feature);
app.maps.activeMap.layerCollection.globalHider.hideObjects(["manual"]);
featureToHide.loops++;
}
}
}
if (allHidden) {
const primitives = app.maps.activeMap.getScene().primitives;
for (let i = 0; i < primitives.length; i++) {
const tileSet = primitives.get(i);
if (!tileSet instanceof Cesium3DTileset) {
continue;
}
tileSet.tileVisible.removeEventListener(hidingListener);
}
}
};
function updateHideCondition(gmlId) {
conditions.unshift(['${gml_id} === "' + gmlId + '"', false]);
}
function saveObjects() {
const outputObject = {};
const outputArray = [];
for (const m of placedModels) {
const tempRoll = hpRollMap.get(m.model);
let heading = 0;
if (tempRoll !== undefined) {
heading = tempRoll.heading;
}
outputArray.push({
name: m.name,
position: m.model.position.getValue(),
heading: heading,
});
}
outputObject.placedObjects = outputArray;
const hiddenObjects = [];
for (const o of hidingFeatures) {
hiddenObjects.push(o.id);
}
outputObject.hiddenObjects = hiddenObjects;
let textData = JSON.stringify(outputObject);
let blobData = new Blob([textData], {type: "application/json"});
saveFile('ObjektPlatzierung.json', window.URL.createObjectURL(blobData));
}
function saveFile(fileName, urlFile){
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
a.href = urlFile;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(urlFile);
a.remove();
}
function setupModel(vcsApp, windowPos, url, name) {
const vcMap = vcsApp.maps.activeMap;
const scene = vcMap.getScene();
const ray = scene.camera.getPickRay(windowPos);
const center = scene.globe.pick(ray, scene);
heightDif = 0;
// Add the model to the viewer
model = vcMap.getEntities().add({
name: name,
position: center,
model: {
uri: url,
show: true,
},
});
placedModels.push({
model: model,
name: name,
});
vcMap.requestRender();
const interaction = new MoveInteraction();
interaction.setActive(EventType.CLICKMOVE);
activeMouseEvent = vcsApp.maps.eventHandler.addExclusiveInteraction(interaction, () => {});
}
function removePlacedModel(modelToBeRemoved) {
placedModels = placedModels.filter(function(m) {
return m.model !== modelToBeRemoved;
});
}
class MoveInteraction extends AbstractInteraction {
async pipe(event) {
if (event.pointerEvent === 2) {
if (activeMouseEvent !== undefined) {
activeMouseEvent();
}
} else if (event.pointerEvent === 3 && model !== undefined) {
const cesiumMap = event.map;
const scene = cesiumMap.getScene();
const pickResult = scene.globe.pick(
event.ray,
scene
);
pickResult.z = pickResult.z + heightDif;
model.position.setValue(pickResult);
}
return event;
}
}
class HeightInteraction extends AbstractInteraction {
async pipe(event) {
// prevent the event from beeing passed to the next interaction within the chain
event.stopPropagation = false;
if (model === undefined) {
if (activeMouseEvent !== undefined) {
activeMouseEvent();
}
return event;
}
if (event.pointerEvent === 2) {
if (activeMouseEvent !== undefined) {
currentMousePosition = undefined;
activeMouseEvent();
return event;
}
} else if (event.pointerEvent === 3) {
if (currentMousePosition === undefined) {
currentMousePosition = [event.windowPosition.x, event.windowPosition.y];
return event;
}
const dif = event.windowPosition.y - currentMousePosition[1];
if (dif === 0) {
return event;
}
heightDif = heightDif - (dif / 50);
let pos = model.position.getValue();
currentMousePosition = [event.windowPosition.x, event.windowPosition.y];
pos.z = pos.z - (dif / 50);
model.position.setValue(pos);
}
return event;
}
}
class RotateAction extends AbstractInteraction {
async pipe(event) {
// prevent the event from beeing passed to the next interaction within the chain
event.stopPropagation = false;
if (model === undefined) {
if (activeMouseEvent !== undefined) {
activeMouseEvent();
}
return event;
}
if (event.pointerEvent === 2) {
if (activeMouseEvent !== undefined) {
currentMousePosition = undefined;
activeMouseEvent();
return event;
}
} else if (event.pointerEvent === 3) {
if (currentMousePosition === undefined) {
currentMousePosition = [event.windowPosition.x, event.windowPosition.y];
return event;
}
const dif = event.windowPosition.x - currentMousePosition[0];
if (dif === 0) {
return event;
}
currentMousePosition = [event.windowPosition.x, event.windowPosition.y];
const modelPos = model.position.getValue();
const deltaRadians = CMath.toRadians(dif / 3);
hpRoll.heading += deltaRadians;
if (hpRoll.heading > CMath.TWO_PI) {
hpRoll.heading -= CMath.TWO_PI;
}
if (hpRoll.heading < 0.0) {
hpRoll.heading += CMath.TWO_PI;
}
const orientation = new ConstantProperty(Transforms.headingPitchRollQuaternion(modelPos, hpRoll));
model.orientation = orientation;
}
return event;
}
}
/**
* @param {PluginConfig} config - the configuration of this plugin instance, passed in from the app.
* @param {string} baseUrl - the absolute URL from which the plugin was loaded (without filename, ending on /)
* @returns {import("@vcmap/ui/src/vcsUiApp").VcsPlugin<PluginConfig, PluginState>}
*/
export default function smartVillagesPlugin(config, baseUrl) {
const pluginState = {
files: [],
objects: [],
};
return {
get name() {
return name;
},
get version() {
return version;
},
get mapVersion() {
return mapVersion;
},
pluginState,
setupModel,
saveObjects,
loadObjects(app) {
// Create an input element
const inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = ".json, .txt";
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", e => {
const fileInput = e.target;
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async readerEvent => {
const content = readerEvent.target.result;
const objects = JSON.parse(content);
const vcMap = app.maps.activeMap;
for (const loadingObject of objects.placedObjects) {
let objectUrl = undefined;
for (const loadedObject of pluginState.objects) {
if (loadedObject.name === loadingObject.name) {
objectUrl = loadedObject.url;
break;
}
}
if (objectUrl === undefined) {
app.notifier.add({
type: NotificationType.ERROR,
message: "Objekt mit dem namen: " + loadingObject.name + " konnte nicht in den geladenen Objekten gefunden werden. Konfiguration konnte nicht vollständig geladen werden.",
});
// abort
return;
}
// Add the model to the viewer
model = vcMap.getEntities().add({
name: loadingObject.name,
position: loadingObject.position,
model: {
uri: objectUrl,
show: true,
},
});
const roll = new HeadingPitchRoll();
hpRollMap.set(model, roll);
roll.heading = loadingObject.heading;
const orientation = new ConstantProperty(Transforms.headingPitchRollQuaternion(model.position.getValue(), roll));
model.orientation = orientation;
placedModels.push({
model: model,
name: loadingObject.name,
});
}
for (const objectToHide of objects.hiddenObjects) {
hidingFeatures.push({
id: objectToHide,
loops: 0,
});
}
const primitives = vcMap.getScene().primitives;
for (let i = 0; i < primitives.length; i++) {
const tileSet = primitives.get(i);
if (!tileSet instanceof Cesium3DTileset) {
continue;
}
tileSet.tileVisible.addEventListener(hidingListener);
}
}
reader.readAsText(file);
});
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
},
get config() {
return config;
},
initialize(vcsApp) {
app = vcsApp;
vcsApp.contextMenuManager.addEventHandler(async (event) => {
const actions = [];
const pick = vcsApp.maps.activeMap.getScene().pick(event.windowPosition);
if (pick !== undefined && pick.primitive !== undefined && pick.primitive.id !== undefined) {
model = pick.primitive.id
actions.push({
id: 'move',
name: 'Objekt verschieben',
callback() {
const interaction = new MoveInteraction();
interaction.setActive(EventType.CLICKMOVE);
activeMouseEvent = vcsApp.maps.eventHandler.addExclusiveInteraction(interaction, () => { console.log("removed") });
},
});
actions.push({
id: 'move',
name: 'Objekthöhe verändern',
callback() {
const interaction = new HeightInteraction();
interaction.setActive(EventType.CLICKMOVE);
activeMouseEvent = vcsApp.maps.eventHandler.addExclusiveInteraction(interaction, () => { console.log("removed") });
},
});
actions.push({
id: 'rotate',
name: 'Objekt drehen',
callback() {
hpRoll = hpRollMap.get(model);
if (hpRoll === undefined) {
hpRoll = new HeadingPitchRoll();
hpRollMap.set(model, hpRoll);
}
const interaction = new RotateAction();
interaction.setActive(EventType.CLICKMOVE);
activeMouseEvent = vcsApp.maps.eventHandler.addExclusiveInteraction(interaction, () => { console.log("removed") });
},
});
actions.push({
id: 'delete',
name: 'Objekt löschen',
callback() {
vcsApp.maps.activeMap.getEntities().remove(model);
removePlacedModel(model);
console.log(placedModels);
},
});
} else if (event.feature) {
actions.push({
id: 'delete',
name: 'Objekt verstecken',
callback() {
const gmlId = event.feature.getProperty("gml_id");
if (gmlId !== undefined) {
updateHideCondition();
event.feature.tileset.style = new Cesium3DTileStyle({
show: {
conditions: conditions,
},
});
activeMap.layerCollection.requestRender();
} else {
const { activeMap } = vcsApp.maps;
activeMap.layerCollection.globalHider.addFeature("manual", event.feature);
hidingFeatures.push({
id: event.feature.featureId,
loops: 3,
});
activeMap.layerCollection.globalHider.hideObjects(["manual"]);
}
},
});
}
return actions;
}, name);
this._app = vcsApp;
},
/**
* @param {import("@vcmap/ui").VcsUiApp} vcsUiApp
* @returns {Promise<void>}
*/
async onVcsAppMounted(vcsApp) {
const bimGroup = {
id: 'bim-functions',
type: ToolboxType.GROUP,
icon: "ifc",
disabled: false,
title: 'BIM Funktionen',
};
vcsApp.toolboxManager.add(
bimGroup,
name,
);
/**
* @type {Array<import("@vcmap/ui").ButtonComponentOptions>}
*/
const buttonComponents = [
{
id: 'ifcUpload',
action: {
name: 'ifcUpload',
title: 'IFC nach gltf Konvertierung',
icon: 'mdi-upload-outline',
active: false,
callback() {
vcsApp.windowManager.add(
{
id: windowId,
component: BIMOptions,
slot: WindowSlot.DETACHED,
position: {
width: 400,
},
state: {
headerTitle: "IFC nach gltf Konvertierung",
},
},
name,
);
},
},
},
{
id: 'objectManager',
action: {
name: 'objectManager',
title: 'Objektverwaltung',
icon: 'mdi-bookmark-outline',
active: false,
callback() {
vcsApp.windowManager.add(
{
id: windowId,
component: objectList,
slot: WindowSlot.DYNAMIC_LEFT,
state: {
headerTitle: "Objektverwaltung",
},
},
name,
);
},
},
},
{
id: 'help',
action: {
name: 'help',
title: 'Anleitung',
icon: 'mdi-help',
active: false,
callback() {
window.open(config.instructions);
},
},
},
];
const groupButtonManager = vcsApp.toolboxManager.get(
'bim-functions',
).buttonManager;
buttonComponents.forEach((b) =>
groupButtonManager.add(b, name),
);
},
/**
* @param {boolean} forUrl
* @returns {PluginState}
*/
getState(forUrl) {
return undefined;
},
/**
* @returns {PluginConfig}
*/
toJSON() {
const options = {};
return options;
},
i18n: {
},
destroy() {
// empty
},
};
}
\ No newline at end of file
<template>
<v-sheet>
<VcsFormSection heading="Objektliste">
<template #help>
<p>Objektliste:</p>
<span>Hier werden alle geladenen Objekte aufgelistet.
Über das Dreipunktemenü kann das geladene Objekt platziert werden</span>
</template>
<v-container class="py-1 px-1">
<v-row no-gutters>
<vcs-list
:items="items"
:draggable="draggable"
:selectable="selectable"
:single-select="selectSingle"
:searchable="searchable"
:show-title="showTitle"
:icon="titleIconSrc"
:actions="titleActionsArray"
:title="title"
v-model="selected"
@item-moved="move"
@item-renamed="({ item, newTitle }) => (item.title = newTitle)"
/>
</v-row>
</v-container>
</VcsFormSection>
<VcsFormSection heading="Objekte Hinzufügen">
<template #help>
<p>Objekte laden:</p>
<span>Über den Objekte laden Knopf können glTF/glb Modelle der Objektliste hinzugefügt werden.</span>
</template>
<v-container class="py-1 px-1">
<v-row no-gutters>
<VcsFormButton id="loadBtn" @click="loadModel()"> Objekte Laden </VcsFormButton>
</v-row>
</v-container>
</VcsFormSection>
<VcsFormSection heading="Objekt Positionierung">
<template #help>
<p>Positionierung speichern/laden:</p>
<span>Hier können versteckte Gebäude und neu platzierte Objekte an ihrer jetzigen Position gespeichert werden
und wieder geladen werden.
</span>
</template>
<v-container class="py-1 px-1">
<v-row no-gutters justify="center">
<v-col>
<VcsFormButton id="loadBtn" @click="saveConfiguration()"> Speichern </VcsFormButton>
</v-col>
<v-col>
<VcsFormButton id="loadBtn" @click="loadConfiguration()"> Laden </VcsFormButton>
</v-col>
</v-row>
<v-row no-gutters>
</v-row>
</v-container>
</VcsFormSection>
</v-sheet>
</template>
<script>
import {
VcsList,
VcsFormButton,
VcsTextField,
Icons,
VcsFormSection,
createListItemRenameAction,
NotificationType,
} from '@vcmap/ui';
import {
VSwitch,
VSheet,
VDialog,
VCard,
VForm,
VContainer,
VRow,
VCol,
} from 'vuetify/lib';
import { computed, ref, inject } from 'vue';
import { name } from '../package.json';
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { Cartesian2 } from '@vcmap-cesium/engine';
const defaultItems = [];
const items = ref(defaultItems);
let setupModelFunction = undefined;
let app = undefined;
let projectStateObject = undefined;
function uploadModel() {
// Create an input element
const inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
inputElement.setAttribute("multiple", "");
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = ".glb, .gltf";
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", e => {
const fileInput = e.target;
for (const file of fileInput.files) {
const reader = new FileReader();
reader.onload = async readerEvent => {
const content = readerEvent.target.result;
let blob = new Blob([content], {
type: "application/octet-stream",
});
let url = URL.createObjectURL(blob);
const loader = new GLTFLoader();
loader.load(url, function(gltf) {
let bounds = new THREE.Box3().setFromObject(gltf.scene);
const x = bounds.min.x + (bounds.max.x - bounds.min.x) / 2;
const z = bounds.min.z + (bounds.max.z - bounds.min.z) / 2;
const m = new THREE.Matrix4().makeTranslation(-x, -bounds.min.y, -z);
gltf.scene.applyMatrix4(m);
const exporter = new GLTFExporter();
const options = {
binary: true,
};
exporter.parse(gltf.scene,
// called when the gltf has been generated
function (output) {
blob = new Blob([output]);
url = URL.createObjectURL(blob);
const name = file.name;
projectStateObject.objects.push({
name: name,
url: url,
});
const item = {
name: name,
title: name,
actions: [
{
name: 'Objekt platzieren',
callback() {
const x = window.innerWidth / 2;
const y = window.innerHeight / 2;
const cart = new Cartesian2(x, y);
setupModelFunction(app, cart, url, name);
},
}
]
};
items.value.push(item);
},
// called when there is an error in the generation
function ( error ) {
app.notifier.add({
type: NotificationType.ERROR,
message: "Ein Fehler ist beim Laden der glTF Datei aufgetreten. Bitte vergewissern Sie sich, dass es sich um eine gültige glTF Datei handelt.",
});
}, options);
});
}
reader.readAsArrayBuffer(file);
}
});
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
function getRandomIcon() {
const keys = Object.keys(Icons);
const index = Math.floor(keys.length * Math.random());
return `$${keys[index]}`;
}
export default {
name: 'objectList',
components: {
VcsList,
VcsFormButton,
VcsTextField,
VcsFormSection,
VSwitch,
VSheet,
VDialog,
VCard,
VForm,
VContainer,
VRow,
VCol,
},
setup() {
app = inject('vcsApp');
const { pluginState, setupModel, saveObjects, loadObjects } = app.plugins.getByKey(name);
const draggable = ref(false);
const selectable = ref(false);
const searchable = ref(false);
const selectSingle = ref(false);
const showSelection = ref(false);
const showTitle = ref(false);
const title = ref('Objekte');
const titleActionsArray = ref([]);
const titleIconSrc = ref(null);
const selected = ref([]);
const newItem = ref({
name: 'foo',
title: 'foo',
disabled: false,
visible: true,
icon: 'home-outline',
renameAction: false,
action: false,
clicked: false,
selected: false,
});
const dialog = ref(false);
setupModelFunction = setupModel;
projectStateObject = pluginState;
return {
draggable,
selectable,
searchable,
selectSingle,
selected,
showSelection,
showTitle,
title,
titleActionsArray,
titleIconSrc,
items,
newItem,
dialog,
required: [
(v) => !!v || 'Input may not be null',
(v) => v.length > 0 || 'Input must have a length',
],
add() {
const item = {
name: newItem.value.name,
title: newItem.value.title,
disabled: newItem.value.disabled,
visible: newItem.value.visible,
hasUpdate: newItem.value.hasUpdate,
};
if (newItem.value.icon) {
item.icon = getRandomIcon();
}
item.actions = [];
if (newItem.value.renameAction) {
item.rename = false;
item.actions.push(createListItemRenameAction(item));
}
items.value.push(item);
newItem.value = {
name: 'foo',
title: 'foo',
disabled: false,
visible: true,
icon: false,
renameAction: false,
action: false,
clicked: false,
selected: false,
hasUpdate: false,
};
dialog.value = false;
},
titleActions: computed({
get() {
return titleActionsArray.value.length > 0;
},
set(value) {
if (value) {
titleActionsArray.value = [
{
name: 'console.log foo',
callback() {
console.log('foo');
},
},
];
} else {
titleActionsArray.value = [];
}
},
}),
titleIcon: computed({
get() {
return !!titleIconSrc.value;
},
set(value) {
if (value) {
titleIconSrc.value = getRandomIcon();
} else {
titleIconSrc.value = null;
}
},
}),
move({ item, targetIndex }) {
let target = targetIndex;
target = target >= 0 ? target : 0;
target =
target < items.value.length ? target : items.value.length - 1;
const from = items.value.indexOf(item);
if (from !== target) {
items.value.splice(from, 1);
items.value.splice(target, 0, item);
}
},
loadModel() {
uploadModel();
},
loadConfiguration() {
loadObjects(app);
},
saveConfiguration() {
saveObjects();
},
};
},
};
</script>
<style lang="scss" scoped>
.d-grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
</style>
<template>
<v-sheet>
<v-card class="pa-2 ma-2">
<v-container>
<v-row no-gutters class="justify-center">
<v-col>
<VcsLabel html-for="fileInput">
IFC Datei:
</VcsLabel>
</v-col>
<v-col>
<VcsTextField id="fileInput" type="file" v-model="state.files" />
</v-col>
</v-row>
<v-row no-gutters class="justify-center">
</v-row>
<v-row no-gutters class="justify-center">
<VcsFormButton id="convertBtn" @click="convert()" :disabled="disable"> Konvertieren </VcsFormButton>
</v-row>
</v-container>
</v-card>
</v-sheet>
</template>
<script>
import { inject, ref } from 'vue';
import {
VcsSelect,
VcsCheckbox,
VcsRadio,
VcsFormButton,
VcsTextField,
NotificationType,
VcsFormattedNumber,
VcsFormSection,
VcsLabel,
VcsTextArea,
VcsSlider,
} from '@vcmap/ui';
import { VContainer, VRow, VForm, VCol } from 'vuetify/lib';
import { name } from '../package.json';
export const windowId = 'upload_ifc_id';
export default {
name: 'IFC Konvertierung',
components: {
VcsFormButton,
VcsSelect,
VcsTextField,
VcsCheckbox,
VcsRadio,
VcsFormattedNumber,
VcsFormSection,
VcsLabel,
VcsTextArea,
VForm,
VRow,
VCol,
VContainer,
VcsSlider,
},
setup(props, { emit }) {
const app = inject('vcsApp');
const { pluginState, config } = app.plugins.getByKey(name);
const disable = ref(false);
return {
closeSelf() {
emit('close');
},
convert() {
const fileInput = document.getElementById("fileInput");
const fd = new FormData();
fd.append('file', pluginState.files);
const req = fetch(config.convertLink, {
method: 'post',
body: fd /* or aFile[0]*/
}); // returns a promise
let filename = pluginState.files.name.replace(/\.[^/.]+$/, "") + ".glb";
disable.value = true;
const convertBtn = document.getElementById("convertBtn");
convertBtn.innerHTML = " Konvertierung läuft ";
req.then(function (res) {
disable.value = false;
convertBtn.innerHTML = " Konvertieren ";
emit('close');
if (res.ok) {
// status code was 200-299
app.notifier.add({
type: NotificationType.SUCCESS,
message: "Datei erfolgreich konvertiert",
timeout: 5000,
});
return res.blob();
} else {
app.notifier.add({
type: NotificationType.ERROR,
message: "Ein Fehler ist beim konvertieren aufgetreten, die Konvertierung unterstützt " +
"Dateien im IFC Format IFC2x3 und IFC4 Add2 TC1. Bitte stellen Sie sicher, dass die Datei " +
"die korrekte Version hat und nicht korrupt ist. Falls dies der Fall ist dann ist ein " +
"unbekannter Fehler beim Konvertieren aufgetreten, der nicht behoben werden konnte.",
});
}
}, function (error) {
app.notifier.add({
type: NotificationType.ERROR,
message: "Ein Fehler ist beim konvertieren aufgetreten, die Konvertierung unterstützt " +
"Dateien im IFC Format IFC2x3 und IFC4 Add2 TC1. Bitte stellen Sie sicher, dass die Datei " +
"die korrekte Version hat und nicht korrupt ist. Falls dies der Fall ist dann ist ein " +
"unbekannter Fehler beim Konvertieren aufgetreten, der nicht behoben werden konnte.",
});
}).then((blob) => {
if (blob != null) {
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
}
})
},
disable,
state: pluginState,
};
},
};
</script>
{
"extends": ["@vcsuite/eslint-config/mocha"],
"rules": {
"import/extensions": ["error", "always"]
}
}
import { vi, describe, it, expect, beforeAll } from 'vitest';
import { VcsUiApp } from '@vcmap/ui';
import { VcsModule } from '@vcmap/core';
import { helloWorld } from '../src/index.js';
import { name } from '../package.json';
describe('HelloWorld', () => {
describe('helloWorld', () => {
it('should return hello World', () => {
const val = helloWorld();
expect(val).to.equal('Hello World!');
});
});
describe('addModule', () => {
let module;
/** @type {VcsUiApp} */
let app;
let added;
beforeAll(async () => {
module = new VcsModule({
plugins: [
{
name,
},
],
});
app = new VcsUiApp();
added = vi.fn();
app.moduleAdded.addEventListener(added);
// since plugin's entry cannot be resolved, we mock the _parseContext method and call override on the plugins collection
vi.spyOn(app, '_parseModule').mockImplementationOnce(() => {
app.plugins.override({ name });
});
await app.addModule(module);
});
it('should add the module', () => {
expect(app.getModuleById(module._id)).to.equal(module);
});
it('should raise the contextAdded event', () => {
expect(added).toHaveBeenCalledTimes(1);
});
it('should add plugins part of the module', () => {
const plugin = app.plugins.getByKey(name);
// eslint-disable-next-line no-unused-expressions
expect(plugin).not.to.be.undefined;
});
});
});
/* eslint-disable import/no-extraneous-dependencies, import/first */
import { vi } from 'vitest';
vi.hoisted(() => {
global.jest = vi;
});
import ResizeObserver from 'resize-observer-polyfill';
global.ResizeObserver = ResizeObserver;
import 'jest-canvas-mock';
import Vue from 'vue';
Vue.config.productionTip = false;
window.CESIUM_BASE_URL = '/node_modules/@vcmap-cesium/engine/Build/';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { VcsUiApp, loadPlugin } from '@vcmap/ui';
import plugin from '../src/index.js';
import packageJSON from '../package.json';
function sleep(ms = 0) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
window.VcsPluginLoaderFunction = (name, module) => ({
default: () => plugin({ name }, module),
});
const testPropSymbol = Symbol('testProp');
describe('VcsPlugin Interface test', () => {
let pluginInstance;
beforeAll(async () => {
pluginInstance = await loadPlugin(packageJSON.name, {
name: packageJSON.name,
entry: '_dev',
});
});
afterAll(() => {
pluginInstance?.destroy?.();
});
describe('name, version, mapVersion', () => {
it('should return the plugin name from the package.json', () => {
expect(pluginInstance).to.have.property('name', packageJSON.name);
});
it('should return the plugin version from the package.json', () => {
expect(pluginInstance).to.have.property('version', packageJSON.version);
});
it('should return the plugin mapVersion from the package.json', () => {
expect(pluginInstance).to.have.property(
'mapVersion',
packageJSON.mapVersion,
);
});
});
describe('internationalization', () => {
it('may provide an i18n object and should provide at least en as fallback language', () => {
if (pluginInstance?.i18n) {
expect(pluginInstance?.i18n).to.be.a('object').with.property('en');
}
});
it('should use unscoped, camel-case plugin name as namespace for plugin specific i18n entries', () => {
if (pluginInstance?.i18n) {
expect(pluginInstance.i18n).to.be.a('object');
const [scope, name] = packageJSON.name.split('/');
const unscopedName = name || scope;
const camelCaseName = unscopedName.replace(/-./g, (x) =>
x[1].toUpperCase(),
);
Object.values(pluginInstance.i18n).forEach((locale) => {
expect(locale).to.have.property(camelCaseName);
});
}
});
});
describe('plugin hooks', () => {
it('may implement initialize', () => {
if (pluginInstance?.initialize) {
expect(pluginInstance.initialize).to.be.a('function');
expect(pluginInstance.initialize(new VcsUiApp(), undefined)).to.not
.throw;
}
});
it('may implement onVcsAppMounted', () => {
if (pluginInstance?.onVcsAppMounted) {
expect(pluginInstance.onVcsAppMounted).to.be.a('function');
expect(pluginInstance.onVcsAppMounted(new VcsUiApp())).to.not.throw;
}
});
it('should implement destroy', () => {
if (pluginInstance?.destroy) {
expect(pluginInstance.destroy).to.be.a('function');
}
});
});
describe('options & serialization', () => {
it('may return default options', () => {
if (pluginInstance?.getDefaultOptions) {
expect(pluginInstance.getDefaultOptions()).to.be.a('object');
}
});
it('may implement toJSON returning the plugin config', () => {
if (pluginInstance?.toJSON) {
expect(pluginInstance.toJSON()).to.be.a('object');
}
});
});
describe('shadowing a plugin', () => {
let app;
let pluginInstance2;
beforeAll(async () => {
app = new VcsUiApp();
app.plugins.add(pluginInstance);
pluginInstance2 = await loadPlugin(packageJSON.name, {
name: packageJSON.name,
version: '2.0.0',
entry: '_dev',
});
if (pluginInstance2) {
pluginInstance2[testPropSymbol] = 'test';
}
});
afterAll(() => {
pluginInstance2?.destroy?.();
});
it('should override the plugin correctly', () => {
expect(() => app.plugins.override(pluginInstance2)).to.not.throw;
app.plugins.override(pluginInstance2);
expect(app.plugins.getByKey(packageJSON.name)).to.have.property(
testPropSymbol,
'test',
);
expect(app.plugins.getByKey(packageJSON.name)).to.equal(pluginInstance2);
});
it('should reincarnate the plugin correctly', async () => {
expect(() => app.plugins.remove(pluginInstance2)).to.not.throw;
app.plugins.remove(pluginInstance2);
await sleep(0);
expect(app.plugins.getByKey(packageJSON.name)).not.to.have.property(
testPropSymbol,
'test',
);
});
});
});
import { defineConfig } from 'vite';
export default defineConfig({
esbuild: {
supported: {
'top-level-await': true
},
},
});
\ No newline at end of file
// eslint-disable-next-line import/no-extraneous-dependencies
import { defineConfig } from 'vite';
import commonViteConfig from '@vcmap/ui/build/commonViteConfig.js';
const configTest = defineConfig({
...commonViteConfig,
resolve: {
alias: {
vue: 'vue/dist/vue.esm.js',
tinyqueue: 'tinyqueue/tinyqueue.js',
},
},
css: {
preprocessorOptions: {
sass: {
additionalData: "\n@import '@vcmap/ui/src/styles/variables.scss'\n",
},
},
},
test: {
server: {
deps: {
inline: ['vuetify', '@vcmap/ui'],
},
},
environment: 'jsdom',
setupFiles: ['tests/setup.js'],
isolate: false,
threads: false,
},
});
export default configTest;
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment