Merge remote-tracking branch 'origin/master' into 021214renderer

Conflicts:
	pom.xml
	src/net/mosstest/launcher/GUIClientsideLauncher.java
	src/net/mosstest/scripting/MapChunk.java
	src/net/mosstest/scripting/NodePosition.java
	src/net/mosstest/scripting/SimplexMapGenerator.java
	src/net/mosstest/servercore/IFileManager.java
	src/net/mosstest/servercore/IMossFile.java
	src/net/mosstest/servercore/LocalAssetLocator.java
	src/net/mosstest/servercore/LocalFile.java
	src/net/mosstest/servercore/LocalFileManager.java
	src/net/mosstest/servercore/MossWorld.java
	src/net/mosstest/servercore/MosstestSecurityManager.java
	src/net/mosstest/servercore/RenderProcessor.java
	tests/net/mosstest/tests/NodePositionTest.java
master
Aaron Chan 2014-03-02 16:20:20 -05:00
commit fc0976000a
47 changed files with 5018 additions and 5153 deletions

View File

@ -1,26 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="tests">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry including="**/*.java" kind="src" output="target/classes" path="src">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="tests">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

5
.gitignore vendored
View File

@ -31,3 +31,8 @@ src/git.properties
/stacktraces
/*.log
*.log
.idea
/.idea
/out
/.idea/*
/out/*

51
mosstest.iml Normal file
View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-math:2.2" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.1" level="project" />
<orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.1" level="project" />
<orderEntry type="library" name="Maven: net.java.jinput:jinput:2.0.5" level="project" />
<orderEntry type="library" name="Maven: net.java.jutils:jutils:1.0.0" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.java.jinput:jinput-platform:natives-linux:2.0.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.java.jinput:jinput-platform:natives-windows:2.0.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.java.jinput:jinput-platform:natives-osx:2.0.5" level="project" />
<orderEntry type="library" name="Maven: jme3:jme3-desktop:3.1.0" level="project" />
<orderEntry type="library" name="Maven: jme3:jme3-lwjgl:3.1.0" level="project" />
<orderEntry type="library" name="Maven: jme3:jme3-lwjgl-natives:3.1.0" level="project" />
<orderEntry type="library" name="Maven: jme3:jme3-lwjgl-niftygui:3.1.0" level="project" />
<orderEntry type="library" name="Maven: jme3:niftygui:3.1.0" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava-collections:r03" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava-annotations:r03" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava-primitives:r03" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava-base:r03" level="project" />
<orderEntry type="library" name="Maven: commons-cli:commons-cli:1.2" level="project" />
<orderEntry type="library" name="Maven: commons-configuration:commons-configuration:1.9" level="project" />
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.1.1" level="project" />
<orderEntry type="library" name="Maven: rhino:js:1.7R2" level="project" />
<orderEntry type="library" name="Maven: jme3:jme3-core:1.3.0" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-all:1.7" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni:1.7" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.hawtjni:hawtjni-runtime:1.8" level="project" />
<orderEntry type="library" name="Maven: org.iq80.leveldb:leveldb-api:0.5" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-osx:1.5" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-linux32:1.5" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-linux64:1.5" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-win32:1.5" level="project" />
<orderEntry type="library" name="Maven: org.fusesource.leveldbjni:leveldbjni-win64:1.5" level="project" />
<orderEntry type="library" name="Maven: jme3:lwjgl-workaround:9.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.8.1" level="project" />
<orderEntry type="library" name="Maven: log4j:log4j:1.2.15" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.4" level="project" />
</component>
</module>

669
pom.xml
View File

@ -1,332 +1,337 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mosstest</groupId>
<artifactId>mosstest</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>Mosstest</name>
<description>Open-source InfiniMiner remake</description>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</repository>
<repository>
<id>moss-forums</id>
<url>http://forum-mosstest.rhcloud.com/repository/</url>
</repository>
</repositories>
<build>
<testSourceDirectory>tests</testSourceDirectory>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.1.7</version>
<executions>
<execution>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<prefix>git</prefix>
<dateFormat>yyyy.MM.dd '@' HH:mm:ss z</dateFormat>
<verbose>true</verbose>
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
<skipPoms>true</skipPoms>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>src/git.properties</generateGitPropertiesFilename>
<failOnNoGitDirectory>false</failOnNoGitDirectory>
<gitDescribe>
<skip>false</skip>
<always>false</always>
<abbrev>7</abbrev>
<dirty>-dirty</dirty>
<forceLongFormat>false</forceLongFormat>
</gitDescribe>
</configuration>
</plugin>
<!-- END OF GIT COMMIT ID PLUGIN CONFIGURATION -->
<!-- <plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>clientbuild</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptors>
<descriptor>buildcfg/assembly-client.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>net.mosstest.launcher.GUIClientsideLauncher</mainClass>
</manifest>
</archive>
</configuration>
</execution>
<execution>
<id>serverbuild</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptors>
<descriptor>buildcfg/assembly-server.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>net.mosstest.launcher.ServerMain</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- signed jars -->
<excludes>
<exclude>bouncycastle:bcprov-jdk15</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- Main class -->
<mainClass>net.mosstest.servercore.MossWorld</mainClass>
</transformer>
<!-- Use resource transformers to prevent file overwrites -->
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>properties.properties</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
<resource>applicationContext.xml</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/cxf/cxf.extension</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
<resource>META-INF/cxf/bus-extensions.xml</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
<url>https://github.com/mosstest/mosstest</url>
<issueManagement>
<system>Launchpad</system>
<url>https://bugs.launchpad.net/mosstest</url>
</issueManagement>
<ciManagement>
<system>Travis-CI</system>
</ciManagement>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-desktop</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl-natives</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl-niftygui</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>niftygui</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-collections</artifactId>
<version>r03</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.7R2</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-core</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.fusesource.leveldbjni</groupId>
<artifactId>leveldbjni-all</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.lwjgl.lwjgl</groupId>
<artifactId>parent</artifactId>
<version>2.9.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>lwjgl-workaround</artifactId>
<version>9.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
</project>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mosstest</groupId>
<artifactId>mosstest</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>Mosstest</name>
<description>Open-source InfiniMiner remake</description>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</repository>
<repository>
<id>moss-forums</id>
<url>http://forum-mosstest.rhcloud.com/repository/</url>
</repository>
</repositories>
<build>
<testSourceDirectory>tests</testSourceDirectory>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.1.7</version>
<executions>
<execution>
<goals>
<goal>revision</goal>
</goals>
</execution>
</executions>
<configuration>
<prefix>git</prefix>
<dateFormat>yyyy.MM.dd '@' HH:mm:ss z</dateFormat>
<verbose>true</verbose>
<dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
<skipPoms>true</skipPoms>
<generateGitPropertiesFile>true</generateGitPropertiesFile>
<generateGitPropertiesFilename>src/git.properties</generateGitPropertiesFilename>
<failOnNoGitDirectory>false</failOnNoGitDirectory>
<gitDescribe>
<skip>false</skip>
<always>false</always>
<abbrev>7</abbrev>
<dirty>-dirty</dirty>
<forceLongFormat>false</forceLongFormat>
</gitDescribe>
</configuration>
</plugin>
<!-- END OF GIT COMMIT ID PLUGIN CONFIGURATION -->
<!-- <plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>clientbuild</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptors>
<descriptor>buildcfg/assembly-client.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>net.mosstest.launcher.GUIClientsideLauncher</mainClass>
</manifest>
</archive>
</configuration>
</execution>
<execution>
<id>serverbuild</id>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptors>
<descriptor>buildcfg/assembly-server.xml</descriptor>
</descriptors>
<archive>
<manifest>
<mainClass>net.mosstest.launcher.ServerMain</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<!-- signed jars -->
<excludes>
<exclude>bouncycastle:bcprov-jdk15</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- Main class -->
<mainClass>net.mosstest.servercore.MossWorld</mainClass>
</transformer>
<!-- Use resource transformers to prevent file overwrites -->
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>properties.properties</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
<resource>applicationContext.xml</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/cxf/cxf.extension</resource>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
<resource>META-INF/cxf/bus-extensions.xml</resource>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
<url>https://github.com/mosstest/mosstest</url>
<issueManagement>
<system>Launchpad</system>
<url>https://bugs.launchpad.net/mosstest</url>
</issueManagement>
<ciManagement>
<system>Travis-CI</system>
</ciManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>net.java.jinput</groupId>
<artifactId>jinput</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-desktop</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl-natives</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-lwjgl-niftygui</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>niftygui</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-collections</artifactId>
<version>r03</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.7R2</version>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>jme3-core</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.fusesource.leveldbjni</groupId>
<artifactId>leveldbjni-all</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.lwjgl.lwjgl</groupId>
<artifactId>parent</artifactId>
<version>2.9.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>jme3</groupId>
<artifactId>lwjgl-workaround</artifactId>
<version>9.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
>>>>>>> refs/remotes/origin/master
</project>

View File

@ -1,440 +1,439 @@
package net.mosstest.launcher;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog.ModalExclusionType;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import org.apache.log4j.Logger;
import net.mosstest.servercore.MossDebugUtils;
import net.mosstest.servercore.MossWorld;
import net.mosstest.servercore.MosstestSecurityManager;
// TODO: Auto-generated Javadoc
/**
* The Class GUIClientsideLauncher.
*/
public class GUIClientsideLauncher {
/** The logger. */
static Logger logger = Logger.getLogger(GUIClientsideLauncher.class);
/** The mdl. */
private SingleplayerListTableModel mdl;
static {
System.setSecurityManager(MosstestSecurityManager.instance);
}
/**
* The Class SingleplayerListEntry.
*/
public static class SingleplayerListEntry {
/** The name. */
public String name;
/** The description. */
public String description;
/** The game preset. */
public String gamePreset;
/**
* Instantiates a new singleplayer list entry.
*
* @param name the name
* @param description the description
* @param gamePreset the game preset
*/
public SingleplayerListEntry(String name, String description,
String gamePreset) {
this.name = name;
this.description = description;
this.gamePreset = gamePreset;
}
}
/** The frm mosstest client launcher. */
private JDialog frmMosstestClientLauncher;
/** The table. */
private JTable table;
/**
* Launch the application.
*
* @param args the arguments
* @throws InvocationTargetException the invocation target exception
* @throws InterruptedException the interrupted exception
*/
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
logger.info("Mosstest client starting...");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
logger.warn(Messages
.getString("GUIClientsideLauncher.WARN_SET_LAF")); //$NON-NLS-1$
}
EventQueue.invokeAndWait(new Runnable() {
public void run() {
try {
ArrayList<SingleplayerListEntry> entries = new ArrayList<SingleplayerListEntry>();
entries.add(new SingleplayerListEntry("name1", "desc1", //$NON-NLS-1$ //$NON-NLS-2$
"game1")); //$NON-NLS-1$
entries.add(new SingleplayerListEntry(
"name2", //$NON-NLS-1$
"desc2", //$NON-NLS-1$
"game2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); //$NON-NLS-1$
GUIClientsideLauncher window = new GUIClientsideLauncher(
entries);
window.frmMosstestClientLauncher.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @param singleplayerEntries the singleplayer entries
*/
public GUIClientsideLauncher(
ArrayList<SingleplayerListEntry> singleplayerEntries) {
initialize(singleplayerEntries);
}
/**
* Initialize the contents of the frame.
*
* @param singleplayerEntries the singleplayer entries
*/
private void initialize(ArrayList<SingleplayerListEntry> singleplayerEntries) {
this.frmMosstestClientLauncher = new JDialog();
this.frmMosstestClientLauncher.setModal(true);
this.frmMosstestClientLauncher.setModalityType(ModalityType.APPLICATION_MODAL);
this.frmMosstestClientLauncher.setTitle(Messages
.getString("GUIClientsideLauncher.DLG_TITLE")); //$NON-NLS-1$
this.frmMosstestClientLauncher.setBounds(100, 100, 800, 480);
this.frmMosstestClientLauncher
.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
this.frmMosstestClientLauncher.getContentPane().add(tabbedPane,
BorderLayout.CENTER);
JPanel singleplayerTab = new JPanel();
tabbedPane
.addTab(Messages
.getString("GUIClientsideLauncher.DLG_SINGLEPLAYER"), null, singleplayerTab, null); //$NON-NLS-1$
singleplayerTab.setLayout(new BorderLayout(0, 0));
this.table = new JTable();
this.table.setFillsViewportHeight(true);
this.mdl = new SingleplayerListTableModel(singleplayerEntries);
this.table.setModel(this.mdl);
this.table.getColumnModel().getColumn(0).setPreferredWidth(90);
this.table.getColumnModel().getColumn(1).setPreferredWidth(256);
this.table.getColumnModel().getColumn(2).setPreferredWidth(104);
this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel singleplayerControlBtns = new JPanel();
singleplayerTab.add(singleplayerControlBtns, BorderLayout.SOUTH);
singleplayerControlBtns.setLayout(new GridLayout(0, 4, 0, 0));
JButton btnPlaySingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_PLAY")); //$NON-NLS-1$
btnPlaySingleplayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int row = GUIClientsideLauncher.this.table.getSelectedRow();
if (row < 0) {
logger.warn("An attempt was made to start gameplay without selecting a world.");
JOptionPane.showMessageDialog(
null,
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED"), //$NON-NLS-1$
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED_TITLE"), //$NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return;
}
GUIClientsideLauncher.this.frmMosstestClientLauncher
.setVisible(false);
// below is testing code. in reality this would call a method to
// start a world and block. This should be in a try-catch block
// for the bug reporter to snatch up.
try {
throw new Exception();
// MossWorld w=new
// MossWorld((String)GUIClientsideLauncher.this.table.getModel().getValueAt(row,
// 0), -16511);
} catch (Exception e) {
logger.error("Uncaught exception in game code, opening bug reporter.");
StringBuilder s = new StringBuilder(
"Exception uncaught in code\r\n");
String fname = MossDebugUtils.writeStracktrace(e);
logger.error("Stracktrace has been written to " + fname);
GUIBugReportDialog bg = new GUIBugReportDialog(
MossDebugUtils.getDebugInformation(e));
bg.setVisible(true);
}
GUIClientsideLauncher.this.frmMosstestClientLauncher
.setVisible(true);
}
});
singleplayerControlBtns.add(btnPlaySingleplayer);
JButton btnNewSingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_NEW")); //$NON-NLS-1$
btnNewSingleplayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GUIWorldCreationDialog dlg = new GUIWorldCreationDialog();
dlg.setVisible(true);
if (dlg.dlgResult) {
logger.debug("Got world: "
+ dlg.nameField.getText()
+ " with desc: "
+ dlg.inputDesc.getText()
+ " with game: "
+ dlg.comboBox.getItemAt(dlg.comboBox
.getSelectedIndex())); //$NON-NLS-1$
} else
logger.info("World creation cancelled");
}
});
singleplayerControlBtns.add(btnNewSingleplayer);
JButton btnSettingsSingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_SETTINGS")); //$NON-NLS-1$
singleplayerControlBtns.add(btnSettingsSingleplayer);
JButton btnDelete = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_DELETE")); //$NON-NLS-1$
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = GUIClientsideLauncher.this.table.getSelectedRow();
if (row < 0) {
logger.warn("An attempt was made to delete a world, but none was selected.");
JOptionPane.showMessageDialog(
null,
Messages.getString("GUIClientsideLauncher.DLG_NO_WORLD_TO_DELETE"), //$NON-NLS-1$
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED_TITLE"), //$NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return;
}
}
});
singleplayerControlBtns.add(btnDelete);
// singleplayerTab.add(this.table, BorderLayout.CENTER);
JScrollPane singleplayerScrollPane = new JScrollPane(this.table);
singleplayerScrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
singleplayerTab.add(singleplayerScrollPane, BorderLayout.CENTER);
JPanel aboutTab = new JPanel();
tabbedPane
.addTab(Messages.getString("GUIClientsideLauncher.DLG_ABOUT"), null, aboutTab, null); //$NON-NLS-1$
tabbedPane.setEnabledAt(1, true);
SpringLayout sl_aboutTab = new SpringLayout();
aboutTab.setLayout(sl_aboutTab);
JPanel communityToolsButtonPanel = new JPanel();
sl_aboutTab.putConstraint(SpringLayout.NORTH,
communityToolsButtonPanel, 405, SpringLayout.NORTH, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.WEST, communityToolsButtonPanel,
0, SpringLayout.WEST, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.EAST, communityToolsButtonPanel,
787, SpringLayout.WEST, aboutTab);
aboutTab.add(communityToolsButtonPanel);
communityToolsButtonPanel.setLayout(new GridLayout(0, 5, 0, 0));
JButton btnReportBug = new JButton(
Messages.getString("GUIClientsideLauncher.23")); //$NON-NLS-1$
btnReportBug.setEnabled(false);
communityToolsButtonPanel.add(btnReportBug);
JButton btnRequestNewFeature = new JButton(
Messages.getString("GUIClientsideLauncher.24")); //$NON-NLS-1$
btnRequestNewFeature.setEnabled(false);
communityToolsButtonPanel.add(btnRequestNewFeature);
JButton btnVisitWebsite = new JButton(
Messages.getString("GUIClientsideLauncher.25")); //$NON-NLS-1$
btnVisitWebsite.setEnabled(false);
communityToolsButtonPanel.add(btnVisitWebsite);
JButton btnGithubProject = new JButton(
Messages.getString("GUIClientsideLauncher.26")); //$NON-NLS-1$
btnGithubProject.setEnabled(false);
communityToolsButtonPanel.add(btnGithubProject);
JButton btnVisitForums = new JButton(
Messages.getString("GUIClientsideLauncher.27")); //$NON-NLS-1$
btnVisitForums.setEnabled(false);
communityToolsButtonPanel.add(btnVisitForums);
JTextArea textArea = new JTextArea();
aboutTab.add(textArea);
textArea.setText(" __ __ ____ _____ _____ _______ ______ _____ _______ \r\n"
+ " | \\/ |/ __ \\ / ____/ ____|__ __| ____|/ ____|__ __|\r\n"
+ " | \\ / | | | | (___| (___ | | | |__ | (___ | | \r\n"
+ " | |\\/| | | | |\\___ \\\\___ \\ | | | __| \\___ \\ | | \r\n"
+ " | | | | |__| |____) |___) | | | | |____ ____) | | | \r\n"
+ " |_| |_|\\____/|_____/_____/ |_| |______|_____/ |_| \r\n"
+ " \r\n"
+ " 0.0.1-initial \r\n"
+ ""
+ Messages
.getString("GUIClientsideLauncher.NOTICE_PRIMARY_AUTHORS") //$NON-NLS-1$
+ Messages
.getString("GUIClientsideLauncher.NOTICE_DEFAULT_GAME_CODE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.SYS_NEWLINE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.USES_LIBS") //$NON-NLS-1$
+ "* Apache Commons Lang\r\n"
+ "* Apache Commons Collections\r\n"
+ "* JInput\r\n"
+ "* jmonkeyengine/jme3\r\n"
+ "* niftygui\r\n"
+ "* Google Guava Collections\r\n"
+ "* Apache Commons CLI (currently unused)\r\n"
+ "* Apache Commons Configuration\r\n"
+ "* Mozilla Rhino\r\n"
+ "* leveldbjni\r\n"
+ "* junit4 for testing\r\n"
+ Messages.getString("GUIClientsideLauncher.SYS_NEWLINE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.NOTICE_TOOLS_USED")); //$NON-NLS-1$
textArea.setWrapStyleWord(true);
textArea.setBackground(new Color(192, 192, 192));
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
sl_aboutTab.putConstraint(SpringLayout.NORTH, scrollPane, 0,
SpringLayout.NORTH, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.WEST, scrollPane, 0,
SpringLayout.WEST, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.SOUTH, scrollPane, 0,
SpringLayout.NORTH, communityToolsButtonPanel);
sl_aboutTab.putConstraint(SpringLayout.EAST, scrollPane, 787,
SpringLayout.WEST, aboutTab);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
aboutTab.add(scrollPane);
frmMosstestClientLauncher.setVisible(true);
}
/**
* The Class SingleplayerListTableModel.
*/
class SingleplayerListTableModel extends AbstractTableModel {
/** The column names. */
private String[] columnNames = {
Messages.getString("GUIClientsideLauncher.COL_WORLD_NAME"), Messages.getString("GUIClientsideLauncher.COL_WORLD_DESC"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("GUIClientsideLauncher.COL_GAME_PRESET") }; //$NON-NLS-1$
/** The entries. */
private ArrayList<SingleplayerListEntry> entries = new ArrayList<>();
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return this.columnNames.length;
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount() {
return this.entries.size();
}
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnName(int)
*/
public String getColumnName(int col) {
return this.columnNames[col];
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int col) {
SingleplayerListEntry entry = this.entries.get(row);
switch (col) {
case 0:
return entry.name;
case 1:
return entry.description;
case 2:
return entry.gamePreset;
default:
return null;
}
}
/*
* All entries are strings *at the moment*.
*/
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnClass(int)
*/
public Class<?> getColumnClass(int c) {
return String.class;
}
/*
* Don't need to implement this method unless your table's editable.
*/
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
*/
public boolean isCellEditable(int row, int col) {
return false;
}
/**
* Instantiates a new singleplayer list table model.
*
* @param entries the entries
*/
public SingleplayerListTableModel(
ArrayList<SingleplayerListEntry> entries) {
this.entries = entries;
}
}
}
package net.mosstest.launcher;
import net.mosstest.servercore.MossDebugUtils;
import net.mosstest.servercore.MosstestSecurityManager;
import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
// TODO: Auto-generated Javadoc
/**
* The Class GUIClientsideLauncher.
*/
public class GUIClientsideLauncher {
/**
* The logger.
*/
static Logger logger = Logger.getLogger(GUIClientsideLauncher.class);
/**
* The mdl.
*/
private SingleplayerListTableModel mdl;
static {
System.setSecurityManager(MosstestSecurityManager.instance);
}
/**
* The Class SingleplayerListEntry.
*/
public static class SingleplayerListEntry {
/**
* The name.
*/
public String name;
/**
* The description.
*/
public String description;
/**
* The game preset.
*/
public String gamePreset;
/**
* Instantiates a new singleplayer list entry.
*
* @param name the name
* @param description the description
* @param gamePreset the game preset
*/
public SingleplayerListEntry(String name, String description,
String gamePreset) {
this.name = name;
this.description = description;
this.gamePreset = gamePreset;
}
}
/**
* The frm mosstest client launcher.
*/
private JDialog frmMosstestClientLauncher;
/**
* The table.
*/
private JTable table;
/**
* Launch the application.
*
* @param args the arguments
* @throws InvocationTargetException the invocation target exception
* @throws InterruptedException the interrupted exception
*/
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
logger.info("Mosstest client starting...");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
logger.warn(Messages
.getString("GUIClientsideLauncher.WARN_SET_LAF")); //$NON-NLS-1$
}
EventQueue.invokeAndWait(new Runnable() {
public void run() {
try {
ArrayList<SingleplayerListEntry> entries = new ArrayList<>();
entries.add(new SingleplayerListEntry("name1", "desc1", //$NON-NLS-1$ //$NON-NLS-2$
"game1")); //$NON-NLS-1$
entries.add(new SingleplayerListEntry(
"name2", //$NON-NLS-1$
"desc2", //$NON-NLS-1$
"game2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); //$NON-NLS-1$
GUIClientsideLauncher window = new GUIClientsideLauncher(
entries);
window.frmMosstestClientLauncher.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @param singleplayerEntries the singleplayer entries
*/
public GUIClientsideLauncher(
ArrayList<SingleplayerListEntry> singleplayerEntries) {
initialize(singleplayerEntries);
}
/**
* Initialize the contents of the frame.
*
* @param singleplayerEntries the singleplayer entries
*/
private void initialize(ArrayList<SingleplayerListEntry> singleplayerEntries) {
this.frmMosstestClientLauncher = new JDialog();
this.frmMosstestClientLauncher.setModal(true);
this.frmMosstestClientLauncher.setModalityType(ModalityType.APPLICATION_MODAL);
this.frmMosstestClientLauncher.setTitle(Messages
.getString("GUIClientsideLauncher.DLG_TITLE")); //$NON-NLS-1$
this.frmMosstestClientLauncher.setBounds(100, 100, 800, 480);
this.frmMosstestClientLauncher
.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
this.frmMosstestClientLauncher.getContentPane().add(tabbedPane,
BorderLayout.CENTER);
JPanel singleplayerTab = new JPanel();
tabbedPane
.addTab(Messages
.getString("GUIClientsideLauncher.DLG_SINGLEPLAYER"), null, singleplayerTab, null); //$NON-NLS-1$
singleplayerTab.setLayout(new BorderLayout(0, 0));
this.table = new JTable();
this.table.setFillsViewportHeight(true);
this.mdl = new SingleplayerListTableModel(singleplayerEntries);
this.table.setModel(this.mdl);
this.table.getColumnModel().getColumn(0).setPreferredWidth(90);
this.table.getColumnModel().getColumn(1).setPreferredWidth(256);
this.table.getColumnModel().getColumn(2).setPreferredWidth(104);
this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel singleplayerControlBtns = new JPanel();
singleplayerTab.add(singleplayerControlBtns, BorderLayout.SOUTH);
singleplayerControlBtns.setLayout(new GridLayout(0, 4, 0, 0));
JButton btnPlaySingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_PLAY")); //$NON-NLS-1$
btnPlaySingleplayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int row = GUIClientsideLauncher.this.table.getSelectedRow();
if (row < 0) {
logger.warn("An attempt was made to start gameplay without selecting a world.");
JOptionPane.showMessageDialog(
null,
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED"), //$NON-NLS-1$
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED_TITLE"), //$NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return;
}
GUIClientsideLauncher.this.frmMosstestClientLauncher
.setVisible(false);
// below is testing code. in reality this would call a method to
// start a world and block. This should be in a try-catch block
// for the bug reporter to snatch up.
try {
throw new Exception();
// MossWorld w=new
// MossWorld((String)GUIClientsideLauncher.this.table.getModel().getValueAt(row,
// 0), -16511);
} catch (Exception e) {
logger.error("Uncaught exception in game code, opening bug reporter.");
String fname = MossDebugUtils.writeStracktrace(e);
logger.error("Stracktrace has been written to " + fname);
GUIBugReportDialog bg = new GUIBugReportDialog(
MossDebugUtils.getDebugInformation(e));
bg.setVisible(true);
}
GUIClientsideLauncher.this.frmMosstestClientLauncher
.setVisible(true);
}
});
singleplayerControlBtns.add(btnPlaySingleplayer);
JButton btnNewSingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_NEW")); //$NON-NLS-1$
btnNewSingleplayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GUIWorldCreationDialog dlg = new GUIWorldCreationDialog();
dlg.setVisible(true);
if (dlg.dlgResult) {
logger.debug("Got world: "
+ dlg.nameField.getText()
+ " with desc: "
+ dlg.inputDesc.getText()
+ " with game: "
+ dlg.comboBox.getItemAt(dlg.comboBox
.getSelectedIndex())); //$NON-NLS-1$
} else
logger.info("World creation cancelled");
}
});
singleplayerControlBtns.add(btnNewSingleplayer);
JButton btnSettingsSingleplayer = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_SETTINGS")); //$NON-NLS-1$
singleplayerControlBtns.add(btnSettingsSingleplayer);
JButton btnDelete = new JButton(
Messages.getString("GUIClientsideLauncher.DLG_DELETE")); //$NON-NLS-1$
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = GUIClientsideLauncher.this.table.getSelectedRow();
if (row < 0) {
logger.warn("An attempt was made to delete a world, but none was selected.");
JOptionPane.showMessageDialog(
null,
Messages.getString("GUIClientsideLauncher.DLG_NO_WORLD_TO_DELETE"), //$NON-NLS-1$
Messages.getString("GUIClientsideLauncher.ERR_NO_WORLD_SELECTED_TITLE"), //$NON-NLS-1$
JOptionPane.WARNING_MESSAGE);
return;
}
}
});
singleplayerControlBtns.add(btnDelete);
// singleplayerTab.add(this.table, BorderLayout.CENTER);
JScrollPane singleplayerScrollPane = new JScrollPane(this.table);
singleplayerScrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
singleplayerTab.add(singleplayerScrollPane, BorderLayout.CENTER);
JPanel aboutTab = new JPanel();
tabbedPane
.addTab(Messages.getString("GUIClientsideLauncher.DLG_ABOUT"), null, aboutTab, null); //$NON-NLS-1$
tabbedPane.setEnabledAt(1, true);
SpringLayout sl_aboutTab = new SpringLayout();
aboutTab.setLayout(sl_aboutTab);
JPanel communityToolsButtonPanel = new JPanel();
sl_aboutTab.putConstraint(SpringLayout.NORTH,
communityToolsButtonPanel, 405, SpringLayout.NORTH, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.WEST, communityToolsButtonPanel,
0, SpringLayout.WEST, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.EAST, communityToolsButtonPanel,
787, SpringLayout.WEST, aboutTab);
aboutTab.add(communityToolsButtonPanel);
communityToolsButtonPanel.setLayout(new GridLayout(0, 5, 0, 0));
JButton btnReportBug = new JButton(
Messages.getString("GUIClientsideLauncher.23")); //$NON-NLS-1$
btnReportBug.setEnabled(false);
communityToolsButtonPanel.add(btnReportBug);
JButton btnRequestNewFeature = new JButton(
Messages.getString("GUIClientsideLauncher.24")); //$NON-NLS-1$
btnRequestNewFeature.setEnabled(false);
communityToolsButtonPanel.add(btnRequestNewFeature);
JButton btnVisitWebsite = new JButton(
Messages.getString("GUIClientsideLauncher.25")); //$NON-NLS-1$
btnVisitWebsite.setEnabled(false);
communityToolsButtonPanel.add(btnVisitWebsite);
JButton btnGithubProject = new JButton(
Messages.getString("GUIClientsideLauncher.26")); //$NON-NLS-1$
btnGithubProject.setEnabled(false);
communityToolsButtonPanel.add(btnGithubProject);
JButton btnVisitForums = new JButton(
Messages.getString("GUIClientsideLauncher.27")); //$NON-NLS-1$
btnVisitForums.setEnabled(false);
communityToolsButtonPanel.add(btnVisitForums);
JTextArea textArea = new JTextArea();
aboutTab.add(textArea);
textArea.setText(" __ __ ____ _____ _____ _______ ______ _____ _______ \r\n"
+ " | \\/ |/ __ \\ / ____/ ____|__ __| ____|/ ____|__ __|\r\n"
+ " | \\ / | | | | (___| (___ | | | |__ | (___ | | \r\n"
+ " | |\\/| | | | |\\___ \\\\___ \\ | | | __| \\___ \\ | | \r\n"
+ " | | | | |__| |____) |___) | | | | |____ ____) | | | \r\n"
+ " |_| |_|\\____/|_____/_____/ |_| |______|_____/ |_| \r\n"
+ " \r\n"
+ " 0.0.1-initial \r\n"
+ ""
+ Messages
.getString("GUIClientsideLauncher.NOTICE_PRIMARY_AUTHORS") //$NON-NLS-1$
+ Messages
.getString("GUIClientsideLauncher.NOTICE_DEFAULT_GAME_CODE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.SYS_NEWLINE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.USES_LIBS") //$NON-NLS-1$
+ "* Apache Commons Lang\r\n"
+ "* Apache Commons Collections\r\n"
+ "* JInput\r\n"
+ "* jmonkeyengine/jme3\r\n"
+ "* niftygui\r\n"
+ "* Google Guava Collections\r\n"
+ "* Apache Commons CLI\r\n"
+ "* Apache Commons Configuration\r\n"
+ "* Mozilla Rhino\r\n"
+ "* leveldbjni\r\n"
+ "* junit4 for testing\r\n"
+ Messages.getString("GUIClientsideLauncher.SYS_NEWLINE") //$NON-NLS-1$
+ Messages.getString("GUIClientsideLauncher.NOTICE_TOOLS_USED")); //$NON-NLS-1$
textArea.setWrapStyleWord(true);
textArea.setBackground(new Color(192, 192, 192));
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
sl_aboutTab.putConstraint(SpringLayout.NORTH, scrollPane, 0,
SpringLayout.NORTH, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.WEST, scrollPane, 0,
SpringLayout.WEST, aboutTab);
sl_aboutTab.putConstraint(SpringLayout.SOUTH, scrollPane, 0,
SpringLayout.NORTH, communityToolsButtonPanel);
sl_aboutTab.putConstraint(SpringLayout.EAST, scrollPane, 787,
SpringLayout.WEST, aboutTab);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
aboutTab.add(scrollPane);
frmMosstestClientLauncher.setVisible(true);
}
/**
* The Class SingleplayerListTableModel.
*/
class SingleplayerListTableModel extends AbstractTableModel {
/**
* The column names.
*/
private String[] columnNames = {
Messages.getString("GUIClientsideLauncher.COL_WORLD_NAME"), Messages.getString("GUIClientsideLauncher.COL_WORLD_DESC"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("GUIClientsideLauncher.COL_GAME_PRESET")}; //$NON-NLS-1$
/**
* The entries.
*/
private ArrayList<SingleplayerListEntry> entries = new ArrayList<>();
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return this.columnNames.length;
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount() {
return this.entries.size();
}
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnName(int)
*/
public String getColumnName(int col) {
return this.columnNames[col];
}
/* (non-Javadoc)
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int col) {
SingleplayerListEntry entry = this.entries.get(row);
switch (col) {
case 0:
return entry.name;
case 1:
return entry.description;
case 2:
return entry.gamePreset;
default:
return null;
}
}
/*
* All entries are strings *at the moment*.
*/
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#getColumnClass(int)
*/
public Class<?> getColumnClass(int c) {
return String.class;
}
/*
* Don't need to implement this method unless your table's editable.
*/
/* (non-Javadoc)
* @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
*/
public boolean isCellEditable(int row, int col) {
return false;
}
/**
* Instantiates a new singleplayer list table model.
*
* @param entries the entries
*/
public SingleplayerListTableModel(
ArrayList<SingleplayerListEntry> entries) {
this.entries = entries;
}
}
}

View File

@ -1,156 +0,0 @@
package net.mosstest.scripting;
import net.mosstest.scripting.MossTool.InteractType;
// TODO: Auto-generated Javadoc
/**
* The Class AirNodeParams.
*/
public class AirNodeParams implements INodeParams {
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#onPunch(net.mosstest.scripting.Player, net.mosstest.scripting.MossItem, net.mosstest.scripting.NodePosition, net.mosstest.scripting.Face)
*/
@Override
public void onPunch(Player player, MossItem tool,
NodePosition target, Face punchedFace)
throws EventProcessingCompletedSignal {
// pass
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#onDig(net.mosstest.scripting.Player, net.mosstest.scripting.MossItem, net.mosstest.scripting.NodePosition, net.mosstest.scripting.Face)
*/
@Override
public void onDig(Player player, MossItem tool, NodePosition target,
Face punchedFace) throws EventProcessingCompletedSignal {
// pass
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#onPlaceNextTo(net.mosstest.scripting.Player, net.mosstest.scripting.NodePosition, net.mosstest.scripting.NodePosition)
*/
@Override
public void onPlaceNextTo(Player player, NodePosition target,
NodePosition placed) throws EventProcessingCompletedSignal {
// pass
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#onRightClick(net.mosstest.scripting.Player, net.mosstest.scripting.MossItem, net.mosstest.scripting.NodePosition, net.mosstest.scripting.Face)
*/
@Override
public void onRightClick(Player player, MossItem tool,
NodePosition target, Face clickedFace)
throws EventProcessingCompletedSignal {
// pass
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#onStepOn(net.mosstest.scripting.Player, net.mosstest.scripting.NodePosition)
*/
@Override
public boolean onStepOn(Player player, NodePosition pos)
throws EventProcessingCompletedSignal {
// pass
return false;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#jumpOffHeight(net.mosstest.scripting.Player)
*/
@Override
public double jumpOffHeight(Player player) {
return 0;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcBounceHeight(net.mosstest.scripting.Player, double)
*/
@Override
public double calcBounceHeight(Player player, double fallheight) {
return 0;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSinkIn(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkIn(Player player, double fallheight) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSinkEscape(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkEscape(Player player, double sinkheight) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcWalkSpeed(net.mosstest.scripting.Player)
*/
@Override
public double calcWalkSpeed(Player player) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSprintSpeed(net.mosstest.scripting.Player)
*/
@Override
public double calcSprintSpeed(Player player) {
return 4;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcFallDamage(net.mosstest.scripting.Player, double)
*/
@Override
public double calcFallDamage(Player player, double height) {
return 0;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#shouldContinueFall(net.mosstest.scripting.Player, double)
*/
@Override
public boolean shouldContinueFall(Player player, double height) {
return true;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#shouldHitAimRay(net.mosstest.scripting.Player, double)
*/
@Override
public boolean shouldHitAimRay(Player player, double distance) {
return false;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSinkActive(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkActive(Player player, double fallheight) {
// TODO Auto-generated method stub
return 0;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcInteractProperties(net.mosstest.scripting.MossTool.InteractType, double)
*/
@Override
public double calcInteractProperties(InteractType key, double strength) {
// TODO Auto-generated method stub
return 0;
}
}

View File

@ -1,42 +1,34 @@
package net.mosstest.scripting;
import net.mosstest.servercore.SessionManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import net.mosstest.servercore.SessionManager;
// TODO: Auto-generated Javadoc
/**
* The Class AntiCheatController.
*/
public class AntiCheatController {
/** The checks. */
protected ArrayList<AntiCheatCheck> checks = new ArrayList<>();
/** The handlers. */
protected ArrayList<AntiCheatHandler> handlers = new ArrayList<>();
/** The env. */
protected MossScriptEnv env;
/** The sess. */
protected SessionManager sess;
/** The run. */
protected volatile boolean run = false;
/** The need deaths from. */
protected AtomicInteger needDeathsFrom = new AtomicInteger(0);
/**
* Instantiates a new anti cheat controller.
*
* @param env the env
* @param sess the sess
*/
public AntiCheatController(MossScriptEnv env, SessionManager sess) {
protected final List<AntiCheatCheck> checks = new ArrayList<>();
protected final List<AntiCheatHandler> handlers = new ArrayList<>();
protected MossScriptEnv env;
protected SessionManager sess;
protected volatile boolean run = false;
protected AtomicInteger needDeathsFrom = new AtomicInteger(0);
/**
* Instantiates a new anticheat controller.
*/
public AntiCheatController(MossScriptEnv env, SessionManager sess) {
this.env = env;
this.sess = sess;
}
@ -64,10 +56,10 @@ public class AntiCheatController {
}
/** The threads. */
private ArrayList<Thread> threads = new ArrayList<>();
private List<Thread> threads = new ArrayList<>();
/**
* Start threads.
/**
* Start threads.
*
* @param threads the threads
* @param priority the priority

View File

@ -55,13 +55,7 @@ public class DefaultNodeParams implements INodeParams {
return;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#jumpOffHeight(net.mosstest.scripting.Player)
*/
@Override
public double jumpOffHeight(Player player) {
return 1.125;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcWalkSpeed(net.mosstest.scripting.Player)
@ -79,21 +73,7 @@ public class DefaultNodeParams implements INodeParams {
return 4;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSinkIn(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkIn(Player player, double fallheight) {
return 0;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcSinkEscape(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkEscape(Player player, double fallheight) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.INodeParams#calcBounceHeight(net.mosstest.scripting.Player, double)
@ -143,4 +123,14 @@ public class DefaultNodeParams implements INodeParams {
public double calcInteractProperties(InteractType key, double strength) {
return 1;
}
@Override
public double calcSinkPassive(Player player, double fallheight) {
return 0;
}
@Override
public double calcSinkJump(Player player, double sinkheight) {
return 0;
}
}

View File

@ -4,87 +4,93 @@ import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MapGeneratorException;
// TODO: Auto-generated Javadoc
/**
* The Class FlatMapGenerator.
*/
public class FlatMapGenerator implements IMapGenerator {
/** The seed. */
long seed;
/** The nm. */
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.seed = seed;
this.nm=nm;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] nodes = new int[16][16][16];
try {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode(
"mg:air", false).getNodeId() : this.nm.getNode( //$NON-NLS-1$
"mg:ground", false).getNodeId(); //$NON-NLS-1$
public static final int CHUNK_DIMENSION = 16;
/**
* The seed.
*/
long seed;
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
nodes[x][y][z] = fillNode;
}
}
/**
* The nm.
*/
INodeManager nm;
}
return new MapChunk(pos, nodes, new boolean[16][16][16]);
} catch (NullPointerException e) {
throw new MapGeneratorException();
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.seed = seed;
this.nm = nm;
}
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] nodes = new int[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION];
try {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode(
"mg:air", false).getNodeId() : this.nm.getNode( //$NON-NLS-1$
"mg:ground", false).getNodeId(); //$NON-NLS-1$
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode("mg:air", //$NON-NLS-1$
false).getNodeId() : this.nm
.getNode("mg:ground", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < CHUNK_DIMENSION; x++) {
for (int y = 0; y < CHUNK_DIMENSION; y++) {
for (int z = 0; z < CHUNK_DIMENSION; z++) {
nodes[x][y][z] = fillNode;
}
}
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
if (lightNodes[x][y][z] == 0) {
// operation in place on passed in array as per
// contract
lightNodes[x][y][z] = fillNode;
}
}
}
}
return new MapChunk(pos, nodes, new boolean[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION]);
} catch (NullPointerException e) {
throw new MapGeneratorException();
}
}
}
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode("mg:air", //$NON-NLS-1$
false).getNodeId() : this.nm
.getNode("mg:ground", false).getNodeId(); //$NON-NLS-1$
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
// TODO Auto-generated method stub
for (int x = 0; x < CHUNK_DIMENSION; x++) {
for (int y = 0; y < CHUNK_DIMENSION; y++) {
for (int z = 0; z < CHUNK_DIMENSION; z++) {
if (lightNodes[x][y][z] == 0) {
// operation in place on passed in array as per
// contract
lightNodes[x][y][z] = fillNode;
}
}
}
}
}
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
// TODO Auto-generated method stub
}
}

View File

@ -12,15 +12,21 @@ package net.mosstest.scripting;
*
*/
public interface INodeParams {
public static final double GRAVITY_EARTH = -9.81;
/**
* Function that is called when a node is punched.
*
* @param player The player punching the node.
* @param tool The tool being used to punch the node.
* @param target The position of the targeted node.
* @param punchedFace The face being punched.
* @throws EventProcessingCompletedSignal the event processing completed signal
*
* @param player
* The player punching the node.
* @param tool
* The tool being used to punch the node.
* @param target
* The position of the targeted node.
* @param punchedFace
* The face being punched.
* @throws EventProcessingCompletedSignal
* the event processing completed signal
*/
public abstract void onPunch(Player player, MossItem tool,
NodePosition target, Face punchedFace)
@ -28,9 +34,11 @@ public interface INodeParams {
/**
* Determines if a fall should continue.
*
* @param player The player.
* @param height The height.
*
* @param player
* The player.
* @param height
* The height.
* @return A boolean representing whether the fall should continue or be
* marked as a fall.
*/
@ -38,15 +46,20 @@ public interface INodeParams {
/**
* Called when a node is fully dug.
*
* @param player The player digging the node.
* @param tool The tool used to dig the node.
* @param target The position of the node that has been dug.
* @param punchedFace The face on which the the tool was pointed when digging was
*
* @param player
* The player digging the node.
* @param tool
* The tool used to dig the node.
* @param target
* The position of the node that has been dug.
* @param punchedFace
* The face on which the the tool was pointed when digging was
* complete. Note that if a dig begins on one face but the player
* moves the aim to another face the onPunch handler may receive
* a different face than this handler.
* @throws EventProcessingCompletedSignal the event processing completed signal
* @throws EventProcessingCompletedSignal
* the event processing completed signal
*/
public abstract void onDig(Player player, MossItem tool,
NodePosition target, Face punchedFace)
@ -55,11 +68,15 @@ public interface INodeParams {
/**
* Called when a node is placed directly above, below, left, right, in front
* of, or behind this node.
*
* @param player The player placing the node.
* @param target the target
* @param placed the placed
* @throws EventProcessingCompletedSignal the event processing completed signal
*
* @param player
* The player placing the node.
* @param target
* the target
* @param placed
* the placed
* @throws EventProcessingCompletedSignal
* the event processing completed signal
*/
public abstract void onPlaceNextTo(Player player, NodePosition target,
NodePosition placed) throws EventProcessingCompletedSignal;
@ -68,12 +85,17 @@ public interface INodeParams {
* Called when a right-click is done on a node. Note that this is called
* even if no node is placed, such as if the player is not holding anything,
* or is holding a tool.
*
* @param player Player performing the action.
* @param tool Tool held by user in active slot during this action.
* @param target Position of targeted node
* @param clickedFace Face which was right-clicked.
* @throws EventProcessingCompletedSignal the event processing completed signal
*
* @param player
* Player performing the action.
* @param tool
* Tool held by user in active slot during this action.
* @param target
* Position of targeted node
* @param clickedFace
* Face which was right-clicked.
* @throws EventProcessingCompletedSignal
* the event processing completed signal
*/
public abstract void onRightClick(Player player, MossItem tool,
NodePosition target, Face clickedFace)
@ -82,45 +104,29 @@ public interface INodeParams {
/**
* Called when a player steps on a node either from jumping, falling, or
* walking forward.
*
* @param player Player that steps on this node.
* @param pos Position of node that is stepped on.
*
* @param player
* Player that steps on this node.
* @param pos
* Position of node that is stepped on.
* @return Currently unused.
* @throws EventProcessingCompletedSignal the event processing completed signal
* @throws EventProcessingCompletedSignal
* the event processing completed signal
*/
public abstract boolean onStepOn(Player player, NodePosition pos)
throws EventProcessingCompletedSignal;
/**
* Calculates the height a player may jump off of this node. One node is
* equal to 1.0.
*
* @param player the player
* @return The height the player may jump off this node.
*/
public abstract double jumpOffHeight(Player player);
/**
* Calculates the height a player will bounce when landing on this node.
*
* @param player the player
* @param fallheight The height from which the player has fallen.
* @return A double value representing the height the player is to bounce.
*/
public abstract double calcBounceHeight(Player player, double fallheight);
/**
* Calculates at which rate a player will sink in after landing on this
* node.
*
* @param player
* The player to calculate sink for.
* the player
* @param fallheight
* The height from which they have fallen. 0 if the player walks
* onto the node without jumping or falling.
* @return The rate for the player to sink.
* The height from which the player has fallen. This may be 0.
* @return A double value representing the height the player is to bounce. A
* negative height represents sinking.
*/
public abstract double calcSinkIn(Player player, double fallheight);
public abstract double calcBounceHeight(Player player, double fallheight);
/**
* Calculates at which rate a player will sink in if they are holding the
@ -132,10 +138,24 @@ public interface INodeParams {
* The height from which they have fallen. 0 if the player walks
* onto the node without jumping or falling(feet at surface), or
* negative if they have already sunk in partially.
* @return The rate for the player to sink.
* @return The rate for the player to rise or sink, positive for rising
*/
public abstract double calcSinkActive(Player player, double fallheight);
/**
* Calculates at which rate a player will sink in if they are holding
* neither the jump nor descend key
*
* @param player
* The player to calculate sink for.
* @param fallheight
* The height from which they have fallen. 0 if the player walks
* onto the node without jumping or falling(feet at surface), or
* negative if they have already sunk in partially.
* @return The rate for the player to rise or sink, positive for rising
*/
public abstract double calcSinkPassive(Player player, double fallheight);
/**
* Calculates the rate at which a player will rise out of this node if they
* have sunk in and are pressing the jump key. If the player is in multiple
@ -145,13 +165,14 @@ public interface INodeParams {
* The player to perform the calculation for.
* @param sinkheight
* The depth to which the player has sunk. 0 is the surface at
* the player's feet. 1 corresponds to the player's feet being at
* the player's feet (and corresponds to jumping off a solid
* node's surface). 1 corresponds to the player's feet being at
* the bottom of the node, and 2 or more is if the player is
* submerged in multiple nodes.
* @return The rate at which the player should rise when they hold the key
* corresponding to jumping, in nodes per second.
*/
public abstract double calcSinkEscape(Player player, double sinkheight);
public abstract double calcSinkJump(Player player, double sinkheight);
/**
* Calculates the speed at which a player will move across this node when
@ -159,6 +180,8 @@ public interface INodeParams {
*
* @param player
* The player for which the walk rate is being calculated.
* @param depth
* The depth to which the player has sunk, 0 for surface.
* @return The rate in nodes/second at which the player should walk.
*/
public abstract double calcWalkSpeed(Player player);

View File

@ -43,10 +43,7 @@ public class LiquidFlowingNodeParams extends DefaultNodeParams implements
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#jumpOffHeight(net.mosstest.scripting.Player)
*/
@Override
public double jumpOffHeight(Player player) {
return 1.125;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcWalkSpeed(net.mosstest.scripting.Player)
@ -64,21 +61,7 @@ public class LiquidFlowingNodeParams extends DefaultNodeParams implements
return 0.8;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcSinkIn(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkIn(Player player, double fallheight) {
return 0.4;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcSinkEscape(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkEscape(Player player, double fallheight) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcBounceHeight(net.mosstest.scripting.Player, double)
@ -104,4 +87,17 @@ public class LiquidFlowingNodeParams extends DefaultNodeParams implements
return false;
}
@Override
public double calcSinkActive(Player player, double fallheight) {
return -0.8;
}
@Override
public double calcSinkPassive(Player player, double fallheight) {
return (fallheight > -0.25)?0:0.05;
}
@Override
public double calcSinkJump(Player player, double sinkheight) {
return (sinkheight > -0.25)?0:0.6;
}
}

View File

@ -40,17 +40,6 @@ public class LiquidSourceNodeParams extends DefaultNodeParams implements
return false;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#jumpOffHeight(net.mosstest.scripting.Player)
*/
@Override
public double jumpOffHeight(Player player) {
return 1.125;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcWalkSpeed(net.mosstest.scripting.Player)
*/
@Override
public double calcWalkSpeed(Player player) {
return 0.6;
@ -64,21 +53,7 @@ public class LiquidSourceNodeParams extends DefaultNodeParams implements
return 0.8;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcSinkIn(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkIn(Player player, double fallheight) {
return 0.4;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcSinkEscape(net.mosstest.scripting.Player, double)
*/
@Override
public double calcSinkEscape(Player player, double fallheight) {
return 1;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.DefaultNodeParams#calcBounceHeight(net.mosstest.scripting.Player, double)
@ -104,4 +79,17 @@ public class LiquidSourceNodeParams extends DefaultNodeParams implements
return false;
}
}
@Override
public double calcSinkActive(Player player, double fallheight) {
return -0.8;
}
@Override
public double calcSinkPassive(Player player, double fallheight) {
return (fallheight > -0.25)?0:0.05;
}
@Override
public double calcSinkJump(Player player, double sinkheight) {
return (sinkheight > -0.25)?0:0.6;
}
}

View File

@ -1,227 +1,232 @@
package net.mosstest.scripting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import net.mosstest.servercore.ExceptionHandler;
import net.mosstest.servercore.MapDatabase;
import net.mosstest.servercore.MapGeneratorException;
import net.mosstest.servercore.Messages;
import net.mosstest.servercore.MossWorldLoadException;
// TODO: Auto-generated Javadoc
/**
* The Class MapChunk.
*/
public class MapChunk {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.lightNodes);
result = prime * result + ((this.pos == null) ? 0 : this.pos.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MapChunk)) {
return false;
}
MapChunk other = (MapChunk) obj;
if (!Arrays.deepEquals(this.lightNodes, other.lightNodes)) {
return false;
}
if (this.pos == null) {
if (other.pos != null) {
return false;
}
} else if (!this.pos.equals(other.pos)) {
return false;
}
return true;
}
/** The pos. */
public Position pos;
/** The light nodes. */
int[][][] lightNodes = new int[16][16][16];
/** The modified. */
boolean[][][] modified = new boolean[16][16][16];
/** The compressed. */
boolean compressed;
/** The db. */
transient MapDatabase db;
/** The Constant MAPCHUNK_SERIALIZATION_VERSION. */
static final int MAPCHUNK_SERIALIZATION_VERSION = 1;
/*
* Compressed format: Short values act as follows: val&32768: 0 means take
* this node literally, 1 means is repeating
*
* val&16384: 0: This is repeating an unchanged node. Next short shall be
* the start of a new node/run 1: This is repeating a *changed* node. Next
* short value identifies node type
*/
/**
* Instantiates a new map chunk.
*
* @param pos the pos
* @param light the light
* @param db the db
* @throws IOException Signals that an I/O exception has occurred.
*/
public MapChunk(Position pos, byte[] light, MapDatabase db)
throws IOException {
this.db = db;
this.pos = pos;
Arrays.copyOf(light, light.length);
DataInputStream lightStreamIn = new DataInputStream(
new ByteArrayInputStream(light));
int flags = lightStreamIn.readUnsignedShort();
int version = lightStreamIn.readUnsignedShort();
if (version > MAPCHUNK_SERIALIZATION_VERSION)
ExceptionHandler.registerException(new MossWorldLoadException(
Messages.getString("MapChunk.BAD_SER_VER"))); //$NON-NLS-1$
/*
* flags short: 1=has heavies 2=none yet 4=run-length diff compression
* (not implemented yet) 8...=reserved
*/
if (((flags & 0x01)) != 0) {
db.getHeavy(pos);
loadHeavies();
}
this.compressed = (((flags & 0x04)) != 0);
if (this.compressed) {
int cursor = 0;
int[] lightTmp = new int[16 * 16 * 16];
while (lightStreamIn.available() > 0) {
int curShort = lightStreamIn.readUnsignedShort();
if ((curShort & 16384) != 0) {
lightTmp[cursor] = curShort;
cursor++;
} else {
if ((curShort & 16384) != 0) {
for (int i = 0; i < (curShort & 0b0011111111111111); i++) {
lightTmp[cursor] = 0;
cursor++;
}
}
}
}
try {
MapGenerators.getDefaultMapgen().fillInChunk(this.lightNodes,
pos);
} catch (MapGeneratorException e) {
// pass, we'll deal with a bad chunk later in the pipeline
}
// throw new NotImplementedException();
} else {
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
this.lightNodes[x][y][z] = lightStreamIn.readShort();
}
}
}
}
}
/**
* Load heavies.
*/
private void loadHeavies() {
// TODO Heavies not here yet
}
/**
* Instantiates a new map chunk.
*
* @param pos2 the pos2
* @param nodes the nodes
* @param modified the modified
*/
public MapChunk(Position pos2, int[][][] nodes, boolean[][][] modified) {
this.pos = pos2;
this.lightNodes = Arrays.copyOf(nodes, nodes.length);
this.modified = modified==null?new boolean[16][16][16]:Arrays.copyOf(modified, modified.length);
}
/**
* Gets the node id.
*
* @param x the x
* @param y the y
* @param z the z
* @return the node id
*/
public int getNodeId(byte x, byte y, byte z) {
return this.lightNodes[x][y][z];
}
/**
* Updates the chunk to set a node. The chunk is not written to the database
* or committed across the network.
*
* @param x the x
* @param y the y
* @param z the z
* @param node the node
*/
public void setNode(byte x, byte y, byte z, short node) {
this.lightNodes[x][y][z] = node;
}
public int[][][] getNodes () {
return this.lightNodes;
}
/**
* Write light.
*
* @param compressed the compressed
* @return the byte[]
*/
public byte[] writeLight(boolean compressed) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (DataOutputStream dos = new DataOutputStream(bos);) {
dos.writeShort(0);
dos.writeShort(MAPCHUNK_SERIALIZATION_VERSION);
for (int[][] nodelvl : this.lightNodes) {
for (int[] nodelvl2 : nodelvl) {
for (int node : nodelvl2) {
dos.writeShort(node);
}
}
}
dos.flush();
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bos.toByteArray();
}
}
package net.mosstest.scripting;
import net.mosstest.servercore.*;
import net.mosstest.servercore.Messages;
import java.io.*;
import java.util.Arrays;
// TODO: Auto-generated Javadoc
/**
* The Class MapChunk.
*/
public class MapChunk {
public static final int CHUNK_DIMENSION = 16;
public static final int IS_CHANGED_MASK = 16384;
public static final int UNSIGNED_IDENTITY_MASK = 0b0011111111111111;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.lightNodes);
result = prime * result + ((this.pos == null) ? 0 : this.pos.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MapChunk)) {
return false;
}
MapChunk other = (MapChunk) obj;
if (!Arrays.deepEquals(this.lightNodes, other.lightNodes)) {
return false;
}
if (this.pos == null) {
if (other.pos != null) {
return false;
}
} else if (!this.pos.equals(other.pos)) {
return false;
}
return true;
}
/**
* The pos.
*/
public Position pos;
/**
* The light nodes.
*/
int[][][] lightNodes = new int[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION];
/**
* The modified.
*/
boolean[][][] modified = new boolean[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION];
/**
* The compressed.
*/
boolean compressed;
/**
* The db.
*/
transient MapDatabase db;
/**
* The Constant MAPCHUNK_SERIALIZATION_VERSION.
*/
static final int MAPCHUNK_SERIALIZATION_VERSION = 1;
/*
* Compressed format: Short values act as follows: val&32768: 0 means take
* this node literally, 1 means is repeating
*
* val&16384: 0: This is repeating an unchanged node. Next short shall be
* the start of a new node/run 1: This is repeating a *changed* node. Next
* short value identifies node type
*/
/**
* Instantiates a new map chunk.
*
* @param pos the pos
* @param light the light
* @param db the db
* @throws IOException Signals that an I/O exception has occurred.
*/
public MapChunk(Position pos, byte[] light, MapDatabase db)
throws IOException {
this.db = db;
this.pos = pos;
Arrays.copyOf(light, light.length);
DataInputStream lightStreamIn = new DataInputStream(
new ByteArrayInputStream(light));
int flags = lightStreamIn.readUnsignedShort();
int version = lightStreamIn.readUnsignedShort();
if (version > MAPCHUNK_SERIALIZATION_VERSION)
ExceptionHandler.registerException(new MossWorldLoadException(
Messages.getString("MapChunk.BAD_SER_VER"))); //$NON-NLS-1$
/*
* flags short: 1=has heavies 2=none yet 4=run-length diff compression
* (not implemented yet) 8...=reserved
*/
if (((flags & 0x01)) != 0) {
db.getHeavy(pos);
loadHeavies();
}
this.compressed = (((flags & 0x04)) != 0);
if (this.compressed) {
int cursor = 0;
int[] lightTmp = new int[CHUNK_DIMENSION * CHUNK_DIMENSION * CHUNK_DIMENSION];
while (lightStreamIn.available() > 0) {
int curShort = lightStreamIn.readUnsignedShort();
if ((curShort & IS_CHANGED_MASK) != 0) {
lightTmp[cursor] = curShort;
cursor++;
} else {
if ((curShort & IS_CHANGED_MASK) != 0) {
for (int i = 0; i < (curShort & UNSIGNED_IDENTITY_MASK); i++) {
lightTmp[cursor] = 0;
cursor++;
}
}
}
}
try {
MapGenerators.getDefaultMapgen().fillInChunk(this.lightNodes,
pos);
} catch (MapGeneratorException e) {
// pass, we'll deal with a bad chunk later in the pipeline
}
// throw new NotImplementedException();
} else {
for (int x = 0; x < CHUNK_DIMENSION; x++) {
for (int y = 0; y < CHUNK_DIMENSION; y++) {
for (int z = 0; z < CHUNK_DIMENSION; z++) {
this.lightNodes[x][y][z] = lightStreamIn.readShort();
}
}
}
}
}
/**
* Load heavies.
*/
private void loadHeavies() {
// TODO Heavies not here yet
}
/**
* Instantiates a new map chunk.
*
* @param pos2 the pos2
* @param nodes the nodes
* @param modified the modified
*/
public MapChunk(Position pos2, int[][][] nodes, boolean[][][] modified) {
this.pos = pos2;
this.lightNodes = Arrays.copyOf(nodes, nodes.length);
this.modified = modified == null ? new boolean[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION] : Arrays.copyOf(modified, modified.length);
}
/**
* Gets the node id.
*
* @param x the x
* @param y the y
* @param z the z
* @return the node id
*/
public int getNodeId(byte x, byte y, byte z) {
return this.lightNodes[x][y][z];
}
/**
* Updates the chunk to set a node. The chunk is not written to the database
* or committed across the network.
*
* @param x the x
* @param y the y
* @param z the z
* @param node the node
*/
public void setNode(byte x, byte y, byte z, short node) {
this.lightNodes[x][y][z] = node;
}
public int[][][] getNodes() {
return this.lightNodes;
}
public byte[] writeLight(boolean compressed) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (DataOutputStream dos = new DataOutputStream(bos);) {
dos.writeShort(0);
dos.writeShort(MAPCHUNK_SERIALIZATION_VERSION);
for (int[][] nodelvl : this.lightNodes) {
for (int[] nodelvl2 : nodelvl) {
for (int node : nodelvl2) {
dos.writeShort(node);
}
}
}
dos.flush();
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bos.toByteArray();
}
}

View File

@ -1,398 +1,447 @@
package net.mosstest.scripting;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MapGeneratorException;
import org.apache.commons.lang.NotImplementedException;
import toxi.math.noise.SimplexNoise;
import java.util.ArrayList;
import java.util.Random;
import org.apache.commons.lang.NotImplementedException;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MapGeneratorException;
import toxi.math.noise.SimplexNoise;
// TODO: Auto-generated Javadoc
/**
* The Class MapGenerators.
*/
public class MapGenerators {
/** The mg. */
private static volatile IMapGenerator mg;
/**
* Sets the default map generator.
*
* @param g the g
* @param nm the nm
* @param seed the seed
* @param params the params
* @throws MapGeneratorException the map generator exception
*/
public static void setDefaultMapGenerator(IMapGenerator g, INodeManager nm, long seed,
Object... params) throws MapGeneratorException {
synchronized (MapGenerators.class) {
mg = g;
mg.init(seed, nm, params);
}
}
public static final int CHUNK_DIMENSION = 16;
/**
* The mg.
*/
private static volatile IMapGenerator mg;
/**
* Gets the default mapgen.
*
* @return the default mapgen
*/
public static IMapGenerator getDefaultMapgen() {
return mg;
}
/**
* Sets the default map generator.
*
* @param g the g
* @param nm the nm
* @param seed the seed
* @param params the params
* @throws MapGeneratorException the map generator exception
*/
public static void setDefaultMapGenerator(IMapGenerator g, INodeManager nm, long seed,
Object... params) throws MapGeneratorException {
synchronized (MapGenerators.class) {
mg = g;
mg.init(seed, nm, params);
}
}
/**
* The Class FlatMapGenerator.
*/
public static class FlatMapGenerator implements IMapGenerator {
/** The seed. */
long seed;
/** The nm. */
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.seed = seed;
this.nm=nm;
}
/**
* Gets the default mapgen.
*
* @return the default mapgen
*/
public static IMapGenerator getDefaultMapgen() {
return mg;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] nodes = new int[16][16][16];
try {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode(
"mg:air", false).getNodeId() : this.nm.getNode( //$NON-NLS-1$
"mg:ground", false).getNodeId(); //$NON-NLS-1$
/**
* The Class FlatMapGenerator.
*/
public static class FlatMapGenerator implements IMapGenerator {
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
nodes[x][y][z] = fillNode;
}
}
/**
* The seed.
*/
long seed;
}
return new MapChunk(pos, nodes, new boolean[16][16][16]);
} catch (NullPointerException e) {
throw new MapGeneratorException();
}
/**
* The nm.
*/
INodeManager nm;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.seed = seed;
this.nm = nm;
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode("mg:air", //$NON-NLS-1$
false).getNodeId() : this.nm
.getNode("mg:ground", false).getNodeId(); //$NON-NLS-1$
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] nodes = new int[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION];
try {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode(
"mg:air", false).getNodeId() : this.nm.getNode( //$NON-NLS-1$
"mg:ground", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
if (lightNodes[x][y][z] == 0) {
// operation in place on passed in array as per
// contract
lightNodes[x][y][z] = fillNode;
}
}
}
for (int x = 0; x < CHUNK_DIMENSION; x++) {
for (int y = 0; y < CHUNK_DIMENSION; y++) {
for (int z = 0; z < CHUNK_DIMENSION; z++) {
nodes[x][y][z] = fillNode;
}
}
}
}
return new MapChunk(pos, nodes, new boolean[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION]);
} catch (NullPointerException e) {
throw new MapGeneratorException();
}
}
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
throw new NotImplementedException(FlatMapGenerator.class);
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
int fillNode = (pos.getZ() >= 0) ? this.nm.getNode("mg:air", //$NON-NLS-1$
false).getNodeId() : this.nm
.getNode("mg:ground", false).getNodeId(); //$NON-NLS-1$
}
for (int x = 0; x < CHUNK_DIMENSION; x++) {
for (int y = 0; y < CHUNK_DIMENSION; y++) {
for (int z = 0; z < CHUNK_DIMENSION; z++) {
if (lightNodes[x][y][z] == 0) {
// operation in place on passed in array as per
// contract
lightNodes[x][y][z] = fillNode;
}
}
}
}
}
/**
* The Class SimplexMapGenerator.
*/
public static class SimplexMapGenerator implements IMapGenerator {
/** The Constant HEIGHT_AVG. */
public static final int HEIGHT_AVG = 0;
/** The Constant HEIGHT_JITTER. */
public static final int HEIGHT_JITTER = 100;
/** The Constant SIMPLEX_SCALE_FACTOR. */
public static final double SIMPLEX_SCALE_FACTOR = 1;
/** The Constant SIMPLEX_LOCAL_SCALE_FACTOR. */
public static final double SIMPLEX_LOCAL_SCALE_FACTOR = 10 * SIMPLEX_SCALE_FACTOR;
/** The Constant SIMPLEX_ROOT_DEGREE. */
public static final double SIMPLEX_ROOT_DEGREE = 2;
/** The Constant SEA_LEVEL. */
public static final int SEA_LEVEL = 0;
// todo tweak parameters
// TODO finish simplex generator including ores
/** The base seed. */
long baseSeed;
/** The elevation seed. */
double elevationSeed;
/** The dirt seed. */
double dirtSeed;
/** The humidity seed. */
double humiditySeed;
/** The elevation noise. */
SimplexNoise elevationNoise = new SimplexNoise();
/** The ores. */
ArrayList<Ore> ores = new ArrayList<>();
/** The nm. */
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm,Object... params)
throws MapGeneratorException {
this.nm=nm;
this.baseSeed = seed;
Random rand = new Random(seed);
}
// not sure if this is really going to work in terms of the range of
// simplex. I'm guessing 2^32 is enough variation.
this.elevationSeed = rand.nextInt();
this.dirtSeed = rand.nextInt();
this.humiditySeed = rand.nextInt();
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
throw new NotImplementedException(FlatMapGenerator.class);
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] lightNodes = new int[16][16][16];
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed, pos.getY()*16+y, this.humiditySeed, pos.getX()*16+x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity>=0.5)?grass:sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity>=0.5)?dirt:sand;
}
}
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} //if
} //oreloop
} //z
} //y
} //x
return new MapChunk(pos, lightNodes, null);
}
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
//TODO make trees
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed, pos.getY()*16+y, this.humiditySeed, pos.getX()*16+x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity>=0.5)?grass:sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity>=0.5)?dirt:sand;
}
/**
* The Class SimplexMapGenerator.
*/
public static class SimplexMapGenerator implements IMapGenerator {
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} //if
} //oreloop
} //z
} //y
} //x
} //method
/**
* The Constant HEIGHT_AVG.
*/
public static final int HEIGHT_AVG = 0;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
Ore ore = new Ore(oreNode, seed, minDepth, rarity);
/**
* The Constant HEIGHT_JITTER.
*/
public static final int HEIGHT_JITTER = 100;
}
/**
* The Constant SIMPLEX_SCALE_FACTOR.
*/
public static final double SIMPLEX_SCALE_FACTOR = 1;
/**
* The Class Ore.
*/
private class Ore {
/** The node. */
MapNode node;
/** The noise. */
SimplexNoise noise;
/** The min depth. */
double minDepth;
/** The cutoff. */
double cutoff;
/** The simplex seed position. */
double simplexSeedPosition;
/** The ore seed. */
int oreSeed;
/**
* The Constant SIMPLEX_LOCAL_SCALE_FACTOR.
*/
public static final double SIMPLEX_LOCAL_SCALE_FACTOR = 10 * SIMPLEX_SCALE_FACTOR;
/**
* Instantiates a new ore.
*
* @param node the node
* @param seed the seed
* @param minDepth the min depth
* @param rarity the rarity
*/
public Ore(MapNode node, int seed, double minDepth, double rarity) {
Random random = new Random(seed);
this.simplexSeedPosition = 10 * Integer.MAX_VALUE
* random.nextDouble();
this.oreSeed = seed;
this.node = node;
this.noise = new SimplexNoise();
this.minDepth = minDepth;
this.cutoff = 1.0 / rarity;
}
/**
* The Constant SIMPLEX_ROOT_DEGREE.
*/
public static final double SIMPLEX_ROOT_DEGREE = 2;
/**
* Check ore.
*
* @param x the x
* @param y the y
* @param z the z
* @return true, if successful
*/
public boolean checkOre(long x, long y, long z) {
Random r = new Random(SimplexMapGenerator.this.baseSeed
- this.oreSeed - x + y - z);
double preProb;
if (z > (-1 * this.minDepth)) {
preProb = 0;
return false;
}
if (z > ((-1 * this.minDepth) - 100)) {
preProb = ((100 + this.minDepth + z) / -100);
} else
preProb = 1;
/**
* The Constant SEA_LEVEL.
*/
public static final int SEA_LEVEL = 0;
// todo tweak parameters
// TODO finish simplex generator including ores
/**
* The base seed.
*/
long baseSeed;
return (r.nextDouble() < preProb)
&& (this.noise.noise(this.simplexSeedPosition, x, y, z) < this.cutoff);
/**
* The elevation seed.
*/
double elevationSeed;
}
}
/**
* The dirt seed.
*/
double dirtSeed;
}
/**
* The humidity seed.
*/
double humiditySeed;
/**
* The elevation noise.
*/
SimplexNoise elevationNoise = new SimplexNoise();
/**
* The ores.
*/
ArrayList<Ore> ores = new ArrayList<>();
/**
* The nm.
*/
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.nm = nm;
this.baseSeed = seed;
Random rand = new Random(seed);
// not sure if this is really going to work in terms of the range of
// simplex. I'm guessing 2^32 is enough variation.
this.elevationSeed = rand.nextInt();
this.dirtSeed = rand.nextInt();
this.humiditySeed = rand.nextInt();
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos)
throws MapGeneratorException {
int[][][] lightNodes = new int[CHUNK_DIMENSION][CHUNK_DIMENSION][CHUNK_DIMENSION];
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < CHUNK_DIMENSION; x++) {
long globalx = pos.getX() * CHUNK_DIMENSION + x;
for (int y = 0; y < CHUNK_DIMENSION; y++) {
long globaly = pos.getY() * CHUNK_DIMENSION + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed, pos.getY() * CHUNK_DIMENSION + y, this.humiditySeed, pos.getX() * CHUNK_DIMENSION + x);
inner:
for (int z = 0; z < CHUNK_DIMENSION; z++) {
long globalz = pos.getZ() * CHUNK_DIMENSION + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? dirt : sand;
}
oreLoop:
for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} //if
} //oreloop
} //z
} //y
} //x
return new MapChunk(pos, lightNodes, null);
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
//TODO make trees
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < CHUNK_DIMENSION; x++) {
long globalx = pos.getX() * CHUNK_DIMENSION + x;
for (int y = 0; y < CHUNK_DIMENSION; y++) {
long globaly = pos.getY() * CHUNK_DIMENSION + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed, pos.getY() * CHUNK_DIMENSION + y, this.humiditySeed, pos.getX() * CHUNK_DIMENSION + x);
inner:
for (int z = 0; z < CHUNK_DIMENSION; z++) {
long globalz = pos.getZ() * CHUNK_DIMENSION + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? dirt : sand;
}
oreLoop:
for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} //if
} //oreloop
} //z
} //y
} //x
} //method
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth,
double rarity, double clumping, int seed, Object... params) {
Ore ore = new Ore(oreNode, seed, minDepth, rarity);
}
/**
* The Class Ore.
*/
private class Ore {
/**
* The node.
*/
MapNode node;
/**
* The noise.
*/
SimplexNoise noise;
/**
* The min depth.
*/
double minDepth;
/**
* The cutoff.
*/
double cutoff;
/**
* The simplex seed position.
*/
double simplexSeedPosition;
/**
* The ore seed.
*/
int oreSeed;
/**
* Instantiates a new ore.
*
* @param node the node
* @param seed the seed
* @param minDepth the min depth
* @param rarity the rarity
*/
public Ore(MapNode node, int seed, double minDepth, double rarity) {
Random random = new Random(seed);
this.simplexSeedPosition = (Integer.MAX_VALUE
* random.nextDouble());
this.oreSeed = seed;
this.node = node;
this.noise = new SimplexNoise();
this.minDepth = minDepth;
this.cutoff = 1.0 / rarity;
}
/**
* Check ore.
*
* @param x the x
* @param y the y
* @param z the z
* @return true, if successful
*/
public boolean checkOre(long x, long y, long z) {
Random r = new Random(SimplexMapGenerator.this.baseSeed
- this.oreSeed - x + y - z);
double preProb;
if (z > (-1 * this.minDepth)) {
preProb = 0;
return false;
}
if (z > ((-1 * this.minDepth) - 100)) {
preProb = ((100 + this.minDepth + z) / -100);
} else
preProb = 1;
return (r.nextDouble() < preProb)
&& (this.noise.noise(this.simplexSeedPosition, x, y, z) < this.cutoff);
}
}
}
}

View File

@ -1,7 +1,5 @@
package net.mosstest.scripting;
import net.mosstest.servercore.ItemManager;
// TODO: Auto-generated Javadoc
/**
* The Class MapNode.
@ -60,7 +58,6 @@ public class MapNode {
this.userFacingName = userFacingName;
this.lightEmission = lightEmission;
this.dropItem = ItemManager.getForNode(this);
}
@ -120,11 +117,18 @@ public class MapNode {
this.nodeName = nodeName;
this.userFacingName = userFacingName;
this.lightEmission = lightEmission;
this.dropItem = ItemManager.getForNode(this);
}
/**
* Gets the node id.
public MossItem getDropItem() {
return dropItem;
}
public void setDropItem(MossItem dropItem) {
this.dropItem = dropItem;
}
/**
* Gets the node id.
*
* @return the node id
*/

View File

@ -3,113 +3,170 @@ package net.mosstest.scripting;
import net.mosstest.servercore.ScriptSandboxBorderToken;
// TODO: Auto-generated Javadoc
/**
* The Class MossEvent.
*/
public class MossEvent {
/**
* Instantiates a new moss event.
*
* @param type the type
* @param actor the actor
* @param pos the pos
* @param nodeBefore the node before
* @param nodeAfter the node after
* @param recvEntity the recv entity
* @param fspec the fspec
* @param action the action
* @param damage the damage
* @param initiatingMessage the initiating message
* @param tok the tok
*/
public MossEvent(EvtType type, Player actor, NodePosition pos, MapNode nodeBefore, MapNode nodeAfter,
Entity recvEntity, MossFormspec fspec, MossInventoryAction action, double damage,
String initiatingMessage, ScriptSandboxBorderToken tok) {
if (!(tok instanceof ScriptSandboxBorderToken) || tok == null)
throw new SecurityException(Messages.getString("MossEvent.MSG_CROSS_DMZ_SECURITY_WARNING")); //$NON-NLS-1$
this.type = type;
this.actor = actor;
this.pos=pos;
this.nodeBefore = nodeBefore;
this.nodeAfter = nodeAfter;
this.recvEntity = recvEntity;
this.fspec = fspec;
this.damage=damage;
this.action = action;
this.initiatingMessage = initiatingMessage;
}
/**
* The Enum EvtType.
*/
public enum EvtType {
/** The evt dieplayer. */
EVT_DIEPLAYER,
/** The evt dignode. */
EVT_DIGNODE,
/** The evt generate. */
EVT_GENERATE,
/** The evt joinplayer. */
EVT_JOINPLAYER,
/** The evt quitplayer. */
EVT_QUITPLAYER,
/** The evt newplayer. */
EVT_NEWPLAYER,
/** The evt placenode. */
EVT_PLACENODE,
/** The evt fspec open. */
EVT_FSPEC_OPEN,
/** The evt fspec submit. */
EVT_FSPEC_SUBMIT,
/** The evt fspec invaction. */
EVT_FSPEC_INVACTION,
/** The evt threadstop. */
EVT_THREADSTOP,
/** The evt entity punch. */
EVT_ENTITY_PUNCH,
/** The evt entity death. */
EVT_ENTITY_DEATH,
/** The evt chatmessage. */
EVT_CHATMESSAGE,
/** The evt shutdown. */
EVT_SHUTDOWN,
/** The evt chatcommand. */
EVT_CHATCOMMAND,
/** The evt nodemove. */
EVT_NODEMOVE,
/** The evt playerdamage. */
EVT_PLAYERDAMAGE
}
/**
* Instantiates a new moss event.
*
* @param type the type
* @param actor the actor
* @param pos the pos
* @param nodeBefore the node before
* @param nodeAfter the node after
* @param recvEntity the recv entity
* @param fspec the fspec
* @param action the action
* @param damage the damage
* @param initiatingMessage the initiating message
* @param tok the tok
*/
public MossEvent(EvtType type, Player actor, NodePosition pos, MapNode nodeBefore, MapNode nodeAfter,
Entity recvEntity, MossFormspec fspec, MossInventoryAction action, double damage,
String initiatingMessage, ScriptSandboxBorderToken tok) {
if (!(tok instanceof ScriptSandboxBorderToken))
throw new SecurityException(Messages.getString("MossEvent.MSG_CROSS_DMZ_SECURITY_WARNING")); //$NON-NLS-1$
this.type = type;
this.actor = actor;
this.pos = pos;
this.nodeBefore = nodeBefore;
this.nodeAfter = nodeAfter;
this.recvEntity = recvEntity;
this.fspec = fspec;
this.damage = damage;
this.action = action;
this.initiatingMessage = initiatingMessage;
}
/** The type. */
public final MossEvent.EvtType type;
/** The actor. */
public final Player actor; // Player no longer extends entity
/** The pos. */
public final NodePosition pos;
/** The node before. */
public final MapNode nodeBefore;
/** The node after. */
public final MapNode nodeAfter;
/** The recv entity. */
public final Entity recvEntity;
/** The damage. */
public final double damage;
/** The fspec. */
public final MossFormspec fspec;
/** The action. */
public final MossInventoryAction action;
/** The initiating message. */
public final String initiatingMessage;
/**
* The Enum EvtType.
*/
public enum EvtType {
/**
* The evt dieplayer.
*/
EVT_DIEPLAYER,
/**
* The evt dignode.
*/
EVT_DIGNODE,
/**
* The evt generate.
*/
EVT_GENERATE,
/**
* The evt joinplayer.
*/
EVT_JOINPLAYER,
/**
* The evt quitplayer.
*/
EVT_QUITPLAYER,
/**
* The evt newplayer.
*/
EVT_NEWPLAYER,
/**
* The evt placenode.
*/
EVT_PLACENODE,
/**
* The evt fspec open.
*/
EVT_FSPEC_OPEN,
/**
* The evt fspec submit.
*/
EVT_FSPEC_SUBMIT,
/**
* The evt fspec invaction.
*/
EVT_FSPEC_INVACTION,
/**
* The evt threadstop.
*/
EVT_THREADSTOP,
/**
* The evt entity punch.
*/
EVT_ENTITY_PUNCH,
/**
* The evt entity death.
*/
EVT_ENTITY_DEATH,
/**
* The evt chatmessage.
*/
EVT_CHATMESSAGE,
/**
* The evt shutdown.
*/
EVT_SHUTDOWN,
/**
* The evt chatcommand.
*/
EVT_CHATCOMMAND,
/**
* The evt nodemove.
*/
EVT_NODEMOVE,
/**
* The evt playerdamage.
*/
EVT_PLAYERDAMAGE
}
/**
* The type.
*/
public final MossEvent.EvtType type;
/**
* The actor.
*/
public final Player actor; // Player no longer extends entity
/**
* The pos.
*/
public final NodePosition pos;
/**
* The node before.
*/
public final MapNode nodeBefore;
/**
* The node after.
*/
public final MapNode nodeAfter;
/**
* The recv entity.
*/
public final Entity recvEntity;
/**
* The damage.
*/
public final double damage;
/**
* The fspec.
*/
public final MossFormspec fspec;
/**
* The action.
*/
public final MossInventoryAction action;
/**
* The initiating message.
*/
public final String initiatingMessage;
}

View File

@ -1,85 +1,126 @@
package net.mosstest.scripting;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.mosstest.servercore.ItemManager;
import java.io.*;
// TODO: Auto-generated Javadoc
/**
* The Class MossInventory.
*/
public class MossInventory {
/** The max stack size. */
final int maxStackSize;
/** The stacks. */
final MossItem.Stack[][] stacks;
/**
* Instantiates a new moss inventory.
*
* @param maxStackSize the max stack size
* @param rows the rows
* @param cols the cols
*/
public MossInventory(int maxStackSize, int rows, int cols) {
this.maxStackSize = maxStackSize;
this.stacks = new MossItem.Stack[rows][cols];
}
/**
* The max stack size.
*/
final int maxStackSize;
/**
* To bytes.
*
* @return the byte[]
* @throws IOException Signals that an I/O exception has occurred.
*/
public byte[] toBytes() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(this.stacks.length);
dos.writeInt(this.stacks[0].length);
for(MossItem.Stack[] sa: this.stacks) {
for(MossItem.Stack s: sa) {
dos.writeShort(s.item.getItemId());
dos.writeDouble(s.amount);
}
}
dos.flush();
bos.flush();
return bos.toByteArray();
}
/**
* Adds the item.
*
* @param stack the stack
* @return the double
*/
public synchronized double addItem(MossItem.Stack stack) {
double added = 0;
double maxAddable = stack.item.mayStack ? this.maxStackSize : 1;
for (int row = 0; row < this.stacks.length; row++) {
for (int col = 0; col < this.stacks[row].length; col++) {
if (this.stacks[row][col] == null) {
double addedThisRound = Math.min(stack.amount, maxAddable);
added += addedThisRound;
this.stacks[row][col] = new MossItem.Stack(stack.item,
addedThisRound);
} else if (this.stacks[row][col].item.equals(stack.item)) {
double addedThisRound = Math.min(stack.amount, maxAddable
- this.stacks[row][col].amount);
added += addedThisRound;
this.stacks[row][col].amount += addedThisRound;
}
if (added >= stack.amount)
return added;
}
}
return added;
/**
* The stacks.
*/
final MossItem.Stack[][] stacks;
}
/**
* Instantiates a new moss inventory.
*
* @param maxStackSize the max stack size
* @param rows the rows
* @param cols the cols
*/
public MossInventory(int maxStackSize, int rows, int cols) {
this.maxStackSize = maxStackSize;
this.stacks = new MossItem.Stack[rows][cols];
}
// TODO remove item
/**
* To bytes.
*
* @return the byte[]
* @throws IOException Signals that an I/O exception has occurred.
*/
public final byte[] toBytes() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(this.maxStackSize);
dos.writeInt(this.stacks.length);
dos.writeInt(this.stacks[0].length);
for (MossItem.Stack[] sa : this.stacks) {
for (MossItem.Stack s : sa) {
dos.writeUTF(s.item.getInternalName());
dos.writeDouble(s.amount);
}
}
dos.flush();
bos.flush();
return bos.toByteArray();
}
public MossInventory(byte[] buf, ItemManager im) throws IOException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(buf)) {
try (DataInputStream dis = new DataInputStream(bais)) {
this.maxStackSize = dis.readInt();
int rows = dis.readInt();
int cols = dis.readInt();
this.stacks = new MossItem.Stack[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
MossItem itm = im.getItem(dis.readUTF());
double amount = dis.readDouble();
this.stacks[i][j] = new MossItem.Stack(itm, amount);
}
}
}
}
}
public synchronized double addItem(MossItem.Stack stack) {
double added = 0;
for (int row = 0; row < this.stacks.length; row++) {
for (int col = 0; col < this.stacks[row].length; col++) {
if (this.stacks[row][col] == null) {
double addedThisRound = MossItem.Stack.getMaxSize(stack.item.stackMode, stack.amount - added, this.maxStackSize);
added += addedThisRound;
this.stacks[row][col] = new MossItem.Stack(stack.item,
addedThisRound);
} else if (this.stacks[row][col].item.equals(stack.item)) {
double addedThisRound = this.stacks[row][col].getAddable(stack.item.stackMode, stack.amount - added, this.maxStackSize);
added += addedThisRound;
this.stacks[row][col].amount += addedThisRound;
}
if (added >= stack.amount)
return added;
}
}
return added;
}
public synchronized MossItem.Stack removeItem(MossItem.Stack stack) {
double removed = 0;
for (int row = 0; row < this.stacks.length; row++)
for (int col = 0; col < this.stacks[row].length; col++) {
if (this.stacks[row][col].item.equals(stack.item)) {
double removedThisRound = this.stacks[row][col].getRemovable(stack.item.stackMode, stack.amount - removed);
removed += removedThisRound;
if (this.stacks[row][col].amount != removedThisRound)
this.stacks[row][col].amount -= removedThisRound;
else this.stacks[row][col] = null;
}
if (removed >= stack.amount)
return new MossItem.Stack(stack.item, removed);
}
return new MossItem.Stack(stack.item, removed);
}
// TODO remove item
public enum RemovalMode {
REMOVE_NET_AMOUNT,
REMOVE_TOOL_LVL,
}
}

View File

@ -2,145 +2,177 @@ package net.mosstest.scripting;
// TODO: Auto-generated Javadoc
/**
* The Class MossItem.
*/
public class MossItem {
/** The item id. */
private short itemId = 0;
/**
* Sets the item id.
*
* @param itemId the new item id
*/
public void setItemId(short itemId) {
this.itemId = itemId;
}
public enum StackMode {
STACK_NET_AMOUNT,
STACK_UNIT,
STACK_TOOL,
STACK_SINGLE
}
/**
* Gets the item id.
*
* @return the item id
*/
public short getItemId() {
return this.itemId;
}
public MossItem(String invTex, String wieldTex, double invWeight,
StackMode stackMode, String displayName, String internalName) {
this.invTex = invTex;
this.wieldTex = wieldTex;
this.invWeight = invWeight;
this.stackMode = stackMode;
this.displayName = displayName;
this.internalName = internalName;
}
/**
* Instantiates a new moss item.
*
* @param invTex the inv tex
* @param wieldTex the wield tex
* @param invWeight the inv weight
* @param mayStack the may stack
* @param displayName the display name
* @param technicalName the technical name
*/
public MossItem(String invTex, String wieldTex, double invWeight,
boolean mayStack, String displayName, String technicalName) {
this.invTex = invTex;
this.wieldTex = wieldTex;
this.invWeight = invWeight;
this.mayStack = mayStack;
this.displayName = displayName;
this.technicalName = technicalName;
}
final String invTex;
/** The inv tex. */
final String invTex;
/** The wield tex. */
final String wieldTex;
/** The inv weight. */
final double invWeight;
/** The may stack. */
boolean mayStack;
/** The display name. */
final String displayName;
/** The technical name. */
final String technicalName;
final String wieldTex;
/**
* The Class Stack.
*/
public static class Stack {
/**
* Instantiates a new stack.
*
* @param item the item
* @param amount the amount
*/
public Stack(MossItem item, double amount) {
this.item = item;
this.amount = amount;
}
final double invWeight;
/** The item. */
final MossItem item;
/**
* If amount is not an integer then it is a stack with wear. Once zero
* it is no longer a stack.
*/
double amount;
}
StackMode stackMode;
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((this.technicalName == null) ? 0 : this.technicalName
.hashCode());
return result;
}
final String displayName;
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MossItem other = (MossItem) obj;
if (this.technicalName == null) {
if (other.technicalName != null)
return false;
} else if (!this.technicalName.equals(other.technicalName))
return false;
return true;
}
final String internalName;
/**
* Gets the display name.
*
* @return the display name
*/
public String getDisplayName() {
return displayName;
}
/**
* The Class Stack.
*/
public static class Stack {
/**
* Gets the technical name.
*
* @return the technical name
*/
public String getTechnicalName() {
return technicalName;
}
/**
* Instantiates a new stack.
*
* @param item the item
* @param amount the amount
*/
public Stack(MossItem item, double amount) {
this.item = item;
this.amount = amount;
}
public double getRemovable(StackMode stackMode, double maxAmount) {
switch (stackMode) {
case STACK_NET_AMOUNT:
return Math.min(this.amount, maxAmount);
case STACK_SINGLE:
return (maxAmount >= 1) ? 1 : 0;
case STACK_TOOL:
double frac = (this.amount - Math.floor(amount));
return frac + (Math.floor(maxAmount - frac));
case STACK_UNIT:
return Math.floor(Math.max(this.amount, maxAmount));
default:
return 0;
}
}
public double getAddable(StackMode stackMode, double maxAmount, int stackSize) {
switch (stackMode) {
case STACK_NET_AMOUNT:
return Math.min(maxAmount, stackSize - this.amount);
case STACK_SINGLE:
return (this.amount == 0) ? 1 : 0;
case STACK_TOOL:
// this stack is integer value
if (this.amount == Math.floor(this.amount)) return Math.min((stackSize - this.amount), maxAmount);
// other stack is integer value
else if (maxAmount == Math.floor(maxAmount))
return Math.floor(Math.min(stackSize - this.amount, maxAmount));
// neither are, but we have more than one in other stack
else if (maxAmount >= 1) {
return Math.floor(Math.min(maxAmount, stackSize - this.amount));
} else return 0;
case STACK_UNIT:
return Math.floor(Math.min(maxAmount, stackSize - this.amount));
default:
return 0;
}
}
public static double getMaxSize(StackMode stackMode, double maxAmount, int stackSize) {
switch (stackMode) {
case STACK_NET_AMOUNT:
return Math.min(maxAmount, stackSize);
case STACK_SINGLE:
return 1;
case STACK_TOOL:
// this stack is integer value
return Math.min((stackSize), maxAmount);
case STACK_UNIT:
return Math.floor(Math.min(maxAmount, stackSize));
default:
return 0;
}
}
/**
* The item.
*/
final MossItem item;
/**
* If amount is not an integer then it is a stack with wear. Once zero
* it is no longer a stack.
*/
double amount;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((this.internalName == null) ? 0 : this.internalName
.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MossItem other = (MossItem) obj;
if (this.internalName == null) {
if (other.internalName != null)
return false;
} else if (!this.internalName.equals(other.internalName))
return false;
return true;
}
/**
* Gets the display name.
*
* @return the display name
*/
public String getDisplayName() {
return displayName;
}
/**
* Gets the technical name.
*
* @return the technical name
*/
public String getInternalName() {
return internalName;
}
}

View File

@ -0,0 +1,68 @@
package net.mosstest.scripting;
public class MossItemBuilder {
private String invTex;
private String wieldTex;
private double invWeight;
private MossItem.StackMode mayStack = MossItem.StackMode.STACK_UNIT;
private String displayName;
private String internalName;
public MossItemBuilder setInvTex(String invTex) {
this.invTex = invTex;
return this;
}
public MossItemBuilder setWieldTex(String wieldTex) {
this.wieldTex = wieldTex;
return this;
}
public MossItemBuilder setInvWeight(double invWeight) {
this.invWeight = invWeight;
return this;
}
public String getInvTex() {
return invTex;
}
public String getWieldTex() {
return wieldTex;
}
public double getInvWeight() {
return invWeight;
}
public MossItem.StackMode getStackMode() {
return mayStack;
}
public MossItemBuilder setStackMode(MossItem.StackMode mayStack) {
this.mayStack = mayStack;
return this;
}
public String getDisplayName() {
return displayName;
}
public String getInternalName() {
return internalName;
}
public MossItemBuilder setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
public MossItemBuilder setInternalName(String internalName) {
this.internalName = internalName;
return this;
}
public MossItem createMossItem() {
return new MossItem(invTex, wieldTex, invWeight, mayStack, displayName, internalName);
}
}

View File

@ -7,19 +7,10 @@ package net.mosstest.scripting;
*/
public class MossTool extends MossItem {
/**
* Instantiates a new moss tool.
*
* @param invTex the inv tex
* @param wieldTex the wield tex
* @param invWeight the inv weight
* @param mayStack the may stack
* @param displayName the display name
* @param technicalName the technical name
*/
public MossTool(String invTex, String wieldTex, double invWeight,
boolean mayStack, String displayName, String technicalName) {
super(invTex, wieldTex, invWeight, mayStack, displayName, technicalName);
StackMode stackMode, String displayName, String technicalName) {
super(invTex, wieldTex, invWeight, stackMode, displayName, technicalName);
}

View File

@ -1,131 +1,126 @@
package net.mosstest.scripting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.*;
import java.util.Arrays;
// TODO: Auto-generated Javadoc
/**
* The Class NodePosition.
*/
public class NodePosition {
/** The zl. */
public final byte xl, yl, zl;
/** The chunk. */
public final Position chunk;
/**
* The zl.
*/
public final byte xl, yl, zl;
/**
* The chunk.
*/
public final Position chunk;
/**
* Instantiates a new node position.
*
* @param x the x
* @param y the y
* @param z the z
* @param realm the realm
* @param xl the xl
* @param yl the yl
* @param zl the zl
*/
public NodePosition(int x, int y, int z, int realm, byte xl, byte yl,
byte zl) {
this.chunk = new Position(x, y, z, realm);
this.xl = xl;
this.yl = yl;
this.zl = zl;
}
/**
* Instantiates a new node position.
*
* @param bytes the bytes
* @throws IOException Signals that an I/O exception has occurred.
*/
public NodePosition(byte[] bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes, 16, bytes.length - 16);
DataInputStream dis = new DataInputStream(bis);
this.chunk = new Position(Arrays.copyOfRange(bytes, 0, 16));
this.xl = dis.readByte();
this.yl = dis.readByte();
this.zl = dis.readByte();
// this.isValid = true;
}
/**
* Instantiates a new node position.
*
* @param x the x
* @param y the y
* @param z the z
* @param realm the realm
* @param xl the xl
* @param yl the yl
* @param zl the zl
*/
public NodePosition(int x, int y, int z, int realm, byte xl, byte yl,
byte zl) {
chunk = new Position(x, y, z, realm);
this.xl = xl;
this.yl = yl;
this.zl = zl;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.chunk.hashCode());
result = prime * result + this.xl;
result = prime * result + this.yl;
result = prime * result + this.zl;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof NodePosition)) {
return false;
}
NodePosition other = (NodePosition) obj;
if (!this.chunk.equals(other.chunk)) {
return false;
}
if (this.xl != other.xl) {
return false;
}
if (this.yl != other.yl) {
return false;
}
if (this.zl != other.zl) {
return false;
}
return true;
}
/**
* Instantiates a new node position.
*
* @param bytes the bytes
* @throws IOException Signals that an I/O exception has occurred.
*/
public NodePosition(byte[] bytes) throws IOException {
super();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bis);
this.chunk = new Position(dis.readInt(), dis.readInt(), dis.readInt(),
dis.readInt());
this.xl = dis.readByte();
this.yl = dis.readByte();
this.zl = dis.readByte();
// this.isValid = true;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((chunk == null) ? 0 : chunk.hashCode());
result = prime * result + xl;
result = prime * result + yl;
result = prime * result + zl;
return result;
}
/**
* To bytes.
*
* @return the byte[]
*/
public byte[] toBytes() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
bos.write(this.chunk.toBytes());
dos.writeByte(this.xl);
dos.writeByte(this.yl);
dos.writeByte(this.zl);
dos.flush();
bos.flush();
return bos.toByteArray();
} catch (IOException e) {
// Auto-generated catch block
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof NodePosition)) {
return false;
}
NodePosition other = (NodePosition) obj;
if (chunk == null) {
if (other.chunk != null) {
return false;
}
} else if (!chunk.equals(other.chunk)) {
return false;
}
if (xl != other.xl) {
return false;
}
if (yl != other.yl) {
return false;
}
if (zl != other.zl) {
return false;
}
return true;
}
/**
* To bytes.
*
* @return the byte[]
*/
public byte[] toBytes() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
bos.write(chunk.toBytes());
dos.writeByte(this.xl);
dos.writeByte(this.yl);
dos.writeByte(this.zl);
dos.flush();
bos.flush();
return bos.toByteArray();
} catch (IOException e) {
// Auto-generated catch block
}
return new byte[] {};
}
}
return new byte[]{};
}
}

View File

@ -1,290 +1,288 @@
package net.mosstest.scripting;
import java.util.ArrayList;
import java.util.Random;
import org.apache.log4j.Logger;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MapGeneratorException;
import net.mosstest.servercore.MossDebugUtils;
import toxi.math.noise.SimplexNoise;
// TODO: Auto-generated Javadoc
/**
* The Class SimplexMapGenerator.
*/
public class SimplexMapGenerator implements IMapGenerator {
/** The logger. */
static Logger logger = Logger.getLogger(SimplexMapGenerator.class);
/** The Constant HEIGHT_AVG. */
public static final double HEIGHT_AVG = 0;
/** The Constant HEIGHT_JITTER. */
public static final double HEIGHT_JITTER = 10;
/** The Constant SIMPLEX_SCALE_FACTOR. */
public static final double SIMPLEX_SCALE_FACTOR = 0.03;
/** The Constant SIMPLEX_LOCAL_SCALE_FACTOR. */
public static final double SIMPLEX_LOCAL_SCALE_FACTOR = 10 * SIMPLEX_SCALE_FACTOR;
/** The Constant SIMPLEX_ROOT_DEGREE. */
public static final double SIMPLEX_ROOT_DEGREE = 2;
/** The Constant SEA_LEVEL. */
public static final int SEA_LEVEL = 0;
// todo tweak parameters
// TODO finish simplex generator including ores
/** The base seed. */
long baseSeed;
/** The elevation seed. */
double elevationSeed;
/** The dirt seed. */
double dirtSeed;
/** The humidity seed. */
double humiditySeed;
/** The elevation noise. */
SimplexNoise elevationNoise = new SimplexNoise();
/** The ores. */
ArrayList<Ore> ores = new ArrayList<>();
/** The nm. */
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.nm = nm;
this.baseSeed = seed;
Random rand = new Random(seed);
// not sure if this is really going to work in terms of the range of
// simplex. I'm guessing 2^32 is enough variation.
this.elevationSeed = rand.nextInt(1 << 16) + rand.nextDouble();
this.dirtSeed = rand.nextInt(1 << 16) + rand.nextDouble();
this.humiditySeed = rand.nextInt(1 << 16) + rand.nextDouble();
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos) throws MapGeneratorException {
int[][][] lightNodes = new int[16][16][16];
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = 0; //this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
double elRawNoise = this.elevationNoise.noise( // get noise
globalx * SIMPLEX_SCALE_FACTOR, // scale
globaly * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed);// , // seed
int elevation = (int) (HEIGHT_AVG + (HEIGHT_JITTER * elRawNoise - 0.5)); // center
// on
// average
// height
// System.err.println("("+x+", "+y+", "+elevation+")");
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed,
pos.getY() * 16 + y, this.humiditySeed, pos.getX() * 16
+ x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0) ? dirt : sand;
}
lightNodes[x][y][z] = stone;
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
System.err.println(ore.node.getNodeId());
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} // if
} // oreloop
} // z
} // y
} // x
return new MapChunk(pos, lightNodes, null);
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
// TODO make trees
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
logger.debug("(" + x + ", " + y + ", " + elevation + ")");
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed,
pos.getY() * 16 + y, this.humiditySeed, pos.getX() * 16
+ x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? dirt : sand;
}
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} // if
} // oreloop
} // z
} // y
} // x
} // method
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth, double rarity,
double clumping, int seed, Object... params) {
Ore ore = new Ore(oreNode, seed, minDepth, rarity);
}
/**
* The Class Ore.
*/
private class Ore {
/** The node. */
MapNode node;
/** The noise. */
SimplexNoise noise;
/** The min depth. */
double minDepth;
/** The cutoff. */
double cutoff;
/** The simplex seed position. */
double simplexSeedPosition;
/** The ore seed. */
int oreSeed;
/**
* Instantiates a new ore.
*
* @param node the node
* @param seed the seed
* @param minDepth the min depth
* @param rarity the rarity
*/
public Ore(MapNode node, int seed, double minDepth, double rarity) {
Random random = new Random(seed);
this.simplexSeedPosition = 10 * Integer.MAX_VALUE
* random.nextDouble();
this.oreSeed = seed;
this.node = node;
this.noise = new SimplexNoise();
this.minDepth = minDepth;
this.cutoff = 1.0 / rarity;
}
/**
* Check ore.
*
* @param x the x
* @param y the y
* @param z the z
* @return true, if successful
*/
public boolean checkOre(long x, long y, long z) {
Random r = new Random(SimplexMapGenerator.this.baseSeed
- this.oreSeed - x + y - z);
double preProb;
if (z > (-1 * this.minDepth)) {
preProb = 0;
return false;
}
if (z > ((-1 * this.minDepth) - 100)) {
preProb = ((100 + this.minDepth + z) / -100);
} else
preProb = 1;
return (r.nextDouble() < preProb)
&& (this.noise.noise(this.simplexSeedPosition, x, y, z) < this.cutoff);
}
}
}
package net.mosstest.scripting;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MapGeneratorException;
import org.apache.log4j.Logger;
import toxi.math.noise.SimplexNoise;
import java.util.ArrayList;
import java.util.Random;
// TODO: Auto-generated Javadoc
/**
* The Class SimplexMapGenerator.
*/
public class SimplexMapGenerator implements IMapGenerator {
/** The logger. */
static Logger logger = Logger.getLogger(SimplexMapGenerator.class);
/** The Constant HEIGHT_AVG. */
public static final double HEIGHT_AVG = 0;
/** The Constant HEIGHT_JITTER. */
public static final double HEIGHT_JITTER = 10;
/** The Constant SIMPLEX_SCALE_FACTOR. */
public static final double SIMPLEX_SCALE_FACTOR = 0.03;
/** The Constant SIMPLEX_LOCAL_SCALE_FACTOR. */
public static final double SIMPLEX_LOCAL_SCALE_FACTOR = 10 * SIMPLEX_SCALE_FACTOR;
/** The Constant SIMPLEX_ROOT_DEGREE. */
public static final double SIMPLEX_ROOT_DEGREE = 2;
/** The Constant SEA_LEVEL. */
public static final int SEA_LEVEL = 0;
// todo tweak parameters
// TODO finish simplex generator including ores
/** The base seed. */
long baseSeed;
/** The elevation seed. */
double elevationSeed;
/** The dirt seed. */
double dirtSeed;
/** The humidity seed. */
double humiditySeed;
/** The elevation noise. */
SimplexNoise elevationNoise = new SimplexNoise();
/** The ores. */
ArrayList<Ore> ores = new ArrayList<>();
/** The nm. */
INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#init(long, net.mosstest.servercore.INodeManager, java.lang.Object[])
*/
@Override
public void init(long seed, INodeManager nm, Object... params)
throws MapGeneratorException {
this.nm = nm;
this.baseSeed = seed;
Random rand = new Random(seed);
// not sure if this is really going to work in terms of the range of
// simplex. I'm guessing 2^32 is enough variation.
this.elevationSeed = rand.nextInt(1 << 16) + rand.nextDouble();
this.dirtSeed = rand.nextInt(1 << 16) + rand.nextDouble();
this.humiditySeed = rand.nextInt(1 << 16) + rand.nextDouble();
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#generateChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk generateChunk(Position pos) throws MapGeneratorException {
int[][][] lightNodes = new int[16][16][16];
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = 0; //this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
double elRawNoise = this.elevationNoise.noise( // get noise
globalx * SIMPLEX_SCALE_FACTOR, // scale
globaly * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed);// , // seed
int elevation = (int) (HEIGHT_AVG + (HEIGHT_JITTER * elRawNoise - 0.5)); // center
// on
// average
// height
// System.err.println("("+x+", "+y+", "+elevation+")");
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed,
pos.getY() * 16 + y, this.humiditySeed, pos.getX() * 16
+ x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0) ? dirt : sand;
}
lightNodes[x][y][z] = stone;
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
System.err.println(ore.node.getNodeId());
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} // if
} // oreloop
} // z
} // y
} // x
return new MapChunk(pos, lightNodes, null);
}
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#fillInChunk(int[][][], net.mosstest.scripting.Position)
*/
@Override
public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException {
// TODO make trees
short grass = this.nm.getNode("mg:grass", false).getNodeId(); //$NON-NLS-1$
short dirt = this.nm.getNode("mg:dirt", false).getNodeId(); //$NON-NLS-1$
short stone = this.nm.getNode("mg:stone", false).getNodeId(); //$NON-NLS-1$
short air = this.nm.getNode("mg:air", false).getNodeId(); //$NON-NLS-1$
short sand = this.nm.getNode("mg:sand", false).getNodeId(); //$NON-NLS-1$
for (int x = 0; x < 16; x++) {
long globalx = pos.getX() * 16 + x;
for (int y = 0; y < 16; y++) {
long globaly = pos.getY() * 16 + y;
int elevation = (int) (HEIGHT_AVG + // average height
(HEIGHT_JITTER * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_SCALE_FACTOR, // scale
y * SIMPLEX_SCALE_FACTOR, // scale
this.elevationSeed, this.elevationSeed), // seed
SIMPLEX_ROOT_DEGREE) // emphasize peaks
- 0.5))); // center on average height
logger.debug("(" + x + ", " + y + ", " + elevation + ")");
int dirtelevation = (int) (elevation - // max possible
// height
(3 * // jitter height
(Math.pow(this.elevationNoise.noise( // get noise
x * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
y * SIMPLEX_LOCAL_SCALE_FACTOR, // scale
this.dirtSeed, this.elevationSeed), // seed
1.0 / SIMPLEX_ROOT_DEGREE) // emphasize peaks
)));
double humidity = this.elevationNoise.noise(this.elevationSeed,
pos.getY() * 16 + y, this.humiditySeed, pos.getX() * 16
+ x);
inner: for (int z = 0; z < 16; z++) {
long globalz = pos.getZ() * 16 + z;
if (lightNodes[x][y][z] != 0)
continue inner;
if (globalz > elevation) {
lightNodes[x][y][z] = air;
continue inner;
}
if (globalz == elevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? grass : sand;
continue inner;
}
if (globalz > dirtelevation) {
lightNodes[x][y][z] = (humidity >= 0.5) ? dirt : sand;
}
oreLoop: for (Ore ore : this.ores) {
if (ore.checkOre(globalx, globaly, globalz)) {
lightNodes[x][y][z] = ore.node.getNodeId();
break oreLoop;
} // if
} // oreloop
} // z
} // y
} // x
} // method
/* (non-Javadoc)
* @see net.mosstest.scripting.IMapGenerator#registerOre(net.mosstest.scripting.MapNode, double, double, double, int, java.lang.Object[])
*/
@Override
public void registerOre(MapNode oreNode, double minDepth, double rarity,
double clumping, int seed, Object... params) {
Ore ore = new Ore(oreNode, seed, minDepth, rarity);
}
/**
* The Class Ore.
*/
private class Ore {
/** The node. */
MapNode node;
/** The noise. */
SimplexNoise noise;
/** The min depth. */
double minDepth;
/** The cutoff. */
double cutoff;
/** The simplex seed position. */
double simplexSeedPosition;
/** The ore seed. */
int oreSeed;
/**
* Instantiates a new ore.
*
* @param node the node
* @param seed the seed
* @param minDepth the min depth
* @param rarity the rarity
*/
public Ore(MapNode node, int seed, double minDepth, double rarity) {
Random random = new Random(seed);
this.simplexSeedPosition = (Integer.MAX_VALUE
* random.nextDouble());
this.oreSeed = seed;
this.node = node;
this.noise = new SimplexNoise();
this.minDepth = minDepth;
this.cutoff = 1.0 / rarity;
}
/**
* Check ore.
*
* @param x the x
* @param y the y
* @param z the z
* @return true, if successful
*/
public boolean checkOre(long x, long y, long z) {
Random r = new Random(SimplexMapGenerator.this.baseSeed
- this.oreSeed - x + y - z);
double preProb;
if (z > (-1 * this.minDepth)) {
preProb = 0;
return false;
}
if (z > ((-1 * this.minDepth) - 100)) {
preProb = ((100 + this.minDepth + z) / -100);
} else
preProb = 1;
return (r.nextDouble() < preProb)
&& (this.noise.noise(this.simplexSeedPosition, x, y, z) < this.cutoff);
}
}
}

View File

@ -1,36 +0,0 @@
package net.mosstest.servercore;
import net.mosstest.scripting.Position;
// TODO: Auto-generated Javadoc
/**
* The Class ChunkNotFoundException.
*/
public class ChunkNotFoundException extends Exception {
/** The z. */
long x, y, z;
/**
* Instantiates a new chunk not found exception.
*
* @param x the x
* @param y the y
* @param z the z
*/
public ChunkNotFoundException(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Instantiates a new chunk not found exception.
*
* @param pos the pos
*/
public ChunkNotFoundException(Position pos) {
// TODO Auto-generated constructor stub
}
}

View File

@ -1,32 +1,33 @@
package net.mosstest.servercore;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class ClientNetworkingManager.
*/
public class ClientNetworkingManager {
/** The logger. */
static Logger logger = Logger.getLogger(ClientNetworkingManager.class);
// There's a potential DoS attack here but it can only be mounted by the
public static final int CMD_QUENCH = 255;
public static final int QUENCH_CAPACITY_REMAINING = 32;
public static final int IPTOS_LOWDELAY = 0x10;
public static final int UDP_MAX_PAYLOAD = 250;
public static final int TIMEOUT = 10000;
public static final int REINIT_TIMEOUT = TIMEOUT;
public static final int PACKET_QUEUE_CAPACITY = 1024;
public static final int TIME_TO_KEEPALIVE = 4000;
public static final byte[] EMPTY_PAYLOAD = new byte[]{};
/**
* The logger.
*/
static Logger logger = Logger.getLogger(ClientNetworkingManager.class);
// There's a potential DoS attack here but it can only be mounted by the
// server, so you might as well just not use that server. No security
// threat except small client hang, won't fix.
/** The run threads. */
@ -88,10 +89,12 @@ public class ClientNetworkingManager {
*/
/** The packets. */
public ArrayBlockingQueue<MossNetPacket> packets = new ArrayBlockingQueue<>(
1024);
/** The bulk read handler. */
protected Thread bulkReadHandler = new Thread(new Runnable() {
PACKET_QUEUE_CAPACITY);
/**
* The bulk read handler.
*/
protected Thread bulkReadHandler = new Thread(new Runnable() {
@Override
public void run() {
@ -100,8 +103,8 @@ public class ClientNetworkingManager {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
if (ClientNetworkingManager.this.bulkDataIn.readInt() != CommonNetworking.magic) {
// Handle reconnect
}
// TODO Handle reconnect
}
int length = ClientNetworkingManager.this.bulkDataIn
.readShort();
@ -109,9 +112,9 @@ public class ClientNetworkingManager {
int commandId = ClientNetworkingManager.this.bulkDataIn
.readUnsignedByte();
if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
if (commandId == CMD_QUENCH) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
}
ClientNetworkingManager.this.bulkStreamIn.read(buf);
@ -126,9 +129,9 @@ public class ClientNetworkingManager {
ClientNetworkingManager.this.lastBulkIn.set(System
.currentTimeMillis());
if (ClientNetworkingManager.this.packets
.remainingCapacity() < 32)
sendQuench();
}
.remainingCapacity() < QUENCH_CAPACITY_REMAINING)
sendQuench();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -147,17 +150,17 @@ public class ClientNetworkingManager {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
if (ClientNetworkingManager.this.lowlatencyDataIn.readInt() != CommonNetworking.magic) {
// Handle reconnect
}
int length = ClientNetworkingManager.this.lowlatencyDataIn
// TODO Handle reconnect
}
int length = ClientNetworkingManager.this.lowlatencyDataIn
.readShort();
byte[] buf = new byte[length];
int commandId = ClientNetworkingManager.this.lowlatencyDataIn
.readUnsignedByte();
if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
if (commandId == CMD_QUENCH) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
}
ClientNetworkingManager.this.fastStreamIn.read(buf);
ClientNetworkingManager.this.packets.add(new MossNetPacket(
@ -167,9 +170,9 @@ public class ClientNetworkingManager {
ClientNetworkingManager.this.packets.add(new MossNetPacket(
commandId, buf));
if (ClientNetworkingManager.this.packets
.remainingCapacity() < 32)
sendQuench();
}
.remainingCapacity() < QUENCH_CAPACITY_REMAINING)
sendQuench();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -191,9 +194,9 @@ public class ClientNetworkingManager {
public void run() {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
byte[] buf = new byte[270];
DatagramPacket pckt = new DatagramPacket(buf, 270);
try {
byte[] buf = new byte[270]; // above the size for a maximum dgram packet
DatagramPacket pckt = new DatagramPacket(buf, 270);
try {
ClientNetworkingManager.this.udpSocket.receive(pckt);
ByteArrayInputStream bufStr = new ByteArrayInputStream(
pckt.getData());
@ -213,9 +216,9 @@ public class ClientNetworkingManager {
}
int length = dos.readUnsignedByte();
int commandId = dos.readUnsignedByte();
if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
if (commandId == CMD_QUENCH) {
ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop;
}
byte[] pBuf = new byte[length];
bufStr.read(pBuf);
@ -256,18 +259,18 @@ public class ClientNetworkingManager {
throws IOException {
this.endpoint = InetAddress.getByName(endpoint);
this.lowLatencyStreamSocket.setPerformancePreferences(0, 1, 0);
this.lowLatencyStreamSocket.setTrafficClass(0x10);
this.lowLatencyStreamSocket.setTcpNoDelay(true);
this.bulkDataSocket.connect(new InetSocketAddress(endpoint, 16511),
16511);
this.bulkStreamIn = this.bulkDataSocket.getInputStream();
this.lowLatencyStreamSocket.setTrafficClass(IPTOS_LOWDELAY);
this.lowLatencyStreamSocket.setTcpNoDelay(true);
this.bulkDataSocket.connect(new InetSocketAddress(endpoint, port),
port);
this.bulkStreamIn = this.bulkDataSocket.getInputStream();
this.bulkStreamOut = this.bulkDataSocket.getOutputStream();
this.bulkDataOut = new DataOutputStream(this.bulkStreamOut);
this.bulkDataIn = new DataInputStream(this.bulkStreamIn);
this.lowLatencyStreamSocket.connect(new InetSocketAddress(endpoint,
16511), 16511);
this.fastStreamIn = this.lowLatencyStreamSocket.getInputStream();
this.fastStreamOut = this.lowLatencyStreamSocket.getOutputStream();
port), port);
this.fastStreamIn = this.lowLatencyStreamSocket.getInputStream();
this.fastStreamOut = this.lowLatencyStreamSocket.getOutputStream();
this.lowlatencyDataOut = new DataOutputStream(this.fastStreamOut);
this.lowlatencyDataIn = new DataInputStream(this.fastStreamIn);
this.udpOn = false;
@ -331,9 +334,9 @@ public class ClientNetworkingManager {
if(this.partyQuenched.get()&&!p.isImportant) return;
if (p.needsFast) {
if ((p.payload.length < 250) && this.udpOn)
sendPacketUdp(p.commandId, p.payload, p.needsAck);
else {
if ((p.payload.length < UDP_MAX_PAYLOAD) && this.udpOn)
sendPacketUdp(p.commandId, p.payload, p.needsAck);
else {
sendPacketLowLatency(p.commandId, p.payload);
}
} else
@ -380,7 +383,7 @@ public class ClientNetworkingManager {
this.bulkDataSocket.close();
this.bulkDataSocket = new Socket();
this.bulkDataSocket.connect(new InetSocketAddress(this.endpoint,
this.port), 10000);
this.port), REINIT_TIMEOUT);
this.bulkDataOut = new DataOutputStream(
this.bulkDataSocket.getOutputStream());
@ -504,7 +507,7 @@ public class ClientNetworkingManager {
/** The send queue. */
final ArrayBlockingQueue<MossNetPacket> sendQueue = new ArrayBlockingQueue<>(
1024);
PACKET_QUEUE_CAPACITY);
/** The send queue thread. */
private Thread sendQueueThread = new Thread(new Runnable() {
@ -529,47 +532,47 @@ public class ClientNetworkingManager {
public void run() {
while (ClientNetworkingManager.this.runThreads.get()) {
long cTime = System.currentTimeMillis();
if (cTime - ClientNetworkingManager.this.lastBulkIn.get() > 10000
|| cTime
- ClientNetworkingManager.this.lastFastIn.get() > 10000
|| cTime - ClientNetworkingManager.this.lastUdpIn.get() > 10000) {
ClientManager
.showErrorScreen(
Messages.getString("ClientNetworkingManager.ERR_NETWORK_TIMEOUT"), //$NON-NLS-1$
Messages.getString("ClientNetworkingManager.DESC_NETWORK_TIMEOUT"), //$NON-NLS-1$
true);
if (cTime - ClientNetworkingManager.this.lastBulkIn.get() > TIMEOUT
|| cTime
- ClientNetworkingManager.this.lastFastIn.get() > TIMEOUT
|| cTime - ClientNetworkingManager.this.lastUdpIn.get() > TIMEOUT) {
ClientManager
.showErrorScreen(
Messages.getString("ClientNetworkingManager.ERR_NETWORK_TIMEOUT"), //$NON-NLS-1$
Messages.getString("ClientNetworkingManager.DESC_NETWORK_TIMEOUT"), //$NON-NLS-1$
true);
logger.error("The connection to the server has timed out or otherwise failed.");
}
try {
if (cTime - ClientNetworkingManager.this.lastBulkOut.get() > 4000)
sendPacketDefault(00, new byte[] {});
} catch (IOException e) {
// pass
}
try {
if (cTime - ClientNetworkingManager.this.lastFastOut.get() > 4000)
sendPacketLowLatency(00, new byte[] {});
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
if (cTime - ClientNetworkingManager.this.lastBulkOut.get() > TIME_TO_KEEPALIVE)
sendPacketDefault(0, EMPTY_PAYLOAD);
} catch (IOException e) {
// pass
}
try {
if (cTime - ClientNetworkingManager.this.lastFastOut.get() > TIME_TO_KEEPALIVE)
sendPacketLowLatency(0, EMPTY_PAYLOAD);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (cTime - ClientNetworkingManager.this.lastUdpOut.get() > 4000)
sendPacketUdp(00, new byte[] {}, false);
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
if (cTime - ClientNetworkingManager.this.lastUdpOut.get() > TIME_TO_KEEPALIVE)
sendPacketUdp(0, EMPTY_PAYLOAD, false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (cTime - ClientNetworkingManager.this.quenchedSince.get() > 4000)
ClientNetworkingManager.this.partyQuenched.set(false);
if (cTime - ClientNetworkingManager.this.quenchedSince.get() > TIME_TO_KEEPALIVE)
ClientNetworkingManager.this.partyQuenched.set(false);
try {
// oh, joy
Thread.sleep(4000
- cTime
+ Math.min(
try {
// oh, joy
Thread.sleep(TIME_TO_KEEPALIVE
- cTime
+ Math.min(
ClientNetworkingManager.this.lastBulkIn
.get(),
Math.min(

View File

@ -1,10 +1,5 @@
package net.mosstest.servercore;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import net.mosstest.scripting.MossScriptEnv;
import net.mosstest.scripting.MossScriptException;
import net.mosstest.scripting.events.IMossEvent;
@ -13,17 +8,22 @@ import net.mosstest.scripting.events.ThreadStopEvent;
import net.mosstest.scripting.handlers.MossEventHandler;
import net.mosstest.scripting.handlers.MossNodeChangeHandler;
import net.mosstest.servercore.MosstestSecurityManager.ThreadContext;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
// TODO: Auto-generated Javadoc
/**
* The Class EventProcessor.
*
*
* @author rarkenin, hexafraction
*
* <p/>
* Blargh.
*
* <p/>
* This is a nasty thread pool. If you don't understand threading or
* Java well, you may want to stick to only accessing the queue as
* otherwise asphyxiation, drowning, or chlorine poisoning may occur.
@ -31,194 +31,194 @@ import org.apache.log4j.Logger;
*/
public class EventProcessor {
static Logger logger = Logger.getLogger(EventProcessor.class);
public static final int EVT_QUEUE_CAPACITY = 40;
static Logger logger = Logger.getLogger(EventProcessor.class);
ArrayBlockingQueue<IMossEvent> eventQueue = new ArrayBlockingQueue<>(
EngineSettings.getInt("eventQueueCapacity", 40), false); //$NON-NLS-1$
ArrayBlockingQueue<IMossEvent> eventQueue = new ArrayBlockingQueue<>(
EngineSettings.getInt("eventQueueCapacity", EVT_QUEUE_CAPACITY), false); //$NON-NLS-1$
protected final int maxEventThreads = EngineSettings.getInt(
"maxEventThreads", 8); //$NON-NLS-1$
protected final int maxEventThreads = EngineSettings.getInt(
"maxEventThreads", 8); //$NON-NLS-1$
protected final int initialEventThreads = EngineSettings.getInt(
"initialEventThreads", 8); //$NON-NLS-1$
protected final int initialEventThreads = EngineSettings.getInt(
"initialEventThreads", 8); //$NON-NLS-1$
ThreadGroup eventProcessorGroup = new ThreadGroup(
Messages.getString("EventProcessor.THREADGROUP")); //$NON-NLS-1$
ThreadGroup eventProcessorGroup = new ThreadGroup(
Messages.getString("EventProcessor.THREADGROUP")); //$NON-NLS-1$
protected AtomicBoolean runManager = new AtomicBoolean(true);
protected AtomicBoolean runManager = new AtomicBoolean(true);
protected final int sampleInterval = EngineSettings.getInt(
"eventQueueTuneSampleInterval", 100); //$NON-NLS-1$
protected final int sampleInterval = EngineSettings.getInt(
"eventQueueTuneSampleInterval", 100); //$NON-NLS-1$
protected final int upshift = EngineSettings.getInt(
"eventQueueTuneUpshift", 90); //$NON-NLS-1$
protected final int upshift = EngineSettings.getInt(
"eventQueueTuneUpshift", 90); //$NON-NLS-1$
protected final int downshift = EngineSettings.getInt(
"eventQueueTuneDownshift", 10); //$NON-NLS-1$
protected final int downshift = EngineSettings.getInt(
"eventQueueTuneDownshift", 10); //$NON-NLS-1$
protected final int samples = EngineSettings.getInt(
"eventQueueTuneSamples", 100); //$NON-NLS-1$
protected final int samples = EngineSettings.getInt(
"eventQueueTuneSamples", 100); //$NON-NLS-1$
protected final AtomicInteger currentThreads = new AtomicInteger(0);
protected final AtomicInteger currentThreads = new AtomicInteger(0);
private Thread manager = new Thread(this.eventProcessorGroup,
new Runnable() {
/**
*
* The manager. Controls the thread number.
*/
@SuppressWarnings("nls")
@Override
public void run() {
private Thread manager = new Thread(this.eventProcessorGroup,
new Runnable() {
/**
*
* The manager. Controls the thread number.
*/
@SuppressWarnings("nls")
@Override
public void run() {
logger.info("The manager thread has been started."); //$NON-NLS-1$
int ticks = 0;
int ticksBusy = 0;
int lSampleInterval = EventProcessor.this.sampleInterval;
int lUpshift = EventProcessor.this.upshift;
int lDownshift = EventProcessor.this.downshift;
int lSamples = EventProcessor.this.samples;
Thread[] threads = new Thread[EventProcessor.this.maxEventThreads];
logger.info("The manager thread has been started."); //$NON-NLS-1$
int ticks = 0;
int ticksBusy = 0;
int lSampleInterval = EventProcessor.this.sampleInterval;
int lUpshift = EventProcessor.this.upshift;
int lDownshift = EventProcessor.this.downshift;
int lSamples = EventProcessor.this.samples;
Thread[] threads = new Thread[EventProcessor.this.maxEventThreads];
for (int i = 0; i < EventProcessor.this.initialEventThreads; i++) {
int c = EventProcessor.this.currentThreads.get();
threads[c] = new Thread(
EventProcessor.this.eventProcessorGroup,
new Runnable() {
for (int i = 0; i < EventProcessor.this.initialEventThreads; i++) {
int c = EventProcessor.this.currentThreads.get();
threads[c] = new Thread(
EventProcessor.this.eventProcessorGroup,
new Runnable() {
@Override
public void run() {
logger.debug(Messages
.getString("EventProcessor.MSG_THREAD_START")); //$NON-NLS-1$
processEvents();
}
@Override
public void run() {
logger.debug(Messages
.getString("EventProcessor.MSG_THREAD_START")); //$NON-NLS-1$
processEvents();
}
});
threads[c].start();
});
threads[c].start();
EventProcessor.this.currentThreads.incrementAndGet();
EventProcessor.this.currentThreads.incrementAndGet();
}
while (EventProcessor.this.runManager.get()) {
ticks++;
if (!EventProcessor.this.eventQueue.isEmpty()) {
ticksBusy++;
}
if (ticks >= lSamples) {
if ((EventProcessor.this.currentThreads.get() < EventProcessor.this.maxEventThreads)
&& (((float) ticksBusy / (float) ticks) > ((float) lUpshift / (float) lSamples))) {
new Thread(
EventProcessor.this.eventProcessorGroup,
new Runnable() {
}
while (EventProcessor.this.runManager.get()) {
ticks++;
if (!EventProcessor.this.eventQueue.isEmpty()) {
ticksBusy++;
}
if (ticks >= lSamples) {
if ((EventProcessor.this.currentThreads.get() < EventProcessor.this.maxEventThreads)
&& (((float) ticksBusy / (float) ticks) > ((float) lUpshift / (float) lSamples))) {
new Thread(
EventProcessor.this.eventProcessorGroup,
new Runnable() {
@Override
public void run() {
System.out.println(Messages
.getString("EventProcessor.MSG_ADD_DYNAMIC")); //$NON-NLS-1$
processEvents();
}
@Override
public void run() {
System.out.println(Messages
.getString("EventProcessor.MSG_ADD_DYNAMIC")); //$NON-NLS-1$
processEvents();
}
}).run();
EventProcessor.this.currentThreads
.incrementAndGet();
}).run();
EventProcessor.this.currentThreads
.incrementAndGet();
}
if (((float) ticksBusy / (float) ticks) < ((float) lDownshift / (float) lSamples)) {
logger.info((Messages
.getString("EventProcessor.MSG_STOP_ONE_THREAD"))); //$NON-NLS-1$
EventProcessor.this.eventQueue
.add(new ThreadStopEvent());
}
if (((float) ticksBusy / (float) ticks) < ((float) lDownshift / (float) lSamples)) {
logger.info((Messages
.getString("EventProcessor.MSG_STOP_ONE_THREAD"))); //$NON-NLS-1$
EventProcessor.this.eventQueue
.add(new ThreadStopEvent());
}
ticks = 0;
ticksBusy = 0;
}
try {
Thread.sleep(lSampleInterval);
} catch (InterruptedException e) {
// manager awoke, no problem
}
}
}
}, Messages.getString("EventProcessor.THREAD_NAME_MGR")); //$NON-NLS-1$
}
ticks = 0;
ticksBusy = 0;
}
try {
Thread.sleep(lSampleInterval);
} catch (InterruptedException e) {
// manager awoke, no problem
}
}
}
}, Messages.getString("EventProcessor.THREAD_NAME_MGR")); //$NON-NLS-1$
private final MossScriptEnv ev;
private final MossScriptEnv ev;
private final ThreadContext tc;
private final ThreadContext tc;
/**
* Process events.
*/
void processEvents() {
MosstestSecurityManager.instance.setThreadContext(this.tc);
boolean run = true; // Not synchronized as only used locally
queueLoop: while (run) {
try {
IMossEvent myEvent = this.eventQueue.take();
{// Section for actually handling the events
if (myEvent instanceof ThreadStopEvent) {
this.currentThreads.decrementAndGet();
return;
}
dispatchEvent(myEvent);
}
/**
* Process events.
*/
void processEvents() {
MosstestSecurityManager.instance.setThreadContext(this.tc);
boolean run = true; // Not synchronized as only used locally
queueLoop:
while (true) {
try {
IMossEvent myEvent = this.eventQueue.take();
{// Section for actually handling the events
if (myEvent instanceof ThreadStopEvent) {
this.currentThreads.decrementAndGet();
return;
}
dispatchEvent(myEvent);
}
} catch (InterruptedException e) {
// thread struck, shut down the operation.
}
logger.info("A thread is shutting down."); //$NON-NLS-1$
this.currentThreads.decrementAndGet();
}
} catch (InterruptedException e) {
// thread struck, shut down the operation.
}
logger.info("A thread is shutting down."); //$NON-NLS-1$
this.currentThreads.decrementAndGet();
}
}
}
private void dispatchEvent(IMossEvent evt) {
ArrayList<MossEventHandler> evtHandlerList = this.ev
.getEventHandlers(evt.getClass());
try {
for (MossEventHandler ourHandler : evtHandlerList) {
if (dispatchEventInner(ourHandler, evt)) {
// continue loop
}
}
DefaultEventHandlers.processEvent(evt, this.ev);
} catch (MossScriptException | IllegalArgumentException e) {
logger.warn(e.getClass().getName() + " upon processing event: "
+ e.getMessage());
}
}
private void dispatchEvent(IMossEvent evt) {
ArrayList<MossEventHandler> evtHandlerList = this.ev
.getEventHandlers(evt.getClass());
try {
for (MossEventHandler ourHandler : evtHandlerList) {
if (dispatchEventInner(ourHandler, evt)) {
continue;
}
}
DefaultEventHandlers.processEvent(evt, this.ev);
} catch (MossScriptException | IllegalArgumentException e) {
logger.warn(e.getClass().getName() + " upon processing event: "
+ e.getMessage());
}
}
private boolean dispatchEventInner(MossEventHandler ourHandler,
IMossEvent evt) throws IllegalArgumentException {
try {
if (evt instanceof MossNodeChangeEvent) {
private boolean dispatchEventInner(MossEventHandler ourHandler,
IMossEvent evt) throws IllegalArgumentException {
try {
if (evt instanceof MossNodeChangeEvent) {
return ((MossNodeChangeHandler) ourHandler)
.onAction((MossNodeChangeEvent) evt);
return ((MossNodeChangeHandler) ourHandler)
.onAction((MossNodeChangeEvent) evt);
} else
throw new IllegalArgumentException(
"The event passed in was not a type that Mosstest is equipped to handle.");
} else
throw new IllegalArgumentException(
"The event passed in was not a type that Mosstest is equipped to handle.");
} catch (ClassCastException e) {
throw new IllegalArgumentException(
"The event handler did not match in type with the event.");
}
}
} catch (ClassCastException e) {
throw new IllegalArgumentException(
"The event handler did not match in type with the event.");
}
}
/**
* Constructs a new event processor.
*
* @param ev
* A script environment populated with event handlers.
* @param tc
* the tc
*/
public EventProcessor(MossScriptEnv ev, ThreadContext tc) {
this.ev = ev;
this.tc = tc;
this.manager.start();
/**
* Constructs a new event processor.
*
* @param ev A script environment populated with event handlers.
* @param tc the tc
*/
public EventProcessor(MossScriptEnv ev, ThreadContext tc) {
this.ev = ev;
this.tc = tc;
this.manager.start();
}
}
}

View File

@ -1,11 +1,7 @@
package net.mosstest.servercore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;
// TODO: Auto-generated Javadoc
/**
@ -34,9 +30,9 @@ public class FuturesProcessor {
public synchronized void runOnce(long delayMillis, Runnable runnable) {
Job tJob = new Job(System.currentTimeMillis() + delayMillis, 0, 0, 1.0,
false, runnable);
this.nextWakeup = (long) Math.min(this.nextWakeup,
System.currentTimeMillis() + delayMillis);
this.jobs.put(System.currentTimeMillis() + delayMillis, tJob);
this.nextWakeup = Math.min(this.nextWakeup,
System.currentTimeMillis() + delayMillis);
this.jobs.put(System.currentTimeMillis() + delayMillis, tJob);
this.futuresThread.interrupt();
}
@ -109,10 +105,10 @@ public class FuturesProcessor {
for (Job job : requeues) {
job.nextInvocation = System.currentTimeMillis()
+ job.delay + (long) Math.random()
* job.delayJitter;
FuturesProcessor.this.jobs.put(job.nextInvocation, job);
}
+ job.delay + (long) (Math.random()
* job.delayJitter);
FuturesProcessor.this.jobs.put(job.nextInvocation, job);
}
}
}
@ -165,8 +161,8 @@ public class FuturesProcessor {
this.renew = renew;
this.r = r;
this.nextInvocation = firstInvocation + delay
+ (long) Math.random() * delayJitter;
}
+ (int) (Math.random() * delayJitter);
}
}
}
}

View File

@ -1,164 +0,0 @@
package net.mosstest.servercore;
import java.util.ArrayList;
import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.bytes;
import java.util.HashMap;
import java.util.Map.Entry;
import net.mosstest.scripting.MapNode;
import net.mosstest.scripting.MossItem;
import net.mosstest.scripting.MossItem;
import org.iq80.leveldb.DB;
import com.google.common.collect.HashBiMap;
// TODO: Auto-generated Javadoc
/**
* The Class GenericManager.
*
* @param <E> the element type
* @param <B> the generic type
*/
public class GenericManager<E, B> {
/** The def items. */
private ArrayList<MossItem> defItems = new ArrayList<>();
/** The def items by name. */
private HashMap<String, MossItem> defItemsByName = new HashMap<>();
/** The pending. */
private HashBiMap<Short, String> pending = HashBiMap.create();
/** The item db. */
private DB itemDb;
/** The unknown fallback item. */
private final MossItem unknownFallbackItem = new MossItem(
"item_unknown.png", "sys_hand.png", 1, true,
"An unidentifiable item", "sys:unknown");
{
this.unknownFallbackItem.setItemId((short) -1);
defItems.add(this.unknownFallbackItem);
itemsForNode.put(NodeManager.getUnknownFallbackNode(),
this.unknownFallbackItem);
}
/**
* Gets the node.
*
* @param nodeId the node id
* @return the node
*/
public MossItem getNode(short nodeId) {
return this.defItems.get(nodeId);
}
/**
* Put node.
*
* @param item the item
* @return the short
* @throws MossWorldLoadException the moss world load exception
*/
public short putNode(MossItem item) throws MossWorldLoadException {
if (this.pending.containsValue(item.getTechnicalName())) {
item.setItemId(this.pending.inverse().get(item.getTechnicalName()));
this.defItems.set(
this.pending.inverse().get(item.getTechnicalName()), item);
this.defItemsByName.put(item.getTechnicalName(), item);
} else {
if (this.defItems.size() > 32000)
throw new MossWorldLoadException("Too many itemdefs"); //$NON-NLS-1$
item.setItemId((short) this.defItems.size());
this.defItems.add(item);
this.defItemsByName.put(item.getTechnicalName(), item);
this.itemDb.put(new byte[] { (byte) (item.getItemId() >>> 8),
(byte) (item.getItemId() & 0xFF) },
bytes(item.getTechnicalName()));
}
return item.getItemId();
}
/**
* Put node alias.
*
* @param alias the alias
* @param dst the dst
*/
public void putNodeAlias(String alias, String dst) {
MossItem dstItem = this.defItemsByName.get(dst);
this.defItemsByName.put(alias, dstItem);
}
/**
* Gets the item.
*
* @param string the string
* @param isModified the is modified
* @return the item
*/
public MossItem getItem(String string, boolean isModified) {
MossItem r = this.defItemsByName.get(string);
return r == null ? this.unknownFallbackItem : r;
}
/**
* Gets the item.
*
* @param string the string
* @return the item
*/
public MossItem getItem(String string) {
MossItem r = this.defItemsByName.get(string);
return r == null ? this.unknownFallbackItem : r;
}
/**
* Instantiates a new generic manager.
*
* @param itemdb the itemdb
*/
public GenericManager(DB itemdb) {
this.itemDb = itemdb;
for (Entry<byte[], byte[]> entry : itemdb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
/** The items for node. */
private static HashMap<MapNode, MossItem> itemsForNode = new HashMap<>();
/**
* Gets the for node.
*
* @param nd the nd
* @return the for node
*/
public static MossItem getForNode(MapNode nd) {
MossItem item = itemsForNode.get(nd);
if (item == null) {
// item = createForNode(MossItem); //FIXME
itemsForNode.put(nd, item);
return item;
} else
return item;
}
/*
* private static MossItem createForNode(MossItem MossItem) { MossItem
* mi=new MossItem(MossItem.texture, MossItem, 1, true,
* MossItem.userFacingName, MossItem.nodeName) return mi; //TODO todo }
*/
// FIXME above
}

View File

@ -1,20 +1,19 @@
package net.mosstest.servercore;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import com.jme3.asset.AssetLocator;
public interface IFileManager {
public IMossFile getFile(String name) throws FileNotFoundException, IOException;
public void registerFile(String name, String sha256, int size, long version);
public void receiveFileChunk(String sha512, int chunkId, ByteBuffer buf);
public Class<? extends AssetLocator> getAssetLocatorClass();
public List<IMossFile> getFiles();
}
package net.mosstest.servercore;
import com.jme3.asset.AssetLocator;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
public interface IFileManager {
public IMossFile getFile(String name) throws IOException;
public void registerFile(String name, String sha256, int size, long version);
public void receiveFileChunk(String sha512, int chunkId, ByteBuffer buf);
public Class<? extends AssetLocator> getAssetLocatorClass();
public List<? extends IMossFile> getFiles();
}

View File

@ -1,22 +1,22 @@
package net.mosstest.servercore;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
public interface IMossFile {
long CHUNK_SIZE = 65536;
public Reader getReader() throws FileNotFoundException;
public InputStream getInputStream() throws FileNotFoundException;
public byte[] readChunk(int chunkId) throws IOException;
public void writeChunk(int chunkId, byte[] buf) throws IOException;
public String getSha256();
}
package net.mosstest.servercore;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
public interface IMossFile {
long CHUNK_SIZE = 65536;
public Reader getReader() throws FileNotFoundException;
public InputStream getInputStream() throws FileNotFoundException;
public byte[] readChunk(int chunkId) throws IOException;
public void writeChunk(int chunkId, byte[] buf) throws IOException;
public String getSha256();
public String getName();
}

View File

@ -1,161 +1,81 @@
package net.mosstest.servercore;
import java.util.ArrayList;
import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.bytes;
import java.util.HashMap;
import java.util.Map.Entry;
import net.mosstest.scripting.MapNode;
import net.mosstest.scripting.MossItem;
import net.mosstest.scripting.MossItem;
import net.mosstest.scripting.MossItemBuilder;
import org.iq80.leveldb.DB;
import com.google.common.collect.HashBiMap;
import java.util.ArrayList;
import java.util.HashMap;
// TODO: Auto-generated Javadoc
/**
* The Class ItemManager.
*/
public class ItemManager {
/** The def items. */
private ArrayList<MossItem> defItems = new ArrayList<>();
/** The def items by name. */
private HashMap<String, MossItem> defItemsByName = new HashMap<>();
/** The pending. */
private HashBiMap<Short, String> pending = HashBiMap.create();
/** The item db. */
private DB itemDb;
/** The unknown fallback item. */
private final MossItem unknownFallbackItem = new MossItem(
"item_unknown.png", "sys_hand.png", 1, true,
"An unidentifiable item", "sys:unknown");
{
this.unknownFallbackItem.setItemId((short) -1);
defItems.add(this.unknownFallbackItem);
itemsForNode.put(NodeManager.getUnknownFallbackNode(),
this.unknownFallbackItem);
}
public static final int MAX_ITEMDEF = 32000;
public static final int BYTE_CAST_MASK = 0xFF;
/**
* Gets the node.
*
* @param nodeId the node id
* @return the node
*/
public MossItem getNode(short nodeId) {
return this.defItems.get(nodeId);
}
private ArrayList<MossItem> defItems = new ArrayList<>();
/**
* Put node.
*
* @param item the item
* @return the short
* @throws MossWorldLoadException the moss world load exception
*/
public short putNode(MossItem item) throws MossWorldLoadException {
if (this.pending.containsValue(item.getTechnicalName())) {
item.setItemId(this.pending.inverse().get(item.getTechnicalName()));
this.defItems.set(
this.pending.inverse().get(item.getTechnicalName()), item);
this.defItemsByName.put(item.getTechnicalName(), item);
} else {
if (this.defItems.size() > 32000)
throw new MossWorldLoadException("Too many itemdefs"); //$NON-NLS-1$
private HashMap<String, MossItem> defItemsByName = new HashMap<>();
item.setItemId((short) this.defItems.size());
this.defItems.add(item);
this.defItemsByName.put(item.getTechnicalName(), item);
this.itemDb.put(new byte[] { (byte) (item.getItemId() >>> 8),
(byte) (item.getItemId() & 0xFF) },
bytes(item.getTechnicalName()));
}
return item.getItemId();
}
/**
* The unknown fallback item.
*/
private final MossItem unknownFallbackItem = new MossItemBuilder().setInvTex("item_unknown.png").setWieldTex("sys_hand.png").setInvWeight(1).setStackMode(MossItem.StackMode.STACK_UNIT).setDisplayName("An unidentifiable item").setInternalName("sys:unknown").createMossItem();
/**
* Put node alias.
*
* @param alias the alias
* @param dst the dst
*/
public void putNodeAlias(String alias, String dst) {
MossItem dstItem = this.defItemsByName.get(dst);
this.defItemsByName.put(alias, dstItem);
}
/**
* Gets the item.
*
* @param string the string
* @param isModified the is modified
* @return the item
*/
public MossItem getItem(String string, boolean isModified) {
MossItem r = this.defItemsByName.get(string);
return r == null ? this.unknownFallbackItem : r;
}
public MossItem getItem(short itemId) {
return this.defItems.get(itemId);
}
/**
* Gets the item.
*
* @param string the string
* @return the item
*/
public MossItem getItem(String string) {
MossItem r = this.defItemsByName.get(string);
return r == null ? this.unknownFallbackItem : r;
}
/**
* Instantiates a new item manager.
*
* @param itemdb the itemdb
*/
public ItemManager(DB itemdb) {
this.itemDb = itemdb;
for (Entry<byte[], byte[]> entry : itemdb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
/** The items for node. */
private static HashMap<MapNode, MossItem> itemsForNode = new HashMap<>();
public void putNodeAlias(String alias, String dst) {
MossItem dstItem = this.defItemsByName.get(dst);
this.defItemsByName.put(alias, dstItem);
}
/**
* Gets the for node.
*
* @param nd the nd
* @return the for node
*/
public static MossItem getForNode(MapNode nd) {
MossItem item = itemsForNode.get(nd);
if (item == null) {
// item = createForNode(MossItem); //FIXME
itemsForNode.put(nd, item);
return item;
} else
return item;
}
public MossItem getItem(String string) {
MossItem r = this.defItemsByName.get(string);
return r == null ? this.unknownFallbackItem : r;
}
public ItemManager() {
}
private HashMap<MapNode, MossItem> itemsForNode = new HashMap<>();
public MossItem getForNode(MapNode nd) {
MossItem item = itemsForNode.get(nd);
if (item == null) {
// item = createForNode(MossItem); //FIXME
itemsForNode.put(nd, item);
return item;
} else
return item;
}
{
defItems.add(this.unknownFallbackItem);
itemsForNode.put(NodeManager.getUnknownFallbackNode(),
this.unknownFallbackItem);
}
/*
* private static MossItem createForNode(MossItem MossItem) { MossItem
* private static MossItem createForNode(MossItem MossItem) { MossItem
* mi=new MossItem(MossItem.texture, MossItem, 1, true,
* MossItem.userFacingName, MossItem.nodeName) return mi; //TODO todo }
*/
// FIXME above
// FIXME above
}

View File

@ -1,56 +1,56 @@
package net.mosstest.servercore;
import java.io.IOException;
import java.io.InputStream;
import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetLocator;
import com.jme3.asset.AssetManager;
public class LocalAssetLocator implements AssetLocator {
private LocalFileManager lfm;
@Override
public AssetInfo locate(AssetManager manager, AssetKey key) {
if (this.lfm == null)
this.lfm = LocalFileManager.getFileManager("moss://scripts");
if (this.lfm == null)
this.lfm = LocalFileManager.scriptsInstance;
try {
return new LocalAssetInfo(manager, key,
this.lfm.getFile(key.getName()));
} catch (IOException ex) {
throw new AssetLoadException("Failed to open file: "
+ key.getName(), ex);
}
}
@Override
public void setRootPath(String arg0) {
this.lfm = LocalFileManager.getFileManager(arg0);
}
private static class LocalAssetInfo extends AssetInfo {
private LocalFile file;
public LocalAssetInfo(AssetManager manager, AssetKey key, LocalFile file) {
super(manager, key);
this.file = file;
}
@Override
public InputStream openStream() {
try {
return this.file.getInputStream();
} catch (IOException ex) {
throw new AssetLoadException("Failed to open file: "
+ this.file.getFilename(), ex);
}
}
}
}
package net.mosstest.servercore;
import java.io.IOException;
import java.io.InputStream;
import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetLocator;
import com.jme3.asset.AssetManager;
public class LocalAssetLocator implements AssetLocator {
private LocalFileManager lfm;
@Override
public AssetInfo locate(AssetManager manager, AssetKey key) {
if (this.lfm == null)
this.lfm = LocalFileManager.getFileManager("scripts");
if (this.lfm == null)
this.lfm = LocalFileManager.scriptsInstance;
try {
return new LocalAssetInfo(manager, key,
this.lfm.getFile(key.getName()));
} catch (IOException ex) {
throw new AssetLoadException("Failed to open file: "
+ key.getName(), ex);
}
}
@Override
public void setRootPath(String arg0) {
this.lfm = LocalFileManager.getFileManager(arg0);
}
private static class LocalAssetInfo extends AssetInfo {
private LocalFile file;
public LocalAssetInfo(AssetManager manager, AssetKey key, LocalFile file) {
super(manager, key);
this.file = file;
}
@Override
public InputStream openStream() {
try {
return this.file.getInputStream();
} catch (IOException ex) {
throw new AssetLoadException("Failed to open file: "
+ this.file.getFilename(), ex);
}
}
}
}

View File

@ -1,78 +1,77 @@
package net.mosstest.servercore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
public class LocalFile implements IMossFile {
public String getFilename() {
return f.getAbsolutePath();
}
static Logger logger = Logger.getLogger(LocalFile.class);
private final File f;
private final RandomAccessFile rFile;
private final int numChunks;
private final long length;
private final String sha256;
public LocalFile(File f) throws IOException {
if (!f.canRead())
throw new FileNotFoundException(
"File not existent or cannot be read");
this.f = f;
this.rFile = new RandomAccessFile(f, "r");
this.length = this.rFile.length();
this.numChunks = (int) Math.ceil(this.length
/ ((double) IMossFile.CHUNK_SIZE));
try {
this.sha256 = LocalFileManager.getHash(f);
logger.info("Hashed " + f.getAbsolutePath() + " as " + this.sha256);
} catch (NoSuchAlgorithmException e) {
logger.error("Could not find algorithm SHA-256 while hashing " + f.getAbsolutePath());
throw new IOException("Hashing failed while preparing file");
}
}
@Override
public Reader getReader() throws FileNotFoundException {
return new FileReader(this.f);
}
@Override
public InputStream getInputStream() throws FileNotFoundException {
return new FileInputStream(this.f);
}
@Override
public byte[] readChunk(int chunkId) throws IOException {
this.rFile.seek(chunkId * IMossFile.CHUNK_SIZE);
byte[] buf = new byte[(int) (chunkId == (this.numChunks - 1) ? (this.length % IMossFile.CHUNK_SIZE)
: IMossFile.CHUNK_SIZE)];
this.rFile.readFully(buf);
return buf;
}
@Override
public void writeChunk(int chunkId, byte[] buf) throws IOException {
throw new IOException(
"An attempt was made to write to a read-only local file");
}
@Override
public String getSha256() {
return this.sha256;
}
}
package net.mosstest.servercore;
import org.apache.log4j.Logger;
import java.io.*;
import java.security.NoSuchAlgorithmException;
public class LocalFile implements IMossFile {
public String getFilename() {
return f.getAbsolutePath();
}
static Logger logger = Logger.getLogger(LocalFile.class);
private final File f;
private final RandomAccessFile rFile;
private final int numChunks;
private final long length;
private final String name;
@Override
public String getName() {
return name;
}
private final String sha256;
public LocalFile(String name, File f) throws IOException {
this.name = name;
if (!f.canRead())
throw new FileNotFoundException(
"File not existent or cannot be read");
this.f = f;
this.rFile = new RandomAccessFile(f, "r");
this.length = this.rFile.length();
this.numChunks = (int) Math.ceil(this.length
/ ((double) IMossFile.CHUNK_SIZE));
try {
this.sha256 = LocalFileManager.getHash(f);
logger.info("Hashed " + f.getAbsolutePath() + " as " + this.sha256);
} catch (NoSuchAlgorithmException e) {
logger.error("Could not find algorithm SHA-256 while hashing " + f.getAbsolutePath());
throw new IOException("Hashing failed while preparing file");
}
}
@Override
public Reader getReader() throws FileNotFoundException {
return new FileReader(this.f);
}
@Override
public InputStream getInputStream() throws FileNotFoundException {
return new FileInputStream(this.f);
}
@Override
public byte[] readChunk(int chunkId) throws IOException {
this.rFile.seek(chunkId * IMossFile.CHUNK_SIZE);
byte[] buf = new byte[(int) (chunkId == (this.numChunks - 1) ? (this.length % IMossFile.CHUNK_SIZE)
: IMossFile.CHUNK_SIZE)];
this.rFile.readFully(buf);
return buf;
}
@Override
public void writeChunk(int chunkId, byte[] buf) throws IOException {
throw new IOException(
"An attempt was made to write to a read-only local file");
}
@Override
public String getSha256() {
return this.sha256;
}
}

View File

@ -1,125 +1,189 @@
package net.mosstest.servercore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.NotImplementedException;
import org.apache.log4j.Logger;
import com.jme3.asset.AssetLocator;
public class LocalFileManager implements IFileManager {
public static final LocalFileManager scriptsInstance;
private static HashMap<String, LocalFileManager> managers = new HashMap<>();
static {
scriptsInstance = new LocalFileManager(
new File("data/scripts"));
managers.put("scripts", scriptsInstance);
}
private ArrayList<LocalFile> files;
public static LocalFileManager getFileManager(String key) {
return managers.get(key);
}
private final File basedir;
static Logger logger = Logger.getLogger(LocalFileManager.class);
@Override
public LocalFile getFile(String name) throws IOException {
String normalized = FilenameUtils.normalize(name);
if (normalized == null) {
logger.warn("Failed to normalize game resource filename: " + name);
throw new FileNotFoundException("The filename " + name
+ " could not be normalized.");
}
File f = new File(this.basedir, normalized);
logger.info("Got local file " + name + " as " + f.getAbsolutePath());
return new LocalFile(f);
}
@Override
public void registerFile(String name, String sha256, int size, long version)
throws NotImplementedException {
throw new NotImplementedException();
}
@Override
public void receiveFileChunk(String sha512, int chunkId, ByteBuffer buf) {
throw new NotImplementedException();
}
@Override
public Class<? extends AssetLocator> getAssetLocatorClass() {
return LocalAssetLocator.class;
}
public LocalFileManager(File basedir) {
this.basedir = basedir;
}
public static String getHash(File f) throws IOException,
NoSuchAlgorithmException {
MessageDigest md = null;
FileInputStream fis = null;
FileChannel fc = null;
ByteBuffer bbf = null;
StringBuilder hexString = null;
md = MessageDigest.getInstance("SHA-256");
fis = new FileInputStream(f);
fc = fis.getChannel();
bbf = ByteBuffer.allocateDirect(8192);
int b;
b = fc.read(bbf);
while ((b != -1) && (b != 0)) {
bbf.flip();
byte[] bytes = new byte[b];
bbf.get(bytes);
md.update(bbf);
bbf.clear();
b = fc.read(bbf);
}
fis.close();
byte[] mdbytes = md.digest();
hexString = new StringBuilder();
for (int i = 0; i < mdbytes.length; i++) {
hexString.append(Integer.toHexString((0xFF & mdbytes[i])));
}
return hexString.toString();
}
@Override
public List<IMossFile> getFiles() {
// TODO Auto-generated method stub
return null;
}
}
package net.mosstest.servercore;
import com.google.common.collect.ImmutableList;
import com.jme3.asset.AssetLocator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang.NotImplementedException;
import org.apache.log4j.Logger;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
public class LocalFileManager implements IFileManager {
public static final LocalFileManager scriptsInstance;
public static final int HASHING_BUFFER_SIZE = 8192;
public static final int BYTE_CAST_MASK = 0xFF;
@SuppressWarnings("StaticCollection")
private static HashMap<String, LocalFileManager> managers = new HashMap<>();
static {
scriptsInstance = new LocalFileManager(new File("data/scripts"));
managers.put("scripts", scriptsInstance);
}
private HashMap<String, LocalFile> files = new HashMap<>();
public static final IOFileFilter CVS_FILTER = FileFilterUtils.makeCVSAware(null);
public static LocalFileManager getFileManager(String key) {
return managers.get(key);
}
private final File basedir;
static Logger logger = Logger.getLogger(LocalFileManager.class);
@Override
public LocalFile getFile(String name) throws IOException {
String normalized = FilenameUtils.normalize(name);
if (normalized == null) {
logger.warn("Failed to normalize game resource filename: " + name);
throw new FileNotFoundException("The filename " + name
+ " could not be normalized.");
}
File f = new File(this.basedir, normalized);
logger.info("Got local file " + name + " as " + f.getAbsolutePath());
return new LocalFile(name, f);
}
@Override
public void registerFile(String name, String sha256, int size, long version)
throws NotImplementedException {
throw new NotImplementedException();
}
public void registerFile(String name, LocalFile lf) {
this.files.put(name, lf);
}
@Override
public void receiveFileChunk(String sha512, int chunkId, ByteBuffer buf) {
throw new NotImplementedException();
}
@Override
public Class<? extends AssetLocator> getAssetLocatorClass() {
return LocalAssetLocator.class;
}
public LocalFileManager(File basedir) {
this.basedir = basedir;
}
public static String getHash(File f) throws IOException,
NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (FileInputStream fis = new FileInputStream(f)) {
try (FileChannel fc = fis.getChannel()) {
ByteBuffer bbf = ByteBuffer.allocateDirect(HASHING_BUFFER_SIZE);
int bytesRead;
bytesRead = fc.read(bbf);
while ((bytesRead != -1) && (bytesRead != 0)) {
bbf.flip();
byte[] bytes = new byte[bytesRead];
bbf.get(bytes);
md.update(bbf);
bbf.clear();
bytesRead = fc.read(bbf);
}
fis.close();
byte[] mdBytes = md.digest();
StringBuilder hexString = new StringBuilder();
for (byte b : mdBytes) {
hexString.append(Integer.toHexString((BYTE_CAST_MASK & b)));
}
return hexString.toString();
}
}
}
@Override
public List<? extends IMossFile> getFiles() {
return ImmutableList.copyOf(files.values());
}
public IMossFile getScriptInitFile(String scName) throws IOException {
String normalized = FilenameUtils.normalize(scName);
if (normalized == null) {
logger.warn("Failed to normalize game resource filename: " + scName);
throw new FileNotFoundException("The filename " + scName
+ " could not be normalized.");
}
final String scriptName = normalized + "/init.js";
LocalFile scriptFile = getFile(scriptName);
registerFile(scriptName, scriptFile);
try {
final String indexName = normalized + "/index";
LocalFile fileIndex = getFile(indexName);
registerFile(indexName, scriptFile);
BufferedReader idxR = new BufferedReader(fileIndex.getReader());
String line;
while ((line = idxR.readLine()) != null) {
String normalizedLine = FilenameUtils.normalize(line.trim());
if (normalizedLine == null) {
logger.warn("Failed to normalize game resource filename from file index: "
+ line);
continue;
}
try {
final String filename = normalized + normalizedLine;
final LocalFile file = getFile(filename);
this.registerFile(filename, file);
} catch (FileNotFoundException e) {
logger.warn("File was in index but not on disk: "
+ line);
}
}
} catch (FileNotFoundException e) {
logger.warn("No index file found; no files will be served to the client.");
File base = new File(basedir, normalized);
Path basePath = Paths.get(basedir.getAbsolutePath());
for (File f : FileUtils.listFiles(base, CVS_FILTER, CVS_FILTER)) {
try {
Path path = Paths.get(f.getAbsolutePath());
final String resolvedName = basePath.relativize(path).toFile().getPath();
LocalFile file = this.getFile(resolvedName);
logger.debug("Got file via recursive directory listing: " + resolvedName);
this.registerFile(resolvedName, file);
} catch (FileNotFoundException fnfe2) {
// should not happen
logger.warn("Could not find file from recursive directory listing. This should never happen.");
}
}
}
return scriptFile;
}
}

View File

@ -1,109 +1,110 @@
package net.mosstest.servercore;
import java.util.ArrayList;
import net.mosstest.scripting.MapNode;
import org.iq80.leveldb.DB;
import java.util.Map.Entry;
import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.bytes;
import java.util.HashMap;
import java.util.Map.Entry;
import net.mosstest.scripting.MapNode;
import org.iq80.leveldb.DB;
import com.google.common.collect.HashBiMap;
// TODO: Auto-generated Javadoc
/**
* The Class LocalNodeManager.
*/
public class LocalNodeManager extends AbstractNodeManager {
/** The node db. */
private DB nodeDb;
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(short)
*/
@Override
public MapNode getNode(short nodeId) {
return this.definedNodes.get(nodeId);
}
public static final int NODE_ID_MAX = 16384;
/**
* The node db.
*/
private DB nodeDb;
private ItemManager itemManager;
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNode(net.mosstest.scripting.MapNode)
*/
@Override
public short putNode(MapNode node) throws MossWorldLoadException {
if (this.pending.containsValue(node.nodeName)) {
node.setNodeId(this.pending.inverse().get(node.nodeName));
this.definedNodes.set(this.pending.inverse().get(node.nodeName),
node);
this.defNodeByName.put(node.nodeName, node);
} else {
if (this.definedNodes.size() > 16384)
throw new MossWorldLoadException("Too many nodedefs"); //$NON-NLS-1$
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(short)
*/
@Override
public MapNode getNode(short nodeId) {
return this.definedNodes.get(nodeId);
}
node.setNodeId((short) this.definedNodes.size());
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNode(net.mosstest.scripting.MapNode)
*/
@Override
public short putNode(MapNode node) throws MossWorldLoadException {
if (this.pending.containsValue(node.nodeName)) {
node.setNodeId(this.pending.inverse().get(node.nodeName));
this.definedNodes.set(this.pending.inverse().get(node.nodeName),
node);
this.defNodeByName.put(node.nodeName, node);
node.setDropItem(this.itemManager.getForNode(node));
} else {
if (this.definedNodes.size() > NODE_ID_MAX)
throw new MossWorldLoadException("Too many nodedefs"); //$NON-NLS-1$
this.definedNodes.add(node);
this.defNodeByName.put(node.nodeName, node);
this.nodeDb.put(new byte[] { (byte) (node.getNodeId() >>> 8),
(byte) (node.getNodeId() & 0xFF) }, bytes(node.nodeName));
}
node.setNodeId((short) this.definedNodes.size());
return node.getNodeId();
}
this.definedNodes.add(node);
this.defNodeByName.put(node.nodeName, node);
this.nodeDb.put(new byte[]{(byte) (node.getNodeId() >>> 8),
(byte) (node.getNodeId() & 0xFF)}, bytes(node.nodeName));
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNodeAlias(java.lang.String, java.lang.String)
*/
@Override
public void putNodeAlias(String alias, String dst) {
MapNode dstNode = this.defNodeByName.get(dst);
this.defNodeByName.put(alias, dstNode);
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String, boolean)
*/
@Override
public MapNode getNode(String string, boolean isModified) {
MapNode r = this.defNodeByName.get(string);
return (r==null)?AbstractNodeManager.MAPNODE_UNKNOWN:r;
}
return node.getNodeId();
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String)
*/
@Override
public MapNode getNode(String string) {
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNodeAlias(java.lang.String, java.lang.String)
*/
@Override
public void putNodeAlias(String alias, String dst) {
MapNode dstNode = this.defNodeByName.get(dst);
this.defNodeByName.put(alias, dstNode);
}
MapNode r = this.defNodeByName.get(string);
return (r==null)?AbstractNodeManager.MAPNODE_UNKNOWN:r;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String, boolean)
*/
@Override
public MapNode getNode(String string, boolean isModified) {
MapNode r = this.defNodeByName.get(string);
return (r == null) ? AbstractNodeManager.MAPNODE_UNKNOWN : r;
}
/**
* Instantiates a new local node manager.
*
* @param nodedb the nodedb
*/
public LocalNodeManager(DB nodedb) {
this.nodeDb = nodedb;
this.init();
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String)
*/
@Override
public MapNode getNode(String string) {
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#init()
*/
@Override
public void init() {
for (Entry<byte[], byte[]> entry : this.nodeDb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
MapNode r = this.defNodeByName.get(string);
return (r == null) ? AbstractNodeManager.MAPNODE_UNKNOWN : r;
}
/**
* Instantiates a new local node manager.
*
* @param nodedb the nodedb
*/
public LocalNodeManager(DB nodedb, ItemManager mgr) {
this.nodeDb = nodedb;
this.itemManager = mgr;
this.init();
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#init()
*/
@Override
public void init() {
for (Entry<byte[], byte[]> entry : this.nodeDb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
}

View File

@ -1,176 +1,186 @@
package net.mosstest.servercore;
import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.Player;
import net.mosstest.scripting.Position;
import org.apache.log4j.Logger;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.log4j.Logger;
import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.MapGenerators;
import net.mosstest.scripting.Player;
import net.mosstest.scripting.Position;
import net.mosstest.scripting.SimplexMapGenerator;
// TODO: Auto-generated Javadoc
/**
* The Class LocalRenderPreparator.
*/
public class LocalRenderPreparator implements IRenderPreparator {
/** The logger. */
static Logger logger = Logger.getLogger(LocalRenderPreparator.class);
/**
* The Class ChunkLookupRunnable.
*/
public class ChunkLookupRunnable implements Runnable {
public static final int CHUNK_REQUESTS_QUEUE_SIZE = 1024;
/**
* The logger.
*/
static Logger logger = Logger.getLogger(LocalRenderPreparator.class);
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (LocalRenderPreparator.this.run) {
try {
Position requested = LocalRenderPreparator.this.chunkRequests
.take();
System.out
.println(Messages
.getString("LocalRenderPreparator.MSG_REQUESTED") + requested.x + "," //$NON-NLS-1$ //$NON-NLS-2$
+ requested.y + "," + requested.z); //$NON-NLS-1$
MapChunk chk = LocalRenderPreparator.this.nc
.getChunk(requested);
chk.pos = requested;
LocalRenderPreparator.this.rend.renderEventQueue
.put(new MossRenderChunkEvent(chk));
} catch (InterruptedException e) {
// pass
} catch (MapGeneratorException e) {
logger.error(Messages
.getString("LocalRenderPreparator.MG_EXCEPT")); //$NON-NLS-1$
}
}
}
/**
* The Class ChunkLookupRunnable.
*/
public class ChunkLookupRunnable implements Runnable {
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (LocalRenderPreparator.this.run) {
try {
Position requested = LocalRenderPreparator.this.chunkRequests
.take();
System.out
.println(Messages
.getString("LocalRenderPreparator.MSG_REQUESTED") + requested.x + "," //$NON-NLS-1$ //$NON-NLS-2$
+ requested.y + "," + requested.z); //$NON-NLS-1$
MapChunk chk = LocalRenderPreparator.this.nc
.getChunk(requested);
chk.pos = requested;
LocalRenderPreparator.this.rend.renderEventQueue
.put(new MossRenderChunkEvent(chk));
} catch (InterruptedException e) {
// pass
} catch (MapGeneratorException e) {
logger.error(Messages
.getString("LocalRenderPreparator.MG_EXCEPT")); //$NON-NLS-1$
}
}
}
/** The local player. */
private Player localPlayer;
/** The rend. */
private RenderProcessor rend;
/** The nc. */
private NodeCache nc;
/** The run. */
private volatile boolean run = true;
/** The chunk requests. */
public ArrayBlockingQueue<Position> chunkRequests = new ArrayBlockingQueue<>(
1024);
// private HashMap<Position, Position> outstandingChunks = new HashMap<>();
}
/** The lookup thread. */
private Thread lookupThread = new Thread(new ChunkLookupRunnable());
/** The nm. */
private INodeManager nm;
/**
* The local player.
*/
private Player localPlayer;
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#requestChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk requestChunk(Position pos) throws MapGeneratorException,
InterruptedException {
try {
MapChunk chk = this.nc.getChunkFailFast(pos);
logger.trace(chk == null ? "Chunk is null" : "Chunk obtained is: "+chk //$NON-NLS-1$
.toString());
if (chk == null) {
this.chunkRequests.put(pos);
}
return chk;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* The rend.
*/
private RenderProcessor rend;
/**
* Instantiates a new local render preparator.
*
* @param rp the rp
* @param nc the nc
*/
public LocalRenderPreparator(RenderProcessor rp, NodeCache nc) {
this.rend = rp;
this.nc = nc;
}
/**
* The nc.
*/
private NodeCache nc;
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#shutdown()
*/
@Override
public void shutdown() {
this.run = false;
}
/**
* The run.
*/
private volatile boolean run = true;
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#recvOutstandingChunk(net.mosstest.scripting.Position, net.mosstest.scripting.MapChunk)
*/
@Override
public void recvOutstandingChunk(Position pos, MapChunk chk) {
// pass
}
/**
* The chunk requests.
*/
public ArrayBlockingQueue<Position> chunkRequests = new ArrayBlockingQueue<>(
CHUNK_REQUESTS_QUEUE_SIZE);
// private HashMap<Position, Position> outstandingChunks = new HashMap<>();
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#start()
*/
@Override
public void start() {
try {
MapGenerators.setDefaultMapGenerator(new SimplexMapGenerator(), nm, 108080, new Object[0]);
} catch (MapGeneratorException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
logger.info(Messages
.getString("LocalRenderPreparator.START_MSG")); //$NON-NLS-1$
this.lookupThread.start();
/**
* The lookup thread.
*/
private Thread lookupThread = new Thread(new ChunkLookupRunnable());
}
/**
* The nm.
*/
private INodeManager nm;
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#setRenderProcessor(net.mosstest.servercore.RenderProcessor)
*/
@Override
public void setRenderProcessor(RenderProcessor rend) {
this.rend = rend;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#requestChunk(net.mosstest.scripting.Position)
*/
@Override
public MapChunk requestChunk(Position pos) throws MapGeneratorException,
InterruptedException {
try {
MapChunk chk = this.nc.getChunkFailFast(pos);
logger.trace(chk == null ? "Chunk is null" : "Chunk obtained is: " + chk //$NON-NLS-1$
.toString());
if (chk == null) {
this.chunkRequests.put(pos);
}
return chk;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#setNodeManager(net.mosstest.servercore.INodeManager)
*/
@Override
public void setNodeManager(INodeManager nm) {
this.nm = nm;
}
/**
* Instantiates a new local render preparator.
*
* @param rp the rp
* @param nc the nc
*/
public LocalRenderPreparator(RenderProcessor rp, NodeCache nc) {
this.rend = rp;
this.nc = nc;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.PlayerCommunicator#forceSetPosition(net.mosstest.scripting.Player, int, int, int, double, double, double)
*/
@Override
public void forceSetPosition(Player pl, int cx, int cy, int cz,
double offsetx, double offsety, double offsetz) throws InterruptedException {
if (!pl.equals(this.localPlayer))
return;
MossRenderSetPositionEvent mrspe = new MossRenderSetPositionEvent(
offsetx, offsety, offsetz, cx, cy, cz);
this.rend.renderEventQueue.put(mrspe);
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#shutdown()
*/
@Override
public void shutdown() {
this.run = false;
}
// TODO: Handle player movement, other server->client events affecting
// rendering
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#recvOutstandingChunk(net.mosstest.scripting.Position, net.mosstest.scripting.MapChunk)
*/
@Override
public void recvOutstandingChunk(Position pos, MapChunk chk) {
// pass
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#start()
*/
@Override
public void start() {
logger.info(Messages
.getString("LocalRenderPreparator.START_MSG")); //$NON-NLS-1$
this.lookupThread.start();
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#setRenderProcessor(net.mosstest.servercore.RenderProcessor)
*/
@Override
public void setRenderProcessor(RenderProcessor rend) {
this.rend = rend;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.IRenderPreparator#setNodeManager(net.mosstest.servercore.INodeManager)
*/
@Override
public void setNodeManager(INodeManager nm) {
this.nm = nm;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.PlayerCommunicator#forceSetPosition(net.mosstest.scripting.Player, int, int, int, double, double, double)
*/
@Override
public void forceSetPosition(Player pl, int cx, int cy, int cz,
double offsetx, double offsety, double offsetz) throws InterruptedException {
if (!pl.equals(this.localPlayer))
return;
MossRenderSetPositionEvent mrspe = new MossRenderSetPositionEvent(
offsetx, offsety, offsetz, cx, cy, cz);
this.rend.renderEventQueue.put(mrspe);
}
// TODO: Handle player movement, other server->client events affecting
// rendering
}

View File

@ -1,129 +1,130 @@
package net.mosstest.servercore;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
// TODO: Auto-generated Javadoc
/**
* The Class MossDebugUtils.
*/
public class MossDebugUtils {
/** The logger. */
static Logger logger = Logger.getLogger(MossDebugUtils.class);
/** The Constant propertiesToGet. */
private static final String[] propertiesToGet = { "awt.toolkit", //$NON-NLS-1$
"file.encoding", "file.separator", "java.class.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.home", "java.runtime.name", "java.runtime.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.specification.name", "java.specification.vendor", //$NON-NLS-1$ //$NON-NLS-2$
"java.specification.version", "java.vendor", "java.vm.info", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.vm.name", "java.vm.specification.name", "java.vm.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"os.arch", "os.name", "path.separator", "sun.arch.data.model", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
"sun.cpu.endian", "sun.desktop", "user.language" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
/**
* The logger.
*/
static Logger logger = Logger.getLogger(MossDebugUtils.class);
};
/**
* The Constant propertiesToGet.
*/
private static final String[] propertiesToGet = {"awt.toolkit", //$NON-NLS-1$
"file.encoding", "file.separator", "java.class.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.home", "java.runtime.name", "java.runtime.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.specification.name", "java.specification.vendor", //$NON-NLS-1$ //$NON-NLS-2$
"java.specification.version", "java.vendor", "java.vm.info", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"java.vm.name", "java.vm.specification.name", "java.vm.version", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"os.arch", "os.name", "path.separator", "sun.arch.data.model", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
"sun.cpu.endian", "sun.desktop", "user.language" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
/**
* Write stracktrace.
*
* @param e the e
* @return the string
*/
public static String writeStracktrace(Exception e) {
String fName = Integer.toString(System.identityHashCode(e), 16) + "@"
+ System.currentTimeMillis();
File write = new File("stacktraces/"+fName+".txt");
try {
new File("stacktraces").mkdirs();
write.createNewFile();
FileWriter writer = new FileWriter(write);
writer.write(getDebugInformation(e));
writer.close();
} catch (Exception e1) {
logger.fatal(e1.getClass().getName() + " caught trying to write stacktrace of an existing exception. Message: "+e1.getMessage());
}
return write.getAbsolutePath();
}
};
/**
* Gets the debug information.
*
* @param e the e
* @return the debug information
*/
public static String getDebugInformation(Exception e) {
StringBuilder s = new StringBuilder(
MossDebugUtils.getGitConfig("git.commit.id") + " on " + MossDebugUtils.getGitConfig("git.branch") + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
s.append(Messages.getString("MossDebugUtils.MSG_BUILT_ON") + MossDebugUtils.getGitConfig(Messages.getString("MossDebugUtils.27")) + "\r\n\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
s.append(Messages.getString("MossDebugUtils.MSG_EXCEPTION_CAUGHT")); //$NON-NLS-1$
for (StackTraceElement ste : e.getStackTrace()) {
s.append(ste.toString()).append("\r\n"); //$NON-NLS-1$
}
s.append("\r\n"); //$NON-NLS-1$
s.append(getOsDetails());
return s.toString();
}
/**
* Write stracktrace.
*
* @param e the e
* @return the string
*/
public static String writeStracktrace(Exception e) {
String fName = Integer.toString(System.identityHashCode(e), 16) + "@"
+ System.currentTimeMillis();
File write = new File("stacktraces/" + fName + ".txt");
try {
new File("stacktraces").mkdirs();
write.createNewFile();
try (FileWriter writer = new FileWriter(write)) {
writer.write(getDebugInformation(e));
writer.close();
}
} catch (Exception e1) {
logger.fatal(e1.getClass().getName() + " caught trying to write stacktrace of an existing exception. Message: " + e1.getMessage());
}
return write.getAbsolutePath();
}
/**
* Gets the os details.
*
* @return the os details
*/
public static String getOsDetails() {
StringBuilder s = new StringBuilder();
/**
* Gets the debug information.
*
* @param e the e
* @return the debug information
*/
public static String getDebugInformation(Exception e) {
StringBuilder s = new StringBuilder(
MossDebugUtils.getGitConfig("git.commit.id") + " on " + MossDebugUtils.getGitConfig("git.branch") + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
s.append(Messages.getString("MossDebugUtils.MSG_BUILT_ON")).append(MossDebugUtils.getGitConfig(Messages.getString("MossDebugUtils.27"))).append("\r\n\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
s.append(Messages.getString("MossDebugUtils.MSG_EXCEPTION_CAUGHT")); //$NON-NLS-1$
for (StackTraceElement ste : e.getStackTrace()) {
s.append(ste.toString()).append("\r\n"); //$NON-NLS-1$
}
s.append("\r\n"); //$NON-NLS-1$
s.append(getOsDetails());
return s.toString();
}
s.append(Messages.getString("MossDebugUtils.MSG_SYS_PROPS")); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_CORES") //$NON-NLS-1$
+ Runtime.getRuntime().availableProcessors() + "\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_FREEMEM") + Runtime.getRuntime().freeMemory() //$NON-NLS-1$
+ "\r\n"); //$NON-NLS-1$
long maxMemory = Runtime.getRuntime().maxMemory();
s.append(Messages.getString("MossDebugUtils.MSG_MAXMEM") //$NON-NLS-1$
+ (maxMemory == Long.MAX_VALUE ? Messages
.getString("MossDebugUtils.MSG_MEM_NO_LIMIT") : maxMemory) //$NON-NLS-1$
+ "\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_TOTAL_MEM") + Runtime.getRuntime().totalMemory() //$NON-NLS-1$
+ "\r\n"); //$NON-NLS-1$
File[] roots = File.listRoots();
/**
* Gets the os details.
*
* @return the os details
*/
public static String getOsDetails() {
StringBuilder s = new StringBuilder();
for (File root : roots) {
s.append(Messages.getString("MossDebugUtils.MSG_FS_ROOT") + root.getAbsolutePath() + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
s.append(Messages.getString("MossDebugUtils.MSG_TOTAL_SPACE") + root.getTotalSpace() + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
s.append(Messages.getString("MossDebugUtils.MSG_SYS_PROPS")); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_CORES")).append(Runtime.getRuntime().availableProcessors()).append("\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_FREEMEM")).append(Runtime.getRuntime().freeMemory()).append("\r\n"); //$NON-NLS-1$
long maxMemory = Runtime.getRuntime().maxMemory();
s.append(Messages.getString("MossDebugUtils.MSG_MAXMEM")).append(maxMemory == Long.MAX_VALUE ? Messages
.getString("MossDebugUtils.MSG_MEM_NO_LIMIT") : maxMemory).append("\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_TOTAL_MEM")).append(Runtime.getRuntime().totalMemory()).append("\r\n"); //$NON-NLS-1$
File[] roots = File.listRoots();
s.append(Messages.getString("MossDebugUtils.MSG_FREE_SPACE") + root.getFreeSpace() + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
s.append(Messages.getString("MossDebugUtils.MSG_USABLE_SPACE") + root.getUsableSpace() + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
s.append("\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_JAVA_PROPS")); //$NON-NLS-1$
for (String key : propertiesToGet) {
s.append(key + ":" + System.getProperty(key, "") + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return s.toString();
}
for (File root : roots) {
s.append(Messages.getString("MossDebugUtils.MSG_FS_ROOT")).append(root.getAbsolutePath()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
s.append(Messages.getString("MossDebugUtils.MSG_TOTAL_SPACE")).append(root.getTotalSpace()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
/**
* Gets the git config.
*
* @param cfgKey the cfg key
* @return the git config
*/
private static String getGitConfig(String cfgKey) {
s.append(Messages.getString("MossDebugUtils.MSG_FREE_SPACE")).append(root.getFreeSpace()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
s.append(Messages.getString("MossDebugUtils.MSG_USABLE_SPACE")).append(root.getUsableSpace()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
s.append("\r\n"); //$NON-NLS-1$
s.append(Messages.getString("MossDebugUtils.MSG_JAVA_PROPS")); //$NON-NLS-1$
for (String key : propertiesToGet) {
s.append(key).append(":").append(System.getProperty(key, "")).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return s.toString();
}
Properties properties = new Properties();
try {
properties.load(MossDebugUtils.class.getClassLoader()
.getResourceAsStream("git.properties")); //$NON-NLS-1$
} catch (IOException e) {
return Messages.getString("MossDebugUtils.MSG_IO_EXCEPTION"); //$NON-NLS-1$
}
return properties.getProperty(cfgKey);
/**
* Gets the git config.
*
* @param cfgKey the cfg key
* @return the git config
*/
private static String getGitConfig(String cfgKey) {
Properties properties = new Properties();
try {
properties.load(MossDebugUtils.class.getClassLoader()
.getResourceAsStream("git.properties")); //$NON-NLS-1$
} catch (IOException e) {
return Messages.getString("MossDebugUtils.MSG_IO_EXCEPTION"); //$NON-NLS-1$
}
return properties.getProperty(cfgKey);
}
}
}

View File

@ -1,16 +1,15 @@
package net.mosstest.servercore;
import com.google.common.collect.ImmutableList;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import com.google.common.collect.ImmutableList;
// TODO: Auto-generated Javadoc
/**
* The Class MossGame.
@ -42,22 +41,26 @@ public class MossGame {
}
this.scripts = new ArrayList<>();
String[] scNames = this.gameCfg.getStringArray("plugin"); //$NON-NLS-1$
for (String scName : scNames) {
try {
this.scripts.add(LocalFileManager.scriptsInstance
.getFile(scName + "/init.js")); //$NON-NLS-1$
} catch (FileNotFoundException e) {
throw new MossWorldLoadException(
Messages.getString("MossGame.FILE_NOT_FOUND") + scName); //$NON-NLS-1$
}
}
}
for (String scName : scNames)
try {
this.scripts.add(LocalFileManager.scriptsInstance
.getScriptInitFile(scName)); //$NON-NLS-1$
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new MossWorldLoadException(
Messages.getString("MossGame.FILE_NOT_FOUND") + scName); //$NON-NLS-1$
}
}
/** The base dir. */
private File baseDir;
/**
* The base dir.
*/
private File baseDir;
/** The game cfg. */
private XMLConfiguration gameCfg;
/**
* The game cfg.
*/
private XMLConfiguration gameCfg;
/** The cfg file. */
private File cfgFile;

View File

@ -1,57 +1,74 @@
package net.mosstest.servercore;
// TODO: Auto-generated Javadoc
import java.util.Arrays;
/**
* The Class MossNetPacket.
*/
public class MossNetPacket {
/** The command id. */
int commandId;
/** The payload. */
byte[] payload;
/** The needs fast. */
boolean needsFast;
/** The needs ack. */
boolean needsAck;
/** The is important. */
boolean isImportant;
/** The sess. */
ServerSession sess;
/**
* Constructs a packet, for either sending or from receiving.
* @param commandId The command ID
* @param payload The payload, as a byte array.
*/
public MossNetPacket(int commandId, byte[] payload) {
this.commandId = commandId;
this.payload = payload;
this.needsAck = true;
this.needsFast = false;
this.isImportant = true;
}
/**
* Instantiates a new moss net packet.
*
* @param commandId the command id
* @param payload the payload
* @param needsFast the needs fast
* @param needsAck the needs ack
* @param isImportant the is important
*/
public MossNetPacket(int commandId, byte[] payload, boolean needsFast,
boolean needsAck, boolean isImportant) {
this.commandId = commandId;
this.payload = payload;
this.needsFast = needsFast;
this.needsAck = needsAck;
this.isImportant = true;
}
/**
* The command id.
*/
int commandId;
/**
* The payload.
*/
byte[] payload;
/**
* The needs fast.
*/
boolean needsFast;
/**
* The needs ack.
*/
boolean needsAck;
/**
* The is important.
*/
boolean isImportant;
/**
* The sess.
*/
ServerSession sess;
/**
* Constructs a packet, for either sending or from receiving.
*
* @param commandId The command ID
* @param payload The payload, as a byte array.
*/
public MossNetPacket(int commandId, byte[] payload) {
this.commandId = commandId;
this.payload = Arrays.copyOf(payload, payload.length);
this.needsAck = true;
this.needsFast = false;
this.isImportant = true;
}
/**
* Instantiates a new moss net packet.
*
* @param commandId the command id
* @param payload the payload
* @param needsFast the needs fast
* @param needsAck the needs ack
* @param isImportant the is important
*/
public MossNetPacket(int commandId, byte[] payload, boolean needsFast,
boolean needsAck, boolean isImportant) {
this.commandId = commandId;
this.payload = payload;
this.needsFast = needsFast;
this.needsAck = needsAck;
this.isImportant = isImportant;
}
}

View File

@ -1,140 +1,141 @@
package net.mosstest.servercore;
import java.io.File;
import java.io.IOException;
import java.util.List;
import net.mosstest.scripting.MapGenerators;
import net.mosstest.scripting.MossScriptEnv;
import net.mosstest.scripting.ScriptableDatabase;
import net.mosstest.scripting.events.IMossEvent;
import net.mosstest.servercore.MosstestSecurityManager.ThreadContext;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
public class MossWorld {
static {
System.setSecurityManager(MosstestSecurityManager.instance);
}
static Logger logger = Logger.getLogger(MossWorld.class);
private MossGame game;
private File baseDir;
private XMLConfiguration worldCfg;
private File cfgFile;
private MapDatabase db;
private NodeCache nc;
private MossScriptEnv mossEnv;
private ScriptEnv sEnv;
private ScriptableDatabase sdb;
private EventProcessor evp;
@SuppressWarnings("unused")
private ServerNetworkingManager snv;
volatile boolean run = true;
private FuturesProcessor fp;
private INodeManager nm;
private IRenderPreparator rp;
private RenderProcessor rend;
/**
* Initializes a server world. This will start the server once the world is
* initialized, loaded, and passes basic consistency checks. This
* constructor will not initialize load-balancing.
*
* @param name
* A string that names the world.
* @param port
* The port number on which to run the server. If negative a
* singleplayer stack is created.
* @throws MossWorldLoadException
* Thrown if the world cannot be loaded, due to inconsistency,
* missing files, or lack of system resources.
* @throws MapDatabaseException
* @throws IOException
* @throws ConfigurationException
*/
@SuppressWarnings("nls")
public MossWorld(String name, int port) throws MossWorldLoadException,
MapDatabaseException, IOException, ConfigurationException {
//Thread.currentThread().setContextClassLoader(
// MosstestSecurityManager.instance.getScriptClassLoader(Thread
// .currentThread().getContextClassLoader()));
this.baseDir = new File("data/worlds/" + name); //$NON-NLS-1$
if (!this.baseDir.exists()) {
this.baseDir.mkdirs();
}
// Sets the security manager to trust attempts to open anything below
// data/scripts
MosstestSecurityManager.instance
.setTrustedBasedir(new File("scripts/"));
this.cfgFile = new File(this.baseDir, "world.xml"); //$NON-NLS-1$
if (!this.cfgFile.isFile())
this.cfgFile.createNewFile();
this.worldCfg = new XMLConfiguration(this.cfgFile);
if (!this.worldCfg.containsKey("gameid")) { //$NON-NLS-1$
throw new MossWorldLoadException(
Messages.getString("MossWorld.NO_GAME_ID")); //$NON-NLS-1$
}
this.game = new MossGame(this.worldCfg.getString("gameid")); //$NON-NLS-1$
try {
this.db = new MapDatabase(this.baseDir);
} catch (MapDatabaseException e) {
throw new MossWorldLoadException(
Messages.getString("MossWorld.ERR_DB")); //$NON-NLS-1$
}
this.nc = new NodeCache(this.db);
this.nm = new LocalNodeManager(this.db.nodes);
// this.db = new MapDatabase(this.baseDir);
try {
MapGenerators.setDefaultMapGenerator(
new MapGenerators.SimplexMapGenerator(), this.nm, 8448);
} catch (MapGeneratorException e) {
System.err.println(Messages
.getString("MossWorld.MG_SELECT_FAILURE")); //$NON-NLS-1$
System.exit(4);
}
this.sdb = new ScriptableDatabase(this.baseDir);
this.fp = new FuturesProcessor();
this.mossEnv = new MossScriptEnv(this.sdb, this.nc, this.fp, this.nm);
this.sEnv = new ScriptEnv(this.mossEnv);
List<IMossFile> scripts = this.game.getScripts();
for (IMossFile sc : scripts) {
this.sEnv.runScript(sc);
}
this.evp = new EventProcessor(this.mossEnv,
ThreadContext.CONTEXT_SCRIPT);
if (port >= 0) {
logger.error(Messages.getString("MossWorld.NO_NETWORKING_NOW")); //$NON-NLS-1$
/*
* try { this.snv = new ServerNetworkingManager(port, this); } catch
* (IOException e) { throw new MossWorldLoadException(
* "Failure in opening server socket for listening!"); }
*/
} // else {
/* */this.rp = new LocalRenderPreparator(this.rend, this.nc);
this.rp.setNodeManager(nm);
/* */this.rend = RenderProcessor.init(this.nm, this.rp);
// }
}
public void enqueueEvent(IMossEvent e) throws InterruptedException {
this.evp.eventQueue.put(e);
}
public static void main(String[] args) throws MossWorldLoadException,
MapDatabaseException, ConfigurationException, IOException {
MossWorld m = new MossWorld("test", -1); //$NON-NLS-1$
}
}
package net.mosstest.servercore;
import net.mosstest.scripting.MapGenerators;
import net.mosstest.scripting.MossScriptEnv;
import net.mosstest.scripting.ScriptableDatabase;
import net.mosstest.scripting.events.IMossEvent;
import net.mosstest.servercore.MosstestSecurityManager.ThreadContext;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class MossWorld {
static {
System.setSecurityManager(MosstestSecurityManager.instance);
}
static Logger logger = Logger.getLogger(MossWorld.class);
private MossGame game;
private File baseDir;
private XMLConfiguration worldCfg;
private File cfgFile;
private MapDatabase db;
private NodeCache nc;
private MossScriptEnv mossEnv;
private ScriptEnv sEnv;
private ScriptableDatabase sdb;
private EventProcessor evp;
@SuppressWarnings("unused")
private ServerNetworkingManager snv;
volatile boolean run = true;
private FuturesProcessor fp;
private INodeManager nm;
private IRenderPreparator rp;
private RenderProcessor rend;
private ItemManager im;
/**
* Initializes a server world. This will start the server once the world is
* initialized, loaded, and passes basic consistency checks. This
* constructor will not initialize load-balancing.
*
* @param name
* A string that names the world.
* @param port
* The port number on which to run the server. If negative a
* singleplayer stack is created.
* @throws MossWorldLoadException
* Thrown if the world cannot be loaded, due to inconsistency,
* missing files, or lack of system resources.
* @throws MapDatabaseException
* @throws IOException
* @throws ConfigurationException
*/
@SuppressWarnings("nls")
public MossWorld(String name, int port) throws MossWorldLoadException,
MapDatabaseException, IOException, ConfigurationException {
//Thread.currentThread().setContextClassLoader(
// MosstestSecurityManager.instance.getScriptClassLoader(Thread
// .currentThread().getContextClassLoader()));
this.baseDir = new File("data/worlds/" + name); //$NON-NLS-1$
if (!this.baseDir.exists()) {
this.baseDir.mkdirs();
}
// Sets the security manager to trust attempts to open anything below
// data/scripts
MosstestSecurityManager.instance
.setTrustedBasedir(new File("scripts/"));
this.cfgFile = new File(this.baseDir, "world.xml"); //$NON-NLS-1$
if (!this.cfgFile.isFile())
this.cfgFile.createNewFile();
this.worldCfg = new XMLConfiguration(this.cfgFile);
if (!this.worldCfg.containsKey("gameid")) { //$NON-NLS-1$
throw new MossWorldLoadException(
Messages.getString("MossWorld.NO_GAME_ID")); //$NON-NLS-1$
}
this.game = new MossGame(this.worldCfg.getString("gameid")); //$NON-NLS-1$
try {
this.db = new MapDatabase(this.baseDir);
} catch (MapDatabaseException e) {
throw new MossWorldLoadException(
Messages.getString("MossWorld.ERR_DB")); //$NON-NLS-1$
}
this.nc = new NodeCache(this.db);
this.im = new ItemManager();
this.nm = new LocalNodeManager(this.db.nodes, im);
// this.db = new MapDatabase(this.baseDir);
try {
MapGenerators.setDefaultMapGenerator(
new MapGenerators.SimplexMapGenerator(), this.nm, 8448);
} catch (MapGeneratorException e) {
System.err.println(Messages
.getString("MossWorld.MG_SELECT_FAILURE")); //$NON-NLS-1$
System.exit(4);
}
this.sdb = new ScriptableDatabase(this.baseDir);
this.fp = new FuturesProcessor();
this.mossEnv = new MossScriptEnv(this.sdb, this.nc, this.fp, this.nm);
this.sEnv = new ScriptEnv(this.mossEnv);
List<IMossFile> scripts = this.game.getScripts();
for (IMossFile sc : scripts) {
this.sEnv.runScript(sc);
}
this.evp = new EventProcessor(this.mossEnv,
ThreadContext.CONTEXT_SCRIPT);
if (port >= 0) {
logger.error(Messages.getString("MossWorld.NO_NETWORKING_NOW")); //$NON-NLS-1$
/*
* try { this.snv = new ServerNetworkingManager(port, this); } catch
* (IOException e) { throw new MossWorldLoadException(
* "Failure in opening server socket for listening!"); }
*/
} // else {
/* */this.rp = new LocalRenderPreparator(this.rend, this.nc);
this.rp.setNodeManager(nm);
/* */this.rend = RenderProcessor.init(this.nm, this.rp);
// }
}
public void enqueueEvent(IMossEvent e) throws InterruptedException {
this.evp.eventQueue.put(e);
}
public static void main(String[] args) throws MossWorldLoadException,
MapDatabaseException, ConfigurationException, IOException {
new MossWorld("test", -1); //$NON-NLS-1$
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
package net.mosstest.servercore;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.Position;
import java.lang.ref.SoftReference;
import java.util.HashMap;
// TODO: Auto-generated Javadoc
/**
@ -14,10 +14,12 @@ import net.mosstest.scripting.Position;
public class NodeCache {
/** The chunks. */
private HashMap<Position, SoftReference<MapChunk>> chunks = new HashMap<>();
/** The db. */
private MapDatabase db ;
private final HashMap<Position, SoftReference<MapChunk>> chunks = new HashMap<>();
/**
* The db.
*/
private MapDatabase db ;
/**
* Gets the chunk.
@ -29,11 +31,11 @@ public class NodeCache {
public MapChunk getChunk(Position pos) throws MapGeneratorException {
synchronized (this.chunks) {
synchronized (MapDatabase.class) {
MapChunk ourChunk = null;
SoftReference<MapChunk> ref = this.chunks.get(pos);
ourChunk = ref==null?null:ref.get();
if (ourChunk == null) {
ourChunk = this.db.getChunk(pos);
SoftReference<MapChunk> ref = this.chunks.get(pos);
MapChunk ourChunk = (ref == null) ? null : ref.get();
if (ourChunk == null) {
ourChunk = this.db.getChunk(pos);
this.chunks.put(pos, new SoftReference<>(ourChunk));
}
return ourChunk;

View File

@ -1,142 +1,152 @@
package net.mosstest.servercore;
import com.google.common.collect.HashBiMap;
import net.mosstest.scripting.MapNode;
import org.iq80.leveldb.DB;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.bytes;
import java.util.HashMap;
import java.util.Map.Entry;
import net.mosstest.scripting.MapNode;
import org.iq80.leveldb.DB;
import com.google.common.collect.HashBiMap;
// TODO: Auto-generated Javadoc
/**
* The Class NodeManager.
*/
public class NodeManager {
/** The defined nodes. */
private ArrayList<MapNode> definedNodes = new ArrayList<>();
/** The def node by name. */
private HashMap<String, MapNode> defNodeByName = new HashMap<>();
/** The pending. */
private HashBiMap<Short, String> pending = HashBiMap.create();
/** The node db. */
private DB nodeDb;
/** The Constant unknownFallbackNode. */
private static final MapNode unknownFallbackNode = new MapNode("unknown.png", "sys:unknown", Messages.getString("NodeManager.DESC_UNKNWN_NODE"), 1); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
static {
unknownFallbackNode.setNodeId((short) -1);
}
/* instance creation */{
this.definedNodes.add(this.unknownFallbackNode);
}
public static final int NODEDEF_MAX = 16384;
/**
* The defined nodes.
*/
private ArrayList<MapNode> definedNodes = new ArrayList<>();
/**
* Gets the node.
*
* @param nodeId the node id
* @return the node
*/
public MapNode getNode(short nodeId) {
return this.definedNodes.get(nodeId);
}
/**
* The def node by name.
*/
private HashMap<String, MapNode> defNodeByName = new HashMap<>();
/**
* Put node.
*
* @param node the node
* @return the short
* @throws MossWorldLoadException the moss world load exception
*/
public short putNode(MapNode node) throws MossWorldLoadException {
if (this.pending.containsValue(node.nodeName)) {
node.setNodeId(this.pending.inverse().get(node.nodeName));
this.definedNodes.set(this.pending.inverse().get(node.nodeName),
node);
this.defNodeByName.put(node.nodeName, node);
} else {
if (this.definedNodes.size() > 16384)
throw new MossWorldLoadException("Too many nodedefs"); //$NON-NLS-1$
/**
* The pending.
*/
private HashBiMap<Short, String> pending = HashBiMap.create();
node.setNodeId((short) this.definedNodes.size());
/**
* The node db.
*/
private DB nodeDb;
this.definedNodes.add(node);
this.defNodeByName.put(node.nodeName, node);
this.nodeDb.put(new byte[] { (byte) (node.getNodeId() >>> 8),
(byte) (node.getNodeId() & 0xFF) }, bytes(node.nodeName));
}
/**
* The Constant unknownFallbackNode.
*/
private static final MapNode unknownFallbackNode = new MapNode("unknown.png", "sys:unknown", Messages.getString("NodeManager.DESC_UNKNWN_NODE"), 1); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return node.getNodeId();
}
static {
unknownFallbackNode.setNodeId((short) -1);
}
/**
* Put node alias.
*
* @param alias the alias
* @param dst the dst
*/
public void putNodeAlias(String alias, String dst) {
MapNode dstNode = this.defNodeByName.get(dst);
this.defNodeByName.put(alias, dstNode);
}
/* instance creation */ {
this.definedNodes.add(this.unknownFallbackNode);
}
/**
* Gets the node.
*
* @param string the string
* @param isModified the is modified
* @return the node
*/
public MapNode getNode(String string, boolean isModified) {
MapNode r = this.defNodeByName.get(string);
return r==null?this.unknownFallbackNode:r;
}
/**
* Gets the node.
*
* @param nodeId the node id
* @return the node
*/
public MapNode getNode(short nodeId) {
return this.definedNodes.get(nodeId);
}
/**
* Gets the node.
*
* @param string the string
* @return the node
*/
public MapNode getNode(String string) {
/**
* Put node.
*
* @param node the node
* @return the short
* @throws MossWorldLoadException the moss world load exception
*/
public short putNode(MapNode node) throws MossWorldLoadException {
if (this.pending.containsValue(node.nodeName)) {
node.setNodeId(this.pending.inverse().get(node.nodeName));
this.definedNodes.set(this.pending.inverse().get(node.nodeName),
node);
this.defNodeByName.put(node.nodeName, node);
} else {
if (this.definedNodes.size() > NODEDEF_MAX)
throw new MossWorldLoadException("Too many nodedefs"); //$NON-NLS-1$
MapNode r = this.defNodeByName.get(string);
return r==null?this.unknownFallbackNode:r;
}
node.setNodeId((short) this.definedNodes.size());
/**
* Instantiates a new node manager.
*
* @param nodedb the nodedb
*/
public NodeManager(DB nodedb) {
this.nodeDb = nodedb;
for (Entry<byte[], byte[]> entry : nodedb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
this.definedNodes.add(node);
this.defNodeByName.put(node.nodeName, node);
this.nodeDb.put(new byte[]{(byte) (node.getNodeId() >>> 8),
(byte) (node.getNodeId() & 0xFF)}, bytes(node.nodeName));
}
/**
* Gets the unknown fallback node.
*
* @return the unknown fallback node
*/
public static MapNode getUnknownFallbackNode() {
return unknownFallbackNode;
}
return node.getNodeId();
}
/**
* Put node alias.
*
* @param alias the alias
* @param dst the dst
*/
public void putNodeAlias(String alias, String dst) {
MapNode dstNode = this.defNodeByName.get(dst);
this.defNodeByName.put(alias, dstNode);
}
/**
* Gets the node.
*
* @param string the string
* @param isModified the is modified
* @return the node
*/
public MapNode getNode(String string, boolean isModified) {
MapNode r = this.defNodeByName.get(string);
return r == null ? this.unknownFallbackNode : r;
}
/**
* Gets the node.
*
* @param string the string
* @return the node
*/
public MapNode getNode(String string) {
MapNode r = this.defNodeByName.get(string);
return r == null ? this.unknownFallbackNode : r;
}
/**
* Instantiates a new node manager.
*
* @param nodedb the nodedb
*/
public NodeManager(DB nodedb) {
this.nodeDb = nodedb;
for (Entry<byte[], byte[]> entry : nodedb) {
short parsedId = (short) (entry.getKey()[0] * 256 + entry.getKey()[1]);
String parsedString = asString(entry.getValue());
this.pending.put(parsedId, parsedString);
}
}
/**
* Gets the unknown fallback node.
*
* @return the unknown fallback node
*/
public static MapNode getUnknownFallbackNode() {
return unknownFallbackNode;
}
}

View File

@ -1,14 +1,5 @@
package net.mosstest.servercore;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import jme3tools.optimize.GeometryBatchFactory;
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
@ -20,27 +11,24 @@ import com.jme3.light.DirectionalLight;
import com.jme3.light.PointLight;
import com.jme3.light.SpotLight;
import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Matrix3f;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.math.*;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.system.AppSettings;
import com.jme3.math.ColorRGBA;
import java.util.Arrays;
import org.apache.log4j.Logger;
import net.mosstest.scripting.INodeParams;
import jme3tools.optimize.GeometryBatchFactory;
import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.MapNode;
import net.mosstest.scripting.Player;
import net.mosstest.scripting.Position;
import org.apache.log4j.Logger;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
public class RenderProcessor extends SimpleApplication {
@ -136,15 +124,15 @@ public class RenderProcessor extends SimpleApplication {
GeometryBatchFactory.optimize(worldNode);
}
}
public void getChunk (Position pos) {
MapChunk maybe = null;
public void getChunk (Position pos) {
MapChunk maybe = null;
try {maybe = rPreparator.requestChunk(pos);}
catch (MapGeneratorException e) {e.printStackTrace();}
catch (InterruptedException e) {e.printStackTrace();}
if (maybe != null) {renderChunk(maybe, pos);}
}
public void renderChunk(MapChunk chk, Position pos) {
int vertexIndexCounter = 0;
@ -162,7 +150,7 @@ public class RenderProcessor extends SimpleApplication {
//MapNode node = nManager.getNode((short) nVal);
//Material mat = getMaterial((short) nVal);
if (nVal == 0) {/*System.out.println("GOT A 0");*/}
else {
float x = (float) ((pos.x + (CHUNK_SIZE * pos.x)) - BLOCK_OFFSET_FROM_CENTER + CHUNK_OFFSET + (i * BLOCK_SIZE));
float z = (float) ((pos.y - PLAYER_HEIGHT) - (j * BLOCK_SIZE));
@ -224,11 +212,11 @@ public class RenderProcessor extends SimpleApplication {
getChunk(p1);
getChunk(p2);
getChunk(p3);
getChunk(p3);
getChunk(p4);
getChunk(p5);
getChunk(p6);
getChunk(p7);
getChunk(p7);
}
private FloatBuffer getDirectFloatBuffer (int size) {
@ -461,5 +449,5 @@ public class RenderProcessor extends SimpleApplication {
System.err.println("\nDEBUGGING FEATURE\n");
}
}
};
}
};
}

View File

@ -1,105 +0,0 @@
package net.mosstest.servercore;
import java.util.ArrayList;
// TODO: Auto-generated Javadoc
/**
* The Enum ToClientNetCommand.
*/
public enum ToClientNetCommand {
/** The toclient nop. */
TOCLIENT_NOP(0x00),
/** The toclient auth requested. */
TOCLIENT_AUTH_REQUESTED,
/** The toclient auth accepted. */
TOCLIENT_AUTH_ACCEPTED,
/** The toclient auth denied. */
TOCLIENT_AUTH_DENIED,
/** The toclient bulk tranfer. */
TOCLIENT_BULK_TRANFER,
/** The toclient mapblock. */
TOCLIENT_MAPBLOCK,
/** The toclient inv. */
TOCLIENT_INV,
/** The toclient bulk tranfer params. */
TOCLIENT_BULK_TRANFER_PARAMS,
/** The toclient player mapping. */
TOCLIENT_PLAYER_MAPPING,
/** The toclient entity. */
TOCLIENT_ENTITY,
/** The toclient teleport entity. */
TOCLIENT_TELEPORT_ENTITY,
/** The toclient move entity delta. */
TOCLIENT_MOVE_ENTITY_DELTA,
/** The toclient animate mesh. */
TOCLIENT_ANIMATE_MESH,
/** The toclient node def. */
TOCLIENT_NODE_DEF,
/** The toclient place node. */
TOCLIENT_PLACE_NODE,
/** The toclient remove node. */
TOCLIENT_REMOVE_NODE,
/** The toclient slide node. */
TOCLIENT_SLIDE_NODE,
/** The toclient formspec. */
TOCLIENT_FORMSPEC,
/** The toclient formspec instance. */
TOCLIENT_FORMSPEC_INSTANCE,
/** The TOCLIEN t_ pl aye r_ event. */
TOCLIENT_PlAYER_EVENT,
/** The toclient entity follow nodepath. */
TOCLIENT_ENTITY_FOLLOW_NODEPATH;
/** The command. */
int command;
/** The commands. */
static ArrayList<ToClientNetCommand> commands=new ArrayList<>();
/**
* Instantiates a new to client net command.
*
* @param cmd the cmd
*/
ToClientNetCommand(int cmd){
this.command=cmd;
add(this);
}
/**
* Instantiates a new to client net command.
*/
ToClientNetCommand(){
this.command=0xFF;
}
/**
* Adds the.
*
* @param tcnc the tcnc
*/
private static void add(ToClientNetCommand tcnc){
ToClientNetCommand.commands.add(tcnc.command, tcnc);
}
}

View File

@ -0,0 +1,68 @@
package net.mosstest.tests;
import net.mosstest.scripting.DefaultNodeParams;
import net.mosstest.scripting.MapNode;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MossWorldLoadException;
// TODO: Auto-generated Javadoc
/**
* The Class MockNodeManager.
*/
public class MockNodeManager implements INodeManager {
/**
* The Constant MOCK_SOLID_MAPNODE.
*/
private static final MapNode MOCK_SOLID_MAPNODE = new MapNode(
new DefaultNodeParams(), "mock", "!mock:mock", "Mock node", 1);
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(short)
*/
@Override
public MapNode getNode(short nodeId) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNode(net.mosstest.scripting.MapNode)
*/
@Override
public short putNode(MapNode node) throws MossWorldLoadException {
// TODO Auto-generated method stub
return 1337;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNodeAlias(java.lang.String, java.lang.String)
*/
@Override
public void putNodeAlias(String alias, String dst) {
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String, boolean)
*/
@Override
public MapNode getNode(String string, boolean isModified) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String)
*/
@Override
public MapNode getNode(String string) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#init()
*/
@Override
public void init() {
}
}

View File

@ -1,66 +0,0 @@
package net.mosstest.tests;
import net.mosstest.scripting.AirNodeParams;
import net.mosstest.scripting.DefaultNodeParams;
import net.mosstest.scripting.MapNode;
import net.mosstest.servercore.INodeManager;
import net.mosstest.servercore.MossWorldLoadException;
// TODO: Auto-generated Javadoc
/**
* The Class MockNodeManager.
*/
public class MockNodeManager implements INodeManager {
/** The Constant MOCK_SOLID_MAPNODE. */
private static final MapNode MOCK_SOLID_MAPNODE = new MapNode(
new DefaultNodeParams(), "mock", "!mock:mock", "Mock node", 1);
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(short)
*/
@Override
public MapNode getNode(short nodeId) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNode(net.mosstest.scripting.MapNode)
*/
@Override
public short putNode(MapNode node) throws MossWorldLoadException {
// TODO Auto-generated method stub
return 1337;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#putNodeAlias(java.lang.String, java.lang.String)
*/
@Override
public void putNodeAlias(String alias, String dst) {
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String, boolean)
*/
@Override
public MapNode getNode(String string, boolean isModified) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#getNode(java.lang.String)
*/
@Override
public MapNode getNode(String string) {
return MOCK_SOLID_MAPNODE;
}
/* (non-Javadoc)
* @see net.mosstest.servercore.INodeManager#init()
*/
@Override
public void init() {
}
}

View File

@ -1,149 +1,148 @@
package net.mosstest.tests;
import static org.junit.Assert.*;
import java.io.IOException;
import net.mosstest.scripting.NodePosition;
import org.junit.Assert;
import org.junit.Test;
public class NodePositionTest {
public static final int[] coords = { 0, 1, -1, 16, -16, 67, -66, 269, -267,
65601, -65601, Integer.MAX_VALUE, Integer.MIN_VALUE };
@Test
public void testHashCode() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < 16; x+=2) {
for (byte y = 0; y < 16; y+=2) {
for (byte z = 0; z < 16; z+=2) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertEquals(
"Mismatched hashCodes for value-identical NodePosition objects",
pos1.hashCode(), pos2.hashCode());
}
}
}
}
}
}
}
@Test
public void testByteArrayReadWrite() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < 16; x++) {
for (byte y = 0; y < 16; y++) {
for (byte z = 0; z < 16; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
byte[] bytes = pos1.toBytes();
NodePosition pos2;
try {
pos2 = new NodePosition(bytes);
Assert.assertTrue(
"NodePosition nmarshaled from byte[] fails equals() check with original NodePosition.",
pos1.equals(pos2));
} catch (IOException e) {
fail("IOException caught in unmarshaling NodePosition from byte[]");
}
}
}
}
}
}
}
}
@Test
public void testEqualsObject() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < 16; x++) {
for (byte y = 0; y < 16; y++) {
for (byte z = 0; z < 16; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos1.equals(pos2));
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos2.equals(pos1));
NodePosition pos3 = new NodePosition(
coords[i] + 1, coords[j], coords[k], 0,
x, y, z);
NodePosition pos4 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos3.equals(pos4));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos4.equals(pos3));
NodePosition pos5 = new NodePosition(coords[i],
coords[j] + 1, coords[k], 0, x, y, z);
NodePosition pos6 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos5.equals(pos6));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos6.equals(pos5));
NodePosition pos7 = new NodePosition(coords[i],
coords[j], coords[k] + 1, 0, x, y, z);
NodePosition pos8 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos7.equals(pos8));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos8.equals(pos7));
}
}
}
}
}
}
}
@Test
public void testToBytes() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < 16; x++) {
for (byte y = 0; y < 16; y++) {
for (byte z = 0; z < 16; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
org.junit.Assert.assertArrayEquals(
pos1.toBytes(), pos2.toBytes());
}
}
}
}
}
}
}
}
package net.mosstest.tests;
import net.mosstest.scripting.NodePosition;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.fail;
public class NodePositionTest {
public static final int CHUNK_DIMENSION = 16;
public static final int[] coords = {0, 1, -1, 16, -16, 67, -66, 269, -267,
65601, -65601, Integer.MAX_VALUE, Integer.MIN_VALUE};
@Test
public void testHashCode() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x += 2) {
for (byte y = 0; y < CHUNK_DIMENSION; y += 2) {
for (byte z = 0; z < CHUNK_DIMENSION; z += 2) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertEquals(
"Mismatched hashCodes for value-identical NodePosition objects",
pos1.hashCode(), pos2.hashCode());
}
}
}
}
}
}
}
@Test
public void testByteArrayReadWrite() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; i < coords.length; i++) {
for (int k = 0; i < coords.length; i++) {
for (byte x = 0; x < CHUNK_DIMENSION; x++) {
for (byte y = 0; y < CHUNK_DIMENSION; y++) {
for (byte z = 0; z < CHUNK_DIMENSION; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
byte[] bytes = pos1.toBytes();
NodePosition pos2;
try {
pos2 = new NodePosition(bytes);
Assert.assertTrue(
"NodePosition nmarshaled from byte[] fails equals() check with original NodePosition.",
pos1.equals(pos2));
} catch (IOException e) {
fail("IOException caught in unmarshaling NodePosition from byte[]");
}
}
}
}
}
}
}
}
@Test
public void testEqualsObject() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x++) {
for (byte y = 0; y < CHUNK_DIMENSION; y++) {
for (byte z = 0; z < CHUNK_DIMENSION; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos1.equals(pos2));
Assert.assertTrue(
"Value-equal objects fail equals() check",
pos2.equals(pos1));
NodePosition pos3 = new NodePosition(
coords[i] + 1, coords[j], coords[k], 0,
x, y, z);
NodePosition pos4 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos3.equals(pos4));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for x",
pos4.equals(pos3));
NodePosition pos5 = new NodePosition(coords[i],
coords[j] + 1, coords[k], 0, x, y, z);
NodePosition pos6 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos5.equals(pos6));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for y",
pos6.equals(pos5));
NodePosition pos7 = new NodePosition(coords[i],
coords[j], coords[k] + 1, 0, x, y, z);
NodePosition pos8 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos7.equals(pos8));
Assert.assertFalse(
"Value-unequal objects erroneously pass equals() check for z",
pos8.equals(pos7));
}
}
}
}
}
}
}
@Test
public void testToBytes() {
for (int i = 0; i < coords.length; i++) {
for (int j = 0; j < coords.length; j++) {
for (int k = 0; k < coords.length; k++) {
for (byte x = 0; x < CHUNK_DIMENSION; x++) {
for (byte y = 0; y < CHUNK_DIMENSION; y++) {
for (byte z = 0; z < CHUNK_DIMENSION; z++) {
NodePosition pos1 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
NodePosition pos2 = new NodePosition(coords[i],
coords[j], coords[k], 0, x, y, z);
org.junit.Assert.assertArrayEquals(
pos1.toBytes(), pos2.toBytes());
}
}
}
}
}
}
}
}