Merge remote-tracking branch 'origin' into fix1renderer

Conflicts:
	src/net/mosstest/servercore/RenderProcessor.java
master
Aaron Chan 2013-11-01 18:30:06 -04:00
commit a589734645
120 changed files with 7752 additions and 7734 deletions

46
.gitignore vendored
View File

@ -1,24 +1,24 @@
*.class *.class
*.jar *.jar
*.war *.war
*.ear *.ear
/bin /bin
/lib /lib
*.db *.db
.svn .svn
.svn .svn
.project .project
/nbproject/private/ /nbproject/private/
/dist/ /dist/
/build/ /build/
/testDBs /testDBs
/.settings /.settings
/doc /doc
*.dll *.dll
*.exe *.exe
*.so *.so
COMMIT_EDITMSG COMMIT_EDITMSG
.DS_Store .DS_Store
/target /target
/build/output /build/output
/data/worlds /data/worlds

View File

@ -1,33 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>MossTest</name> <name>MossTest</name>
<comment></comment> <comment></comment>
<projects> <projects>
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name> <name>org.eclipse.jdt.core.javabuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>com.stateofflow.eclipse.metrics.MetricsBuilder</name> <name>com.stateofflow.eclipse.metrics.MetricsBuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>fr.obeo.dsl.viewpoint.nature.modelingproject</nature> <nature>fr.obeo.dsl.viewpoint.nature.modelingproject</nature>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>com.stateofflow.eclipse.metrics.MetricsNature</nature> <nature>com.stateofflow.eclipse.metrics.MetricsNature</nature>
</natures> </natures>
<linkedResources> <linkedResources>
</linkedResources> </linkedResources>
</projectDescription> </projectDescription>

View File

@ -1,22 +1,22 @@
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.core.codeComplete.argumentPrefixes= org.eclipse.jdt.core.codeComplete.argumentPrefixes=
org.eclipse.jdt.core.codeComplete.argumentSuffixes= org.eclipse.jdt.core.codeComplete.argumentSuffixes=
org.eclipse.jdt.core.codeComplete.fieldPrefixes= org.eclipse.jdt.core.codeComplete.fieldPrefixes=
org.eclipse.jdt.core.codeComplete.fieldSuffixes= org.eclipse.jdt.core.codeComplete.fieldSuffixes=
org.eclipse.jdt.core.codeComplete.localPrefixes= org.eclipse.jdt.core.codeComplete.localPrefixes=
org.eclipse.jdt.core.codeComplete.localSuffixes= org.eclipse.jdt.core.codeComplete.localSuffixes=
org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= org.eclipse.jdt.core.codeComplete.staticFieldPrefixes=
org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= org.eclipse.jdt.core.codeComplete.staticFieldSuffixes=
org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes=
org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes=
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7 org.eclipse.jdt.core.compiler.source=1.7

View File

@ -1,6 +1,6 @@
cleanup_settings_version=2 cleanup_settings_version=2
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.ui.exception.name=e org.eclipse.jdt.ui.exception.name=e
org.eclipse.jdt.ui.gettersetter.use.is=true org.eclipse.jdt.ui.gettersetter.use.is=true
org.eclipse.jdt.ui.keywordthis=false org.eclipse.jdt.ui.keywordthis=false
org.eclipse.jdt.ui.overrideannotation=true org.eclipse.jdt.ui.overrideannotation=true

1346
COPYING

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
mosstest mosstest
======== ========
Open-source Minetest clone. Refer to wiki for details. Open-source Minetest clone. Refer to wiki for details.
Pull requesters: Pull requesters:
Don't touch the thread pool or the scripting interface. Don't touch the thread pool or the scripting interface.
Electrocution, drowning, or security bots attacking you may occur. Electrocution, drowning, or security bots attacking you may occur.
pom.xml refers to non-maven jars in a custom jMonkey reporitory. Please hold as our server will have that repository available for download soon. pom.xml refers to non-maven jars in a custom jMonkey reporitory. Please hold as our server will have that repository available for download soon.

View File

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="javadoc"> <project default="javadoc">
<target name="javadoc"> <target name="javadoc">
<javadoc access="private" author="true" classpath="C:\Program Files\jmonkeyplatform\jmonkeyplatform\libs\lwjgl.jar;../lib/commons-cli-1.2.jar;../lib/jts-1.13.jar;../lib/leveldbjni-all-1.7.jar;../lib/js-14.jar;../lib/commons-collections4-4.0-alpha1.jar" destdir="../doc" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" source="1.7" sourcefiles="../src/org/nodetest/scripting/MossScriptEnv.java" sourcepath="../assets;../src" splitindex="true" use="true" version="true"> <javadoc access="private" author="true" classpath="C:\Program Files\jmonkeyplatform\jmonkeyplatform\libs\lwjgl.jar;../lib/commons-cli-1.2.jar;../lib/jts-1.13.jar;../lib/leveldbjni-all-1.7.jar;../lib/js-14.jar;../lib/commons-collections4-4.0-alpha1.jar" destdir="../doc" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" source="1.7" sourcefiles="../src/org/nodetest/scripting/MossScriptEnv.java" sourcepath="../assets;../src" splitindex="true" use="true" version="true">
<link href="http://download.oracle.com/javase/7/docs/api/"/> <link href="http://download.oracle.com/javase/7/docs/api/"/>
</javadoc> </javadoc>
</target> </target>
</project> </project>

View File

@ -1,18 +1,18 @@
Assignments: Assignments:
===ACh=== ===ACh===
Renderer Renderer
Formspecs Formspecs
Inventory Inventory
===MR=== ===MR===
JS scipts JS scipts
===AA=== ===AA===
Script API Script API
Event Processor Thread Pool Event Processor Thread Pool
Node cache Node cache
File cache File cache
Mapgen Mapgen
DB DB
Mapchunk handling Mapchunk handling

286
build.xml
View File

@ -1,143 +1,143 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file. <!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten. Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?> directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build" name="MossTest"> as the first entry and export the buildfile again. --><project basedir="." default="build" name="MossTest">
<property environment="env"/> <property environment="env"/>
<property name="ECLIPSE_HOME" value="../../../../Program Files/eclipse/eclipse"/> <property name="ECLIPSE_HOME" value="../../../../Program Files/eclipse/eclipse"/>
<property name="debuglevel" value="source,lines,vars"/> <property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.7"/> <property name="target" value="1.7"/>
<property name="source" value="1.7"/> <property name="source" value="1.7"/>
<path id="MossTest.classpath"> <path id="MossTest.classpath">
<pathelement location="bin"/> <pathelement location="bin"/>
<pathelement location="lib/leveldbjni-all-1.7.jar"/> <pathelement location="lib/leveldbjni-all-1.7.jar"/>
<pathelement location="lib/jts-1.13.jar"/> <pathelement location="lib/jts-1.13.jar"/>
<pathelement location="lib/lwjgl.jar"/> <pathelement location="lib/lwjgl.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-blender.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-blender.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-core.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-core.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-desktop.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-desktop.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-lwjgl-natives.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-lwjgl-natives.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/lwjgl.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/lwjgl.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/eventbus.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/eventbus.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jbullet.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jbullet.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jinput.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jinput.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-android.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-android.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet-natives.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet-natives.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet-natives-android.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-bullet-natives-android.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-effects.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-effects.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-jbullet.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-jbullet.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-jogg.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-jogg.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-lwjgl.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-lwjgl.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-networking.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-networking.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-niftygui.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-niftygui.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-plugins.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-plugins.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-terrain.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-terrain.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-testdata.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/jME3-testdata.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/j-ogg-oggd.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/j-ogg-oggd.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/j-ogg-vorbisd.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/j-ogg-vorbisd.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/launch4j.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/launch4j.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-default-controls.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-default-controls.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-default-controls-javadoc.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-default-controls-javadoc.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-javadoc.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-javadoc.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-style-black.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/nifty-style-black.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/retrace.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/retrace.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/stack-alloc.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/stack-alloc.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/vecmath.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/vecmath.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/xmlpull-xpp3.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/xmlpull-xpp3.jar"/>
<pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/xstream.jar"/> <pathelement location="../../../../Program Files/jmonkeyplatform/jmonkeyplatform/libs/xstream.jar"/>
<pathelement location="lib/commons-cli-1.2.jar"/> <pathelement location="lib/commons-cli-1.2.jar"/>
<pathelement location="lib/js.jar"/> <pathelement location="lib/js.jar"/>
<pathelement location="lib/commons-configuration-1.9.jar"/> <pathelement location="lib/commons-configuration-1.9.jar"/>
<pathelement location="lib/commons-lang3-3.1.jar"/> <pathelement location="lib/commons-lang3-3.1.jar"/>
<pathelement location="lib/commons-lang-2.6.jar"/> <pathelement location="lib/commons-lang-2.6.jar"/>
</path> </path>
<target name="init"> <target name="init">
<mkdir dir="bin"/> <mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin"> <copy includeemptydirs="false" todir="bin">
<fileset dir="src"> <fileset dir="src">
<exclude name="**/*.java"/> <exclude name="**/*.java"/>
</fileset> </fileset>
</copy> </copy>
<copy includeemptydirs="false" todir="bin"> <copy includeemptydirs="false" todir="bin">
<fileset dir="assets"> <fileset dir="assets">
<exclude name="**/*.java"/> <exclude name="**/*.java"/>
</fileset> </fileset>
</copy> </copy>
</target> </target>
<target name="clean"> <target name="clean">
<delete dir="bin"/> <delete dir="bin"/>
</target> </target>
<target depends="clean" name="cleanall"/> <target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/> <target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/> <target name="build-subprojects"/>
<target depends="init" name="build-project"> <target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/> <echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}"> <javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/> <src path="src"/>
<src path="assets"/> <src path="assets"/>
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</javac> </javac>
</target> </target>
<target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/> <target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/>
<target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler"> <target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
<copy todir="${ant.library.dir}"> <copy todir="${ant.library.dir}">
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/> <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</copy> </copy>
<unzip dest="${ant.library.dir}"> <unzip dest="${ant.library.dir}">
<patternset includes="jdtCompilerAdapter.jar"/> <patternset includes="jdtCompilerAdapter.jar"/>
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/> <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</unzip> </unzip>
</target> </target>
<target description="compile project with Eclipse compiler" name="build-eclipse-compiler"> <target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/> <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<antcall target="build"/> <antcall target="build"/>
</target> </target>
<target name="LevelDB"> <target name="LevelDB">
<java classname="org.nodetest.testing.LevelDB" failonerror="true" fork="yes"> <java classname="org.nodetest.testing.LevelDB" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="MapDatabase"> <target name="MapDatabase">
<java classname="org.nodetest.servercore.EventProcessor" failonerror="true" fork="yes"> <java classname="org.nodetest.servercore.EventProcessor" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="MapGenerator"> <target name="MapGenerator">
<java classname="org.nodetest.servercore.MapGenerator" failonerror="true" fork="yes"> <java classname="org.nodetest.servercore.MapGenerator" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="MosstestTesting"> <target name="MosstestTesting">
<java classname="org.nodetest.testing.VoronoiTesting" failonerror="true" fork="yes"> <java classname="org.nodetest.testing.VoronoiTesting" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="RenderProcessor (1)"> <target name="RenderProcessor (1)">
<java classname="net.mosstest.servercore.RenderProcessor" failonerror="true" fork="yes"> <java classname="net.mosstest.servercore.RenderProcessor" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="RenderProcessor"> <target name="RenderProcessor">
<java classname="org.nodetest.servercore.RenderProcessor" failonerror="true" fork="yes"> <java classname="org.nodetest.servercore.RenderProcessor" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="ScriptEnv (1)"> <target name="ScriptEnv (1)">
<java classname="net.mosstest.servercore.ScriptEnv" failonerror="true" fork="yes"> <java classname="net.mosstest.servercore.ScriptEnv" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="ScriptEnv"> <target name="ScriptEnv">
<java classname="org.nodetest.common.ScriptEnv" failonerror="true" fork="yes"> <java classname="org.nodetest.common.ScriptEnv" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
<target name="VoronoiUtils"> <target name="VoronoiUtils">
<java classname="org.nodetest.utilities.VoronoiUtils" failonerror="true" fork="yes"> <java classname="org.nodetest.utilities.VoronoiUtils" failonerror="true" fork="yes">
<classpath refid="MossTest.classpath"/> <classpath refid="MossTest.classpath"/>
</java> </java>
</target> </target>
</project> </project>

View File

@ -1,58 +1,58 @@
#Mosstest default settings. Categories are [server] and [client]. Names not case-sensitive. #Mosstest default settings. Categories are [server] and [client]. Names not case-sensitive.
[server-global] [server-global]
#Sets server name #Sets server name
serverId=New Mosstest Server serverId=New Mosstest Server
#Sets server failover cluster. Blank for no failover. NOT IMPLEMENTED YET. #Sets server failover cluster. Blank for no failover. NOT IMPLEMENTED YET.
failoverCluster= failoverCluster=
#Sets in-cluster identifier. 0 for no cluster support. NOT IMPLEMENTED YET. #Sets in-cluster identifier. 0 for no cluster support. NOT IMPLEMENTED YET.
replicationId replicationId
#port number #port number
port=16511 port=16511
#UDP support. Set to 0 to disable UDP. #UDP support. Set to 0 to disable UDP.
udpport=16511 udpport=16511
#Maximum number of players #Maximum number of players
maxplayers=256 maxplayers=256
#Maximum number of half-open connections #Maximum number of half-open connections
maxhalfopen=16 maxhalfopen=16
#Max upstream bandwidth #Max upstream bandwidth
maxupxmit=16K maxupxmit=16K
#maximum downstream bandwidth #maximum downstream bandwidth
maxdownstream=64K maxdownstream=64K
#Enable rollback #Enable rollback
rollback=false rollback=false
#Enable smartban #Enable smartban
smartban=true smartban=true
#Performance settings #Performance settings
#Maximum chunks loaded. Remember that a chunk is roughly 16KiB. The setting 16394 equates to just under 300MB of RAM. #Maximum chunks loaded. Remember that a chunk is roughly 16KiB. The setting 16394 equates to just under 300MB of RAM.
maxLoadedChunks=16384 maxLoadedChunks=16384
#Maximum number of events queued for processing. Beyond this events will be dropped. #Maximum number of events queued for processing. Beyond this events will be dropped.
eventQueueCapacity=40 eventQueueCapacity=40
#number of event processor threads at start #number of event processor threads at start
initialEventThreads=8 initialEventThreads=8
#maximum number of event threads #maximum number of event threads
maxEventThreads=8 maxEventThreads=8
#How often the event system is checked for load, in milliseconds. #How often the event system is checked for load, in milliseconds.
eventQueueTuneSampleInterval=100 eventQueueTuneSampleInterval=100
#How many event queue checks are in one round #How many event queue checks are in one round
eventQueueTuneSamples=100 eventQueueTuneSamples=100
#for how many samples the queue must be busy for a new thread to start #for how many samples the queue must be busy for a new thread to start
eventQueueTuneUpshift=90 eventQueueTuneUpshift=90
#How many idle samples are needed before a thread is shut down #How many idle samples are needed before a thread is shut down
eventQueueTuneDownshift=10 eventQueueTuneDownshift=10
#Central authentication server, for user trust. Connection to this server is NOT needed for gameplay, and this field may be blank. #Central authentication server, for user trust. Connection to this server is NOT needed for gameplay, and this field may be blank.
authserver=auth.mosstest.net authserver=auth.mosstest.net
#Easter eggs #Easter eggs
enableEasterEggs=true enableEasterEggs=true
#How hard the server insists ITS textures are used over the client's. #How hard the server insists ITS textures are used over the client's.
texPackInsistence=0 texPackInsistence=0

2
lib/.gitignore vendored
View File

@ -1 +1 @@
/com /com

View File

@ -1,3 +1,3 @@
Manifest-Version: 1.0 Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build X-COMMENT: Main-Class will be added automatically by build

File diff suppressed because it is too large Load Diff

View File

@ -1 +1 @@
main.class=org.nodetest.servercore.EventProcessor main.class=org.nodetest.servercore.EventProcessor

View File

@ -1 +1 @@
main.class=org.nodetest.common.ScriptEnv main.class=org.nodetest.common.ScriptEnv

View File

@ -1,8 +1,8 @@
build.xml.data.CRC32=23062b59 build.xml.data.CRC32=23062b59
build.xml.script.CRC32=9ea92df2 build.xml.script.CRC32=9ea92df2
build.xml.stylesheet.CRC32=28e38971@1.53.1.46 build.xml.stylesheet.CRC32=28e38971@1.53.1.46
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=23062b59 nbproject/build-impl.xml.data.CRC32=23062b59
nbproject/build-impl.xml.script.CRC32=3b7463a5 nbproject/build-impl.xml.script.CRC32=3b7463a5
nbproject/build-impl.xml.stylesheet.CRC32=6ddba6b6@1.53.1.46 nbproject/build-impl.xml.stylesheet.CRC32=6ddba6b6@1.53.1.46

View File

@ -1,83 +1,83 @@
annotation.processing.enabled=true annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false annotation.processing.enabled.in.editor=false
annotation.processing.processor.options= annotation.processing.processor.options=
annotation.processing.processors.list= annotation.processing.processors.list=
annotation.processing.run.all.processors=true annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
auxiliary.org-netbeans-modules-projectimport-eclipse-core.key=src=src;file=lib/commons-cli-1.2.jar;file=lib/js-14.jar;file=lib/commons-cli-1.2-sources.jar;file=lib/db4o-8.0.249.16098-all-java5.jar;output=bin; auxiliary.org-netbeans-modules-projectimport-eclipse-core.key=src=src;file=lib/commons-cli-1.2.jar;file=lib/js-14.jar;file=lib/commons-cli-1.2-sources.jar;file=lib/db4o-8.0.249.16098-all-java5.jar;output=bin;
auxiliary.org-netbeans-modules-projectimport-eclipse-core.project=. auxiliary.org-netbeans-modules-projectimport-eclipse-core.project=.
auxiliary.org-netbeans-modules-projectimport-eclipse-core.timestamp=1370875172897 auxiliary.org-netbeans-modules-projectimport-eclipse-core.timestamp=1370875172897
auxiliary.org-netbeans-modules-projectimport-eclipse-core.workspace=C:\\Users\\Alexander\\workspace auxiliary.org-netbeans-modules-projectimport-eclipse-core.workspace=C:\\Users\\Alexander\\workspace
build.classes.dir=${build.dir}/classes build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned: # This directory is removed when the project is cleaned:
build.dir=build build.dir=build
build.generated.dir=${build.dir}/generated build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here: # Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport: # Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket #debug.transport=dt_socket
debug.classpath=\ debug.classpath=\
${run.classpath} ${run.classpath}
debug.test.classpath=\ debug.test.classpath=\
${run.test.classpath} ${run.test.classpath}
# This directory is removed when the project is cleaned: # This directory is removed when the project is cleaned:
dist.dir=dist dist.dir=dist
dist.jar=${dist.dir}/MossTest.jar dist.jar=${dist.dir}/MossTest.jar
dist.javadoc.dir=${dist.dir}/javadoc dist.javadoc.dir=${dist.dir}/javadoc
excludes= excludes=
file.reference.commons-cli-1.2-sources.jar=lib/commons-cli-1.2-sources.jar file.reference.commons-cli-1.2-sources.jar=lib/commons-cli-1.2-sources.jar
file.reference.commons-cli-1.2.jar=lib/commons-cli-1.2.jar file.reference.commons-cli-1.2.jar=lib/commons-cli-1.2.jar
file.reference.db4o-8.0.249.16098-all-java5.jar=lib/db4o-8.0.249.16098-all-java5.jar file.reference.db4o-8.0.249.16098-all-java5.jar=lib/db4o-8.0.249.16098-all-java5.jar
file.reference.js-14.jar=lib/js-14.jar file.reference.js-14.jar=lib/js-14.jar
file.reference.mosstest-src=src file.reference.mosstest-src=src
includes=** includes=**
jar.compress=false jar.compress=false
javac.classpath=\ javac.classpath=\
${file.reference.commons-cli-1.2.jar}:\ ${file.reference.commons-cli-1.2.jar}:\
${file.reference.js-14.jar}:\ ${file.reference.js-14.jar}:\
${file.reference.commons-cli-1.2-sources.jar}:\ ${file.reference.commons-cli-1.2-sources.jar}:\
${file.reference.db4o-8.0.249.16098-all-java5.jar} ${file.reference.db4o-8.0.249.16098-all-java5.jar}
# Space-separated list of extra javac options # Space-separated list of extra javac options
javac.compilerargs= javac.compilerargs=
javac.deprecation=false javac.deprecation=false
javac.processorpath=\ javac.processorpath=\
${javac.classpath} ${javac.classpath}
javac.source=1.7 javac.source=1.7
javac.target=1.7 javac.target=1.7
javac.test.classpath=\ javac.test.classpath=\
${javac.classpath}:\ ${javac.classpath}:\
${build.classes.dir} ${build.classes.dir}
javac.test.processorpath=\ javac.test.processorpath=\
${javac.test.classpath} ${javac.test.classpath}
javadoc.additionalparam= javadoc.additionalparam=
javadoc.author=false javadoc.author=false
javadoc.encoding=${source.encoding} javadoc.encoding=${source.encoding}
javadoc.noindex=false javadoc.noindex=false
javadoc.nonavbar=false javadoc.nonavbar=false
javadoc.notree=false javadoc.notree=false
javadoc.private=false javadoc.private=false
javadoc.splitindex=true javadoc.splitindex=true
javadoc.use=true javadoc.use=true
javadoc.version=false javadoc.version=false
javadoc.windowtitle= javadoc.windowtitle=
manifest.file=manifest.mf manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=true mkdist.disabled=true
platform.active=default_platform platform.active=default_platform
run.classpath=\ run.classpath=\
${javac.classpath}:\ ${javac.classpath}:\
${build.classes.dir} ${build.classes.dir}
# Space-separated list of JVM arguments used when running the project. # Space-separated list of JVM arguments used when running the project.
# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. # You may also define separate properties like run-sys-prop.name=value instead of -Dname=value.
# To set system properties for unit tests define test-sys-prop.name=value: # To set system properties for unit tests define test-sys-prop.name=value:
run.jvmargs= run.jvmargs=
run.test.classpath=\ run.test.classpath=\
${javac.test.classpath}:\ ${javac.test.classpath}:\
${build.test.classes.dir} ${build.test.classes.dir}
source.encoding=UTF-8 source.encoding=UTF-8
source.reference.commons-cli-1.2.jar=lib/commons-cli-1.2-sources.jar source.reference.commons-cli-1.2.jar=lib/commons-cli-1.2-sources.jar
src.dir=${file.reference.mosstest-src} src.dir=${file.reference.mosstest-src}

View File

@ -1,13 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1"> <project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type> <type>org.netbeans.modules.java.j2seproject</type>
<configuration> <configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3"> <data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>MossTest</name> <name>MossTest</name>
<source-roots> <source-roots>
<root id="src.dir" name="src"/> <root id="src.dir" name="src"/>
</source-roots> </source-roots>
<test-roots/> <test-roots/>
</data> </data>
</configuration> </configuration>
</project> </project>

View File

@ -1,28 +1,28 @@
Main Main
Net Net
inBandUDP inBandUDP
OutOFBandUDP OutOFBandUDP
TCPNet TCPNet
MapManager MapManager
Mapgen(Pool?) Mapgen(Pool?)
MapLookup(Pool?) MapLookup(Pool?)
Player Player
PEvents(Pool?) PEvents(Pool?)
BlockChange BlockChange
Movement Movement
Entities Entities
EntActions EntActions
EntPathfindingAI EntPathfindingAI
Scripting Scripting
ScriptMgr ScriptMgr
Administrator Administrator
Logging Logging
UserMgmt UserMgmt
Ban/anti-attack Ban/anti-attack
Maintenance Maintenance
DBManager DBManager
DeadlockWatchdog-This shall be simple and never rely on blocked methods DeadlockWatchdog-This shall be simple and never rely on blocked methods
DB DB
DatabaseAccessors DatabaseAccessors
LoadBalancer LoadBalancer
LBCommunicator LBCommunicator

View File

@ -1,75 +1,75 @@
package net.mosstest.sandbox; package net.mosstest.sandbox;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
public class SandboxClass<T> { public class SandboxClass<T> {
Class<T> clazz; Class<T> clazz;
final boolean allowStatic, instantiable, deny, iface; final boolean allowStatic, instantiable, deny, iface;
public SandboxClass(Class<T> clazz, boolean allowStatic, public SandboxClass(Class<T> clazz, boolean allowStatic,
boolean instantiable, boolean deny, boolean iface) { boolean instantiable, boolean deny, boolean iface) {
this.clazz = clazz; this.clazz = clazz;
this.allowStatic = allowStatic; this.allowStatic = allowStatic;
this.instantiable = instantiable; this.instantiable = instantiable;
this.deny = deny; this.deny = deny;
this.iface = iface; this.iface = iface;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result result = prime * result
+ ((this.clazz == null) ? 0 : this.clazz.hashCode()); + ((this.clazz == null) ? 0 : this.clazz.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof SandboxClass)) { if (!(obj instanceof SandboxClass)) {
return false; return false;
} }
SandboxClass<?> other = (SandboxClass<?>) obj; SandboxClass<?> other = (SandboxClass<?>) obj;
if (this.clazz == null) { if (this.clazz == null) {
if (other.clazz != null) { if (other.clazz != null) {
return false; return false;
} }
} else if (!this.clazz.equals(other.clazz)) { } else if (!this.clazz.equals(other.clazz)) {
return false; return false;
} }
return true; return true;
} }
public Object invokeStatic(String method, Object... params) public Object invokeStatic(String method, Object... params)
throws NoSuchMethodException, SecurityException, throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException { InvocationTargetException {
Class<?>[] clazzes = new Class<?>[params.length]; Class<?>[] clazzes = new Class<?>[params.length];
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
clazzes[i] = params[i].getClass(); clazzes[i] = params[i].getClass();
} }
Method mth = this.clazz.getMethod(method, clazzes); Method mth = this.clazz.getMethod(method, clazzes);
return mth.invoke(null); return mth.invoke(null);
} }
public T getInstance(Object... params) throws NoSuchMethodException, public T getInstance(Object... params) throws NoSuchMethodException,
SecurityException, InstantiationException, IllegalAccessException, SecurityException, InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException { IllegalArgumentException, InvocationTargetException {
Class<?>[] clazzes = new Class<?>[params.length]; Class<?>[] clazzes = new Class<?>[params.length];
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
clazzes[i] = params[i].getClass(); clazzes[i] = params[i].getClass();
} }
Constructor<T> constr = this.clazz.getConstructor(clazzes); Constructor<T> constr = this.clazz.getConstructor(clazzes);
return constr.newInstance(params); return constr.newInstance(params);
} }
} }

View File

@ -1,28 +1,28 @@
package net.mosstest.sandbox.lang; package net.mosstest.sandbox.lang;
public class Runtime { public class Runtime {
private java.lang.Runtime runtime = java.lang.Runtime.getRuntime(); private java.lang.Runtime runtime = java.lang.Runtime.getRuntime();
public int availableProcessors() { public int availableProcessors() {
return this.runtime.availableProcessors(); return this.runtime.availableProcessors();
} }
public long freeMemory() { public long freeMemory() {
return this.runtime.freeMemory(); return this.runtime.freeMemory();
} }
public long totalMemory() { public long totalMemory() {
return this.runtime.totalMemory(); return this.runtime.totalMemory();
} }
public long maxMemory() { public long maxMemory() {
return this.runtime.maxMemory(); return this.runtime.maxMemory();
} }
public void gc() { public void gc() {
this.runtime.gc(); this.runtime.gc();
return; return;
} }
public Runtime() { public Runtime() {
} }
} }

View File

@ -1,38 +1,38 @@
package net.mosstest.sandbox.lang; package net.mosstest.sandbox.lang;
import java.io.InputStream; import java.io.InputStream;
import java.io.PrintStream; import java.io.PrintStream;
public final class System { public final class System {
private System() { private System() {
}; };
public static final PrintStream err = java.lang.System.err; public static final PrintStream err = java.lang.System.err;
public static final PrintStream out = java.lang.System.out; public static final PrintStream out = java.lang.System.out;
public static final InputStream in = java.lang.System.in; public static final InputStream in = java.lang.System.in;
public static void arraycopy(Object src, int srcPos, Object dest, public static void arraycopy(Object src, int srcPos, Object dest,
int destPos, int length) { int destPos, int length) {
java.lang.System.arraycopy(src, srcPos, dest, destPos, length); java.lang.System.arraycopy(src, srcPos, dest, destPos, length);
} }
public static long currentTimeMillis() { public static long currentTimeMillis() {
return java.lang.System.currentTimeMillis(); return java.lang.System.currentTimeMillis();
} }
public static void gc() { public static void gc() {
java.lang.System.gc(); java.lang.System.gc();
} }
public static int identityHashCode(Object o) { public static int identityHashCode(Object o) {
return java.lang.System.identityHashCode(o); return java.lang.System.identityHashCode(o);
} }
public static String lineSeparator() { public static String lineSeparator() {
return java.lang.System.lineSeparator(); return java.lang.System.lineSeparator();
} }
public static long nanoTime() { public static long nanoTime() {
return java.lang.System.nanoTime(); return java.lang.System.nanoTime();
} }
} }

View File

@ -1,9 +1,9 @@
package net.mosstest.sandbox.lang; package net.mosstest.sandbox.lang;
import net.mosstest.scripting.ScriptRunnable; import net.mosstest.scripting.ScriptRunnable;
public class Thread { public class Thread {
static void spawnThread(ScriptRunnable r) { static void spawnThread(ScriptRunnable r) {
//todo todo //todo todo
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.lang; package net.mosstest.sandbox.lang;
public class ThreadGroup { public class ThreadGroup {
//todo sandbox //todo sandbox
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.lang; package net.mosstest.sandbox.lang;
public class ThreadLocal { public class ThreadLocal {
//todo sandbox--probably discard, in fact. //todo sandbox--probably discard, in fact.
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.util; package net.mosstest.sandbox.util;
public class Collections { public class Collections {
//todo sandbox //todo sandbox
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.util; package net.mosstest.sandbox.util;
public class Enumeration { public class Enumeration {
//todo sandbox //todo sandbox
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.util; package net.mosstest.sandbox.util;
public class ResourceBundle { public class ResourceBundle {
//todo sandbox //todo sandbox
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.sandbox.util.concurrent.atomic; package net.mosstest.sandbox.util.concurrent.atomic;
public class AtomicReferenceFieldUpdater { public class AtomicReferenceFieldUpdater {
//todo sandbox //todo sandbox
} }

View File

@ -1,131 +1,131 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Random; import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import net.mosstest.servercore.SessionManager; import net.mosstest.servercore.SessionManager;
public class AntiCheatController { public class AntiCheatController {
protected ArrayList<AntiCheatCheck> checks = new ArrayList<>(); protected ArrayList<AntiCheatCheck> checks = new ArrayList<>();
protected ArrayList<AntiCheatHandler> handlers = new ArrayList<>(); protected ArrayList<AntiCheatHandler> handlers = new ArrayList<>();
protected MossScriptEnv env; protected MossScriptEnv env;
protected SessionManager sess; protected SessionManager sess;
protected volatile boolean run = false; protected volatile boolean run = false;
protected AtomicInteger needDeathsFrom = new AtomicInteger(0); protected AtomicInteger needDeathsFrom = new AtomicInteger(0);
public AntiCheatController(MossScriptEnv env, SessionManager sess) { public AntiCheatController(MossScriptEnv env, SessionManager sess) {
this.env = env; this.env = env;
this.sess = sess; this.sess = sess;
} }
public void registerCheck(AntiCheatCheck chk) { public void registerCheck(AntiCheatCheck chk) {
synchronized (this.checks) { synchronized (this.checks) {
this.checks.add(chk); this.checks.add(chk);
} }
} }
public void registerHandler(AntiCheatHandler hdl) { public void registerHandler(AntiCheatHandler hdl) {
synchronized (this.handlers) { synchronized (this.handlers) {
this.handlers.add(hdl); this.handlers.add(hdl);
} }
} }
private ArrayList<Thread> threads = new ArrayList<>(); private ArrayList<Thread> threads = new ArrayList<>();
public void startThreads(int threads, int priority) { public void startThreads(int threads, int priority) {
this.run = true; this.run = true;
for (int i = 0; i < threads; i++) { for (int i = 0; i < threads; i++) {
Thread cThread = new Thread(new AntiCheatRunnable(), "anticheat" Thread cThread = new Thread(new AntiCheatRunnable(), "anticheat"
+ new Random().nextInt()); + new Random().nextInt());
this.threads.add(cThread); this.threads.add(cThread);
cThread.start(); cThread.start();
cThread.setPriority(priority); cThread.setPriority(priority);
} }
} }
public void killThreads(int threads) { public void killThreads(int threads) {
this.needDeathsFrom.addAndGet(threads); this.needDeathsFrom.addAndGet(threads);
} }
public static interface AntiCheatCheck { public static interface AntiCheatCheck {
/** /**
* Check that a player is compliant with this anti-cheat check. This * Check that a player is compliant with this anti-cheat check. This
* method is not guaranteed to be called, especially if system resources * method is not guaranteed to be called, especially if system resources
* are low. * are low.
* *
* @param p * @param p
* The player to check. The volatile fields xpos, ypos, zpos, * The player to check. The volatile fields xpos, ypos, zpos,
* oldx, oldy, oldz, lastAntiCheatMillis may prove * oldx, oldy, oldz, lastAntiCheatMillis may prove
* particularly useful. * particularly useful.
* @param env * @param env
* The MossScriptEnv that may be used in case * The MossScriptEnv that may be used in case
* <code>moss</code> is not available in javascript global * <code>moss</code> is not available in javascript global
* scope. * scope.
* @return Value representing a violation level. Recommended values are * @return Value representing a violation level. Recommended values are
* 0 for all-OK to 100 for the most severe cheating. * 0 for all-OK to 100 for the most severe cheating.
*/ */
public int check(Player p, MossScriptEnv env); public int check(Player p, MossScriptEnv env);
} }
public static interface AntiCheatHandler { public static interface AntiCheatHandler {
/** /**
* Called if a violation is detected by any check. This method is * Called if a violation is detected by any check. This method is
* guaranteed to be called upon any violation being detected. * guaranteed to be called upon any violation being detected.
* *
* @param p * @param p
* The player with a violation. * The player with a violation.
* @param severity * @param severity
* Value representing a violation level. Recommended values * Value representing a violation level. Recommended values
* are 0 for all-OK to 100 for the most severe cheating. * are 0 for all-OK to 100 for the most severe cheating.
* @param env * @param env
* The MossScriptEnv that may be used in case * The MossScriptEnv that may be used in case
* <code>moss</code> is not available in javascript global * <code>moss</code> is not available in javascript global
* scope. * scope.
*/ */
public void handleViolation(Player p, int severity, MossScriptEnv env); public void handleViolation(Player p, int severity, MossScriptEnv env);
} }
private class AntiCheatRunnable implements Runnable { private class AntiCheatRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
runLoop: while (AntiCheatController.this.run) { runLoop: while (AntiCheatController.this.run) {
int needDeaths; int needDeaths;
if ((needDeaths = AntiCheatController.this.needDeathsFrom.get()) > 0) { if ((needDeaths = AntiCheatController.this.needDeathsFrom.get()) > 0) {
if (AntiCheatController.this.needDeathsFrom.compareAndSet( if (AntiCheatController.this.needDeathsFrom.compareAndSet(
needDeaths, needDeaths - 1)) needDeaths, needDeaths - 1))
break runLoop; break runLoop;
} }
try { try {
for (Player player : AntiCheatController.this.sess.playerSessions for (Player player : AntiCheatController.this.sess.playerSessions
.keySet()) { .keySet()) {
for (AntiCheatCheck chk : AntiCheatController.this.checks) { for (AntiCheatCheck chk : AntiCheatController.this.checks) {
int severity; int severity;
if ((severity = chk.check(player, if ((severity = chk.check(player,
AntiCheatController.this.env)) > 0) { AntiCheatController.this.env)) > 0) {
for (AntiCheatHandler hdl : AntiCheatController.this.handlers) { for (AntiCheatHandler hdl : AntiCheatController.this.handlers) {
hdl.handleViolation(player, severity, hdl.handleViolation(player, severity,
AntiCheatController.this.env); AntiCheatController.this.env);
} }
} }
} }
} }
} catch (Exception e) { } catch (Exception e) {
// pass for possible ConcurrentModificationException // pass for possible ConcurrentModificationException
} }
try { try {
Thread.sleep(100); Thread.sleep(100);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// pass // pass
} }
} }
} }
} }
} }

View File

@ -1,15 +1,15 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class Entity { public class Entity {
int id; int id;
public String name; public String name;
int hp; int hp;
int maxHealth; int maxHealth;
public void destroy() { public void destroy() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
protected Entity(String name, int maxHealth) { protected Entity(String name, int maxHealth) {
//TODO DB lookup for entities //TODO DB lookup for entities
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class EventProcessingCompletedSignal extends Throwable { public class EventProcessingCompletedSignal extends Throwable {
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public enum Face { public enum Face {
TOP, BOTTOM, N, S, E, W TOP, BOTTOM, N, S, E, W
} }

View File

@ -1,51 +1,51 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import net.mosstest.servercore.MapGeneratorException; import net.mosstest.servercore.MapGeneratorException;
import net.mosstest.servercore.NodeManager; import net.mosstest.servercore.NodeManager;
public interface IMapGenerator { public interface IMapGenerator {
void init(long seed, NodeManager nm, Object... params) throws MapGeneratorException; void init(long seed, NodeManager nm, Object... params) throws MapGeneratorException;
public MapChunk generateChunk(Position pos) throws MapGeneratorException; public MapChunk generateChunk(Position pos) throws MapGeneratorException;
/** /**
* Fills in a chunk as an array of light nodes, where 0 values require * Fills in a chunk as an array of light nodes, where 0 values require
* filling. * filling.
* *
* @param lightNodes * @param lightNodes
* A reference to the array that must be updated. * A reference to the array that must be updated.
* @param pos * @param pos
* The position corresponding to the chunk to be filled in. * The position corresponding to the chunk to be filled in.
* @throws MapGeneratorException * @throws MapGeneratorException
* Thrown in case the map generator encounters an inconsistency * Thrown in case the map generator encounters an inconsistency
* it cannot recover from. * it cannot recover from.
*/ */
public void fillInChunk(int[][][] lightNodes, Position pos) public void fillInChunk(int[][][] lightNodes, Position pos)
throws MapGeneratorException; throws MapGeneratorException;
/** /**
* Register an ore for future generation of chunks. The values given here * Register an ore for future generation of chunks. The values given here
* are hints to the map generator and need not be exact. * are hints to the map generator and need not be exact.
* *
* @param oreNode * @param oreNode
* The ore to generate. * The ore to generate.
* @param minDepth * @param minDepth
* The minimum depth(as a positive integer number of nodes below * The minimum depth(as a positive integer number of nodes below
* sea level. * sea level.
* @param rarity * @param rarity
* How rare the ore should be. Rarity 1 corresponds to virtually * How rare the ore should be. Rarity 1 corresponds to virtually
* every ore-containing node, and rarity 100 would correspond to * every ore-containing node, and rarity 100 would correspond to
* approximately one out of 100 nodes being this ore. * approximately one out of 100 nodes being this ore.
* @param clumping * @param clumping
* Defines how clumped the ore should be. Generally corresponds * Defines how clumped the ore should be. Generally corresponds
* to 0=uniform and 1=most strongly clumped(solid spheres of ore * to 0=uniform and 1=most strongly clumped(solid spheres of ore
* clumps to meet rarity goal) * clumps to meet rarity goal)
* @param params * @param params
* Miscellaneous params for the map generator. * Miscellaneous params for the map generator.
*/ */
public void registerOre(MapNode oreNode, double minDepth, double rarity, public void registerOre(MapNode oreNode, double minDepth, double rarity,
double clumping, int seed, Object... params); double clumping, int seed, Object... params);
} }

View File

@ -1,224 +1,224 @@
package net.mosstest.scripting; package net.mosstest.scripting;
/** /**
* Interface to specify handlers to be called when various actions are taken by * Interface to specify handlers to be called when various actions are taken by
* players directed at a node. These handlers are called after the ones defined * players directed at a node. These handlers are called after the ones defined
* in {@link MossScriptEnv} but before the default handlers. Handlers have a * in {@link MossScriptEnv} but before the default handlers. Handlers have a
* chance to throw {@link EventProcessingCompletedSignal} to bypass the default * chance to throw {@link EventProcessingCompletedSignal} to bypass the default
* handler. * handler.
* *
* @author rarkenin * @author rarkenin
* *
*/ */
public interface INodeParams { public interface INodeParams {
/** /**
* Function that is called when a node is punched. * Function that is called when a node is punched.
* *
* @param player * @param player
* The player punching the node. * The player punching the node.
* @param tool * @param tool
* The tool being used to punch the node. * The tool being used to punch the node.
* @param target * @param target
* The position of the targeted node. * The position of the targeted node.
* @param punchedFace * @param punchedFace
* The face being punched. * The face being punched.
*/ */
public abstract void onPunch(Player player, MossItem tool, public abstract void onPunch(Player player, MossItem tool,
NodePosition target, Face punchedFace) NodePosition target, Face punchedFace)
throws EventProcessingCompletedSignal; throws EventProcessingCompletedSignal;
/** /**
* Determines if a fall should continue * Determines if a fall should continue
* *
* @param player * @param player
* The player. * The player.
* @param height * @param height
* The height. * The height.
* @return A boolean representing whether the fall should continue or be * @return A boolean representing whether the fall should continue or be
* marked as a fall. * marked as a fall.
*/ */
public abstract boolean shouldContinueFall(Player player, double height); public abstract boolean shouldContinueFall(Player player, double height);
/** /**
* Called when a node is fully dug. * Called when a node is fully dug.
* *
* @param player * @param player
* The player digging the node. * The player digging the node.
* @param tool * @param tool
* The tool used to dig the node. * The tool used to dig the node.
* @param target * @param target
* The position of the node that has been dug. * The position of the node that has been dug.
* @param punchedFace * @param punchedFace
* The face on which the the tool was pointed when digging was * 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 * complete. Note that if a dig begins on one face but the player
* moves the aim to another face the onPunch handler may receive * moves the aim to another face the onPunch handler may receive
* a different face than this handler. * a different face than this handler.
* @throws EventProcessingCompletedSignal * @throws EventProcessingCompletedSignal
*/ */
public abstract void onDig(Player player, MossItem tool, public abstract void onDig(Player player, MossItem tool,
NodePosition target, Face punchedFace) NodePosition target, Face punchedFace)
throws EventProcessingCompletedSignal; throws EventProcessingCompletedSignal;
/** /**
* Called when a node is placed directly above, below, left, right, in front * Called when a node is placed directly above, below, left, right, in front
* of, or behind this node. * of, or behind this node.
* *
* @param player * @param player
* The player placing the node. * The player placing the node.
* @param target * @param target
* @param placed * @param placed
* @throws EventProcessingCompletedSignal * @throws EventProcessingCompletedSignal
*/ */
public abstract void onPlaceNextTo(Player player, NodePosition target, public abstract void onPlaceNextTo(Player player, NodePosition target,
NodePosition placed) throws EventProcessingCompletedSignal; NodePosition placed) throws EventProcessingCompletedSignal;
/** /**
* Called when a right-click is done on a node. Note that this is called * 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, * even if no node is placed, such as if the player is not holding anything,
* or is holding a tool. * or is holding a tool.
* *
* @param player * @param player
* Player performing the action. * Player performing the action.
* @param tool * @param tool
* Tool held by user in active slot during this action. * Tool held by user in active slot during this action.
* @param target * @param target
* Position of targeted node * Position of targeted node
* @param clickedFace * @param clickedFace
* Face which was right-clicked. * Face which was right-clicked.
* @throws EventProcessingCompletedSignal * @throws EventProcessingCompletedSignal
*/ */
public abstract void onRightClick(Player player, MossItem tool, public abstract void onRightClick(Player player, MossItem tool,
NodePosition target, Face clickedFace) NodePosition target, Face clickedFace)
throws EventProcessingCompletedSignal; throws EventProcessingCompletedSignal;
/** /**
* Called when a player steps on a node either from jumping, falling, or * Called when a player steps on a node either from jumping, falling, or
* walking forward. * walking forward.
* *
* @param player * @param player
* Player that steps on this node. * Player that steps on this node.
* @param pos * @param pos
* Position of node that is stepped on. * Position of node that is stepped on.
* @return Currently unused. * @return Currently unused.
* @throws EventProcessingCompletedSignal * @throws EventProcessingCompletedSignal
*/ */
public abstract boolean onStepOn(Player player, NodePosition pos) public abstract boolean onStepOn(Player player, NodePosition pos)
throws EventProcessingCompletedSignal; throws EventProcessingCompletedSignal;
/** /**
* Calculates the height a player may jump off of this node. One node is * Calculates the height a player may jump off of this node. One node is
* equal to 1.0. * equal to 1.0.
* *
* @param player * @param player
* @return The height the player may jump off this node. * @return The height the player may jump off this node.
*/ */
public abstract double jumpOffHeight(Player player); public abstract double jumpOffHeight(Player player);
/** /**
* Calculates the height a player will bounce when landing on this node. * Calculates the height a player will bounce when landing on this node.
* *
* @param player * @param player
* @param fallheight * @param fallheight
* The height from which the player has fallen. * The height from which the player has fallen.
* @return A double value representing the height the player is to bounce. * @return A double value representing the height the player is to bounce.
*/ */
public abstract double calcBounceHeight(Player player, double fallheight); public abstract double calcBounceHeight(Player player, double fallheight);
/** /**
* Calculates at which rate a player will sink in after landing on this * Calculates at which rate a player will sink in after landing on this
* node. * node.
* *
* @param player * @param player
* The player to calculate sink for. * The player to calculate sink for.
* @param fallheight * @param fallheight
* The height from which they have fallen. 0 if the player walks * The height from which they have fallen. 0 if the player walks
* onto the node without jumping or falling. * onto the node without jumping or falling.
* @return The rate for the player to sink. * @return The rate for the player to sink.
*/ */
public abstract double calcSinkIn(Player player, double fallheight); public abstract double calcSinkIn(Player player, double fallheight);
/** /**
* Calculates at which rate a player will sink in if they are holding the * Calculates at which rate a player will sink in if they are holding the
* key to actively descend. * key to actively descend.
* *
* @param player * @param player
* The player to calculate sink for. * The player to calculate sink for.
* @param fallheight * @param fallheight
* The height from which they have fallen. 0 if the player walks * The height from which they have fallen. 0 if the player walks
* onto the node without jumping or falling(feet at surface), or * onto the node without jumping or falling(feet at surface), or
* negative if they have already sunk in partially. * negative if they have already sunk in partially.
* @return The rate for the player to sink. * @return The rate for the player to sink.
*/ */
public abstract double calcSinkActive(Player player, double fallheight); public abstract double calcSinkActive(Player player, double fallheight);
/** /**
* Calculates the rate at which a player will rise out of this node if they * 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 * have sunk in and are pressing the jump key. If the player is in multiple
* node the lowermost node at the player's horizontal center is considered. * node the lowermost node at the player's horizontal center is considered.
* *
* @param player * @param player
* The player to perform the calculation for. * The player to perform the calculation for.
* @param sinkheight * @param sinkheight
* The depth to which the player has sunk. 0 is the surface at * 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. 1 corresponds to the player's feet being at
* the bottom of the node, and 2 or more is if the player is * the bottom of the node, and 2 or more is if the player is
* submerged in multiple nodes. * submerged in multiple nodes.
* @return The rate at which the player should rise when they hold the key * @return The rate at which the player should rise when they hold the key
* corresponding to jumping, in nodes per second. * corresponding to jumping, in nodes per second.
*/ */
public abstract double calcSinkEscape(Player player, double sinkheight); public abstract double calcSinkEscape(Player player, double sinkheight);
/** /**
* Calculates the speed at which a player will move across this node when * Calculates the speed at which a player will move across this node when
* walking. * walking.
* *
* @param player * @param player
* The player for which the walk rate is being calculated. * The player for which the walk rate is being calculated.
* @return The rate in nodes/second at which the player should walk. * @return The rate in nodes/second at which the player should walk.
*/ */
public abstract double calcWalkSpeed(Player player); public abstract double calcWalkSpeed(Player player);
/** /**
* Calculates the speed at which a player will move across this node when * Calculates the speed at which a player will move across this node when
* sprinting. * sprinting.
* *
* @param player * @param player
* The player for which the sprint rate is being calculated. * The player for which the sprint rate is being calculated.
* @return The rate in nodes/second at which the player should sprint. * @return The rate in nodes/second at which the player should sprint.
*/ */
public abstract double calcSprintSpeed(Player player); public abstract double calcSprintSpeed(Player player);
/** /**
* Calculates the damage a player will take when falling onto this node. * Calculates the damage a player will take when falling onto this node.
* *
* @param player * @param player
* The player falling onto this node. * The player falling onto this node.
* @param height * @param height
* The fall height. * The fall height.
* @return The damage to be given to the player. A player has a default * @return The damage to be given to the player. A player has a default
* health of 64 units. * health of 64 units.
*/ */
public abstract double calcFallDamage(Player player, double height); public abstract double calcFallDamage(Player player, double height);
/** /**
* Calculate whether a ray aimed from the crosshairs should stop at this * Calculate whether a ray aimed from the crosshairs should stop at this
* node. * node.
* *
* @param player * @param player
* The player. * The player.
* @param distance * @param distance
* The distance from the camera to the node. * The distance from the camera to the node.
* @return * @return
*/ */
public abstract boolean shouldHitAimRay(Player player, double distance); public abstract boolean shouldHitAimRay(Player player, double distance);
/** /**
* Calculate a dig property. These are generally 0 for inability to dig to 1 * Calculate a dig property. These are generally 0 for inability to dig to 1
* for digging the node in one second. * for digging the node in one second.
* *
* @param key * @param key
* @return * @return
*/ */
public abstract double calcInteractProperties(MossTool.InteractType key); public abstract double calcInteractProperties(MossTool.InteractType key);
} }

View File

@ -1,235 +1,235 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.geom.GeneralPath; import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D; import java.awt.geom.Path2D;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape; import java.awt.geom.RectangularShape;
import java.lang.ref.PhantomReference; import java.lang.ref.PhantomReference;
import java.lang.ref.Reference; import java.lang.ref.Reference;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger; import java.math.BigInteger;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.util.AbstractCollection; import java.util.AbstractCollection;
import java.util.AbstractList; import java.util.AbstractList;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.AbstractSequentialList; import java.util.AbstractSequentialList;
import java.util.AbstractSet; import java.util.AbstractSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.BitSet; import java.util.BitSet;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Currency; import java.util.Currency;
import java.util.Date; import java.util.Date;
import java.util.Deque; import java.util.Deque;
import java.util.Dictionary; import java.util.Dictionary;
import java.util.EmptyStackException; import java.util.EmptyStackException;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.EventListener; import java.util.EventListener;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.NavigableMap; import java.util.NavigableMap;
import java.util.Properties; import java.util.Properties;
import java.util.Queue; import java.util.Queue;
import java.util.Random; import java.util.Random;
import java.util.RandomAccess; import java.util.RandomAccess;
import java.util.Set; import java.util.Set;
import java.util.SortedMap; import java.util.SortedMap;
import java.util.Stack; import java.util.Stack;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.Vector; import java.util.Vector;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.AbstractOwnableSynchronizer; import java.util.concurrent.locks.AbstractOwnableSynchronizer;
import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.MatchResult; import java.util.regex.MatchResult;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.mosstest.sandbox.SandboxClass; import net.mosstest.sandbox.SandboxClass;
import net.mosstest.sandbox.lang.Runtime; import net.mosstest.sandbox.lang.Runtime;
import net.mosstest.sandbox.lang.System; import net.mosstest.sandbox.lang.System;
import net.mosstest.sandbox.lang.Thread; import net.mosstest.sandbox.lang.Thread;
import net.mosstest.sandbox.lang.ThreadGroup; import net.mosstest.sandbox.lang.ThreadGroup;
import net.mosstest.sandbox.lang.ThreadLocal; import net.mosstest.sandbox.lang.ThreadLocal;
import net.mosstest.sandbox.util.Enumeration; import net.mosstest.sandbox.util.Enumeration;
import net.mosstest.sandbox.util.ResourceBundle; import net.mosstest.sandbox.util.ResourceBundle;
import net.mosstest.sandbox.util.concurrent.atomic.AtomicReferenceFieldUpdater; import net.mosstest.sandbox.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/** /**
* Class for scripts to instantiate and access the static methods of various approved classes. * Class for scripts to instantiate and access the static methods of various approved classes.
* @author rarkenin * @author rarkenin
* *
*/ */
public class JavaApi { public class JavaApi {
private static final HashMap<String, SandboxClass> qualifiedClasses=new HashMap<String, SandboxClass>(){{ private static final HashMap<String, SandboxClass> qualifiedClasses=new HashMap<String, SandboxClass>(){{
put("java.lang.Object", new SandboxClass<Object>(java.lang.Object.class, true, true, false, false)); put("java.lang.Object", new SandboxClass<Object>(java.lang.Object.class, true, true, false, false));
put("java.lang.String", new SandboxClass<String>(java.lang.String.class, true, true, false, false)); put("java.lang.String", new SandboxClass<String>(java.lang.String.class, true, true, false, false));
put("java.lang.Comparable", new SandboxClass<Comparable>(java.lang.Comparable.class, true, true, false, true)); put("java.lang.Comparable", new SandboxClass<Comparable>(java.lang.Comparable.class, true, true, false, true));
put("java.lang.CharSequence", new SandboxClass<CharSequence>(java.lang.CharSequence.class, true, true, false, true)); put("java.lang.CharSequence", new SandboxClass<CharSequence>(java.lang.CharSequence.class, true, true, false, true));
put("java.lang.Class", new SandboxClass<Class>(java.lang.Class.class, false, false, true, false)); put("java.lang.Class", new SandboxClass<Class>(java.lang.Class.class, false, false, true, false));
put("java.lang.Cloneable", new SandboxClass<Cloneable>(java.lang.Cloneable.class, true, true, false, true)); put("java.lang.Cloneable", new SandboxClass<Cloneable>(java.lang.Cloneable.class, true, true, false, true));
put("java.lang.ClassLoader", new SandboxClass<ClassLoader>(java.lang.ClassLoader.class, false, false, true, false)); put("java.lang.ClassLoader", new SandboxClass<ClassLoader>(java.lang.ClassLoader.class, false, false, true, false));
put("java.lang.System", new SandboxClass<System>(net.mosstest.sandbox.lang.System.class, true, false, true, false)); put("java.lang.System", new SandboxClass<System>(net.mosstest.sandbox.lang.System.class, true, false, true, false));
put("java.lang.Throwable", new SandboxClass<Throwable>(java.lang.Throwable.class, true, true, false, false)); put("java.lang.Throwable", new SandboxClass<Throwable>(java.lang.Throwable.class, true, true, false, false));
put("java.lang.Error", new SandboxClass<Error>(java.lang.Error.class, true, true, false, false)); put("java.lang.Error", new SandboxClass<Error>(java.lang.Error.class, true, true, false, false));
put("java.lang.ThreadDeath", new SandboxClass<ThreadDeath>(java.lang.ThreadDeath.class, false, false, true, false)); put("java.lang.ThreadDeath", new SandboxClass<ThreadDeath>(java.lang.ThreadDeath.class, false, false, true, false));
put("java.lang.Exception", new SandboxClass<Exception>(java.lang.Exception.class, true, true, false, false)); put("java.lang.Exception", new SandboxClass<Exception>(java.lang.Exception.class, true, true, false, false));
put("java.lang.RuntimeException", new SandboxClass<RuntimeException>(java.lang.RuntimeException.class, true, true, false, false)); put("java.lang.RuntimeException", new SandboxClass<RuntimeException>(java.lang.RuntimeException.class, true, true, false, false));
put("java.lang.ClassCastException", new SandboxClass<ClassCastException>(java.lang.ClassCastException.class, true, true, false, false)); put("java.lang.ClassCastException", new SandboxClass<ClassCastException>(java.lang.ClassCastException.class, true, true, false, false));
put("java.lang.ArrayStoreException", new SandboxClass<ArrayStoreException>(java.lang.ArrayStoreException.class, true, true, false, false)); put("java.lang.ArrayStoreException", new SandboxClass<ArrayStoreException>(java.lang.ArrayStoreException.class, true, true, false, false));
put("java.lang.ref.Reference", new SandboxClass<Reference>(java.lang.ref.Reference.class, true, true, false, false)); put("java.lang.ref.Reference", new SandboxClass<Reference>(java.lang.ref.Reference.class, true, true, false, false));
put("java.lang.ref.SoftReference", new SandboxClass<SoftReference>(java.lang.ref.SoftReference.class, true, true, false, false)); put("java.lang.ref.SoftReference", new SandboxClass<SoftReference>(java.lang.ref.SoftReference.class, true, true, false, false));
put("java.lang.ref.WeakReference", new SandboxClass<WeakReference>(java.lang.ref.WeakReference.class, true, true, false, false)); put("java.lang.ref.WeakReference", new SandboxClass<WeakReference>(java.lang.ref.WeakReference.class, true, true, false, false));
put("java.lang.ref.PhantomReference", new SandboxClass<PhantomReference>(java.lang.ref.PhantomReference.class, true, true, false, false)); put("java.lang.ref.PhantomReference", new SandboxClass<PhantomReference>(java.lang.ref.PhantomReference.class, true, true, false, false));
put("java.lang.Thread", new SandboxClass<Thread>(net.mosstest.sandbox.lang.Thread.class, true, true, false, false)); put("java.lang.Thread", new SandboxClass<Thread>(net.mosstest.sandbox.lang.Thread.class, true, true, false, false));
put("java.lang.Runnable", new SandboxClass<Runnable>(java.lang.Runnable.class, true, true, false, true)); put("java.lang.Runnable", new SandboxClass<Runnable>(java.lang.Runnable.class, true, true, false, true));
put("java.lang.ref.SoftReference", new SandboxClass<ThreadGroup>(net.mosstest.sandbox.lang.ThreadGroup.class, true, true, false, false)); put("java.lang.ref.SoftReference", new SandboxClass<ThreadGroup>(net.mosstest.sandbox.lang.ThreadGroup.class, true, true, false, false));
put("java.util.Properties", new SandboxClass<Properties>(java.util.Properties.class, true, true, false, false)); put("java.util.Properties", new SandboxClass<Properties>(java.util.Properties.class, true, true, false, false));
put("java.util.Hashtable", new SandboxClass<Hashtable>(java.util.Hashtable.class, true, true, false, false)); put("java.util.Hashtable", new SandboxClass<Hashtable>(java.util.Hashtable.class, true, true, false, false));
put("java.util.Map", new SandboxClass<Map>(java.util.Map.class, true, true, false, false)); put("java.util.Map", new SandboxClass<Map>(java.util.Map.class, true, true, false, false));
put("java.util.Dictionary", new SandboxClass<Dictionary>(java.util.Dictionary.class, true, true, false, false)); put("java.util.Dictionary", new SandboxClass<Dictionary>(java.util.Dictionary.class, true, true, false, false));
put("java.util.Vector", new SandboxClass<Vector>(java.util.Vector.class, true, true, false, false)); put("java.util.Vector", new SandboxClass<Vector>(java.util.Vector.class, true, true, false, false));
put("java.util.List", new SandboxClass<List>(java.util.List.class, true, true, false, false)); put("java.util.List", new SandboxClass<List>(java.util.List.class, true, true, false, false));
put("java.util.Collection", new SandboxClass<Collection>(java.util.Collection.class, true, true, false, true)); put("java.util.Collection", new SandboxClass<Collection>(java.util.Collection.class, true, true, false, true));
put("java.lang.Iterable", new SandboxClass<Iterable>(java.lang.Iterable.class, true, true, false, true)); put("java.lang.Iterable", new SandboxClass<Iterable>(java.lang.Iterable.class, true, true, false, true));
put("java.util.RandomAccess", new SandboxClass<RandomAccess>(java.util.RandomAccess.class, true, true, false, true)); put("java.util.RandomAccess", new SandboxClass<RandomAccess>(java.util.RandomAccess.class, true, true, false, true));
put("java.util.AbstractList", new SandboxClass<AbstractList>(java.util.AbstractList.class, true, true, false, false)); put("java.util.AbstractList", new SandboxClass<AbstractList>(java.util.AbstractList.class, true, true, false, false));
put("java.util.AbstractCollection", new SandboxClass<AbstractCollection>(java.util.AbstractCollection.class, true, true, false, false)); put("java.util.AbstractCollection", new SandboxClass<AbstractCollection>(java.util.AbstractCollection.class, true, true, false, false));
put("java.lang.StringBuffer", new SandboxClass<StringBuffer>(java.lang.StringBuffer.class, true, true, false, false)); put("java.lang.StringBuffer", new SandboxClass<StringBuffer>(java.lang.StringBuffer.class, true, true, false, false));
put("java.lang.Appendable", new SandboxClass<Appendable>(java.lang.Appendable.class, true, true, false, false)); put("java.lang.Appendable", new SandboxClass<Appendable>(java.lang.Appendable.class, true, true, false, false));
put("java.lang.StackTraceElement", new SandboxClass<StackTraceElement>(java.lang.StackTraceElement.class, true, true, false, false)); put("java.lang.StackTraceElement", new SandboxClass<StackTraceElement>(java.lang.StackTraceElement.class, true, true, false, false));
put("java.lang.Boolean", new SandboxClass<Boolean>(java.lang.Boolean.class, true, true, false, false)); put("java.lang.Boolean", new SandboxClass<Boolean>(java.lang.Boolean.class, true, true, false, false));
put("java.lang.Character", new SandboxClass<Character>(java.lang.Character.class, true, true, false, false)); put("java.lang.Character", new SandboxClass<Character>(java.lang.Character.class, true, true, false, false));
put("java.lang.Float", new SandboxClass<Float>(java.lang.Float.class, true, true, false, false)); put("java.lang.Float", new SandboxClass<Float>(java.lang.Float.class, true, true, false, false));
put("java.lang.Number", new SandboxClass<Number>(java.lang.Number.class, true, true, false, false)); put("java.lang.Number", new SandboxClass<Number>(java.lang.Number.class, true, true, false, false));
put("java.lang.Double", new SandboxClass<Double>(java.lang.Double.class, true, true, false, false)); put("java.lang.Double", new SandboxClass<Double>(java.lang.Double.class, true, true, false, false));
put("java.lang.Byte", new SandboxClass<Byte>(java.lang.Byte.class, true, true, false, false)); put("java.lang.Byte", new SandboxClass<Byte>(java.lang.Byte.class, true, true, false, false));
put("java.lang.Short", new SandboxClass<Short>(java.lang.Short.class, true, true, false, false)); put("java.lang.Short", new SandboxClass<Short>(java.lang.Short.class, true, true, false, false));
put("java.lang.Integer", new SandboxClass<Integer>(java.lang.Integer.class, true, true, false, false)); put("java.lang.Integer", new SandboxClass<Integer>(java.lang.Integer.class, true, true, false, false));
put("java.lang.Long", new SandboxClass<Long>(java.lang.Long.class, true, true, false, false)); put("java.lang.Long", new SandboxClass<Long>(java.lang.Long.class, true, true, false, false));
put("java.lang.NullPointerException", new SandboxClass<NullPointerException>(java.lang.NullPointerException.class, true, true, false, false)); put("java.lang.NullPointerException", new SandboxClass<NullPointerException>(java.lang.NullPointerException.class, true, true, false, false));
put("java.lang.ArithmeticException", new SandboxClass<ArithmeticException>(java.lang.ArithmeticException.class, true, true, false, false)); put("java.lang.ArithmeticException", new SandboxClass<ArithmeticException>(java.lang.ArithmeticException.class, true, true, false, false));
put("java.util.Comparator", new SandboxClass<Comparator>(java.util.Comparator.class, true, true, false, true)); put("java.util.Comparator", new SandboxClass<Comparator>(java.util.Comparator.class, true, true, false, true));
put("java.util.AbstractMap", new SandboxClass<AbstractMap>(java.util.AbstractMap.class, true, true, false, false)); put("java.util.AbstractMap", new SandboxClass<AbstractMap>(java.util.AbstractMap.class, true, true, false, false));
put("java.util.HashMap", new SandboxClass<HashMap>(java.util.HashMap.class, true, true, false, false)); put("java.util.HashMap", new SandboxClass<HashMap>(java.util.HashMap.class, true, true, false, false));
put("java.util.Stack", new SandboxClass<Stack>(java.util.Stack.class, true, true, false, false)); put("java.util.Stack", new SandboxClass<Stack>(java.util.Stack.class, true, true, false, false));
put("java.util.Enumeration", new SandboxClass<Enumeration>(net.mosstest.sandbox.util.Enumeration.class, true, true, false, false)); put("java.util.Enumeration", new SandboxClass<Enumeration>(net.mosstest.sandbox.util.Enumeration.class, true, true, false, false));
put("java.util.Iterator", new SandboxClass<Iterator>(java.util.Iterator.class, true, true, false, false)); put("java.util.Iterator", new SandboxClass<Iterator>(java.util.Iterator.class, true, true, false, false));
put("java.util.concurrent.atomic.AtomicReferenceFieldUpdater", new SandboxClass<AtomicReferenceFieldUpdater>(net.mosstest.sandbox.util.concurrent.atomic.AtomicReferenceFieldUpdater.class, true, true, false, false)); put("java.util.concurrent.atomic.AtomicReferenceFieldUpdater", new SandboxClass<AtomicReferenceFieldUpdater>(net.mosstest.sandbox.util.concurrent.atomic.AtomicReferenceFieldUpdater.class, true, true, false, false));
put("java.lang.NoSuchMethodError", new SandboxClass<NoSuchMethodError>(java.lang.NoSuchMethodError.class, true, true, false, false)); put("java.lang.NoSuchMethodError", new SandboxClass<NoSuchMethodError>(java.lang.NoSuchMethodError.class, true, true, false, false));
put("java.util.Collections", new SandboxClass<Collections>(java.util.Collections.class, true, false, false, false)); put("java.util.Collections", new SandboxClass<Collections>(java.util.Collections.class, true, false, false, false));
put("java.util.AbstractSet", new SandboxClass<AbstractSet>(java.util.AbstractSet.class, true, true, false, false)); put("java.util.AbstractSet", new SandboxClass<AbstractSet>(java.util.AbstractSet.class, true, true, false, false));
put("java.util.Set", new SandboxClass<Set>(java.util.Set.class, true, true, false, true)); put("java.util.Set", new SandboxClass<Set>(java.util.Set.class, true, true, false, true));
put("java.lang.ThreadLocal", new SandboxClass<ThreadLocal>(net.mosstest.sandbox.lang.ThreadLocal.class, false, false, false, false)); put("java.lang.ThreadLocal", new SandboxClass<ThreadLocal>(net.mosstest.sandbox.lang.ThreadLocal.class, false, false, false, false));
put("java.util.concurrent.atomic.AtomicInteger", new SandboxClass<AtomicInteger>(java.util.concurrent.atomic.AtomicInteger.class, true, true, false, false)); put("java.util.concurrent.atomic.AtomicInteger", new SandboxClass<AtomicInteger>(java.util.concurrent.atomic.AtomicInteger.class, true, true, false, false));
put("java.util.Arrays", new SandboxClass<Arrays>(java.util.Arrays.class, true, false, false, false)); put("java.util.Arrays", new SandboxClass<Arrays>(java.util.Arrays.class, true, false, false, false));
put("java.lang.Math", new SandboxClass<Math>(java.lang.Math.class, true, false, false, false)); put("java.lang.Math", new SandboxClass<Math>(java.lang.Math.class, true, false, false, false));
put("java.lang.StringBuilder", new SandboxClass<StringBuilder>(java.lang.StringBuilder.class, true, true, false, false)); put("java.lang.StringBuilder", new SandboxClass<StringBuilder>(java.lang.StringBuilder.class, true, true, false, false));
put("java.lang.Runtime", new SandboxClass<Runtime>(net.mosstest.sandbox.lang.Runtime.class, true, true, false, false)); put("java.lang.Runtime", new SandboxClass<Runtime>(net.mosstest.sandbox.lang.Runtime.class, true, true, false, false));
put("java.lang.Readable", new SandboxClass<Readable>(java.lang.Readable.class, true, true, false, false)); put("java.lang.Readable", new SandboxClass<Readable>(java.lang.Readable.class, true, true, false, false));
put("java.util.LinkedHashMap", new SandboxClass<LinkedHashMap>(java.util.LinkedHashMap.class, true, true, false, false)); put("java.util.LinkedHashMap", new SandboxClass<LinkedHashMap>(java.util.LinkedHashMap.class, true, true, false, false));
put("java.util.ArrayList", new SandboxClass<ArrayList>(java.util.ArrayList.class, true, true, false, false)); put("java.util.ArrayList", new SandboxClass<ArrayList>(java.util.ArrayList.class, true, true, false, false));
put("java.util.IdentityHashMap", new SandboxClass<IdentityHashMap>(java.util.IdentityHashMap.class, true, true, false, false)); put("java.util.IdentityHashMap", new SandboxClass<IdentityHashMap>(java.util.IdentityHashMap.class, true, true, false, false));
put("java.util.StringTokenizer", new SandboxClass<StringTokenizer>(java.util.StringTokenizer.class, true, true, false, false)); put("java.util.StringTokenizer", new SandboxClass<StringTokenizer>(java.util.StringTokenizer.class, true, true, false, false));
put("java.util.concurrent.ConcurrentHashMap", new SandboxClass<ConcurrentHashMap>(java.util.concurrent.ConcurrentHashMap.class, true, true, false, false)); put("java.util.concurrent.ConcurrentHashMap", new SandboxClass<ConcurrentHashMap>(java.util.concurrent.ConcurrentHashMap.class, true, true, false, false));
put("java.util.concurrent", new SandboxClass<ConcurrentMap>(java.util.concurrent.ConcurrentMap.class, true, true, false, false)); put("java.util.concurrent", new SandboxClass<ConcurrentMap>(java.util.concurrent.ConcurrentMap.class, true, true, false, false));
put("java.util.concurrent.locks.ReentrantLock", new SandboxClass<ReentrantLock>(java.util.concurrent.locks.ReentrantLock.class, true, true, false, false)); put("java.util.concurrent.locks.ReentrantLock", new SandboxClass<ReentrantLock>(java.util.concurrent.locks.ReentrantLock.class, true, true, false, false));
put("java.util.concurrent.locks.Lock", new SandboxClass<Lock>(java.util.concurrent.locks.Lock.class, true, true, false, false)); put("java.util.concurrent.locks.Lock", new SandboxClass<Lock>(java.util.concurrent.locks.Lock.class, true, true, false, false));
put("java.util.concurrent.locks.AbstractQueuedSynchronizer", new SandboxClass<AbstractQueuedSynchronizer>(java.util.concurrent.locks.AbstractQueuedSynchronizer.class, true, true, false, false)); put("java.util.concurrent.locks.AbstractQueuedSynchronizer", new SandboxClass<AbstractQueuedSynchronizer>(java.util.concurrent.locks.AbstractQueuedSynchronizer.class, true, true, false, false));
put("java.util.concurrent.locks.AbstractOwnableSynchronizer", new SandboxClass<AbstractOwnableSynchronizer>(java.util.concurrent.locks.AbstractOwnableSynchronizer.class, true, true, false, false)); put("java.util.concurrent.locks.AbstractOwnableSynchronizer", new SandboxClass<AbstractOwnableSynchronizer>(java.util.concurrent.locks.AbstractOwnableSynchronizer.class, true, true, false, false));
put("java.util.BitSet", new SandboxClass<BitSet>(java.util.BitSet.class, true, true, false, false)); put("java.util.BitSet", new SandboxClass<BitSet>(java.util.BitSet.class, true, true, false, false));
put("java.util.HashSet", new SandboxClass<HashSet>(java.util.HashSet.class, true, true, false, false)); put("java.util.HashSet", new SandboxClass<HashSet>(java.util.HashSet.class, true, true, false, false));
put("java.util.LinkedHashSet", new SandboxClass<LinkedHashSet>(java.util.LinkedHashSet.class, true, true, false, false)); put("java.util.LinkedHashSet", new SandboxClass<LinkedHashSet>(java.util.LinkedHashSet.class, true, true, false, false));
put("java.lang.InterruptedException", new SandboxClass<InterruptedException>(java.lang.InterruptedException.class, true, true, false, false)); put("java.lang.InterruptedException", new SandboxClass<InterruptedException>(java.lang.InterruptedException.class, true, true, false, false));
put("java.util.ResourceBundle", new SandboxClass<ResourceBundle>(net.mosstest.sandbox.util.ResourceBundle.class, true, true, false, false)); put("java.util.ResourceBundle", new SandboxClass<ResourceBundle>(net.mosstest.sandbox.util.ResourceBundle.class, true, true, false, false));
put("java.util.EventListener", new SandboxClass<EventListener>(java.util.EventListener.class, true, true, false, true)); put("java.util.EventListener", new SandboxClass<EventListener>(java.util.EventListener.class, true, true, false, true));
put("java.awt.geom.AffineTransform", new SandboxClass<AffineTransform>(java.awt.geom.AffineTransform.class, true, true, false, false)); put("java.awt.geom.AffineTransform", new SandboxClass<AffineTransform>(java.awt.geom.AffineTransform.class, true, true, false, false));
put("java.lang.Enum", new SandboxClass<Enum>(java.lang.Enum.class, true, true, false, false)); put("java.lang.Enum", new SandboxClass<Enum>(java.lang.Enum.class, true, true, false, false));
put("java.util.WeakHashMap", new SandboxClass<WeakHashMap>(java.util.WeakHashMap.class, true, true, false, false)); put("java.util.WeakHashMap", new SandboxClass<WeakHashMap>(java.util.WeakHashMap.class, true, true, false, false));
put("java.awt.geom.Dimension2D", new SandboxClass<Dimension2D>(java.awt.geom.Dimension2D.class, true, true, false, false)); put("java.awt.geom.Dimension2D", new SandboxClass<Dimension2D>(java.awt.geom.Dimension2D.class, true, true, false, false));
put("java.util.concurrent.atomic.AtomicBoolean", new SandboxClass<AtomicBoolean>(java.util.concurrent.atomic.AtomicBoolean.class, true, true, false, false)); put("java.util.concurrent.atomic.AtomicBoolean", new SandboxClass<AtomicBoolean>(java.util.concurrent.atomic.AtomicBoolean.class, true, true, false, false));
put("java.lang.NoSuchMethodException", new SandboxClass<NoSuchMethodException>(java.lang.NoSuchMethodException.class, true, true, false, false)); put("java.lang.NoSuchMethodException", new SandboxClass<NoSuchMethodException>(java.lang.NoSuchMethodException.class, true, true, false, false));
put("java.awt.geom.Point2D", new SandboxClass<Point2D>(java.awt.geom.Point2D.class, true, true, false, false)); put("java.awt.geom.Point2D", new SandboxClass<Point2D>(java.awt.geom.Point2D.class, true, true, false, false));
put("java.lang.UnsupportedOperationException", new SandboxClass<UnsupportedOperationException>(java.lang.UnsupportedOperationException.class, true, true, false, false)); put("java.lang.UnsupportedOperationException", new SandboxClass<UnsupportedOperationException>(java.lang.UnsupportedOperationException.class, true, true, false, false));
put("java.awt.geom.Rectangle2D", new SandboxClass<Rectangle2D>(java.awt.geom.Rectangle2D.class, true, true, false, false)); put("java.awt.geom.Rectangle2D", new SandboxClass<Rectangle2D>(java.awt.geom.Rectangle2D.class, true, true, false, false));
put("java.awt.geom.RectangularShape", new SandboxClass<RectangularShape>(java.awt.geom.RectangularShape.class, true, true, false, false)); put("java.awt.geom.RectangularShape", new SandboxClass<RectangularShape>(java.awt.geom.RectangularShape.class, true, true, false, false));
put("java.lang.SecurityException", new SandboxClass<SecurityException>(java.lang.SecurityException.class, true, true, false, false)); put("java.lang.SecurityException", new SandboxClass<SecurityException>(java.lang.SecurityException.class, true, true, false, false));
put("java.util.IllegalStateException", new SandboxClass<IllegalStateException>(java.lang.IllegalStateException.class, true, true, false, false)); put("java.util.IllegalStateException", new SandboxClass<IllegalStateException>(java.lang.IllegalStateException.class, true, true, false, false));
put("java.awt.geom.Path2D", new SandboxClass<Path2D>(java.awt.geom.Path2D.class, true, true, false, false)); put("java.awt.geom.Path2D", new SandboxClass<Path2D>(java.awt.geom.Path2D.class, true, true, false, false));
put("java.awt.geom.GeneralPath", new SandboxClass<GeneralPath>(java.awt.geom.GeneralPath.class, true, true, false, false)); put("java.awt.geom.GeneralPath", new SandboxClass<GeneralPath>(java.awt.geom.GeneralPath.class, true, true, false, false));
put("java.util.MissingResourceException", new SandboxClass<MissingResourceException>(java.util.MissingResourceException.class, true, true, false, false)); put("java.util.MissingResourceException", new SandboxClass<MissingResourceException>(java.util.MissingResourceException.class, true, true, false, false));
put("java.util.LinkedList", new SandboxClass<LinkedList>(java.util.LinkedList.class, true, true, false, false)); put("java.util.LinkedList", new SandboxClass<LinkedList>(java.util.LinkedList.class, true, true, false, false));
put("java.util.Deque", new SandboxClass<Deque>(java.util.Deque.class, true, true, false, false)); put("java.util.Deque", new SandboxClass<Deque>(java.util.Deque.class, true, true, false, false));
put("java.util.Queue", new SandboxClass<Queue>(java.util.Queue.class, true, true, false, false)); put("java.util.Queue", new SandboxClass<Queue>(java.util.Queue.class, true, true, false, false));
put("java.util.AbstractSequentialList", new SandboxClass<AbstractSequentialList>(java.util.AbstractSequentialList.class, true, true, false, false)); put("java.util.AbstractSequentialList", new SandboxClass<AbstractSequentialList>(java.util.AbstractSequentialList.class, true, true, false, false));
put("java.util.EmptyStackException", new SandboxClass<EmptyStackException>(java.util.EmptyStackException.class, true, true, false, false)); put("java.util.EmptyStackException", new SandboxClass<EmptyStackException>(java.util.EmptyStackException.class, true, true, false, false));
put("java.util.TreeSet", new SandboxClass<TreeSet>(java.util.TreeSet.class, true, true, false, false)); put("java.util.TreeSet", new SandboxClass<TreeSet>(java.util.TreeSet.class, true, true, false, false));
put("java.util.NavigableMap", new SandboxClass<NavigableMap>(java.util.NavigableMap.class, true, true, false, false)); put("java.util.NavigableMap", new SandboxClass<NavigableMap>(java.util.NavigableMap.class, true, true, false, false));
put("java.util.SortedMap", new SandboxClass<SortedMap>(java.util.SortedMap.class, true, true, false, false)); put("java.util.SortedMap", new SandboxClass<SortedMap>(java.util.SortedMap.class, true, true, false, false));
put("java.util.ListIterator", new SandboxClass<ListIterator>(java.util.ListIterator.class, true, true, false, false)); put("java.util.ListIterator", new SandboxClass<ListIterator>(java.util.ListIterator.class, true, true, false, false));
put("java.lang.IllegalAccessException", new SandboxClass<IllegalAccessException>(java.lang.IllegalAccessException.class, true, true, false, false)); put("java.lang.IllegalAccessException", new SandboxClass<IllegalAccessException>(java.lang.IllegalAccessException.class, true, true, false, false));
put("java.util.regex.Pattern", new SandboxClass<Pattern>(java.util.regex.Pattern.class, true, true, false, false)); put("java.util.regex.Pattern", new SandboxClass<Pattern>(java.util.regex.Pattern.class, true, true, false, false));
put("java.lang.StrictMath", new SandboxClass<StrictMath>(java.lang.StrictMath.class, true, false, false, false)); put("java.lang.StrictMath", new SandboxClass<StrictMath>(java.lang.StrictMath.class, true, false, false, false));
put("java.lang.NumberFormatException", new SandboxClass<NumberFormatException>(java.lang.NumberFormatException.class, true, true, false, false)); put("java.lang.NumberFormatException", new SandboxClass<NumberFormatException>(java.lang.NumberFormatException.class, true, true, false, false));
put("java.lang.IllegalArgumentException", new SandboxClass<IllegalArgumentException>(java.lang.IllegalArgumentException.class, true, true, false, false)); put("java.lang.IllegalArgumentException", new SandboxClass<IllegalArgumentException>(java.lang.IllegalArgumentException.class, true, true, false, false));
put("java.util.Date", new SandboxClass<Date>(java.util.Date.class, true, true, false, false)); put("java.util.Date", new SandboxClass<Date>(java.util.Date.class, true, true, false, false));
put("java.util.TimeZone", new SandboxClass<TimeZone>(java.util.TimeZone.class, true, true, false, false)); put("java.util.TimeZone", new SandboxClass<TimeZone>(java.util.TimeZone.class, true, true, false, false));
put("java.util.regex.Matcher", new SandboxClass<Matcher>(java.util.regex.Matcher.class, true, true, false, false)); put("java.util.regex.Matcher", new SandboxClass<Matcher>(java.util.regex.Matcher.class, true, true, false, false));
put("java.util.regex.MathResult", new SandboxClass<MatchResult>(java.util.regex.MatchResult.class, true, true, false, false)); put("java.util.regex.MathResult", new SandboxClass<MatchResult>(java.util.regex.MatchResult.class, true, true, false, false));
put("java.util.Random", new SandboxClass<Random>(java.util.Random.class, true, true, false, false)); put("java.util.Random", new SandboxClass<Random>(java.util.Random.class, true, true, false, false));
put("java.util.concurrent.atomic.AtomicLong", new SandboxClass<AtomicLong>(java.util.concurrent.atomic.AtomicLong.class, true, true, false, false)); put("java.util.concurrent.atomic.AtomicLong", new SandboxClass<AtomicLong>(java.util.concurrent.atomic.AtomicLong.class, true, true, false, false));
put("java.lang.InternalError", new SandboxClass<InternalError>(java.lang.InternalError.class, true, true, false, false)); put("java.lang.InternalError", new SandboxClass<InternalError>(java.lang.InternalError.class, true, true, false, false));
put("java.lang.NoSuchFieldException", new SandboxClass<NoSuchFieldException>(java.lang.NoSuchFieldException.class, true, true, false, false)); put("java.lang.NoSuchFieldException", new SandboxClass<NoSuchFieldException>(java.lang.NoSuchFieldException.class, true, true, false, false));
put("java.lang.InstantiationException", new SandboxClass<InstantiationException>(java.lang.InstantiationException.class, true, true, false, false)); put("java.lang.InstantiationException", new SandboxClass<InstantiationException>(java.lang.InstantiationException.class, true, true, false, false));
put("java.lang.ArrayIndexOutOfBoundsException", new SandboxClass<ArrayIndexOutOfBoundsException>(java.lang.ArrayIndexOutOfBoundsException.class, true, true, false, false)); put("java.lang.ArrayIndexOutOfBoundsException", new SandboxClass<ArrayIndexOutOfBoundsException>(java.lang.ArrayIndexOutOfBoundsException.class, true, true, false, false));
put("java.lang.IllegalAccessError", new SandboxClass<IllegalAccessError>(java.lang.IllegalAccessError.class, true, true, false, false)); put("java.lang.IllegalAccessError", new SandboxClass<IllegalAccessError>(java.lang.IllegalAccessError.class, true, true, false, false));
put("java.lang.CloneNotSupportedException", new SandboxClass<CloneNotSupportedException>(java.lang.CloneNotSupportedException.class, true, true, false, false)); put("java.lang.CloneNotSupportedException", new SandboxClass<CloneNotSupportedException>(java.lang.CloneNotSupportedException.class, true, true, false, false));
put("java.lang.UnsatisfiedLinkError", new SandboxClass<UnsatisfiedLinkError>(java.lang.UnsatisfiedLinkError.class, true, true, false, false)); put("java.lang.UnsatisfiedLinkError", new SandboxClass<UnsatisfiedLinkError>(java.lang.UnsatisfiedLinkError.class, true, true, false, false));
put("java.util.Calendar", new SandboxClass<Calendar>(java.util.Calendar.class, true, true, false, false)); put("java.util.Calendar", new SandboxClass<Calendar>(java.util.Calendar.class, true, true, false, false));
put("java.util.GregorianCalendar", new SandboxClass<GregorianCalendar>(java.util.GregorianCalendar.class, true, true, false, false)); put("java.util.GregorianCalendar", new SandboxClass<GregorianCalendar>(java.util.GregorianCalendar.class, true, true, false, false));
put("java.util.Currency", new SandboxClass<Currency>(java.util.Currency.class, true, true, false, false)); put("java.util.Currency", new SandboxClass<Currency>(java.util.Currency.class, true, true, false, false));
put("java.math.RoundingMode", new SandboxClass<RoundingMode>(java.math.RoundingMode.class, true, true, false, false)); put("java.math.RoundingMode", new SandboxClass<RoundingMode>(java.math.RoundingMode.class, true, true, false, false));
put("java.lang.StringIndexOutOfBoundsException", new SandboxClass<StringIndexOutOfBoundsException>(java.lang.StringIndexOutOfBoundsException.class, true, true, false, false)); put("java.lang.StringIndexOutOfBoundsException", new SandboxClass<StringIndexOutOfBoundsException>(java.lang.StringIndexOutOfBoundsException.class, true, true, false, false));
put("java.math.BigInteger", new SandboxClass<BigInteger>(java.math.BigInteger.class, true, true, false, false)); put("java.math.BigInteger", new SandboxClass<BigInteger>(java.math.BigInteger.class, true, true, false, false));
put("java.util.EnumMap", new SandboxClass<EnumMap>(java.util.EnumMap.class, true, true, false, false)); put("java.util.EnumMap", new SandboxClass<EnumMap>(java.util.EnumMap.class, true, true, false, false));
}}; }};
public static Object getInstance(String clazz, Object... constructorParams) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { public static Object getInstance(String clazz, Object... constructorParams) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
SandboxClass<?> sc=qualifiedClasses.get(clazz); SandboxClass<?> sc=qualifiedClasses.get(clazz);
return sc.getInstance(constructorParams); return sc.getInstance(constructorParams);
} }
public static Object invokeStatic(String clazz, String method, public static Object invokeStatic(String clazz, String method,
Object... parameters) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Object... parameters) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
SandboxClass<?> sc=qualifiedClasses.get(clazz); SandboxClass<?> sc=qualifiedClasses.get(clazz);
return sc.invokeStatic(method, parameters); return sc.invokeStatic(method, parameters);
} }
} }

View File

@ -1,68 +1,68 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class LiquidFlowingNodeParams extends DefaultNodeParams implements public class LiquidFlowingNodeParams extends DefaultNodeParams implements
LiquidNodeParams { LiquidNodeParams {
@Override @Override
public double calcFlowRate(NodePosition pos) { public double calcFlowRate(NodePosition pos) {
return 1; return 1;
} }
@Override @Override
public void onLiquidFlow(NodePosition pos) { public void onLiquidFlow(NodePosition pos) {
// pass // pass
} }
@Override @Override
public double calcDrainRate(NodePosition pos) { public double calcDrainRate(NodePosition pos) {
return 1; return 1;
} }
@Override @Override
public boolean shouldFill(int contacting, int flowing) { public boolean shouldFill(int contacting, int flowing) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return (contacting>=2); return (contacting>=2);
} }
@Override @Override
public double jumpOffHeight(Player player) { public double jumpOffHeight(Player player) {
return 1.125; return 1.125;
} }
@Override @Override
public double calcWalkSpeed(Player player) { public double calcWalkSpeed(Player player) {
return 0.6; return 0.6;
} }
@Override @Override
public double calcSprintSpeed(Player player) { public double calcSprintSpeed(Player player) {
return 0.8; return 0.8;
} }
@Override @Override
public double calcSinkIn(Player player, double fallheight) { public double calcSinkIn(Player player, double fallheight) {
return 0.4; return 0.4;
} }
@Override @Override
public double calcSinkEscape(Player player, double fallheight) { public double calcSinkEscape(Player player, double fallheight) {
return 1; return 1;
} }
@Override @Override
public double calcBounceHeight(Player player, double fallheight) { public double calcBounceHeight(Player player, double fallheight) {
return 0; return 0;
} }
@Override @Override
public double calcFallDamage(Player player, double height) { public double calcFallDamage(Player player, double height) {
return 0; return 0;
} }
@Override @Override
public boolean shouldContinueFall(Player player, double height) { public boolean shouldContinueFall(Player player, double height) {
return false; return false;
} }
} }

View File

@ -1,15 +1,15 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class LiquidNode extends MapNode { public class LiquidNode extends MapNode {
public final LiquidNodeParams nodeParams; public final LiquidNodeParams nodeParams;
public LiquidNode[] liquidLevels = new LiquidNode[8]; public LiquidNode[] liquidLevels = new LiquidNode[8];
public int level; public int level;
public LiquidNode(LiquidNodeParams nodeparams, String texture, public LiquidNode(LiquidNodeParams nodeparams, String texture,
String nodeName, String userFacingName, int lightEmission) { String nodeName, String userFacingName, int lightEmission) {
super(nodeparams, texture, nodeName, userFacingName, lightEmission); super(nodeparams, texture, nodeName, userFacingName, lightEmission);
this.nodeParams = nodeparams; this.nodeParams = nodeparams;
} }
} }

View File

@ -1,40 +1,40 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public interface LiquidNodeParams extends INodeParams { public interface LiquidNodeParams extends INodeParams {
/** /**
* Calculates the liquid output from this liquid * Calculates the liquid output from this liquid
* *
* @param pos * @param pos
* The NodePosition of the liquid's location. * The NodePosition of the liquid's location.
* @return A double representing the flow rate, in a fully filled node in 1 * @return A double representing the flow rate, in a fully filled node in 1
* second for 1.0 * second for 1.0
*/ */
public double calcFlowRate(NodePosition pos); public double calcFlowRate(NodePosition pos);
/** /**
* Calculate how quickly this liquid should disappear. For * Calculate how quickly this liquid should disappear. For
* flowRate=drainRate the liquid will be effectively finite. * flowRate=drainRate the liquid will be effectively finite.
* *
* @param pos * @param pos
* @return * @return
*/ */
public double calcDrainRate(NodePosition pos); public double calcDrainRate(NodePosition pos);
/** /**
* Callback for liquid flow. * Callback for liquid flow.
* *
* @param pos * @param pos
* Position. * Position.
*/ */
public void onLiquidFlow(NodePosition pos); public void onLiquidFlow(NodePosition pos);
/** /**
* Tell if a liquid area should fill with source(level 0) * Tell if a liquid area should fill with source(level 0)
* @param contacting Number of sources contacting. * @param contacting Number of sources contacting.
* @return Boolean, true if it should. * @return Boolean, true if it should.
*/ */
public boolean shouldFill(int contactingSources, int contactingFlowings); public boolean shouldFill(int contactingSources, int contactingFlowings);
} }

View File

@ -1,68 +1,68 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class LiquidSourceNodeParams extends DefaultNodeParams implements public class LiquidSourceNodeParams extends DefaultNodeParams implements
LiquidNodeParams { LiquidNodeParams {
@Override @Override
public double calcFlowRate(NodePosition pos) { public double calcFlowRate(NodePosition pos) {
return 1; return 1;
} }
@Override @Override
public void onLiquidFlow(NodePosition pos) { public void onLiquidFlow(NodePosition pos) {
// pass // pass
} }
@Override @Override
public double calcDrainRate(NodePosition pos) { public double calcDrainRate(NodePosition pos) {
return 0; return 0;
} }
@Override @Override
public boolean shouldFill(int contacting, int flowing) { public boolean shouldFill(int contacting, int flowing) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
@Override @Override
public double jumpOffHeight(Player player) { public double jumpOffHeight(Player player) {
return 1.125; return 1.125;
} }
@Override @Override
public double calcWalkSpeed(Player player) { public double calcWalkSpeed(Player player) {
return 0.6; return 0.6;
} }
@Override @Override
public double calcSprintSpeed(Player player) { public double calcSprintSpeed(Player player) {
return 0.8; return 0.8;
} }
@Override @Override
public double calcSinkIn(Player player, double fallheight) { public double calcSinkIn(Player player, double fallheight) {
return 0.4; return 0.4;
} }
@Override @Override
public double calcSinkEscape(Player player, double fallheight) { public double calcSinkEscape(Player player, double fallheight) {
return 1; return 1;
} }
@Override @Override
public double calcBounceHeight(Player player, double fallheight) { public double calcBounceHeight(Player player, double fallheight) {
return 0; return 0;
} }
@Override @Override
public double calcFallDamage(Player player, double height) { public double calcFallDamage(Player player, double height) {
return 0; return 0;
} }
@Override @Override
public boolean shouldContinueFall(Player player, double height) { public boolean shouldContinueFall(Player player, double height) {
return false; return false;
} }
} }

View File

@ -1,132 +1,132 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import net.mosstest.servercore.ItemManager; import net.mosstest.servercore.ItemManager;
public class MapNode { public class MapNode {
private short nodeId = 0; private short nodeId = 0;
public final transient INodeParams nodeparams; public final transient INodeParams nodeparams;
public final transient String texture; public final transient String texture;
public String nodeName; public String nodeName;
public String userFacingName; public String userFacingName;
public int lightEmission; public int lightEmission;
public MossItem dropItem; public MossItem dropItem;
public boolean isBuildableTo = true; public boolean isBuildableTo = true;
public DrawType drawType = DrawType.DRAW_BLOCK; public DrawType drawType = DrawType.DRAW_BLOCK;
public float boxOriginX = 0, boxOriginY = 0, boxOriginZ = 0; public float boxOriginX = 0, boxOriginY = 0, boxOriginZ = 0;
/** /**
* Each of these is 0.5 for the unit box, since each vertex is +/-0.5 from * Each of these is 0.5 for the unit box, since each vertex is +/-0.5 from
* the origin in each dimension. * the origin in each dimension.
*/ */
public float lengthX = 0.5f, lengthY = 0.5f, lengthZ = 0.5f; public float lengthX = 0.5f, lengthY = 0.5f, lengthZ = 0.5f;
public MapNode(INodeParams nodeparams, String texture, String nodeName, public MapNode(INodeParams nodeparams, String texture, String nodeName,
String userFacingName, int lightEmission) { String userFacingName, int lightEmission) {
this.nodeparams = nodeparams; this.nodeparams = nodeparams;
this.texture = texture; this.texture = texture;
this.nodeName = nodeName; this.nodeName = nodeName;
this.userFacingName = userFacingName; this.userFacingName = userFacingName;
this.lightEmission = lightEmission; this.lightEmission = lightEmission;
this.dropItem = ItemManager.getForNode(this); this.dropItem = ItemManager.getForNode(this);
} }
public void setByBounds(float x1, float x2, float y1, float y2, float z1, public void setByBounds(float x1, float x2, float y1, float y2, float z1,
float z2) { float z2) {
this.boxOriginX = (x1 + x2) / 2; this.boxOriginX = (x1 + x2) / 2;
this.boxOriginY = (y1 + y2) / 2; this.boxOriginY = (y1 + y2) / 2;
this.boxOriginZ = (z1 + z2) / 2; this.boxOriginZ = (z1 + z2) / 2;
this.lengthX = Math.abs(x2 - x1); this.lengthX = Math.abs(x2 - x1);
this.lengthY = Math.abs(y2 - y1); this.lengthY = Math.abs(y2 - y1);
this.lengthZ = Math.abs(z2 - z1); this.lengthZ = Math.abs(z2 - z1);
} }
public void setBySize(float originX, float originY, float originZ, public void setBySize(float originX, float originY, float originZ,
float lengthX, float lengthY, float lengthZ) { float lengthX, float lengthY, float lengthZ) {
this.boxOriginX = originX; this.boxOriginX = originX;
this.boxOriginY = originY; this.boxOriginY = originY;
this.boxOriginZ = originZ; this.boxOriginZ = originZ;
this.lengthX = lengthX; this.lengthX = lengthX;
this.lengthY = lengthY; this.lengthY = lengthY;
this.lengthZ = lengthZ; this.lengthZ = lengthZ;
} }
public MapNode(String textures, String nodeName, String userFacingName, public MapNode(String textures, String nodeName, String userFacingName,
int lightEmission) { int lightEmission) {
this.nodeparams = new DefaultNodeParams(); this.nodeparams = new DefaultNodeParams();
this.texture = textures; this.texture = textures;
this.nodeName = nodeName; this.nodeName = nodeName;
this.userFacingName = userFacingName; this.userFacingName = userFacingName;
this.lightEmission = lightEmission; this.lightEmission = lightEmission;
this.dropItem = ItemManager.getForNode(this); this.dropItem = ItemManager.getForNode(this);
} }
public short getNodeId() { public short getNodeId() {
return this.nodeId; return this.nodeId;
} }
/** /**
* Sets node ID. Scripts should not call this except under special * Sets node ID. Scripts should not call this except under special
* circumstances. * circumstances.
* *
* @param nodeId * @param nodeId
*/ */
public void setNodeId(short nodeId) { public void setNodeId(short nodeId) {
this.nodeId = nodeId; this.nodeId = nodeId;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + this.nodeId; result = prime * result + this.nodeId;
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof MapNode)) { if (!(obj instanceof MapNode)) {
return false; return false;
} }
MapNode other = (MapNode) obj; MapNode other = (MapNode) obj;
if (this.nodeId != other.nodeId) { if (this.nodeId != other.nodeId) {
return false; return false;
} }
return true; return true;
} }
protected MapNode() { protected MapNode() {
this.texture = null; this.texture = null;
this.nodeparams = null; this.nodeparams = null;
} }
public enum DrawType { public enum DrawType {
/** /**
* Standard appearance for blocks * Standard appearance for blocks
*/ */
DRAW_BLOCK, DRAW_BLOCK,
/** /**
* Drawtype for liquids * Drawtype for liquids
*/ */
DRAW_LIQUID, DRAW_LIQUID,
/** /**
* Drawtype for plantlike materials. In this draw, two planes with the * Drawtype for plantlike materials. In this draw, two planes with the
* item texture(which should be symmetrical for this) are drawn * item texture(which should be symmetrical for this) are drawn
* intersecting in an X-pattern. * intersecting in an X-pattern.
*/ */
DRAW_PLANTLIKE, DRAW_PLANTLIKE,
/** /**
* Do not draw the node at all. * Do not draw the node at all.
*/ */
DRAW_NONE DRAW_NONE
} }
} }

View File

@ -1,37 +1,37 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import net.mosstest.servercore.ScriptSandboxBorderToken; import net.mosstest.servercore.ScriptSandboxBorderToken;
public class MossEvent { public class MossEvent {
public MossEvent(EvtType type, Player actor, NodePosition pos, MapNode nodeBefore, MapNode nodeAfter, public MossEvent(EvtType type, Player actor, NodePosition pos, MapNode nodeBefore, MapNode nodeAfter,
Entity recvEntity, MossFormspec fspec, MossInventoryAction action, double damage, Entity recvEntity, MossFormspec fspec, MossInventoryAction action, double damage,
String initiatingMessage, ScriptSandboxBorderToken tok) { String initiatingMessage, ScriptSandboxBorderToken tok) {
if (!(tok instanceof ScriptSandboxBorderToken) || tok == null) if (!(tok instanceof ScriptSandboxBorderToken) || tok == null)
throw new SecurityException("Attempt to access controlled resources in the script DMZ."); throw new SecurityException("Attempt to access controlled resources in the script DMZ.");
this.type = type; this.type = type;
this.actor = actor; this.actor = actor;
this.pos=pos; this.pos=pos;
this.nodeBefore = nodeBefore; this.nodeBefore = nodeBefore;
this.nodeAfter = nodeAfter; this.nodeAfter = nodeAfter;
this.recvEntity = recvEntity; this.recvEntity = recvEntity;
this.fspec = fspec; this.fspec = fspec;
this.damage=damage; this.damage=damage;
this.action = action; this.action = action;
this.initiatingMessage = initiatingMessage; this.initiatingMessage = initiatingMessage;
} }
public enum EvtType { public enum EvtType {
EVT_DIEPLAYER, EVT_DIGNODE, EVT_GENERATE, EVT_JOINPLAYER, EVT_QUITPLAYER, EVT_NEWPLAYER, EVT_PLACENODE, EVT_FSPEC_OPEN, EVT_FSPEC_SUBMIT, EVT_FSPEC_INVACTION, EVT_THREADSTOP, EVT_ENTITY_PUNCH, EVT_ENTITY_DEATH, EVT_CHATMESSAGE, EVT_SHUTDOWN, EVT_CHATCOMMAND, EVT_NODEMOVE, EVT_PLAYERDAMAGE EVT_DIEPLAYER, EVT_DIGNODE, EVT_GENERATE, EVT_JOINPLAYER, EVT_QUITPLAYER, EVT_NEWPLAYER, EVT_PLACENODE, EVT_FSPEC_OPEN, EVT_FSPEC_SUBMIT, EVT_FSPEC_INVACTION, EVT_THREADSTOP, EVT_ENTITY_PUNCH, EVT_ENTITY_DEATH, EVT_CHATMESSAGE, EVT_SHUTDOWN, EVT_CHATCOMMAND, EVT_NODEMOVE, EVT_PLAYERDAMAGE
} }
public final MossEvent.EvtType type; public final MossEvent.EvtType type;
public final Player actor; // Player no longer extends entity public final Player actor; // Player no longer extends entity
public final NodePosition pos; public final NodePosition pos;
public final MapNode nodeBefore; public final MapNode nodeBefore;
public final MapNode nodeAfter; public final MapNode nodeAfter;
public final Entity recvEntity; public final Entity recvEntity;
public final double damage; public final double damage;
public final MossFormspec fspec; public final MossFormspec fspec;
public final MossInventoryAction action; public final MossInventoryAction action;
public final String initiatingMessage; public final String initiatingMessage;
} }

View File

@ -1,14 +1,14 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public interface MossEventHandler { public interface MossEventHandler {
/** /**
* Process an event * Process an event
* *
* @param myEvent * @param myEvent
* The event * The event
* @return `true` to skip all future handlers for this event, false to run * @return `true` to skip all future handlers for this event, false to run
* the next handler. * the next handler.
* @throws MossScriptException * @throws MossScriptException
*/ */
boolean processEvent(MossEvent myEvent) throws MossScriptException; boolean processEvent(MossEvent myEvent) throws MossScriptException;
} }

View File

@ -1,9 +1,9 @@
/** /**
* TODO * TODO
*/ */
package net.mosstest.scripting; package net.mosstest.scripting;
public class MossFormspec { public class MossFormspec {
} }

View File

@ -1,36 +1,36 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class MossInventory { public class MossInventory {
final int maxStackSize; final int maxStackSize;
final MossItem.Stack[][] stacks; final MossItem.Stack[][] stacks;
public MossInventory(int maxStackSize, int rows, int cols) { public MossInventory(int maxStackSize, int rows, int cols) {
this.maxStackSize = maxStackSize; this.maxStackSize = maxStackSize;
stacks = new MossItem.Stack[rows][cols]; stacks = new MossItem.Stack[rows][cols];
} }
public synchronized double addItem(MossItem.Stack stack) { public synchronized double addItem(MossItem.Stack stack) {
double added = 0; double added = 0;
double maxAddable = stack.item.mayStack ? maxStackSize : 1; double maxAddable = stack.item.mayStack ? maxStackSize : 1;
for (int row = 0; row < stacks.length; row++) { for (int row = 0; row < stacks.length; row++) {
for (int col = 0; col < stacks[row].length; col++) { for (int col = 0; col < stacks[row].length; col++) {
if (stacks[row][col] == null) { if (stacks[row][col] == null) {
double addedThisRound = Math.min(stack.amount, maxAddable); double addedThisRound = Math.min(stack.amount, maxAddable);
added += addedThisRound; added += addedThisRound;
stacks[row][col] = new MossItem.Stack(stack.item, addedThisRound); stacks[row][col] = new MossItem.Stack(stack.item, addedThisRound);
} }
else if (stacks[row][col].item.equals(stack.item)){ else if (stacks[row][col].item.equals(stack.item)){
double addedThisRound = Math.min(stack.amount, maxAddable-stacks[row][col].amount); double addedThisRound = Math.min(stack.amount, maxAddable-stacks[row][col].amount);
added += addedThisRound; added += addedThisRound;
stacks[row][col].amount += addedThisRound; stacks[row][col].amount += addedThisRound;
} }
if(added>=stack.amount) return added; if(added>=stack.amount) return added;
} }
} }
return added; return added;
} }
//TODO remove item //TODO remove item
} }

View File

@ -1,12 +1,12 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class MossInventoryAction { public class MossInventoryAction {
MossInventory from; MossInventory from;
MossInventory to; MossInventory to;
MossItem.Stack moved; MossItem.Stack moved;
public void acceptAsStated() { public void acceptAsStated() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -1,62 +1,62 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import net.mosstest.servercore.MossFile; import net.mosstest.servercore.MossFile;
public class MossItem { public class MossItem {
public MossItem(MossFile invTex, MossFile wieldTex, double invWeight, public MossItem(MossFile invTex, MossFile wieldTex, double invWeight,
boolean mayStack, String displayName, String technicalName) { boolean mayStack, String displayName, String technicalName) {
this.invTex = invTex; this.invTex = invTex;
this.wieldTex = wieldTex; this.wieldTex = wieldTex;
this.invWeight = invWeight; this.invWeight = invWeight;
this.mayStack = mayStack; this.mayStack = mayStack;
this.displayName = displayName; this.displayName = displayName;
this.technicalName = technicalName; this.technicalName = technicalName;
} }
final MossFile invTex; final MossFile invTex;
final MossFile wieldTex; final MossFile wieldTex;
final double invWeight; final double invWeight;
boolean mayStack; boolean mayStack;
final String displayName; final String displayName;
final String technicalName; final String technicalName;
public static class Stack { public static class Stack {
public Stack(MossItem item, double amount) { public Stack(MossItem item, double amount) {
this.item = item; this.item = item;
this.amount = amount; this.amount = amount;
} }
final MossItem item; final MossItem item;
/** /**
* If amount is not an integer then it is a stack with wear. Once zero * If amount is not an integer then it is a stack with wear. Once zero
* it is no longer a stack. * it is no longer a stack.
*/ */
double amount; double amount;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result result = prime * result
+ ((technicalName == null) ? 0 : technicalName.hashCode()); + ((technicalName == null) ? 0 : technicalName.hashCode());
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
MossItem other = (MossItem) obj; MossItem other = (MossItem) obj;
if (technicalName == null) { if (technicalName == null) {
if (other.technicalName != null) if (other.technicalName != null)
return false; return false;
} else if (!technicalName.equals(other.technicalName)) } else if (!technicalName.equals(other.technicalName))
return false; return false;
return true; return true;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class MossScriptException extends Exception { public class MossScriptException extends Exception {
} }

View File

@ -1,95 +1,95 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
public class NodePosition { public class NodePosition {
public final byte xl, yl, zl; public final byte xl, yl, zl;
public final Position chunk; public final Position chunk;
public NodePosition(int x, int y, int z, int realm, byte xl, byte yl, public NodePosition(int x, int y, int z, int realm, byte xl, byte yl,
byte zl) { byte zl) {
chunk = new Position(x, y, z, realm); chunk = new Position(x, y, z, realm);
this.xl = xl; this.xl = xl;
this.yl = yl; this.yl = yl;
this.zl = zl; this.zl = zl;
} }
public NodePosition(byte[] bytes) throws IOException { public NodePosition(byte[] bytes) throws IOException {
super(); super();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bis); DataInputStream dis = new DataInputStream(bis);
this.chunk = new Position(dis.readInt(), dis.readInt(), dis.readInt(), this.chunk = new Position(dis.readInt(), dis.readInt(), dis.readInt(),
dis.readInt()); dis.readInt());
this.xl = dis.readByte(); this.xl = dis.readByte();
this.yl = dis.readByte(); this.yl = dis.readByte();
this.zl = dis.readByte(); this.zl = dis.readByte();
// this.isValid = true; // this.isValid = true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((chunk == null) ? 0 : chunk.hashCode()); result = prime * result + ((chunk == null) ? 0 : chunk.hashCode());
result = prime * result + xl; result = prime * result + xl;
result = prime * result + yl; result = prime * result + yl;
result = prime * result + zl; result = prime * result + zl;
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof NodePosition)) { if (!(obj instanceof NodePosition)) {
return false; return false;
} }
NodePosition other = (NodePosition) obj; NodePosition other = (NodePosition) obj;
if (chunk == null) { if (chunk == null) {
if (other.chunk != null) { if (other.chunk != null) {
return false; return false;
} }
} else if (!chunk.equals(other.chunk)) { } else if (!chunk.equals(other.chunk)) {
return false; return false;
} }
if (xl != other.xl) { if (xl != other.xl) {
return false; return false;
} }
if (yl != other.yl) { if (yl != other.yl) {
return false; return false;
} }
if (zl != other.zl) { if (zl != other.zl) {
return false; return false;
} }
return true; return true;
} }
public byte[] toBytes() { public byte[] toBytes() {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos); DataOutputStream dos = new DataOutputStream(bos);
try { try {
bos.write(chunk.toBytes()); bos.write(chunk.toBytes());
dos.writeByte(this.xl); dos.writeByte(this.xl);
dos.writeByte(this.yl); dos.writeByte(this.yl);
dos.writeByte(this.zl); dos.writeByte(this.zl);
dos.flush(); dos.flush();
bos.flush(); bos.flush();
return bos.toByteArray(); return bos.toByteArray();
} catch (IOException e) { } catch (IOException e) {
// Auto-generated catch block // Auto-generated catch block
} }
return new byte[] {}; return new byte[] {};
} }
} }

View File

@ -1,36 +1,36 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import java.util.HashMap; import java.util.HashMap;
public class Player { public class Player {
private HashMap<String, MossInventory> inventories=new HashMap<>(); private HashMap<String, MossInventory> inventories=new HashMap<>();
public final String name; public final String name;
public volatile double xpos; public volatile double xpos;
public volatile double ypos; public volatile double ypos;
public volatile double zpos; public volatile double zpos;
public volatile double oldx; public volatile double oldx;
public volatile double oldy; public volatile double oldy;
public volatile double oldz; public volatile double oldz;
public volatile long lastAnticheatMillis; public volatile long lastAnticheatMillis;
/** /**
* Object to be synchronized on for * Object to be synchronized on for
*/ */
public final Object antiCheatDataLock= new Object(); public final Object antiCheatDataLock= new Object();
private Player(String name, int maxHealth) { private Player(String name, int maxHealth) {
this.name=name; this.name=name;
this.inventories.put("default", new MossInventory(96, 8, 6)); this.inventories.put("default", new MossInventory(96, 8, 6));
} }
public MossInventory createInventory(String name, int rows, int cols, int maxStack) { public MossInventory createInventory(String name, int rows, int cols, int maxStack) {
MossInventory inv=new MossInventory(maxStack, rows, cols); MossInventory inv=new MossInventory(maxStack, rows, cols);
this.inventories.put(name,inv); this.inventories.put(name,inv);
return inv; return inv;
} }
public void respawn() { public void respawn() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -1,111 +1,111 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
public class Position { public class Position {
public int x; public int x;
public int y; public int y;
public int z; public int z;
public int realm; public int realm;
transient boolean isValid = true; transient boolean isValid = true;
public Position(int x, int y, int z, int realm) { public Position(int x, int y, int z, int realm) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
this.realm = realm; this.realm = realm;
this.isValid = true; this.isValid = true;
} }
public Position(byte[] bytes) throws IOException { public Position(byte[] bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bis); DataInputStream dis = new DataInputStream(bis);
this.x = dis.readInt(); this.x = dis.readInt();
this.y = dis.readInt(); this.y = dis.readInt();
this.z = dis.readInt(); this.z = dis.readInt();
this.realm = dis.readInt(); this.realm = dis.readInt();
this.isValid = true; this.isValid = true;
} }
public Position() { public Position() {
this.isValid = false; this.isValid = false;
} }
static final long serialVersionUID = 1128980133700001337L; static final long serialVersionUID = 1128980133700001337L;
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (!(obj instanceof Position)) { if (!(obj instanceof Position)) {
return false; return false;
} }
Position other = (Position) obj; Position other = (Position) obj;
if (this.realm != other.realm) { if (this.realm != other.realm) {
return false; return false;
} }
if (this.x != other.x) { if (this.x != other.x) {
return false; return false;
} }
if (this.y != other.y) { if (this.y != other.y) {
return false; return false;
} }
if (this.z != other.z) { if (this.z != other.z) {
return false; return false;
} }
return true; return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + this.realm; result = prime * result + this.realm;
result = prime * result + this.x; result = prime * result + this.x;
result = prime * result + this.y; result = prime * result + this.y;
result = prime * result + this.z; result = prime * result + this.z;
return result; return result;
} }
public byte[] toBytes() { public byte[] toBytes() {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos); DataOutputStream dos = new DataOutputStream(bos);
try { try {
dos.writeInt(this.x); dos.writeInt(this.x);
dos.writeInt(this.y); dos.writeInt(this.y);
dos.writeInt(this.z); dos.writeInt(this.z);
dos.writeInt(this.realm); dos.writeInt(this.realm);
dos.flush(); dos.flush();
bos.flush(); bos.flush();
return bos.toByteArray(); return bos.toByteArray();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
this.isValid = false; this.isValid = false;
} }
return new byte[] {}; return new byte[] {};
} }
public int getX() { public int getX() {
return this.x; return this.x;
} }
public int getY() { public int getY() {
return this.y; return this.y;
} }
public int getZ() { public int getZ() {
return this.z; return this.z;
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public interface ScriptRunnable { public interface ScriptRunnable {
public void run(); public void run();
} }

View File

@ -1,152 +1,152 @@
package net.mosstest.scripting; package net.mosstest.scripting;
import static org.fusesource.leveldbjni.JniDBFactory.asString; import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.bytes; import static org.fusesource.leveldbjni.JniDBFactory.bytes;
import static org.fusesource.leveldbjni.JniDBFactory.factory; import static org.fusesource.leveldbjni.JniDBFactory.factory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ArrayUtils;
import org.iq80.leveldb.DB; import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options; import org.iq80.leveldb.Options;
public class ScriptableDatabase { public class ScriptableDatabase {
File baseDir; File baseDir;
public ScriptableDatabase(File baseDir) { public ScriptableDatabase(File baseDir) {
this.baseDir = baseDir; this.baseDir = baseDir;
} }
public DBase getDb(String name) throws IOException { public DBase getDb(String name) throws IOException {
if (!name.matches("[a-zA-Z]{1,32}")) { //$NON-NLS-1$ if (!name.matches("[a-zA-Z]{1,32}")) { //$NON-NLS-1$
throw new IllegalArgumentException("Invalid database name."); throw new IllegalArgumentException("Invalid database name.");
} }
Options options = new Options(); Options options = new Options();
options.createIfMissing(true); options.createIfMissing(true);
return new DBase(factory.open(new File(this.baseDir, "sc_" + name return new DBase(factory.open(new File(this.baseDir, "sc_" + name
+ ".db"), options), name); + ".db"), options), name);
} }
public class DBase { public class DBase {
// this class will contain a database that scripts may access. // this class will contain a database that scripts may access.
private final DB innerDb; private final DB innerDb;
DBase(DB innerDb, String name) { DBase(DB innerDb, String name) {
this.innerDb = innerDb; this.innerDb = innerDb;
} }
/** /**
* Get a piece of string data with a string key, or <code>null</code> if * Get a piece of string data with a string key, or <code>null</code> if
* the datum cannot be found. String keys are exclusive from all other * the datum cannot be found. String keys are exclusive from all other
* key types. * key types.
* *
* @param key * @param key
* @return A string representing the stored data. * @return A string representing the stored data.
*/ */
public String getDatum(String key) { public String getDatum(String key) {
byte[] keyBytes = bytes("string::" + key); //$NON-NLS-1$ byte[] keyBytes = bytes("string::" + key); //$NON-NLS-1$
byte[] dataBytes = this.innerDb.get(keyBytes); byte[] dataBytes = this.innerDb.get(keyBytes);
return (dataBytes == null) ? null : asString(dataBytes); return (dataBytes == null) ? null : asString(dataBytes);
} }
/** /**
* Put a datum with a generic string key, overwriting as necessary. * Put a datum with a generic string key, overwriting as necessary.
* *
* @param key * @param key
* The string key. * The string key.
* @param data * @param data
* The data to put. * The data to put.
*/ */
public void putDatum(String key, String data) { public void putDatum(String key, String data) {
this.innerDb.put(bytes("string::" + key), bytes(data)); //$NON-NLS-1$ this.innerDb.put(bytes("string::" + key), bytes(data)); //$NON-NLS-1$
} }
/** /**
* Get a piece of string data with a position and string key, or * Get a piece of string data with a position and string key, or
* <code>null</code> if the datum cannot be found. Position keys are * <code>null</code> if the datum cannot be found. Position keys are
* exclusive from all other key types. * exclusive from all other key types.
* *
* @param key * @param key
* @return The found data. * @return The found data.
*/ */
public String getPositionDatum(NodePosition pos, String key) { public String getPositionDatum(NodePosition pos, String key) {
byte[] keyBytes = ArrayUtils.addAll(bytes("npos::"), //$NON-NLS-1$ byte[] keyBytes = ArrayUtils.addAll(bytes("npos::"), //$NON-NLS-1$
ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$ ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$
byte[] dataBytes = this.innerDb.get(keyBytes); byte[] dataBytes = this.innerDb.get(keyBytes);
return (dataBytes == null) ? null : asString(dataBytes); return (dataBytes == null) ? null : asString(dataBytes);
} }
/** /**
* Put a datum with a position and string key, overwriting as necessary. * Put a datum with a position and string key, overwriting as necessary.
* *
* @param pos * @param pos
* The position portion of the key. * The position portion of the key.
* @param key * @param key
* The string key. * The string key.
* @param data * @param data
* The data to put. * The data to put.
*/ */
public void putPositionDatum(NodePosition pos, String key, String data) { public void putPositionDatum(NodePosition pos, String key, String data) {
byte[] keyBytes = ArrayUtils.addAll(bytes("npos::"), //$NON-NLS-1$ byte[] keyBytes = ArrayUtils.addAll(bytes("npos::"), //$NON-NLS-1$
ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$ ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$
byte[] dataBytes = bytes(data); byte[] dataBytes = bytes(data);
this.innerDb.put(keyBytes, dataBytes); this.innerDb.put(keyBytes, dataBytes);
} }
/** /**
* Gets a string of data associated with a chunk and string key, or * Gets a string of data associated with a chunk and string key, or
* <code>null</code> if not found. * <code>null</code> if not found.
* *
* @param pos The chunk position. * @param pos The chunk position.
* @param key The string key. * @param key The string key.
* @return The found data. * @return The found data.
*/ */
public String getChunkDatum(Position pos, String key) { public String getChunkDatum(Position pos, String key) {
byte[] keyBytes = ArrayUtils.addAll(bytes("cpos::"), //$NON-NLS-1$ byte[] keyBytes = ArrayUtils.addAll(bytes("cpos::"), //$NON-NLS-1$
ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$ ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$
byte[] dataBytes = this.innerDb.get(keyBytes); byte[] dataBytes = this.innerDb.get(keyBytes);
return (dataBytes == null) ? null : asString(dataBytes); return (dataBytes == null) ? null : asString(dataBytes);
} }
/** /**
* Puts a string of data keyed with a string and chunk. * Puts a string of data keyed with a string and chunk.
* @param pos The chunk position. * @param pos The chunk position.
* @param key The string key. * @param key The string key.
* @param data The data to put. * @param data The data to put.
*/ */
public void putChunkDatum(Position pos, String key, String data) { public void putChunkDatum(Position pos, String key, String data) {
byte[] keyBytes = ArrayUtils.addAll(bytes("cpos::"), //$NON-NLS-1$ byte[] keyBytes = ArrayUtils.addAll(bytes("cpos::"), //$NON-NLS-1$
ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$ ArrayUtils.addAll(pos.toBytes(), bytes("str::" + key))); //$NON-NLS-1$
byte[] dataBytes = bytes(data); byte[] dataBytes = bytes(data);
this.innerDb.put(keyBytes, dataBytes); this.innerDb.put(keyBytes, dataBytes);
} }
/** /**
* Gets a string of data associated with a player and string key, or * Gets a string of data associated with a player and string key, or
* <code>null</code> if not found. * <code>null</code> if not found.
* *
* @param p The player. * @param p The player.
* @param key The string key. * @param key The string key.
* @return The found data. * @return The found data.
*/ */
public String getPlayerDatum(Player p, String key) { public String getPlayerDatum(Player p, String key) {
byte[] keyBytes = bytes("plr::" + p.name + "str::" + key); //$NON-NLS-1$ //$NON-NLS-2$ byte[] keyBytes = bytes("plr::" + p.name + "str::" + key); //$NON-NLS-1$ //$NON-NLS-2$
byte[] dataBytes = this.innerDb.get(keyBytes); byte[] dataBytes = this.innerDb.get(keyBytes);
return (dataBytes == null) ? null : asString(dataBytes); return (dataBytes == null) ? null : asString(dataBytes);
} }
/** /**
* Puts a string of data keyed with a string and player. * Puts a string of data keyed with a string and player.
* @param p The player. * @param p The player.
* @param key The string key. * @param key The string key.
* @param data The data to put. * @param data The data to put.
*/ */
public void putPlayerDatum(Player p, String key, String data) { public void putPlayerDatum(Player p, String key, String data) {
byte[] keyBytes = bytes("plr::" + p.name + "str::" + key); //$NON-NLS-1$ //$NON-NLS-2$ byte[] keyBytes = bytes("plr::" + p.name + "str::" + key); //$NON-NLS-1$ //$NON-NLS-2$
byte[] dataBytes = bytes(data); byte[] dataBytes = bytes(data);
this.innerDb.put(keyBytes, dataBytes); this.innerDb.put(keyBytes, dataBytes);
} }
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.scripting; package net.mosstest.scripting;
public class UtilityClassSandbox { public class UtilityClassSandbox {
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class AntiCheatException extends PlayerSecurityException { public class AntiCheatException extends PlayerSecurityException {
} }

View File

@ -1,22 +1,22 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public class ApplicationLevelNetworkingManager { public class ApplicationLevelNetworkingManager {
ClientNetworkingManager net; ClientNetworkingManager net;
static final int PROTOCOL_VERSION_MAJOR = 1; static final int PROTOCOL_VERSION_MAJOR = 1;
static final int PROTOCOL_VERSION_MINOR = 1; // change for static final int PROTOCOL_VERSION_MINOR = 1; // change for
// backward-compatible // backward-compatible
// changes such as changes // changes such as changes
// in timing that do not // in timing that do not
// break older versions // break older versions
public ApplicationLevelNetworkingManager(ClientNetworkingManager net) { public ApplicationLevelNetworkingManager(ClientNetworkingManager net) {
this.net = net; this.net = net;
} }
public void sendChunkRequest(Position pos) { public void sendChunkRequest(Position pos) {
// TODO create generated code // TODO create generated code
} }
} }

View File

@ -1,8 +1,8 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public enum Biome { public enum Biome {
MG_LAKE, MG_ICE, MG_OCEAN, MG_SWAMP, MG_FOREST, MG_PLAIN, MG_DELTA, MG_DESERT, MG_RAINFOREST, MG_JUNGLE, MG_VOLCANIC, MG_DEFAULT; MG_LAKE, MG_ICE, MG_OCEAN, MG_SWAMP, MG_FOREST, MG_PLAIN, MG_DELTA, MG_DESERT, MG_RAINFOREST, MG_JUNGLE, MG_VOLCANIC, MG_DEFAULT;
public Biome select(double humidity, double elevation, double geo_age, double temperature){ public Biome select(double humidity, double elevation, double geo_age, double temperature){
return MG_DEFAULT; return MG_DEFAULT;
} }
} }

View File

@ -1,18 +1,18 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public class ChunkNotFoundException extends Exception { public class ChunkNotFoundException extends Exception {
long x, y, z; long x, y, z;
public ChunkNotFoundException(long x, long y, long z) { public ChunkNotFoundException(long x, long y, long z) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
} }
public ChunkNotFoundException(Position pos) { public ChunkNotFoundException(Position pos) {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
} }

View File

@ -1,10 +1,10 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class ClientMain { public class ClientMain {
public static void main(String[] args) { public static void main(String[] args) {
// TODO Initialize the client here. // TODO Initialize the client here.
} }
} }

View File

@ -1,40 +1,40 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.IOException; import java.io.IOException;
public class ClientManager { public class ClientManager {
volatile static int state=0; volatile static int state=0;
static final int STATE_DISCONNECTED=0; static final int STATE_DISCONNECTED=0;
static final int STATE_FETCHING_SCRIPTS=1; static final int STATE_FETCHING_SCRIPTS=1;
static final int STATE_FETCHING_TEXTURES=2; static final int STATE_FETCHING_TEXTURES=2;
static final int STATE_FETCHING_MESHES=3; static final int STATE_FETCHING_MESHES=3;
static final int STATE_PLAYABLE=4; static final int STATE_PLAYABLE=4;
static final int STATE_INVALID=-1; static final int STATE_INVALID=-1;
static ClientNetworkingManager net; static ClientNetworkingManager net;
static void init(String host, int port, String username, char[] password) throws IOException{ static void init(String host, int port, String username, char[] password) throws IOException{
net=new ClientNetworkingManager(host, port, EngineSettings.getBool("client_udp", true)); net=new ClientNetworkingManager(host, port, EngineSettings.getBool("client_udp", true));
net.beginConnectHandshake(); net.beginConnectHandshake();
} }
public static ClientNetworkingManager getNetworkingManager() { public static ClientNetworkingManager getNetworkingManager() {
return net; return net;
} }
public static ApplicationLevelNetworkingManager getApplicationLevelNetworkingManager() { public static ApplicationLevelNetworkingManager getApplicationLevelNetworkingManager() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
/** /**
* Show an error screen on the client * Show an error screen on the client
* @param title The title to show * @param title The title to show
* @param msg The message to show * @param msg The message to show
* @param disconnect Whether to disconnect from the current server, if any. * @param disconnect Whether to disconnect from the current server, if any.
*/ */
public static void showErrorScreen(String title, String msg, boolean disconnect) { public static void showErrorScreen(String title, String msg, boolean disconnect) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -1,462 +1,462 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.DatagramSocket; import java.net.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.net.SocketException; import java.net.SocketException;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
public class ClientNetworkingManager { public class ClientNetworkingManager {
// There's a potential DoS attack here but it can only be mounted by the // 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 // server, so you might as well just not use that server. No security
// threat except small client hang, won't fix. // threat except small client hang, won't fix.
protected AtomicBoolean runThreads = new AtomicBoolean(true); protected AtomicBoolean runThreads = new AtomicBoolean(true);
protected Socket bulkDataSocket = new Socket(); protected Socket bulkDataSocket = new Socket();
protected Socket lowLatencyStreamSocket = new Socket(); protected Socket lowLatencyStreamSocket = new Socket();
protected DatagramSocket udpSocket; protected DatagramSocket udpSocket;
protected DataOutputStream bulkDataOut; protected DataOutputStream bulkDataOut;
protected DataOutputStream lowlatencyDataOut; protected DataOutputStream lowlatencyDataOut;
protected DataInputStream bulkDataIn; protected DataInputStream bulkDataIn;
protected DataInputStream lowlatencyDataIn; protected DataInputStream lowlatencyDataIn;
protected boolean udpOn = false; protected boolean udpOn = false;
protected AtomicBoolean fastLinkAckd = new AtomicBoolean(false); protected AtomicBoolean fastLinkAckd = new AtomicBoolean(false);
protected final InetAddress endpoint; protected final InetAddress endpoint;
protected int port; protected int port;
protected AtomicLong lastBulkOut = new AtomicLong(); protected AtomicLong lastBulkOut = new AtomicLong();
protected AtomicLong lastBulkIn = new AtomicLong(); protected AtomicLong lastBulkIn = new AtomicLong();
protected AtomicLong lastFastOut = new AtomicLong(); protected AtomicLong lastFastOut = new AtomicLong();
protected AtomicLong lastFastIn = new AtomicLong(); protected AtomicLong lastFastIn = new AtomicLong();
protected AtomicLong lastUdpOut = new AtomicLong(); protected AtomicLong lastUdpOut = new AtomicLong();
protected AtomicLong lastUdpIn = new AtomicLong(); protected AtomicLong lastUdpIn = new AtomicLong();
/* /*
* Should be no need for another lowlatency queue unless we find poor * Should be no need for another lowlatency queue unless we find poor
* performance * performance
*/ */
public ArrayBlockingQueue<MossNetPacket> packets = new ArrayBlockingQueue<>( public ArrayBlockingQueue<MossNetPacket> packets = new ArrayBlockingQueue<>(
1024); 1024);
protected Thread bulkReadHandler = new Thread(new Runnable() { protected Thread bulkReadHandler = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) { recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
if (ClientNetworkingManager.this.bulkDataIn.readInt() != CommonNetworking.magic) { if (ClientNetworkingManager.this.bulkDataIn.readInt() != CommonNetworking.magic) {
// Handle reconnect // Handle reconnect
} }
int length = ClientNetworkingManager.this.bulkDataIn int length = ClientNetworkingManager.this.bulkDataIn
.readShort(); .readShort();
byte[] buf = new byte[length]; byte[] buf = new byte[length];
int commandId = ClientNetworkingManager.this.bulkDataIn int commandId = ClientNetworkingManager.this.bulkDataIn
.readUnsignedByte(); .readUnsignedByte();
if (commandId == 255) { if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true); ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop; continue recvLoop;
} }
ClientNetworkingManager.this.bulkStreamIn.read(buf); ClientNetworkingManager.this.bulkStreamIn.read(buf);
if (commandId == 254) { if (commandId == 254) {
ClientNetworkingManager.this.fastLinkAckd.set(true); ClientNetworkingManager.this.fastLinkAckd.set(true);
sendPacketLowLatency(254, buf); sendPacketLowLatency(254, buf);
sendPacketUdp(254, buf, true); sendPacketUdp(254, buf, true);
continue recvLoop; continue recvLoop;
} }
ClientNetworkingManager.this.packets.add(new MossNetPacket( ClientNetworkingManager.this.packets.add(new MossNetPacket(
commandId, buf)); commandId, buf));
ClientNetworkingManager.this.lastBulkIn.set(System ClientNetworkingManager.this.lastBulkIn.set(System
.currentTimeMillis()); .currentTimeMillis());
if (ClientNetworkingManager.this.packets if (ClientNetworkingManager.this.packets
.remainingCapacity() < 32) .remainingCapacity() < 32)
sendQuench(); sendQuench();
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
}, "ClientBulkRecv"); //$NON-NLS-1$ }, "ClientBulkRecv"); //$NON-NLS-1$
protected Thread fastReadHandler = new Thread(new Runnable() { protected Thread fastReadHandler = new Thread(new Runnable() {
// TODO // TODO
@Override @Override
public void run() { public void run() {
try { try {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) { recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
if (ClientNetworkingManager.this.lowlatencyDataIn.readInt() != CommonNetworking.magic) { if (ClientNetworkingManager.this.lowlatencyDataIn.readInt() != CommonNetworking.magic) {
// Handle reconnect // Handle reconnect
} }
int length = ClientNetworkingManager.this.lowlatencyDataIn int length = ClientNetworkingManager.this.lowlatencyDataIn
.readShort(); .readShort();
byte[] buf = new byte[length]; byte[] buf = new byte[length];
int commandId = ClientNetworkingManager.this.lowlatencyDataIn int commandId = ClientNetworkingManager.this.lowlatencyDataIn
.readUnsignedByte(); .readUnsignedByte();
if (commandId == 255) { if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true); ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop; continue recvLoop;
} }
ClientNetworkingManager.this.fastStreamIn.read(buf); ClientNetworkingManager.this.fastStreamIn.read(buf);
ClientNetworkingManager.this.packets.add(new MossNetPacket( ClientNetworkingManager.this.packets.add(new MossNetPacket(
commandId, buf)); commandId, buf));
ClientNetworkingManager.this.lastFastIn.set(System ClientNetworkingManager.this.lastFastIn.set(System
.currentTimeMillis()); .currentTimeMillis());
ClientNetworkingManager.this.packets.add(new MossNetPacket( ClientNetworkingManager.this.packets.add(new MossNetPacket(
commandId, buf)); commandId, buf));
if (ClientNetworkingManager.this.packets if (ClientNetworkingManager.this.packets
.remainingCapacity() < 32) .remainingCapacity() < 32)
sendQuench(); sendQuench();
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
}, "ClientBulkRecv"); //$NON-NLS-1$ }, "ClientBulkRecv"); //$NON-NLS-1$
protected AtomicBoolean partyQuenched = new AtomicBoolean(false); protected AtomicBoolean partyQuenched = new AtomicBoolean(false);
AtomicLong quenchedSince = new AtomicLong(0); AtomicLong quenchedSince = new AtomicLong(0);
protected Thread dgramReadHandler = new Thread(new Runnable() { protected Thread dgramReadHandler = new Thread(new Runnable() {
// TODO--spanish for "all" // TODO--spanish for "all"
@Override @Override
public void run() { public void run() {
recvLoop: while (ClientNetworkingManager.this.runThreads.get()) { recvLoop: while (ClientNetworkingManager.this.runThreads.get()) {
byte[] buf = new byte[270]; byte[] buf = new byte[270];
DatagramPacket pckt = new DatagramPacket(buf, 270); DatagramPacket pckt = new DatagramPacket(buf, 270);
try { try {
ClientNetworkingManager.this.udpSocket.receive(pckt); ClientNetworkingManager.this.udpSocket.receive(pckt);
ByteArrayInputStream bufStr = new ByteArrayInputStream( ByteArrayInputStream bufStr = new ByteArrayInputStream(
pckt.getData()); pckt.getData());
if (!pckt.getAddress().equals( if (!pckt.getAddress().equals(
ClientNetworkingManager.this.endpoint)) { ClientNetworkingManager.this.endpoint)) {
System.out.println("received mismatched packet source"); //$NON-NLS-1$ System.out.println("received mismatched packet source"); //$NON-NLS-1$
continue recvLoop; continue recvLoop;
} }
DataInputStream dos = new DataInputStream(bufStr); DataInputStream dos = new DataInputStream(bufStr);
int magic = dos.readInt(); int magic = dos.readInt();
if (magic == CommonNetworking.magic) if (magic == CommonNetworking.magic)
sendAck(dos.readUnsignedShort()); sendAck(dos.readUnsignedShort());
if (!(magic == CommonNetworking.magic || magic == CommonNetworking.magicNoAck)) { if (!(magic == CommonNetworking.magic || magic == CommonNetworking.magicNoAck)) {
System.out.println("bad magic"); //$NON-NLS-1$ System.out.println("bad magic"); //$NON-NLS-1$
continue recvLoop; continue recvLoop;
} }
int length = dos.readUnsignedByte(); int length = dos.readUnsignedByte();
int commandId = dos.readUnsignedByte(); int commandId = dos.readUnsignedByte();
if (commandId == 255) { if (commandId == 255) {
ClientNetworkingManager.this.partyQuenched.set(true); ClientNetworkingManager.this.partyQuenched.set(true);
continue recvLoop; continue recvLoop;
} }
byte[] pBuf = new byte[length]; byte[] pBuf = new byte[length];
bufStr.read(pBuf); bufStr.read(pBuf);
ClientNetworkingManager.this.lastUdpIn.set(System ClientNetworkingManager.this.lastUdpIn.set(System
.currentTimeMillis()); .currentTimeMillis());
ClientNetworkingManager.this.packets.add(new MossNetPacket( ClientNetworkingManager.this.packets.add(new MossNetPacket(
commandId, pBuf)); commandId, pBuf));
} catch (IOException e) { } catch (IOException e) {
ClientNetworkingManager.this.udpOn = false; ClientNetworkingManager.this.udpOn = false;
} }
} }
} }
}, "ClientDgramRecv"); //$NON-NLS-1$ }, "ClientDgramRecv"); //$NON-NLS-1$
protected InputStream bulkStreamIn; protected InputStream bulkStreamIn;
protected OutputStream bulkStreamOut; protected OutputStream bulkStreamOut;
protected InputStream fastStreamIn; protected InputStream fastStreamIn;
protected OutputStream fastStreamOut; protected OutputStream fastStreamOut;
public ClientNetworkingManager(String endpoint, int port, boolean useUdp) public ClientNetworkingManager(String endpoint, int port, boolean useUdp)
throws IOException { throws IOException {
this.endpoint = InetAddress.getByName(endpoint); this.endpoint = InetAddress.getByName(endpoint);
this.lowLatencyStreamSocket.setPerformancePreferences(0, 1, 0); this.lowLatencyStreamSocket.setPerformancePreferences(0, 1, 0);
this.lowLatencyStreamSocket.setTrafficClass(0x10); this.lowLatencyStreamSocket.setTrafficClass(0x10);
this.lowLatencyStreamSocket.setTcpNoDelay(true); this.lowLatencyStreamSocket.setTcpNoDelay(true);
this.bulkDataSocket.connect(new InetSocketAddress(endpoint, 16511), this.bulkDataSocket.connect(new InetSocketAddress(endpoint, 16511),
16511); 16511);
this.bulkStreamIn = this.bulkDataSocket.getInputStream(); this.bulkStreamIn = this.bulkDataSocket.getInputStream();
this.bulkStreamOut = this.bulkDataSocket.getOutputStream(); this.bulkStreamOut = this.bulkDataSocket.getOutputStream();
this.bulkDataOut = new DataOutputStream(this.bulkStreamOut); this.bulkDataOut = new DataOutputStream(this.bulkStreamOut);
this.bulkDataIn = new DataInputStream(this.bulkStreamIn); this.bulkDataIn = new DataInputStream(this.bulkStreamIn);
this.lowLatencyStreamSocket.connect(new InetSocketAddress(endpoint, this.lowLatencyStreamSocket.connect(new InetSocketAddress(endpoint,
16511), 16511); 16511), 16511);
this.fastStreamIn = this.lowLatencyStreamSocket.getInputStream(); this.fastStreamIn = this.lowLatencyStreamSocket.getInputStream();
this.fastStreamOut = this.lowLatencyStreamSocket.getOutputStream(); this.fastStreamOut = this.lowLatencyStreamSocket.getOutputStream();
this.lowlatencyDataOut = new DataOutputStream(this.fastStreamOut); this.lowlatencyDataOut = new DataOutputStream(this.fastStreamOut);
this.lowlatencyDataIn = new DataInputStream(this.fastStreamIn); this.lowlatencyDataIn = new DataInputStream(this.fastStreamIn);
this.udpOn = false; this.udpOn = false;
if (useUdp) { if (useUdp) {
try { try {
this.udpSocket = new DatagramSocket(port, this.udpSocket = new DatagramSocket(port,
InetAddress.getByName(endpoint)); InetAddress.getByName(endpoint));
this.udpSocket.setSoTimeout(0); this.udpSocket.setSoTimeout(0);
sendTosUdpConn(); sendTosUdpConn();
} catch (SocketException e) { } catch (SocketException e) {
this.udpOn = false; this.udpOn = false;
} }
} }
this.lastBulkIn.set(System.currentTimeMillis()); this.lastBulkIn.set(System.currentTimeMillis());
this.lastBulkOut.set(System.currentTimeMillis()); this.lastBulkOut.set(System.currentTimeMillis());
this.lastFastIn.set(System.currentTimeMillis()); this.lastFastIn.set(System.currentTimeMillis());
this.lastFastOut.set(System.currentTimeMillis()); this.lastFastOut.set(System.currentTimeMillis());
this.lastUdpIn.set(System.currentTimeMillis()); this.lastUdpIn.set(System.currentTimeMillis());
this.lastUdpOut.set(System.currentTimeMillis()); this.lastUdpOut.set(System.currentTimeMillis());
this.bulkReadHandler.start(); this.bulkReadHandler.start();
this.fastReadHandler.start(); this.fastReadHandler.start();
this.dgramReadHandler.start(); this.dgramReadHandler.start();
this.sendQueueThread.start(); this.sendQueueThread.start();
this.netTimeoutThread.start(); this.netTimeoutThread.start();
} }
protected void sendAck(int seqnum) { protected void sendAck(int seqnum) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
protected void sendTosUdpConn() { protected void sendTosUdpConn() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
protected void sendQuench() { protected void sendQuench() {
// TODO Sends a request for the server to back off with data and skip // TODO Sends a request for the server to back off with data and skip
// non-essential data. // non-essential data.
} }
/** /**
* Send a packet, dispatching to the correct socket. * Send a packet, dispatching to the correct socket.
* *
* @param commandId * @param commandId
* Byte representing command ID. * Byte representing command ID.
* @param payload * @param payload
* The data to send. * The data to send.
* @param latencyPrio * @param latencyPrio
* @throws IOException * @throws IOException
*/ */
protected void sendPacket(MossNetPacket p) throws IOException { protected void sendPacket(MossNetPacket p) throws IOException {
if(this.partyQuenched.get()&&!p.isImportant) return; if(this.partyQuenched.get()&&!p.isImportant) return;
if (p.needsFast) { if (p.needsFast) {
if ((p.payload.length < 250) && this.udpOn) if ((p.payload.length < 250) && this.udpOn)
sendPacketUdp(p.commandId, p.payload, p.needsAck); sendPacketUdp(p.commandId, p.payload, p.needsAck);
else { else {
sendPacketLowLatency(p.commandId, p.payload); sendPacketLowLatency(p.commandId, p.payload);
} }
} else } else
sendPacketDefault(p.commandId, p.payload); sendPacketDefault(p.commandId, p.payload);
} }
protected void sendPacketDefault(int commandId, byte[] payload) protected void sendPacketDefault(int commandId, byte[] payload)
throws IOException { throws IOException {
this.lastBulkOut.set(System.currentTimeMillis()); this.lastBulkOut.set(System.currentTimeMillis());
synchronized (this.bulkDataOut) { synchronized (this.bulkDataOut) {
try { try {
this.bulkDataOut.writeInt(CommonNetworking.magic); this.bulkDataOut.writeInt(CommonNetworking.magic);
this.bulkDataOut.writeShort(payload.length); this.bulkDataOut.writeShort(payload.length);
this.bulkDataOut.write(commandId); this.bulkDataOut.write(commandId);
this.bulkDataOut.write(payload); this.bulkDataOut.write(payload);
this.bulkDataOut.flush(); this.bulkDataOut.flush();
} catch (IOException e) { } catch (IOException e) {
defaultReinit(); defaultReinit();
this.bulkDataOut.writeInt(CommonNetworking.magic); this.bulkDataOut.writeInt(CommonNetworking.magic);
this.bulkDataOut.writeShort(payload.length); this.bulkDataOut.writeShort(payload.length);
this.bulkDataOut.write(commandId); this.bulkDataOut.write(commandId);
this.bulkDataOut.write(payload); this.bulkDataOut.write(payload);
this.bulkDataOut.flush(); this.bulkDataOut.flush();
} }
} }
} }
protected void defaultReinit() throws IOException { protected void defaultReinit() throws IOException {
this.bulkDataIn.close(); this.bulkDataIn.close();
this.bulkDataOut.close(); this.bulkDataOut.close();
this.bulkDataSocket.close(); this.bulkDataSocket.close();
this.bulkDataSocket = new Socket(); this.bulkDataSocket = new Socket();
this.bulkDataSocket.connect(new InetSocketAddress(this.endpoint, this.bulkDataSocket.connect(new InetSocketAddress(this.endpoint,
this.port), 10000); this.port), 10000);
this.bulkDataOut = new DataOutputStream( this.bulkDataOut = new DataOutputStream(
this.bulkDataSocket.getOutputStream()); this.bulkDataSocket.getOutputStream());
this.bulkDataIn = new DataInputStream( this.bulkDataIn = new DataInputStream(
this.bulkDataSocket.getInputStream()); this.bulkDataSocket.getInputStream());
performBulkReconnect(); performBulkReconnect();
this.lastBulkIn.set(System.currentTimeMillis()); this.lastBulkIn.set(System.currentTimeMillis());
this.lastBulkOut.set(System.currentTimeMillis()); this.lastBulkOut.set(System.currentTimeMillis());
} }
protected void performBulkReconnect() { protected void performBulkReconnect() {
synchronized (this.bulkDataOut) { synchronized (this.bulkDataOut) {
// PERFORM RECONNECTION // PERFORM RECONNECTION
} }
} }
protected void sendPacketLowLatency(int commandId, byte[] payload) protected void sendPacketLowLatency(int commandId, byte[] payload)
throws IOException { throws IOException {
if (!this.fastLinkAckd.get()) { if (!this.fastLinkAckd.get()) {
sendPacketDefault(commandId, payload); sendPacketDefault(commandId, payload);
} else { } else {
this.lastFastOut.set(System.currentTimeMillis()); this.lastFastOut.set(System.currentTimeMillis());
try { try {
this.lowlatencyDataOut.writeInt(CommonNetworking.magic); this.lowlatencyDataOut.writeInt(CommonNetworking.magic);
this.lowlatencyDataOut.writeShort(payload.length); this.lowlatencyDataOut.writeShort(payload.length);
this.lowlatencyDataOut.write(commandId); this.lowlatencyDataOut.write(commandId);
this.lowlatencyDataOut.flush(); this.lowlatencyDataOut.flush();
this.fastStreamOut.write(payload); this.fastStreamOut.write(payload);
this.fastStreamOut.flush(); this.fastStreamOut.flush();
} catch (IOException e) { } catch (IOException e) {
defaultReinit(); defaultReinit();
this.lowlatencyDataOut.writeInt(CommonNetworking.magic); this.lowlatencyDataOut.writeInt(CommonNetworking.magic);
this.lowlatencyDataOut.writeShort(payload.length); this.lowlatencyDataOut.writeShort(payload.length);
this.lowlatencyDataOut.write(commandId); this.lowlatencyDataOut.write(commandId);
this.lowlatencyDataOut.flush(); this.lowlatencyDataOut.flush();
this.fastStreamOut.write(payload); this.fastStreamOut.write(payload);
this.fastStreamOut.flush(); this.fastStreamOut.flush();
} }
} }
} }
protected void sendPacketUdp(int commandId, byte[] payload, boolean needsAck) protected void sendPacketUdp(int commandId, byte[] payload, boolean needsAck)
throws IOException { throws IOException {
this.lastUdpOut.set(System.currentTimeMillis()); this.lastUdpOut.set(System.currentTimeMillis());
DatagramPacket toSend = new DatagramPacket(payload, payload.length); DatagramPacket toSend = new DatagramPacket(payload, payload.length);
toSend.setSocketAddress(new InetSocketAddress(this.endpoint, this.port)); toSend.setSocketAddress(new InetSocketAddress(this.endpoint, this.port));
synchronized (this.udpSocket) { synchronized (this.udpSocket) {
this.udpSocket.send(toSend); this.udpSocket.send(toSend);
} }
} }
public void enqueuePacket(MossNetPacket p) throws InterruptedException { public void enqueuePacket(MossNetPacket p) throws InterruptedException {
this.sendQueue.put(p); this.sendQueue.put(p);
} }
protected class StateMachine { protected class StateMachine {
static final int DISCONNECTED = 0; static final int DISCONNECTED = 0;
static final int LINK = 1; static final int LINK = 1;
static final int AUTH = 2; static final int AUTH = 2;
static final int RESOURCE_XFER = 3; static final int RESOURCE_XFER = 3;
static final int ESTABLISHED = 4; static final int ESTABLISHED = 4;
static final int DENIED = 5; static final int DENIED = 5;
static final int TIMEDOUT = 6; static final int TIMEDOUT = 6;
int curStatus = 0; int curStatus = 0;
} }
public void beginConnectHandshake() { public void beginConnectHandshake() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
final ArrayBlockingQueue<MossNetPacket> sendQueue = new ArrayBlockingQueue<>( final ArrayBlockingQueue<MossNetPacket> sendQueue = new ArrayBlockingQueue<>(
1024); 1024);
private Thread sendQueueThread = new Thread(new Runnable() { private Thread sendQueueThread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
while (ClientNetworkingManager.this.runThreads.get()) { while (ClientNetworkingManager.this.runThreads.get()) {
try { try {
MossNetPacket p = ClientNetworkingManager.this.sendQueue.take(); MossNetPacket p = ClientNetworkingManager.this.sendQueue.take();
ClientNetworkingManager.this.sendPacket(p); ClientNetworkingManager.this.sendPacket(p);
} catch (InterruptedException | IOException e) { } catch (InterruptedException | IOException e) {
// superfluous exception // superfluous exception
} }
} }
} }
}, "netClientSendQueue"); }, "netClientSendQueue");
private Thread netTimeoutThread = new Thread(new Runnable() { private Thread netTimeoutThread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
while (ClientNetworkingManager.this.runThreads.get()) { while (ClientNetworkingManager.this.runThreads.get()) {
long cTime = System.currentTimeMillis(); long cTime = System.currentTimeMillis();
if (cTime - ClientNetworkingManager.this.lastBulkIn.get() > 10000 if (cTime - ClientNetworkingManager.this.lastBulkIn.get() > 10000
|| cTime || cTime
- ClientNetworkingManager.this.lastFastIn.get() > 10000 - ClientNetworkingManager.this.lastFastIn.get() > 10000
|| cTime - ClientNetworkingManager.this.lastUdpIn.get() > 10000) { || cTime - ClientNetworkingManager.this.lastUdpIn.get() > 10000) {
ClientManager ClientManager
.showErrorScreen( .showErrorScreen(
"Network Timeout", "Network Timeout",
"The connection to the server has been lost or has become too slow to continue. \r\nThis is likely caused by an unstable connection, poor WiFi, loose cables, or a firewall issue.", "The connection to the server has been lost or has become too slow to continue. \r\nThis is likely caused by an unstable connection, poor WiFi, loose cables, or a firewall issue.",
true); true);
} }
try { try {
if (cTime - ClientNetworkingManager.this.lastBulkOut.get() > 4000) if (cTime - ClientNetworkingManager.this.lastBulkOut.get() > 4000)
sendPacketDefault(00, new byte[] {}); sendPacketDefault(00, new byte[] {});
} catch (IOException e) { } catch (IOException e) {
// pass // pass
} }
try { try {
if (cTime - ClientNetworkingManager.this.lastFastOut.get() > 4000) if (cTime - ClientNetworkingManager.this.lastFastOut.get() > 4000)
sendPacketLowLatency(00, new byte[] {}); sendPacketLowLatency(00, new byte[] {});
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
try { try {
if (cTime - ClientNetworkingManager.this.lastUdpOut.get() > 4000) if (cTime - ClientNetworkingManager.this.lastUdpOut.get() > 4000)
sendPacketUdp(00, new byte[] {}, false); sendPacketUdp(00, new byte[] {}, false);
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
if (cTime - ClientNetworkingManager.this.quenchedSince.get() > 4000) if (cTime - ClientNetworkingManager.this.quenchedSince.get() > 4000)
ClientNetworkingManager.this.partyQuenched.set(false); ClientNetworkingManager.this.partyQuenched.set(false);
try { try {
// oh, joy // oh, joy
Thread.sleep(4000 Thread.sleep(4000
- cTime - cTime
+ Math.min( + Math.min(
ClientNetworkingManager.this.lastBulkIn ClientNetworkingManager.this.lastBulkIn
.get(), .get(),
Math.min( Math.min(
ClientNetworkingManager.this.lastBulkOut ClientNetworkingManager.this.lastBulkOut
.get(), .get(),
Math.min( Math.min(
ClientNetworkingManager.this.lastFastIn ClientNetworkingManager.this.lastFastIn
.get(), .get(),
Math.min( Math.min(
ClientNetworkingManager.this.lastFastOut ClientNetworkingManager.this.lastFastOut
.get(), .get(),
Math.min( Math.min(
ClientNetworkingManager.this.lastUdpIn ClientNetworkingManager.this.lastUdpIn
.get(), .get(),
Math.min( Math.min(
ClientNetworkingManager.this.lastUdpOut ClientNetworkingManager.this.lastUdpOut
.get(), .get(),
ClientNetworkingManager.this.quenchedSince ClientNetworkingManager.this.quenchedSince
.get()))))))); .get())))))));
} catch (InterruptedException e) { } catch (InterruptedException e) {
// pass // pass
} }
} }
} }
}, "netTimeout"); }, "netTimeout");
} }

View File

@ -1,7 +1,7 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class CommonNetworking { public class CommonNetworking {
static final int magic=0xfa7d2e4a; static final int magic=0xfa7d2e4a;
static final int magicNoAck=0xfa7d2e4f; static final int magicNoAck=0xfa7d2e4f;
static final int magicAck=0xfa7d2740; static final int magicAck=0xfa7d2740;
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class DatabaseWriteEvent { public class DatabaseWriteEvent {
} }

View File

@ -1,82 +1,82 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.MossEvent; import net.mosstest.scripting.MossEvent;
import net.mosstest.scripting.MossItem; import net.mosstest.scripting.MossItem;
import net.mosstest.scripting.MossScriptEnv; import net.mosstest.scripting.MossScriptEnv;
import net.mosstest.scripting.MossScriptException; import net.mosstest.scripting.MossScriptException;
import net.mosstest.scripting.Player; import net.mosstest.scripting.Player;
public class DefaultEventHandlers { public class DefaultEventHandlers {
public static void processEvent(final MossEvent evt, MossScriptEnv env) throws MossScriptException { public static void processEvent(final MossEvent evt, MossScriptEnv env) throws MossScriptException {
switch (evt.type) { switch (evt.type) {
case EVT_CHATCOMMAND: case EVT_CHATCOMMAND:
env.sendChatMessage((Player) evt.actor, null, env.sendChatMessage((Player) evt.actor, null,
"No such chat command"); "No such chat command");
break; break;
case EVT_CHATMESSAGE: case EVT_CHATMESSAGE:
env.sendChatAll((Player) evt.actor, env.sendChatAll((Player) evt.actor,
evt.initiatingMessage); evt.initiatingMessage);
break; break;
case EVT_DIEPLAYER: case EVT_DIEPLAYER:
env.setHp(evt.actor, 64); // Max HP=64 env.setHp(evt.actor, 64); // Max HP=64
evt.actor.respawn(); evt.actor.respawn();
// FIXME rarkenin env.moveEntity(myEvent.actor, // FIXME rarkenin env.moveEntity(myEvent.actor,
// Mapgen.getSpawnPoint); // Mapgen.getSpawnPoint);
break; break;
case EVT_DIGNODE: case EVT_DIGNODE:
try { try {
env.damageTool(evt.actor, env.damageTool(evt.actor,
evt.nodeBefore); evt.nodeBefore);
env.givePlayer(evt.actor, env.givePlayer(evt.actor,
new MossItem.Stack(evt.nodeBefore.dropItem, 1)); new MossItem.Stack(evt.nodeBefore.dropItem, 1));
env.removeNode(evt.pos); env.removeNode(evt.pos);
} catch (MossScriptException e) { } catch (MossScriptException e) {
//FIXME MossSecurityManager.log(e); //FIXME MossSecurityManager.log(e);
} }
break; break;
case EVT_ENTITY_DEATH: case EVT_ENTITY_DEATH:
env.getFuturesProcessor().runOnce(8000, new Runnable() { env.getFuturesProcessor().runOnce(8000, new Runnable() {
@Override @Override
public void run() { public void run() {
evt.actor.respawn(); evt.actor.respawn();
} }
}); });
break; break;
case EVT_ENTITY_PUNCH: case EVT_ENTITY_PUNCH:
//No default action //No default action
break; break;
case EVT_FSPEC_INVACTION: case EVT_FSPEC_INVACTION:
evt.action.acceptAsStated(); evt.action.acceptAsStated();
break; break;
case EVT_FSPEC_OPEN: case EVT_FSPEC_OPEN:
break; break;
case EVT_FSPEC_SUBMIT: case EVT_FSPEC_SUBMIT:
break; break;
case EVT_GENERATE: case EVT_GENERATE:
break; break;
case EVT_JOINPLAYER: case EVT_JOINPLAYER:
break; break;
case EVT_NEWPLAYER: case EVT_NEWPLAYER:
break; break;
case EVT_NODEMOVE: case EVT_NODEMOVE:
break; break;
case EVT_PLACENODE: case EVT_PLACENODE:
env.setNode(evt.pos, evt.nodeAfter); env.setNode(evt.pos, evt.nodeAfter);
break; break;
case EVT_QUITPLAYER: case EVT_QUITPLAYER:
break; break;
case EVT_SHUTDOWN: case EVT_SHUTDOWN:
break; break;
case EVT_THREADSTOP: case EVT_THREADSTOP:
break; break;
default: default:
break; break;
} }
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public interface Drawable2D { public interface Drawable2D {
public void Draw(DrawableHudset screen); public void Draw(DrawableHudset screen);
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public interface Drawable3D { public interface Drawable3D {
public void draw(DrawableWorld world); public void draw(DrawableWorld world);
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class DrawableHudset { public class DrawableHudset {
} }

View File

@ -1,14 +1,14 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.MapNode; import net.mosstest.scripting.MapNode;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public class DrawableWorld { public class DrawableWorld {
public void addBlockMesh(MapNode mapNode, Position pos) { public void addBlockMesh(MapNode mapNode, Position pos) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class DuplicateNodedefException extends Exception { public class DuplicateNodedefException extends Exception {
} }

View File

@ -1,17 +1,17 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class EngineSettings { public class EngineSettings {
static int getInt(String name, int def){ static int getInt(String name, int def){
if("forced".equals("false")){ if("forced".equals("false")){
return 0; //TODO this case return 0; //TODO this case
} }
return def; return def;
} }
public static boolean getBool(String string, boolean def) { public static boolean getBool(String string, boolean def) {
if("forced".equals("false")){ if("forced".equals("false")){
return false; //TODO this case return false; //TODO this case
} }
return def; return def;
} }
} }

View File

@ -1,180 +1,180 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import net.mosstest.scripting.EventProcessingCompletedSignal; import net.mosstest.scripting.EventProcessingCompletedSignal;
import net.mosstest.scripting.MossEvent; import net.mosstest.scripting.MossEvent;
import net.mosstest.scripting.MossEventHandler; import net.mosstest.scripting.MossEventHandler;
import net.mosstest.scripting.MossScriptEnv; import net.mosstest.scripting.MossScriptEnv;
import net.mosstest.scripting.MossScriptException; import net.mosstest.scripting.MossScriptException;
import net.mosstest.scripting.MossEvent.EvtType; import net.mosstest.scripting.MossEvent.EvtType;
/** /**
* *
* @author rarkenin, hexafraction * @author rarkenin, hexafraction
* *
* Blargh. * Blargh.
* *
* This is a nasty thread pool. If you don't understand threading or * 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 * Java well, you may want to stick to only accessing the queue as
* otherwise asphyxiation, drowning, or chlorine poisoning may occur. * otherwise asphyxiation, drowning, or chlorine poisoning may occur.
* USE ACCESS METHODS OTHER THAN THE QUEUE AT YOUR OWN RISK. * USE ACCESS METHODS OTHER THAN THE QUEUE AT YOUR OWN RISK.
* *
*/ */
public class EventProcessor { public class EventProcessor {
ArrayBlockingQueue<MossEvent> eventQueue = new ArrayBlockingQueue<>( ArrayBlockingQueue<MossEvent> eventQueue = new ArrayBlockingQueue<>(
EngineSettings.getInt("eventQueueCapacity", 40), false); //$NON-NLS-1$ EngineSettings.getInt("eventQueueCapacity", 40), false); //$NON-NLS-1$
protected final int maxEventThreads = EngineSettings.getInt( protected final int maxEventThreads = EngineSettings.getInt(
"maxEventThreads", 8); //$NON-NLS-1$ "maxEventThreads", 8); //$NON-NLS-1$
protected final int initialEventThreads = EngineSettings.getInt( protected final int initialEventThreads = EngineSettings.getInt(
"initialEventThreads", 8); //$NON-NLS-1$ "initialEventThreads", 8); //$NON-NLS-1$
ThreadGroup eventProcessorGroup = new ThreadGroup("EventProcessor"); //$NON-NLS-1$ ThreadGroup eventProcessorGroup = new ThreadGroup("EventProcessor"); //$NON-NLS-1$
protected AtomicBoolean runManager = new AtomicBoolean(true); protected AtomicBoolean runManager = new AtomicBoolean(true);
protected final int sampleInterval = EngineSettings.getInt( protected final int sampleInterval = EngineSettings.getInt(
"eventQueueTuneSampleInterval", 100); //$NON-NLS-1$ "eventQueueTuneSampleInterval", 100); //$NON-NLS-1$
protected final int upshift = EngineSettings.getInt( protected final int upshift = EngineSettings.getInt(
"eventQueueTuneUpshift", 90); //$NON-NLS-1$ "eventQueueTuneUpshift", 90); //$NON-NLS-1$
protected final int downshift = EngineSettings.getInt( protected final int downshift = EngineSettings.getInt(
"eventQueueTuneDownshift", 10); //$NON-NLS-1$ "eventQueueTuneDownshift", 10); //$NON-NLS-1$
protected final int samples = EngineSettings.getInt( protected final int samples = EngineSettings.getInt(
"eventQueueTuneSamples", 100); //$NON-NLS-1$ "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, private Thread manager = new Thread(this.eventProcessorGroup,
new Runnable() { new Runnable() {
/** /**
* *
* The manager. Controls the thread number. * The manager. Controls the thread number.
*/ */
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
public void run() { public void run() {
System.out.println("manager thread started"); //$NON-NLS-1$ System.out.println("manager thread started"); //$NON-NLS-1$
int ticks = 0; int ticks = 0;
int ticksBusy = 0; int ticksBusy = 0;
int lSampleInterval = EventProcessor.this.sampleInterval; int lSampleInterval = EventProcessor.this.sampleInterval;
int lUpshift = EventProcessor.this.upshift; int lUpshift = EventProcessor.this.upshift;
int lDownshift = EventProcessor.this.downshift; int lDownshift = EventProcessor.this.downshift;
int lSamples = EventProcessor.this.samples; int lSamples = EventProcessor.this.samples;
Thread[] threads = new Thread[EventProcessor.this.maxEventThreads]; Thread[] threads = new Thread[EventProcessor.this.maxEventThreads];
for (int i = 0; i < EventProcessor.this.initialEventThreads; i++) { for (int i = 0; i < EventProcessor.this.initialEventThreads; i++) {
System.out.println("foo"); //$NON-NLS-1$ System.out.println("foo"); //$NON-NLS-1$
int c = EventProcessor.this.currentThreads.get(); int c = EventProcessor.this.currentThreads.get();
threads[c] = new Thread( threads[c] = new Thread(
EventProcessor.this.eventProcessorGroup, EventProcessor.this.eventProcessorGroup,
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
System.out System.out
.println("Worker thread starteds"); //$NON-NLS-1$ .println("Worker thread starteds"); //$NON-NLS-1$
processEvents(); processEvents();
} }
}); });
threads[c].start(); threads[c].start();
System.out.println("PostRun"); //$NON-NLS-1$ System.out.println("PostRun"); //$NON-NLS-1$
EventProcessor.this.currentThreads.incrementAndGet(); EventProcessor.this.currentThreads.incrementAndGet();
} }
while (EventProcessor.this.runManager.get()) { while (EventProcessor.this.runManager.get()) {
ticks++; ticks++;
if (!EventProcessor.this.eventQueue.isEmpty()) { if (!EventProcessor.this.eventQueue.isEmpty()) {
ticksBusy++; ticksBusy++;
} }
if (ticks >= lSamples) { if (ticks >= lSamples) {
if ((EventProcessor.this.currentThreads.get() < EventProcessor.this.maxEventThreads) if ((EventProcessor.this.currentThreads.get() < EventProcessor.this.maxEventThreads)
&& (((float) ticksBusy / (float) ticks) > ((float) lUpshift / (float) lSamples))) { && (((float) ticksBusy / (float) ticks) > ((float) lUpshift / (float) lSamples))) {
new Thread( new Thread(
EventProcessor.this.eventProcessorGroup, EventProcessor.this.eventProcessorGroup,
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
System.out System.out
.println("Dynamically added thread"); //$NON-NLS-1$ .println("Dynamically added thread"); //$NON-NLS-1$
processEvents(); processEvents();
} }
}).run(); }).run();
EventProcessor.this.currentThreads EventProcessor.this.currentThreads
.incrementAndGet(); .incrementAndGet();
} }
if (((float) ticksBusy / (float) ticks) < ((float) lDownshift / (float) lSamples)) { if (((float) ticksBusy / (float) ticks) < ((float) lDownshift / (float) lSamples)) {
System.out.println(("Stopping one thread")); System.out.println(("Stopping one thread"));
EventProcessor.this.eventQueue EventProcessor.this.eventQueue
.add(new MossEvent( .add(new MossEvent(
MossEvent.EvtType.EVT_THREADSTOP, MossEvent.EvtType.EVT_THREADSTOP,
null, null, null, null, null, null, null, null, null, null,
null, null, 0, null, null, null, 0, null,
new ScriptSandboxBorderToken( new ScriptSandboxBorderToken(
84, 84,
EventProcessor.class))); EventProcessor.class)));
} }
ticks = 0; ticks = 0;
ticksBusy = 0; ticksBusy = 0;
} }
try { try {
Thread.sleep(lSampleInterval); Thread.sleep(lSampleInterval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// manager awoke, no problem // manager awoke, no problem
} }
} }
} }
}, "EventProcessorManager"); //$NON-NLS-1$ }, "EventProcessorManager"); //$NON-NLS-1$
private MossScriptEnv ev; private MossScriptEnv ev;
void processEvents() { void processEvents() {
System.out.println("Worker thread entered"); //$NON-NLS-1$ System.out.println("Worker thread entered"); //$NON-NLS-1$
boolean run = true; // Not synchronized as only used locally boolean run = true; // Not synchronized as only used locally
queueLoop: while (run) { queueLoop: while (run) {
try { try {
MossEvent myEvent = this.eventQueue.take(); MossEvent myEvent = this.eventQueue.take();
{// Section for actually handling the events {// Section for actually handling the events
if (myEvent.type == EvtType.EVT_THREADSTOP) { if (myEvent.type == EvtType.EVT_THREADSTOP) {
this.currentThreads.decrementAndGet(); this.currentThreads.decrementAndGet();
return; return;
} }
ArrayList<MossEventHandler> evtHandlerList = this.ev ArrayList<MossEventHandler> evtHandlerList = this.ev
.getHandlers(myEvent.type, .getHandlers(myEvent.type,
new ScriptSandboxBorderToken(84, new ScriptSandboxBorderToken(84,
EventProcessor.class)); EventProcessor.class));
try { try {
for (MossEventHandler ourHandler : evtHandlerList) { for (MossEventHandler ourHandler : evtHandlerList) {
if (ourHandler.processEvent(myEvent)) if (ourHandler.processEvent(myEvent))
continue queueLoop; continue queueLoop;
} }
DefaultEventHandlers.processEvent(myEvent, this.ev); DefaultEventHandlers.processEvent(myEvent, this.ev);
} catch (MossScriptException e) { } catch (MossScriptException e) {
// Event processing complete, pass // Event processing complete, pass
} }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
// thread struck, shut down the operation. // thread struck, shut down the operation.
} }
System.out.println("Reached end of thread code"); //$NON-NLS-1$ System.out.println("Reached end of thread code"); //$NON-NLS-1$
this.currentThreads.decrementAndGet(); this.currentThreads.decrementAndGet();
} }
} }
/** /**
* Constructs a new event processor. * Constructs a new event processor.
* *
* @param ev * @param ev
* A script environment populated with event handlers. * A script environment populated with event handlers.
*/ */
public EventProcessor(MossScriptEnv ev) { public EventProcessor(MossScriptEnv ev) {
this.ev = ev; this.ev = ev;
this.manager.start(); this.manager.start();
} }
} }

View File

@ -1,7 +1,7 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class ExceptionHandler { public class ExceptionHandler {
public static void registerException(Exception e){ public static void registerException(Exception e){
//pass //pass
} }
} }

View File

@ -1,118 +1,118 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Random; import java.util.Random;
import java.util.TreeMap; import java.util.TreeMap;
public class FuturesProcessor { public class FuturesProcessor {
Random r = new Random(); Random r = new Random();
TreeMap<Long, Job> jobs = new TreeMap<>(); TreeMap<Long, Job> jobs = new TreeMap<>();
volatile long nextWakeup = System.currentTimeMillis(); volatile long nextWakeup = System.currentTimeMillis();
public Thread futuresThread = new Thread(new FuturesRunnable(), "futures"); public Thread futuresThread = new Thread(new FuturesRunnable(), "futures");
public synchronized void runOnce(long delayMillis, Runnable runnable) { public synchronized void runOnce(long delayMillis, Runnable runnable) {
Job tJob = new Job(System.currentTimeMillis() + delayMillis, 0, 0, 1.0, Job tJob = new Job(System.currentTimeMillis() + delayMillis, 0, 0, 1.0,
false, runnable); false, runnable);
this.nextWakeup = (long) Math.min(this.nextWakeup, this.nextWakeup = (long) Math.min(this.nextWakeup,
System.currentTimeMillis() + delayMillis); System.currentTimeMillis() + delayMillis);
this.jobs.put(System.currentTimeMillis() + delayMillis, tJob); this.jobs.put(System.currentTimeMillis() + delayMillis, tJob);
this.futuresThread.interrupt(); this.futuresThread.interrupt();
} }
public synchronized void registerAbm(long delayMillis, public synchronized void registerAbm(long delayMillis,
long delayJitterMillis, double probability, Runnable runnable) { long delayJitterMillis, double probability, Runnable runnable) {
Job tJob = new Job(System.currentTimeMillis(), delayMillis, Job tJob = new Job(System.currentTimeMillis(), delayMillis,
delayJitterMillis, probability, true, runnable); delayJitterMillis, probability, true, runnable);
this.nextWakeup = (long) Math.min(this.nextWakeup, this.nextWakeup = (long) Math.min(this.nextWakeup,
System.currentTimeMillis() + delayMillis + Math.random() System.currentTimeMillis() + delayMillis + Math.random()
* delayJitterMillis); * delayJitterMillis);
this.jobs.put(System.currentTimeMillis(), tJob); this.jobs.put(System.currentTimeMillis(), tJob);
this.futuresThread.interrupt(); // interrupt, and step back to release this.futuresThread.interrupt(); // interrupt, and step back to release
// the lock // the lock
} }
public void start() { public void start() {
this.futuresThread.start(); this.futuresThread.start();
} }
private volatile boolean run = true; private volatile boolean run = true;
public class FuturesRunnable implements Runnable { public class FuturesRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
while (FuturesProcessor.this.run) { while (FuturesProcessor.this.run) {
try { try {
Thread.sleep(FuturesProcessor.this.nextWakeup Thread.sleep(FuturesProcessor.this.nextWakeup
- System.currentTimeMillis()); - System.currentTimeMillis());
} catch (InterruptedException | IllegalArgumentException e) { } catch (InterruptedException | IllegalArgumentException e) {
// pass, got a new job. // pass, got a new job.
} }
synchronized (FuturesProcessor.this) { synchronized (FuturesProcessor.this) {
ArrayList<Job> requeues = new ArrayList<>(); ArrayList<Job> requeues = new ArrayList<>();
iterLoop: for (Iterator<Entry<Long, Job>> iterator = FuturesProcessor.this.jobs iterLoop: for (Iterator<Entry<Long, Job>> iterator = FuturesProcessor.this.jobs
.entrySet().iterator(); iterator.hasNext();) { .entrySet().iterator(); iterator.hasNext();) {
Map.Entry<Long, FuturesProcessor.Job> e = iterator Map.Entry<Long, FuturesProcessor.Job> e = iterator
.next(); .next();
// ascending key order // ascending key order
if (e.getKey() <= System.currentTimeMillis()) { if (e.getKey() <= System.currentTimeMillis()) {
e.getValue().r.run(); e.getValue().r.run();
if (e.getValue().renew) { if (e.getValue().renew) {
requeues.add(e.getValue()); requeues.add(e.getValue());
} }
iterator.remove(); iterator.remove();
} else } else
break iterLoop; break iterLoop;
} }
for (Job job : requeues) { for (Job job : requeues) {
job.nextInvocation = System.currentTimeMillis() job.nextInvocation = System.currentTimeMillis()
+ job.delay + (long) Math.random() + job.delay + (long) Math.random()
* job.delayJitter; * job.delayJitter;
FuturesProcessor.this.jobs.put(job.nextInvocation, job); FuturesProcessor.this.jobs.put(job.nextInvocation, job);
} }
} }
} }
} }
} }
public class Job { public class Job {
long firstInvocation; long firstInvocation;
long delay; long delay;
long delayJitter; long delayJitter;
double probability; double probability;
boolean renew; boolean renew;
Runnable r; Runnable r;
volatile long nextInvocation; volatile long nextInvocation;
/** /**
* @param firstInvocation * @param firstInvocation
* @param delay * @param delay
* @param delayJitter * @param delayJitter
* @param probability * @param probability
* @param renew * @param renew
* @param r * @param r
*/ */
public Job(long firstInvocation, long delay, long delayJitter, public Job(long firstInvocation, long delay, long delayJitter,
double probability, boolean renew, Runnable r) { double probability, boolean renew, Runnable r) {
this.firstInvocation = firstInvocation; this.firstInvocation = firstInvocation;
this.delay = delay; this.delay = delay;
this.delayJitter = delayJitter; this.delayJitter = delayJitter;
this.probability = probability; this.probability = probability;
this.renew = renew; this.renew = renew;
this.r = r; this.r = r;
this.nextInvocation = firstInvocation + delay this.nextInvocation = firstInvocation + delay
+ (long) Math.random() * delayJitter; + (long) Math.random() * delayJitter;
} }
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class GameMesh { public class GameMesh {
} }

View File

@ -1,6 +1,6 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public abstract class GenericTexture { public abstract class GenericTexture {
static long lastAllocatedTexId; static long lastAllocatedTexId;
} }

View File

@ -1,14 +1,18 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.MapChunk; import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public interface IRenderPreparator { public interface IRenderPreparator {
public abstract MapChunk requestChunk(Position pos) public void setRenderProcessor(RenderProcessor rend);
throws MapGeneratorException, InterruptedException;
public abstract MapChunk requestChunk(Position pos)
public abstract void recvOutstandingChunk(Position pos, MapChunk chk); throws MapGeneratorException, InterruptedException;
public abstract void shutdown(); public abstract void recvOutstandingChunk(Position pos, MapChunk chk);
public abstract void shutdown();
public abstract void start();
} }

View File

@ -1,29 +1,29 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.util.HashMap; import java.util.HashMap;
import net.mosstest.scripting.MapNode; import net.mosstest.scripting.MapNode;
import net.mosstest.scripting.MossItem; import net.mosstest.scripting.MossItem;
public class ItemManager { public class ItemManager {
private static HashMap<MapNode, MossItem> itemsForNode = new HashMap<>(); private static HashMap<MapNode, MossItem> itemsForNode = new HashMap<>();
public static MossItem getForNode(MapNode mapNode) { public static MossItem getForNode(MapNode mapNode) {
MossItem item = itemsForNode.get(mapNode); MossItem item = itemsForNode.get(mapNode);
if (item == null) { if (item == null) {
//item = createForNode(mapNode); //FIXME //item = createForNode(mapNode); //FIXME
itemsForNode.put(mapNode, item); itemsForNode.put(mapNode, item);
return item; return item;
} else } else
return item; return item;
} }
/*private static MossItem createForNode(MapNode mapNode) { /*private static MossItem createForNode(MapNode mapNode) {
MossItem mi=new MossItem(mapNode.texture, mapNode, 1, true, mapNode.userFacingName, mapNode.nodeName) MossItem mi=new MossItem(mapNode.texture, mapNode, 1, true, mapNode.userFacingName, mapNode.nodeName)
return mi; return mi;
//TODO todo //TODO todo
} }
*/ */
//FIXME above //FIXME above
} }

View File

@ -1,9 +1,9 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class Launcher { public class Launcher {
public static void main(String[] args){ public static void main(String[] args){
//real todo //real todo
} }
} }

View File

@ -1,81 +1,91 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import net.mosstest.scripting.MapChunk; import net.mosstest.scripting.MapChunk;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public class LocalRenderPreparator implements IRenderPreparator { public class LocalRenderPreparator implements IRenderPreparator {
public class ChunkLookupRunnable implements Runnable { public class ChunkLookupRunnable implements Runnable {
@Override @Override
public void run() { public void run() {
while (LocalRenderPreparator.this.run) { while (LocalRenderPreparator.this.run) {
try { try {
Position requested = LocalRenderPreparator.this.chunkRequests Position requested = LocalRenderPreparator.this.chunkRequests
.take(); .take();
System.out.println("REQUESTED " + requested.x + "," System.out.println("REQUESTED " + requested.x + ","
+ requested.y + "," + requested.z); + requested.y + "," + requested.z);
MapChunk chk = LocalRenderPreparator.this.nc MapChunk chk = LocalRenderPreparator.this.nc
.getChunk(requested); .getChunk(requested);
chk.pos = requested; chk.pos = requested;
LocalRenderPreparator.this.rp.renderEventQueue LocalRenderPreparator.this.rend.renderEventQueue
.put(new MossRenderChunkEvent(chk)); .put(new MossRenderChunkEvent(chk));
} catch (InterruptedException e) { } catch (InterruptedException e) {
// pass // pass
} catch (MapGeneratorException e) { } catch (MapGeneratorException e) {
System.out System.out
.print("The map generator has thrown an exception."); .print("The map generator has thrown an exception.");
} }
} }
} }
} }
private RenderProcessor rp; private RenderProcessor rend;
private NodeCache nc; private NodeCache nc;
private volatile boolean run = true; private volatile boolean run = true;
public ArrayBlockingQueue<Position> chunkRequests = new ArrayBlockingQueue<>( public ArrayBlockingQueue<Position> chunkRequests = new ArrayBlockingQueue<>(
1024); 1024);
// private HashMap<Position, Position> outstandingChunks = new HashMap<>(); // private HashMap<Position, Position> outstandingChunks = new HashMap<>();
private Thread lookupThread = new Thread(new ChunkLookupRunnable()); private Thread lookupThread = new Thread(new ChunkLookupRunnable());
@Override @Override
public MapChunk requestChunk(Position pos) throws MapGeneratorException, public MapChunk requestChunk(Position pos) throws MapGeneratorException,
InterruptedException { InterruptedException {
try { try {
MapChunk chk = this.nc.getChunkFailFast(pos); MapChunk chk = this.nc.getChunkFailFast(pos);
System.out.println(chk == null ? "null chunk failfast" : chk System.out.println(chk == null ? "null chunk failfast" : chk
.toString()); .toString());
if (chk == null) { if (chk == null) {
this.chunkRequests.put(pos); this.chunkRequests.put(pos);
} }
return chk; return chk;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public LocalRenderPreparator(RenderProcessor rp, NodeCache nc) { public LocalRenderPreparator(RenderProcessor rp, NodeCache nc) {
this.rp = rp; this.rend = rp;
this.nc = nc; this.nc = nc;
this.lookupThread.start(); }
}
@Override
@Override public void shutdown() {
public void shutdown() { this.run = false;
this.run = false; }
}
@Override
@Override public void recvOutstandingChunk(Position pos, MapChunk chk) {
public void recvOutstandingChunk(Position pos, MapChunk chk) { // pass
// TODO Auto-generated method stub }
} @Override
public void start() {
// TODO: Handle player movement, other server->client events affecting System.out.println("<<< START LOCAL RENDER PREPARATOR >>>");
// rendering this.lookupThread.start();
} }
@Override
public void setRenderProcessor(RenderProcessor rend) {
this.rend = rend;
}
// TODO: Handle player movement, other server->client events affecting
// rendering
}

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MapChangeEvent { public class MapChangeEvent {
} }

View File

@ -1,18 +1,18 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MapDatabaseException extends Exception{ public class MapDatabaseException extends Exception{
private static final long serialVersionUID = -1261363696203853384L; private static final long serialVersionUID = -1261363696203853384L;
public static final int SEVERITY_CORRUPT = 0; public static final int SEVERITY_CORRUPT = 0;
public static final int SEVERITY_CORRUPT_REPARABLE = 1; public static final int SEVERITY_CORRUPT_REPARABLE = 1;
public static final int SEVERITY_FATAL_TRANSIENT = 2; public static final int SEVERITY_FATAL_TRANSIENT = 2;
public static final int SEVERITY_WARNING = 4; public static final int SEVERITY_WARNING = 4;
public static final int SEVERITY_NOTFOUND = 8; public static final int SEVERITY_NOTFOUND = 8;
public static final int SEVERITY_UNKNOWN = 16; public static final int SEVERITY_UNKNOWN = 16;
public String desc; public String desc;
public int severity; public int severity;
public MapDatabaseException(int severity, String desc) { public MapDatabaseException(int severity, String desc) {
super(); super();
this.desc = desc; this.desc = desc;
this.severity = severity; this.severity = severity;
} }
} }

View File

@ -1,8 +1,8 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MapGeneratorException extends Exception { public class MapGeneratorException extends Exception {
private static final long serialVersionUID = -8402982836293707854L; private static final long serialVersionUID = -8402982836293707854L;
//marker type //marker type
} }

View File

@ -1,22 +1,22 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
public class Messages { public class Messages {
private static final String BUNDLE_NAME = "net.mosstest.servercore.messages"; //$NON-NLS-1$ private static final String BUNDLE_NAME = "net.mosstest.servercore.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME); .getBundle(BUNDLE_NAME);
private Messages() { private Messages() {
} }
public static String getString(String key) { public static String getString(String key) {
try { try {
return RESOURCE_BUNDLE.getString(key); return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) { } catch (MissingResourceException e) {
return '!' + key + '!'; return '!' + key + '!';
} }
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossChunkDrawEvent extends MossRenderEvent { public class MossChunkDrawEvent extends MossRenderEvent {
} }

View File

@ -1,46 +1,46 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
public abstract class MossFile { public abstract class MossFile {
/** /**
* Get a local copy of the file. This may be either a direct local file or a * Get a local copy of the file. This may be either a direct local file or a
* cached file. * cached file.
* *
* @return A valid RandomAccessFile. * @return A valid RandomAccessFile.
* @throws FileNotFoundException * @throws FileNotFoundException
*/ */
public abstract RandomAccessFile getRandAccessCopy() throws FileNotFoundException; public abstract RandomAccessFile getRandAccessCopy() throws FileNotFoundException;
/** /**
* String denoting the containing directory for the pathname. * String denoting the containing directory for the pathname.
*/ */
public final String dirName; public final String dirName;
public abstract byte[] readChunk(int chk) throws IOException; public abstract byte[] readChunk(int chk) throws IOException;
/** /**
* String denoting name of resource. * String denoting name of resource.
*/ */
public final String resourceName; public final String resourceName;
public abstract long getSize(); public abstract long getSize();
/** /**
* @param author * @param author
* @param plugin * @param plugin
* @param resourceName * @param resourceName
*/ */
public MossFile(String dirName, String resourceName) { public MossFile(String dirName, String resourceName) {
this.dirName=dirName; this.dirName=dirName;
this.resourceName = resourceName; this.resourceName = resourceName;
} }
public abstract File getFile() throws IOException; public abstract File getFile() throws IOException;
} }

View File

@ -1,45 +1,45 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.ArrayList; import java.util.ArrayList;
import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.configuration.XMLConfiguration;
public class MossGame { public class MossGame {
@SuppressWarnings("nls") @SuppressWarnings("nls")
public MossGame(String name) throws MossWorldLoadException { public MossGame(String name) throws MossWorldLoadException {
this.baseDir = new File("data/games/" + name); //$NON-NLS-1$ this.baseDir = new File("data/games/" + name); //$NON-NLS-1$
this.cfgFile = new File(this.baseDir, "game.xml"); this.cfgFile = new File(this.baseDir, "game.xml");
if (!(this.baseDir.isDirectory() && this.cfgFile.isFile())) { if (!(this.baseDir.isDirectory() && this.cfgFile.isFile())) {
throw new MossWorldLoadException( throw new MossWorldLoadException(
"Game directory or configuration file not found."); "Game directory or configuration file not found.");
} }
try { try {
this.gameCfg = new XMLConfiguration(this.cfgFile); this.gameCfg = new XMLConfiguration(this.cfgFile);
} catch (ConfigurationException e) { } catch (ConfigurationException e) {
throw new MossWorldLoadException( throw new MossWorldLoadException(
"Error in loading the configuration file."); "Error in loading the configuration file.");
} }
this.scripts = new ArrayList<>(); this.scripts = new ArrayList<>();
String[] scNames = this.gameCfg.getStringArray("plugin"); String[] scNames = this.gameCfg.getStringArray("plugin");
for (String scName : scNames) { for (String scName : scNames) {
try { try {
this.scripts.add(new MossScript(new MossLocalFile(new File("data/scripts/"), this.scripts.add(new MossScript(new MossLocalFile(new File("data/scripts/"),
scName, "init.js"))); scName, "init.js")));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new MossWorldLoadException("file not found: " + scName); throw new MossWorldLoadException("file not found: " + scName);
} // TODO directory structure and proper iteration } // TODO directory structure and proper iteration
} }
} }
private File baseDir; private File baseDir;
private XMLConfiguration gameCfg; private XMLConfiguration gameCfg;
private File cfgFile; private File cfgFile;
private ArrayList<MossScript> scripts; private ArrayList<MossScript> scripts;
public ArrayList<MossScript> getScripts() { public ArrayList<MossScript> getScripts() {
return this.scripts; return this.scripts;
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossGenericEvent { public class MossGenericEvent {
} }

View File

@ -1,50 +1,50 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
public class MossLocalFile extends MossFile { public class MossLocalFile extends MossFile {
public static final int CHUNK_LENGTH = 65536; public static final int CHUNK_LENGTH = 65536;
public MossLocalFile(File baseDir, String dirName, String resourceName) throws FileNotFoundException { public MossLocalFile(File baseDir, String dirName, String resourceName) throws FileNotFoundException {
// super call to establish fields. // super call to establish fields.
super(dirName, resourceName); super(dirName, resourceName);
//ensure filename is valid. //ensure filename is valid.
if(!(dirName.matches("[a-zA-Z0-9.]*")&&resourceName.matches("[a-zA-Z0-9.]*"))) throw new FileNotFoundException(); if(!(dirName.matches("[a-zA-Z0-9.]*")&&resourceName.matches("[a-zA-Z0-9.]*"))) throw new FileNotFoundException();
this.file = new File(baseDir, dirName); this.file = new File(baseDir, dirName);
this.file = new File(this.file, resourceName); this.file = new File(this.file, resourceName);
} }
private File file; private File file;
@Override @Override
public RandomAccessFile getRandAccessCopy() throws FileNotFoundException { public RandomAccessFile getRandAccessCopy() throws FileNotFoundException {
return new RandomAccessFile(this.file, "r"); return new RandomAccessFile(this.file, "r");
} }
public byte[] readChunk(int chk) throws IOException { public byte[] readChunk(int chk) throws IOException {
if ((chk < 0) || (chk > 65535)) if ((chk < 0) || (chk > 65535))
throw new IllegalArgumentException( throw new IllegalArgumentException(
"attempted to access a chunk with an invalid length"); //$NON-NLS-1$ "attempted to access a chunk with an invalid length"); //$NON-NLS-1$
byte[] buf = new byte[CHUNK_LENGTH]; byte[] buf = new byte[CHUNK_LENGTH];
RandomAccessFile rf = new RandomAccessFile(this.file, this.dirName); RandomAccessFile rf = new RandomAccessFile(this.file, this.dirName);
rf.seek(CHUNK_LENGTH * chk); rf.seek(CHUNK_LENGTH * chk);
rf.readFully(buf); rf.readFully(buf);
rf.close(); rf.close();
return buf; return buf;
} }
@Override @Override
public long getSize() { public long getSize() {
return this.file.length(); return this.file.length();
} }
public File getFile() { public File getFile() {
return this.file; return this.file;
} }
} }

View File

@ -1,31 +1,31 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossNetPacket { public class MossNetPacket {
int commandId; int commandId;
byte[] payload; byte[] payload;
boolean needsFast; boolean needsFast;
boolean needsAck; boolean needsAck;
boolean isImportant; boolean isImportant;
ServerSession sess; ServerSession sess;
/** /**
* Constructs a packet, for either sending or from receiving. * Constructs a packet, for either sending or from receiving.
* @param commandId The command ID * @param commandId The command ID
* @param payload The payload, as a byte array. * @param payload The payload, as a byte array.
*/ */
public MossNetPacket(int commandId, byte[] payload) { public MossNetPacket(int commandId, byte[] payload) {
this.commandId = commandId; this.commandId = commandId;
this.payload = payload; this.payload = payload;
this.needsAck = true; this.needsAck = true;
this.needsFast = false; this.needsFast = false;
this.isImportant = true; this.isImportant = true;
} }
public MossNetPacket(int commandId, byte[] payload, boolean needsFast, public MossNetPacket(int commandId, byte[] payload, boolean needsFast,
boolean needsAck, boolean isImportant) { boolean needsAck, boolean isImportant) {
this.commandId = commandId; this.commandId = commandId;
this.payload = payload; this.payload = payload;
this.needsFast = needsFast; this.needsFast = needsFast;
this.needsAck = needsAck; this.needsAck = needsAck;
this.isImportant = true; this.isImportant = true;
} }
} }

View File

@ -1,31 +1,31 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import net.mosstest.scripting.Position; import net.mosstest.scripting.Position;
public class MossNodeAddEvent extends MossRenderEvent { public class MossNodeAddEvent extends MossRenderEvent {
private int x, y, z; //position in chunk private int x, y, z; //position in chunk
private short definition; private short definition;
private Position parentChunkPosition; private Position parentChunkPosition;
public MossNodeAddEvent (int x, int y, int z, Position parentChunkPosition, short definition) { public MossNodeAddEvent (int x, int y, int z, Position parentChunkPosition, short definition) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
this.definition = definition; this.definition = definition;
this.parentChunkPosition = parentChunkPosition; this.parentChunkPosition = parentChunkPosition;
} }
public int getX() { public int getX() {
return x; return x;
} }
public int getY() { public int getY() {
return y; return y;
} }
public int getZ() { public int getZ() {
return z; return z;
} }
public short getDef() { public short getDef() {
return definition; return definition;
} }
public Position getPosition () { public Position getPosition () {
return parentChunkPosition; return parentChunkPosition;
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossNodeMoveEvent { public class MossNodeMoveEvent {
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossNodeRemoveEvent { public class MossNodeRemoveEvent {
} }

View File

@ -1,84 +1,84 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.util.BitSet; import java.util.BitSet;
public class MossRemoteFile extends MossFile { public class MossRemoteFile extends MossFile {
public class IncompleteFileException extends IOException { public class IncompleteFileException extends IOException {
private static final long serialVersionUID = -4932174729349395760L; private static final long serialVersionUID = -4932174729349395760L;
} }
public static final int CHUNK_LENGTH = 65536; public static final int CHUNK_LENGTH = 65536;
public final int numChunks; public final int numChunks;
public final int length; public final int length;
private BitSet chunksDone; private BitSet chunksDone;
public MossRemoteFile(File cacheDir, String dirName, String resourceName, public MossRemoteFile(File cacheDir, String dirName, String resourceName,
int length) throws FileNotFoundException { int length) throws FileNotFoundException {
// super call to establish fields. // super call to establish fields.
super(dirName, resourceName); super(dirName, resourceName);
//ensure filename is valid. //ensure filename is valid.
if(!(dirName.matches("[a-zA-Z0-9]*")&&resourceName.matches("[a-zA-Z0-9]*"))) throw new FileNotFoundException(); if(!(dirName.matches("[a-zA-Z0-9]*")&&resourceName.matches("[a-zA-Z0-9]*"))) throw new FileNotFoundException();
this.file = new File(cacheDir, dirName); this.file = new File(cacheDir, dirName);
this.file = new File(this.file, resourceName); this.file = new File(this.file, resourceName);
this.length = length; this.length = length;
this.numChunks = (length / 65536) + 1; this.numChunks = (length / 65536) + 1;
this.chunksDone = new BitSet(this.numChunks); this.chunksDone = new BitSet(this.numChunks);
} }
private File file; private File file;
@Override @Override
public RandomAccessFile getRandAccessCopy() throws FileNotFoundException { public RandomAccessFile getRandAccessCopy() throws FileNotFoundException {
return new RandomAccessFile(this.file, "rwd"); //$NON-NLS-1$ return new RandomAccessFile(this.file, "rwd"); //$NON-NLS-1$
} }
public byte[] readChunk(int chk) throws IOException { public byte[] readChunk(int chk) throws IOException {
if ((chk < 0) || (chk > 65535)) if ((chk < 0) || (chk > 65535))
throw new IllegalArgumentException( throw new IllegalArgumentException(
"attempted to access a chunk with an invalid length"); //$NON-NLS-1$ "attempted to access a chunk with an invalid length"); //$NON-NLS-1$
byte[] buf = new byte[CHUNK_LENGTH]; byte[] buf = new byte[CHUNK_LENGTH];
RandomAccessFile rf = new RandomAccessFile(this.file, "r"); RandomAccessFile rf = new RandomAccessFile(this.file, "r");
rf.seek(CHUNK_LENGTH * chk); rf.seek(CHUNK_LENGTH * chk);
rf.readFully(buf); rf.readFully(buf);
rf.close(); rf.close();
return buf; return buf;
} }
public void writeChunk(int chk, byte[] data) throws IOException { public void writeChunk(int chk, byte[] data) throws IOException {
// this will check if the chunk is the last one. If it is then it will // this will check if the chunk is the last one. If it is then it will
// use only the correct number of bytes. Otherwise it will use // use only the correct number of bytes. Otherwise it will use
// CHUNK_LENGTH. // CHUNK_LENGTH.
if (data.length != ((chk == this.numChunks - 1) ? this.length if (data.length != ((chk == this.numChunks - 1) ? this.length
% CHUNK_LENGTH : CHUNK_LENGTH)) % CHUNK_LENGTH : CHUNK_LENGTH))
throw new ArrayIndexOutOfBoundsException("Array is not 65536 bytes"); //$NON-NLS-1$ throw new ArrayIndexOutOfBoundsException("Array is not 65536 bytes"); //$NON-NLS-1$
RandomAccessFile rf = new RandomAccessFile(this.file, "rwd"); RandomAccessFile rf = new RandomAccessFile(this.file, "rwd");
rf.seek(chk*CHUNK_LENGTH); rf.seek(chk*CHUNK_LENGTH);
rf.write(data); rf.write(data);
this.chunksDone.set(chk, true); this.chunksDone.set(chk, true);
rf.close(); rf.close();
} }
@Override @Override
public long getSize() { public long getSize() {
return this.file.length(); return this.file.length();
} }
public File getFile() throws IncompleteFileException { public File getFile() throws IncompleteFileException {
if(!this.isReady()) throw new IncompleteFileException(); if(!this.isReady()) throw new IncompleteFileException();
return this.file; return this.file;
} }
public boolean isReady() { public boolean isReady() {
return (this.chunksDone.cardinality()==this.numChunks); return (this.chunksDone.cardinality()==this.numChunks);
} }
} }

View File

@ -1,11 +1,11 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossRenderAddAssetPath extends MossRenderEvent { public class MossRenderAddAssetPath extends MossRenderEvent {
String path; String path;
public MossRenderAddAssetPath (String newpath) { public MossRenderAddAssetPath (String newpath) {
path = newpath; path = newpath;
} }
public String getPath () { public String getPath () {
return path; return path;
} }
} }

View File

@ -1,7 +1,7 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossRenderEvent extends MossGenericEvent { public class MossRenderEvent extends MossGenericEvent {
public MossRenderEvent () { public MossRenderEvent () {
//Blank Constructor //Blank Constructor
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossRenderStopEvent extends MossRenderEvent{ public class MossRenderStopEvent extends MossRenderEvent{
} }

View File

@ -1,32 +1,32 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
public class MossScript { public class MossScript {
MossFile file; MossFile file;
public MossScript(MossFile file) throws MossWorldLoadException { public MossScript(MossFile file) throws MossWorldLoadException {
this.file = file; this.file = file;
try { try {
if (!this.file.getFile().isFile()) if (!this.file.getFile().isFile())
throw new MossWorldLoadException("Script named " + file.dirName throw new MossWorldLoadException("Script named " + file.dirName
+ "/" + file.resourceName + " not found!"); + "/" + file.resourceName + " not found!");
} catch (IOException e) { } catch (IOException e) {
throw new MossWorldLoadException("IOException with script named " throw new MossWorldLoadException("IOException with script named "
+ file.dirName + "/" + file.resourceName); + file.dirName + "/" + file.resourceName);
} }
} }
Reader getReader() throws MossWorldLoadException { Reader getReader() throws MossWorldLoadException {
try { try {
return new FileReader(this.file.getFile()); return new FileReader(this.file.getFile());
} catch (IOException e) { } catch (IOException e) {
// whoa there, something REALLY bad happened // whoa there, something REALLY bad happened
throw new MossWorldLoadException( throw new MossWorldLoadException(
"Extremely unexpected situation on our hands"); "Extremely unexpected situation on our hands");
} }
} }
} }

View File

@ -1,5 +1,5 @@
package net.mosstest.servercore; package net.mosstest.servercore;
public class MossSecurityManager { public class MossSecurityManager {
//Static crap only, shall use DB4O. //Static crap only, shall use DB4O.
} }

View File

@ -1,23 +1,23 @@
package net.mosstest.servercore; package net.mosstest.servercore;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
public class MossTest { public class MossTest {
public MossTest() { public MossTest() {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
Options options=new Options(); Options options=new Options();
options.addOption("server", false, "Run as standalone server"); options.addOption("server", false, "Run as standalone server");
options.addOption("port", true, "Port number to use"); options.addOption("port", true, "Port number to use");
} }
} }

Some files were not shown because too many files have changed in this diff Show More