Source reformat

This commit is contained in:
Anuken
2019-04-08 09:03:18 -04:00
parent 4a96b9bb00
commit b40beb0d1d
331 changed files with 2822 additions and 3274 deletions
+5 -6
View File
@@ -1,11 +1,10 @@
jdk: jdk:
- openjdk8 - openjdk8
script: script:
- "git clone --depth=1 --branch=master https://github.com/Anuken/Arc ../Arc" - "git clone --depth=1 --branch=master https://github.com/Anuken/Arc ../Arc"
- "./gradlew test" - "./gradlew test"
- "./gradlew desktop:dist -Pbuildversion=${TRAVIS_TAG:1}" - "./gradlew desktop:dist -Pbuildversion=${TRAVIS_TAG:1}"
- "./gradlew server:dist -Pbuildversion=${TRAVIS_TAG:1}" - "./gradlew server:dist -Pbuildversion=${TRAVIS_TAG:1}"
deploy: deploy:
provider: releases provider: releases
+16 -16
View File
@@ -2,10 +2,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.anuke.mindustry"> package="io.anuke.mindustry">
<uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET"/>
<application <application
android:resizeableActivity="false" android:resizeableActivity="false"
@@ -16,7 +16,7 @@
android:appCategory="game" android:appCategory="game"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@style/GdxTheme" android:fullBackupContent="@xml/backup_rules"> android:theme="@style/GdxTheme" android:fullBackupContent="@xml/backup_rules">
<meta-data android:name="android.max_aspect" android:value="2.1" /> <meta-data android:name="android.max_aspect" android:value="2.1"/>
<activity <activity
android:name="io.anuke.mindustry.AndroidLauncher" android:name="io.anuke.mindustry.AndroidLauncher"
android:label="@string/app_name" android:label="@string/app_name"
@@ -24,8 +24,8 @@
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout"> android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
<intent-filter> <intent-filter>
@@ -33,7 +33,7 @@
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.BROWSABLE"/>
<data android:mimeType="application/octet-stream"/> <data android:mimeType="application/octet-stream"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" /> <data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap"/>
</intent-filter> </intent-filter>
<intent-filter> <intent-filter>
@@ -41,28 +41,28 @@
<category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/> <category android:name="android.intent.category.BROWSABLE"/>
<data android:mimeType="application/octet-stream"/> <data android:mimeType="application/octet-stream"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" /> <data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav"/>
</intent-filter> </intent-filter>
<intent-filter android:icon="@mipmap/ic_launcher" <intent-filter android:icon="@mipmap/ic_launcher"
android:label="Mindustry Map" android:label="Mindustry Map"
android:priority="1"> android:priority="1">
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" android:mimeType="*/*" /> <data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" android:mimeType="*/*"/>
</intent-filter> </intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" android:mimeType="*/*" /> <data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" android:mimeType="*/*"/>
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".DonationsActivity" <activity android:name=".DonationsActivity"
android:theme="@style/GdxTheme" /> android:theme="@style/GdxTheme"/>
</application> </application>
+42 -42
View File
@@ -1,30 +1,30 @@
buildscript { buildscript{
repositories { repositories{
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
google() google()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" }
jcenter() jcenter()
} }
dependencies { dependencies{
classpath 'com.android.tools.build:gradle:3.3.2' classpath 'com.android.tools.build:gradle:3.3.2'
} }
} }
apply plugin: "com.android.application" apply plugin: "com.android.application"
configurations { natives } configurations{ natives }
repositories { repositories{
mavenCentral() mavenCentral()
jcenter() jcenter()
maven { maven{
url "https://maven.google.com" url "https://maven.google.com"
} }
} }
dependencies { dependencies{
implementation project(":core") implementation project(":core")
implementation project(":net") implementation project(":net")
@@ -46,14 +46,14 @@ task deploy(type: Copy){
from "build/outputs/apk/release/android-release.apk" from "build/outputs/apk/release/android-release.apk"
into "../deploy/" into "../deploy/"
rename ("android-release.apk", appName + "-android-" + getVersionString() + ".apk") rename("android-release.apk", appName + "-android-" + getVersionString() + ".apk")
} }
android { android{
buildToolsVersion '28.0.3' buildToolsVersion '28.0.3'
compileSdkVersion 28 compileSdkVersion 28
sourceSets { sourceSets{
main { main{
manifest.srcFile 'AndroidManifest.xml' manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src'] java.srcDirs = ['src']
aidl.srcDirs = ['src'] aidl.srcDirs = ['src']
@@ -65,11 +65,11 @@ android {
androidTest.setRoot('tests') androidTest.setRoot('tests')
} }
packagingOptions { packagingOptions{
exclude 'META-INF/robovm/ios/robovm.xml' exclude 'META-INF/robovm/ios/robovm.xml'
} }
defaultConfig { defaultConfig{
def vfile = file('../core/assets/version.properties') def vfile = file('../core/assets/version.properties')
def code = 0 def code = 0
@@ -93,16 +93,16 @@ android {
versionName versionNameResult versionName versionNameResult
} }
compileOptions { compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8
} }
flavorDimensions "google" flavorDimensions "google"
signingConfigs { signingConfigs{
release { release{
if(project.hasProperty("RELEASE_STORE_FILE")) { if(project.hasProperty("RELEASE_STORE_FILE")){
storeFile file(RELEASE_STORE_FILE) storeFile file(RELEASE_STORE_FILE)
storePassword RELEASE_STORE_PASSWORD storePassword RELEASE_STORE_PASSWORD
keyAlias RELEASE_KEY_ALIAS keyAlias RELEASE_KEY_ALIAS
@@ -113,8 +113,8 @@ android {
} }
} }
buildTypes { buildTypes{
release { release{
signingConfig signingConfigs.release signingConfig signingConfigs.release
} }
} }
@@ -122,22 +122,22 @@ android {
// called every time gradle gets executed, takes the native dependencies of // called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders // the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK. // so they get packed with the APK.
task copyAndroidNatives() { task copyAndroidNatives(){
file("libs/armeabi/").mkdirs() file("libs/armeabi/").mkdirs()
file("libs/armeabi-v7a/").mkdirs() file("libs/armeabi-v7a/").mkdirs()
file("libs/arm64-v8a/").mkdirs() file("libs/arm64-v8a/").mkdirs()
file("libs/x86_64/").mkdirs() file("libs/x86_64/").mkdirs()
file("libs/x86/").mkdirs() file("libs/x86/").mkdirs()
configurations.natives.files.each { jar -> configurations.natives.files.each{ jar ->
def outputDir = null def outputDir = null
if (jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a") if(jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if (jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a") if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if (jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi") if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
if (jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64") if(jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if (jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86") if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if (outputDir != null) { if(outputDir != null){
copy { copy{
from zipTree(jar) from zipTree(jar)
into outputDir into outputDir
include "*.so" include "*.so"
@@ -146,21 +146,21 @@ task copyAndroidNatives() {
} }
} }
task run(type: Exec) { task run(type: Exec){
def path def path
def localProperties = project.file("../local.properties") def localProperties = project.file("../local.properties")
if (localProperties.exists()) { if(localProperties.exists()){
Properties properties = new Properties() Properties properties = new Properties()
localProperties.withInputStream { instr -> localProperties.withInputStream{ instr ->
properties.load(instr) properties.load(instr)
} }
def sdkDir = properties.getProperty('sdk.dir') def sdkDir = properties.getProperty('sdk.dir')
if (sdkDir) { if(sdkDir){
path = sdkDir path = sdkDir
} else { }else{
path = "$System.env.ANDROID_HOME" path = "$System.env.ANDROID_HOME"
} }
} else { }else{
path = "$System.env.ANDROID_HOME" path = "$System.env.ANDROID_HOME"
} }
@@ -169,19 +169,19 @@ task run(type: Exec) {
} }
// sets up the Android Idea project, using the old Ant based build. // sets up the Android Idea project, using the old Ant based build.
idea { idea{
module { module{
sourceDirs += file("src") sourceDirs += file("src")
scopes = [COMPILE: [plus: [project.configurations.compile]]] scopes = [COMPILE: [plus: [project.configurations.compile]]]
iml { iml{
withXml { withXml{
def node = it.asNode() def node = it.asNode()
def builder = NodeBuilder.newInstance() def builder = NodeBuilder.newInstance()
builder.current = node builder.current = node
builder.component(name: "FacetManager") { builder.component(name: "FacetManager"){
facet(type: "android", name: "Android") { facet(type: "android", name: "Android"){
configuration { configuration{
option(name: "UPDATE_PROPERTY_FILES", value: "true") option(name: "UPDATE_PROPERTY_FILES", value: "true")
} }
} }
-1
View File
@@ -9,6 +9,5 @@
# #
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target. # Project target.
target=android-19 target=android-19
@@ -18,18 +18,15 @@ import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.layout.Unit; import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Strings; import io.anuke.arc.util.Strings;
import io.anuke.arc.util.serialization.Base64Coder; import io.anuke.arc.util.serialization.Base64Coder;
import io.anuke.net.KryoClient;
import io.anuke.net.KryoServer;
import io.anuke.mindustry.core.Platform; import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.game.Saves.SaveSlot; import io.anuke.mindustry.game.Saves.SaveSlot;
import io.anuke.mindustry.io.SaveIO; import io.anuke.mindustry.io.SaveIO;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.ui.dialogs.FileChooser; import io.anuke.mindustry.ui.dialogs.FileChooser;
import io.anuke.net.KryoClient;
import io.anuke.net.KryoServer;
import java.io.File; import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -59,7 +56,7 @@ public class AndroidLauncher extends AndroidApplication{
int len = s.length(); int len = s.length();
byte[] data = new byte[len / 2]; byte[] data = new byte[len / 2];
for(int i = 0; i < len; i += 2){ for(int i = 0; i < len; i += 2){
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) data[i / 2] = (byte)((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16)); + Character.digit(s.charAt(i + 1), 16));
} }
String result = new String(Base64Coder.encode(data)); String result = new String(Base64Coder.encode(data));
@@ -184,7 +181,7 @@ public class AndroidLauncher extends AndroidApplication{
} }
private boolean isTablet(Context context){ private boolean isTablet(Context context){
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return manager != null && manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE; return manager != null && manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE;
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
apply plugin: "java" apply plugin: "java"
sourceCompatibility = 1.8 sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = [ "src/main/java/" ] sourceSets.main.java.srcDirs = ["src/main/java/"]
sourceSets.main.resources.srcDirs = [ "src/main/resources/" ] sourceSets.main.resources.srcDirs = ["src/main/resources/"]
@@ -1,9 +1,6 @@
package io.anuke.annotations; package io.anuke.annotations;
import java.lang.annotation.ElementType; import java.lang.annotation.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Annotations{ public class Annotations{
@@ -19,25 +16,25 @@ public class Annotations{
} }
/** Marks a class as serializable.*/ /** Marks a class as serializable. */
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
public @interface Serialize{ public @interface Serialize{
} }
/** Marks a class as a special value type struct. Class name must end in 'Struct'.*/ /** Marks a class as a special value type struct. Class name must end in 'Struct'. */
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
public @interface Struct{ public @interface Struct{
} }
/**Marks a field of a struct. Optional.*/ /** Marks a field of a struct. Optional. */
@Target(ElementType.FIELD) @Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
public @interface StructField{ public @interface StructField{
/**Size of a struct field in bits. Not valid on booleans or floating point numbers.*/ /** Size of a struct field in bits. Not valid on booleans or floating point numbers. */
int value(); int value();
} }
@@ -1,7 +1,5 @@
package io.anuke.annotations; package io.anuke.annotations;
import io.anuke.annotations.MethodEntry;
import java.util.ArrayList; import java.util.ArrayList;
/** Represents a class witha list method entries to include in it. */ /** Represents a class witha list method entries to include in it. */
@@ -1,8 +1,6 @@
package io.anuke.annotations; package io.anuke.annotations;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.*;
import io.anuke.annotations.Annotations.PacketPriority;
import io.anuke.annotations.Annotations.Variant;
import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.ExecutableElement;
@@ -1,18 +1,13 @@
package io.anuke.annotations; package io.anuke.annotations;
import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.*;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.annotations.IOFinder.ClassSerializer; import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.annotation.processing.*; import javax.annotation.processing.*;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element; import javax.lang.model.element.*;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind; import javax.tools.Diagnostic.Kind;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -21,14 +16,14 @@ import java.util.stream.Collectors;
/** The annotation processor for generating remote method call code. */ /** The annotation processor for generating remote method call code. */
@SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({ @SupportedAnnotationTypes({
"io.anuke.annotations.Annotations.Remote", "io.anuke.annotations.Annotations.Remote",
"io.anuke.annotations.Annotations.WriteClass", "io.anuke.annotations.Annotations.WriteClass",
"io.anuke.annotations.Annotations.ReadClass", "io.anuke.annotations.Annotations.ReadClass",
}) })
public class RemoteMethodAnnotationProcessor extends AbstractProcessor{ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
/** Maximum size of each event packet. */ /** Maximum size of each event packet. */
public static final int maxPacketSize = 4096; public static final int maxPacketSize = 4096;
/** Warning on top of each autogenerated file.*/ /** Warning on top of each autogenerated file. */
public static final String autogenWarning = "Autogenerated file. Do not modify!\n"; public static final String autogenWarning = "Autogenerated file. Do not modify!\n";
/** Name of the base package to put all the generated classes. */ /** Name of the base package to put all the generated classes. */
private static final String packageName = "io.anuke.mindustry.gen"; private static final String packageName = "io.anuke.mindustry.gen";
@@ -37,7 +32,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
private static final String readServerName = "RemoteReadServer"; private static final String readServerName = "RemoteReadServer";
/** Name of class that handles reading and invoking packets on the client. */ /** Name of class that handles reading and invoking packets on the client. */
private static final String readClientName = "RemoteReadClient"; private static final String readClientName = "RemoteReadClient";
/**Simple class name of generated class name.*/ /** Simple class name of generated class name. */
private static final String callLocation = "Call"; private static final String callLocation = "Call";
/** Processing round number. */ /** Processing round number. */
@@ -115,7 +110,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
//create and add entry //create and add entry
MethodEntry method = new MethodEntry(entry.name, Utils.getMethodName(element), annotation.targets(), annotation.variants(), MethodEntry method = new MethodEntry(entry.name, Utils.getMethodName(element), annotation.targets(), annotation.variants(),
annotation.called(), annotation.unreliable(), annotation.forward(), lastMethodID++, (ExecutableElement) element, annotation.priority()); annotation.called(), annotation.unreliable(), annotation.forward(), lastMethodID++, (ExecutableElement)element, annotation.priority());
entry.methods.add(method); entry.methods.add(method);
methods.add(method); methods.add(method);
@@ -3,9 +3,7 @@ package io.anuke.annotations;
import com.squareup.javapoet.*; import com.squareup.javapoet.*;
import io.anuke.annotations.IOFinder.ClassSerializer; import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.lang.model.element.Modifier; import javax.lang.model.element.*;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic.Kind; import javax.tools.Diagnostic.Kind;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
@@ -25,7 +23,6 @@ public class RemoteReadGenerator{
/** /**
* Generates a class for reading remote invoke packets. * Generates a class for reading remote invoke packets.
*
* @param entries List of methods to use. * @param entries List of methods to use.
* @param className Simple target class name. * @param className Simple target class name.
* @param packageName Full target package name. * @param packageName Full target package name.
@@ -115,7 +112,7 @@ public class RemoteReadGenerator{
//execute the relevant method before the forward //execute the relevant method before the forward
//if it throws a ValidateException, the method won't be forwarded //if it throws a ValidateException, the method won't be forwarded
readBlock.addStatement("$N." + entry.element.getSimpleName() + "(" + varResult.toString() + ")", ((TypeElement) entry.element.getEnclosingElement()).getQualifiedName().toString()); readBlock.addStatement("$N." + entry.element.getSimpleName() + "(" + varResult.toString() + ")", ((TypeElement)entry.element.getEnclosingElement()).getQualifiedName().toString());
//call forwarded method, don't forward on the client reader //call forwarded method, don't forward on the client reader
if(entry.forward && entry.where.isServer && needsPlayer){ if(entry.forward && entry.where.isServer && needsPlayer){
@@ -4,10 +4,7 @@ import com.squareup.javapoet.*;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.IOFinder.ClassSerializer; import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.*;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.Diagnostic.Kind; import javax.tools.Diagnostic.Kind;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@@ -119,7 +116,7 @@ public class RemoteWriteGenerator{
//add the statement to call it //add the statement to call it
method.addStatement("$N." + elem.getSimpleName() + "(" + results.toString() + ")", method.addStatement("$N." + elem.getSimpleName() + "(" + results.toString() + ")",
((TypeElement) elem.getEnclosingElement()).getQualifiedName().toString()); ((TypeElement)elem.getEnclosingElement()).getQualifiedName().toString());
if(methodEntry.local != Loc.both){ if(methodEntry.local != Loc.both){
method.endControlFlow(); method.endControlFlow();
@@ -5,13 +5,9 @@ import io.anuke.annotations.Annotations.Serialize;
import javax.annotation.processing.*; import javax.annotation.processing.*;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier; import javax.lang.model.element.*;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter; import javax.lang.model.util.ElementFilter;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -21,7 +17,7 @@ import java.util.Set;
"io.anuke.annotations.Annotations.Serialize" "io.anuke.annotations.Annotations.Serialize"
}) })
public class SerializeAnnotationProcessor extends AbstractProcessor{ public class SerializeAnnotationProcessor extends AbstractProcessor{
/**Target class name.*/ /** Target class name. */
private static final String className = "Serialization"; private static final String className = "Serialization";
/** Name of the base package to put all the generated classes. */ /** Name of the base package to put all the generated classes. */
private static final String packageName = "io.anuke.mindustry.gen"; private static final String packageName = "io.anuke.mindustry.gen";
@@ -99,7 +95,8 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
List<VariableElement> fields = ElementFilter.fieldsIn(Utils.elementUtils.getAllMembers(elem)); List<VariableElement> fields = ElementFilter.fieldsIn(Utils.elementUtils.getAllMembers(elem));
for(VariableElement field : fields){ for(VariableElement field : fields){
if(field.getModifiers().contains(Modifier.STATIC) || field.getModifiers().contains(Modifier.TRANSIENT) || field.getModifiers().contains(Modifier.PRIVATE)) continue; if(field.getModifiers().contains(Modifier.STATIC) || field.getModifiers().contains(Modifier.TRANSIENT) || field.getModifiers().contains(Modifier.PRIVATE))
continue;
String name = field.getSimpleName().toString(); String name = field.getSimpleName().toString();
String typeName = Utils.typeUtils.erasure(field.asType()).toString().replace('$', '.'); String typeName = Utils.typeUtils.erasure(field.asType()).toString().replace('$', '.');
@@ -109,11 +106,11 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
writeMethod.addStatement("stream.write" + capName + "(object." + name + ")"); writeMethod.addStatement("stream.write" + capName + "(object." + name + ")");
readMethod.addStatement("object." + name + "= stream.read" + capName + "()"); readMethod.addStatement("object." + name + "= stream.read" + capName + "()");
jsonWriteMethod.addStatement("json.writeValue(\"" + name + "\", object." + name +")"); jsonWriteMethod.addStatement("json.writeValue(\"" + name + "\", object." + name + ")");
jsonReadMethod.addStatement("if(value.has(\"" + name + "\")) object." + name + "= value.get" + capName + "(\"" + name + "\")"); jsonReadMethod.addStatement("if(value.has(\"" + name + "\")) object." + name + "= value.get" + capName + "(\"" + name + "\")");
}else{ }else{
writeMethod.addStatement("io.anuke.arc.Core.settings.getSerializer(" + typeName+ ".class).write(stream, object." + name + ")"); writeMethod.addStatement("io.anuke.arc.Core.settings.getSerializer(" + typeName + ".class).write(stream, object." + name + ")");
readMethod.addStatement("object." + name + " = (" +typeName+")io.anuke.arc.Core.settings.getSerializer(" + typeName+ ".class).read(stream)"); readMethod.addStatement("object." + name + " = (" + typeName + ")io.anuke.arc.Core.settings.getSerializer(" + typeName + ".class).read(stream)");
} }
} }
@@ -1,28 +1,25 @@
package io.anuke.annotations; package io.anuke.annotations;
import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.*;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import io.anuke.annotations.Annotations.Struct; import io.anuke.annotations.Annotations.Struct;
import io.anuke.annotations.Annotations.StructField; import io.anuke.annotations.Annotations.StructField;
import javax.annotation.processing.*; import javax.annotation.processing.*;
import javax.lang.model.SourceVersion; import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier; import javax.lang.model.element.*;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeKind;
import javax.lang.model.util.ElementFilter; import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic.Kind; import javax.tools.Diagnostic.Kind;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/**Generates ""value types"" classes that are packed into integer primitives of the most aproppriate size. /**
* It would be nice if Java didn't make crazy hacks like this necessary.*/ * Generates ""value types"" classes that are packed into integer primitives of the most aproppriate size.
* It would be nice if Java didn't make crazy hacks like this necessary.
*/
@SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({ @SupportedAnnotationTypes({
"io.anuke.annotations.Annotations.Struct" "io.anuke.annotations.Annotations.Struct"
}) })
public class StructAnnotationProcessor extends AbstractProcessor{ public class StructAnnotationProcessor extends AbstractProcessor{
/** Name of the base package to put all the generated classes. */ /** Name of the base package to put all the generated classes. */
@@ -209,7 +206,7 @@ public class StructAnnotationProcessor extends AbstractProcessor{
throw new IllegalArgumentException("Too many fields, must fit in 64 bits. Curent size: " + size); throw new IllegalArgumentException("Too many fields, must fit in 64 bits. Curent size: " + size);
} }
/**returns a type's element size in bits.*/ /** returns a type's element size in bits. */
static int typeSize(TypeKind kind) throws IllegalArgumentException{ static int typeSize(TypeKind kind) throws IllegalArgumentException{
switch(kind){ switch(kind){
case BOOLEAN: case BOOLEAN:
@@ -14,7 +14,7 @@ public class Utils{
public static Messager messager; public static Messager messager;
public static String getMethodName(Element element){ public static String getMethodName(Element element){
return ((TypeElement) element.getEnclosingElement()).getQualifiedName().toString() + "." + element.getSimpleName(); return ((TypeElement)element.getEnclosingElement()).getQualifiedName().toString() + "." + element.getSimpleName();
} }
public static boolean isPrimitive(String type){ public static boolean isPrimitive(String type){
+2 -1
View File
@@ -89,7 +89,8 @@ allprojects{
try{ try{
pfile.createNewFile() pfile.createNewFile()
}catch(Exception ignored){} }catch(Exception ignored){
}
if(pfile.exists()){ if(pfile.exists()){
props.load(new FileInputStream(pfile)) props.load(new FileInputStream(pfile))
@@ -4,5 +4,5 @@
flattenPaths: true, flattenPaths: true,
maxWidth: 2048, maxWidth: 2048,
maxHeight: 2048, maxHeight: 2048,
fast: true, fast: true
} }
@@ -4,5 +4,5 @@
flattenPaths: true, flattenPaths: true,
maxWidth: 1024, maxWidth: 1024,
maxHeight: 1024, maxHeight: 1024,
fast: true, fast: true
} }
+1 -1
View File
@@ -4,5 +4,5 @@
flattenPaths: true, flattenPaths: true,
maxWidth: 2048, maxWidth: 2048,
maxHeight: 2048, maxHeight: 2048,
fast: true, fast: true
} }
+1 -1
View File
@@ -4,5 +4,5 @@
flattenPaths: true, flattenPaths: true,
maxWidth: 1024, maxWidth: 1024,
maxHeight: 1024, maxHeight: 1024,
fast: true, fast: true
} }
@@ -4,5 +4,5 @@
flattenPaths: true, flattenPaths: true,
maxWidth: 2048, maxWidth: 2048,
maxHeight: 2048, maxHeight: 2048,
fast: true, fast: true
} }
-13
View File
@@ -14,7 +14,6 @@ screenshot = 화면 캡쳐가 {0} 경로에 저장되었습니다.
gameover = 게임 오버 gameover = 게임 오버
gameover.pvp = [accent]{0}[] 팀이 승리했습니다! gameover.pvp = [accent]{0}[] 팀이 승리했습니다!
highscore = [accent]최고점수 달성! highscore = [accent]최고점수 달성!
stat.wave = 웨이브 성공:[accent]{0} stat.wave = 웨이브 성공:[accent]{0}
stat.enemiesDestroyed = 파괴한 적 수:[accent]{0} stat.enemiesDestroyed = 파괴한 적 수:[accent]{0}
stat.built = 건설한 건물 수:[accent]{0} stat.built = 건설한 건물 수:[accent]{0}
@@ -22,10 +21,8 @@ stat.destroyed = 파괴된 건물 수:[accent]{0}
stat.deconstructed = 파괴한 건물 수:[accent]{0} stat.deconstructed = 파괴한 건물 수:[accent]{0}
stat.delivered = 획득한 자원: stat.delivered = 획득한 자원:
stat.rank = 최종 기록: [accent]{0} stat.rank = 최종 기록: [accent]{0}
placeline = 블록을 선택하셨습니다.\n][accent]몇초간 설치 시작지점을 누르고[] 원하는 방향을 향해 드래그 하면 [accent]일렬로[] 설치할 수 있습니다.\n한번 해 보세요. placeline = 블록을 선택하셨습니다.\n][accent]몇초간 설치 시작지점을 누르고[] 원하는 방향을 향해 드래그 하면 [accent]일렬로[] 설치할 수 있습니다.\n한번 해 보세요.
removearea = 블록 제거모드를 선택하셨습니다.\n[accent]몇초간 제거 시작지점을 누르고[] 원하는 구역 끝을 향해 드래그 하면 [accent]직사각형[] 안에 있는 모든 건물을 제거할 수 있습니다.\n한번 해 보세요. removearea = 블록 제거모드를 선택하셨습니다.\n[accent]몇초간 제거 시작지점을 누르고[] 원하는 구역 끝을 향해 드래그 하면 [accent]직사각형[] 안에 있는 모든 건물을 제거할 수 있습니다.\n한번 해 보세요.
launcheditems = [accent]출격 아이템 launcheditems = [accent]출격 아이템
map.delete = 정말로 "[accent]{0}[]" 맵을 삭제하시겠습니까?\n map.delete = 정말로 "[accent]{0}[]" 맵을 삭제하시겠습니까?\n
level.highscore = 최고 점수: [accent]{0} level.highscore = 최고 점수: [accent]{0}
@@ -284,7 +281,6 @@ tutorial = 게임 방법
editor = 편집기 editor = 편집기
mapeditor = 맵 편집기 mapeditor = 맵 편집기
donate = 기부 donate = 기부
abandon = 포기 abandon = 포기
abandon.text = 이 구역과 모든 자원이 적에게 빼앗길 것입니다. abandon.text = 이 구역과 모든 자원이 적에게 빼앗길 것입니다.
locked = 잠김 locked = 잠김
@@ -306,7 +302,6 @@ zone.config.complete = 웨이브 {0} 달성:\n로드아웃 설정 잠금 해제
zone.resources = 자원 감지됨: zone.resources = 자원 감지됨:
add = 추가... add = 추가...
boss.health = 보스 체력 boss.health = 보스 체력
connectfail = [crimson]{0}[accent] 서버에 연결하지 못했습니다.[] connectfail = [crimson]{0}[accent] 서버에 연결하지 못했습니다.[]
error.unreachable = 서버에 연결하지 못했습니다.\n서버 주소가 정확히 입력되었나요? error.unreachable = 서버에 연결하지 못했습니다.\n서버 주소가 정확히 입력되었나요?
error.invalidaddress = 잘못된 주소입니다. error.invalidaddress = 잘못된 주소입니다.
@@ -316,7 +311,6 @@ error.alreadyconnected = 이미 접속중입니다.
error.mapnotfound = 맵 파일을 찾을 수 없습니다! error.mapnotfound = 맵 파일을 찾을 수 없습니다!
error.io = 네트워크 I/O 오류. error.io = 네트워크 I/O 오류.
error.any = 알 수 없는 네트워크 오류. error.any = 알 수 없는 네트워크 오류.
zone.groundZero.name = 그라운드 제로 zone.groundZero.name = 그라운드 제로
zone.craters.name = 분화구 zone.craters.name = 분화구
zone.frozenForest.name = 얼어붙은 숲 zone.frozenForest.name = 얼어붙은 숲
@@ -324,7 +318,6 @@ zone.ruinousShores.name = 파멸의 기슭
zone.stainedMountains.name = 얼룩진 산맥 zone.stainedMountains.name = 얼룩진 산맥
zone.desolateRift.name = 황량한 강 zone.desolateRift.name = 황량한 강
zone.nuclearComplex.name = 핵 생산 단지 zone.nuclearComplex.name = 핵 생산 단지
settings.language = 언어 settings.language = 언어
settings.reset = 설정 초기화 settings.reset = 설정 초기화
settings.rebind = 키 재설정 settings.rebind = 키 재설정
@@ -384,7 +377,6 @@ bar.heat = 발열
bar.power = 전력 bar.power = 전력
bar.progress = 건설 진행 bar.progress = 건설 진행
bar.spawned = 유닛: {0}/{1} bar.spawned = 유닛: {0}/{1}
bullet.damage = [stat]{0}[lightgray] 데미지 bullet.damage = [stat]{0}[lightgray] 데미지
bullet.splashdamage = [stat]{0}[lightgray] area 데미지 ~[stat] {1}[lightgray] 타일 bullet.splashdamage = [stat]{0}[lightgray] area 데미지 ~[stat] {1}[lightgray] 타일
bullet.incendiary = [stat]방화 bullet.incendiary = [stat]방화
@@ -396,7 +388,6 @@ bullet.freezing = [stat]동결
bullet.tarred = [stat]타르 bullet.tarred = [stat]타르
bullet.multiplier = [stat]{0}[lightgray]x 탄약 배율 bullet.multiplier = [stat]{0}[lightgray]x 탄약 배율
bullet.reload = [stat]{0}[lightgray]x 사격 속도 bullet.reload = [stat]{0}[lightgray]x 사격 속도
unit.blocks = 블록 unit.blocks = 블록
unit.powersecond = 전력/초 unit.powersecond = 전력/초
unit.liquidsecond = 액체/초 unit.liquidsecond = 액체/초
@@ -497,7 +488,6 @@ mode.pvp.description = 실제 플레이어와 PvP를 합니다.
mode.attack.name = 공격 mode.attack.name = 공격
mode.attack.description = 일정 시간마다 적이 오는 단계가 없으며, 적의 기지를 파괴하는 것을 목표로 합니다. mode.attack.description = 일정 시간마다 적이 오는 단계가 없으며, 적의 기지를 파괴하는 것을 목표로 합니다.
mode.custom = 커스텀 규칙 mode.custom = 커스텀 규칙
rules.infiniteresources = 무한 자원 rules.infiniteresources = 무한 자원
rules.wavetimer = 웨이브 타이머 rules.wavetimer = 웨이브 타이머
rules.waves = 웨이브 rules.waves = 웨이브
@@ -512,7 +502,6 @@ rules.respawntime = 리스폰 시간:[LIGHT_GRAY] (초)
rules.wavespacing = 웨이브 간격:[LIGHT_GRAY] (초) rules.wavespacing = 웨이브 간격:[LIGHT_GRAY] (초)
rules.buildcostmultiplier = 건설 소모 배율 rules.buildcostmultiplier = 건설 소모 배율
rules.buildspeedmultiplier = 건설 속도 배율 rules.buildspeedmultiplier = 건설 속도 배율
content.item.name = 아이템 content.item.name = 아이템
content.liquid.name = 액체 content.liquid.name = 액체
content.unit.name = 유닛 content.unit.name = 유닛
@@ -597,7 +586,6 @@ mech.buildspeed = [LIGHT_GRAY]건설 속도: {0}%
liquid.heatcapacity = [LIGHT_GRAY]발열 용량: {0} liquid.heatcapacity = [LIGHT_GRAY]발열 용량: {0}
liquid.viscosity = [LIGHT_GRAY]점도: {0} liquid.viscosity = [LIGHT_GRAY]점도: {0}
liquid.temperature = [LIGHT_GRAY]온도: {0} liquid.temperature = [LIGHT_GRAY]온도: {0}
block.grass.name = 잔디 block.grass.name = 잔디
block.salt.name = 소금 block.salt.name = 소금
block.sandrocks.name = 모래 바위 block.sandrocks.name = 모래 바위
@@ -896,7 +884,6 @@ block.wraith-factory.description = 빠른 뺑소니 요격기 유닛을 생산
block.ghoul-factory.description = 중탄두 폭격기를 생산합니다. block.ghoul-factory.description = 중탄두 폭격기를 생산합니다.
block.dagger-factory.description = 기본 지상 유닛을 생산합니다. block.dagger-factory.description = 기본 지상 유닛을 생산합니다.
block.titan-factory.description = 첨단 장갑 지상부대를 생산합니다. block.titan-factory.description = 첨단 장갑 지상부대를 생산합니다.
block.fortress-factory.description = 중대포 지상부대를 생산합니다. block.fortress-factory.description = 중대포 지상부대를 생산합니다.
block.revenant-factory.description = 중량의 레이저 포대를 가진 공중부대를 생산합니다. block.revenant-factory.description = 중량의 레이저 포대를 가진 공중부대를 생산합니다.
block.repair-point.description = 주변에서 가장 가까운 손상된 유닛을 지속적으로 치료합니다. block.repair-point.description = 주변에서 가장 가까운 손상된 유닛을 지속적으로 치료합니다.
+2 -4
View File
@@ -1,8 +1,6 @@
package io.anuke.mindustry; package io.anuke.mindustry;
import io.anuke.arc.ApplicationCore; import io.anuke.arc.*;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.util.Log; import io.anuke.arc.util.Log;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.mindustry.core.*; import io.anuke.mindustry.core.*;
@@ -55,7 +53,7 @@ public class Mindustry extends ApplicationCore{
int fpsCap = Core.settings.getInt("fpscap", 125); int fpsCap = Core.settings.getInt("fpscap", 125);
if(fpsCap <= 120){ if(fpsCap <= 120){
long target = (1000 * 1000000)/fpsCap; //target in nanos long target = (1000 * 1000000) / fpsCap; //target in nanos
long elapsed = Time.timeSinceNanos(lastFrameTime); long elapsed = Time.timeSinceNanos(lastFrameTime);
if(elapsed < target){ if(elapsed < target){
try{ try{
+40 -44
View File
@@ -14,12 +14,8 @@ import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.entities.impl.EffectEntity; import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.mindustry.entities.traits.DrawTrait; import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.traits.SyncTrait; import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.entities.type.BaseUnit; import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.game.*;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.game.GlobalData;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.gen.Serialization; import io.anuke.mindustry.gen.Serialization;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity; import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity;
@@ -30,49 +26,49 @@ import java.util.Locale;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class Vars{ public class Vars{
/**IO buffer size.*/ /** IO buffer size. */
public static final int bufferSize = 8192; public static final int bufferSize = 8192;
/**global charset*/ /** global charset */
public static final Charset charset = Charset.forName("UTF-8"); public static final Charset charset = Charset.forName("UTF-8");
/**main application name, capitalized*/ /** main application name, capitalized */
public static final String appName = "Mindustry"; public static final String appName = "Mindustry";
/**URL for itch.io donations.*/ /** URL for itch.io donations. */
public static final String donationURL = "https://anuke.itch.io/mindustry/purchase"; public static final String donationURL = "https://anuke.itch.io/mindustry/purchase";
/**URL for discord invite.*/ /** URL for discord invite. */
public static final String discordURL = "https://discord.gg/mindustry"; public static final String discordURL = "https://discord.gg/mindustry";
/**URL for Github API for releases*/ /** URL for Github API for releases */
public static final String releasesURL = "https://api.github.com/repos/Anuken/Mindustry/releases"; public static final String releasesURL = "https://api.github.com/repos/Anuken/Mindustry/releases";
/**URL for Github API for contributors*/ /** URL for Github API for contributors */
public static final String contributorsURL = "https://api.github.com/repos/Anuken/Mindustry/contributors"; public static final String contributorsURL = "https://api.github.com/repos/Anuken/Mindustry/contributors";
/**URL for sending crash reports to*/ /** URL for sending crash reports to */
public static final String crashReportURL = "http://mindustry.us.to/report"; public static final String crashReportURL = "http://mindustry.us.to/report";
/**maximum distance between mine and core that supports automatic transferring*/ /** maximum distance between mine and core that supports automatic transferring */
public static final float mineTransferRange = 220f; public static final float mineTransferRange = 220f;
/**team of the player by default*/ /** team of the player by default */
public static final Team defaultTeam = Team.blue; public static final Team defaultTeam = Team.blue;
/**team of the enemy in waves/sectors*/ /** team of the enemy in waves/sectors */
public static final Team waveTeam = Team.red; public static final Team waveTeam = Team.red;
/**how many times longer a boss wave takes*/ /** how many times longer a boss wave takes */
public static final float bossWaveMultiplier = 3f; public static final float bossWaveMultiplier = 3f;
/**how many times longer a launch wave takes*/ /** how many times longer a launch wave takes */
public static final float launchWaveMultiplier = 2f; public static final float launchWaveMultiplier = 2f;
/**max chat message length*/ /** max chat message length */
public static final int maxTextLength = 150; public static final int maxTextLength = 150;
/**max player name length in bytes*/ /** max player name length in bytes */
public static final int maxNameLength = 40; public static final int maxNameLength = 40;
/**displayed item size when ingame, TODO remove.*/ /** displayed item size when ingame, TODO remove. */
public static final float itemSize = 5f; public static final float itemSize = 5f;
/**extra padding around the world; units outside this bound will begin to self-destruct.*/ /** extra padding around the world; units outside this bound will begin to self-destruct. */
public static final float worldBounds = 100f; public static final float worldBounds = 100f;
/**units outside of this bound will simply die instantly*/ /** units outside of this bound will simply die instantly */
public static final float finalWorldBounds = worldBounds + 500; public static final float finalWorldBounds = worldBounds + 500;
/**ticks spent out of bound until self destruct.*/ /** ticks spent out of bound until self destruct. */
public static final float boundsCountdown = 60*7; public static final float boundsCountdown = 60 * 7;
/**for map generator dialog*/ /** for map generator dialog */
public static boolean updateEditorOnChange = false; public static boolean updateEditorOnChange = false;
/**size of tiles in units*/ /** size of tiles in units */
public static final int tilesize = 8; public static final int tilesize = 8;
/**all choosable player colors in join/host dialog*/ /** all choosable player colors in join/host dialog */
public static final Color[] playerColors = { public static final Color[] playerColors = {
Color.valueOf("82759a"), Color.valueOf("82759a"),
Color.valueOf("c0c1c5"), Color.valueOf("c0c1c5"),
@@ -91,34 +87,34 @@ public class Vars{
Color.valueOf("4b5ef1"), Color.valueOf("4b5ef1"),
Color.valueOf("2cabfe"), Color.valueOf("2cabfe"),
}; };
/**default server port*/ /** default server port */
public static final int port = 6567; public static final int port = 6567;
/**if true, UI is not drawn*/ /** if true, UI is not drawn */
public static boolean disableUI; public static boolean disableUI;
/**if true, game is set up in mobile mode, even on desktop. used for debugging*/ /** if true, game is set up in mobile mode, even on desktop. used for debugging */
public static boolean testMobile; public static boolean testMobile;
/**whether the game is running on a mobile device*/ /** whether the game is running on a mobile device */
public static boolean mobile; public static boolean mobile;
/**whether the game is running on an iOS device*/ /** whether the game is running on an iOS device */
public static boolean ios; public static boolean ios;
/**whether the game is running on an Android device*/ /** whether the game is running on an Android device */
public static boolean android; public static boolean android;
/**whether the game is running on a headless server*/ /** whether the game is running on a headless server */
public static boolean headless; public static boolean headless;
/**application data directory, equivalent to {@link io.anuke.arc.Settings#getDataDirectory()}*/ /** application data directory, equivalent to {@link io.anuke.arc.Settings#getDataDirectory()} */
public static FileHandle dataDirectory; public static FileHandle dataDirectory;
/**data subdirectory used for screenshots*/ /** data subdirectory used for screenshots */
public static FileHandle screenshotDirectory; public static FileHandle screenshotDirectory;
/**data subdirectory used for custom mmaps*/ /** data subdirectory used for custom mmaps */
public static FileHandle customMapDirectory; public static FileHandle customMapDirectory;
/**data subdirectory used for saves*/ /** data subdirectory used for saves */
public static FileHandle saveDirectory; public static FileHandle saveDirectory;
/**map file extension*/ /** map file extension */
public static final String mapExtension = "mmap"; public static final String mapExtension = "mmap";
/**save file extension*/ /** save file extension */
public static final String saveExtension = "msav"; public static final String saveExtension = "msav";
/**list of all locales that can be switched to*/ /** list of all locales that can be switched to */
public static Locale[] locales; public static Locale[] locales;
public static ContentLoader content; public static ContentLoader content;
@@ -143,7 +139,7 @@ public class Vars{
public static EntityGroup<Fire> fireGroup; public static EntityGroup<Fire> fireGroup;
public static EntityGroup<BaseUnit>[] unitGroups; public static EntityGroup<BaseUnit>[] unitGroups;
/**all local players, currently only has one player. may be used for local co-op in the future*/ /** all local players, currently only has one player. may be used for local co-op in the future */
public static Player player; public static Player player;
public static void init(){ public static void init(){
@@ -17,31 +17,31 @@ import io.anuke.mindustry.world.meta.BlockFlag;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
/**Class used for indexing special target blocks for AI.*/ /** Class used for indexing special target blocks for AI. */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class BlockIndexer{ public class BlockIndexer{
/**Size of one ore quadrant.*/ /** Size of one ore quadrant. */
private final static int oreQuadrantSize = 20; private final static int oreQuadrantSize = 20;
/**Size of one structure quadrant.*/ /** Size of one structure quadrant. */
private final static int structQuadrantSize = 12; private final static int structQuadrantSize = 12;
/**Set of all ores that are being scanned.*/ /** Set of all ores that are being scanned. */
private final ObjectSet<Item> scanOres = ObjectSet.with(Item.getAllOres().toArray(Item.class)); private final ObjectSet<Item> scanOres = ObjectSet.with(Item.getAllOres().toArray(Item.class));
private final ObjectSet<Item> itemSet = new ObjectSet<>(); private final ObjectSet<Item> itemSet = new ObjectSet<>();
/**Stores all ore quadtrants on the map.*/ /** Stores all ore quadtrants on the map. */
private ObjectMap<Item, ObjectSet<Tile>> ores; private ObjectMap<Item, ObjectSet<Tile>> ores;
/**Tags all quadrants.*/ /** Tags all quadrants. */
private Bits[] structQuadrants; private Bits[] structQuadrants;
/**Stores all damaged tile entities by team.*/ /** Stores all damaged tile entities by team. */
private ObjectSet<Tile>[] damagedTiles = new ObjectSet[Team.all.length]; private ObjectSet<Tile>[] damagedTiles = new ObjectSet[Team.all.length];
/**Maps teams to a map of flagged tiles by type.*/ /** Maps teams to a map of flagged tiles by type. */
private ObjectSet<Tile>[][] flagMap = new ObjectSet[Team.all.length][BlockFlag.all.length]; private ObjectSet<Tile>[][] flagMap = new ObjectSet[Team.all.length][BlockFlag.all.length];
/**Maps tile positions to their last known tile index data.*/ /** Maps tile positions to their last known tile index data. */
private IntMap<TileIndex> typeMap = new IntMap<>(); private IntMap<TileIndex> typeMap = new IntMap<>();
/**Empty set used for returning.*/ /** Empty set used for returning. */
private ObjectSet<Tile> emptySet = new ObjectSet<>(); private ObjectSet<Tile> emptySet = new ObjectSet<>();
/**Array used for returning and reusing.*/ /** Array used for returning and reusing. */
private Array<Tile> returnArray = new Array<>(); private Array<Tile> returnArray = new Array<>();
public BlockIndexer(){ public BlockIndexer(){
@@ -72,7 +72,7 @@ public class BlockIndexer{
//create bitset for each team type that contains each quadrant //create bitset for each team type that contains each quadrant
structQuadrants = new Bits[Team.all.length]; structQuadrants = new Bits[Team.all.length];
for(int i = 0; i < Team.all.length; i++){ for(int i = 0; i < Team.all.length; i++){
structQuadrants[i] = new Bits(Mathf.ceil(world.width() / (float) structQuadrantSize) * Mathf.ceil(world.height() / (float) structQuadrantSize)); structQuadrants[i] = new Bits(Mathf.ceil(world.width() / (float)structQuadrantSize) * Mathf.ceil(world.height() / (float)structQuadrantSize));
} }
for(int x = 0; x < world.width(); x++){ for(int x = 0; x < world.width(); x++){
@@ -101,7 +101,7 @@ public class BlockIndexer{
return flagMap[team.ordinal()]; return flagMap[team.ordinal()];
} }
/**Returns all damaged tiles by team.*/ /** Returns all damaged tiles by team. */
public ObjectSet<Tile> getDamaged(Team team){ public ObjectSet<Tile> getDamaged(Team team){
returnArray.clear(); returnArray.clear();
@@ -123,12 +123,12 @@ public class BlockIndexer{
return set; return set;
} }
/**Get all allied blocks with a flag.*/ /** Get all allied blocks with a flag. */
public ObjectSet<Tile> getAllied(Team team, BlockFlag type){ public ObjectSet<Tile> getAllied(Team team, BlockFlag type){
return flagMap[team.ordinal()][type.ordinal()]; return flagMap[team.ordinal()][type.ordinal()];
} }
/**Get all enemy blocks with a flag.*/ /** Get all enemy blocks with a flag. */
public Array<Tile> getEnemy(Team team, BlockFlag type){ public Array<Tile> getEnemy(Team team, BlockFlag type){
returnArray.clear(); returnArray.clear();
for(Team enemy : state.teams.enemiesOf(team)){ for(Team enemy : state.teams.enemiesOf(team)){
@@ -154,8 +154,8 @@ public class BlockIndexer{
TileEntity closest = null; TileEntity closest = null;
float dst = 0; float dst = 0;
for(int rx = Math.max((int) ((x - range) / tilesize / structQuadrantSize), 0); rx <= (int) ((x + range) / tilesize / structQuadrantSize) && rx < quadWidth(); rx++){ for(int rx = Math.max((int)((x - range) / tilesize / structQuadrantSize), 0); rx <= (int)((x + range) / tilesize / structQuadrantSize) && rx < quadWidth(); rx++){
for(int ry = Math.max((int) ((y - range) / tilesize / structQuadrantSize), 0); ry <= (int) ((y + range) / tilesize / structQuadrantSize) && ry < quadHeight(); ry++){ for(int ry = Math.max((int)((y - range) / tilesize / structQuadrantSize), 0); ry <= (int)((y + range) / tilesize / structQuadrantSize) && ry < quadHeight(); ry++){
if(!getQuad(team, rx, ry)) continue; if(!getQuad(team, rx, ry)) continue;
@@ -167,7 +167,8 @@ public class BlockIndexer{
other = other.target(); other = other.target();
if(other.entity == null || other.getTeam() != team || !pred.test(other) || !other.block().targetable) continue; if(other.entity == null || other.getTeam() != team || !pred.test(other) || !other.block().targetable)
continue;
TileEntity e = other.entity; TileEntity e = other.entity;
@@ -194,7 +195,7 @@ public class BlockIndexer{
return ores.get(item, emptySet); return ores.get(item, emptySet);
} }
/**Find the closest ore block relative to a position.*/ /** Find the closest ore block relative to a position. */
public Tile findClosestOre(float xp, float yp, Item item){ public Tile findClosestOre(float xp, float yp, Item item){
Tile tile = Geometry.findClosest(xp, yp, world.indexer.getOrePositions(item)); Tile tile = Geometry.findClosest(xp, yp, world.indexer.getOrePositions(item));
@@ -241,7 +242,7 @@ public class BlockIndexer{
for(int x = quadrantX * structQuadrantSize; x < world.width() && x < (quadrantX + 1) * structQuadrantSize; x++){ for(int x = quadrantX * structQuadrantSize; x < world.width() && x < (quadrantX + 1) * structQuadrantSize; x++){
for(int y = quadrantY * structQuadrantSize; y < world.height() && y < (quadrantY + 1) * structQuadrantSize; y++){ for(int y = quadrantY * structQuadrantSize; y < world.height() && y < (quadrantY + 1) * structQuadrantSize; y++){
Tile result = world.tile(x, y); Tile result = world.tile(x, y);
if( result == null || result.drop() == null || !scanOres.contains(result.drop())) continue; if(result == null || result.drop() == null || !scanOres.contains(result.drop())) continue;
itemSet.add(result.drop()); itemSet.add(result.drop());
} }
@@ -294,16 +295,16 @@ public class BlockIndexer{
} }
private boolean getQuad(Team team, int quadrantX, int quadrantY){ private boolean getQuad(Team team, int quadrantX, int quadrantY){
int index = quadrantX + quadrantY * Mathf.ceil(world.width() / (float) structQuadrantSize); int index = quadrantX + quadrantY * Mathf.ceil(world.width() / (float)structQuadrantSize);
return structQuadrants[team.ordinal()].get(index); return structQuadrants[team.ordinal()].get(index);
} }
private int quadWidth(){ private int quadWidth(){
return Mathf.ceil(world.width() / (float) structQuadrantSize); return Mathf.ceil(world.width() / (float)structQuadrantSize);
} }
private int quadHeight(){ private int quadHeight(){
return Mathf.ceil(world.height() / (float) structQuadrantSize); return Mathf.ceil(world.height() / (float)structQuadrantSize);
} }
private void scanOres(){ private void scanOres(){
@@ -65,7 +65,7 @@ public class Pathfinder{
Tile other = world.tile(dx, dy); Tile other = world.tile(dx, dy);
if(other == null) continue; if(other == null) continue;
if(values[dx][dy] < value && (target == null || values[dx][dy]< tl) && if(values[dx][dy] < value && (target == null || values[dx][dy] < tl) &&
!other.solid() && !other.solid() &&
!(point.x != 0 && point.y != 0 && (world.solid(tile.x + point.x, tile.y) || world.solid(tile.x, tile.y + point.y)))){ //diagonal corner trap !(point.x != 0 && point.y != 0 && (world.solid(tile.x + point.x, tile.y) || world.solid(tile.x, tile.y + point.y)))){ //diagonal corner trap
target = other; target = other;
@@ -86,8 +86,10 @@ public class Pathfinder{
return (!tile.solid()) || (tile.breakable() && (tile.target().getTeam() != team)); return (!tile.solid()) || (tile.breakable() && (tile.target().getTeam() != team));
} }
/**Clears the frontier, increments the search and sets up all flow sources. /**
* This only occurs for active teams.*/ * Clears the frontier, increments the search and sets up all flow sources.
* This only occurs for active teams.
*/
private void update(Tile tile, Team team){ private void update(Tile tile, Team team){
//make sure team exists //make sure team exists
if(paths != null && paths[team.ordinal()] != null && paths[team.ordinal()].weights != null){ if(paths != null && paths[team.ordinal()] != null && paths[team.ordinal()].weights != null){
@@ -16,9 +16,7 @@ import io.anuke.mindustry.game.SpawnGroup;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.Pos; import io.anuke.mindustry.world.Pos;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -56,7 +54,7 @@ public class WaveSpawner{
return groundSpawns.size; return groundSpawns.size;
} }
/**@return true if the player is near a ground spawn point.*/ /** @return true if the player is near a ground spawn point. */
public boolean playerNear(){ public boolean playerNear(){
return groundSpawns.count(g -> Mathf.dst(g.x * tilesize, g.y * tilesize, player.x, player.y) < maxShockwaveDst) > 0; return groundSpawns.count(g -> Mathf.dst(g.x * tilesize, g.y * tilesize, player.x, player.y) < maxShockwaveDst) > 0;
} }
@@ -88,7 +86,7 @@ public class WaveSpawner{
for(GroundSpawn spawn : groundSpawns){ for(GroundSpawn spawn : groundSpawns){
spawnX = spawn.x * tilesize; spawnX = spawn.x * tilesize;
spawnY = spawn.y * tilesize; spawnY = spawn.y * tilesize;
spread = tilesize*2; spread = tilesize * 2;
for(int i = 0; i < spawned; i++){ for(int i = 0; i < spawned; i++){
Tmp.v1.rnd(spread); Tmp.v1.rnd(spread);
@@ -96,7 +94,7 @@ public class WaveSpawner{
BaseUnit unit = group.createUnit(waveTeam); BaseUnit unit = group.createUnit(waveTeam);
unit.set(spawnX + Tmp.v1.x, spawnY + Tmp.v1.y); unit.set(spawnX + Tmp.v1.x, spawnY + Tmp.v1.y);
Time.run(Math.min(i*5, 60*2), () -> shockwave(unit)); Time.run(Math.min(i * 5, 60 * 2), () -> shockwave(unit));
} }
Time.run(20f, () -> Effects.effect(Fx.spawnShockwave, spawn.x * tilesize, spawn.y * tilesize)); Time.run(20f, () -> Effects.effect(Fx.spawnShockwave, spawn.x * tilesize, spawn.y * tilesize));
//would be interesting to see player structures survive this without hacks //would be interesting to see player structures survive this without hacks
@@ -125,7 +123,7 @@ public class WaveSpawner{
//hide spawnpoints, they have served their purpose //hide spawnpoints, they have served their purpose
world.tile(x, y).setBlock(Blocks.air); world.tile(x, y).setBlock(Blocks.air);
Log.info("Add spawn "+ x + " " + y); Log.info("Add spawn " + x + " " + y);
} }
} }
} }
@@ -145,7 +143,7 @@ public class WaveSpawner{
groundSpawns.add(spawn); groundSpawns.add(spawn);
FlyerSpawn fspawn = new FlyerSpawn(); FlyerSpawn fspawn = new FlyerSpawn();
fspawn.angle = Angles.angle(world.width()/2f, world.height()/2f, x, y); fspawn.angle = Angles.angle(world.width() / 2f, world.height() / 2f, x, y);
flySpawns.add(fspawn); flySpawns.add(fspawn);
} }
+28 -28
View File
@@ -2,18 +2,12 @@ package io.anuke.mindustry.content;
import io.anuke.arc.Core; import io.anuke.arc.Core;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.TextureRegion;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.Vars; import io.anuke.mindustry.Vars;
import io.anuke.mindustry.game.ContentList; import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.graphics.CacheLayer; import io.anuke.mindustry.graphics.*;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.graphics.Shaders;
import io.anuke.mindustry.type.Category;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.LiquidStack;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.*; import io.anuke.mindustry.world.blocks.*;
@@ -23,13 +17,8 @@ import io.anuke.mindustry.world.blocks.distribution.*;
import io.anuke.mindustry.world.blocks.power.*; import io.anuke.mindustry.world.blocks.power.*;
import io.anuke.mindustry.world.blocks.production.*; import io.anuke.mindustry.world.blocks.production.*;
import io.anuke.mindustry.world.blocks.sandbox.*; import io.anuke.mindustry.world.blocks.sandbox.*;
import io.anuke.mindustry.world.blocks.storage.CoreBlock; import io.anuke.mindustry.world.blocks.storage.*;
import io.anuke.mindustry.world.blocks.storage.LaunchPad; import io.anuke.mindustry.world.blocks.units.*;
import io.anuke.mindustry.world.blocks.storage.Unloader;
import io.anuke.mindustry.world.blocks.storage.Vault;
import io.anuke.mindustry.world.blocks.units.MechPad;
import io.anuke.mindustry.world.blocks.units.RepairPoint;
import io.anuke.mindustry.world.blocks.units.UnitFactory;
import io.anuke.mindustry.world.consumers.ConsumeLiquidFilter; import io.anuke.mindustry.world.consumers.ConsumeLiquidFilter;
import io.anuke.mindustry.world.meta.Attribute; import io.anuke.mindustry.world.meta.Attribute;
import io.anuke.mindustry.world.modules.LiquidModule; import io.anuke.mindustry.world.modules.LiquidModule;
@@ -91,15 +80,25 @@ public class Blocks implements ContentList{
public void load(){ public void load(){
//region environment //region environment
air = new Floor("air"){{ air = new Floor("air"){
{
alwaysReplace = true; alwaysReplace = true;
hasShadow = false; hasShadow = false;
} }
public void draw(Tile tile){} public void draw(Tile tile){
public void load(){} }
public void init(){}
public boolean isHidden(){ return true; } public void load(){
}
public void init(){
}
public boolean isHidden(){
return true;
}
public TextureRegion[] variantRegions(){ public TextureRegion[] variantRegions(){
if(variantRegions == null){ if(variantRegions == null){
variantRegions = new TextureRegion[]{Core.atlas.find("clear")}; variantRegions = new TextureRegion[]{Core.atlas.find("clear")};
@@ -111,7 +110,8 @@ public class Blocks implements ContentList{
part = new BlockPart(); part = new BlockPart();
spawn = new Block("spawn"){ spawn = new Block("spawn"){
public void drawShadow(Tile tile){} public void drawShadow(Tile tile){
}
}; };
//Registers build blocks from size 1-6 //Registers build blocks from size 1-6
@@ -630,7 +630,7 @@ public class Blocks implements ContentList{
} }
int liquidRegion = reg("-liquid"); int liquidRegion = reg("-liquid");
int topRegion =reg("-top"); int topRegion = reg("-top");
drawIcons = () -> new TextureRegion[]{Core.atlas.find(name), Core.atlas.find(name + "-top")}; drawIcons = () -> new TextureRegion[]{Core.atlas.find(name), Core.atlas.find(name + "-top")};
@@ -638,7 +638,7 @@ public class Blocks implements ContentList{
GenericCrafterEntity entity = tile.entity(); GenericCrafterEntity entity = tile.entity();
Draw.rect(region, tile.drawx(), tile.drawy()); Draw.rect(region, tile.drawx(), tile.drawy());
Draw.rect(reg(frameRegions[(int) Mathf.absin(entity.totalProgress, 5f, 2.999f)]), tile.drawx(), tile.drawy()); Draw.rect(reg(frameRegions[(int)Mathf.absin(entity.totalProgress, 5f, 2.999f)]), tile.drawx(), tile.drawy());
Draw.color(Color.CLEAR, tile.entity.liquids.current().color, tile.entity.liquids.total() / liquidCapacity); Draw.color(Color.CLEAR, tile.entity.liquids.current().color, tile.entity.liquids.total() / liquidCapacity);
Draw.rect(reg(liquidRegion), tile.drawx(), tile.drawy()); Draw.rect(reg(liquidRegion), tile.drawx(), tile.drawy());
Draw.color(); Draw.color();
@@ -1277,7 +1277,7 @@ public class Blocks implements ContentList{
inaccuracy = 17f; inaccuracy = 17f;
shootCone = 35f; shootCone = 35f;
health = 260*size*size; health = 260 * size * size;
}}; }};
scorch = new ItemTurret("scorch"){{ scorch = new ItemTurret("scorch"){{
@@ -1325,7 +1325,7 @@ public class Blocks implements ContentList{
shootCone = 50f; shootCone = 50f;
shootEffect = Fx.shootLiquid; shootEffect = Fx.shootLiquid;
range = 110f; range = 110f;
health = 250*size*size; health = 250 * size * size;
drawer = (tile, entity) -> { drawer = (tile, entity) -> {
Draw.rect(region, tile.drawx() + tr2.x, tile.drawy() + tr2.y, entity.rotation - 90); Draw.rect(region, tile.drawx() + tr2.x, tile.drawy() + tr2.y, entity.rotation - 90);
@@ -1356,7 +1356,7 @@ public class Blocks implements ContentList{
chargeBeginEffect = Fx.lancerLaserChargeBegin; chargeBeginEffect = Fx.lancerLaserChargeBegin;
heatColor = Color.RED; heatColor = Color.RED;
size = 2; size = 2;
health = 280*size*size; health = 280 * size * size;
targetAir = false; targetAir = false;
}}; }};
@@ -1391,7 +1391,7 @@ public class Blocks implements ContentList{
range = 140f; range = 140f;
xRand = 6f; xRand = 6f;
size = 2; size = 2;
health = 300*size*size; health = 300 * size * size;
}}; }};
salvo = new BurstTurret("salvo"){{ salvo = new BurstTurret("salvo"){{
@@ -1,20 +1,15 @@
package io.anuke.mindustry.content; package io.anuke.mindustry.content;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.CapStyle; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp; import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.entities.Damage; import io.anuke.mindustry.entities.Damage;
import io.anuke.mindustry.entities.type.Unit; import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.bullet.*; import io.anuke.mindustry.entities.bullet.*;
import io.anuke.mindustry.entities.effect.Fire; import io.anuke.mindustry.entities.effect.*;
import io.anuke.mindustry.entities.effect.Lightning; import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.game.ContentList; import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.graphics.Shapes; import io.anuke.mindustry.graphics.Shapes;
@@ -562,7 +557,7 @@ public class Bullets implements ContentList{
public void hit(Bullet b, float hitx, float hity){ public void hit(Bullet b, float hitx, float hity){
Effects.effect(hitEffect, colors[2], hitx, hity); Effects.effect(hitEffect, colors[2], hitx, hity);
if(Mathf.chance(0.4)){ if(Mathf.chance(0.4)){
Fire.create(world.tileWorld(hitx+Mathf.range(5f), hity+Mathf.range(5f))); Fire.create(world.tileWorld(hitx + Mathf.range(5f), hity + Mathf.range(5f)));
} }
} }
@@ -586,6 +581,7 @@ public class Bullets implements ContentList{
fuseShot = new BulletType(0.01f, 70){ fuseShot = new BulletType(0.01f, 70){
int rays = 3; int rays = 3;
float rayLength = 80f; float rayLength = 80f;
{ {
hitEffect = Fx.hitFuse; hitEffect = Fx.hitFuse;
lifetime = 13f; lifetime = 13f;
@@ -594,23 +590,23 @@ public class Bullets implements ContentList{
} }
@Override @Override
public void init(Bullet b) { public void init(Bullet b){
for (int i = 0; i < rays; i++) { for(int i = 0; i < rays; i++){
Damage.collideLine(b, b.getTeam(), hitEffect, b.x, b.y, b.rot(), rayLength - Math.abs(i - (rays/2))*20f); Damage.collideLine(b, b.getTeam(), hitEffect, b.x, b.y, b.rot(), rayLength - Math.abs(i - (rays / 2)) * 20f);
} }
} }
@Override @Override
public void draw(Bullet b) { public void draw(Bullet b){
super.draw(b); super.draw(b);
Draw.color(Color.WHITE, Pal.surge, b.fin()); Draw.color(Color.WHITE, Pal.surge, b.fin());
for(int i = 0; i < 7; i++){ for(int i = 0; i < 7; i++){
Tmp.v1.trns(b.rot(), i * 8f); Tmp.v1.trns(b.rot(), i * 8f);
float sl = Mathf.clamp(b.fout()-0.5f) * (80f - i *10); float sl = Mathf.clamp(b.fout() - 0.5f) * (80f - i * 10);
Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() + 90); Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() + 90);
Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() - 90); Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() - 90);
} }
Shapes.tri(b.x, b.y, 13f, (rayLength+50) * b.fout(), b.rot()); Shapes.tri(b.x, b.y, 13f, (rayLength + 50) * b.fout(), b.rot());
Shapes.tri(b.x, b.y, 13f, 10f * b.fout(), b.rot() + 180f); Shapes.tri(b.x, b.y, 13f, 10f * b.fout(), b.rot() + 180f);
Draw.reset(); Draw.reset();
} }
@@ -665,14 +661,16 @@ public class Bullets implements ContentList{
} }
}; };
arc = new BulletType(0.001f, 25){{ arc = new BulletType(0.001f, 25){
{
lifetime = 1; lifetime = 1;
despawnEffect = Fx.none; despawnEffect = Fx.none;
hitEffect = Fx.hitLancer; hitEffect = Fx.hitLancer;
} }
@Override @Override
public void draw(Bullet b){} public void draw(Bullet b){
}
@Override @Override
public void init(Bullet b){ public void init(Bullet b){
@@ -709,7 +707,8 @@ public class Bullets implements ContentList{
incendSpread = 10f; incendSpread = 10f;
}}; }};
bombOil = new BombBulletType(2f, 3f, "shell"){{ bombOil = new BombBulletType(2f, 3f, "shell"){
{
bulletWidth = 8f; bulletWidth = 8f;
bulletHeight = 12f; bulletHeight = 12f;
hitEffect = Fx.pulverize; hitEffect = Fx.pulverize;
@@ -728,7 +727,8 @@ public class Bullets implements ContentList{
} }
}; };
explode = new BombBulletType(2f, 3f, "clear"){{ explode = new BombBulletType(2f, 3f, "clear"){
{
hitEffect = Fx.pulverize; hitEffect = Fx.pulverize;
lifetime = 23f; lifetime = 23f;
speed = 1f; speed = 1f;
+16 -17
View File
@@ -2,9 +2,7 @@ package io.anuke.mindustry.content;
import io.anuke.arc.Core; import io.anuke.arc.Core;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.math.Angles; import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Tmp; import io.anuke.arc.util.Tmp;
@@ -39,14 +37,15 @@ public class Fx implements ContentList{
@Override @Override
public void load(){ public void load(){
none = new Effect(0, 0f, e -> {}); none = new Effect(0, 0f, e -> {
});
unitSpawn = new Effect(30f, e -> { unitSpawn = new Effect(30f, e -> {
if(!(e.data instanceof BaseUnit)) return; if(!(e.data instanceof BaseUnit)) return;
Draw.alpha(e.fin()); Draw.alpha(e.fin());
float scl = 1f + e.fout()*2f; float scl = 1f + e.fout() * 2f;
BaseUnit unit = (BaseUnit)e.data; BaseUnit unit = (BaseUnit)e.data;
Draw.rect(unit.getIconRegion(), e.x, e.y, Draw.rect(unit.getIconRegion(), e.x, e.y,
@@ -74,7 +73,7 @@ public class Fx implements ContentList{
Lines.stroke(3f - e.fin() * 2f); Lines.stroke(3f - e.fin() * 2f);
Lines.square(e.x, e.y, tilesize / 2f * e.rotation + e.fin() * 3f); Lines.square(e.x, e.y, tilesize / 2f * e.rotation + e.fin() * 3f);
Angles.randLenVectors(e.id, 3 + (int) (e.rotation * 3), e.rotation * 2f + (tilesize * e.rotation) * e.finpow(), (x, y) -> { Angles.randLenVectors(e.id, 3 + (int)(e.rotation * 3), e.rotation * 2f + (tilesize * e.rotation) * e.finpow(), (x, y) -> {
Fill.square(e.x + x, e.y + y, 1f + e.fout() * (3f + e.rotation)); Fill.square(e.x + x, e.y + y, 1f + e.fout() * (3f + e.rotation));
}); });
Draw.reset(); Draw.reset();
@@ -179,7 +178,7 @@ public class Fx implements ContentList{
e.scaled(7f, s -> { e.scaled(7f, s -> {
Lines.stroke(0.5f + s.fout()); Lines.stroke(0.5f + s.fout());
Lines.circle(e.x, e.y, s.fin()*5f); Lines.circle(e.x, e.y, s.fin() * 5f);
}); });
@@ -198,7 +197,7 @@ public class Fx implements ContentList{
e.scaled(7f, s -> { e.scaled(7f, s -> {
Lines.stroke(0.5f + s.fout()); Lines.stroke(0.5f + s.fout());
Lines.circle(e.x, e.y, s.fin()*7f); Lines.circle(e.x, e.y, s.fin() * 7f);
}); });
@@ -273,7 +272,7 @@ public class Fx implements ContentList{
hitLaser = new Effect(8, e -> { hitLaser = new Effect(8, e -> {
Draw.color(Color.WHITE, Pal.heal, e.fin()); Draw.color(Color.WHITE, Pal.heal, e.fin());
Lines.stroke(0.5f + e.fout()); Lines.stroke(0.5f + e.fout());
Lines.circle(e.x, e.y, e.fin()*5f); Lines.circle(e.x, e.y, e.fin() * 5f);
Draw.reset(); Draw.reset();
}); });
@@ -539,7 +538,7 @@ public class Fx implements ContentList{
Draw.color(Pal.accent); Draw.color(Pal.accent);
Angles.randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> { Angles.randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> {
Fill.square(e.x + x, e.y + y, e.fout() * 2.3f+0.5f); Fill.square(e.x + x, e.y + y, e.fout() * 2.3f + 0.5f);
}); });
Draw.color(); Draw.color();
@@ -549,7 +548,7 @@ public class Fx implements ContentList{
float length = 20f * e.finpow(); float length = 20f * e.finpow();
float size = 7f * e.fout(); float size = 7f * e.fout();
Draw.rect(((Item) e.data).icon(Icon.large), e.x + Angles.trnsx(e.rotation, length), e.y + Angles.trnsy(e.rotation, length), size, size); Draw.rect(((Item)e.data).icon(Icon.large), e.x + Angles.trnsx(e.rotation, length), e.y + Angles.trnsy(e.rotation, length), size, size);
}); });
@@ -614,23 +613,23 @@ public class Fx implements ContentList{
dynamicExplosion = new Effect(30, e -> { dynamicExplosion = new Effect(30, e -> {
float intensity = e.rotation; float intensity = e.rotation;
e.scaled(5 + intensity*2, i -> { e.scaled(5 + intensity * 2, i -> {
Lines.stroke(3.1f * i.fout()); Lines.stroke(3.1f * i.fout());
Lines.poly(e.x, e.y, (int)(20 * intensity), (3f + i.fin() * 14f) * intensity); Lines.poly(e.x, e.y, (int)(20 * intensity), (3f + i.fin() * 14f) * intensity);
}); });
Draw.color(Color.GRAY); Draw.color(Color.GRAY);
Angles.randLenVectors(e.id, e.finpow(), (int)(6 * intensity), 21f*intensity, (x, y, in, out) -> { Angles.randLenVectors(e.id, e.finpow(), (int)(6 * intensity), 21f * intensity, (x, y, in, out) -> {
Fill.circle(e.x + x, e.y + y, out * (2f+intensity) * 3 + 0.5f); Fill.circle(e.x + x, e.y + y, out * (2f + intensity) * 3 + 0.5f);
Fill.circle(e.x + x / 2f, e.y + y / 2f, out * (intensity) * 3); Fill.circle(e.x + x / 2f, e.y + y / 2f, out * (intensity) * 3);
}); });
Draw.color(Pal.lighterOrange, Pal.lightOrange, Color.GRAY, e.fin()); Draw.color(Pal.lighterOrange, Pal.lightOrange, Color.GRAY, e.fin());
Lines.stroke((1.7f * e.fout()) * (1f + (intensity - 1f) / 2f)); Lines.stroke((1.7f * e.fout()) * (1f + (intensity - 1f) / 2f));
Angles.randLenVectors(e.id + 1, e.finpow(), (int)(9*intensity), 40f*intensity, (x, y, in, out) -> { Angles.randLenVectors(e.id + 1, e.finpow(), (int)(9 * intensity), 40f * intensity, (x, y, in, out) -> {
Lines.lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (3f+intensity)); Lines.lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (3f + intensity));
}); });
Draw.reset(); Draw.reset();
@@ -1178,7 +1177,7 @@ public class Fx implements ContentList{
healBlock = new Effect(20, e -> { healBlock = new Effect(20, e -> {
Draw.color(Pal.heal); Draw.color(Pal.heal);
Lines.stroke(2f * e.fout() + 0.5f); Lines.stroke(2f * e.fout() + 0.5f);
Lines.square(e.x, e.y, 1f + (e.fin() * e.rotation * tilesize/2f-1f)); Lines.square(e.x, e.y, 1f + (e.fin() * e.rotation * tilesize / 2f - 1f));
Draw.color(); Draw.color();
}); });
@@ -21,7 +21,7 @@ import io.anuke.mindustry.type.Weapon;
public class Mechs implements ContentList{ public class Mechs implements ContentList{
public static Mech alpha, delta, tau, omega, dart, javelin, trident, glaive; public static Mech alpha, delta, tau, omega, dart, javelin, trident, glaive;
/**These are not new mechs, just re-assignments for convenience.*/ /** These are not new mechs, just re-assignments for convenience. */
public static Mech starterDesktop, starterMobile; public static Mech starterDesktop, starterMobile;
@Override @Override
@@ -137,7 +137,7 @@ public class Mechs implements ContentList{
if(player.timer.get(Player.timerAbility, healReload)){ if(player.timer.get(Player.timerAbility, healReload)){
wasHealed = false; wasHealed = false;
rect.setSize(healRange*2f).setCenter(player.x, player.y); rect.setSize(healRange * 2f).setCenter(player.x, player.y);
Units.getNearby(player.getTeam(), rect, unit -> { Units.getNearby(player.getTeam(), rect, unit -> {
if(unit.dst(player) <= healRange){ if(unit.dst(player) <= healRange){
if(unit.health < unit.maxHealth()){ if(unit.health < unit.maxHealth()){
@@ -192,7 +192,7 @@ public class Mechs implements ContentList{
@Override @Override
public float spreadX(Player player){ public float spreadX(Player player){
return player.shootHeat*2f; return player.shootHeat * 2f;
} }
@Override @Override
@@ -203,7 +203,7 @@ public class Mechs implements ContentList{
@Override @Override
public void updateAlt(Player player){ public void updateAlt(Player player){
float scl = 1f - player.shootHeat/2f; float scl = 1f - player.shootHeat / 2f;
player.velocity().scl(scl); player.velocity().scl(scl);
} }
@@ -257,6 +257,7 @@ public class Mechs implements ContentList{
float minV = 3.6f; float minV = 3.6f;
float maxV = 6f; float maxV = 6f;
TextureRegion shield; TextureRegion shield;
{ {
drillPower = -1; drillPower = -1;
speed = 0.11f; speed = 0.11f;
@@ -292,7 +293,7 @@ public class Mechs implements ContentList{
@Override @Override
public void updateAlt(Player player){ public void updateAlt(Player player){
float scl = scld(player); float scl = scld(player);
if(Mathf.chance(Time.delta() * (0.15*scl))){ if(Mathf.chance(Time.delta() * (0.15 * scl))){
Effects.effect(Fx.hitLancer, Pal.lancerLaser, player.x, player.y); Effects.effect(Fx.hitLancer, Pal.lancerLaser, player.x, player.y);
Lightning.create(player.getTeam(), Pal.lancerLaser, 10f, Lightning.create(player.getTeam(), Pal.lancerLaser, 10f,
player.x + player.velocity().x, player.y + player.velocity().y, player.rotation, 14); player.x + player.velocity().x, player.y + player.velocity().y, player.rotation, 14);
@@ -304,9 +305,9 @@ public class Mechs implements ContentList{
float scl = scld(player); float scl = scld(player);
if(scl < 0.01f) return; if(scl < 0.01f) return;
Draw.color(Pal.lancerLaser); Draw.color(Pal.lancerLaser);
Draw.alpha(scl/2f); Draw.alpha(scl / 2f);
Draw.blend(Blending.additive); Draw.blend(Blending.additive);
Draw.rect(shield, player.x + Mathf.range(scl/2f), player.y + Mathf.range(scl/2f), player.rotation - 90); Draw.rect(shield, player.x + Mathf.range(scl / 2f), player.y + Mathf.range(scl / 2f), player.rotation - 90);
Draw.blend(); Draw.blend();
} }
@@ -1,7 +1,7 @@
package io.anuke.mindustry.content; package io.anuke.mindustry.content;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.game.ContentList; import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.type.StatusEffect; import io.anuke.mindustry.type.StatusEffect;
@@ -88,7 +88,6 @@ public class TechTree implements ContentList{
}); });
node(copperWall, () -> { node(copperWall, () -> {
node(copperWallLarge); node(copperWallLarge);
node(titaniumWall, () -> { node(titaniumWall, () -> {
@@ -172,7 +171,6 @@ public class TechTree implements ContentList{
}); });
node(mechanicalPump, () -> { node(mechanicalPump, () -> {
node(conduit, () -> { node(conduit, () -> {
node(liquidJunction, () -> { node(liquidJunction, () -> {
@@ -280,7 +278,8 @@ public class TechTree implements ContentList{
} }
private TechNode node(Block block){ private TechNode node(Block block){
return node(block, () -> {}); return node(block, () -> {
});
} }
public static class TechNode{ public static class TechNode{
@@ -4,9 +4,7 @@ import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.game.Rules; import io.anuke.mindustry.game.Rules;
import io.anuke.mindustry.maps.generators.MapGenerator; import io.anuke.mindustry.maps.generators.MapGenerator;
import io.anuke.mindustry.maps.generators.MapGenerator.Decoration; import io.anuke.mindustry.maps.generators.MapGenerator.Decoration;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.Zone;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
public class Zones implements ContentList{ public class Zones implements ContentList{
@@ -1,8 +1,6 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.*;
import io.anuke.arc.collection.ObjectMap;
import io.anuke.arc.collection.ObjectSet;
import io.anuke.arc.function.Consumer; import io.anuke.arc.function.Consumer;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.Pixmap; import io.anuke.arc.graphics.Pixmap;
@@ -10,14 +8,10 @@ import io.anuke.arc.util.Log;
import io.anuke.mindustry.content.*; import io.anuke.mindustry.content.*;
import io.anuke.mindustry.entities.bullet.Bullet; import io.anuke.mindustry.entities.bullet.Bullet;
import io.anuke.mindustry.entities.bullet.BulletType; import io.anuke.mindustry.entities.bullet.BulletType;
import io.anuke.mindustry.entities.effect.Fire; import io.anuke.mindustry.entities.effect.*;
import io.anuke.mindustry.entities.effect.Lightning;
import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.entities.traits.TypeTrait; import io.anuke.mindustry.entities.traits.TypeTrait;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Content; import io.anuke.mindustry.game.*;
import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.game.MappableContent;
import io.anuke.mindustry.type.*; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.LegacyColorMapper; import io.anuke.mindustry.world.LegacyColorMapper;
@@ -58,7 +52,7 @@ public class ContentLoader{
verbose = true; verbose = true;
} }
/**Creates all content types.*/ /** Creates all content types. */
public void load(){ public void load(){
if(loaded){ if(loaded){
Log.info("Content already loaded, skipping."); Log.info("Content already loaded, skipping.");
@@ -82,13 +76,13 @@ public class ContentLoader{
for(Content c : contentMap[type.ordinal()]){ for(Content c : contentMap[type.ordinal()]){
if(c instanceof MappableContent){ if(c instanceof MappableContent){
String name = ((MappableContent) c).name; String name = ((MappableContent)c).name;
if(contentNameMap[type.ordinal()].containsKey(name)){ if(contentNameMap[type.ordinal()].containsKey(name)){
throw new IllegalArgumentException("Two content objects cannot have the same name! (issue: '" + name + "')"); throw new IllegalArgumentException("Two content objects cannot have the same name! (issue: '" + name + "')");
} }
contentNameMap[type.ordinal()].put(name, (MappableContent) c); contentNameMap[type.ordinal()].put(name, (MappableContent)c);
} }
total ++; total++;
} }
} }
@@ -119,7 +113,7 @@ public class ContentLoader{
loaded = true; loaded = true;
} }
/**Initializes all content with the specified function.*/ /** Initializes all content with the specified function. */
public void initialize(Consumer<Content> callable){ public void initialize(Consumer<Content> callable){
if(initialization.contains(callable)) return; if(initialization.contains(callable)) return;
@@ -132,7 +126,7 @@ public class ContentLoader{
initialization.add(callable); initialization.add(callable);
} }
/**Loads block colors.*/ /** Loads block colors. */
public void loadColors(){ public void loadColors(){
Pixmap pixmap = new Pixmap(files.internal("sprites/block_colors.png")); Pixmap pixmap = new Pixmap(files.internal("sprites/block_colors.png"));
for(int i = 0; i < 256; i++){ for(int i = 0; i < 256; i++){
@@ -193,7 +187,7 @@ public class ContentLoader{
} }
public <T extends Content> Array<T> getBy(ContentType type){ public <T extends Content> Array<T> getBy(ContentType type){
return (Array<T>) contentMap[type.ordinal()]; return (Array<T>)contentMap[type.ordinal()];
} }
//utility methods, just makes things a bit shorter //utility methods, just makes things a bit shorter
@@ -203,7 +197,7 @@ public class ContentLoader{
} }
public Block block(int id){ public Block block(int id){
return (Block) getByID(ContentType.block, id); return (Block)getByID(ContentType.block, id);
} }
public Array<Item> items(){ public Array<Item> items(){
@@ -211,7 +205,7 @@ public class ContentLoader{
} }
public Item item(int id){ public Item item(int id){
return (Item) getByID(ContentType.item, id); return (Item)getByID(ContentType.item, id);
} }
public Array<Liquid> liquids(){ public Array<Liquid> liquids(){
@@ -219,7 +213,7 @@ public class ContentLoader{
} }
public Liquid liquid(int id){ public Liquid liquid(int id){
return (Liquid) getByID(ContentType.liquid, id); return (Liquid)getByID(ContentType.liquid, id);
} }
public Array<BulletType> bullets(){ public Array<BulletType> bullets(){
@@ -227,7 +221,7 @@ public class ContentLoader{
} }
public BulletType bullet(int id){ public BulletType bullet(int id){
return (BulletType) getByID(ContentType.bullet, id); return (BulletType)getByID(ContentType.bullet, id);
} }
public Array<Zone> zones(){ public Array<Zone> zones(){
@@ -250,5 +244,9 @@ public class ContentLoader{
TypeTrait.registerType(Lightning.class, Lightning::new); TypeTrait.registerType(Lightning.class, Lightning::new);
} }
private class ImpendingDoomException extends RuntimeException{ ImpendingDoomException(String s){ super(s); }} private class ImpendingDoomException extends RuntimeException{
ImpendingDoomException(String s){
super(s);
}
}
} }
+7 -15
View File
@@ -1,8 +1,6 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import io.anuke.arc.ApplicationListener; import io.anuke.arc.*;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.GL20; import io.anuke.arc.graphics.GL20;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
@@ -16,16 +14,10 @@ import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects; import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityQuery; import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Content; import io.anuke.mindustry.game.*;
import io.anuke.mindustry.game.EventType.*; import io.anuke.mindustry.game.EventType.*;
import io.anuke.mindustry.game.GlobalData;
import io.anuke.mindustry.game.Rules;
import io.anuke.mindustry.game.Saves;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.input.Binding; import io.anuke.mindustry.input.*;
import io.anuke.mindustry.input.DesktopInput;
import io.anuke.mindustry.input.InputHandler;
import io.anuke.mindustry.input.MobileInput;
import io.anuke.mindustry.maps.Map; import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.Item;
@@ -152,20 +144,20 @@ public class Control implements ApplicationListener{
if(e.breaking){ if(e.breaking){
state.stats.buildingsDeconstructed++; state.stats.buildingsDeconstructed++;
}else{ }else{
state.stats.buildingsBuilt ++; state.stats.buildingsBuilt++;
} }
} }
}); });
Events.on(BlockDestroyEvent.class, e -> { Events.on(BlockDestroyEvent.class, e -> {
if(e.tile.getTeam() == player.getTeam()){ if(e.tile.getTeam() == player.getTeam()){
state.stats.buildingsDestroyed ++; state.stats.buildingsDestroyed++;
} }
}); });
Events.on(UnitDestroyEvent.class, e -> { Events.on(UnitDestroyEvent.class, e -> {
if(e.unit.getTeam() != player.getTeam()){ if(e.unit.getTeam() != player.getTeam()){
state.stats.enemyUnitsDestroyed ++; state.stats.enemyUnitsDestroyed++;
} }
}); });
@@ -309,7 +301,7 @@ public class Control implements ApplicationListener{
Time.update(); Time.update();
} }
if(!scene.hasDialog() && !(scene.root.getChildren().peek() instanceof Dialog) &&Core.input.keyTap(KeyCode.BACK)){ if(!scene.hasDialog() && !(scene.root.getChildren().peek() instanceof Dialog) && Core.input.keyTap(KeyCode.BACK)){
Platform.instance.hide(); Platform.instance.hide();
} }
} }
@@ -3,30 +3,28 @@ package io.anuke.mindustry.core;
import io.anuke.arc.Events; import io.anuke.arc.Events;
import io.anuke.mindustry.entities.type.BaseUnit; import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.game.EventType.StateChangeEvent; import io.anuke.mindustry.game.EventType.StateChangeEvent;
import io.anuke.mindustry.game.Rules; import io.anuke.mindustry.game.*;
import io.anuke.mindustry.game.Stats;
import io.anuke.mindustry.game.Teams;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import static io.anuke.mindustry.Vars.unitGroups; import static io.anuke.mindustry.Vars.unitGroups;
import static io.anuke.mindustry.Vars.waveTeam; import static io.anuke.mindustry.Vars.waveTeam;
public class GameState{ public class GameState{
/**Current wave number, can be anything in non-wave modes.*/ /** Current wave number, can be anything in non-wave modes. */
public int wave = 1; public int wave = 1;
/**Wave countdown in ticks.*/ /** Wave countdown in ticks. */
public float wavetime; public float wavetime;
/**Whether the game is in game over state.*/ /** Whether the game is in game over state. */
public boolean gameOver = false, launched = false; public boolean gameOver = false, launched = false;
/**The current game rules.*/ /** The current game rules. */
public Rules rules = new Rules(); public Rules rules = new Rules();
/**Statistics for this save/game. Displayed after game over.*/ /** Statistics for this save/game. Displayed after game over. */
public Stats stats = new Stats(); public Stats stats = new Stats();
/**Team data. Gets reset every new game.*/ /** Team data. Gets reset every new game. */
public Teams teams = new Teams(); public Teams teams = new Teams();
/**Number of enemies in the game; only used clientside in servers.*/ /** Number of enemies in the game; only used clientside in servers. */
public int enemies; public int enemies;
/**Current game state.*/ /** Current game state. */
private State state = State.menu; private State state = State.menu;
public int enemies(){ public int enemies(){
+3 -9
View File
@@ -8,15 +8,9 @@ import io.anuke.arc.collection.ObjectSet.ObjectSetIterator;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.Entities;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.type.TileEntity; import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.game.EventType.GameOverEvent; import io.anuke.mindustry.game.EventType.*;
import io.anuke.mindustry.game.EventType.PlayEvent;
import io.anuke.mindustry.game.EventType.ResetEvent;
import io.anuke.mindustry.game.EventType.WaveEvent;
import io.anuke.mindustry.game.*; import io.anuke.mindustry.game.*;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.Item;
@@ -51,7 +45,7 @@ public class Logic implements ApplicationListener{
}); });
} }
/**Handles the event of content being used by either the player or some block.*/ /** Handles the event of content being used by either the player or some block. */
public void handleContent(UnlockableContent content){ public void handleContent(UnlockableContent content){
if(!headless){ if(!headless){
data.unlockContent(content); data.unlockContent(content);
+12 -19
View File
@@ -1,17 +1,12 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.*;
import io.anuke.annotations.Annotations.PacketPriority;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.annotations.Annotations.Variant;
import io.anuke.arc.ApplicationListener; import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Core; import io.anuke.arc.Core;
import io.anuke.arc.collection.IntSet; import io.anuke.arc.collection.IntSet;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.math.RandomXS128; import io.anuke.arc.math.RandomXS128;
import io.anuke.arc.util.Interval; import io.anuke.arc.util.*;
import io.anuke.arc.util.Log;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.io.ReusableByteArrayInputStream; import io.anuke.arc.util.io.ReusableByteArrayInputStream;
import io.anuke.arc.util.serialization.Base64Coder; import io.anuke.arc.util.serialization.Base64Coder;
import io.anuke.mindustry.Vars; import io.anuke.mindustry.Vars;
@@ -25,11 +20,9 @@ import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Version; import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.gen.RemoteReadClient; import io.anuke.mindustry.gen.RemoteReadClient;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.*;
import io.anuke.mindustry.net.Net.SendMode; import io.anuke.mindustry.net.Net.SendMode;
import io.anuke.mindustry.net.NetworkIO;
import io.anuke.mindustry.net.Packets.*; import io.anuke.mindustry.net.Packets.*;
import io.anuke.mindustry.net.ValidateException;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.modules.ItemModule; import io.anuke.mindustry.world.modules.ItemModule;
@@ -45,18 +38,18 @@ public class NetClient implements ApplicationListener{
public final static float viewScale = 2f; public final static float viewScale = 2f;
private Interval timer = new Interval(5); private Interval timer = new Interval(5);
/**Whether the client is currently connecting.*/ /** Whether the client is currently connecting. */
private boolean connecting = false; private boolean connecting = false;
/**If true, no message will be shown on disconnect.*/ /** If true, no message will be shown on disconnect. */
private boolean quiet = false; private boolean quiet = false;
/**Counter for data timeout.*/ /** Counter for data timeout. */
private float timeoutTime = 0f; private float timeoutTime = 0f;
/**Last sent client snapshot ID.*/ /** Last sent client snapshot ID. */
private int lastSent; private int lastSent;
/**List of entities that were removed, and need not be added while syncing.*/ /** List of entities that were removed, and need not be added while syncing. */
private IntSet removed = new IntSet(); private IntSet removed = new IntSet();
/**Byte stream for reading in snapshots.*/ /** Byte stream for reading in snapshots. */
private ReusableByteArrayInputStream byteStream = new ReusableByteArrayInputStream(); private ReusableByteArrayInputStream byteStream = new ReusableByteArrayInputStream();
private DataInputStream dataStream = new DataInputStream(byteStream); private DataInputStream dataStream = new DataInputStream(byteStream);
@@ -210,7 +203,7 @@ public class NetClient implements ApplicationListener{
int id = input.readInt(); int id = input.readInt();
byte typeID = input.readByte(); byte typeID = input.readByte();
SyncTrait entity = (SyncTrait) group.getByID(id); SyncTrait entity = (SyncTrait)group.getByID(id);
boolean add = false; boolean add = false;
if(entity == null && id == player.id){ if(entity == null && id == player.id){
@@ -220,7 +213,7 @@ public class NetClient implements ApplicationListener{
//entity must not be added yet, so create it //entity must not be added yet, so create it
if(entity == null){ if(entity == null){
entity = (SyncTrait) TypeTrait.getTypeByID(typeID).get(); //create entity from supplier entity = (SyncTrait)TypeTrait.getTypeByID(typeID).get(); //create entity from supplier
entity.resetID(id); entity.resetID(id);
if(!netClient.isEntityUsed(entity.getID())){ if(!netClient.isEntityUsed(entity.getID())){
add = true; add = true;
@@ -323,7 +316,7 @@ public class NetClient implements ApplicationListener{
Net.disconnect(); Net.disconnect();
} }
/**When set, any disconnects will be ignored and no dialogs will be shown.*/ /** When set, any disconnects will be ignored and no dialogs will be shown. */
public void setQuiet(){ public void setQuiet(){
quiet = true; quiet = true;
} }
+20 -31
View File
@@ -4,26 +4,19 @@ import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.ApplicationListener; import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Events; import io.anuke.arc.Events;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.*;
import io.anuke.arc.collection.IntMap;
import io.anuke.arc.collection.ObjectSet;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.Colors; import io.anuke.arc.graphics.Colors;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2; import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Log; import io.anuke.arc.util.*;
import io.anuke.arc.util.Structs;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.io.ByteBufferOutput; import io.anuke.arc.util.io.ByteBufferOutput;
import io.anuke.arc.util.io.CountableByteArrayOutputStream; import io.anuke.arc.util.io.CountableByteArrayOutputStream;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.content.Mechs; import io.anuke.mindustry.content.Mechs;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Entities; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.traits.BuilderTrait.BuildRequest; import io.anuke.mindustry.entities.traits.BuilderTrait.BuildRequest;
import io.anuke.mindustry.entities.traits.Entity; import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.traits.SyncTrait; import io.anuke.mindustry.entities.traits.SyncTrait;
@@ -33,44 +26,40 @@ import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.game.Version; import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.gen.RemoteReadServer; import io.anuke.mindustry.gen.RemoteReadServer;
import io.anuke.mindustry.net.Administration; import io.anuke.mindustry.net.*;
import io.anuke.mindustry.net.Administration.PlayerInfo; import io.anuke.mindustry.net.Administration.PlayerInfo;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.net.NetConnection;
import io.anuke.mindustry.net.NetworkIO;
import io.anuke.mindustry.net.Packets.*; import io.anuke.mindustry.net.Packets.*;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import java.io.ByteArrayInputStream; import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.zip.DeflaterOutputStream; import java.util.zip.DeflaterOutputStream;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
import java.lang.StringBuilder;
public class NetServer implements ApplicationListener{ public class NetServer implements ApplicationListener{
public final static int maxSnapshotSize = 430; public final static int maxSnapshotSize = 430;
private final static float serverSyncTime = 30, kickDuration = 30 * 1000; private final static float serverSyncTime = 30, kickDuration = 30 * 1000;
private final static Vector2 vector = new Vector2(); private final static Vector2 vector = new Vector2();
private final static Rectangle viewport = new Rectangle(); private final static Rectangle viewport = new Rectangle();
private final static Array<Entity> returnArray = new Array<>(); private final static Array<Entity> returnArray = new Array<>();
/**If a player goes away of their server-side coordinates by this distance, they get teleported back.*/ /** If a player goes away of their server-side coordinates by this distance, they get teleported back. */
private final static float correctDist = 16f; private final static float correctDist = 16f;
public final Administration admins = new Administration(); public final Administration admins = new Administration();
/**Maps connection IDs to players.*/ /** Maps connection IDs to players. */
private IntMap<Player> connections = new IntMap<>(); private IntMap<Player> connections = new IntMap<>();
private boolean closing = false; private boolean closing = false;
private ByteBuffer writeBuffer = ByteBuffer.allocate(127); private ByteBuffer writeBuffer = ByteBuffer.allocate(127);
private ByteBufferOutput outputBuffer = new ByteBufferOutput(writeBuffer); private ByteBufferOutput outputBuffer = new ByteBufferOutput(writeBuffer);
/**Stream for writing player sync data to.*/ /** Stream for writing player sync data to. */
private CountableByteArrayOutputStream syncStream = new CountableByteArrayOutputStream(); private CountableByteArrayOutputStream syncStream = new CountableByteArrayOutputStream();
/**Data stream for writing player sync data to.*/ /** Data stream for writing player sync data to. */
private DataOutputStream dataStream = new DataOutputStream(syncStream); private DataOutputStream dataStream = new DataOutputStream(syncStream);
public NetServer(){ public NetServer(){
@@ -215,7 +204,7 @@ public class NetServer implements ApplicationListener{
int count = 0; int count = 0;
for(Player other : players){ for(Player other : players){
if(other.getTeam() == team){ if(other.getTeam() == team){
count ++; count++;
} }
} }
return count; return count;
@@ -394,7 +383,7 @@ public class NetServer implements ApplicationListener{
int used = 0; int used = 0;
for(Team t : Team.all){ for(Team t : Team.all){
if(playerGroup.count(p -> p.getTeam() == t) > 0){ if(playerGroup.count(p -> p.getTeam() == t) > 0){
used ++; used++;
} }
} }
return used < 2; return used < 2;
@@ -472,7 +461,7 @@ public class NetServer implements ApplicationListener{
for(EntityGroup<?> group : Entities.getAllGroups()){ for(EntityGroup<?> group : Entities.getAllGroups()){
if(group.isEmpty() || !(group.all().get(0) instanceof SyncTrait)) continue; if(group.isEmpty() || !(group.all().get(0) instanceof SyncTrait)) continue;
//clipping is done by representatives //clipping is done by representatives
SyncTrait represent = (SyncTrait) group.all().get(0); SyncTrait represent = (SyncTrait)group.all().get(0);
//make sure mapping is enabled for this group //make sure mapping is enabled for this group
if(!group.mappingEnabled()){ if(!group.mappingEnabled()){
@@ -482,13 +471,13 @@ public class NetServer implements ApplicationListener{
returnArray.clear(); returnArray.clear();
if(represent.isClipped()){ if(represent.isClipped()){
EntityQuery.getNearby(group, viewport, entity -> { EntityQuery.getNearby(group, viewport, entity -> {
if(((SyncTrait) entity).isSyncing() && viewport.overlaps(Tmp.r3.setSize(((SyncTrait)entity).clipSize(), ((SyncTrait)entity).clipSize()).setCenter(entity.getX(), entity.getY()))){ if(((SyncTrait)entity).isSyncing() && viewport.overlaps(Tmp.r3.setSize(((SyncTrait)entity).clipSize(), ((SyncTrait)entity).clipSize()).setCenter(entity.getX(), entity.getY()))){
returnArray.add(entity); returnArray.add(entity);
} }
}); });
}else{ }else{
for(Entity entity : group.all()){ for(Entity entity : group.all()){
if(((SyncTrait) entity).isSyncing()){ if(((SyncTrait)entity).isSyncing()){
returnArray.add(entity); returnArray.add(entity);
} }
} }
@@ -501,10 +490,10 @@ public class NetServer implements ApplicationListener{
for(Entity entity : returnArray){ for(Entity entity : returnArray){
//write all entities now //write all entities now
dataStream.writeInt(entity.getID()); //write id dataStream.writeInt(entity.getID()); //write id
dataStream.writeByte(((SyncTrait) entity).getTypeID()); //write type ID dataStream.writeByte(((SyncTrait)entity).getTypeID()); //write type ID
((SyncTrait) entity).write(dataStream); //write entity ((SyncTrait)entity).write(dataStream); //write entity
sent ++; sent++;
if(syncStream.position() > maxSnapshotSize){ if(syncStream.position() > maxSnapshotSize){
dataStream.close(); dataStream.close();
@@ -579,7 +568,7 @@ public class NetServer implements ApplicationListener{
try{ try{
//iterate through each player //iterate through each player
for(int i = 0; i < playerGroup.size(); i ++){ for(int i = 0; i < playerGroup.size(); i++){
Player player = playerGroup.all().get(i); Player player = playerGroup.all().get(i);
if(player.isLocal) continue; if(player.isLocal) continue;
+32 -20
View File
@@ -10,15 +10,17 @@ import io.anuke.arc.util.serialization.Base64Coder;
import static io.anuke.mindustry.Vars.mobile; import static io.anuke.mindustry.Vars.mobile;
public abstract class Platform { public abstract class Platform{
/**Each separate game platform should set this instance to their own implementation.*/ /** Each separate game platform should set this instance to their own implementation. */
public static Platform instance = new Platform() {}; public static Platform instance = new Platform(){
};
/**Add a text input dialog that should show up after the field is tapped.*/ /** Add a text input dialog that should show up after the field is tapped. */
public void addDialog(TextField field){ public void addDialog(TextField field){
addDialog(field, 16); addDialog(field, 16);
} }
/**See addDialog().*/
/** See addDialog(). */
public void addDialog(TextField field, int maxLength){ public void addDialog(TextField field, int maxLength){
if(!mobile) return; //this is mobile only, desktop doesn't need dialogs if(!mobile) return; //this is mobile only, desktop doesn't need dialogs
@@ -35,13 +37,17 @@ public abstract class Platform {
Core.input.getTextInput(input); Core.input.getTextInput(input);
}); });
} }
/**Update discord RPC.*/
public void updateRPC(){} /** Update discord RPC. */
/**Whether donating is supported.*/ public void updateRPC(){
}
/** Whether donating is supported. */
public boolean canDonate(){ public boolean canDonate(){
return false; return false;
} }
/**Must be a base64 string 8 bytes in length.*/
/** Must be a base64 string 8 bytes in length. */
public String getUUID(){ public String getUUID(){
String uuid = Core.settings.getString("uuid", ""); String uuid = Core.settings.getString("uuid", "");
if(uuid.isEmpty()){ if(uuid.isEmpty()){
@@ -54,25 +60,31 @@ public abstract class Platform {
} }
return uuid; return uuid;
} }
/**Only used for iOS or android: open the share menu for a map or save.*/
public void shareFile(FileHandle file){}
/**Show a file chooser. Desktop only. /** Only used for iOS or android: open the share menu for a map or save. */
* public void shareFile(FileHandle file){
}
/**
* Show a file chooser. Desktop only.
* @param text File chooser title text * @param text File chooser title text
* @param content Description of the type of files to be loaded * @param content Description of the type of files to be loaded
* @param cons Selection listener * @param cons Selection listener
* @param open Whether to open or save files * @param open Whether to open or save files
* @param filetype File extension to filter * @param filetype File extension to filter
*/ */
public void showFileChooser(String text, String content, Consumer<FileHandle> cons, boolean open, String filetype){} public void showFileChooser(String text, String content, Consumer<FileHandle> cons, boolean open, String filetype){
}
/**Hide the app. Android only.*/ /** Hide the app. Android only. */
public void hide(){} public void hide(){
}
/**Forces the app into landscape mode. Currently Android only.*/ /** Forces the app into landscape mode. Currently Android only. */
public void beginForceLandscape(){} public void beginForceLandscape(){
}
/**Stops forcing the app into landscape orientation. Currently Android only.*/ /** Stops forcing the app into landscape orientation. Currently Android only. */
public void endForceLandscape(){} public void endForceLandscape(){
}
} }
+12 -27
View File
@@ -5,37 +5,22 @@ import io.anuke.arc.Core;
import io.anuke.arc.files.FileHandle; import io.anuke.arc.files.FileHandle;
import io.anuke.arc.function.Consumer; import io.anuke.arc.function.Consumer;
import io.anuke.arc.function.Predicate; import io.anuke.arc.function.Predicate;
import io.anuke.arc.graphics.Camera; import io.anuke.arc.graphics.*;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.Pixmap;
import io.anuke.arc.graphics.PixmapIO;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.SpriteBatch;
import io.anuke.arc.graphics.glutils.FrameBuffer; import io.anuke.arc.graphics.glutils.FrameBuffer;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2; import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.BufferUtils; import io.anuke.arc.util.*;
import io.anuke.arc.util.ScreenUtils;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.EntityDraw;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.effect.GroundEffectEntity; import io.anuke.mindustry.entities.effect.GroundEffectEntity;
import io.anuke.mindustry.entities.effect.GroundEffectEntity.GroundEffect; import io.anuke.mindustry.entities.effect.GroundEffectEntity.GroundEffect;
import io.anuke.mindustry.entities.impl.EffectEntity; import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait; import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.traits.DrawTrait; import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.graphics.*; import io.anuke.mindustry.graphics.*;
import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity; import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity;
@@ -84,7 +69,7 @@ public class Renderer implements ApplicationListener{
entity.id++; entity.id++;
entity.set(x, y); entity.set(x, y);
if(data instanceof Entity){ if(data instanceof Entity){
entity.setParent((Entity) data); entity.setParent((Entity)data);
} }
effectGroup.add(entity); effectGroup.add(entity);
}else{ }else{
@@ -96,7 +81,7 @@ public class Renderer implements ApplicationListener{
entity.data = data; entity.data = data;
entity.set(x, y); entity.set(x, y);
if(data instanceof Entity){ if(data instanceof Entity){
entity.setParent((Entity) data); entity.setParent((Entity)data);
} }
groundEffectGroup.add(entity); groundEffectGroup.add(entity);
} }
@@ -329,7 +314,7 @@ public class Renderer implements ApplicationListener{
public void takeMapScreenshot(){ public void takeMapScreenshot(){
drawGroundShadows(); drawGroundShadows();
int w = world.width()*tilesize, h = world.height()*tilesize; int w = world.width() * tilesize, h = world.height() * tilesize;
int memory = w * h * 4 / 1024 / 1024; int memory = w * h * 4 / 1024 / 1024;
if(memory >= 65){ if(memory >= 65){
@@ -348,8 +333,8 @@ public class Renderer implements ApplicationListener{
disableUI = true; disableUI = true;
camera.width = w; camera.width = w;
camera.height = h; camera.height = h;
camera.position.x = w/2f + tilesize/2f; camera.position.x = w / 2f + tilesize / 2f;
camera.position.y = h/2f + tilesize/2f; camera.position.y = h / 2f + tilesize / 2f;
Draw.flush(); Draw.flush();
buffer.begin(); buffer.begin();
draw(); draw();
@@ -361,7 +346,7 @@ public class Renderer implements ApplicationListener{
camera.position.set(px, py); camera.position.set(px, py);
buffer.begin(); buffer.begin();
byte[] lines = ScreenUtils.getFrameBufferPixels(0, 0, w, h, true); byte[] lines = ScreenUtils.getFrameBufferPixels(0, 0, w, h, true);
for(int i = 0; i < lines.length; i+= 4){ for(int i = 0; i < lines.length; i += 4){
lines[i + 3] = (byte)255; lines[i + 3] = (byte)255;
} }
buffer.end(); buffer.end();
+5 -13
View File
@@ -1,8 +1,6 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import io.anuke.arc.ApplicationListener; import io.anuke.arc.*;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.Graphics.Cursor; import io.anuke.arc.Graphics.Cursor;
import io.anuke.arc.Graphics.Cursor.SystemCursor; import io.anuke.arc.Graphics.Cursor.SystemCursor;
import io.anuke.arc.freetype.FreeTypeFontGenerator; import io.anuke.arc.freetype.FreeTypeFontGenerator;
@@ -13,19 +11,13 @@ import io.anuke.arc.graphics.Colors;
import io.anuke.arc.graphics.g2d.BitmapFont; import io.anuke.arc.graphics.g2d.BitmapFont;
import io.anuke.arc.input.KeyCode; import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Interpolation; import io.anuke.arc.math.Interpolation;
import io.anuke.arc.scene.Group; import io.anuke.arc.scene.*;
import io.anuke.arc.scene.Scene;
import io.anuke.arc.scene.Skin;
import io.anuke.arc.scene.actions.Actions; import io.anuke.arc.scene.actions.Actions;
import io.anuke.arc.scene.ui.Dialog; import io.anuke.arc.scene.ui.*;
import io.anuke.arc.scene.ui.TextField;
import io.anuke.arc.scene.ui.TextField.TextFieldFilter; import io.anuke.arc.scene.ui.TextField.TextFieldFilter;
import io.anuke.arc.scene.ui.TooltipManager;
import io.anuke.arc.scene.ui.layout.Table; import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.scene.ui.layout.Unit; import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Align; import io.anuke.arc.util.*;
import io.anuke.arc.util.Strings;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.editor.MapEditorDialog; import io.anuke.mindustry.editor.MapEditorDialog;
import io.anuke.mindustry.game.EventType.ResizeEvent; import io.anuke.mindustry.game.EventType.ResizeEvent;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
@@ -130,7 +122,7 @@ public class UI implements ApplicationListener{
void generateFonts(Skin skin){ void generateFonts(Skin skin){
generator = new FreeTypeFontGenerator(Core.files.internal("fonts/font.ttf")); generator = new FreeTypeFontGenerator(Core.files.internal("fonts/font.ttf"));
FreeTypeFontParameter param = new FreeTypeFontParameter(); FreeTypeFontParameter param = new FreeTypeFontParameter();
param.size = (int)(9*2 * Math.max(Unit.dp.scl(1f), 0.5f)); param.size = (int)(9 * 2 * Math.max(Unit.dp.scl(1f), 0.5f));
param.shadowColor = Color.DARK_GRAY; param.shadowColor = Color.DARK_GRAY;
param.shadowOffsetY = 2; param.shadowOffsetY = 2;
param.incremental = true; param.incremental = true;
+22 -30
View File
@@ -1,20 +1,14 @@
package io.anuke.mindustry.core; package io.anuke.mindustry.core;
import io.anuke.annotations.Annotations.Nullable; import io.anuke.annotations.Annotations.Nullable;
import io.anuke.arc.ApplicationListener; import io.anuke.arc.*;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntArray; import io.anuke.arc.collection.IntArray;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2; import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.util.Log; import io.anuke.arc.util.*;
import io.anuke.arc.util.Structs; import io.anuke.mindustry.ai.*;
import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.ai.BlockIndexer;
import io.anuke.mindustry.ai.Pathfinder;
import io.anuke.mindustry.ai.WaveSpawner;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.core.GameState.State; import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.EntityQuery; import io.anuke.mindustry.entities.EntityQuery;
@@ -22,16 +16,10 @@ import io.anuke.mindustry.game.EventType.TileChangeEvent;
import io.anuke.mindustry.game.EventType.WorldLoadEvent; import io.anuke.mindustry.game.EventType.WorldLoadEvent;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.io.MapIO; import io.anuke.mindustry.io.MapIO;
import io.anuke.mindustry.maps.Map; import io.anuke.mindustry.maps.*;
import io.anuke.mindustry.maps.MapException;
import io.anuke.mindustry.maps.Maps;
import io.anuke.mindustry.maps.generators.Generator; import io.anuke.mindustry.maps.generators.Generator;
import io.anuke.mindustry.type.ContentType; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.type.ItemStack; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.type.Zone;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -97,11 +85,13 @@ public class World implements ApplicationListener{
return tiles == null ? 0 : tiles[0].length; return tiles == null ? 0 : tiles[0].length;
} }
public @Nullable Tile tile(int pos){ public @Nullable
Tile tile(int pos){
return tiles == null ? null : tile(Pos.x(pos), Pos.y(pos)); return tiles == null ? null : tile(Pos.x(pos), Pos.y(pos));
} }
public @Nullable Tile tile(int x, int y){ public @Nullable
Tile tile(int x, int y){
if(tiles == null){ if(tiles == null){
return null; return null;
} }
@@ -113,7 +103,8 @@ public class World implements ApplicationListener{
return tiles[x][y]; return tiles[x][y];
} }
public @Nullable Tile tileWorld(float x, float y){ public @Nullable
Tile tileWorld(float x, float y){
return tile(Math.round(x / tilesize), Math.round(y / tilesize)); return tile(Math.round(x / tilesize), Math.round(y / tilesize));
} }
@@ -161,7 +152,7 @@ public class World implements ApplicationListener{
generating = true; generating = true;
} }
/**Call to signal the beginning of loading the map with a custom set of tiles.*/ /** Call to signal the beginning of loading the map with a custom set of tiles. */
public void beginMapLoad(Tile[][] tiles){ public void beginMapLoad(Tile[][] tiles){
this.tiles = tiles; this.tiles = tiles;
generating = true; generating = true;
@@ -185,7 +176,7 @@ public class World implements ApplicationListener{
addDarkness(tiles); addDarkness(tiles);
EntityQuery.resizeTree(-finalWorldBounds, -finalWorldBounds, tiles.length * tilesize + finalWorldBounds*2, tiles[0].length * tilesize + finalWorldBounds*2); EntityQuery.resizeTree(-finalWorldBounds, -finalWorldBounds, tiles.length * tilesize + finalWorldBounds * 2, tiles[0].length * tilesize + finalWorldBounds * 2);
generating = false; generating = false;
Events.fire(new WorldLoadEvent()); Events.fire(new WorldLoadEvent());
@@ -326,7 +317,7 @@ public class World implements ApplicationListener{
if(!(worldx == tile.x && worldy == tile.y)){ if(!(worldx == tile.x && worldy == tile.y)){
Tile toplace = world.tile(worldx, worldy); Tile toplace = world.tile(worldx, worldy);
if(toplace != null){ if(toplace != null){
toplace.setLinked((byte) (dx + offsetx), (byte) (dy + offsety)); toplace.setLinked((byte)(dx + offsetx), (byte)(dy + offsety));
toplace.setTeam(team); toplace.setTeam(team);
} }
} }
@@ -341,7 +332,7 @@ public class World implements ApplicationListener{
if(!Structs.inBounds(x, y, oldWidth, oldHeight)) return -1; if(!Structs.inBounds(x, y, oldWidth, oldHeight)) return -1;
x += shiftX; x += shiftX;
y += shiftY; y += shiftY;
return y*newWidth + x; return y * newWidth + x;
} }
/** /**
@@ -354,7 +345,6 @@ public class World implements ApplicationListener{
/** /**
* Input is in block coordinates, not world coordinates. * Input is in block coordinates, not world coordinates.
*
* @return null if no collisions found, block position otherwise. * @return null if no collisions found, block position otherwise.
*/ */
public Point2 raycast(int x0f, int y0f, int x1, int y1){ public Point2 raycast(int x0f, int y0f, int x1, int y1){
@@ -422,7 +412,7 @@ public class World implements ApplicationListener{
} }
} }
/**Loads raw map tile data into a Tile[][] array, setting up multiblocks, cliffs and ores. */ /** Loads raw map tile data into a Tile[][] array, setting up multiblocks, cliffs and ores. */
void loadTileData(Tile[][] tiles){ void loadTileData(Tile[][] tiles){
prepareTiles(tiles); prepareTiles(tiles);
} }
@@ -471,10 +461,12 @@ public class World implements ApplicationListener{
} }
} }
/**'Prepares' a tile array by:<br> /**
* 'Prepares' a tile array by:<br>
* - setting up multiblocks<br> * - setting up multiblocks<br>
* - updating occlusion<br> * - updating occlusion<br>
* Usually used before placing structures on a tile array.*/ * Usually used before placing structures on a tile array.
*/
public void prepareTiles(Tile[][] tiles){ public void prepareTiles(Tile[][] tiles){
//find multiblocks //find multiblocks
@@ -510,7 +502,7 @@ public class World implements ApplicationListener{
if(!(worldx == x && worldy == y)){ if(!(worldx == x && worldy == y)){
Tile toplace = world.tile(worldx, worldy); Tile toplace = world.tile(worldx, worldy);
if(toplace != null){ if(toplace != null){
toplace.setLinked((byte) (dx + offsetx), (byte) (dy + offsety)); toplace.setLinked((byte)(dx + offsetx), (byte)(dy + offsety));
toplace.setTeam(team); toplace.setTeam(team);
} }
} }
@@ -8,10 +8,7 @@ import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.Floor; import io.anuke.mindustry.world.blocks.Floor;
import io.anuke.mindustry.world.blocks.OreBlock; import io.anuke.mindustry.world.blocks.OreBlock;
import io.anuke.mindustry.world.modules.ConsumeModule; import io.anuke.mindustry.world.modules.*;
import io.anuke.mindustry.world.modules.ItemModule;
import io.anuke.mindustry.world.modules.LiquidModule;
import io.anuke.mindustry.world.modules.PowerModule;
import static io.anuke.mindustry.Vars.ui; import static io.anuke.mindustry.Vars.ui;
@@ -49,7 +46,7 @@ public class EditorTile extends Tile{
@Override @Override
public void setBlock(Block type){ public void setBlock(Block type){
Block previous =wall; Block previous = wall;
if(previous == type) return; if(previous == type) return;
super.setBlock(type); super.setBlock(type);
op(TileOp.get(x, y, (byte)OpType.block.ordinal(), previous.id, type.id)); op(TileOp.get(x, y, (byte)OpType.block.ordinal(), previous.id, type.id));
@@ -7,12 +7,8 @@ import io.anuke.arc.input.KeyCode;
import io.anuke.arc.util.Pack; import io.anuke.arc.util.Pack;
import io.anuke.arc.util.Structs; import io.anuke.arc.util.Structs;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.Pos; import io.anuke.mindustry.world.blocks.*;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.BlockPart;
import io.anuke.mindustry.world.blocks.Floor;
import io.anuke.mindustry.world.blocks.OreBlock;
public enum EditorTool{ public enum EditorTool{
pick{ pick{
@@ -68,7 +68,7 @@ public class MapEditor{
//adds missing blockparts //adds missing blockparts
public void checkLinkedTiles(){ public void checkLinkedTiles(){
//clear block parts first //clear block parts first
for(int x = 0; x < width(); x ++){ for(int x = 0; x < width(); x++){
for(int y = 0; y < height(); y++){ for(int y = 0; y < height(); y++){
if(tiles[x][y].block() == Blocks.part){ if(tiles[x][y].block() == Blocks.part){
tiles[x][y].setBlock(Blocks.air); tiles[x][y].setBlock(Blocks.air);
@@ -78,8 +78,8 @@ public class MapEditor{
} }
//set up missing blockparts //set up missing blockparts
for(int x = 0; x < width(); x ++){ for(int x = 0; x < width(); x++){
for(int y = 0; y < height(); y ++){ for(int y = 0; y < height(); y++){
Block drawBlock = tiles[x][y].block(); Block drawBlock = tiles[x][y].block();
if(drawBlock.isMultiblock()){ if(drawBlock.isMultiblock()){
int offsetx = -(drawBlock.size - 1) / 2; int offsetx = -(drawBlock.size - 1) / 2;
@@ -92,7 +92,7 @@ public class MapEditor{
if(Structs.inBounds(worldx, worldy, width(), height()) && !(dx + offsetx == 0 && dy + offsety == 0)){ if(Structs.inBounds(worldx, worldy, width(), height()) && !(dx + offsetx == 0 && dy + offsety == 0)){
Tile tile = tiles[worldx][worldy]; Tile tile = tiles[worldx][worldy];
tile.setBlock(Blocks.part); tile.setBlock(Blocks.part);
tile.setLinkByte(Pack.byteByte((byte) (dx + offsetx + 8), (byte) (dy + offsety + 8))); tile.setLinkByte(Pack.byteByte((byte)(dx + offsetx + 8), (byte)(dy + offsety + 8)));
} }
} }
} }
@@ -107,7 +107,7 @@ public class MapEditor{
loading = false; loading = false;
} }
/**Creates a 2-D array of EditorTiles with stone as the floor block.*/ /** Creates a 2-D array of EditorTiles with stone as the floor block. */
public Tile[][] createTiles(int width, int height){ public Tile[][] createTiles(int width, int height){
tiles = new Tile[width][height]; tiles = new Tile[width][height];
@@ -180,8 +180,8 @@ public class MapEditor{
if(drawBlock.isMultiblock()){ if(drawBlock.isMultiblock()){
x = Mathf.clamp(x, (drawBlock.size-1)/2, width() - drawBlock.size/2 - 1); x = Mathf.clamp(x, (drawBlock.size - 1) / 2, width() - drawBlock.size / 2 - 1);
y = Mathf.clamp(y, (drawBlock.size-1)/2, height() - drawBlock.size/2 - 1); y = Mathf.clamp(y, (drawBlock.size - 1) / 2, height() - drawBlock.size / 2 - 1);
int offsetx = -(drawBlock.size - 1) / 2; int offsetx = -(drawBlock.size - 1) / 2;
int offsety = -(drawBlock.size - 1) / 2; int offsety = -(drawBlock.size - 1) / 2;
@@ -197,7 +197,7 @@ public class MapEditor{
if(i == 1){ if(i == 1){
tile.setBlock(Blocks.part); tile.setBlock(Blocks.part);
tile.setLinkByte(Pack.byteByte((byte) (dx + offsetx + 8), (byte) (dy + offsety + 8))); tile.setLinkByte(Pack.byteByte((byte)(dx + offsetx + 8), (byte)(dy + offsety + 8)));
}else{ }else{
byte link = tile.getLinkByte(); byte link = tile.getLinkByte();
Block block = tile.block(); Block block = tile.block();
@@ -279,7 +279,7 @@ public class MapEditor{
clearOp(); clearOp();
Tile[][] previous = tiles; Tile[][] previous = tiles;
int offsetX = -(width - width())/2, offsetY = -(height - height())/2; int offsetX = -(width - width()) / 2, offsetY = -(height - height()) / 2;
loading = true; loading = true;
tiles = new Tile[width][height]; tiles = new Tile[width][height];
@@ -86,8 +86,8 @@ public class MapEditorDialog extends Dialog implements Disposable{
t.addImageTextButton("$editor.import", "icon-load-map", isize, () -> t.addImageTextButton("$editor.import", "icon-load-map", isize, () ->
createDialog("$editor.import", createDialog("$editor.import",
"$editor.importmap", "$editor.importmap.description", "icon-load-map", (Runnable) loadDialog::show, "$editor.importmap", "$editor.importmap.description", "icon-load-map", (Runnable)loadDialog::show,
"$editor.importfile", "$editor.importfile.description", "icon-file", (Runnable) () -> "$editor.importfile", "$editor.importfile.description", "icon-file", (Runnable)() ->
Platform.instance.showFileChooser("$editor.loadmap", "Map Files", file -> ui.loadAnd(() -> { Platform.instance.showFileChooser("$editor.loadmap", "Map Files", file -> ui.loadAnd(() -> {
try{ try{
//TODO what if it's an image? users should be warned for their stupidity //TODO what if it's an image? users should be warned for their stupidity
@@ -106,7 +106,7 @@ public class MapEditorDialog extends Dialog implements Disposable{
Tile[][] tiles = editor.createTiles(pixmap.getWidth(), pixmap.getHeight()); Tile[][] tiles = editor.createTiles(pixmap.getWidth(), pixmap.getHeight());
editor.load(() -> MapIO.readLegacyPixmap(pixmap, tiles)); editor.load(() -> MapIO.readLegacyPixmap(pixmap, tiles));
editor.beginEdit(tiles); editor.beginEdit(tiles);
}catch (Exception e){ }catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false))); ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e); Log.err(e);
} }
@@ -239,10 +239,10 @@ public class MapEditorDialog extends Dialog implements Disposable{
dialog.cont.defaults().size(360f, h).padBottom(5).padRight(5).padLeft(5); dialog.cont.defaults().size(360f, h).padBottom(5).padRight(5).padLeft(5);
for(int i = 0; i < arguments.length; i += 4){ for(int i = 0; i < arguments.length; i += 4){
String name = (String) arguments[i]; String name = (String)arguments[i];
String description = (String) arguments[i + 1]; String description = (String)arguments[i + 1];
String iconname = (String) arguments[i + 2]; String iconname = (String)arguments[i + 2];
Runnable listenable = (Runnable) arguments[i + 3]; Runnable listenable = (Runnable)arguments[i + 3];
TextButton button = dialog.cont.addButton(name, () -> { TextButton button = dialog.cont.addButton(name, () -> {
listenable.run(); listenable.run();
@@ -306,7 +306,7 @@ public class MapEditorDialog extends Dialog implements Disposable{
public void build(){ public void build(){
float amount = 10f, baseSize = 60f; float amount = 10f, baseSize = 60f;
float size = mobile ? (int) (Math.min(Core.graphics.getHeight(), Core.graphics.getWidth()) / amount / Unit.dp.scl(1f)) : float size = mobile ? (int)(Math.min(Core.graphics.getHeight(), Core.graphics.getWidth()) / amount / Unit.dp.scl(1f)) :
Math.min(Core.graphics.getDisplayMode().height / amount, baseSize); Math.min(Core.graphics.getDisplayMode().height / amount, baseSize);
clearChildren(); clearChildren();
@@ -401,7 +401,7 @@ public class MapEditorDialog extends Dialog implements Disposable{
mid.table("underline", t -> { mid.table("underline", t -> {
Slider slider = new Slider(0, MapEditor.brushSizes.length - 1, 1, false); Slider slider = new Slider(0, MapEditor.brushSizes.length - 1, 1, false);
slider.moved(f -> editor.brushSize = MapEditor.brushSizes[(int) (float) f]); slider.moved(f -> editor.brushSize = MapEditor.brushSizes[(int)(float)f]);
t.top(); t.top();
t.add("$editor.brush"); t.add("$editor.brush");
@@ -62,7 +62,7 @@ public class MapGenerateDialog extends FloatingDialog{
update(); update();
}).size(160f, 64f); }).size(160f, 64f);
buttons.addImageTextButton("$add", "icon-add", 14*2, this::showAdd).height(64f).width(140f); buttons.addImageTextButton("$add", "icon-add", 14 * 2, this::showAdd).height(64f).width(140f);
} }
void setup(){ void setup(){
@@ -120,24 +120,24 @@ public class MapGenerateDialog extends FloatingDialog{
t.table(b -> { t.table(b -> {
b.left(); b.left();
b.defaults().size(50f); b.defaults().size(50f);
b.addImageButton("icon-refresh", 14*2, () -> { b.addImageButton("icon-refresh", 14 * 2, () -> {
filter.randomize(); filter.randomize();
update(); update();
}); });
b.addImageButton("icon-arrow-up", 10*2, () -> { b.addImageButton("icon-arrow-up", 10 * 2, () -> {
int idx = filters.indexOf(filter); int idx = filters.indexOf(filter);
filters.swap(idx, Math.max(0, idx - 1)); filters.swap(idx, Math.max(0, idx - 1));
rebuildFilters(); rebuildFilters();
update(); update();
}); });
b.addImageButton("icon-arrow-down", 10*2, () -> { b.addImageButton("icon-arrow-down", 10 * 2, () -> {
int idx = filters.indexOf(filter); int idx = filters.indexOf(filter);
filters.swap(idx, Math.min(filters.size-1, idx + 1)); filters.swap(idx, Math.min(filters.size - 1, idx + 1));
rebuildFilters(); rebuildFilters();
update(); update();
}); });
b.addImageButton("icon-trash", 14*2, () -> { b.addImageButton("icon-trash", 14 * 2, () -> {
filters.remove(filter); filters.remove(filter);
rebuildFilters(); rebuildFilters();
update(); update();
@@ -1,14 +1,12 @@
package io.anuke.mindustry.editor; package io.anuke.mindustry.editor;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.*;
import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.util.Scaling; import io.anuke.arc.util.Scaling;
import io.anuke.mindustry.maps.Map; import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.BorderImage; import io.anuke.mindustry.ui.BorderImage;
import io.anuke.mindustry.ui.dialogs.FloatingDialog; import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.ButtonGroup;
import io.anuke.arc.scene.ui.ScrollPane;
import io.anuke.arc.scene.ui.TextButton;
import io.anuke.arc.scene.ui.layout.Table;
import static io.anuke.mindustry.Vars.world; import static io.anuke.mindustry.Vars.world;
@@ -40,7 +40,7 @@ public class MapRenderer implements Disposable{
} }
} }
chunks = new IndexedRenderer[(int) Math.ceil((float) width / chunksize)][(int) Math.ceil((float) height / chunksize)]; chunks = new IndexedRenderer[(int)Math.ceil((float)width / chunksize)][(int)Math.ceil((float)height / chunksize)];
for(int x = 0; x < chunks.length; x++){ for(int x = 0; x < chunks.length; x++){
for(int y = 0; y < chunks[0].length; y++){ for(int y = 0; y < chunks[0].length; y++){
@@ -119,27 +119,27 @@ public class MapRenderer implements Disposable{
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl, tile.getRotation() * 90 - 90); region.getWidth() * Draw.scl, region.getHeight() * Draw.scl, tile.getRotation() * 90 - 90);
}else{ }else{
mesh.draw(idxWall, region, mesh.draw(idxWall, region,
wx * tilesize + wall.offset() + (tilesize - region.getWidth() * Draw.scl)/2f, wx * tilesize + wall.offset() + (tilesize - region.getWidth() * Draw.scl) / 2f,
wy * tilesize + wall.offset() + (tilesize - region.getHeight() * Draw.scl)/2f, wy * tilesize + wall.offset() + (tilesize - region.getHeight() * Draw.scl) / 2f,
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl); region.getWidth() * Draw.scl, region.getHeight() * Draw.scl);
} }
}else{ }else{
region = floor.editorVariantRegions()[Mathf.randomSeed(idxWall, 0, floor.editorVariantRegions().length-1)]; region = floor.editorVariantRegions()[Mathf.randomSeed(idxWall, 0, floor.editorVariantRegions().length - 1)];
mesh.draw(idxWall, region, wx * tilesize, wy * tilesize, 8, 8); mesh.draw(idxWall, region, wx * tilesize, wy * tilesize, 8, 8);
} }
float offsetX = -(wall.size/3)*tilesize, offsetY = -(wall.size/3) * tilesize; float offsetX = -(wall.size / 3) * tilesize, offsetY = -(wall.size / 3) * tilesize;
if(wall.update || wall.destructible){ if(wall.update || wall.destructible){
mesh.setColor(team.color); mesh.setColor(team.color);
region = Core.atlas.find("block-border-editor"); region = Core.atlas.find("block-border-editor");
}else if(!wall.synthetic() && wall != Blocks.air){ }else if(!wall.synthetic() && wall != Blocks.air){
region = !Core.atlas.isFound(wall.editorIcon()) ? Core.atlas.find("clear-editor") : wall.editorIcon(); region = !Core.atlas.isFound(wall.editorIcon()) ? Core.atlas.find("clear-editor") : wall.editorIcon();
offsetX = tilesize/2f - region.getWidth()/2f * Draw.scl; offsetX = tilesize / 2f - region.getWidth() / 2f * Draw.scl;
offsetY = tilesize/2f - region.getHeight()/2f * Draw.scl; offsetY = tilesize / 2f - region.getHeight() / 2f * Draw.scl;
}else if(wall == Blocks.air && tile.ore() != null){ }else if(wall == Blocks.air && tile.ore() != null){
region = tile.ore().editorVariantRegions()[Mathf.randomSeed(idxWall, 0, tile.ore().editorVariantRegions().length-1)]; region = tile.ore().editorVariantRegions()[Mathf.randomSeed(idxWall, 0, tile.ore().editorVariantRegions().length - 1)];
}else{ }else{
region = Core.atlas.find("clear-editor"); region = Core.atlas.find("clear-editor");
} }
@@ -1,11 +1,11 @@
package io.anuke.mindustry.editor; package io.anuke.mindustry.editor;
import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import io.anuke.arc.function.Consumer; import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.TextButton; import io.anuke.arc.scene.ui.TextButton;
import io.anuke.arc.scene.ui.TextField; import io.anuke.arc.scene.ui.TextField;
import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import static io.anuke.mindustry.Vars.ui; import static io.anuke.mindustry.Vars.ui;
import static io.anuke.mindustry.Vars.world; import static io.anuke.mindustry.Vars.world;
+10 -13
View File
@@ -3,18 +3,14 @@ package io.anuke.mindustry.editor;
import io.anuke.arc.Core; import io.anuke.arc.Core;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.Array;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.ScissorStack;
import io.anuke.arc.input.GestureDetector; import io.anuke.arc.input.GestureDetector;
import io.anuke.arc.input.GestureDetector.GestureListener; import io.anuke.arc.input.GestureDetector.GestureListener;
import io.anuke.arc.input.KeyCode; import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.*; import io.anuke.arc.math.geom.*;
import io.anuke.arc.scene.Element; import io.anuke.arc.scene.Element;
import io.anuke.arc.scene.event.InputEvent; import io.anuke.arc.scene.event.*;
import io.anuke.arc.scene.event.InputListener;
import io.anuke.arc.scene.event.Touchable;
import io.anuke.arc.scene.ui.TextField; import io.anuke.arc.scene.ui.TextField;
import io.anuke.arc.scene.ui.layout.Unit; import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Tmp; import io.anuke.arc.util.Tmp;
@@ -69,6 +65,7 @@ public class MapView extends Element implements GestureListener{
return false; return false;
} }
@Override @Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, KeyCode button){ public boolean touchDown(InputEvent event, float x, float y, int pointer, KeyCode button){
if(pointer != 0){ if(pointer != 0){
@@ -224,7 +221,7 @@ public class MapView extends Element implements GestureListener{
} }
private Point2 project(float x, float y){ private Point2 project(float x, float y){
float ratio = 1f / ((float) editor.width() / editor.height()); float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height); float size = Math.min(width, height);
float sclwidth = size * zoom; float sclwidth = size * zoom;
float sclheight = size * zoom * ratio; float sclheight = size * zoom * ratio;
@@ -232,26 +229,26 @@ public class MapView extends Element implements GestureListener{
y = (y - getHeight() / 2 + sclheight / 2 - offsety * zoom) / sclheight * editor.height(); y = (y - getHeight() / 2 + sclheight / 2 - offsety * zoom) / sclheight * editor.height();
if(editor.drawBlock.size % 2 == 0 && tool != EditorTool.eraser){ if(editor.drawBlock.size % 2 == 0 && tool != EditorTool.eraser){
return Tmp.g1.set((int) (x - 0.5f), (int) (y - 0.5f)); return Tmp.g1.set((int)(x - 0.5f), (int)(y - 0.5f));
}else{ }else{
return Tmp.g1.set((int) x, (int) y); return Tmp.g1.set((int)x, (int)y);
} }
} }
private Vector2 unproject(int x, int y){ private Vector2 unproject(int x, int y){
float ratio = 1f / ((float) editor.width() / editor.height()); float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height); float size = Math.min(width, height);
float sclwidth = size * zoom; float sclwidth = size * zoom;
float sclheight = size * zoom * ratio; float sclheight = size * zoom * ratio;
float px = ((float) x / editor.width()) * sclwidth + offsetx * zoom - sclwidth / 2 + getWidth() / 2; float px = ((float)x / editor.width()) * sclwidth + offsetx * zoom - sclwidth / 2 + getWidth() / 2;
float py = ((float) (y) / editor.height()) * sclheight float py = ((float)(y) / editor.height()) * sclheight
+ offsety * zoom - sclheight / 2 + getHeight() / 2; + offsety * zoom - sclheight / 2 + getHeight() / 2;
return vec.set(px, py); return vec.set(px, py);
} }
@Override @Override
public void draw(){ public void draw(){
float ratio = 1f / ((float) editor.width() / editor.height()); float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height); float size = Math.min(width, height);
float sclwidth = size * zoom; float sclwidth = size * zoom;
float sclheight = size * zoom * ratio; float sclheight = size * zoom * ratio;
@@ -7,9 +7,7 @@ import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.scene.ui.TextField.TextFieldFilter; import io.anuke.arc.scene.ui.TextField.TextFieldFilter;
import io.anuke.arc.scene.ui.layout.Table; import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.util.Align; import io.anuke.arc.util.*;
import io.anuke.arc.util.Strings;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.Vars; import io.anuke.mindustry.Vars;
import io.anuke.mindustry.content.StatusEffects; import io.anuke.mindustry.content.StatusEffects;
import io.anuke.mindustry.content.UnitTypes; import io.anuke.mindustry.content.UnitTypes;
@@ -47,7 +45,7 @@ public class WaveInfoDialog extends FloatingDialog{
}); });
keyDown(key -> { keyDown(key -> {
if(key == KeyCode.ESCAPE || key == KeyCode.BACK) { if(key == KeyCode.ESCAPE || key == KeyCode.BACK){
Core.app.post(this::hide); Core.app.post(this::hide);
} }
}); });
@@ -74,7 +72,7 @@ public class WaveInfoDialog extends FloatingDialog{
dialog.hide(); dialog.hide();
}).disabled(b -> Core.app.getClipboard().getContents() == null || Core.app.getClipboard().getContents().isEmpty()); }).disabled(b -> Core.app.getClipboard().getContents() == null || Core.app.getClipboard().getContents().isEmpty());
dialog.cont.row(); dialog.cont.row();
dialog.cont.addButton("$settings.reset", () -> ui.showConfirm("$confirm", "$settings.clear.confirm", () ->{ dialog.cont.addButton("$settings.reset", () -> ui.showConfirm("$confirm", "$settings.clear.confirm", () -> {
groups = null; groups = null;
buildGroups(); buildGroups();
dialog.hide(); dialog.hide();
@@ -100,7 +98,8 @@ public class WaveInfoDialog extends FloatingDialog{
cont.table("clear", m -> { cont.table("clear", m -> {
m.add("$waves.preview").color(Color.LIGHT_GRAY).growX().center().get().setAlignment(Align.center, Align.center); m.add("$waves.preview").color(Color.LIGHT_GRAY).growX().center().get().setAlignment(Align.center, Align.center);
m.row(); m.row();
m.addButton("-", () -> {}).update(t -> { m.addButton("-", () -> {
}).update(t -> {
if(t.getClickListener().isPressed()){ if(t.getClickListener().isPressed()){
updateTimer += Time.delta(); updateTimer += Time.delta();
if(updateTimer >= updatePeriod){ if(updateTimer >= updatePeriod){
@@ -113,11 +112,12 @@ public class WaveInfoDialog extends FloatingDialog{
m.row(); m.row();
m.pane(t -> preview = t).grow().get().setScrollingDisabled(true, false); m.pane(t -> preview = t).grow().get().setScrollingDisabled(true, false);
m.row(); m.row();
m.addButton("+", () -> {}).update(t -> { m.addButton("+", () -> {
}).update(t -> {
if(t.getClickListener().isPressed()){ if(t.getClickListener().isPressed()){
updateTimer += Time.delta(); updateTimer += Time.delta();
if(updateTimer >= updatePeriod){ if(updateTimer >= updatePeriod){
start ++; start++;
updateTimer = 0f; updateTimer = 0f;
updateWaves(); updateWaves();
} }
@@ -184,7 +184,7 @@ public class WaveInfoDialog extends FloatingDialog{
}).width(80f); }).width(80f);
a.add(" + "); a.add(" + ");
a.addField(Strings.fixed(Math.max((Mathf.isZero(group.unitScaling) ? 0 : 1f/group.unitScaling), 0), 2), TextFieldFilter.floatsOnly, text -> { a.addField(Strings.fixed(Math.max((Mathf.isZero(group.unitScaling) ? 0 : 1f / group.unitScaling), 0), 2), TextFieldFilter.floatsOnly, text -> {
if(Strings.canParsePositiveFloat(text)){ if(Strings.canParsePositiveFloat(text)){
group.unitScaling = 1f / Strings.parseFloat(text); group.unitScaling = 1f / Strings.parseFloat(text);
updateWaves(); updateWaves();
@@ -228,7 +228,7 @@ public class WaveInfoDialog extends FloatingDialog{
dialog.hide(); dialog.hide();
buildGroups(); buildGroups();
}).pad(2).margin(12f).fillX(); }).pad(2).margin(12f).fillX();
if(++i % 3 == 0)dialog.cont.row(); if(++i % 3 == 0) dialog.cont.row();
} }
dialog.show(); dialog.show();
} }
@@ -239,10 +239,10 @@ public class WaveInfoDialog extends FloatingDialog{
Array<SpawnGroup> groups = (this.groups == null ? DefaultWaves.get() : this.groups); Array<SpawnGroup> groups = (this.groups == null ? DefaultWaves.get() : this.groups);
for(int i = start; i < displayed + start; i ++){ for(int i = start; i < displayed + start; i++){
int wave = i; int wave = i;
preview.table("underline", table -> { preview.table("underline", table -> {
table.add((wave+1) + "").color(Pal.accent).center().colspan(2).get().setAlignment(Align.center, Align.center); table.add((wave + 1) + "").color(Pal.accent).center().colspan(2).get().setAlignment(Align.center, Align.center);
table.row(); table.row();
int[] spawned = new int[Vars.content.getBy(ContentType.unit).size]; int[] spawned = new int[Vars.content.getBy(ContentType.unit).size];
@@ -18,7 +18,7 @@ public class DistortFilter extends GenerateFilter{
@Override @Override
public void apply(){ public void apply(){
DummyTile tile = in.tile(in.x / (in.scaling) + (noise(in.x, in.y, scl, mag)-mag/2f)/in.scaling, in.y / (in.scaling) + (noise(in.x, in.y+o, scl, mag)-mag/2f)/in.scaling); DummyTile tile = in.tile(in.x / (in.scaling) + (noise(in.x, in.y, scl, mag) - mag / 2f) / in.scaling, in.y / (in.scaling) + (noise(in.x, in.y + o, scl, mag) - mag / 2f) / in.scaling);
in.floor = content.block(tile.floor); in.floor = content.block(tile.floor);
if(!content.block(tile.block).synthetic() && !in.block.synthetic()) in.block = content.block(tile.block); if(!content.block(tile.block).synthetic() && !in.block.synthetic()) in.block = content.block(tile.block);
@@ -20,7 +20,9 @@ public abstract class FilterOption{
public static final Predicate<Block> oresOnly = b -> b instanceof OreBlock && Core.atlas.isFound(b.icon(Icon.full)); public static final Predicate<Block> oresOnly = b -> b instanceof OreBlock && Core.atlas.isFound(b.icon(Icon.full));
public abstract void build(Table table); public abstract void build(Table table);
public Runnable changed = () -> {};
public Runnable changed = () -> {
};
static class SliderOption extends FilterOption{ static class SliderOption extends FilterOption{
final String name; final String name;
@@ -40,7 +42,7 @@ public abstract class FilterOption{
public void build(Table table){ public void build(Table table){
table.add("$filter.option." + name); table.add("$filter.option." + name);
table.row(); table.row();
Slider slider = table.addSlider(min, max, (max-min)/200f, setter).growX().get(); Slider slider = table.addSlider(min, max, (max - min) / 200f, setter).growX().get();
slider.setValue(getter.get()); slider.setValue(getter.get());
if(updateEditorOnChange){ if(updateEditorOnChange){
slider.changed(changed); slider.changed(changed);
@@ -65,14 +67,14 @@ public abstract class FilterOption{
@Override @Override
public void build(Table table){ public void build(Table table){
table.addButton(b -> b.addImage(supplier.get().icon(Icon.small)).update(i -> ((TextureRegionDrawable)i.getDrawable()).setRegion(supplier.get().icon(Icon.small))).size(8*3), () -> { table.addButton(b -> b.addImage(supplier.get().icon(Icon.small)).update(i -> ((TextureRegionDrawable)i.getDrawable()).setRegion(supplier.get().icon(Icon.small))).size(8 * 3), () -> {
FloatingDialog dialog = new FloatingDialog(""); FloatingDialog dialog = new FloatingDialog("");
dialog.setFillParent(false); dialog.setFillParent(false);
int i = 0; int i = 0;
for(Block block : Vars.content.blocks()){ for(Block block : Vars.content.blocks()){
if(!filter.test(block)) continue; if(!filter.test(block)) continue;
dialog.cont.addImage(block.icon(Icon.medium)).size(8*4).pad(3).get().clicked(() -> { dialog.cont.addImage(block.icon(Icon.medium)).size(8 * 4).pad(3).get().clicked(() -> {
consumer.accept(block); consumer.accept(block);
dialog.hide(); dialog.hide();
changed.run(); changed.run();
@@ -11,7 +11,7 @@ import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.blocks.Floor; import io.anuke.mindustry.world.blocks.Floor;
public abstract class GenerateFilter{ public abstract class GenerateFilter{
protected float o = (float)(Math.random()*10000000.0); protected float o = (float)(Math.random() * 10000000.0);
protected long seed; protected long seed;
protected GenerateInput in; protected GenerateInput in;
@@ -20,15 +20,15 @@ public abstract class GenerateFilter{
protected abstract void apply(); protected abstract void apply();
protected float noise(float x, float y, float scl, float mag){ protected float noise(float x, float y, float scl, float mag){
return (float)in.noise.octaveNoise2D(1f, 0f, 1f/scl, x + o, y + o)*mag; return (float)in.noise.octaveNoise2D(1f, 0f, 1f / scl, x + o, y + o) * mag;
} }
protected float noise(float x, float y, float scl, float mag, float octaves, float persistence){ protected float noise(float x, float y, float scl, float mag, float octaves, float persistence){
return (float)in.noise.octaveNoise2D(octaves, persistence, 1f/scl, x + o, y + o)*mag; return (float)in.noise.octaveNoise2D(octaves, persistence, 1f / scl, x + o, y + o) * mag;
} }
protected float rnoise(float x, float y, float scl, float mag){ protected float rnoise(float x, float y, float scl, float mag){
return in.pnoise.getValue((int)(x + o), (int)(y + o), 1f/scl)*mag; return in.pnoise.getValue((int)(x + o), (int)(y + o), 1f / scl) * mag;
} }
public void randomize(){ public void randomize(){
@@ -4,7 +4,8 @@ import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.editor.generation.FilterOption.SliderOption; import io.anuke.mindustry.editor.generation.FilterOption.SliderOption;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import static io.anuke.mindustry.editor.generation.FilterOption.*; import static io.anuke.mindustry.editor.generation.FilterOption.BlockOption;
import static io.anuke.mindustry.editor.generation.FilterOption.oresOnly;
public class OreFilter extends GenerateFilter{ public class OreFilter extends GenerateFilter{
float scl = 40, threshold = 0.8f, octaves = 3f, falloff = 0.5f; float scl = 40, threshold = 0.8f, octaves = 3f, falloff = 0.5f;
@@ -28,7 +28,7 @@ public class TerrainFilter extends GenerateFilter{
@Override @Override
public void apply(){ public void apply(){
float noise = noise(in.x, in.y, scl, magnitude, octaves, falloff) + Mathf.dst((float) in.x / in.editor.width(), (float) in.y / in.editor.height(), 0.5f, 0.5f) * circleScl; float noise = noise(in.x, in.y, scl, magnitude, octaves, falloff) + Mathf.dst((float)in.x / in.editor.width(), (float)in.y / in.editor.height(), 0.5f, 0.5f) * circleScl;
in.floor = floor; in.floor = floor;
in.ore = Blocks.air; in.ore = Blocks.air;
@@ -7,10 +7,7 @@ import io.anuke.arc.function.Consumer;
import io.anuke.arc.function.Predicate; import io.anuke.arc.function.Predicate;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Bullets; import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
@@ -27,7 +24,7 @@ import io.anuke.mindustry.world.Tile;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
/**Utility class for damaging in an area.*/ /** Utility class for damaging in an area. */
public class Damage{ public class Damage{
private static Rectangle rect = new Rectangle(); private static Rectangle rect = new Rectangle();
private static Rectangle hitrect = new Rectangle(); private static Rectangle hitrect = new Rectangle();
@@ -35,10 +32,10 @@ public class Damage{
private static GridBits bits = new GridBits(30, 30); private static GridBits bits = new GridBits(30, 30);
private static IntQueue propagation = new IntQueue(); private static IntQueue propagation = new IntQueue();
/**Creates a dynamic explosion based on specified parameters.*/ /** Creates a dynamic explosion based on specified parameters. */
public static void dynamicExplosion(float x, float y, float flammability, float explosiveness, float power, float radius, Color color){ public static void dynamicExplosion(float x, float y, float flammability, float explosiveness, float power, float radius, Color color){
for(int i = 0; i < Mathf.clamp(power / 20, 0, 6); i++){ for(int i = 0; i < Mathf.clamp(power / 20, 0, 6); i++){
int branches = 5 + Mathf.clamp((int) (power / 30), 1, 20); int branches = 5 + Mathf.clamp((int)(power / 30), 1, 20);
Time.run(i * 2f + Mathf.random(4f), () -> Lightning.create(Team.none, Pal.power, 3, Time.run(i * 2f + Mathf.random(4f), () -> Lightning.create(Team.none, Pal.power, 3,
x, y, Mathf.random(360f), branches + Mathf.range(2))); x, y, Mathf.random(360f), branches + Mathf.range(2)));
} }
@@ -47,7 +44,7 @@ public class Damage{
Time.run(i / 2f, () -> Call.createBullet(Bullets.fireball, x, y, Mathf.random(360f))); Time.run(i / 2f, () -> Call.createBullet(Bullets.fireball, x, y, Mathf.random(360f)));
} }
int waves = Mathf.clamp((int) (explosiveness / 4), 0, 30); int waves = Mathf.clamp((int)(explosiveness / 4), 0, 30);
for(int i = 0; i < waves; i++){ for(int i = 0; i < waves; i++){
int f = i; int f = i;
@@ -67,7 +64,7 @@ public class Damage{
float shake = Math.min(explosiveness / 4f + 3f, 9f); float shake = Math.min(explosiveness / 4f + 3f, 9f);
Effects.shake(shake, shake, x, y); Effects.shake(shake, shake, x, y);
Effects.effect(Fx.dynamicExplosion, x, y, radius/8f); Effects.effect(Fx.dynamicExplosion, x, y, radius / 8f);
} }
public static void createIncend(float x, float y, float range, int amount){ public static void createIncend(float x, float y, float range, int amount){
@@ -136,7 +133,7 @@ public class Damage{
Units.getNearbyEnemies(team, rect, cons); Units.getNearbyEnemies(team, rect, cons);
} }
/**Damages all entities and blocks in a radius that are enemies of the team.*/ /** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damageUnits(Team team, float x, float y, float size, float damage, Predicate<io.anuke.mindustry.entities.type.Unit> predicate, Consumer<io.anuke.mindustry.entities.type.Unit> acceptor){ public static void damageUnits(Team team, float x, float y, float size, float damage, Predicate<io.anuke.mindustry.entities.type.Unit> predicate, Consumer<io.anuke.mindustry.entities.type.Unit> acceptor){
Consumer<io.anuke.mindustry.entities.type.Unit> cons = entity -> { Consumer<io.anuke.mindustry.entities.type.Unit> cons = entity -> {
if(!predicate.test(entity)) return; if(!predicate.test(entity)) return;
@@ -157,17 +154,17 @@ public class Damage{
} }
} }
/**Damages everything in a radius.*/ /** Damages everything in a radius. */
public static void damage(float x, float y, float radius, float damage){ public static void damage(float x, float y, float radius, float damage){
damage(null, x, y, radius, damage, false); damage(null, x, y, radius, damage, false);
} }
/**Damages all entities and blocks in a radius that are enemies of the team.*/ /** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damage(Team team, float x, float y, float radius, float damage){ public static void damage(Team team, float x, float y, float radius, float damage){
damage(team, x, y, radius, damage, false); damage(team, x, y, radius, damage, false);
} }
/**Damages all entities and blocks in a radius that are enemies of the team.*/ /** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damage(Team team, float x, float y, float radius, float damage, boolean complete){ public static void damage(Team team, float x, float y, float radius, float damage, boolean complete){
Consumer<Unit> cons = entity -> { Consumer<Unit> cons = entity -> {
if(entity.getTeam() == team || entity.dst(x, y) > radius){ if(entity.getTeam() == team || entity.dst(x, y) > radius){
@@ -201,11 +198,11 @@ public class Damage{
public static void tileDamage(Team team, int startx, int starty, int radius, float baseDamage){ public static void tileDamage(Team team, int startx, int starty, int radius, float baseDamage){
bits.clear(); bits.clear();
propagation.clear(); propagation.clear();
int bitOffset = bits.width()/2; int bitOffset = bits.width() / 2;
propagation.addFirst(PropCell.get((byte)0, (byte)0, (short)baseDamage)); propagation.addFirst(PropCell.get((byte)0, (byte)0, (short)baseDamage));
//clamp radius to fit bits //clamp radius to fit bits
radius = Math.min(radius, bits.width()/2); radius = Math.min(radius, bits.width() / 2);
while(!propagation.isEmpty()){ while(!propagation.isEmpty()){
int prop = propagation.removeLast(); int prop = propagation.removeLast();
@@ -242,7 +239,7 @@ public class Damage{
} }
private static void completeDamage(Team team, float x, float y, float radius, float damage){ private static void completeDamage(Team team, float x, float y, float radius, float damage){
int trad = (int) (radius / tilesize); int trad = (int)(radius / tilesize);
for(int dx = -trad; dx <= trad; dx++){ for(int dx = -trad; dx <= trad; dx++){
for(int dy = -trad; dy <= trad; dy++){ for(int dy = -trad; dy <= trad; dy++){
Tile tile = world.tile(Math.round(x / tilesize) + dx, Math.round(y / tilesize) + dy); Tile tile = world.tile(Math.round(x / tilesize) + dx, Math.round(y / tilesize) + dy);
@@ -3,10 +3,7 @@ package io.anuke.mindustry.entities;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntSet; import io.anuke.arc.collection.IntSet;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.geom.QuadTree;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.mindustry.entities.traits.Entity; import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.traits.SolidTrait; import io.anuke.mindustry.entities.traits.SolidTrait;
@@ -135,7 +132,7 @@ public class EntityCollisions{
for(Entity entity : group.all()){ for(Entity entity : group.all()){
if(entity instanceof SolidTrait){ if(entity instanceof SolidTrait){
SolidTrait s = (SolidTrait) entity; SolidTrait s = (SolidTrait)entity;
s.lastPosition().set(s.getX(), s.getY()); s.lastPosition().set(s.getX(), s.getY());
tree.insert(s); tree.insert(s);
} }
@@ -144,8 +141,8 @@ public class EntityCollisions{
private void checkCollide(Entity entity, Entity other){ private void checkCollide(Entity entity, Entity other){
SolidTrait a = (SolidTrait) entity; SolidTrait a = (SolidTrait)entity;
SolidTrait b = (SolidTrait) other; SolidTrait b = (SolidTrait)other;
a.hitbox(this.r1); a.hitbox(this.r1);
b.hitbox(this.r2); b.hitbox(this.r2);
@@ -228,7 +225,7 @@ public class EntityCollisions{
if(!(entity instanceof SolidTrait) || collided.contains(entity.getID())) if(!(entity instanceof SolidTrait) || collided.contains(entity.getID()))
continue; continue;
SolidTrait solid = (SolidTrait) entity; SolidTrait solid = (SolidTrait)entity;
solid.hitbox(r1); solid.hitbox(r1);
r1.x += (solid.lastPosition().x - solid.getX()); r1.x += (solid.lastPosition().x - solid.getX());
@@ -46,7 +46,7 @@ public class EntityDraw{
for(Entity e : group.all()){ for(Entity e : group.all()){
if(!(e instanceof DrawTrait) || !toDraw.test((T)e) || !e.isAdded()) continue; if(!(e instanceof DrawTrait) || !toDraw.test((T)e) || !e.isAdded()) continue;
if(!clip || rect.setSize(((DrawTrait) e).drawSize()).setCenter(e.getX(), e.getY()).overlaps(viewport)){ if(!clip || rect.setSize(((DrawTrait)e).drawSize()).setCenter(e.getX(), e.getY()).overlaps(viewport)){
cons.accept((T)e); cons.accept((T)e);
} }
} }
@@ -180,7 +180,7 @@ public class EntityGroup<T extends Entity>{
return null; return null;
} }
/**Returns the logic-only array for iteration.*/ /** Returns the logic-only array for iteration. */
public Array<T> all(){ public Array<T> all(){
return entityArray; return entityArray;
} }
@@ -74,7 +74,7 @@ public class EntityQuery{
float cdist = 0f; float cdist = 0f;
Array<SolidTrait> entities = getNearby(group, x, y, range * 2f); Array<SolidTrait> entities = getNearby(group, x, y, range * 2f);
for(int i = 0; i < entities.size; i++){ for(int i = 0; i < entities.size; i++){
T e = (T) entities.get(i); T e = (T)entities.get(i);
if(!pred.test(e)) if(!pred.test(e))
continue; continue;
@@ -14,7 +14,6 @@ public class Predict{
/** /**
* Calculates of intercept of a stationary and moving target. Do not call from multiple threads! * Calculates of intercept of a stationary and moving target. Do not call from multiple threads!
*
* @param srcx X of shooter * @param srcx X of shooter
* @param srcy Y of shooter * @param srcy Y of shooter
* @param dstx X of target * @param dstx X of target
+30 -34
View File
@@ -7,10 +7,7 @@ import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.arc.math.geom.Rectangle;
import io.anuke.mindustry.entities.traits.TargetTrait; import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
@@ -29,7 +26,6 @@ public class Units{
/** /**
* Validates a target. * Validates a target.
*
* @param target The target to validate * @param target The target to validate
* @param team The team of the thing doing tha targeting * @param team The team of the thing doing tha targeting
* @param x The X position of the thing doign the targeting * @param x The X position of the thing doign the targeting
@@ -41,17 +37,17 @@ public class Units{
return target == null || (range != Float.MAX_VALUE && target.dst(x, y) > range) || target.getTeam() == team || !target.isValid(); return target == null || (range != Float.MAX_VALUE && target.dst(x, y) > range) || target.getTeam() == team || !target.isValid();
} }
/**See {@link #invalidateTarget(TargetTrait, Team, float, float, float)}*/ /** See {@link #invalidateTarget(TargetTrait, Team, float, float, float)} */
public static boolean invalidateTarget(TargetTrait target, Team team, float x, float y){ public static boolean invalidateTarget(TargetTrait target, Team team, float x, float y){
return invalidateTarget(target, team, x, y, Float.MAX_VALUE); return invalidateTarget(target, team, x, y, Float.MAX_VALUE);
} }
/**See {@link #invalidateTarget(TargetTrait, Team, float, float, float)}*/ /** See {@link #invalidateTarget(TargetTrait, Team, float, float, float)} */
public static boolean invalidateTarget(TargetTrait target, Unit targeter){ public static boolean invalidateTarget(TargetTrait target, Unit targeter){
return invalidateTarget(target, targeter.getTeam(), targeter.x, targeter.y, targeter.getWeapon().bullet.range()); return invalidateTarget(target, targeter.getTeam(), targeter.x, targeter.y, targeter.getWeapon().bullet.range());
} }
/**Returns whether there are any entities on this tile.*/ /** Returns whether there are any entities on this tile. */
public static boolean anyEntities(Tile tile){ public static boolean anyEntities(Tile tile){
Block type = tile.block(); Block type = tile.block();
rect.setSize(type.size * tilesize, type.size * tilesize); rect.setSize(type.size * tilesize, type.size * tilesize);
@@ -60,7 +56,7 @@ public class Units{
return anyEntities(rect); return anyEntities(rect);
} }
/**Can be called from any thread.*/ /** Can be called from any thread. */
public static boolean anyEntities(Rectangle rect){ public static boolean anyEntities(Rectangle rect){
boolResult = false; boolResult = false;
@@ -78,7 +74,7 @@ public class Units{
return boolResult; return boolResult;
} }
/**Returns whether there are any entities on this tile, with the hitbox expanded.*/ /** Returns whether there are any entities on this tile, with the hitbox expanded. */
public static boolean anyEntities(Tile tile, float expansion, Predicate<Unit> pred){ public static boolean anyEntities(Tile tile, float expansion, Predicate<Unit> pred){
Block type = tile.block(); Block type = tile.block();
rect.setSize(type.size * tilesize + expansion, type.size * tilesize + expansion); rect.setSize(type.size * tilesize + expansion, type.size * tilesize + expansion);
@@ -100,18 +96,18 @@ public class Units{
return value[0]; return value[0];
} }
/**Returns the neareset damaged tile.*/ /** Returns the neareset damaged tile. */
public static TileEntity findDamagedTile(Team team, float x, float y){ public static TileEntity findDamagedTile(Team team, float x, float y){
Tile tile = Geometry.findClosest(x, y, world.indexer.getDamaged(team)); Tile tile = Geometry.findClosest(x, y, world.indexer.getDamaged(team));
return tile == null ? null : tile.entity; return tile == null ? null : tile.entity;
} }
/**Returns the neareset ally tile in a range.*/ /** Returns the neareset ally tile in a range. */
public static TileEntity findAllyTile(Team team, float x, float y, float range, Predicate<Tile> pred){ public static TileEntity findAllyTile(Team team, float x, float y, float range, Predicate<Tile> pred){
return world.indexer.findTile(team, x, y, range, pred); return world.indexer.findTile(team, x, y, range, pred);
} }
/**Returns the neareset enemy tile in a range.*/ /** Returns the neareset enemy tile in a range. */
public static TileEntity findEnemyTile(Team team, float x, float y, float range, Predicate<Tile> pred){ public static TileEntity findEnemyTile(Team team, float x, float y, float range, Predicate<Tile> pred){
if(team == Team.none) return null; if(team == Team.none) return null;
@@ -124,7 +120,7 @@ public class Units{
return null; return null;
} }
/**Iterates over all units on all teams, including players.*/ /** Iterates over all units on all teams, including players. */
public static void allUnits(Consumer<Unit> cons){ public static void allUnits(Consumer<Unit> cons){
//check all unit groups first //check all unit groups first
for(EntityGroup<BaseUnit> group : unitGroups){ for(EntityGroup<BaseUnit> group : unitGroups){
@@ -141,17 +137,17 @@ public class Units{
} }
} }
/**Returns the closest target enemy. First, units are checked, then tile entities.*/ /** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range){ public static TargetTrait getClosestTarget(Team team, float x, float y, float range){
return getClosestTarget(team, x, y, range, Unit::isValid); return getClosestTarget(team, x, y, range, Unit::isValid);
} }
/**Returns the closest target enemy. First, units are checked, then tile entities.*/ /** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred){ public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred){
return getClosestTarget(team, x, y, range, unitPred, t -> true); return getClosestTarget(team, x, y, range, unitPred, t -> true);
} }
/**Returns the closest target enemy. First, units are checked, then tile entities.*/ /** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred, Predicate<Tile> tilePred){ public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred, Predicate<Tile> tilePred){
Unit unit = getClosestEnemy(team, x, y, range, unitPred); Unit unit = getClosestEnemy(team, x, y, range, unitPred);
if(unit != null){ if(unit != null){
@@ -161,7 +157,7 @@ public class Units{
} }
} }
/**Returns the closest enemy of this team. Filter by predicate.*/ /** Returns the closest enemy of this team. Filter by predicate. */
public static Unit getClosestEnemy(Team team, float x, float y, float range, Predicate<Unit> predicate){ public static Unit getClosestEnemy(Team team, float x, float y, float range, Predicate<Unit> predicate){
if(team == Team.none) return null; if(team == Team.none) return null;
@@ -186,7 +182,7 @@ public class Units{
return result; return result;
} }
/**Returns the closest ally of this team. Filter by predicate.*/ /** Returns the closest ally of this team. Filter by predicate. */
public static Unit getClosest(Team team, float x, float y, float range, Predicate<Unit> predicate){ public static Unit getClosest(Team team, float x, float y, float range, Predicate<Unit> predicate){
result = null; result = null;
cdist = 0f; cdist = 0f;
@@ -209,21 +205,21 @@ public class Units{
return result; return result;
} }
/**Iterates over all units in a rectangle.*/ /** Iterates over all units in a rectangle. */
public static void getNearby(Team team, Rectangle rect, Consumer<Unit> cons){ public static void getNearby(Team team, Rectangle rect, Consumer<Unit> cons){
EntityGroup<BaseUnit> group = unitGroups[team.ordinal()]; EntityGroup<BaseUnit> group = unitGroups[team.ordinal()];
if(!group.isEmpty()){ if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity)); EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
} }
//now check all players //now check all players
EntityQuery.getNearby(playerGroup, rect, player -> { EntityQuery.getNearby(playerGroup, rect, player -> {
if(((Unit) player).getTeam() == team) cons.accept((Unit) player); if(((Unit)player).getTeam() == team) cons.accept((Unit)player);
}); });
} }
/**Iterates over all units in a circle around this position.*/ /** Iterates over all units in a circle around this position. */
public static void getNearby(Team team, float x, float y, float radius, Consumer<Unit> cons){ public static void getNearby(Team team, float x, float y, float radius, Consumer<Unit> cons){
rect.setSize(radius * 2).setCenter(x, y); rect.setSize(radius * 2).setCenter(x, y);
@@ -231,53 +227,53 @@ public class Units{
if(!group.isEmpty()){ if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> { EntityQuery.getNearby(group, rect, entity -> {
if(entity.dst(x, y) <= radius){ if(entity.dst(x, y) <= radius){
cons.accept((Unit) entity); cons.accept((Unit)entity);
} }
}); });
} }
//now check all players //now check all players
EntityQuery.getNearby(playerGroup, rect, player -> { EntityQuery.getNearby(playerGroup, rect, player -> {
if(((Unit) player).getTeam() == team && player.dst(x, y) <= radius){ if(((Unit)player).getTeam() == team && player.dst(x, y) <= radius){
cons.accept((Unit) player); cons.accept((Unit)player);
} }
}); });
} }
/**Iterates over all units in a rectangle.*/ /** Iterates over all units in a rectangle. */
public static void getNearby(Rectangle rect, Consumer<Unit> cons){ public static void getNearby(Rectangle rect, Consumer<Unit> cons){
for(Team team : Team.all){ for(Team team : Team.all){
EntityGroup<BaseUnit> group = unitGroups[team.ordinal()]; EntityGroup<BaseUnit> group = unitGroups[team.ordinal()];
if(!group.isEmpty()){ if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity)); EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
} }
} }
//now check all enemy players //now check all enemy players
EntityQuery.getNearby(playerGroup, rect, player -> cons.accept((Unit) player)); EntityQuery.getNearby(playerGroup, rect, player -> cons.accept((Unit)player));
} }
/**Iterates over all units that are enemies of this team.*/ /** Iterates over all units that are enemies of this team. */
public static void getNearbyEnemies(Team team, Rectangle rect, Consumer<Unit> cons){ public static void getNearbyEnemies(Team team, Rectangle rect, Consumer<Unit> cons){
EnumSet<Team> targets = state.teams.enemiesOf(team); EnumSet<Team> targets = state.teams.enemiesOf(team);
for(Team other : targets){ for(Team other : targets){
EntityGroup<BaseUnit> group = unitGroups[other.ordinal()]; EntityGroup<BaseUnit> group = unitGroups[other.ordinal()];
if(!group.isEmpty()){ if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity)); EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
} }
} }
//now check all enemy players //now check all enemy players
EntityQuery.getNearby(playerGroup, rect, player -> { EntityQuery.getNearby(playerGroup, rect, player -> {
if(targets.contains(((Player) player).getTeam())){ if(targets.contains(((Player)player).getTeam())){
cons.accept((Unit) player); cons.accept((Unit)player);
} }
}); });
} }
/**Iterates over all units.*/ /** Iterates over all units. */
public static void getAllUnits(Consumer<Unit> cons){ public static void getAllUnits(Consumer<Unit> cons){
for(Team team : Team.all){ for(Team team : Team.all){
@@ -1,9 +1,9 @@
package io.anuke.mindustry.entities.bullet; package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect;
//TODO scale velocity depending on fslope() //TODO scale velocity depending on fslope()
public class ArtilleryBulletType extends BasicBulletType{ public class ArtilleryBulletType extends BasicBulletType{
@@ -6,7 +6,7 @@ import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.TextureRegion; import io.anuke.arc.graphics.g2d.TextureRegion;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
/**An extended BulletType for most ammo-based bullets shot from turrets and units.*/ /** An extended BulletType for most ammo-based bullets shot from turrets and units. */
public class BasicBulletType extends BulletType{ public class BasicBulletType extends BulletType{
public Color backColor = Pal.bulletYellowBack, frontColor = Pal.bulletYellow; public Color backColor = Pal.bulletYellowBack, frontColor = Pal.bulletYellow;
public float bulletWidth = 5f, bulletHeight = 7f; public float bulletWidth = 5f, bulletHeight = 7f;
@@ -5,9 +5,7 @@ import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2; import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Interval; import io.anuke.arc.util.*;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.pooling.Pool.Poolable; import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.entities.EntityGroup; import io.anuke.mindustry.entities.EntityGroup;
@@ -18,9 +16,7 @@ import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -36,7 +32,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
protected Entity owner; protected Entity owner;
protected float time; protected float time;
/**Internal use only!*/ /** Internal use only! */
public Bullet(){ public Bullet(){
} }
@@ -64,7 +60,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
bullet.velocity.set(0, type.speed).setAngle(angle).scl(velocityScl); bullet.velocity.set(0, type.speed).setAngle(angle).scl(velocityScl);
if(type.keepVelocity){ if(type.keepVelocity){
bullet.velocity.add(owner instanceof VelocityTrait ? ((VelocityTrait) owner).velocity() : Vector2.ZERO); bullet.velocity.add(owner instanceof VelocityTrait ? ((VelocityTrait)owner).velocity() : Vector2.ZERO);
} }
bullet.team = team; bullet.team = team;
@@ -85,13 +81,13 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
return create(type, parent.owner, parent.team, x, y, angle, velocityScl); return create(type, parent.owner, parent.team, x, y, angle, velocityScl);
} }
/**Internal use only.*/ /** Internal use only. */
@Remote(called = Loc.server, unreliable = true) @Remote(called = Loc.server, unreliable = true)
public static void createBullet(BulletType type, float x, float y, float angle){ public static void createBullet(BulletType type, float x, float y, float angle){
create(type, null, Team.none, x, y, angle); create(type, null, Team.none, x, y, angle);
} }
/**ok*/ /** ok */
@Remote(called = Loc.server, unreliable = true) @Remote(called = Loc.server, unreliable = true)
public static void createBullet(BulletType type, Team team, float x, float y, float angle){ public static void createBullet(BulletType type, Team team, float x, float y, float angle){
create(type, null, team, x, y, angle); create(type, null, team, x, y, angle);
@@ -133,7 +129,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
public float damageMultiplier(){ public float damageMultiplier(){
if(owner instanceof Unit){ if(owner instanceof Unit){
return ((Unit) owner).getDamageMultipler(); return ((Unit)owner).getDamageMultipler();
} }
return 1f; return 1f;
} }
@@ -194,7 +190,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
@Override @Override
public boolean collides(SolidTrait other){ public boolean collides(SolidTrait other){
return type.collides && (other != owner && !(other instanceof DamageTrait)) && !supressCollision && !(other instanceof Unit && ((Unit) other).isFlying() && !type.collidesAir); return type.collides && (other != owner && !(other instanceof DamageTrait)) && !supressCollision && !(other instanceof Unit && ((Unit)other).isFlying() && !type.collidesAir);
} }
@Override @Override
@@ -203,7 +199,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
type.hit(this, x, y); type.hit(this, x, y);
if(other instanceof Unit){ if(other instanceof Unit){
Unit unit = (Unit) other; Unit unit = (Unit)other;
unit.velocity().add(Tmp.v3.set(other.getX(), other.getY()).sub(x, y).setLength(type.knockback / unit.mass())); unit.velocity().add(Tmp.v3.set(other.getX(), other.getY()).sub(x, y).setLength(type.knockback / unit.mass()));
unit.applyEffect(type.status, type.statusDuration); unit.applyEffect(type.status, type.statusDuration);
} }
@@ -218,7 +214,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
velocity.scl(Mathf.clamp(1f - type.drag * Time.delta())); velocity.scl(Mathf.clamp(1f - type.drag * Time.delta()));
time += Time.delta() * 1f/(lifeScl); time += Time.delta() * 1f / (lifeScl);
time = Mathf.clamp(time, 0, type.lifetime); time = Mathf.clamp(time, 0, type.lifetime);
if(time >= type.lifetime){ if(time >= type.lifetime){
@@ -336,12 +332,12 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
velocity.limit(f); velocity.limit(f);
} }
/** Sets the bullet's rotation in degrees.*/ /** Sets the bullet's rotation in degrees. */
public void rot(float angle){ public void rot(float angle){
velocity.setAngle(angle); velocity.setAngle(angle);
} }
/** @return the bullet's rotation.*/ /** @return the bullet's rotation. */
public float rot(){ public float rot(){
float angle = Mathf.atan2(velocity.x, velocity.y) * Mathf.radiansToDegrees; float angle = Mathf.atan2(velocity.x, velocity.y) * Mathf.radiansToDegrees;
if(angle < 0) angle += 360; if(angle < 0) angle += 360;
@@ -4,10 +4,8 @@ import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.content.StatusEffects; import io.anuke.mindustry.content.StatusEffects;
import io.anuke.mindustry.entities.Damage; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect; import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.effect.Lightning; import io.anuke.mindustry.entities.effect.Lightning;
import io.anuke.mindustry.entities.traits.TargetTrait; import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.game.Content; import io.anuke.mindustry.game.Content;
@@ -26,39 +24,39 @@ public abstract class BulletType extends Content{
public boolean pierce; public boolean pierce;
public Effect hitEffect, despawnEffect; public Effect hitEffect, despawnEffect;
/**Effect created when shooting.*/ /** Effect created when shooting. */
public Effect shootEffect = Fx.shootSmall; public Effect shootEffect = Fx.shootSmall;
/**Extra smoke effect created when shooting.*/ /** Extra smoke effect created when shooting. */
public Effect smokeEffect = Fx.shootSmallSmoke; public Effect smokeEffect = Fx.shootSmallSmoke;
/**Extra inaccuracy when firing.*/ /** Extra inaccuracy when firing. */
public float inaccuracy = 0f; public float inaccuracy = 0f;
/**How many bullets get created per ammo item/liquid.*/ /** How many bullets get created per ammo item/liquid. */
public float ammoMultiplier = 1f; public float ammoMultiplier = 1f;
/**Multiplied by turret reload speed to get final shoot speed.*/ /** Multiplied by turret reload speed to get final shoot speed. */
public float reloadMultiplier = 1f; public float reloadMultiplier = 1f;
/**Recoil from shooter entities.*/ /** Recoil from shooter entities. */
public float recoil; public float recoil;
public float splashDamage = 0f; public float splashDamage = 0f;
/**Knockback in velocity.*/ /** Knockback in velocity. */
public float knockback; public float knockback;
/**Whether this bullet hits tiles.*/ /** Whether this bullet hits tiles. */
public boolean hitTiles = true; public boolean hitTiles = true;
/**Status effect applied on hit.*/ /** Status effect applied on hit. */
public StatusEffect status = StatusEffects.none; public StatusEffect status = StatusEffects.none;
/**Intensity of applied status effect in terms of duration.*/ /** Intensity of applied status effect in terms of duration. */
public float statusDuration = 60 * 1f; public float statusDuration = 60 * 1f;
/**Whether to sync this bullet to clients.*/ /** Whether to sync this bullet to clients. */
public boolean syncable; public boolean syncable;
/**Whether this bullet type collides with tiles.*/ /** Whether this bullet type collides with tiles. */
public boolean collidesTiles = true; public boolean collidesTiles = true;
/**Whether this bullet type collides with tiles that are of the same team.*/ /** Whether this bullet type collides with tiles that are of the same team. */
public boolean collidesTeam = false; public boolean collidesTeam = false;
/**Whether this bullet type collides with air units.*/ /** Whether this bullet type collides with air units. */
public boolean collidesAir = true; public boolean collidesAir = true;
/**Whether this bullet types collides with anything at all.*/ /** Whether this bullet types collides with anything at all. */
public boolean collides = true; public boolean collides = true;
/**Whether velocity is inherited from the shooter.*/ /** Whether velocity is inherited from the shooter. */
public boolean keepVelocity = true; public boolean keepVelocity = true;
//additional effects //additional effects
@@ -67,7 +65,7 @@ public abstract class BulletType extends Content{
public float fragVelocityMin = 0.2f, fragVelocityMax = 1f; public float fragVelocityMin = 0.2f, fragVelocityMax = 1f;
public BulletType fragBullet = null; public BulletType fragBullet = null;
/**Use a negative value to disable splash damage.*/ /** Use a negative value to disable splash damage. */
public float splashDamageRadius = -1f; public float splashDamageRadius = -1f;
public int incendAmount = 0; public int incendAmount = 0;
@@ -90,7 +88,7 @@ public abstract class BulletType extends Content{
despawnEffect = Fx.hitBulletSmall; despawnEffect = Fx.hitBulletSmall;
} }
/**Returns maximum distance the bullet this bullet type has can travel.*/ /** Returns maximum distance the bullet this bullet type has can travel. */
public float range(){ public float range(){
return speed * lifetime * (1f - drag); return speed * lifetime * (1f - drag);
} }
@@ -136,7 +134,7 @@ public abstract class BulletType extends Content{
hit(b); hit(b);
} }
for (int i = 0; i < lightining; i++) { for(int i = 0; i < lightining; i++){
Lightning.create(b.getTeam(), Pal.surge, damage, b.x, b.y, Mathf.random(360f), lightningLength); Lightning.create(b.getTeam(), Pal.surge, damage, b.x, b.y, Mathf.random(360f), lightningLength);
} }
} }
@@ -1,9 +1,9 @@
package io.anuke.mindustry.entities.bullet; package io.anuke.mindustry.entities.bullet;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Units; import io.anuke.mindustry.entities.Units;
import io.anuke.arc.util.Time;
public abstract class FlakBulletType extends BasicBulletType{ public abstract class FlakBulletType extends BasicBulletType{
protected static Rectangle rect = new Rectangle(); protected static Rectangle rect = new Rectangle();
@@ -24,7 +24,7 @@ public abstract class FlakBulletType extends BasicBulletType{
if(b.getData() instanceof Integer) return; if(b.getData() instanceof Integer) return;
if(b.timer.get(2, 6)){ if(b.timer.get(2, 6)){
Units.getNearbyEnemies(b.getTeam(), rect.setSize(explodeRange*2f).setCenter(b.x, b.y), unit -> { Units.getNearbyEnemies(b.getTeam(), rect.setSize(explodeRange * 2f).setCenter(b.x, b.y), unit -> {
if(b.getData() instanceof Float) return; if(b.getData() instanceof Float) return;
if(unit.dst(b) < explodeRange){ if(unit.dst(b) < explodeRange){
@@ -1,6 +1,5 @@
package io.anuke.mindustry.entities.bullet; package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill; import io.anuke.arc.graphics.g2d.Fill;
@@ -8,6 +7,7 @@ import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2; import io.anuke.arc.math.geom.Point2;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.effect.Fire; import io.anuke.mindustry.entities.effect.Fire;
import io.anuke.mindustry.entities.effect.Puddle; import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.type.Liquid; import io.anuke.mindustry.type.Liquid;
@@ -35,11 +35,11 @@ public class LiquidBulletType extends BulletType{
@Override @Override
public float range(){ public float range(){
return speed * lifetime /2f; return speed * lifetime / 2f;
} }
@Override @Override
public void update(Bullet b) { public void update(Bullet b){
super.update(b); super.update(b);
if(liquid.canExtinguish()){ if(liquid.canExtinguish()){
@@ -1,11 +1,11 @@
package io.anuke.mindustry.entities.bullet; package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.math.Angles; import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.world.blocks.distribution.MassDriver.DriverBulletData; import io.anuke.mindustry.world.blocks.distribution.MassDriver.DriverBulletData;
@@ -45,7 +45,7 @@ public class MassDriverBolt extends BulletType{
float hitDst = 7f; float hitDst = 7f;
DriverBulletData data = (DriverBulletData) b.getData(); DriverBulletData data = (DriverBulletData)b.getData();
//if the target is dead, just keep flying until the bullet explodes //if the target is dead, just keep flying until the bullet explodes
if(data.to.isDead()){ if(data.to.isDead()){
@@ -87,7 +87,7 @@ public class MassDriverBolt extends BulletType{
if(!(b.getData() instanceof DriverBulletData)) return; if(!(b.getData() instanceof DriverBulletData)) return;
DriverBulletData data = (DriverBulletData) b.getData(); DriverBulletData data = (DriverBulletData)b.getData();
data.to.isRecieving = false; data.to.isRecieving = false;
for(int i = 0; i < data.items.length; i++){ for(int i = 0; i < data.items.length; i++){
@@ -1,11 +1,11 @@
package io.anuke.mindustry.entities.bullet; package io.anuke.mindustry.entities.bullet;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.util.Time;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.graphics.Pal;
public class MissileBulletType extends BasicBulletType{ public class MissileBulletType extends BasicBulletType{
protected Color trailColor = Pal.missileYellowBack; protected Color trailColor = Pal.missileYellowBack;
@@ -1,12 +1,12 @@
package io.anuke.mindustry.entities.effect; package io.anuke.mindustry.entities.effect;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait;
import io.anuke.mindustry.entities.traits.DrawTrait;
import static io.anuke.mindustry.Vars.groundEffectGroup; import static io.anuke.mindustry.Vars.groundEffectGroup;
@@ -3,9 +3,6 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.IntMap; import io.anuke.arc.collection.IntMap;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2; import io.anuke.arc.math.geom.Point2;
@@ -13,22 +10,17 @@ import io.anuke.arc.util.Structs;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pool.Poolable; import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Bullets; import io.anuke.mindustry.content.*;
import io.anuke.mindustry.content.StatusEffects; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.Damage;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.traits.SaveTrait; import io.anuke.mindustry.entities.traits.SaveTrait;
import io.anuke.mindustry.entities.traits.SyncTrait; import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -42,10 +34,11 @@ public class Fire extends TimedEntity implements SaveTrait, SyncTrait, Poolable{
private float baseFlammability = -1, puddleFlammability; private float baseFlammability = -1, puddleFlammability;
private float lifetime; private float lifetime;
/**Deserialization use only!*/ /** Deserialization use only! */
public Fire(){} public Fire(){
}
/**Start a fire on the tile. If there already is a file there, refreshes its lifetime.*/ /** Start a fire on the tile. If there already is a file there, refreshes its lifetime. */
public static void create(Tile tile){ public static void create(Tile tile){
if(Net.client() || tile == null) return; //not clientside. if(Net.client() || tile == null) return; //not clientside.
@@ -1,12 +1,12 @@
package io.anuke.mindustry.entities.effect; package io.anuke.mindustry.entities.effect;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.entities.Effects; import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect; import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.mindustry.entities.Effects.EffectRenderer; import io.anuke.mindustry.entities.Effects.EffectRenderer;
import io.anuke.mindustry.entities.impl.EffectEntity; import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
/** /**
@@ -17,7 +17,7 @@ public class GroundEffectEntity extends EffectEntity{
@Override @Override
public void update(){ public void update(){
GroundEffect effect = (GroundEffect) this.effect; GroundEffect effect = (GroundEffect)this.effect;
if(effect.isStatic){ if(effect.isStatic){
time += Time.delta(); time += Time.delta();
@@ -41,7 +41,7 @@ public class GroundEffectEntity extends EffectEntity{
@Override @Override
public void draw(){ public void draw(){
GroundEffect effect = (GroundEffect) this.effect; GroundEffect effect = (GroundEffect)this.effect;
if(once && effect.isStatic) if(once && effect.isStatic)
Effects.renderEffect(id, effect, color, lifetime(), rotation, x, y, data); Effects.renderEffect(id, effect, color, lifetime(), rotation, x, y, data);
@@ -2,18 +2,16 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.mindustry.entities.EntityGroup; import io.anuke.arc.graphics.g2d.*;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.math.Interpolation; import io.anuke.arc.math.Interpolation;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Position; import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.Vector2; import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.type.Unit; import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.Item;
@@ -4,27 +4,18 @@ import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntSet; import io.anuke.arc.collection.IntSet;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.traits.TimeTrait;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Angles; import io.anuke.arc.math.*;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.RandomXS128;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Bullets; import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.entities.type.Unit; import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.Units; import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.bullet.Bullet; import io.anuke.mindustry.entities.bullet.Bullet;
import io.anuke.mindustry.entities.traits.SyncTrait; import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
@@ -48,16 +39,16 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
private Array<Position> lines = new Array<>(); private Array<Position> lines = new Array<>();
private Color color = Pal.lancerLaser; private Color color = Pal.lancerLaser;
/**For pooling use only. Do not call directly!*/ /** For pooling use only. Do not call directly! */
public Lightning(){ public Lightning(){
} }
/**Create a lighting branch at a location. Use Team.none to damage everyone.*/ /** Create a lighting branch at a location. Use Team.none to damage everyone. */
public static void create(Team team, Color color, float damage, float x, float y, float targetAngle, int length){ public static void create(Team team, Color color, float damage, float x, float y, float targetAngle, int length){
Call.createLighting(lastSeed++, team, color, damage, x, y, targetAngle, length); Call.createLighting(lastSeed++, team, color, damage, x, y, targetAngle, length);
} }
/**Do not invoke!*/ /** Do not invoke! */
@Remote(called = Loc.server) @Remote(called = Loc.server)
public static void createLighting(int seed, Team team, Color color, float damage, float x, float y, float rotation, int length){ public static void createLighting(int seed, Team team, Color color, float damage, float x, float y, float rotation, int length){
@@ -72,7 +63,7 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
random.setSeed(seed); random.setSeed(seed);
hit.clear(); hit.clear();
for (int i = 0; i < length/2; i++) { for(int i = 0; i < length / 2; i++){
Bullet.create(Bullets.damageLightning, l, team, x, y, 0f, 1f, 1f, dmg); Bullet.create(Bullets.damageLightning, l, team, x, y, 0f, 1f, 1f, dmg);
l.lines.add(new Vector2(x + Mathf.range(3f), y + Mathf.range(3f))); l.lines.add(new Vector2(x + Mathf.range(3f), y + Mathf.range(3f)));
@@ -94,8 +85,8 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
y = furthest.y; y = furthest.y;
}else{ }else{
rotation += random.range(20f); rotation += random.range(20f);
x += Angles.trnsx(rotation, hitRange/2f); x += Angles.trnsx(rotation, hitRange / 2f);
y += Angles.trnsy(rotation, hitRange/2f); y += Angles.trnsy(rotation, hitRange / 2f);
} }
} }
} }
@@ -106,10 +97,12 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
} }
@Override @Override
public void write(DataOutput data){} public void write(DataOutput data){
}
@Override @Override
public void read(DataInput data){} public void read(DataInput data){
}
@Override @Override
public float lifetime(){ public float lifetime(){
@@ -144,7 +137,7 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
int i = 0; int i = 0;
for(Position p : lines){ for(Position p : lines){
Fill.square(p.getX(), p.getY(), (5f - (float)i++/lines.size*2f) * fout(), 45); Fill.square(p.getX(), p.getY(), (5f - (float)i++ / lines.size * 2f) * fout(), 45);
} }
Draw.reset(); Draw.reset();
} }
@@ -3,36 +3,25 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc; import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote; import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.IntMap; import io.anuke.arc.collection.IntMap;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.SolidEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill; import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.math.Angles; import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.util.Time; import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pool.Poolable; import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools; import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Liquids; import io.anuke.mindustry.content.*;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.content.Bullets; import io.anuke.mindustry.entities.impl.SolidEntity;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.traits.SaveTrait;
import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Liquid; import io.anuke.mindustry.type.Liquid;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
@@ -55,21 +44,21 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
private float accepting; private float accepting;
private byte generation; private byte generation;
/**Deserialization use only!*/ /** Deserialization use only! */
public Puddle(){ public Puddle(){
} }
/**Deposists a puddle between tile and source.*/ /** Deposists a puddle between tile and source. */
public static void deposit(Tile tile, Tile source, Liquid liquid, float amount){ public static void deposit(Tile tile, Tile source, Liquid liquid, float amount){
deposit(tile, source, liquid, amount, 0); deposit(tile, source, liquid, amount, 0);
} }
/**Deposists a puddle at a tile.*/ /** Deposists a puddle at a tile. */
public static void deposit(Tile tile, Liquid liquid, float amount){ public static void deposit(Tile tile, Liquid liquid, float amount){
deposit(tile, tile, liquid, amount, 0); deposit(tile, tile, liquid, amount, 0);
} }
/**Returns the puddle on the specified tile. May return null.*/ /** Returns the puddle on the specified tile. May return null. */
public static Puddle getPuddle(Tile tile){ public static Puddle getPuddle(Tile tile){
return map.get(tile.pos()); return map.get(tile.pos());
} }
@@ -99,7 +88,7 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
puddle.tile = tile; puddle.tile = tile;
puddle.liquid = liquid; puddle.liquid = liquid;
puddle.amount = amount; puddle.amount = amount;
puddle.generation = (byte) generation; puddle.generation = (byte)generation;
puddle.set((tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f); puddle.set((tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
puddle.add(); puddle.add();
map.put(tile.pos(), puddle); map.put(tile.pos(), puddle);
@@ -123,7 +112,7 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
return liquid == Liquids.oil && other == Liquids.water; return liquid == Liquids.oil && other == Liquids.water;
} }
/**Reacts two liquids together at a location.*/ /** Reacts two liquids together at a location. */
private static float reactPuddle(Liquid dest, Liquid liquid, float amount, Tile tile, float x, float y){ private static float reactPuddle(Liquid dest, Liquid liquid, float amount, Tile tile, float x, float y){
if((dest.flammability > 0.3f && liquid.temperature > 0.7f) || if((dest.flammability > 0.3f && liquid.temperature > 0.7f) ||
(liquid.flammability > 0.3f && dest.temperature > 0.7f)){ //flammable liquid + hot liquid (liquid.flammability > 0.3f && dest.temperature > 0.7f)){ //flammable liquid + hot liquid
@@ -295,7 +284,7 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
data.writeFloat(x); data.writeFloat(x);
data.writeFloat(y); data.writeFloat(y);
data.writeByte(liquid.id); data.writeByte(liquid.id);
data.writeShort((short) (amount * 4)); data.writeShort((short)(amount * 4));
data.writeInt(tile.pos()); data.writeInt(tile.pos());
} }
@@ -11,7 +11,7 @@ public class RubbleDecal extends Decal{
private static final TextureRegion[][] regions = new TextureRegion[16][0]; private static final TextureRegion[][] regions = new TextureRegion[16][0];
private TextureRegion region; private TextureRegion region;
/**Creates a rubble effect at a position. Provide a block size to use.*/ /** Creates a rubble effect at a position. Provide a block size to use. */
public static void create(float x, float y, int size){ public static void create(float x, float y, int size){
if(headless) return; if(headless) return;
@@ -40,10 +40,10 @@ public class ScorchDecal extends Decal{
float space = 1.5f + Mathf.randomSeed(id + i + 1, 0, 20) / 10f; float space = 1.5f + Mathf.randomSeed(id + i + 1, 0, 20) / 10f;
Draw.rect(region, Draw.rect(region,
x + Angles.trnsx(rotation, space), x + Angles.trnsx(rotation, space),
y + Angles.trnsy(rotation, space) + region.getHeight()/2f*Draw.scl, y + Angles.trnsy(rotation, space) + region.getHeight() / 2f * Draw.scl,
region.getWidth() * Draw.scl, region.getWidth() * Draw.scl,
region.getHeight() * Draw.scl, region.getHeight() * Draw.scl,
region.getWidth()/2f*Draw.scl, 0, rotation - 90); region.getWidth() / 2f * Draw.scl, 0, rotation - 90);
} }
} }
} }
@@ -1,9 +1,7 @@
package io.anuke.mindustry.entities.impl; package io.anuke.mindustry.entities.impl;
import io.anuke.mindustry.entities.traits.DamageTrait; import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.traits.HealthTrait;
import io.anuke.mindustry.entities.traits.SolidTrait;
public abstract class DestructibleEntity extends SolidEntity implements HealthTrait{ public abstract class DestructibleEntity extends SolidEntity implements HealthTrait{
public transient boolean dead; public transient boolean dead;
@@ -18,7 +16,7 @@ public abstract class DestructibleEntity extends SolidEntity implements HealthTr
public void collision(SolidTrait other, float x, float y){ public void collision(SolidTrait other, float x, float y){
if(other instanceof DamageTrait){ if(other instanceof DamageTrait){
onHit(other); onHit(other);
damage(((DamageTrait) other).damage()); damage(((DamageTrait)other).damage());
} }
} }
@@ -5,9 +5,7 @@ import io.anuke.arc.Events;
import io.anuke.arc.collection.Array; import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.Queue; import io.anuke.arc.collection.Queue;
import io.anuke.arc.graphics.Color; import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw; import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.math.Angles; import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Vector2; import io.anuke.arc.math.geom.Vector2;
@@ -16,29 +14,23 @@ import io.anuke.mindustry.Vars;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.content.Fx; import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects; import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.EventType.BuildSelectEvent; import io.anuke.mindustry.game.EventType.BuildSelectEvent;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.graphics.Shapes; import io.anuke.mindustry.graphics.Shapes;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.Item;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.Build;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.BuildBlock; import io.anuke.mindustry.world.blocks.BuildBlock;
import io.anuke.mindustry.world.blocks.BuildBlock.BuildEntity; import io.anuke.mindustry.world.blocks.BuildBlock.BuildEntity;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.*; import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.removal;
import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.tmptr;
/** /**
* Interface for units that build, break or mine things. * Interface for units that build, break or mine things.
@@ -54,25 +46,25 @@ public interface BuilderTrait extends Entity, TeamTrait{
static Vector2[] tmptr = new Vector2[]{new Vector2(), new Vector2(), new Vector2(), new Vector2()}; static Vector2[] tmptr = new Vector2[]{new Vector2(), new Vector2(), new Vector2(), new Vector2()};
} }
/**Returns the queue for storing build requests.*/ /** Returns the queue for storing build requests. */
Queue<BuildRequest> getPlaceQueue(); Queue<BuildRequest> getPlaceQueue();
/**Returns the tile this builder is currently mining.*/ /** Returns the tile this builder is currently mining. */
Tile getMineTile(); Tile getMineTile();
/**Sets the tile this builder is currently mining.*/ /** Sets the tile this builder is currently mining. */
void setMineTile(Tile tile); void setMineTile(Tile tile);
/**Returns the minining speed of this miner. 1 = standard, 0.5 = half speed, 2 = double speed, etc.*/ /** Returns the minining speed of this miner. 1 = standard, 0.5 = half speed, 2 = double speed, etc. */
float getMinePower(); float getMinePower();
/**Build power, can be any float. 1 = builds recipes in normal time, 0 = doesn't build at all.*/ /** Build power, can be any float. 1 = builds recipes in normal time, 0 = doesn't build at all. */
float getBuildPower(Tile tile); float getBuildPower(Tile tile);
/**Returns whether or not this builder can mine a specific item type.*/ /** Returns whether or not this builder can mine a specific item type. */
boolean canMine(Item item); boolean canMine(Item item);
/**Whether this type of builder can begin creating new blocks.*/ /** Whether this type of builder can begin creating new blocks. */
default boolean canCreateBlocks(){ default boolean canCreateBlocks(){
return true; return true;
} }
@@ -124,17 +116,17 @@ public interface BuilderTrait extends Entity, TeamTrait{
} }
} }
/**Return whether this builder's place queue contains items.*/ /** Return whether this builder's place queue contains items. */
default boolean isBuilding(){ default boolean isBuilding(){
return getPlaceQueue().size != 0; return getPlaceQueue().size != 0;
} }
/**Clears the placement queue.*/ /** Clears the placement queue. */
default void clearBuilding(){ default void clearBuilding(){
getPlaceQueue().clear(); getPlaceQueue().clear();
} }
/**Add another build requests to the tail of the queue, if it doesn't exist there yet.*/ /** Add another build requests to the tail of the queue, if it doesn't exist there yet. */
default void addBuildRequest(BuildRequest place){ default void addBuildRequest(BuildRequest place){
for(BuildRequest request : getPlaceQueue()){ for(BuildRequest request : getPlaceQueue()){
if(request.x == place.x && request.y == place.y){ if(request.x == place.x && request.y == place.y){
@@ -249,7 +241,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
} }
} }
/**Do not call directly.*/ /** Do not call directly. */
default void updateMining(){ default void updateMining(){
Unit unit = (Unit)this; Unit unit = (Unit)this;
Tile tile = getMineTile(); Tile tile = getMineTile();
@@ -284,7 +276,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
} }
} }
/**Draw placement effects for an entity. This includes mining*/ /** Draw placement effects for an entity. This includes mining */
default void drawBuilding(){ default void drawBuilding(){
Unit unit = (Unit)this; Unit unit = (Unit)this;
BuildRequest request; BuildRequest request;
@@ -332,7 +324,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Draw.color(); Draw.color();
} }
/**Internal use only.*/ /** Internal use only. */
default void drawMining(){ default void drawMining(){
Unit unit = (Unit)this; Unit unit = (Unit)this;
Tile tile = getMineTile(); Tile tile = getMineTile();
@@ -353,7 +345,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Shapes.laser("minelaser", "minelaser-end", px, py, ex, ey, 0.75f); Shapes.laser("minelaser", "minelaser-end", px, py, ex, ey, 0.75f);
if(unit instanceof Player && ((Player) unit).isLocal){ if(unit instanceof Player && ((Player)unit).isLocal){
Lines.stroke(1f, Pal.accent); Lines.stroke(1f, Pal.accent);
Lines.poly(tile.worldx(), tile.worldy(), 4, tilesize / 2f * Mathf.sqrt2, Time.time()); Lines.poly(tile.worldx(), tile.worldy(), 4, tilesize / 2f * Mathf.sqrt2, Time.time());
} }
@@ -361,7 +353,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Draw.color(); Draw.color();
} }
/**Class for storing build requests. Can be either a place or remove request.*/ /** Class for storing build requests. Can be either a place or remove request. */
class BuildRequest{ class BuildRequest{
public final int x, y, rotation; public final int x, y, rotation;
public final Block block; public final Block block;
@@ -370,7 +362,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
public float progress; public float progress;
public boolean initialized; public boolean initialized;
/**This creates a build request.*/ /** This creates a build request. */
public BuildRequest(int x, int y, int rotation, Block block){ public BuildRequest(int x, int y, int rotation, Block block){
this.x = x; this.x = x;
this.y = y; this.y = y;
@@ -379,7 +371,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
this.breaking = false; this.breaking = false;
} }
/**This creates a remove request.*/ /** This creates a remove request. */
public BuildRequest(int x, int y){ public BuildRequest(int x, int y){
this.x = x; this.x = x;
this.y = y; this.y = y;
@@ -1,8 +1,6 @@
package io.anuke.mindustry.entities.traits; package io.anuke.mindustry.entities.traits;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
public interface Saveable{ public interface Saveable{
void writeSave(DataOutput stream) throws IOException; void writeSave(DataOutput stream) throws IOException;
@@ -1,11 +1,9 @@
package io.anuke.mindustry.entities.traits; package io.anuke.mindustry.entities.traits;
import io.anuke.mindustry.entities.EntityQuery; import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.QuadTree.QuadTreeObject; import io.anuke.arc.math.geom.QuadTree.QuadTreeObject;
import io.anuke.arc.math.geom.Rectangle; import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.arc.math.geom.Vector2;
public interface SolidTrait extends QuadTreeObject, MoveTrait, VelocityTrait, Entity, Position{ public interface SolidTrait extends QuadTreeObject, MoveTrait, VelocityTrait, Entity, Position{
@@ -35,7 +33,8 @@ public interface SolidTrait extends QuadTreeObject, MoveTrait, VelocityTrait, En
return true; return true;
} }
default void collision(SolidTrait other, float x, float y){} default void collision(SolidTrait other, float x, float y){
}
default void move(float x, float y){ default void move(float x, float y){
EntityQuery.collisions().move(this, x, y); EntityQuery.collisions().move(this, x, y);
@@ -1,17 +1,15 @@
package io.anuke.mindustry.entities.traits; package io.anuke.mindustry.entities.traits;
import io.anuke.mindustry.core.NetClient;
import io.anuke.mindustry.net.Interpolator;
import io.anuke.arc.Core; import io.anuke.arc.Core;
import io.anuke.arc.util.Tmp; import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.core.NetClient;
import io.anuke.mindustry.net.Interpolator;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
public interface SyncTrait extends Entity, TypeTrait{ public interface SyncTrait extends Entity, TypeTrait{
/**Sets the position of this entity and updated the interpolator.*/ /** Sets the position of this entity and updated the interpolator. */
default void setNet(float x, float y){ default void setNet(float x, float y){
set(x, y); set(x, y);
@@ -24,7 +22,7 @@ public interface SyncTrait extends Entity, TypeTrait{
} }
} }
/**Interpolate entity position only. Override if you need to interpolate rotations or other values.*/ /** Interpolate entity position only. Override if you need to interpolate rotations or other values. */
default void interpolate(){ default void interpolate(){
if(getInterpolator() == null){ if(getInterpolator() == null){
throw new RuntimeException("This entity must have an interpolator to interpolate()!"); throw new RuntimeException("This entity must have an interpolator to interpolate()!");
@@ -47,17 +45,17 @@ public interface SyncTrait extends Entity, TypeTrait{
setY(getInterpolator().pos.y); setY(getInterpolator().pos.y);
} }
/**Return the interpolator used for smoothing the position. Optional.*/ /** Return the interpolator used for smoothing the position. Optional. */
default Interpolator getInterpolator(){ default Interpolator getInterpolator(){
return null; return null;
} }
/**Whether syncing is enabled for this entity; true by default.*/ /** Whether syncing is enabled for this entity; true by default. */
default boolean isSyncing(){ default boolean isSyncing(){
return true; return true;
} }
/**Whether this entity is clipped and not synced when out of viewport.*/ /** Whether this entity is clipped and not synced when out of viewport. */
default boolean isClipped(){ default boolean isClipped(){
return true; return true;
} }
@@ -14,14 +14,14 @@ public interface TargetTrait extends Position, VelocityTrait{
default float getTargetVelocityX(){ default float getTargetVelocityX(){
if(this instanceof SolidTrait){ if(this instanceof SolidTrait){
return ((SolidTrait) this).getDeltaX(); return ((SolidTrait)this).getDeltaX();
} }
return velocity().x; return velocity().x;
} }
default float getTargetVelocityY(){ default float getTargetVelocityY(){
if(this instanceof SolidTrait){ if(this instanceof SolidTrait){
return ((SolidTrait) this).getDeltaY(); return ((SolidTrait)this).getDeltaY();
} }
return velocity().y; return velocity().y;
} }
@@ -28,7 +28,7 @@ public interface VelocityTrait extends MoveTrait{
velocity().scl(1f - drag() * Time.delta()); velocity().scl(1f - drag() * Time.delta());
if(this instanceof SolidTrait){ if(this instanceof SolidTrait){
((SolidTrait) this).move(velocity().x * Time.delta(), velocity().y * Time.delta()); ((SolidTrait)this).move(velocity().x * Time.delta(), velocity().y * Time.delta());
}else{ }else{
moveBy(velocity().x * Time.delta(), velocity().y * Time.delta()); moveBy(velocity().x * Time.delta(), velocity().y * Time.delta());
} }
@@ -29,7 +29,7 @@ import java.io.*;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
/**Base class for AI units.*/ /** Base class for AI units. */
public abstract class BaseUnit extends Unit implements ShooterTrait{ public abstract class BaseUnit extends Unit implements ShooterTrait{
protected static int timerIndex = 0; protected static int timerIndex = 0;
@@ -45,7 +45,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
protected int spawner = noSpawner; protected int spawner = noSpawner;
/**internal constructor used for deserialization, DO NOT USE*/ /** internal constructor used for deserialization, DO NOT USE */
public BaseUnit(){ public BaseUnit(){
} }
@@ -78,7 +78,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
return type.drag; return type.drag;
} }
/**Initialize the type and team of this unit. Only call once!*/ /** Initialize the type and team of this unit. Only call once! */
public void init(UnitType type, Team team){ public void init(UnitType type, Team team){
if(this.type != null) throw new RuntimeException("This unit is already initialized!"); if(this.type != null) throw new RuntimeException("This unit is already initialized!");
@@ -99,7 +99,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
} }
public boolean targetHasFlag(BlockFlag flag){ public boolean targetHasFlag(BlockFlag flag){
return target instanceof TileEntity && ((TileEntity) target).tile.block().flags.contains(flag); return target instanceof TileEntity && ((TileEntity)target).tile.block().flags.contains(flag);
} }
public void setState(UnitState state){ public void setState(UnitState state){
@@ -112,14 +112,14 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
} }
} }
/**Only runs when the unit has a target.*/ /** Only runs when the unit has a target. */
public void behavior(){ public void behavior(){
} }
public void updateTargeting(){ public void updateTargeting(){
if(target == null || (target instanceof Unit && (target.isDead() || target.getTeam() == team)) if(target == null || (target instanceof Unit && (target.isDead() || target.getTeam() == team))
|| (target instanceof TileEntity && ((TileEntity) target).tile.entity == null)){ || (target instanceof TileEntity && ((TileEntity)target).tile.entity == null)){
target = null; target = null;
} }
} }
@@ -127,11 +127,11 @@ public abstract class FlyingUnit extends BaseUnit{
public void drawEngine(){ public void drawEngine(){
Draw.color(Pal.engine); Draw.color(Pal.engine);
Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset), y + Angles.trnsy(rotation + 180, type.engineOffset), Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset), y + Angles.trnsy(rotation + 180, type.engineOffset),
type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize/4f)); type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize / 4f));
Draw.color(Color.WHITE); Draw.color(Color.WHITE);
Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset-1f), y + Angles.trnsy(rotation + 180, type.engineOffset-1f), Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset - 1f), y + Angles.trnsy(rotation + 180, type.engineOffset - 1f),
(type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize/4f)) / 2f); (type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize / 4f)) / 2f);
Draw.color(); Draw.color();
} }
@@ -141,7 +141,7 @@ public abstract class FlyingUnit extends BaseUnit{
if(Units.invalidateTarget(target, this)){ if(Units.invalidateTarget(target, this)){
for(boolean left : Mathf.booleans){ for(boolean left : Mathf.booleans){
int wi = Mathf.num(left); int wi = Mathf.num(left);
weaponAngles[wi] = Mathf.slerpDelta(weaponAngles[wi],rotation, 0.1f); weaponAngles[wi] = Mathf.slerpDelta(weaponAngles[wi], rotation, 0.1f);
} }
} }
} }
@@ -154,8 +154,8 @@ public abstract class FlyingUnit extends BaseUnit{
protected void wobble(){ protected void wobble(){
if(Net.client()) return; if(Net.client()) return;
x += Mathf.sin(Time.time() + id * 999, 25f, 0.05f)*Time.delta(); x += Mathf.sin(Time.time() + id * 999, 25f, 0.05f) * Time.delta();
y += Mathf.cos(Time.time() + id * 999, 25f, 0.05f)*Time.delta(); y += Mathf.cos(Time.time() + id * 999, 25f, 0.05f) * Time.delta();
if(velocity.len() <= 0.05f){ if(velocity.len() <= 0.05f){
//rotation += Mathf.sin(Time.time() + id * 99, 10f, 2f * type.speed)*Time.delta(); //rotation += Mathf.sin(Time.time() + id * 99, 10f, 2f * type.speed)*Time.delta();
@@ -111,7 +111,7 @@ public abstract class GroundUnit extends BaseUnit{
public void draw(){ public void draw(){
Draw.mixcol(Color.WHITE, hitTime / hitDuration); Draw.mixcol(Color.WHITE, hitTime / hitDuration);
float ft = Mathf.sin(walkTime * type.speed*5f, 6f, 2f + type.hitsize/15f); float ft = Mathf.sin(walkTime * type.speed * 5f, 6f, 2f + type.hitsize / 15f);
Floor floor = getFloorOn(); Floor floor = getFloorOn();
@@ -138,7 +138,7 @@ public abstract class GroundUnit extends BaseUnit{
for(int i : Mathf.signs){ for(int i : Mathf.signs){
float tra = rotation - 90, trY = -type.weapon.getRecoil(this, i > 0) + type.weaponOffsetY; float tra = rotation - 90, trY = -type.weapon.getRecoil(this, i > 0) + type.weaponOffsetY;
float w = - i * type.weapon.region.getWidth() * Draw.scl; float w = -i * type.weapon.region.getWidth() * Draw.scl;
Draw.rect(type.weapon.region, Draw.rect(type.weapon.region,
x + Angles.trnsx(tra, getWeapon().width * i, trY), x + Angles.trnsx(tra, getWeapon().width * i, trY),
y + Angles.trnsy(tra, getWeapon().width * i, trY), w, type.weapon.region.getHeight() * Draw.scl, rotation - 90); y + Angles.trnsy(tra, getWeapon().width * i, trY), w, type.weapon.region.getHeight() * Draw.scl, rotation - 90);
@@ -211,7 +211,7 @@ public abstract class GroundUnit extends BaseUnit{
if(tile == targetTile) return; if(tile == targetTile) return;
velocity.add(vec.trns(angleTo(targetTile), type.speed*Time.delta())); velocity.add(vec.trns(angleTo(targetTile), type.speed * Time.delta()));
if(Units.invalidateTarget(target, this)){ if(Units.invalidateTarget(target, this)){
rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed); rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed);
} }
@@ -235,7 +235,7 @@ public abstract class GroundUnit extends BaseUnit{
if(tile == targetTile || core == null || dst(core) < 90f) return; if(tile == targetTile || core == null || dst(core) < 90f) return;
velocity.add(vec.trns(angleTo(targetTile), type.speed*Time.delta())); velocity.add(vec.trns(angleTo(targetTile), type.speed * Time.delta()));
rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed); rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed);
} }
} }
@@ -365,11 +365,11 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
float size = mech.engineSize * (mech.flying ? 1f : boostHeat); float size = mech.engineSize * (mech.flying ? 1f : boostHeat);
Draw.color(mech.engineColor); Draw.color(mech.engineColor);
Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset), y + Angles.trnsy(rotation + 180, mech.engineOffset), Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset), y + Angles.trnsy(rotation + 180, mech.engineOffset),
size + Mathf.absin(Time.time(), 2f, size/4f)); size + Mathf.absin(Time.time(), 2f, size / 4f));
Draw.color(Color.WHITE); Draw.color(Color.WHITE);
Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset-1f), y + Angles.trnsy(rotation + 180, mech.engineOffset-1f), Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset - 1f), y + Angles.trnsy(rotation + 180, mech.engineOffset - 1f),
(size + Mathf.absin(Time.time(), 2f, size/4f)) / 2f); (size + Mathf.absin(Time.time(), 2f, size / 4f)) / 2f);
Draw.color(); Draw.color();
} }
@@ -450,8 +450,9 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
Draw.color(Pal.accent); Draw.color(Pal.accent);
for(int i = 0; i < 4; i++){ for(int i = 0; i < 4; i++){
Point2 p = Geometry.d8edge[i]; Point2 p = Geometry.d8edge[i];
float offset = -Math.max(request.block.size-1, 0)/2f * tilesize; float offset = -Math.max(request.block.size - 1, 0) / 2f * tilesize;
if(i % 2 == 0) Draw.rect("block-select", request.x * tilesize + request.block.offset() + offset * p.x, request.y * tilesize + request.block.offset() + offset * p.y, i * 90); if(i % 2 == 0)
Draw.rect("block-select", request.x * tilesize + request.block.offset() + offset * p.x, request.y * tilesize + request.block.offset() + offset * p.y, i * 90);
} }
Draw.color(); Draw.color();
@@ -615,7 +616,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
} }
protected void updateFlying(){ protected void updateFlying(){
if(Units.invalidateTarget(target, this) && !(target instanceof TileEntity && ((TileEntity) target).damaged() && target.getTeam() == team && if(Units.invalidateTarget(target, this) && !(target instanceof TileEntity && ((TileEntity)target).damaged() && target.getTeam() == team &&
mech.canHeal && dst(target) < getWeapon().bullet.range())){ mech.canHeal && dst(target) < getWeapon().bullet.range())){
target = null; target = null;
} }
@@ -635,7 +636,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
if(dst(moveTarget) < 2f){ if(dst(moveTarget) < 2f){
if(tapping){ if(tapping){
Tile tile = ((TileEntity) moveTarget).tile; Tile tile = ((TileEntity)moveTarget).tile;
tile.block().tapped(tile, this); tile.block().tapped(tile, this);
} }
@@ -695,7 +696,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
if(target != null && dst(target) > getWeapon().bullet.range()){ if(target != null && dst(target) > getWeapon().bullet.range()){
target = null; target = null;
}else if(target != null){ }else if(target != null){
target = ((Tile) target).entity; target = ((Tile)target).entity;
} }
} }
@@ -703,7 +704,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
setMineTile(null); setMineTile(null);
} }
} }
}else if(target.isValid() || (target instanceof TileEntity && ((TileEntity) target).damaged() && target.getTeam() == team && }else if(target.isValid() || (target instanceof TileEntity && ((TileEntity)target).damaged() && target.getTeam() == team &&
mech.canHeal && dst(target) < getWeapon().bullet.range())){ mech.canHeal && dst(target) < getWeapon().bullet.range())){
//rotate toward and shoot the target //rotate toward and shoot the target
if(mech.turnCursor){ if(mech.turnCursor){
@@ -840,7 +841,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
buffer.writeByte(mech.id); buffer.writeByte(mech.id);
buffer.writeInt(mining == null ? noSpawner : mining.pos()); buffer.writeInt(mining == null ? noSpawner : mining.pos());
buffer.writeInt(spawner == null ? noSpawner : spawner.getTile().pos()); buffer.writeInt(spawner == null ? noSpawner : spawner.getTile().pos());
buffer.writeShort((short) (baseRotation * 2)); buffer.writeShort((short)(baseRotation * 2));
writeBuilding(buffer); writeBuilding(buffer);
} }
@@ -20,18 +20,11 @@ import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.game.EventType.BlockDestroyEvent; import io.anuke.mindustry.game.EventType.BlockDestroyEvent;
import io.anuke.mindustry.game.Team; import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.world.Block; import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.Edges;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.defense.Wall; import io.anuke.mindustry.world.blocks.defense.Wall;
import io.anuke.mindustry.world.modules.ConsumeModule; import io.anuke.mindustry.world.modules.*;
import io.anuke.mindustry.world.modules.ItemModule;
import io.anuke.mindustry.world.modules.LiquidModule;
import io.anuke.mindustry.world.modules.PowerModule;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.tileGroup; import static io.anuke.mindustry.Vars.tileGroup;
import static io.anuke.mindustry.Vars.world; import static io.anuke.mindustry.Vars.world;
@@ -39,7 +32,7 @@ import static io.anuke.mindustry.Vars.world;
public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
public static final float timeToSleep = 60f * 4; //4 seconds to fall asleep public static final float timeToSleep = 60f * 4; //4 seconds to fall asleep
private static final ObjectSet<Tile> tmpTiles = new ObjectSet<>(); private static final ObjectSet<Tile> tmpTiles = new ObjectSet<>();
/**This value is only used for debugging.*/ /** This value is only used for debugging. */
public static int sleepingEntities = 0; public static int sleepingEntities = 0;
public Tile tile; public Tile tile;
@@ -53,7 +46,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
public LiquidModule liquids; public LiquidModule liquids;
public ConsumeModule cons; public ConsumeModule cons;
/**List of (cached) tiles with entities in proximity, used for outputting to*/ /** List of (cached) tiles with entities in proximity, used for outputting to */
private Array<Tile> proximity = new Array<>(8); private Array<Tile> proximity = new Array<>(8);
private boolean dead = false; private boolean dead = false;
private boolean sleeping; private boolean sleeping;
@@ -76,7 +69,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
tile.entity.onDeath(); tile.entity.onDeath();
} }
/**Sets this tile entity data to this tile, and adds it if necessary.*/ /** Sets this tile entity data to this tile, and adds it if necessary. */
public TileEntity init(Tile tile, boolean shouldAdd){ public TileEntity init(Tile tile, boolean shouldAdd){
this.tile = tile; this.tile = tile;
x = tile.drawx(); x = tile.drawx();
@@ -93,12 +86,12 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
return this; return this;
} }
/**Scaled delta.*/ /** Scaled delta. */
public float delta(){ public float delta(){
return Time.delta() * timeScale; return Time.delta() * timeScale;
} }
/**Call when nothing is happening to the entity. This increments the internal sleep timer.*/ /** Call when nothing is happening to the entity. This increments the internal sleep timer. */
public void sleep(){ public void sleep(){
sleepTime += Time.delta(); sleepTime += Time.delta();
if(!sleeping && sleepTime >= timeToSleep){ if(!sleeping && sleepTime >= timeToSleep){
@@ -108,7 +101,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
} }
} }
/**Call when this entity is updating. This wakes it up.*/ /** Call when this entity is updating. This wakes it up. */
public void noSleep(){ public void noSleep(){
sleepTime = 0f; sleepTime = 0f;
if(sleeping){ if(sleeping){
@@ -126,13 +119,17 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
return dead || tile.entity != this; return dead || tile.entity != this;
} }
public void write(DataOutput stream) throws IOException{} public void write(DataOutput stream) throws IOException{
}
public void writeConfig(DataOutput stream) throws IOException{} public void writeConfig(DataOutput stream) throws IOException{
}
public void read(DataInput stream) throws IOException{} public void read(DataInput stream) throws IOException{
}
public void readConfig(DataInput stream) throws IOException{} public void readConfig(DataInput stream) throws IOException{
}
public boolean collide(Bullet other){ public boolean collide(Bullet other){
return true; return true;
@@ -24,26 +24,21 @@ import io.anuke.mindustry.game.Teams.TeamData;
import io.anuke.mindustry.graphics.Pal; import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.net.Interpolator; import io.anuke.mindustry.net.Interpolator;
import io.anuke.mindustry.net.Net; import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.StatusEffect;
import io.anuke.mindustry.type.Weapon;
import io.anuke.mindustry.world.Pos; import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.Floor; import io.anuke.mindustry.world.blocks.Floor;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.*; import static io.anuke.mindustry.Vars.*;
public abstract class Unit extends DestructibleEntity implements SaveTrait, TargetTrait, SyncTrait, DrawTrait, TeamTrait{ public abstract class Unit extends DestructibleEntity implements SaveTrait, TargetTrait, SyncTrait, DrawTrait, TeamTrait{
/**Total duration of hit flash effect*/ /** Total duration of hit flash effect */
public static final float hitDuration = 9f; public static final float hitDuration = 9f;
/**Percision divisor of velocity, used when writing. For example a value of '2' would mean the percision is 1/2 = 0.5-size chunks.*/ /** Percision divisor of velocity, used when writing. For example a value of '2' would mean the percision is 1/2 = 0.5-size chunks. */
public static final float velocityPercision = 8f; public static final float velocityPercision = 8f;
/**Maximum absolute value of a velocity vector component.*/ /** Maximum absolute value of a velocity vector component. */
public static final float maxAbsVelocity = 127f / velocityPercision; public static final float maxAbsVelocity = 127f / velocityPercision;
public static final int noSpawner = Pos.get(-1, 1); public static final int noSpawner = Pos.get(-1, 1);
@@ -106,9 +101,9 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
if(isDead()) return false; if(isDead()) return false;
if(other instanceof DamageTrait){ if(other instanceof DamageTrait){
return other instanceof TeamTrait && state.teams.areEnemies((((TeamTrait) other).getTeam()), team); return other instanceof TeamTrait && state.teams.areEnemies((((TeamTrait)other).getTeam()), team);
}else{ }else{
return other instanceof Unit && ((Unit) other).isFlying() == isFlying(); return other instanceof Unit && ((Unit)other).isFlying() == isFlying();
} }
} }
@@ -198,10 +193,10 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
stream.writeBoolean(isDead()); stream.writeBoolean(isDead());
stream.writeFloat(net ? interpolator.target.x : x); stream.writeFloat(net ? interpolator.target.x : x);
stream.writeFloat(net ? interpolator.target.y : y); stream.writeFloat(net ? interpolator.target.y : y);
stream.writeByte((byte) (Mathf.clamp(velocity.x, -maxAbsVelocity, maxAbsVelocity) * velocityPercision)); stream.writeByte((byte)(Mathf.clamp(velocity.x, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeByte((byte) (Mathf.clamp(velocity.y, -maxAbsVelocity, maxAbsVelocity) * velocityPercision)); stream.writeByte((byte)(Mathf.clamp(velocity.y, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeShort((short) (rotation * 2)); stream.writeShort((short)(rotation * 2));
stream.writeShort((short) health); stream.writeShort((short)health);
stream.writeByte(item.item.id); stream.writeByte(item.item.id);
stream.writeShort((short)item.amount); stream.writeShort((short)item.amount);
status.writeSave(stream); status.writeSave(stream);
@@ -258,10 +253,10 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
moveVector.setZero(); moveVector.setZero();
for(int cx = -rad; cx <= rad; cx++){ for(int cx = -rad; cx <= rad; cx++){
for(int cy = -rad; cy <= rad; cy++){ for(int cy = -rad; cy <= rad; cy++){
Tile tile = world.tileWorld(x + cx*tilesize, y + cy*tilesize); Tile tile = world.tileWorld(x + cx * tilesize, y + cy * tilesize);
if(tile == null) continue; if(tile == null) continue;
int weight = flying ? tile.airWeight : tile.weight; int weight = flying ? tile.airWeight : tile.weight;
float scl = (rad - Mathf.dst(tile.worldx(), tile.worldy(), x, y)/(8f * 1.2f * Mathf.sqrt2)) * 0.1f; float scl = (rad - Mathf.dst(tile.worldx(), tile.worldy(), x, y) / (8f * 1.2f * Mathf.sqrt2)) * 0.1f;
moveVector.add(Mathf.sign(x - tile.worldx()) * scaling * weight * scl, Mathf.sign(y - tile.worldy()) * scaling * weight * scl); moveVector.add(Mathf.sign(x - tile.worldx()) * scaling * weight * scl, Mathf.sign(y - tile.worldy()) * scaling * weight * scl);
} }
@@ -301,12 +296,13 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
public Floor getFloorOn(){ public Floor getFloorOn(){
Tile tile = world.tileWorld(x, y); Tile tile = world.tileWorld(x, y);
return tile == null ? (Floor) Blocks.air : tile.floor(); return tile == null ? (Floor)Blocks.air : tile.floor();
} }
public void onRespawn(Tile tile){} public void onRespawn(Tile tile){
}
/**Updates velocity and status effects.*/ /** Updates velocity and status effects. */
public void updateVelocityStatus(){ public void updateVelocityStatus(){
Floor floor = getFloorOn(); Floor floor = getFloorOn();
@@ -314,7 +310,7 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
status.update(this); status.update(this);
velocity.limit(maxVelocity()).scl(1f + (status.getSpeedMultiplier()-1f) * Time.delta()); velocity.limit(maxVelocity()).scl(1f + (status.getSpeedMultiplier() - 1f) * Time.delta());
if(x < -finalWorldBounds || y < -finalWorldBounds || x >= world.width() * tilesize + finalWorldBounds || y >= world.height() * tilesize + finalWorldBounds){ if(x < -finalWorldBounds || y < -finalWorldBounds || x >= world.width() * tilesize + finalWorldBounds || y >= world.height() * tilesize + finalWorldBounds){
kill(); kill();
@@ -420,7 +416,7 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
} }
public void drawStats(){ public void drawStats(){
Draw.color(Color.BLACK, team.color, healthf() + Mathf.absin(Time.time(), healthf()*5f, 1f - healthf())); Draw.color(Color.BLACK, team.color, healthf() + Mathf.absin(Time.time(), healthf() * 5f, 1f - healthf()));
Draw.rect(getPowerCellRegion(), x, y, rotation - 90); Draw.rect(getPowerCellRegion(), x, y, rotation - 90);
Draw.color(); Draw.color();
} }
@@ -2,31 +2,24 @@ package io.anuke.mindustry.entities.type.base;
import io.anuke.arc.Events; import io.anuke.arc.Events;
import io.anuke.arc.collection.Queue; import io.anuke.arc.collection.Queue;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.arc.math.Mathf; import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry; import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.util.Structs; import io.anuke.arc.util.Structs;
import io.anuke.mindustry.content.Blocks; import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.entities.type.Player; import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.Units; import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.traits.BuilderTrait; import io.anuke.mindustry.entities.traits.BuilderTrait;
import io.anuke.mindustry.entities.type.BaseUnit; import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.entities.type.FlyingUnit;
import io.anuke.mindustry.entities.units.UnitState; import io.anuke.mindustry.entities.units.UnitState;
import io.anuke.mindustry.game.EventType.BuildSelectEvent; import io.anuke.mindustry.game.EventType.BuildSelectEvent;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.*;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.ItemType;
import io.anuke.mindustry.world.Tile; import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.BuildBlock; import io.anuke.mindustry.world.blocks.BuildBlock;
import io.anuke.mindustry.world.blocks.BuildBlock.BuildEntity; import io.anuke.mindustry.world.blocks.BuildBlock.BuildEntity;
import io.anuke.mindustry.world.meta.BlockFlag; import io.anuke.mindustry.world.meta.BlockFlag;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.unitGroups; import static io.anuke.mindustry.Vars.unitGroups;
import static io.anuke.mindustry.Vars.world; import static io.anuke.mindustry.Vars.world;
@@ -48,7 +41,7 @@ public class Drone extends FlyingUnit implements BuilderTrait{
} }
public void update(){ public void update(){
BuildEntity entity = (BuildEntity) target; BuildEntity entity = (BuildEntity)target;
TileEntity core = getClosestCore(); TileEntity core = getClosestCore();
if(entity == null){ if(entity == null){
@@ -105,7 +98,7 @@ public class Drone extends FlyingUnit implements BuilderTrait{
if(target == null) return; if(target == null) return;
if(target.dst(Drone.this) > type.range){ if(target.dst(Drone.this) > type.range){
circle(type.range*0.9f); circle(type.range * 0.9f);
}else{ }else{
getWeapon().update(Drone.this, target.getX(), target.getY()); getWeapon().update(Drone.this, target.getX(), target.getY());
} }
@@ -155,10 +148,10 @@ public class Drone extends FlyingUnit implements BuilderTrait{
moveTo(type.range / 1.5f); moveTo(type.range / 1.5f);
if(dst(target) < type.range && mineTile != target){ if(dst(target) < type.range && mineTile != target){
setMineTile((Tile) target); setMineTile((Tile)target);
} }
if(((Tile) target).block() != Blocks.air){ if(((Tile)target).block() != Blocks.air){
setState(drop); setState(drop);
} }
} }
@@ -190,7 +183,7 @@ public class Drone extends FlyingUnit implements BuilderTrait{
if(target == null) return; if(target == null) return;
TileEntity tile = (TileEntity) target; TileEntity tile = (TileEntity)target;
if(dst(target) < type.range){ if(dst(target) < type.range){
if(tile.tile.block().acceptStack(item.item, item.amount, tile.tile, Drone.this) == item.amount){ if(tile.tile.block().acceptStack(item.item, item.amount, tile.tile, Drone.this) == item.amount){
@@ -14,7 +14,7 @@ public class Revenant extends FlyingUnit{
float tra = rotation - 90, trY = -getWeapon().getRecoil(this, i > 0) + type.weaponOffsetY; float tra = rotation - 90, trY = -getWeapon().getRecoil(this, i > 0) + type.weaponOffsetY;
float w = i > 0 ? -12 : 12; float w = i > 0 ? -12 : 12;
float wx = x + Angles.trnsx(tra, getWeapon().width * i, trY), wy = y + Angles.trnsy(tra, getWeapon().width * i, trY); float wx = x + Angles.trnsx(tra, getWeapon().width * i, trY), wy = y + Angles.trnsy(tra, getWeapon().width * i, trY);
int wi = (i + 1)/2; int wi = (i + 1) / 2;
Draw.rect(getWeapon().region, wx, wy, w, 12, weaponAngles[wi] - 90); Draw.rect(getWeapon().region, wx, wy, w, 12, weaponAngles[wi] - 90);
} }
} }
@@ -12,12 +12,11 @@ import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.type.ContentType; import io.anuke.mindustry.type.ContentType;
import io.anuke.mindustry.type.StatusEffect; import io.anuke.mindustry.type.StatusEffect;
import java.io.DataInput; import java.io.*;
import java.io.DataOutput;
import java.io.IOException;
import static io.anuke.mindustry.Vars.content; import static io.anuke.mindustry.Vars.content;
/** Class for controlling status effects on an entity.*/
/** Class for controlling status effects on an entity. */
public class Statuses implements Saveable{ public class Statuses implements Saveable{
private static final StatusEntry globalResult = new StatusEntry(); private static final StatusEntry globalResult = new StatusEntry();
private static final Array<StatusEntry> removals = new Array<>(); private static final Array<StatusEntry> removals = new Array<>();
@@ -1,12 +1,12 @@
package io.anuke.mindustry.entities.units; package io.anuke.mindustry.entities.units;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.Vars; import io.anuke.mindustry.Vars;
import io.anuke.mindustry.content.Items; import io.anuke.mindustry.content.Items;
import io.anuke.mindustry.entities.type.BaseUnit; import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.TileEntity; import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.gen.Call; import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.type.Item; import io.anuke.mindustry.type.Item;
import io.anuke.arc.math.Mathf;
public class UnitDrops{ public class UnitDrops{
private static Item[] dropTable; private static Item[] dropTable;
@@ -37,7 +37,8 @@ public class UnitDrops{
if(Mathf.chance(0.03)){ if(Mathf.chance(0.03)){
int amount = Mathf.random(20, 40); int amount = Mathf.random(20, 40);
amount = core.tile.block().acceptStack(item, amount, core.tile, null); amount = core.tile.block().acceptStack(item, amount, core.tile, null);
if (amount > 0) Call.transferItemTo(item, amount, unit.x + Mathf.range(2f), unit.y + Mathf.range(2f), core.tile); if(amount > 0)
Call.transferItemTo(item, amount, unit.x + Mathf.range(2f), unit.y + Mathf.range(2f), core.tile);
} }
} }
} }
@@ -4,7 +4,7 @@ import io.anuke.mindustry.Vars;
import io.anuke.mindustry.type.ContentType; import io.anuke.mindustry.type.ContentType;
/**Base class for a content type that is loaded in {@link io.anuke.mindustry.core.ContentLoader}.*/ /** Base class for a content type that is loaded in {@link io.anuke.mindustry.core.ContentLoader}. */
public abstract class Content{ public abstract class Content{
public final byte id; public final byte id;
@@ -19,7 +19,7 @@ public abstract class Content{
*/ */
public abstract ContentType getContentType(); public abstract ContentType getContentType();
/**Called after all content is created. Do not use to load regions or texture data!*/ /** Called after all content is created. Do not use to load regions or texture data! */
public void init(){ public void init(){
} }

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