Commit 0f66af82 authored by Matthias Betz's avatar Matthias Betz
Browse files

initial viewer release

parent 364470b6
# Created by https://www.gitignore.io/api/java,maven,macos,linux,eclipse,windows,netbeans,intellij
# Edit at https://www.gitignore.io/?templates=java,maven,macos,linux,eclipse,windows,netbeans,intellij
# User specific
.sonarlint/
Servers/
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# CDT- autotools
.autotools
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
# Annotation Processing
.apt_generated/
# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet
### Eclipse Patch ###
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Annotation Processing
.apt_generated
.sts4-cache/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Java ###
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
### NetBeans ###
**/nbproject/private/
**/nbproject/Makefile-*.mk
**/nbproject/Package-*.bash
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.gitignore.io/api/java,maven,macos,linux,eclipse,windows,netbeans,intellij
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# CityGMLViewer
A CityGMLViewer based on OpenGL. Can display CityGML 2 and 3
\ No newline at end of file
A CityGMLViewer based on OpenGL. Can display CityGML 2 and 3
## Installation
Use [Maven](https://maven.apache.org/) to build the viewer.
```bash
mvn package
```
groundColor=0.9411765 0.9019608 0.54901963
roofColor=1 0 0
doorColor=1 0.784313 0
windowColor=0.0 0.5019608 0.5019608
wallColor=1 1 1
bridgeColor=1 0.49803922 0.3137255
landColor=0.64705884 0.16470589 0.16470589
transportationColor=1 1 0
vegetationColor=0.5647059 0.93333334 0.5647059
waterColor=0.5294118 0.80784315 0.98039216
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.hft.stuttgart</groupId>
<artifactId>citygml-viewer-lwjgl</artifactId>
<version>0.0.1</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<lwjgl.version>3.2.3</lwjgl.version>
<joml.version>1.10.1</joml.version>
</properties>
<profiles>
<profile>
<id>lwjgl-natives-linux-amd64</id>
<activation>
<os>
<family>unix</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-linux</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-macos-amd64</id>
<activation>
<os>
<family>mac</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-macos</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-windows-amd64</id>
<activation>
<os>
<family>windows</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-windows</lwjgl.natives>
</properties>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.citygml4j/citygml4j -->
<dependency>
<groupId>org.citygml4j</groupId>
<artifactId>citygml4j</artifactId>
<version>3.0.0-rc.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.locationtech.proj4j/proj4j -->
<dependency>
<groupId>org.locationtech.proj4j</groupId>
<artifactId>proj4j</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nfd</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>natives-windows</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>natives-windows</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>natives-windows</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>natives-linux</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>natives-linux</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>natives-linux</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nfd</artifactId>
<classifier>natives-linux</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nfd</artifactId>
<classifier>natives-windows</classifier>
</dependency>
<dependency>
<groupId>org.joml</groupId>
<artifactId>joml</artifactId>
<version>${joml.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jogamp.jogl/jogl-all-main -->
<dependency>
<groupId>org.jogamp.jogl</groupId>
<artifactId>jogl-all-main</artifactId>
<version>2.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jogamp.gluegen/gluegen-rt-main -->
<dependency>
<groupId>org.jogamp.gluegen</groupId>
<artifactId>gluegen-rt-main</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>de.hft.stuttgart.citygml.viewer.CityGMLViewer</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<finalName>${project.artifactId}-${project.version}</finalName>
<descriptors>
<descriptor>${project.basedir}/src/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>zip</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>libs</outputDirectory>
<excludes>
<exclude>${project.groupId}:${project.artifactId}:jar:*</exclude>
</excludes>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<directory>${project.build.directory}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>${project.artifactId}-${project.version}.jar</include>
</includes>
</fileSet>
<fileSet>
<directory>${project.basedir}/src/assembly</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>start.bat</include>
<include>color.properties</include>
</includes>
<filtered>true</filtered>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
groundColor=0.9411765 0.9019608 0.54901963
roofColor=1 0 0
doorColor=1 0.784313 0
windowColor=0.0 0.5019608 0.5019608
wallColor=1 1 1
bridgeColor=1 0.49803922 0.3137255
landColor=0.64705884 0.16470589 0.16470589
transportationColor=1 1 0
vegetationColor=0.5647059 0.93333334 0.5647059
waterColor=0.5294118 0.80784315 0.98039216
\ No newline at end of file
start javaw -jar ${project.artifactId}-${project.version}.jar
\ No newline at end of file
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import java.nio.FloatBuffer;
import org.joml.Math;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.system.MemoryUtil;
public class Camera {
private static final float MIN_DISTANCE = 1f;
private static final float PI = (float) Math.PI;
private Matrix4f projMatrix;
private Matrix4f viewMatrix;
private Matrix4f projViewMatrix;
private float rotateAroundX = 2f;
private float rotateAroundZ = 3f;
private Vector3f eyeVec = new Vector3f();
private Vector3f center = new Vector3f();
private Vector3f up = new Vector3f();
private float distance = 5;
private static final float SCROLL_PERCENTAGE = 0.1f;
private UniformLocation uniformLocation;
private FloatBuffer matrixBuffer = MemoryUtil.memAllocFloat(16);
private boolean isOrtho = false;
public Camera(Shader shader) {
uniformLocation = shader.getUniformLocation("projViewModel");
projViewMatrix = new Matrix4f();
viewMatrix = new Matrix4f();
projMatrix = new Matrix4f();
up.z = 1;
}
public void reshape(int width, int height, float distance) {
if (isOrtho) {
projMatrix.setOrtho(0, width, height, 0, 0, distance);
} else {
// 90 degree fow
float fow = PI / 2f;
float aspectRatio = (float) width / height;
projMatrix.setPerspective(fow, aspectRatio, MIN_DISTANCE, distance);
}
updateMatrix();
}
public void setOrtho(boolean isOrtho) {
this.isOrtho = isOrtho;
}
private void updateMatrix() {
// view matrix
if (isOrtho) {
projMatrix.get(matrixBuffer);
} else {
float sx = Math.sin(rotateAroundX);
float cx = Math.cos(rotateAroundX);
float sy = Math.sin(rotateAroundZ);
float cy = Math.cos(rotateAroundZ);
float sxDistance = distance * sx;
eyeVec.x = sxDistance * cy;
eyeVec.y = sxDistance * sy;
eyeVec.z = distance * cx;
viewMatrix.identity();
viewMatrix.translate(0, 0, distance);
viewMatrix.lookAt(eyeVec, center, up);
projMatrix.mul(viewMatrix, projViewMatrix);
// model matrix is identity
projViewMatrix.get(matrixBuffer);
}
uniformLocation.uploadMat4(matrixBuffer);
}
public void drag(double dragDiffX, double dragDiffY) {
rotateAroundX += dragDiffY / 500f;
rotateAroundZ -= dragDiffX / 500f;
if (rotateAroundX > Math.PI) {
rotateAroundX = (float) Math.PI - 0.001f;
} else if (rotateAroundX < 0.001) {
rotateAroundX = (float) 0.001;
}
updateMatrix();
}
public void setDistance(float distance) {
this.distance = distance;
updateMatrix();
}
public void scroll(int scroll) {
int addedDistance = (int) (distance * scroll * SCROLL_PERCENTAGE);
distance += addedDistance;
updateMatrix();
}
public void free() {
MemoryUtil.memFree(matrixBuffer);
}
public void move(double dragDiffX, double dragDiffY) {
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.xml.parsers.ParserConfigurationException;
import org.citygml4j.CityGMLContext;
import org.citygml4j.CityGMLContextException;
import org.citygml4j.model.core.AbstractCityObject;
import org.citygml4j.model.core.AbstractFeature;
import org.citygml4j.xml.reader.ChunkingOptions;
import org.citygml4j.xml.reader.CityGMLInputFactory;
import org.citygml4j.xml.reader.CityGMLReadException;
import org.citygml4j.xml.reader.CityGMLReader;
import org.lwjgl.PointerBuffer;
import org.lwjgl.glfw.Callbacks;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWMouseButtonCallback;
import org.lwjgl.glfw.GLFWScrollCallback;
import org.lwjgl.glfw.GLFWWindowSizeCallbackI;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.nfd.NativeFileDialog;
import org.xml.sax.SAXException;
import com.jogamp.opengl.GLException;
import de.hft.stuttgart.citygml.viewer.datastructure.BoundingBox;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
import de.hft.stuttgart.citygml.viewer.parser.CityGMLParser;
import de.hft.stuttgart.citygml.viewer.parser.FeatureMapper;
import de.hft.stuttgart.citygml.viewer.parser.ObservedInputStream;
import de.hft.stuttgart.citygml.viewer.parser.ParserConfiguration;
public class CityGMLViewer {
private static final Logger log = Logger.getLogger(CityGMLViewer.class.getName());
private static Camera camera;
private static boolean mouse1Down = false;
private static boolean mouse2Down = false;
private static double x;
private static double y;
private static int width = 1024;
private static int height = 768;
private static List<PolygonViewInformation> viewing = new ArrayList<>();
private static float cameraViewDistance = 10000f;
private static long windowId;
private static ProgressBar bar;
public static void main(String[] args) {
File f = null;
if (args != null && args.length == 1) {
f = new File(args[0]);
if (!f.exists() || f.isDirectory()) {
// no file given
f = null;
}
}
if (f == null) {
f = showFileChooserDialog();
}
try {
setupWindow(f);
} finally {
for (PolygonViewInformation view : viewing) {
view.destroy();
}
}
}
private static File showFileChooserDialog() {
File f = null;
try (MemoryStack stack = MemoryStack.stackPush()) {
File defaultPath = new File("bla");
PointerBuffer pathPointer = stack.mallocPointer(1);
int success = NativeFileDialog.NFD_OpenDialog("gml,xml", defaultPath.getAbsolutePath(), pathPointer);
if (success == NativeFileDialog.NFD_OKAY) {
String filePath = pathPointer.getStringUTF8(0);
f = new File(filePath);
} else {
System.exit(0);
}
}
return f;
}
private static void screenShot() {
// Creating an rbg array of total pixels
int[] pixels = new int[width * height];
int bindex;
// allocate space for RBG pixels
ByteBuffer fb = ByteBuffer.allocateDirect(width * height * 3);
// grab a copy of the current frame contents as RGB
GL11.glReadPixels(0, 0, width, height, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, fb);
BufferedImage imageIn = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// convert RGB data in ByteBuffer to integer array
for (int i = 0; i < pixels.length; i++) {
bindex = i * 3;
pixels[i] = (fb.get(bindex) << 16) + (fb.get(bindex + 1) << 8) + (fb.get(bindex + 2));
}
// Allocate colored pixel to buffered Image
imageIn.setRGB(0, 0, width, height, pixels, 0, width);
// Creating the transformation direction (horizontal)
AffineTransform at = AffineTransform.getScaleInstance(1, -1);
at.translate(0, -imageIn.getHeight(null));
// Applying transformation
AffineTransformOp opRotated = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
BufferedImage imageOut = opRotated.filter(imageIn, null);
try {
int nr = 0;
File f = new File("screen_" + nr + ".png");
while (f.exists()) {
nr++;
f = new File("screen_" + nr + ".png");
}
ImageIO.write(imageOut, "png", f);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setupWindow(File f) {
GLFW.glfwSetErrorCallback(GLFWErrorCallback.createPrint(System.err));
if (!GLFW.glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
String title = "CityGMLViewer";
GLFW.glfwDefaultWindowHints(); // Loads GLFW's default window settings
GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE); // Sets window to be visible
GLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_TRUE); // Sets whether the window is resizable
GLFW.glfwWindowHint(GLFW.GLFW_OPENGL_PROFILE, GLFW.GLFW_OPENGL_CORE_PROFILE);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MAJOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_CONTEXT_VERSION_MINOR, 3);
GLFW.glfwWindowHint(GLFW.GLFW_SAMPLES, 2);
windowId = GLFW.glfwCreateWindow(width, height, title, 0, 0);
if (windowId == 0) {
GLFW.glfwTerminate();
throw new IllegalStateException("Failed to create window");
}
GLFW.glfwSetWindowSizeCallback(windowId, new GLFWWindowSizeCallbackI() {
@Override
public void invoke(long window, int width, int height) {
CityGMLViewer.width = width;
CityGMLViewer.height = height;
if (camera != null) {
camera.reshape(width, height, cameraViewDistance);
}
if (bar != null) {
bar.updateWindowSize(width, height);
}
GL11.glViewport(0, 0, width, height);
}
});
GLFW.glfwSetKeyCallback(windowId, (window, key, scancode, action, mods) -> {
if (key == GLFW.GLFW_KEY_ESCAPE && action == GLFW.GLFW_PRESS) {
GLFW.glfwSetWindowShouldClose(window, true);
} else if (key == GLFW.GLFW_KEY_F9 && action == GLFW.GLFW_PRESS) {
screenShot();
}
});
GLFW.glfwSetMouseButtonCallback(windowId, new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
if (button == GLFW.GLFW_MOUSE_BUTTON_1 && action == GLFW.GLFW_PRESS) {
mouse1Down = true;
try (MemoryStack stack = MemoryStack.stackPush()) {
DoubleBuffer xBuffer = stack.mallocDouble(1);
DoubleBuffer yBuffer = stack.mallocDouble(1);
GLFW.glfwGetCursorPos(windowId, xBuffer, yBuffer);
x = xBuffer.get(0);
y = yBuffer.get(0);
}
} else if (button == GLFW.GLFW_MOUSE_BUTTON_1 && action == GLFW.GLFW_RELEASE) {
mouse1Down = false;
} else if (button == GLFW.GLFW_MOUSE_BUTTON_2 && action == GLFW.GLFW_PRESS) {
mouse2Down = true;
try (MemoryStack stack = MemoryStack.stackPush()) {
DoubleBuffer xBuffer = stack.mallocDouble(1);
DoubleBuffer yBuffer = stack.mallocDouble(1);
GLFW.glfwGetCursorPos(windowId, xBuffer, yBuffer);
x = xBuffer.get(0);
y = yBuffer.get(0);
}
} else if (button == GLFW.GLFW_MOUSE_BUTTON_2 && action == GLFW.GLFW_RELEASE) {
mouse2Down = false;
}
}
});
GLFW.glfwSetScrollCallback(windowId, new GLFWScrollCallback() {
@Override
public void invoke(long window, double xoffset, double yoffset) {
camera.scroll((int) (-yoffset));
}
});
GLFW.glfwSetCursorPosCallback(windowId, (window, xPos, yPos) -> {
if (mouse1Down) {
try (MemoryStack stack = MemoryStack.stackPush()) {
double dragDiffX = xPos - x;
double dragDiffY = yPos - y;
camera.drag(dragDiffX, dragDiffY);
x = xPos;
y = yPos;
}
} else if (mouse2Down) {
try (MemoryStack stack = MemoryStack.stackPush()) {
double dragDiffX = xPos - x;
double dragDiffY = yPos - y;
camera.move(dragDiffX, dragDiffY);
x = xPos;
y = yPos;
}
}
});
GLFW.glfwMakeContextCurrent(windowId); // glfwSwapInterval needs a context on the calling thread, otherwise will
// cause
// NO_CURRENT_CONTEXT error
org.lwjgl.opengl.GLCapabilities caps = GL.createCapabilities(); // Will let lwjgl know we want to use this
// context as the context to draw with
if (!caps.OpenGL33) {
log.warning("OpenGL 33 is not supported");
}
GLFW.glfwSwapInterval(1); // How many draws to swap the buffer
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL13.GL_MULTISAMPLE);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glViewport(0, 0, width, height);
GLFW.glfwShowWindow(windowId); // Shows the window
if (log.isLoggable(Level.INFO)) {
log.info("OpenGL error code after displaying the window: " + GL11.glGetError());
}
FloatBuffer clearColor = null;
FloatBuffer clearDepth = null;
try {
Shader program = new Shader("vertex.vert", "fragment.frag");
program.use();
if (log.isLoggable(Level.INFO)) {
log.info("OpenGL error code after shader loading: " + GL11.glGetError());
}
camera = new Camera(program);
camera.setOrtho(true);
camera.reshape(width, height, cameraViewDistance);
bar = new ProgressBar(windowId, width, height);
bar.drawProgress(0);
if (log.isLoggable(Level.INFO)) {
log.info("OpenGL error code after drawing initial progress bar: " + GL11.glGetError());
}
loadGmlFile(f);
bar.free();
bar = null;
if (log.isLoggable(Level.INFO)) {
log.info("OpenGL error code after loading GML file: " + GL11.glGetError());
}
camera.setOrtho(false);
camera.reshape(width, height, cameraViewDistance);
clearColor = MemoryUtil.memAllocFloat(4);
clearColor.put(0, 0.9411765f).put(1, 1f).put(2, 1f).put(3, 1f);
clearDepth = MemoryUtil.memAllocFloat(1);
clearDepth.put(0, 1f);
if (log.isLoggable(Level.INFO)) {
log.info("OpenGL error code before loop: " + GL11.glGetError());
}
while (!GLFW.glfwWindowShouldClose(windowId)) {
/* Do something */
GL30.glClearBufferfv(GL11.GL_COLOR, 0, clearColor);
GL30.glClearBufferfv(GL11.GL_DEPTH, 0, clearDepth);
for (PolygonViewInformation view : viewing) {
view.draw();
}
Thread.sleep(15);
GLFW.glfwSwapBuffers(windowId);
GLFW.glfwPollEvents();
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
MemoryUtil.memFree(clearColor);
MemoryUtil.memFree(clearDepth);
if (camera != null) {
camera.free();
}
}
GLFW.glfwDestroyWindow(windowId);
Callbacks.glfwFreeCallbacks(windowId);
GLFW.glfwTerminate();
}
private static void loadGmlFile(File f) {
try {
File file = f;
ParserConfiguration config = new ParserConfiguration();
CityGMLParser.parseEpsgCodeFromFile(file, config);
CityGMLContext context = CityGMLContext.newInstance();
CityGMLInputFactory in = context.createCityGMLInputFactory()
.withChunking(ChunkingOptions.chunkByCityModelMembers());
try (ObservedInputStream ois = new ObservedInputStream(file);
CityGMLReader reader = in.createCityGMLReader(file.getAbsolutePath(), ois)) {
ois.addListener(p -> bar.drawProgress((int) (p * 82)));
FeatureMapper mapper = new FeatureMapper(config);
while (reader.hasNext()) {
AbstractFeature chunk = reader.next();
if (chunk instanceof AbstractCityObject) {
AbstractCityObject aco = (AbstractCityObject) chunk;
aco.accept(mapper);
}
}
BoundingBox bbox = BoundingBox.of(mapper);
bar.drawProgress(81);
Vector3d center = bbox.getCenter();
mapper.movePolygonsBy(center);
bar.drawProgress(82);
long nrOfPolygons = (long) mapper.getLod1Polygons().size() + mapper.getLod2Polygons().size()
+ mapper.getLod3Polygons().size() + mapper.getLod4Polygons().size();
long[] count = new long[1];
PolygonListener l = () -> {
count[0]++;
bar.drawProgress(82 + (int) (count[0] * 9 / nrOfPolygons));
};
if (!mapper.getLod1Polygons().isEmpty()) {
PolygonViewInformation lod1ViewInfo = new PolygonViewInformation(mapper.getLod1Polygons(), l);
viewing.add(lod1ViewInfo);
}
if (!mapper.getLod2Polygons().isEmpty()) {
PolygonViewInformation lod2ViewInfo = new PolygonViewInformation(mapper.getLod2Polygons(), l);
viewing.add(lod2ViewInfo);
}
if (!mapper.getLod3Polygons().isEmpty()) {
PolygonViewInformation lod3ViewInfo = new PolygonViewInformation(mapper.getLod3Polygons(), l);
viewing.add(lod3ViewInfo);
}
if (!mapper.getLod3Polygons().isEmpty()) {
PolygonViewInformation lod4ViewInfo = new PolygonViewInformation(mapper.getLod4Polygons(), l);
viewing.add(lod4ViewInfo);
}
double longestSide = bbox.getDiagonalLength() * 0.2;
double d = longestSide / Math.tan(Math.toRadians(30) / 2);
double translateZ = -d;
camera.setDistance((float) translateZ);
cameraViewDistance = (float) longestSide * 20f;
camera.reshape(width, height, cameraViewDistance);
}
} catch (GLException | IOException | ParserConfigurationException | SAXException | CityGMLContextException
| CityGMLReadException e) {
e.printStackTrace();
}
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
import de.hft.stuttgart.citygml.viewer.parser.EnvelopeFoundException;
public class CityGmlHandler extends DefaultHandler {
private boolean foundEnvelope = false;
private Vector3d lowerCorner;
private Vector3d upperCorner;
private String epsg;
private boolean nextContentIsLowerCorner = false;
private boolean nextContentIsUpperCorner = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (foundEnvelope) {
if (qName.endsWith("lowerCorner")) {
nextContentIsLowerCorner = true;
} else if (qName.endsWith("upperCorner")) {
nextContentIsUpperCorner = true;
}
} else if (qName.endsWith("Envelope")) {
foundEnvelope = true;
epsg = attributes.getValue("srsName");
}
}
public Vector3d getLowerCorner() {
return lowerCorner;
}
public Vector3d getUpperCorner() {
return upperCorner;
}
public String getEpsg() {
return epsg;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (nextContentIsLowerCorner) {
lowerCorner = parsePoint(ch, start, length);
nextContentIsLowerCorner = false;
} else if (nextContentIsUpperCorner) {
upperCorner = parsePoint(ch, start, length);
nextContentIsUpperCorner = false;
throw new EnvelopeFoundException("Found envelope, stop parsing");
}
}
private Vector3d parsePoint(char[] ch, int start, int length) {
String s = new String(ch, start, length);
String[] coords = s.split("\\s+");
double x = Double.parseDouble(coords[0]);
double y = Double.parseDouble(coords[1]);
double z = Double.parseDouble(coords[2]);
return new Vector3d(x, y, z);
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
public interface PolygonListener {
public void finishedPolygon();
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import static org.lwjgl.opengl.GL11.GL_FLOAT;
import java.awt.Color;
import java.nio.Buffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL44;
import org.lwjgl.opengl.GL45;
import org.lwjgl.system.MemoryUtil;
import de.hft.stuttgart.citygml.viewer.datastructure.BufferConstants;
import de.hft.stuttgart.citygml.viewer.datastructure.Polygon;
import de.hft.stuttgart.citygml.viewer.datastructure.TesselatedPolygon;
import de.hft.stuttgart.citygml.viewer.datastructure.Triangle3d;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
public class PolygonViewInformation {
private static final Vector3d AXIS = new Vector3d(19, 0.8, 1.5).normalize();
private int vao;
private IntBuffer buffers;
private boolean draw = false;
private int elements;
private PolygonListener listener;
public PolygonViewInformation(List<Polygon> polygons, PolygonListener listener) {
this.listener = listener;
vao = GL45.glCreateVertexArrays();
GL45.glVertexArrayAttribBinding(vao, BufferConstants.ATTRIBUTE_POSITION, BufferConstants.BINDING_INDEX_0);
GL45.glVertexArrayAttribBinding(vao, BufferConstants.ATTRIBUTE_COLOR, BufferConstants.BINDING_INDEX_0);
GL45.glVertexArrayAttribFormat(vao, BufferConstants.ATTRIBUTE_POSITION, 3, GL_FLOAT, false, 0);
GL45.glVertexArrayAttribFormat(vao, BufferConstants.ATTRIBUTE_COLOR, 3, GL_FLOAT, false, 3 * 4);
GL45.glEnableVertexArrayAttrib(vao, BufferConstants.ATTRIBUTE_POSITION);
GL45.glEnableVertexArrayAttrib(vao, BufferConstants.ATTRIBUTE_COLOR);
buffers = MemoryUtil.memAllocInt(BufferConstants.SIZE);
GL45.glCreateBuffers(buffers);
GL45.glVertexArrayElementBuffer(vao, buffers.get(BufferConstants.ELEMENT));
GL45.glVertexArrayVertexBuffer(vao, BufferConstants.BINDING_INDEX_0, buffers.get(BufferConstants.VERTEX), 0, (3 + 3) * 4);
setupBuffers(polygons);
}
private void setupBuffers(List<Polygon> polys) {
List<TesselatedPolygon> tessPolys = new ArrayList<>();
for (Polygon poly : polys) {
tessPolys.add(TesselatedPolygon.of(poly));
listener.finishedPolygon();
}
int nrOfTriangles = 0;
for (TesselatedPolygon tessPoly : tessPolys) {
nrOfTriangles += tessPoly.getTriangles().size();
}
// 6 float for 3 vertices per triangle
int moreSpace = nrOfTriangles * 3 * 3 * 2;
FloatBuffer vertexData = MemoryUtil.memAllocFloat(moreSpace);
IntBuffer elementData = MemoryUtil.memAllocInt(nrOfTriangles * 3);
float[] rgba = new float[4];
for (TesselatedPolygon tessPoly : tessPolys) {
Color baseColor = tessPoly.getColor();
double cos = tessPoly.getNormal().dot(AXIS);
double acos = Math.acos(cos);
// normalize to range [0.3, 0.9]
acos = acos / Math.PI;
acos = acos * 0.6 + 0.3;
Color derivedColor = new Color((int) (baseColor.getRed() * acos), (int) (baseColor.getGreen() * acos),
(int) (baseColor.getBlue() * acos));
derivedColor.getComponents(rgba);
for (Triangle3d tri : tessPoly.getTriangles()) {
addPoint(vertexData, tri.getP1(), rgba[0], rgba[1], rgba[2]);
addPoint(vertexData, tri.getP2(), rgba[0], rgba[1], rgba[2]);
addPoint(vertexData, tri.getP3(), rgba[0], rgba[1], rgba[2]);
}
listener.finishedPolygon();
}
for (int i = 0; i < elementData.capacity(); i++) {
elementData.put(i);
}
((Buffer) elementData).flip();
((Buffer) vertexData).flip();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, buffers.get(BufferConstants.VERTEX));
GL44.glBufferStorage(GL15.GL_ARRAY_BUFFER, vertexData, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, buffers.get(BufferConstants.ELEMENT));
GL44.glBufferStorage(GL15.GL_ELEMENT_ARRAY_BUFFER, elementData, 0);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
MemoryUtil.memFree(elementData);
MemoryUtil.memFree(vertexData);
draw = true;
elements = elementData.capacity();
}
private static void addPoint(FloatBuffer lod1VertexData, Vector3d point, float red, float green, float blue) {
lod1VertexData.put((float) point.getX());
lod1VertexData.put((float) point.getY());
lod1VertexData.put((float) point.getZ());
lod1VertexData.put(red);
lod1VertexData.put(green);
lod1VertexData.put(blue);
}
public boolean shouldDraw() {
return draw;
}
public void setShouldDraw(boolean draw) {
this.draw = draw;
}
public int getVao() {
return vao;
}
public void destroy() {
MemoryUtil.memFree(buffers);
}
public void draw() {
if (draw) {
GL30.glBindVertexArray(vao);
GL11.glDrawElements(GL11.GL_TRIANGLES, elements, GL11.GL_UNSIGNED_INT, 0);
}
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
public class ProgressBar {
private int currentProgress;
private FloatBuffer clearColor;
private FloatBuffer clearDepth;
private int width;
private int height;
private long windowId;
private FloatBuffer box;
private int vao;
private int whiteVertexBuffer;
private int indexBufferName;
private int colorBufferName;
public ProgressBar(long windowId, int width, int height) {
this.windowId = windowId;
this.width = width;
this.height = height;
clearColor = MemoryUtil.memAllocFloat(4);
clearColor.put(0, 0f).put(1, 0f).put(2, 0f).put(3, 1f);
clearDepth = MemoryUtil.memAllocFloat(1);
clearDepth.put(0, 1f);
box = MemoryUtil.memAllocFloat(8 * 3);
vao = GL30.glGenVertexArrays();
GL30.glBindVertexArray(vao);
whiteVertexBuffer = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, whiteVertexBuffer);
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);
GL20.glEnableVertexAttribArray(0);
indexBufferName = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBufferName);
try (MemoryStack stack = MemoryStack.stackPush()) {
// index
IntBuffer indexBuffer = stack.mallocInt(12);
indexBuffer.put(0, 0);
indexBuffer.put(1, 1);
indexBuffer.put(2, 2);
indexBuffer.put(3, 0);
indexBuffer.put(4, 2);
indexBuffer.put(5, 3);
indexBuffer.put(6, 4);
indexBuffer.put(7, 5);
indexBuffer.put(8, 6);
indexBuffer.put(9, 4);
indexBuffer.put(10, 6);
indexBuffer.put(11, 7);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL15.GL_STATIC_DRAW);
// color
FloatBuffer color = stack.mallocFloat(8 * 3);
for (int i = 0; i < 4 * 3; i++) {
color.put(i, 1);
}
color.put(12, 0);
color.put(13, 0);
color.put(14, 1);
color.put(15, 0);
color.put(16, 0);
color.put(17, 1);
color.put(18, 0);
color.put(19, 0);
color.put(20, 1);
color.put(21, 0);
color.put(22, 0);
color.put(23, 1);
GL20.glEnableVertexAttribArray(1);
colorBufferName = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, colorBufferName);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, color, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(1, 3, GL11.GL_FLOAT, false, 0, 0);
}
GL30.glBindVertexArray(0);
}
public void updateWindowSize(int width, int height) {
this.width = width;
this.height = height;
forceDraw(currentProgress);
}
private void draw() {
}
public void drawProgress(int progress) {
if (progress == currentProgress) {
return;
}
forceDraw(progress);
}
private void forceDraw(int progress) {
GL30.glClearBufferfv(GL11.GL_COLOR, 0, clearColor);
GL30.glClearBufferfv(GL11.GL_DEPTH, 0, clearDepth);
float progressX = width / 2f - 150f;
float progressY = height / 2f - 30f;
float progressWidth = 300;
float progressHeight = 60;
float okWidth = (progress / 100f) * progressWidth;
box.put(0, progressX + okWidth);
box.put(1, progressY);
box.put(2, 0);
box.put(3, progressX + progressWidth);
box.put(4, progressY);
box.put(5, 0);
box.put(6, progressX + progressWidth);
box.put(7, progressY + progressHeight);
box.put(8, 0);
box.put(9, progressX + okWidth);
box.put(10, progressY + progressHeight);
box.put(11, 0);
box.put(12, progressX);
box.put(13, progressY);
box.put(14, 0);
box.put(15, progressX + okWidth);
box.put(16, progressY);
box.put(17, 0);
box.put(18, progressX + okWidth);
box.put(19, progressY + progressHeight);
box.put(20, 0);
box.put(21, progressX);
box.put(22, progressY + progressHeight);
box.put(23, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, whiteVertexBuffer);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, box, GL15.GL_STATIC_DRAW);
GL30.glBindVertexArray(vao);
GL11.glDrawElements(GL11.GL_TRIANGLES, 12, GL11.GL_UNSIGNED_INT, 0);
GLFW.glfwSwapBuffers(windowId);
GLFW.glfwPollEvents();
currentProgress = progress;
draw();
}
public void free() {
MemoryUtil.memFree(clearDepth);
MemoryUtil.memFree(clearColor);
MemoryUtil.memFree(box);
GL15.glDeleteBuffers(whiteVertexBuffer);
GL15.glDeleteBuffers(indexBufferName);
GL15.glDeleteBuffers(colorBufferName);
GL30.glDeleteVertexArrays(vao);
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import static org.lwjgl.opengl.GL20.glAttachShader;
import static org.lwjgl.opengl.GL20.glCompileShader;
import static org.lwjgl.opengl.GL20.glCreateShader;
import static org.lwjgl.opengl.GL20.glDeleteShader;
import static org.lwjgl.opengl.GL20.glLinkProgram;
import static org.lwjgl.opengl.GL20.glShaderSource;
import static org.lwjgl.opengl.GL20.glUseProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import org.lwjgl.opengl.GL20;
public class Shader {
private int programId;
public Shader(String vertexPath, String fragmentPath) {
int vertexShader = glCreateShader(GL20.GL_VERTEX_SHADER);
glShaderSource(vertexShader, readFully(vertexPath));
glCompileShader(vertexShader);
int fragmentShader = glCreateShader(GL20.GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, readFully(fragmentPath));
glCompileShader(fragmentShader);
programId = GL20.glCreateProgram();
glAttachShader(programId, vertexShader);
glAttachShader(programId, fragmentShader);
glLinkProgram(programId);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
public void use() {
glUseProgram(programId);
}
public static void unUse() {
glUseProgram(0);
}
private String readFully(String path) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(path)))) {
char[] buffer = new char[1024];
StringBuilder builder = new StringBuilder();
while (br.read(buffer) != -1) {
builder.append(buffer);
}
return builder.toString();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public UniformLocation getUniformLocation(String uniformName) {
return new UniformLocation(GL20.glGetUniformLocation(programId, uniformName));
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer;
import java.nio.FloatBuffer;
import org.lwjgl.opengl.GL20;
public class UniformLocation {
private int location;
public UniformLocation(int location) {
this.location = location;
}
public void uploadMat4(FloatBuffer buf) {
GL20.glUniformMatrix4fv(location, false, buf);
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer.datastructure;
import java.util.Arrays;
import java.util.List;
import de.hft.stuttgart.citygml.viewer.math.BoundingBoxCalculator;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
import de.hft.stuttgart.citygml.viewer.parser.FeatureMapper;
/**
* An axis aligned bounding box represented by its two corners
*
* @author Matthias Betz
*
*/
public class BoundingBox {
private Vector3d[] bbox;
/**
* Creates an axis aligned bounding box containing all points of all polygons
*
* @param polygons containing the points from which the box will be created
* @return the bounding box around all points
*/
public static BoundingBox of(List<Polygon> polygons) {
return BoundingBoxCalculator.calculateBoundingBox(polygons);
}
public static BoundingBox ofPoints(List<? extends Vector3d> points) {
return BoundingBoxCalculator.calculateBoundingBoxFromPoints(points);
}
/**
* Creates a new bounding box with two vectors as corner points.
*
* @param box the array of length 2 containing both corners
* @return the new bounding box
*/
public static BoundingBox of(Vector3d[] box) {
return new BoundingBox(box);
}
private BoundingBox(Vector3d[] bbox) {
if (bbox == null || bbox.length != 2) {
throw new IllegalArgumentException("BoundingBox must be an array of the length 2");
}
this.bbox = bbox;
}
/**
* Calculates the volume of the box
*
* @return the volume of the box
*/
public double getVolume() {
double length = getDepth();
double width = getWidth();
double height = getHeight();
return height * width * length;
}
/**
* Calculates the center of the bounding box
*
* @return the center of the bounding box
*/
public Vector3d getCenter() {
return bbox[0].plus(bbox[1].minus(bbox[0]).mult(0.5));
}
/**
* Getter for the corner array
*
* @return the array containing the corner points
*/
public Vector3d[] getBox() {
return bbox;
}
/**
* Calculates the width of the bounding box
*
* @return the width of the bounding box
*/
public double getWidth() {
return bbox[1].getY() - bbox[0].getY();
}
/**
* Calculates the height of the bounding box
*
* @return the height of the bounding box
*/
public double getHeight() {
return bbox[1].getZ() - bbox[0].getZ();
}
/**
* Calculates the depth of the bounding box
*
* @return the depth of the bounding box
*/
public double getDepth() {
return bbox[1].getX() - bbox[0].getX();
}
/**
* Returns the length of the longest side of the bounding box, ignoring the
* height. Only X and Y axis are considered
*
* @return the length of the longest side in X or Y direction
*/
public double getLongestSide() {
double width = getWidth();
double depth = getDepth();
if (width > depth) {
return width;
} else {
return depth;
}
}
/**
* Calculates the direction vector from the lower corner to the upper corner
*
* @return the direction vector from the lower corner to the upper corner
*/
public Vector3d getDiagonal() {
return bbox[1].minus(bbox[0]);
}
/**
* Calculates the distance between the corner points
*
* @return the distance between the corner points
*/
public double getDiagonalLength() {
return bbox[1].getDistance(bbox[0]);
}
public static BoundingBox of(FeatureMapper mapper) {
return BoundingBoxCalculator.calculateBoundingBox(mapper);
}
@Override
public String toString() {
return Arrays.toString(bbox);
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer.datastructure;
public class BufferConstants {
private BufferConstants() {
}
public static final int VERTEX = 0;
public static final int ELEMENT = 1;
public static final int SIZE = 2;
public static final int ATTRIBUTE_POSITION = 0;
public static final int ATTRIBUTE_COLOR = 1;
public static final int UNIFORM_0 = 1;
public static final int BINDING_INDEX_0 = 0;
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer.datastructure;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUtessellator;
import com.jogamp.opengl.glu.GLUtessellatorCallbackAdapter;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
/**
* Tesselator to create triangles out of polygons.
*
* @author Matthias Betz
*
*/
public class JoglTesselator {
private static final String DATA_WAS_NOT_A_LIST = "data was not a list";
private static final GLU glu = new GLU();
private static final GLUtessellator tess = GLU.gluNewTess();
private static final GLUtessellatorCallbackAdapter callback;
private static final ArrayList<Primitive> primitives = new ArrayList<>();
static {
callback = new GLUtessellatorCallbackAdapter() {
private Primitive lastPrimitive;
@Override
public void beginData(int type, Object data) {
if (!(data instanceof ArrayList<?>)) {
throw new IllegalStateException(DATA_WAS_NOT_A_LIST);
}
@SuppressWarnings("unchecked")
ArrayList<Vector3d> vertices = (ArrayList<Vector3d>) data;
lastPrimitive = new Primitive(type, vertices);
primitives.add(lastPrimitive);
}
@Override
public void vertexData(Object vertex, Object data) {
if (!(data instanceof ArrayList)) {
throw new IllegalStateException(DATA_WAS_NOT_A_LIST);
}
if (!(vertex instanceof Integer)) {
throw new IllegalStateException("vertex has to be an Integer");
}
lastPrimitive.addIndex((Integer) vertex);
}
@Override
public void combineData(double[] coords, Object[] vertexIndices, float[] weights, Object[] outgoingData,
Object data) {
if (!(data instanceof ArrayList<?>)) {
throw new IllegalStateException(DATA_WAS_NOT_A_LIST);
}
@SuppressWarnings("unchecked")
ArrayList<Vector3d> vertices = (ArrayList<Vector3d>) data;
// to ensure the coordinates are valid
double[] myCoords = Arrays.copyOf(coords, 3);
Vector3d newVertex = new Vector3d(myCoords);
outgoingData[0] = vertices.size();
vertices.add(newVertex);
}
@Override
public void errorData(int errnum, Object data) {
throw new TesselationException("GLU Error " + glu.gluErrorString(errnum));
}
};
GLU.gluTessCallback(tess, GLU.GLU_TESS_BEGIN_DATA, callback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_VERTEX_DATA, callback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_ERROR_DATA, callback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE_DATA, callback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_END_DATA, callback);
}
public static TesselatedPolygon tesselatePolygon(Polygon p) {
ArrayList<Vector3d> vertices = new ArrayList<>();
Vector3d normal = p.calculateNormal();
if (p.getExteriorRing().getVertices().isEmpty()) {
return new TesselatedPolygon(vertices, Collections.emptyList());
}
synchronized (tess) {
GLU.gluTessProperty(tess, GLU.GLU_TESS_BOUNDARY_ONLY, GL.GL_FALSE);
GLU.gluTessBeginPolygon(tess, vertices);
GLU.gluTessNormal(tess, normal.getX(), normal.getY(), normal.getZ());
// exterior ring
Ring ext = p.getExteriorRing();
createContour(vertices, ext);
// interior rings
for (Ring lr : p.getInteriorRings()) {
createContour(vertices, lr);
}
GLU.gluTessEndPolygon(tess);
ArrayList<Integer> indices = new ArrayList<>();
for (Primitive primitive : primitives) {
primitive.fillListWithIndices(indices);
}
primitives.clear();
return new TesselatedPolygon(vertices, indices);
}
}
private static void createContour(List<Vector3d> vertices, Ring lr) {
GLU.gluTessBeginContour(tess);
for (Vector3d v : lr.getVertices()) {
vertices.add(v);
GLU.gluTessVertex(tess, v.getCoordinates(), 0, vertices.size() - 1);
}
GLU.gluTessEndContour(tess);
}
private JoglTesselator() {
// only static usage
}
}
/*-
* Copyright 2021 Hochschule für Technik Stuttgart
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hft.stuttgart.citygml.viewer.datastructure;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import de.hft.stuttgart.citygml.viewer.math.Vector3d;
public class Polygon {
private Ring exteriorRing;
private List<Ring> interiorRings;
private Color color;
public Polygon(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public Ring getExteriorRing() {
return exteriorRing;
}
public void setExteriorRing(Ring exteriorRing) {
this.exteriorRing = exteriorRing;
}
public void addInteriorRing(Ring innerRing) {
if (interiorRings == null) {
interiorRings = new ArrayList<>();
}
interiorRings.add(innerRing);
}
public List<Ring> getInteriorRings() {
if (interiorRings == null) {
return Collections.emptyList();
}
return interiorRings;
}
public Vector3d calculateNormal() {
return exteriorRing.calculateNormal();
}
}
Markdown is supported
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