From 1cef7c10f8f1da4c955bcfd2a9375534ebfe6f07 Mon Sep 17 00:00:00 2001 From: jdrueckert Date: Sat, 11 Nov 2023 14:19:09 +0100 Subject: [PATCH] refactor: address IntelliJ QAPlug plugin findings (#5149) * make final fields static * remove unnecessary local before return * remove instanceof checks in catch clause * avoid throwing java.lang.Exception * remove null checks covered by instanceof check * remove toString on String objects * remove overrides that only call their super * remove unused private methods * remove unnecessary if statement nesting * remove unused local variables * use try-with-resources to close resources after use * use equals() to compare object references * fix broken javadoc references * fix disallowed self-closing and empty javadoc elements * fix bad use of symbols in javadoc * fix disallowed list item tag in javadoc without surrounding list * fix erroneous javadoc tags * fix emphasize tags in javadoc * remove illegal throws * remove unused imports Related: Terasology/CoreRendering#75 Terasology/Furnishings#17 Terasology/Health#105 Terasology/Inventory#51 Terasology/Behaviors#114 Terasology/CoreWorlds#45 Terasology/FlexiblePathfinding#32 Adds to #3859 --- .../org/terasology/engine/Environment.java | 16 ++-- .../engine/HeadlessEnvironment.java | 4 +- .../engine/ModuleEnvironmentTest.java | 3 +- .../engine/testUtil/ModuleManagerFactory.java | 2 +- .../engine/audio/formats/OggReader.java | 16 ++-- .../engine/audio/openAL/BaseSoundPool.java | 6 +- .../ui/ColorConstraintWidgetFactory.java | 3 +- .../terasology/engine/core/GameThread.java | 10 +-- .../AbstractEventSystemDecorator.java | 2 +- .../engine/core/modes/StateMainMenu.java | 35 -------- .../core/module/RemoteModuleExtension.java | 2 +- .../core/subsystem/config/BindsManager.java | 5 +- .../core/subsystem/config/BindsSubsystem.java | 2 +- .../entitySystem/entity/EntityBuilder.java | 3 +- .../entitySystem/entity/EntityPool.java | 6 +- .../entity/internal/BaseEntityRef.java | 6 +- .../entity/internal/PojoEntityManager.java | 20 +---- .../event/AbstractValueModifiableEvent.java | 4 +- .../event/internal/EventSystemImpl.java | 4 +- .../prefab/internal/PojoPrefab.java | 2 +- .../engine/i18n/assets/TranslationData.java | 2 +- .../input/cameraTarget/TargetSystem.java | 6 +- .../input/lwjgl/LwjglControllerDevice.java | 3 +- .../engine/input/lwjgl/LwjglMouseDevice.java | 3 +- .../engine/logic/behavior/BehaviorSystem.java | 4 +- .../behavior/CollectiveBehaviorSystem.java | 4 +- .../actions/conditions/GuardAction.java | 4 +- .../engine/logic/behavior/core/Action.java | 2 +- .../engine/logic/behavior/core/Actor.java | 3 +- .../behavior/core/BehaviorTreeBuilder.java | 4 +- .../characters/AliveCharacterComponent.java | 6 +- .../CharacterMovementComponent.java | 2 +- .../logic/characters/CharacterSystem.java | 18 ++-- .../logic/characters/GazeAuthoritySystem.java | 3 +- .../logic/characters/events/OnScaleEvent.java | 2 +- .../engine/logic/chat/ChatSystem.java | 8 +- .../engine/logic/console/ConsoleImpl.java | 10 +-- .../engine/logic/console/ConsoleSystem.java | 8 +- .../logic/debug/MovementDebugCommands.java | 13 --- .../logic/permission/PermissionCommands.java | 2 +- .../logic/players/LocalPlayerSystem.java | 1 - .../players/PlayerCharacterComponent.java | 2 +- .../ThirdPersonRemoteClientSystem.java | 12 ++- .../event/LocalPlayerInitializedEvent.java | 2 +- .../players/event/OnPlayerRespawnedEvent.java | 4 +- .../players/event/OnPlayerSpawnedEvent.java | 2 +- .../org/terasology/engine/math/Rotation.java | 6 +- .../java/org/terasology/engine/math/Side.java | 2 +- .../impl/PerformanceMonitorImpl.java | 4 +- .../engine/network/PingService.java | 3 +- .../internal/ClientConnectionHandler.java | 2 +- .../engine/network/internal/NetClient.java | 21 ++--- .../engine/network/internal/NetEntityRef.java | 5 -- .../network/internal/NetworkSystemImpl.java | 72 +++++++-------- .../engine/network/internal/ServerImpl.java | 7 +- .../components/ParticleEmitterComponent.java | 4 +- .../updating/ParticleUpdaterImpl.java | 2 - .../internal/AbstractStorageManager.java | 6 +- .../serializers/EventSerializer.java | 4 +- .../typeHandling/RegisterTypeHandler.java | 4 +- .../RegisterTypeHandlerFactory.java | 4 +- .../extensionTypes/EntityRefTypeHandler.java | 12 --- .../engine/physics/bullet/BulletPhysics.java | 15 ---- .../engine/physics/shapes/CollisionShape.java | 2 +- .../engine/recording/EventCopier.java | 3 +- .../recording/EventSystemReplayImpl.java | 4 +- .../RecordAndReplayCurrentStatus.java | 4 +- .../RecordingEventSystemDecorator.java | 14 ++- .../engine/rendering/animation/Animation.java | 6 +- .../assets/mesh/ScreenQuadMeshProducer.java | 40 ++++----- .../engine/rendering/dag/AbstractNode.java | 10 +-- .../terasology/engine/rendering/dag/Node.java | 4 +- .../engine/rendering/dag/RenderGraph.java | 6 +- .../BufferPairConnection.java | 4 - .../dependencyConnections/FboConnection.java | 4 - .../RunOrderConnection.java | 4 - .../engine/rendering/gltf/GLTFMeshFormat.java | 90 ------------------- .../rendering/nui/BaseInteractionScreen.java | 4 +- .../engine/rendering/nui/CoreScreenLayer.java | 7 +- .../nui/editor/layers/NUIEditorScreen.java | 2 +- .../utils/NUIEditorMenuTreeBuilder.java | 2 +- .../nui/internal/NUIManagerInternal.java | 35 +++----- .../ingame/metrics/DebugMetricsSystem.java | 2 +- .../nui/layers/mainMenu/AddServerPopup.java | 5 -- .../layers/mainMenu/GameManifestProvider.java | 2 +- .../nui/layers/mainMenu/JoinGameScreen.java | 3 +- .../mainMenu/inputSettings/UIInputBind.java | 10 +-- .../mainMenu/savedGames/GameProvider.java | 10 +-- .../mainMenu/savedGames/NumberedGameName.java | 12 +-- .../settings/PlayerSettingsScreen.java | 6 -- .../videoSettings/DisplayModeSetting.java | 2 + .../nui/widgets/UIButtonWebBrowser.java | 2 - .../browser/data/basic/HTMLLikeParser.java | 4 +- .../data/html/HTMLDocumentHandler.java | 6 +- .../basic/list/UnorderedListDecorator.java | 3 +- .../rendering/world/WorldRendererImpl.java | 2 +- .../engine/telemetry/TelemetryField.java | 2 +- .../engine/telemetry/TelemetryScreen.java | 2 +- .../engine/telemetry/TelemetryUtils.java | 17 ++-- .../metrics/GameConfigurationMetric.java | 1 - .../utilities/concurrency/TaskMaster.java | 8 +- .../utilities/modifiable/ModifiableValue.java | 6 +- .../procedural/HeightmapFileReader.java | 30 +++---- .../engine/utilities/tree/SpaceTree.java | 13 ++- .../engine/world/block/BlockAreac.java | 8 +- .../engine/world/block/BlockRegionc.java | 10 +-- .../block/family/AbstractBlockFamily.java | 4 +- .../block/family/AttachedToSurfaceFamily.java | 6 +- .../block/family/MultiConnectFamily.java | 1 - .../loader/BlockFamilyDefinitionData.java | 2 +- .../block/shapes/JsonBlockShapeLoader.java | 6 +- .../structure/AttachSupportRequired.java | 9 +- .../structure/SideBlockSupportRequired.java | 11 ++- .../engine/world/chunks/LodChunkProvider.java | 9 -- .../blockdata/ExtraBlockDataManager.java | 8 +- .../chunks/blockdata/RegisterExtraData.java | 6 +- .../chunks/internal/ChunkSerializer.java | 53 +---------- .../LocalChunkProvider.java | 10 +-- .../RemoteChunkProvider.java | 2 +- .../engine/world/generation/WorldBuilder.java | 12 ++- .../internal/WorldGeneratorManager.java | 7 +- .../internal/EntityAwareWorldProvider.java | 6 +- .../world/internal/WorldProviderCore.java | 2 +- .../world/viewer/TileThreadFactory.java | 2 +- .../world/viewer/color/ColorBlenderArgb.java | 3 +- .../world/viewer/color/ColorBlenderRgba.java | 3 +- .../viewer/picker/CirclePickerClosest.java | 8 +- .../coreTypes/ObjectFieldMapTypeHandler.java | 2 +- 128 files changed, 323 insertions(+), 714 deletions(-) diff --git a/engine-tests/src/main/java/org/terasology/engine/Environment.java b/engine-tests/src/main/java/org/terasology/engine/Environment.java index 032ae6cebe2..b710477c490 100644 --- a/engine-tests/src/main/java/org/terasology/engine/Environment.java +++ b/engine-tests/src/main/java/org/terasology/engine/Environment.java @@ -37,16 +37,14 @@ class Environment { Environment(Name... moduleNames) { try { reset(Sets.newHashSet(moduleNames)); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException(e); - } + throw new RuntimeException(e); } } - protected void reset(Set moduleNames) throws Exception { + protected void reset(Set moduleNames) throws IOException { this.context = new ContextImpl(); RecordAndReplayCurrentStatus recordAndReplayCurrentStatus = new RecordAndReplayCurrentStatus(); context.put(RecordAndReplayCurrentStatus.class, recordAndReplayCurrentStatus); @@ -99,7 +97,7 @@ protected void setupPathManager() throws IOException { PathManager.getInstance(); } - protected void setupModuleManager(Set moduleNames) throws Exception { + protected void setupModuleManager(Set moduleNames) { // empty } @@ -160,9 +158,9 @@ protected void setupCelestialSystem() { /** * Cleans up all resources (similar to AutoCloseable) * - * @throws Exception if something goes wrong + * @throws RuntimeException if something goes wrong */ - public void close() throws Exception { + public void close() { CoreRegistry.setContext(null); context = null; } diff --git a/engine-tests/src/main/java/org/terasology/engine/HeadlessEnvironment.java b/engine-tests/src/main/java/org/terasology/engine/HeadlessEnvironment.java index 52b5239827a..b64e3848c3e 100644 --- a/engine-tests/src/main/java/org/terasology/engine/HeadlessEnvironment.java +++ b/engine-tests/src/main/java/org/terasology/engine/HeadlessEnvironment.java @@ -263,7 +263,7 @@ protected void setupConfig() { } @Override - protected void setupModuleManager(Set moduleNames) throws Exception { + protected void setupModuleManager(Set moduleNames) throws RuntimeException { TypeRegistry.WHITELISTED_CLASSES = ExternalApiWhitelist.CLASSES.stream().map(Class::getName).collect(Collectors.toSet()); ModuleManager moduleManager = ModuleManagerFactory.create(); @@ -320,7 +320,7 @@ protected void loadPrefabs() { } @Override - public void close() throws Exception { + public void close() throws RuntimeException { // it would be nice, if elements in the context implemented (Auto)Closeable // The StorageManager creates a thread pool (through TaskMaster) diff --git a/engine-tests/src/main/java/org/terasology/engine/ModuleEnvironmentTest.java b/engine-tests/src/main/java/org/terasology/engine/ModuleEnvironmentTest.java index 7c195b117ef..b5444fa1599 100644 --- a/engine-tests/src/main/java/org/terasology/engine/ModuleEnvironmentTest.java +++ b/engine-tests/src/main/java/org/terasology/engine/ModuleEnvironmentTest.java @@ -12,6 +12,7 @@ import org.terasology.reflection.ModuleTypeRegistry; import org.terasology.reflection.TypeRegistry; +import java.io.IOException; import java.nio.file.Path; import java.util.stream.Collectors; @@ -21,7 +22,7 @@ public abstract class ModuleEnvironmentTest { protected ModuleTypeRegistry typeRegistry; @BeforeEach - public void before(@TempDir Path tempHome) throws Exception { + public void before(@TempDir Path tempHome) throws IOException { PathManager.getInstance().useOverrideHomePath(tempHome); moduleManager = ModuleManagerFactory.create(); diff --git a/engine-tests/src/main/java/org/terasology/engine/testUtil/ModuleManagerFactory.java b/engine-tests/src/main/java/org/terasology/engine/testUtil/ModuleManagerFactory.java index 62ee685a7ab..92bcb8ed729 100644 --- a/engine-tests/src/main/java/org/terasology/engine/testUtil/ModuleManagerFactory.java +++ b/engine-tests/src/main/java/org/terasology/engine/testUtil/ModuleManagerFactory.java @@ -12,7 +12,7 @@ public final class ModuleManagerFactory { private ModuleManagerFactory() { } - public static ModuleManager create() throws Exception { + public static ModuleManager create() { // Loading screens, among other things, break when NUI classes are not added to engine. ModuleManager moduleManager = new ModuleManager("", ImmutableList.of(UIWidget.class)); Module unittestModule = moduleManager.registerPackageModule("org.terasology.unittest"); diff --git a/engine/src/main/java/org/terasology/engine/audio/formats/OggReader.java b/engine/src/main/java/org/terasology/engine/audio/formats/OggReader.java index cc856251c13..5b4d093957e 100644 --- a/engine/src/main/java/org/terasology/engine/audio/formats/OggReader.java +++ b/engine/src/main/java/org/terasology/engine/audio/formats/OggReader.java @@ -261,7 +261,7 @@ public long skip(long n) throws IOException { /** * Initalizes the vorbis stream. Reads the stream until info and comment are read. */ - private void initVorbis() throws Exception { + private void initVorbis() throws IOException { // Now we can read pages syncState.init(); @@ -283,7 +283,7 @@ private void initVorbis() throws Exception { return; //break; } // error case. Must not be Vorbis data - throw new Exception("Input does not appear to be an Ogg bitstream."); + throw new IOException("Input does not appear to be an Ogg bitstream."); } // Get the serial number and set up the rest of decode. @@ -302,15 +302,15 @@ private void initVorbis() throws Exception { comment.init(); if (streamState.pagein(page) < 0) { // error; stream version mismatch perhaps - throw new Exception("Error reading first page of Ogg bitstream data."); + throw new IOException("Error reading first page of Ogg bitstream data."); } if (streamState.packetout(packet) != 1) { // no page? must not be vorbis - throw new Exception("Error reading initial header packet."); + throw new IOException("Error reading initial header packet."); } if (info.synthesis_headerin(comment, packet) < 0) { // error case; not a vorbis header - throw new Exception("This Ogg bitstream does not contain Vorbis audio data."); + throw new IOException("This Ogg bitstream does not contain Vorbis audio data."); } // At this point, we're sure we're Vorbis. We've set up the logical @@ -346,7 +346,7 @@ private void initVorbis() throws Exception { if (result == -1) { // Uh oh; data at some point was corrupted or missing! // We can't tolerate that in a header. Die. - throw new Exception("Corrupt secondary header. Exiting."); + throw new IOException("Corrupt secondary header. Exiting."); } info.synthesis_headerin(comment, packet); i++; @@ -364,7 +364,7 @@ private void initVorbis() throws Exception { bytes = 0; } if (bytes == 0 && i < 2) { - throw new Exception("End of file before finding all Vorbis headers!"); + throw new IOException("End of file before finding all Vorbis headers!"); } syncState.wrote(bytes); } @@ -386,7 +386,7 @@ private void initVorbis() throws Exception { */ private int decodePacket() { // check the endianes of the computer. - final boolean bigEndian = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + final boolean bigEndian = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN); if (block.synthesis(packet) == 0) { dspState.synthesis_blockin(block); diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/BaseSoundPool.java b/engine/src/main/java/org/terasology/engine/audio/openAL/BaseSoundPool.java index 184786930d1..f1066579e63 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/BaseSoundPool.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/BaseSoundPool.java @@ -32,10 +32,8 @@ public BaseSoundPool() { public SOURCE getLockedSource() { for (SOURCE source : soundSources.keySet()) { - if (!isActive(source)) { - if (lock(source)) { - return source; - } + if (!isActive(source) && lock(source)) { + return source; } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/ui/ColorConstraintWidgetFactory.java b/engine/src/main/java/org/terasology/engine/config/flexible/ui/ColorConstraintWidgetFactory.java index 7970641891d..c523d0b770f 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/ui/ColorConstraintWidgetFactory.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/ui/ColorConstraintWidgetFactory.java @@ -81,7 +81,6 @@ private float findClosestIndex(Color color) { private Color findClosestColor(float findex) { int index = DoubleMath.roundToInt(findex * (double) (colors.size() - 1), RoundingMode.HALF_UP); - Color color = colors.get(index); - return color; + return colors.get(index); } } diff --git a/engine/src/main/java/org/terasology/engine/core/GameThread.java b/engine/src/main/java/org/terasology/engine/core/GameThread.java index 052bec296bf..90d5f421fb5 100644 --- a/engine/src/main/java/org/terasology/engine/core/GameThread.java +++ b/engine/src/main/java/org/terasology/engine/core/GameThread.java @@ -30,7 +30,7 @@ private GameThread() { * @return Whether the currentThread is the gameThread. */ public static boolean isCurrentThread() { - return Thread.currentThread() == gameThread; + return Thread.currentThread().equals(gameThread); } /** @@ -41,7 +41,7 @@ public static boolean isCurrentThread() { * @param process */ public static void asynch(Runnable process) { - if (Thread.currentThread() != gameThread) { + if (!Thread.currentThread().equals(gameThread)) { pendingRunnables.push(process); } else { process.run(); @@ -56,7 +56,7 @@ public static void asynch(Runnable process) { * @param process */ public static void synch(Runnable process) throws InterruptedException { - if (Thread.currentThread() != gameThread) { + if (!Thread.currentThread().equals(gameThread)) { BlockingProcess blockingProcess = new BlockingProcess(process); pendingRunnables.push(blockingProcess); blockingProcess.waitForCompletion(); @@ -69,7 +69,7 @@ public static void synch(Runnable process) throws InterruptedException { * Runs all pending processes submitted from other threads */ public static void processWaitingProcesses() { - if (Thread.currentThread() == gameThread) { + if (Thread.currentThread().equals(gameThread)) { List processes = Lists.newArrayList(); pendingRunnables.drainTo(processes); processes.forEach(Runnable::run); @@ -80,7 +80,7 @@ public static void processWaitingProcesses() { * Removes all pending processes without running them */ public static void clearWaitingProcesses() { - if (gameThread == Thread.currentThread()) { + if (gameThread.equals(Thread.currentThread())) { pendingRunnables.clear(); } } diff --git a/engine/src/main/java/org/terasology/engine/core/bootstrap/eventSystem/AbstractEventSystemDecorator.java b/engine/src/main/java/org/terasology/engine/core/bootstrap/eventSystem/AbstractEventSystemDecorator.java index 8b14075c11f..1b5df81fd6d 100644 --- a/engine/src/main/java/org/terasology/engine/core/bootstrap/eventSystem/AbstractEventSystemDecorator.java +++ b/engine/src/main/java/org/terasology/engine/core/bootstrap/eventSystem/AbstractEventSystemDecorator.java @@ -21,7 +21,7 @@ public AbstractEventSystemDecorator(EventSystem eventSystem) { } public boolean currentThreadIsMain() { - return mainThread == Thread.currentThread(); + return mainThread.equals(Thread.currentThread()); } @Override diff --git a/engine/src/main/java/org/terasology/engine/core/modes/StateMainMenu.java b/engine/src/main/java/org/terasology/engine/core/modes/StateMainMenu.java index e77a93277e7..35768259fe4 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/StateMainMenu.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/StateMainMenu.java @@ -4,8 +4,6 @@ import com.google.common.base.MoreObjects; import org.terasology.engine.audio.AudioManager; -import org.terasology.engine.config.Config; -import org.terasology.engine.config.TelemetryConfig; import org.terasology.engine.core.GameEngine; import org.terasology.engine.core.LoggingContext; import org.terasology.engine.core.modes.loadProcesses.RegisterInputSystem; @@ -17,11 +15,7 @@ import org.terasology.engine.rendering.nui.NUIManager; import org.terasology.engine.rendering.nui.editor.systems.NUIEditorSystem; import org.terasology.engine.rendering.nui.editor.systems.NUISkinEditorSystem; -import org.terasology.engine.rendering.nui.layers.mainMenu.LaunchPopup; import org.terasology.engine.rendering.nui.layers.mainMenu.MessagePopup; -import org.terasology.engine.telemetry.TelemetryScreen; -import org.terasology.engine.telemetry.TelemetryUtils; -import org.terasology.engine.telemetry.logstash.TelemetryLogstashAppender; import org.terasology.engine.utilities.Assets; /** @@ -97,35 +91,6 @@ public void init(GameEngine gameEngine) { // pushLaunchPopup(); } - private void pushLaunchPopup() { - Config config = context.get(Config.class); - TelemetryConfig telemetryConfig = config.getTelemetryConfig(); - TranslationSystem translationSystem = context.get(TranslationSystem.class); - TelemetryLogstashAppender appender = TelemetryUtils.fetchTelemetryLogstashAppender(); - if (!telemetryConfig.isLaunchPopupDisabled()) { - String telemetryTitle = translationSystem.translate("${engine:menu#telemetry-launch-popup-title}"); - String telemetryMessage = translationSystem.translate("${engine:menu#telemetry-launch-popup-text}"); - LaunchPopup telemetryConfirmPopup = nuiManager.pushScreen(LaunchPopup.ASSET_URI, LaunchPopup.class); - telemetryConfirmPopup.setMessage(telemetryTitle, telemetryMessage); - telemetryConfirmPopup.setYesHandler(() -> { - telemetryConfig.setTelemetryAndErrorReportingEnable(true); - - // Enable error reporting - appender.start(); - }); - telemetryConfirmPopup.setNoHandler(() -> { - telemetryConfig.setTelemetryAndErrorReportingEnable(false); - - // Disable error reporting - appender.stop(); - }); - telemetryConfirmPopup.setOptionButtonText(translationSystem.translate("${engine:menu#telemetry-button}")); - telemetryConfirmPopup.setOptionHandler(() -> { - nuiManager.pushScreen(TelemetryScreen.ASSET_URI, TelemetryScreen.class); - }); - } - } - @Override public void dispose(boolean shuttingDown) { stopBackgroundMusic(); diff --git a/engine/src/main/java/org/terasology/engine/core/module/RemoteModuleExtension.java b/engine/src/main/java/org/terasology/engine/core/module/RemoteModuleExtension.java index 1b89b0acea3..d9e998daa5e 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/RemoteModuleExtension.java +++ b/engine/src/main/java/org/terasology/engine/core/module/RemoteModuleExtension.java @@ -9,7 +9,7 @@ import java.util.Date; /** * A set of module extensions for remote modules. - * NOTE: this is copy&paste from meta-server. + * NOTE: this is copy&paste from meta-server. */ public enum RemoteModuleExtension { diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsManager.java b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsManager.java index f01a56aca15..6cd880b02b8 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsManager.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsManager.java @@ -4,7 +4,6 @@ package org.terasology.engine.core.subsystem.config; import org.terasology.engine.config.BindsConfig; -import org.terasology.engine.context.Context; import org.terasology.engine.core.SimpleUri; import org.terasology.engine.input.BindAxisEvent; import org.terasology.engine.input.BindButtonEvent; @@ -35,14 +34,14 @@ public interface BindsManager { /** - * The actual binds config. This reflects the current status from {@link #updateDefaultBinds(Context)} + * The actual binds config. This reflects the current status from {@link BindsManager#updateConfigWithDefaultBinds()}. * and all further modifications like modifications in the user input settings. * @return */ BindsConfig getBindsConfig(); /** - * The default bindings. This reflects the current status from {@link #updateDefaultBinds(Context)}. + * The default bindings. This reflects the current status from {@link BindsManager#updateConfigWithDefaultBinds()}. * @return Returns the default bindings. Changes to this config modify the actual instance * but become invalid the next time {@link #updateConfigWithDefaultBinds()} is called. */ diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java index 2df729c1151..96125c3f173 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java @@ -356,7 +356,7 @@ private BindableAxis registerBindAxis(String id, BindAxisEvent event, BindableBu } private BindableAxis registerRealBindAxis(String id, BindAxisEvent event) { - BindableRealAxis axis = new BindableRealAxis(id.toString(), event); + BindableRealAxis axis = new BindableRealAxis(id, event); axisBinds.add(axis); axisLookup.put(id, axis); return axis; diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityBuilder.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityBuilder.java index f822263c7d3..86ccdaa8396 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityBuilder.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityBuilder.java @@ -70,10 +70,9 @@ public boolean addPrefab(String prefabName) { } } /** - * Adds all of the components from a prefab to this builder + * Adds all components from a prefab to this builder * * @param prefab the prefab to add - * @return whether the prefab was successfully added */ public void addPrefab(Prefab prefab) { if (prefab != null) { diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityPool.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityPool.java index 961fed1c68a..9d466290684 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityPool.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/EntityPool.java @@ -133,9 +133,9 @@ public interface EntityPool { * All entities containing every one of the given components. *

* Implementation note: - * Java generic types are a mess, especially where - * varargs are involved. We can't use {@link SafeVarargs @SafeVarargs} on any interface methods + * Java generic types are a mess (see + * Designing Generic Methods), especially where varargs are involved. + * We can't use {@link SafeVarargs @SafeVarargs} on any interface methods * because there is no way to know the implementations of the interface are safe. *

* In this case, in practice, there are few (if any) callers that pass more than two values. diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/BaseEntityRef.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/BaseEntityRef.java index bfb2ea3377c..3a93a64c09c 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/BaseEntityRef.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/BaseEntityRef.java @@ -44,10 +44,8 @@ public boolean isAlwaysRelevant() { @Override public void setAlwaysRelevant(boolean alwaysRelevant) { - if (exists()) { - if (alwaysRelevant != isAlwaysRelevant()) { - setScope(alwaysRelevant ? GLOBAL : CHUNK); - } + if (exists() && alwaysRelevant != isAlwaysRelevant()) { + setScope(alwaysRelevant ? GLOBAL : CHUNK); } } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java index c2ce163f186..b5715fba7cd 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java @@ -605,13 +605,9 @@ public void saveComponent(long entityId, Component component) { public Optional getPool(long id) { Optional pool = Optional.ofNullable(poolMap.get(id)); - if (!pool.isPresent()) { - if (id != NULL_ID) { - // TODO: Entity pools assignment is not needed as of now, can be enabled later on when necessary. - if (!isExistingEntity(id)) { - logger.error("Entity {} doesn't exist", id); - } - } + // TODO: Entity pools assignment is not needed as of now, can be enabled later on when necessary. + if (!pool.isPresent() && id != NULL_ID && !isExistingEntity(id)) { + logger.error("Entity {} doesn't exist", id); } return pool; } @@ -707,16 +703,6 @@ protected void notifyComponentChanged(EntityRef changedEntity, Class components) { - for (EntityChangeSubscriber subscriber : subscribers) { - subscriber.onReactivation(entity, components); - } - } - - /** * This method gets called before an entity gets deactivated (e.g. for storage). */ diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/event/AbstractValueModifiableEvent.java b/engine/src/main/java/org/terasology/engine/entitySystem/event/AbstractValueModifiableEvent.java index fd146a2aed2..cf0dd2a640c 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/event/AbstractValueModifiableEvent.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/event/AbstractValueModifiableEvent.java @@ -56,7 +56,7 @@ public void postAdd(float amount) { * result = max(0, ResultValueWithoutCapping) * * - * The result value is guaranteed to be non-negative! + * The result value is guaranteed to be non-negative! */ public float getResultValue() { //TODO(skaldarnar): Based on a discussion in https://github.com/MovingBlocks/Terasology/pull/4063 we may want @@ -76,7 +76,7 @@ public float getResultValue() { * result = ( + Σ ) * Π + Σ * } * - * Negative result values are allowed here. + * Negative result values are allowed here. */ public float getResultValueWithoutCapping() { //TODO: Based on an extended discussion from : https://github.com/MovingBlocks/Terasology/pull/4063 diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java index 6fccd116dc4..22c1ab65a7a 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java @@ -242,7 +242,7 @@ public void unregisterEventReceiver(EventReceiver eventRece @Override public void send(EntityRef entity, Event event) { - if (Thread.currentThread() != mainThread) { + if (!Thread.currentThread().equals(mainThread)) { pendingEvents.offer(new PendingEvent(entity, event)); } else { Set selectedHandlersSet = selectEventHandlers(event.getClass(), entity); @@ -281,7 +281,7 @@ private void sendConsumableEvent(EntityRef entity, Event event, List, EventHandlerInfo> handlers = diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/prefab/internal/PojoPrefab.java b/engine/src/main/java/org/terasology/engine/entitySystem/prefab/internal/PojoPrefab.java index 57cd760c3a9..4cea9f5fead 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/prefab/internal/PojoPrefab.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/prefab/internal/PojoPrefab.java @@ -84,7 +84,7 @@ protected void doReload(PrefabData data) { this.persisted = data.isPersisted(); this.alwaysRelevant = data.isAlwaysRelevant(); this.parent = data.getParent(); - if (parent != null && parent instanceof PojoPrefab) { + if (parent instanceof PojoPrefab) { ((PojoPrefab) parent).children.add(this); } } diff --git a/engine/src/main/java/org/terasology/engine/i18n/assets/TranslationData.java b/engine/src/main/java/org/terasology/engine/i18n/assets/TranslationData.java index 466011efb09..e8bbf85c6c6 100644 --- a/engine/src/main/java/org/terasology/engine/i18n/assets/TranslationData.java +++ b/engine/src/main/java/org/terasology/engine/i18n/assets/TranslationData.java @@ -13,7 +13,7 @@ /** - * Defines translation data in the form of a map {ID -> value}. + * Defines translation data in the form of a map {ID → value}. */ public class TranslationData implements AssetData { diff --git a/engine/src/main/java/org/terasology/engine/input/cameraTarget/TargetSystem.java b/engine/src/main/java/org/terasology/engine/input/cameraTarget/TargetSystem.java index 7b3706dcca1..b707acf6c4e 100644 --- a/engine/src/main/java/org/terasology/engine/input/cameraTarget/TargetSystem.java +++ b/engine/src/main/java/org/terasology/engine/input/cameraTarget/TargetSystem.java @@ -67,10 +67,8 @@ public boolean updateTarget(Vector3f pos, Vector3f dir, float maxDist) { EntityRef newTarget = hitInfo.getEntity(); if (hitInfo.isWorldHit()) { - if (targetBlockPos != null) { - if (targetBlockPos.equals(hitInfo.getBlockPosition())) { - return false; - } + if (targetBlockPos != null && targetBlockPos.equals(hitInfo.getBlockPosition())) { + return false; } targetBlockPos = hitInfo.getBlockPosition(); } else { diff --git a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java index 3abb4eb3230..e63aeff998e 100644 --- a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java +++ b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java @@ -84,8 +84,7 @@ private void setupTeraButtonsMapping() { } private void updateGamepadMappings() { - InputStream inputStream = LwjglControllerDevice.class.getResourceAsStream("/gamecontrollerdb.txt"); - try { + try (InputStream inputStream = LwjglControllerDevice.class.getResourceAsStream("/gamecontrollerdb.txt")) { byte[] bytes = ByteStreams.toByteArray(inputStream); String gamecontrollerDBContent = new String(bytes, TerasologyConstants.CHARSET); ByteBuffer gamecontrolleDB = MemoryUtil.memASCIISafe(gamecontrollerDBContent); diff --git a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglMouseDevice.java b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglMouseDevice.java index 104baa6b228..8f65a5b0187 100644 --- a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglMouseDevice.java +++ b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglMouseDevice.java @@ -77,8 +77,7 @@ public Vector2i getPosition() { @Override public Vector2d getDelta() { - Vector2d result = new Vector2d(xposDelta, yposDelta); - return result; + return new Vector2d(xposDelta, yposDelta); } @Override diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/BehaviorSystem.java b/engine/src/main/java/org/terasology/engine/logic/behavior/BehaviorSystem.java index 1f59b02c4b6..79b9c9290d0 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/BehaviorSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/BehaviorSystem.java @@ -37,10 +37,10 @@ /** * Behavior tree system - *

+ *

* Each entity with BehaviorComponent is kept under control by this system. For each such entity a behavior tree is * loaded and an interpreter is started. - *

+ *

* Modifications made to a behavior tree will reflect to all entities using this tree. */ @RegisterSystem(RegisterMode.AUTHORITY) diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/CollectiveBehaviorSystem.java b/engine/src/main/java/org/terasology/engine/logic/behavior/CollectiveBehaviorSystem.java index 2cd55e01cac..457a3bc8bdb 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/CollectiveBehaviorSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/CollectiveBehaviorSystem.java @@ -41,10 +41,10 @@ /** * Behavior tree system - *

+ *

* Each entity with BehaviorComponent is kept under control by this system. For each such entity a behavior tree * is loaded and an interpreter is started. - *

+ *

* Modifications made to a behavior tree will reflect to all entities using this tree. */ @RegisterSystem(RegisterMode.AUTHORITY) diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/GuardAction.java b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/GuardAction.java index 9f873264b2b..1aee13c55b2 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/GuardAction.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/GuardAction.java @@ -27,9 +27,7 @@ public class GuardAction extends ConditionAction { public boolean prune(Actor actor) { try { - boolean condition = condition(actor); - - return !condition; + return !condition(actor); } catch (ClassNotFoundException e) { logger.error("Class not found. Does the Component specified exist?", e); } catch (NoSuchFieldException e) { diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/Action.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/Action.java index 640cd66a4b9..68942e39321 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/Action.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/Action.java @@ -8,7 +8,7 @@ * The action that is used by an action or decorator node. Every action node of a behavior tree has its own action * instance. There is only one action instance for all actors, that run a behavior tree - so all state information * needs to be stored at the actor. - *

+ *

* Action instances are shown in the property panel of the behavior editor. */ @API diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/Actor.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/Actor.java index 2e781748b25..847ccd1a20f 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/Actor.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/Actor.java @@ -73,8 +73,7 @@ public void setDelta(float delta) { * @return The component of the actors minion or null if the minion has no such component. */ public T getComponent(Class type) { - T component = entity.getComponent(type); - return component; + return entity.getComponent(type); } public Object getComponentField(ComponentFieldUri uri) { diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/BehaviorTreeBuilder.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/BehaviorTreeBuilder.java index 23cffb128b9..6a39fa87ce3 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/BehaviorTreeBuilder.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/BehaviorTreeBuilder.java @@ -40,9 +40,9 @@ /** * JSON deserializer to create trees using json: - *

+ *

* { sequence:[action1, {action2:{ foo:bar, duration:7}}] } - *

+ *

* Actions and Decorators need to be registered before parsing. */ public class BehaviorTreeBuilder implements JsonDeserializer, JsonSerializer { diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/AliveCharacterComponent.java b/engine/src/main/java/org/terasology/engine/logic/characters/AliveCharacterComponent.java index 1ee1b8288b3..215561a14c5 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/AliveCharacterComponent.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/AliveCharacterComponent.java @@ -6,11 +6,11 @@ import org.terasology.gestalt.entitysystem.component.EmptyComponent; /** - * This is only attached to the alive character entities.
- * Used to differentiate between alive and dead character entities.

+ * This is only attached to the alive character entities.
+ * Used to differentiate between alive and dead character entities.

* * This needs to be necessarily attached to all character entities that require CharacterMovementComponent - * for movement systems to work.
+ * for movement systems to work.
* Can be used to differently handle situations for character entities that can remain in a dead state * or respawn after a while. */ diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterMovementComponent.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterMovementComponent.java index 16935f53353..8a61d28af8d 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterMovementComponent.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterMovementComponent.java @@ -15,7 +15,7 @@ /** * This component is attached to all character entities. It governs movement and stores associated paramenters, and can - * be used instead of a CapsuleShapeComponent by the physics system to define the collision shape.
The {@link + * be used instead of a CapsuleShapeComponent by the physics system to define the collision shape.
The {@link * AliveCharacterComponent} should necessarily be attached to the character entity for the movement systems to work. */ public final class CharacterMovementComponent implements Component { diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java index d2378ce332c..34ede66c8ce 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java @@ -120,23 +120,20 @@ public String getInstigatorName(EntityRef instigator) { if (instigator.hasComponent(CharacterComponent.class)) { EntityRef instigatorClient = instigator.getComponent(CharacterComponent.class).controller; EntityRef instigatorClientInfo = instigatorClient.getComponent(ClientComponent.class).clientInfo; - DisplayNameComponent displayNameComponent = instigatorClientInfo.getComponent(DisplayNameComponent.class); - return displayNameComponent.name; + return instigatorClientInfo.getComponent(DisplayNameComponent.class).name; } else if (instigator.getParentPrefab() != null) { //A DisplayName can be specified in the entity prefab //Otherwise, the game will attempt to generate one from the name of that prefab Prefab parentPrefab = instigator.getParentPrefab(); if (parentPrefab.hasComponent(DisplayNameComponent.class)) { - DisplayNameComponent displayNameComponent = parentPrefab.getComponent(DisplayNameComponent.class); - return displayNameComponent.name; + return parentPrefab.getComponent(DisplayNameComponent.class).name; } else { String instigatorName = parentPrefab.getName(); //getParentPrefab.getName() returns a ResourceUrn String such as "engine:player" //The following calls change the damage type to be more readable //For instance, "engine:player" becomes "Player" instigatorName = instigatorName.replaceAll(".*:(.*)", "$1"); - instigatorName = Character.toUpperCase(instigatorName.charAt(0)) + instigatorName.substring(1); - return instigatorName; + return Character.toUpperCase(instigatorName.charAt(0)) + instigatorName.substring(1); } } else { return null; @@ -155,8 +152,7 @@ public String getDamageTypeName(Prefab damageType) { //A DisplayName can be specified in the damage type prefab //Otherwise, the game will attempt to generate one from the name of that prefab if (damageType.hasComponent(DisplayNameComponent.class)) { - DisplayNameComponent displayNameComponent = damageType.getComponent(DisplayNameComponent.class); - return displayNameComponent.name; + return damageType.getComponent(DisplayNameComponent.class).name; } else { logger.info(String.format("%s is missing a readable DisplayName", damageType.getName())); String damageTypeName = damageType.getName(); @@ -198,10 +194,8 @@ public void onAttackRequest(AttackButton event, EntityRef entity, CharacterHeldI @ReceiveEvent(components = LocationComponent.class) public void onAttackRequest(AttackRequest event, EntityRef character, CharacterComponent characterComponent) { // if an item is used, make sure this entity is allowed to attack with it - if (event.getItem().exists()) { - if (!character.equals(event.getItem().getOwner())) { - return; - } + if (event.getItem().exists() && !character.equals(event.getItem().getOwner())) { + return; } OnItemUseEvent onItemUseEvent = new OnItemUseEvent(); diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/GazeAuthoritySystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/GazeAuthoritySystem.java index 68f5c1703c5..68176bb93e0 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/GazeAuthoritySystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/GazeAuthoritySystem.java @@ -48,8 +48,7 @@ public void ensureGazeContainerEntitiesCreated(OnActivatedComponent event, Entit private EntityRef createGazeEntity() { EntityBuilder gazeContainerBuilder = entityManager.newBuilder("engine:gaze"); - EntityRef gazeEntity = gazeContainerBuilder.build(); - return gazeEntity; + return gazeContainerBuilder.build(); } @Priority(EventPriority.PRIORITY_LOW) diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/events/OnScaleEvent.java b/engine/src/main/java/org/terasology/engine/logic/characters/events/OnScaleEvent.java index 3c312184be1..0f31c5416e4 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/events/OnScaleEvent.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/events/OnScaleEvent.java @@ -49,7 +49,7 @@ public float getNewValue() { /** * The scaling factor determined by the quotient of new and old value. *

- * This is guaranteed to be greater zero (> 0). + * This is guaranteed to be greater than 0. */ public float getFactor() { return newValue / oldValue; diff --git a/engine/src/main/java/org/terasology/engine/logic/chat/ChatSystem.java b/engine/src/main/java/org/terasology/engine/logic/chat/ChatSystem.java index 339c1381278..d54b7ccee1e 100644 --- a/engine/src/main/java/org/terasology/engine/logic/chat/ChatSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/chat/ChatSystem.java @@ -72,12 +72,10 @@ public void onMessage(MessageEvent event, EntityRef entity) { ClientComponent client = entity.getComponent(ClientComponent.class); if (client.local) { Message message = event.getFormattedMessage(); - if (message.getType() == CoreMessageType.CHAT || message.getType() == CoreMessageType.NOTIFICATION) { - + if (message.getType() == CoreMessageType.CHAT || message.getType() == CoreMessageType.NOTIFICATION + && !nuiManager.isOpen(CHAT_UI) && !nuiManager.isOpen(CONSOLE_UI)) { // show overlay only if chat and console are hidden - if (!nuiManager.isOpen(CHAT_UI) && !nuiManager.isOpen(CONSOLE_UI)) { - overlay.setVisible(true); - } + overlay.setVisible(true); } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java index c4bd35e7b9c..4c506fe6419 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java @@ -206,10 +206,8 @@ public boolean execute(String rawCommand, EntityRef callingClient) { ClientComponent cc = callingClient.getComponent(ClientComponent.class); - if (cc.local) { - if (!rawCommand.isEmpty() && (localCommandHistory.isEmpty() || !localCommandHistory.getLast().equals(rawCommand))) { - localCommandHistory.add(rawCommand); - } + if (cc.local && !rawCommand.isEmpty() && (localCommandHistory.isEmpty() || !localCommandHistory.getLast().equals(rawCommand))) { + localCommandHistory.add(rawCommand); } return execute(new Name(commandName), processedParameters, callingClient); @@ -327,9 +325,7 @@ public List processParameters(String rawCommand) { String parameterPart = cleanedCommand.substring(commandEndIndex).trim(); //get the parameters - List params = splitParameters(parameterPart); - - return params; + return splitParameters(parameterPart); } private static List splitParameters(String paramStr) { diff --git a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleSystem.java b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleSystem.java index eb2a5e7794e..f03bca09273 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleSystem.java @@ -34,12 +34,10 @@ public void initialise() { if (nuiManager != null) { overlay = nuiManager.addOverlay(NotificationOverlay.ASSET_URI, NotificationOverlay.class); console.subscribe((Message message) -> { - if (!nuiManager.isOpen("engine:console")) { + if (!nuiManager.isOpen("engine:console") && message.getType() != CoreMessageType.CHAT + && message.getType() != CoreMessageType.NOTIFICATION || !nuiManager.isOpen("engine:chat")) { // make sure the message isn't already shown in the chat overlay - if (message.getType() != CoreMessageType.CHAT && message.getType() != CoreMessageType.NOTIFICATION - || !nuiManager.isOpen("engine:chat")) { - overlay.setVisible(true); - } + overlay.setVisible(true); } }); } diff --git a/engine/src/main/java/org/terasology/engine/logic/debug/MovementDebugCommands.java b/engine/src/main/java/org/terasology/engine/logic/debug/MovementDebugCommands.java index 8c496c5a3ad..473ce735724 100644 --- a/engine/src/main/java/org/terasology/engine/logic/debug/MovementDebugCommands.java +++ b/engine/src/main/java/org/terasology/engine/logic/debug/MovementDebugCommands.java @@ -224,19 +224,6 @@ public String stepHeight(@Sender EntityRef client, @CommandParam("height") float return ""; } - - private float getJumpSpeed(float ratio, float defaultValue) { - return (float) Math.pow(ratio, 0.74f) * 0.4f * defaultValue + 0.6f * defaultValue; - } - - private float getInteractionRange(float ratio, float defaultValue) { - return (float) Math.pow(ratio, 0.62f) * defaultValue; - } - - private float getRunFactor(float ratio, float defaultValue) { - return (float) Math.pow(ratio, 0.68f) * defaultValue; - } - @Command(shortDescription = "Sets the height of the player", runOnServer = true, requiredPermission = PermissionManager.CHEAT_PERMISSION) public String playerHeight(@Sender EntityRef entity, @CommandParam("height") float newHeight) { diff --git a/engine/src/main/java/org/terasology/engine/logic/permission/PermissionCommands.java b/engine/src/main/java/org/terasology/engine/logic/permission/PermissionCommands.java index 7bfc6bf9f11..ce673051867 100644 --- a/engine/src/main/java/org/terasology/engine/logic/permission/PermissionCommands.java +++ b/engine/src/main/java/org/terasology/engine/logic/permission/PermissionCommands.java @@ -43,7 +43,7 @@ public String usePermissionKey(@CommandParam("key") String key, @Sender EntityRe PermissionConfig permissionConfig = config.getPermission(); String expectedKey = permissionConfig.getOneTimeAuthorizationKey(); - if (expectedKey != null && !expectedKey.equals("") && key.equals(expectedKey)) { + if (expectedKey != null && !expectedKey.isEmpty() && key.equals(expectedKey)) { permissionConfig.setOneTimeAuthorizationKey(""); ClientComponent clientComponent = client.getComponent(ClientComponent.class); EntityRef clientInfo = clientComponent.clientInfo; diff --git a/engine/src/main/java/org/terasology/engine/logic/players/LocalPlayerSystem.java b/engine/src/main/java/org/terasology/engine/logic/players/LocalPlayerSystem.java index 8f56649752d..8bbdc285414 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/LocalPlayerSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/LocalPlayerSystem.java @@ -146,7 +146,6 @@ private void processInput(EntityRef entity, CharacterMovementComponent character Vector3f relMove = new Vector3f(relativeMovement); relMove.y = 0; - Quaternionf viewRotation = new Quaternionf(); switch (characterMovementComponent.mode) { case CROUCHING: case WALKING: diff --git a/engine/src/main/java/org/terasology/engine/logic/players/PlayerCharacterComponent.java b/engine/src/main/java/org/terasology/engine/logic/players/PlayerCharacterComponent.java index 9c0f616d1eb..ce76e6e4c3f 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/PlayerCharacterComponent.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/PlayerCharacterComponent.java @@ -5,7 +5,7 @@ import org.terasology.gestalt.entitysystem.component.EmptyComponent; /** - * This is only attached to the player entities.
+ * This is only attached to the player entities.
* Used to differentiate between player characters and other character entities. */ public class PlayerCharacterComponent extends EmptyComponent { diff --git a/engine/src/main/java/org/terasology/engine/logic/players/ThirdPersonRemoteClientSystem.java b/engine/src/main/java/org/terasology/engine/logic/players/ThirdPersonRemoteClientSystem.java index 79f907d21a8..1879f0ba07c 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/ThirdPersonRemoteClientSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/ThirdPersonRemoteClientSystem.java @@ -288,13 +288,11 @@ public void update(float delta) { // If an associated held item entity does *not* exist yet, consider making one if the player has an item // selected - if (currentHeldItem == EntityRef.NULL) { - if (remotePlayer.hasComponent(CharacterHeldItemComponent.class)) { - CharacterHeldItemComponent characterHeldItemComponent = - remotePlayer.getComponent(CharacterHeldItemComponent.class); - if (characterHeldItemComponent != null && !characterHeldItemComponent.selectedItem.equals(EntityRef.NULL)) { - linkHeldItemLocationForRemotePlayer(remotePlayer.getComponent(CharacterHeldItemComponent.class).selectedItem, remotePlayer); - } + if (currentHeldItem == EntityRef.NULL && remotePlayer.hasComponent(CharacterHeldItemComponent.class)) { + CharacterHeldItemComponent characterHeldItemComponent = + remotePlayer.getComponent(CharacterHeldItemComponent.class); + if (characterHeldItemComponent != null && !characterHeldItemComponent.selectedItem.equals(EntityRef.NULL)) { + linkHeldItemLocationForRemotePlayer(remotePlayer.getComponent(CharacterHeldItemComponent.class).selectedItem, remotePlayer); } } diff --git a/engine/src/main/java/org/terasology/engine/logic/players/event/LocalPlayerInitializedEvent.java b/engine/src/main/java/org/terasology/engine/logic/players/event/LocalPlayerInitializedEvent.java index a454d05fb5a..af33c2a5ddd 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/event/LocalPlayerInitializedEvent.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/event/LocalPlayerInitializedEvent.java @@ -7,7 +7,7 @@ /** * This event gets sent when the {@link LocalPlayer} object is ready to be used. - *
+ *
* The object can be injected using {@link org.terasology.engine.registry.In}. * This event corresponds with its isValid() method returning true for the first time. */ diff --git a/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerRespawnedEvent.java b/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerRespawnedEvent.java index 21e028cf8e5..f51ade39ac9 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerRespawnedEvent.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerRespawnedEvent.java @@ -5,8 +5,8 @@ import org.terasology.gestalt.entitysystem.event.Event; /** - * This event gets sent when the player respawns.
- * The player entity is preserved along with its components during respawn.
+ * This event gets sent when the player respawns.
+ * The player entity is preserved along with its components during respawn.
* This event should be received and handled by systems that need to reset * some components attached to the player entity. */ diff --git a/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerSpawnedEvent.java b/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerSpawnedEvent.java index 8e0d1feff3e..bf86ad84fa0 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerSpawnedEvent.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/event/OnPlayerSpawnedEvent.java @@ -6,7 +6,7 @@ /** * This event gets sent when the player spawns. - *
+ *
* Note: that this should be used only as a one time event i.e. when * the player spawns for the first time in the game. * On every subsequent spawn a onPlayerRespawnedEvent is sent. diff --git a/engine/src/main/java/org/terasology/engine/math/Rotation.java b/engine/src/main/java/org/terasology/engine/math/Rotation.java index 65ee3b8954b..c1c7f674f45 100644 --- a/engine/src/main/java/org/terasology/engine/math/Rotation.java +++ b/engine/src/main/java/org/terasology/engine/math/Rotation.java @@ -207,16 +207,16 @@ public int hashCode() { } /** - * Returns all possible rotations for each yaw, pitch & roll combination, including duplicates. + * Returns all possible rotations for each yaw, pitch & roll combination, including duplicates. * - * @return All possible rotations for each yaw, pitch & roll combination. + * @return All possible rotations for each yaw, pitch & roll combination. */ public static Iterable allValues() { return Arrays.asList(ALL_ROTATIONS); } /** - * Returns only unique rotations, in respect to transformations, rather than in respect to yaw, pitch & roll. + * Returns only unique rotations, in respect to transformations, rather than in respect to yaw, pitch & roll. * * @return Unique rotations, in respect to transformations. */ diff --git a/engine/src/main/java/org/terasology/engine/math/Side.java b/engine/src/main/java/org/terasology/engine/math/Side.java index 3c50e3af177..ffdc08cfd9d 100644 --- a/engine/src/main/java/org/terasology/engine/math/Side.java +++ b/engine/src/main/java/org/terasology/engine/math/Side.java @@ -91,7 +91,7 @@ public static List horizontalSides() { /** * This provides a static List of all Sides defined in the enumeration. The result contains the same values as - * calling {@code Side#values} but this does not create a new copy on every call.
+ * calling {@code Side#values} but this does not create a new copy on every call.
* * @return All available sides */ diff --git a/engine/src/main/java/org/terasology/engine/monitoring/impl/PerformanceMonitorImpl.java b/engine/src/main/java/org/terasology/engine/monitoring/impl/PerformanceMonitorImpl.java index 1c8d70f89be..842ead3ac5f 100644 --- a/engine/src/main/java/org/terasology/engine/monitoring/impl/PerformanceMonitorImpl.java +++ b/engine/src/main/java/org/terasology/engine/monitoring/impl/PerformanceMonitorImpl.java @@ -105,7 +105,7 @@ public void rollCycle() { @Override public Activity startActivity(String activityName) { - if (Thread.currentThread() != mainThread) { + if (!Thread.currentThread().equals(mainThread)) { return OFF_THREAD_ACTIVITY; } @@ -127,7 +127,7 @@ public Activity startActivity(String activityName) { @Override public void endActivity() { - if (Thread.currentThread() != mainThread || activityStack.isEmpty()) { + if (!Thread.currentThread().equals(mainThread) || activityStack.isEmpty()) { return; } diff --git a/engine/src/main/java/org/terasology/engine/network/PingService.java b/engine/src/main/java/org/terasology/engine/network/PingService.java index 836fe776664..f0760afdd8d 100644 --- a/engine/src/main/java/org/terasology/engine/network/PingService.java +++ b/engine/src/main/java/org/terasology/engine/network/PingService.java @@ -36,8 +36,7 @@ public Long call() throws IOException { // root privileges under some operating systems sock.connect(endpoint, timeout); Instant end = Instant.now(); - long millis = Duration.between(start, end).toMillis(); - return millis; + return Duration.between(start, end).toMillis(); } } } diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java index b5a45ccf07c..539f280a920 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java @@ -34,6 +34,7 @@ public class ClientConnectionHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = LoggerFactory.getLogger(ClientConnectionHandler.class); + private static final long timeoutThreshold = 120000; private final Config config; private final Context context; @@ -50,7 +51,6 @@ public class ClientConnectionHandler extends ChannelInboundHandlerAdapter { private long lengthReceived; private Timer timeoutTimer = new Timer("Netty-Timeout-Timer", true); private long timeoutPoint = System.currentTimeMillis(); - private final long timeoutThreshold = 120000; private Channel channel; /** diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java index 371abc01ebb..7b9ab767e9e 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java @@ -304,12 +304,10 @@ public void setComponentAdded(int networkId, Class componen } public void setComponentRemoved(int networkId, Class component) { - if (netRelevant.contains(networkId) && !netInitial.contains(networkId)) { - if (!addedComponents.remove(networkId, component)) { - removedComponents.put(networkId, component); - if (!dirtyComponents.remove(networkId, component)) { - netDirty.add(networkId); - } + if (netRelevant.contains(networkId) && !netInitial.contains(networkId) && !addedComponents.remove(networkId, component)) { + removedComponents.put(networkId, component); + if (!dirtyComponents.remove(networkId, component)) { + netDirty.add(networkId); } } } @@ -342,12 +340,11 @@ public void send(Event event, EntityRef target) { } } else { NetworkComponent networkComponent = target.getComponent(NetworkComponent.class); - if (networkComponent != null) { - if (netRelevant.contains(networkComponent.getNetworkId()) || netInitial.contains(networkComponent.getNetworkId())) { - queuedOutgoingEvents.add(NetData.EventMessage.newBuilder() - .setTargetId(networkComponent.getNetworkId()) - .setEvent(eventSerializer.serialize(event)).build()); - } + if (networkComponent != null && netRelevant.contains(networkComponent.getNetworkId()) + || netInitial.contains(networkComponent.getNetworkId())) { + queuedOutgoingEvents.add(NetData.EventMessage.newBuilder() + .setTargetId(networkComponent.getNetworkId()) + .setEvent(eventSerializer.serialize(event)).build()); } } } catch (SerializationException e) { diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetEntityRef.java b/engine/src/main/java/org/terasology/engine/network/internal/NetEntityRef.java index f2278040482..30557439af9 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetEntityRef.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetEntityRef.java @@ -65,9 +65,4 @@ public void invalidate() { super.invalidate(); exists = false; } - - @Override - public void destroy() { - super.destroy(); - } } diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java index 7aa65acc640..cc856a6ccb9 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java @@ -291,15 +291,13 @@ public void shutdown() { server = null; nextNetId = 1; netIdToEntityId.clear(); - if (mode != NetworkMode.CLIENT) { - if (this.entityManager != null) { - for (EntityRef entity : entityManager.getEntitiesWith(NetworkComponent.class)) { - NetworkComponent netComp = entity.getComponent(NetworkComponent.class); - netComp.setNetworkId(0); - entity.saveComponent(netComp); - } - this.entityManager.unsubscribe(this); + if (mode != NetworkMode.CLIENT && this.entityManager != null) { + for (EntityRef entity : entityManager.getEntitiesWith(NetworkComponent.class)) { + NetworkComponent netComp = entity.getComponent(NetworkComponent.class); + netComp.setNetworkId(0); + entity.saveComponent(netComp); } + this.entityManager.unsubscribe(this); } mode = NetworkMode.NONE; entityManager = null; @@ -328,24 +326,22 @@ public Client joinLocal(String preferredName, Color color) { @Override public void update() { - if (mode != NetworkMode.NONE) { - if (entityManager != null) { - processPendingConnections(); - processPendingDisconnects(); - long currentTimer = time.getRealTimeInMs(); - boolean netTick = false; - if (currentTimer > nextNetworkTick) { - nextNetworkTick += NET_TICK_RATE; - netTick = true; - } - PerformanceMonitor.startActivity("Client update"); - for (Client client : clientList) { - client.update(netTick); - } - PerformanceMonitor.endActivity(); - if (server != null) { - server.update(netTick); - } + if (mode != NetworkMode.NONE && entityManager != null) { + processPendingConnections(); + processPendingDisconnects(); + long currentTimer = time.getRealTimeInMs(); + boolean netTick = false; + if (currentTimer > nextNetworkTick) { + nextNetworkTick += NET_TICK_RATE; + netTick = true; + } + PerformanceMonitor.startActivity("Client update"); + for (Client client : clientList) { + client.update(netTick); + } + PerformanceMonitor.endActivity(); + if (server != null) { + server.update(netTick); } } } @@ -597,14 +593,10 @@ public void connectToEntitySystem(EngineEntityManager newEntityManager, EventLib public void onEntityComponentAdded(EntityRef entity, Class component) { ComponentMetadata metadata = componentLibrary.getMetadata(component); NetworkComponent netComp = entity.getComponent(NetworkComponent.class); - if (netComp != null && netComp.getNetworkId() != NULL_NET_ID) { - if (mode.isServer()) { - if (metadata.isReplicated()) { - for (NetClient client : netClientList) { - logger.debug("Component {} added to {}", component, entity); - client.setComponentAdded(netComp.getNetworkId(), component); - } - } + if (netComp != null && netComp.getNetworkId() != NULL_NET_ID && mode.isServer() && metadata.isReplicated()) { + for (NetClient client : netClientList) { + logger.debug("Component {} added to {}", component, entity); + client.setComponentAdded(netComp.getNetworkId(), component); } } updatedOwnedEntities(entity, component, metadata); @@ -614,14 +606,10 @@ public void onEntityComponentAdded(EntityRef entity, Class public void onEntityComponentRemoved(EntityRef entity, Class component) { ComponentMetadata metadata = componentLibrary.getMetadata(component); NetworkComponent netComp = entity.getComponent(NetworkComponent.class); - if (netComp != null && netComp.getNetworkId() != NULL_NET_ID) { - if (mode.isServer()) { - if (metadata.isReplicated()) { - for (NetClient client : netClientList) { - logger.debug("Component {} removed from {}", component, entity); - client.setComponentRemoved(netComp.getNetworkId(), component); - } - } + if (netComp != null && netComp.getNetworkId() != NULL_NET_ID && mode.isServer() && metadata.isReplicated()) { + for (NetClient client : netClientList) { + logger.debug("Component {} removed from {}", component, entity); + client.setComponentRemoved(netComp.getNetworkId(), component); } } if (mode.isAuthority() && metadata.isReferenceOwner()) { diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java index ba4ec87bb59..f4a8dc7ad1f 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java @@ -366,10 +366,9 @@ private void updateEntity(NetData.UpdateEntityMessage updateEntity) { boolean blockEntityBefore = currentEntity.hasComponent(BlockComponent.class); entitySerializer.deserializeOnto(currentEntity, updateEntity.getEntity()); BlockComponent blockComponent = currentEntity.getComponent(BlockComponent.class); - if (blockComponent != null && !blockEntityBefore) { - if (!blockEntityRegistry.getExistingBlockEntityAt(blockComponent.getPosition()).equals(currentEntity)) { - logger.error("Failed to associated new block entity"); - } + if (blockComponent != null && !blockEntityBefore + && !blockEntityRegistry.getExistingBlockEntityAt(blockComponent.getPosition()).equals(currentEntity)) { + logger.error("Failed to associated new block entity"); } if (netComp.getNetworkId() != updateEntity.getNetId()) { logger.error("Network ID lost in update: {}, {} -> {}", currentEntity, updateEntity.getNetId(), netComp.getNetworkId()); diff --git a/engine/src/main/java/org/terasology/engine/particles/components/ParticleEmitterComponent.java b/engine/src/main/java/org/terasology/engine/particles/components/ParticleEmitterComponent.java index 5bfab104da0..e157be8f280 100644 --- a/engine/src/main/java/org/terasology/engine/particles/components/ParticleEmitterComponent.java +++ b/engine/src/main/java/org/terasology/engine/particles/components/ParticleEmitterComponent.java @@ -86,12 +86,12 @@ public class ParticleEmitterComponent implements Component Function that processes that Generator + * Maps Generator component → Function that processes that Generator */ public final Map generatorFunctionMap = new LinkedHashMap<>(); /** - * Maps Affector component -> Function that processes that Affector + * Maps Affector component → Function that processes that Affector */ public final Map affectorFunctionMap = new LinkedHashMap<>(); diff --git a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java index ff68c0e6bf8..2e0b05925f8 100644 --- a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java +++ b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java @@ -124,8 +124,6 @@ public void initialize() { ModuleEnvironment environment = moduleManager.getEnvironment(); for (Class type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) { - RegisterParticleSystemFunction annotation = type.getAnnotation(RegisterParticleSystemFunction.class); - if (!ParticleSystemFunction.class.isAssignableFrom(type)) { logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", type.getSimpleName()); } else { diff --git a/engine/src/main/java/org/terasology/engine/persistence/internal/AbstractStorageManager.java b/engine/src/main/java/org/terasology/engine/persistence/internal/AbstractStorageManager.java index cc399c75ac5..37f20c93834 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/internal/AbstractStorageManager.java +++ b/engine/src/main/java/org/terasology/engine/persistence/internal/AbstractStorageManager.java @@ -180,10 +180,8 @@ protected Collection getEntitiesOfChunk(Chunk chunk) { continue; } Vector3f pos = loc.getWorldPosition(new Vector3f()); - if (pos.isFinite()) { - if (aabb.containsPoint(loc.getWorldPosition(new Vector3f()))) { - entitiesToStore.add(entity); - } + if (pos.isFinite() && aabb.containsPoint(loc.getWorldPosition(new Vector3f()))) { + entitiesToStore.add(entity); } } } diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java index 1700577b67c..585e4ce2875 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java @@ -63,7 +63,7 @@ public void removeIdMapping() { /** * @param eventData * @return The event described by the eventData - * @throws org.terasology.engine.persistence.typeHandling.DeserializationException if an error occurs when deserializing + * @throws DeserializationException if an error occurs when deserializing */ public Event deserialize(EntityData.Event eventData) { Class eventClass = getEventClass(eventData); @@ -102,7 +102,7 @@ private Event deserializeOnto(Event targetEvent, EntityData.Event eventData, Eve * * @param event * @return The serialized event - * @throws org.terasology.engine.persistence.typeHandling.SerializationException if an error occurs during serialization + * @throws DeserializationException if an error occurs during serialization */ public EntityData.Event serialize(Event event) { EventMetadata eventMetadata = eventLibrary.getMetadata(event.getClass()); diff --git a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandler.java b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandler.java index 1bf72160ec7..b1faf267434 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandler.java +++ b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandler.java @@ -11,8 +11,8 @@ import java.lang.annotation.Target; /** - * Marks a {@link TypeHandler} to be automatically registered at a - * {@link TypeHandlerLibrary TypeHandlerLibrary} on environment change. + * Marks a {@link org.terasology.persistence.typeHandling.TypeHandler} to be automatically registered at a + * {@link org.terasology.persistence.typeHandling.TypeHandlerLibrary} on environment change. * This can be used to (de)serialize custom components. *

* By default, the TypeHandler must have an empty constructor. diff --git a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandlerFactory.java b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandlerFactory.java index 01d7f2b01ee..2ac4c11fede 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandlerFactory.java +++ b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/RegisterTypeHandlerFactory.java @@ -11,8 +11,8 @@ import java.lang.annotation.Target; /** - * Marks a {@link TypeHandlerFactory} to be automatically registered to the - * {@link TypeHandlerLibrary} on environment change. + * Marks a {@link org.terasology.persistence.typeHandling.TypeHandlerFactory} to be automatically registered to the + * {@link org.terasology.persistence.typeHandling.TypeHandlerLibrary} on environment change. * This can be used to (de)serialize custom components. *

* The {@link org.terasology.engine.registry.In} annotation can be used to access objects diff --git a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/extensionTypes/EntityRefTypeHandler.java b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/extensionTypes/EntityRefTypeHandler.java index 6f6ff8a9ec6..30c280f87f1 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/typeHandling/extensionTypes/EntityRefTypeHandler.java +++ b/engine/src/main/java/org/terasology/engine/persistence/typeHandling/extensionTypes/EntityRefTypeHandler.java @@ -2,15 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.persistence.typeHandling.extensionTypes; -import gnu.trove.iterator.TLongIterator; import org.terasology.engine.entitySystem.entity.EntityRef; import org.terasology.engine.entitySystem.entity.internal.EngineEntityManager; import org.terasology.persistence.typeHandling.PersistedData; -import org.terasology.persistence.typeHandling.PersistedDataArray; import org.terasology.persistence.typeHandling.PersistedDataSerializer; import org.terasology.persistence.typeHandling.TypeHandler; -import java.util.List; import java.util.Optional; public class EntityRefTypeHandler extends TypeHandler { @@ -36,13 +33,4 @@ public Optional deserialize(PersistedData data) { } return Optional.ofNullable(EntityRef.NULL); } - - private void addEntitiesFromLongArray(List result, PersistedDataArray array) { - TLongIterator iterator = array.getAsLongArray().iterator(); - while (iterator.hasNext()) { - long item = iterator.next(); - result.add(entityManager.getEntity(item)); - } - } - } diff --git a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java index 61e802e7635..2cf69fb9a91 100644 --- a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java +++ b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java @@ -692,24 +692,10 @@ private void applyPendingImpulsesAndForces() { } } - private void addRigidBody(BulletRigidBody body) { - short filter = - (short) (btBroadphaseProxy.CollisionFilterGroups.DefaultFilter - | btBroadphaseProxy.CollisionFilterGroups.StaticFilter - | btBroadphaseProxy.CollisionFilterGroups.SensorTrigger); - insertionQueue.add(new RigidBodyRequest(body, (short) btBroadphaseProxy.CollisionFilterGroups.DefaultFilter, - filter)); - } - private void addRigidBody(BulletRigidBody body, List groups, List filter) { insertionQueue.add(new RigidBodyRequest(body, combineGroups(groups), combineGroups(filter))); } - private void addRigidBody(BulletRigidBody body, short groups, short filter) { - insertionQueue.add(new RigidBodyRequest(body, groups, - (short) (filter | btBroadphaseProxy.CollisionFilterGroups.SensorTrigger))); - } - private void removeRigidBody(BulletRigidBody body) { removalQueue.add(body); } @@ -839,7 +825,6 @@ private Collection getNewCollisionPairs() Vector3f a2 = new Vector3f(); manifoldPoint.getPositionWorldOnB(a2); - int l = manifoldPoint.getLifeTime(); Vector3f a3 = new Vector3f(); manifoldPoint.getNormalWorldOnB(a3); diff --git a/engine/src/main/java/org/terasology/engine/physics/shapes/CollisionShape.java b/engine/src/main/java/org/terasology/engine/physics/shapes/CollisionShape.java index 4601bc3631c..4248084770d 100644 --- a/engine/src/main/java/org/terasology/engine/physics/shapes/CollisionShape.java +++ b/engine/src/main/java/org/terasology/engine/physics/shapes/CollisionShape.java @@ -12,7 +12,7 @@ */ public interface CollisionShape { /** - * Returns the axis-aligned bounding box ({@link AABBfc}) of the transformed shape. + * Returns the axis-aligned bounding box ({@link org.terasology.joml.geom.AABBfc}) of the transformed shape. * * @return The {@link AABBf} bounding the shape. */ diff --git a/engine/src/main/java/org/terasology/engine/recording/EventCopier.java b/engine/src/main/java/org/terasology/engine/recording/EventCopier.java index 876c4895a3c..7c810d3ffde 100644 --- a/engine/src/main/java/org/terasology/engine/recording/EventCopier.java +++ b/engine/src/main/java/org/terasology/engine/recording/EventCopier.java @@ -89,8 +89,7 @@ public Event copyEvent(Event toBeCopied) { return newEvent; } else if (toBeCopied instanceof AttackEvent) { AttackEvent originalEvent = (AttackEvent) toBeCopied; - AttackEvent newEvent = new AttackEvent(originalEvent.getInstigator(), originalEvent.getDirectCause()); - return newEvent; + return new AttackEvent(originalEvent.getInstigator(), originalEvent.getDirectCause()); } else { return null; } diff --git a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java index 7ae9fa36766..ba3ce7607a3 100644 --- a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java +++ b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java @@ -135,7 +135,7 @@ private void fillRecordedEvents() { // send method of EventSystemImpl private void originalSend(EntityRef entity, Event event) { - if (Thread.currentThread() != mainThread) { + if (!Thread.currentThread().equals(mainThread)) { pendingEvents.offer(new PendingEvent(entity, event)); } else { networkReplicate(entity, event); @@ -155,7 +155,7 @@ private void originalSend(EntityRef entity, Event event) { // send method of EventSystemImpl private void originalSend(EntityRef entity, Event event, Component component) { - if (Thread.currentThread() != mainThread) { + if (!Thread.currentThread().equals(mainThread)) { pendingEvents.offer(new PendingEvent(entity, event, component)); } else { SetMultimap, EventSystemReplayImpl.EventHandlerInfo> handlers = diff --git a/engine/src/main/java/org/terasology/engine/recording/RecordAndReplayCurrentStatus.java b/engine/src/main/java/org/terasology/engine/recording/RecordAndReplayCurrentStatus.java index 62d7f38acc1..7593e8de83e 100644 --- a/engine/src/main/java/org/terasology/engine/recording/RecordAndReplayCurrentStatus.java +++ b/engine/src/main/java/org/terasology/engine/recording/RecordAndReplayCurrentStatus.java @@ -5,7 +5,7 @@ /** * Stores the current RecordAndReplayStatus. This class is extremely important since the status is the flag that * activates Record and Replay. - *

+ *
*

Record Workflow

When the user clicks on the "Record" button on the extras menu, the {@link #status} * is set to PREPARING_RECORD. When a game is selected to be loaded from the "Record Screen" and the game is completely * loaded, the {@link #status} will be set to RECORDING by the {@link org.terasology.engine.core.modes.loadProcesses.InitialiseRecordAndReplay} @@ -22,7 +22,7 @@ * and then every recorded data that was not stored yet will be serialized * and stored once {@link org.terasology.engine.persistence.internal.SaveTransaction}'s * saveRecordingData() method is called right after the game is saved. Once this is done, the {@link #status} is set to NOT_ACTIVATED. - *

+ *
*

Replay Workflow

When the user clicks on the "Replay" button on the extras menu, the {@link #status} * is set to PREPEARING_REPLAY. During the load process of a Replay, the {@link org.terasology.engine.core.modes.loadProcesses.InitialiseWorld} * class gets the game path from the "recordings" folder instead of the "saves" one, diff --git a/engine/src/main/java/org/terasology/engine/recording/RecordingEventSystemDecorator.java b/engine/src/main/java/org/terasology/engine/recording/RecordingEventSystemDecorator.java index 6d9a6a5e812..969db678e34 100644 --- a/engine/src/main/java/org/terasology/engine/recording/RecordingEventSystemDecorator.java +++ b/engine/src/main/java/org/terasology/engine/recording/RecordingEventSystemDecorator.java @@ -11,7 +11,7 @@ import org.terasology.gestalt.entitysystem.event.Event; /** - * Decorator for recording Events to Record&Replay subsystem. + * Decorator for recording Events to Record&Replay subsystem. */ public class RecordingEventSystemDecorator extends AbstractEventSystemDecorator { private final EventCatcher eventCatcher; @@ -26,20 +26,16 @@ public RecordingEventSystemDecorator(EventSystem eventSystem, EventCatcher event @Override public void send(EntityRef entity, Event event) { - if (currentThreadIsMain()) { - if (recordAndReplayCurrentStatus.getStatus() == RecordAndReplayStatus.RECORDING) { - eventCatcher.addEvent(new PendingEvent(entity, event)); - } + if (currentThreadIsMain() && recordAndReplayCurrentStatus.getStatus() == RecordAndReplayStatus.RECORDING) { + eventCatcher.addEvent(new PendingEvent(entity, event)); } super.send(entity, event); } @Override public void send(EntityRef entity, Event event, Component component) { - if (currentThreadIsMain()) { - if (recordAndReplayCurrentStatus.getStatus() == RecordAndReplayStatus.RECORDING) { - eventCatcher.addEvent(new PendingEvent(entity, event, component)); - } + if (currentThreadIsMain() && recordAndReplayCurrentStatus.getStatus() == RecordAndReplayStatus.RECORDING) { + eventCatcher.addEvent(new PendingEvent(entity, event, component)); } super.send(entity, event, component); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/animation/Animation.java b/engine/src/main/java/org/terasology/engine/rendering/animation/Animation.java index 1d4cb1559fe..5b92e4f3c89 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/animation/Animation.java +++ b/engine/src/main/java/org/terasology/engine/rendering/animation/Animation.java @@ -63,8 +63,7 @@ private Animation(Animator animator, float duration, RepeatMode repeatMode, Time * @return the animation */ public static Animation once(Animator animator, float duration, TimeModifier timeModifier) { - Animation anim = new Animation(animator, duration, RepeatMode.RUN_ONCE, timeModifier); - return anim; + return new Animation(animator, duration, RepeatMode.RUN_ONCE, timeModifier); } /** @@ -75,8 +74,7 @@ public static Animation once(Animator animator, float duration, TimeModifier tim * @return the animation */ public static Animation infinite(Animator animator, float duration, TimeModifier timeModifier) { - Animation anim = new Animation(animator, duration, RepeatMode.REPEAT_INFINITE, timeModifier); - return anim; + return new Animation(animator, duration, RepeatMode.REPEAT_INFINITE, timeModifier); } /** diff --git a/engine/src/main/java/org/terasology/engine/rendering/assets/mesh/ScreenQuadMeshProducer.java b/engine/src/main/java/org/terasology/engine/rendering/assets/mesh/ScreenQuadMeshProducer.java index 17010439e7a..656e9d37f53 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/assets/mesh/ScreenQuadMeshProducer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/assets/mesh/ScreenQuadMeshProducer.java @@ -43,31 +43,29 @@ public ResourceUrn redirect(ResourceUrn urn) { @Override public Optional getAssetData(ResourceUrn urn) throws IOException { - if (TerasologyConstants.ENGINE_MODULE.equals(urn.getModuleName())) { - if (SCREEN_QUAD_RESOURCE_NAME.equals(urn.getResourceName())) { - StandardMeshData data = new StandardMeshData(); - Vector3f posDest = new Vector3f(); - Vector2f uvDest = new Vector2f(); - data.position.put(posDest.set(-1.0f, -1.0f, 0.0f)); - data.position.put(posDest.set(-1.0f, 1.0f, 0.0f)); - data.position.put(posDest.set(1.0f, 1.0f, 0.0f)); - data.position.put(posDest.set(1.0f, -1.0f, 0.0f)); + if (TerasologyConstants.ENGINE_MODULE.equals(urn.getModuleName()) && SCREEN_QUAD_RESOURCE_NAME.equals(urn.getResourceName())) { + StandardMeshData data = new StandardMeshData(); + Vector3f posDest = new Vector3f(); + Vector2f uvDest = new Vector2f(); + data.position.put(posDest.set(-1.0f, -1.0f, 0.0f)); + data.position.put(posDest.set(-1.0f, 1.0f, 0.0f)); + data.position.put(posDest.set(1.0f, 1.0f, 0.0f)); + data.position.put(posDest.set(1.0f, -1.0f, 0.0f)); - data.indices.put(0); - data.indices.put(1); - data.indices.put(2); + data.indices.put(0); + data.indices.put(1); + data.indices.put(2); - data.indices.put(0); - data.indices.put(2); - data.indices.put(3); + data.indices.put(0); + data.indices.put(2); + data.indices.put(3); - data.uv0.put(uvDest.set(0.0f, 0.0f)); - data.uv0.put(uvDest.set(0.0f, 1.0f)); - data.uv0.put(uvDest.set(1.0f, 1.0f)); - data.uv0.put(uvDest.set(1.0f, 0.0f)); + data.uv0.put(uvDest.set(0.0f, 0.0f)); + data.uv0.put(uvDest.set(0.0f, 1.0f)); + data.uv0.put(uvDest.set(1.0f, 1.0f)); + data.uv0.put(uvDest.set(1.0f, 0.0f)); - return Optional.of(data); - } + return Optional.of(data); } return Optional.empty(); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java index d52b9200159..7b5663f5c09 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java @@ -101,10 +101,8 @@ public final void postInit(Context context) { public void tryBufferPairPass() { BufferPairConnection bufferPairConnection = getInputBufferPairConnection(1); - if (bufferPairConnection != null) { - if (bufferPairConnection.getData() != null) { - addOutputBufferPairConnection(1, bufferPairConnection); - } + if (bufferPairConnection != null && bufferPairConnection.getData() != null) { + addOutputBufferPairConnection(1, bufferPairConnection); } } @@ -339,9 +337,9 @@ public boolean addOutputFboConnection(int id) { /** - * Is {@code thisNode} dependent on {@param anotherNode}? + * Is {@code thisNode} dependent on {@code anotherNode}? * @param anotherNode - * @return If this node has at least one {@param anotherNode}'s connection on input - true. Otherwise false. + * @return If this node has at least one {@code anotherNode}'s connection on input - true. Otherwise false. */ public boolean isDependentOn(Node anotherNode) { boolean isDependent = false; diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/Node.java b/engine/src/main/java/org/terasology/engine/rendering/dag/Node.java index aa307f3abe2..397f378a819 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/Node.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/Node.java @@ -168,9 +168,9 @@ public interface Node extends RenderPipelineTask { void removeRunOrderConnection(int id, DependencyConnection.Type type); /** - * Is {@code thisNode} dependent on {@param anotherNode}? + * Is {@code thisNode} dependent on {@code anotherNode}? * @param anotherNode - * @return If this node has at least one {@param anotherNode}'s connection on input - true. Otherwise false. + * @return If this node has at least one {@code anotherNode}'s connection on input - true. Otherwise false. */ boolean isDependentOn(Node anotherNode); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java index 12b697c3638..8583fc992f1 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java @@ -406,11 +406,7 @@ public void connectBufferPair(Node fromNode, int outputId, Node toNode, int inpu /** * Remove previous input connection and connect a new input connection to previous output. - * @param fromNode - * @param outputId - * @param toNode - * @param inputId - + */ /*public void reconnectInputBufferPairToOutput(Node fromNode, int outputId, Node toNode, int inputId) { // for each output connection connected to input get it's connected inputs, find us and remove ourselves from its list DependencyConnection connectionToReconnect = toNode.getInputBufferPairConnection(inputId); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/BufferPairConnection.java b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/BufferPairConnection.java index 201a52379ab..14d2fb1ce7c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/BufferPairConnection.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/BufferPairConnection.java @@ -45,10 +45,6 @@ public BufferPair getBufferPair() { return super.getData(); } - public String toString() { - return super.toString(); - } - public static String getConnectionName(int number, SimpleUri nodeUri) { return new StringBuilder(nodeUri.toString()).append(":BufferPair").append(number).toString(); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/FboConnection.java b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/FboConnection.java index c98c10c1f01..3d6cc3171f0 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/FboConnection.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/FboConnection.java @@ -30,10 +30,6 @@ public FboConnection(String name, Type type, FBO data, SimpleUri parentNode) { super.setData(data); } - public String toString() { - return super.toString(); - } - public static String getConnectionName(int number, SimpleUri nodeUri) { return new StringBuilder(nodeUri.toString()).append(":FBO").append(number).toString(); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/RunOrderConnection.java b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/RunOrderConnection.java index c41558a2453..fd9683da1bf 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/RunOrderConnection.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/dependencyConnections/RunOrderConnection.java @@ -13,10 +13,6 @@ public RunOrderConnection(String name, Type type, SimpleUri parentNode) { super(name, type, parentNode); } - public String toString() { - return super.toString(); - } - public static String getConnectionName(int id, SimpleUri nodeUri) { return new StringBuilder(nodeUri.toString()).append(":RunOrder").append(id).toString(); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/gltf/GLTFMeshFormat.java b/engine/src/main/java/org/terasology/engine/rendering/gltf/GLTFMeshFormat.java index b63e674fcf4..af1d45d534d 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/gltf/GLTFMeshFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/gltf/GLTFMeshFormat.java @@ -2,11 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.rendering.gltf; -import gnu.trove.list.TFloatList; import gnu.trove.list.array.TIntArrayList; -import org.joml.Matrix4f; -import org.joml.Quaternionf; -import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.engine.rendering.assets.mesh.MeshData; @@ -15,7 +11,6 @@ import org.terasology.engine.rendering.gltf.model.GLTFAccessor; import org.terasology.engine.rendering.gltf.model.GLTFBufferView; import org.terasology.engine.rendering.gltf.model.GLTFMesh; -import org.terasology.engine.rendering.gltf.model.GLTFNode; import org.terasology.engine.rendering.gltf.model.GLTFPrimitive; import org.terasology.gestalt.assets.ResourceUrn; import org.terasology.gestalt.assets.format.AssetDataFile; @@ -108,89 +103,4 @@ public MeshData load(ResourceUrn urn, List inputs) throws IOExcep return meshData; } } - - private Matrix4f getRootTransform(GLTF gltf) { - int nodeIndex = -1; - for (int i = 0; i < gltf.getNodes().size(); i++) { - if (gltf.getNodes().get(i).getMesh() == 0) { - nodeIndex = i; - break; - } - } - - return getMatrix(gltf, nodeIndex); - } - - private void applyTransformations(GLTF gltf, TFloatList vertices, TFloatList normals) { - int nodeIndex = -1; - for (int i = 0; i < gltf.getNodes().size(); i++) { - if (gltf.getNodes().get(i).getMesh() == 0) { - nodeIndex = i; - break; - } - } - - Matrix4f transform = getMatrix(gltf, nodeIndex); - - applyTransformations(vertices, transform, false); - transform.setTranslation(new Vector3f()); - applyTransformations(normals, transform, true); - } - - private Matrix4f getMatrix(GLTF gltf, int nodeIndex) { - Matrix4f transform = new Matrix4f(); - - if (nodeIndex != -1) { - GLTFNode node = gltf.getNodes().get(nodeIndex); - if (node.getMatrix() == null) { - Vector3f position = new Vector3f(); - Quaternionf rotation = new Quaternionf(); - Vector3f scale = new Vector3f(1, 1, 1); - - if (node.getTranslation() != null) { - position.set(node.getTranslation()); - } - if (node.getRotation() != null) { - rotation.set(node.getRotation()); - } - if (node.getScale() != null) { - scale.set(node.getScale()); - } - transform.translationRotateScale(position, rotation, scale); - } else { - transform.set(node.getMatrix()); - } - - int parentNodeIndex = getParentNode(gltf, nodeIndex); - Matrix4f parentTransform = getMatrix(gltf, parentNodeIndex); - parentTransform.mul(transform); //Must be multiplied in the right order - transform.set(parentTransform); - } - - return transform; - } - - private int getParentNode(GLTF gltf, int nodeIndex) { - for (int i = 0; i < gltf.getNodes().size(); i++) { - GLTFNode curr = gltf.getNodes().get(i); - if (curr.getChildren() != null && curr.getChildren().contains(nodeIndex)) { - return i; - } - } - return -1; - } - - private void applyTransformations(TFloatList buffer, Matrix4f transform, boolean normalize) { - Vector3f current = new Vector3f(); - for (int i = 0; i < buffer.size(); i += 3) { - current.set(buffer.get(i), buffer.get(i + 1), buffer.get(i + 2)); - transform.transformPosition(current); - if (normalize) { - current.normalize(); - } - buffer.set(i, current.x()); - buffer.set(i + 1, current.y()); - buffer.set(i + 2, current.z()); - } - } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/BaseInteractionScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/BaseInteractionScreen.java index 53989439e40..865b4ff9147 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/BaseInteractionScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/BaseInteractionScreen.java @@ -18,9 +18,7 @@ public abstract class BaseInteractionScreen extends CoreScreenLayer { protected EntityRef getInteractionTarget() { EntityRef characterEntity = localPlayer.getCharacterEntity(); - CharacterComponent characterComponent = characterEntity.getComponent(CharacterComponent.class); - - return characterComponent.predictedInteractionTarget; + return characterEntity.getComponent(CharacterComponent.class).predictedInteractionTarget; } @Override diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/CoreScreenLayer.java b/engine/src/main/java/org/terasology/engine/rendering/nui/CoreScreenLayer.java index 68f6bcf337a..50b18511508 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/CoreScreenLayer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/CoreScreenLayer.java @@ -81,6 +81,7 @@ public void setDepthAuto() { } @Override + @SuppressWarnings("PMD.UselessOverridingMethod") // override elevates access modifier public void setId(String id) { super.setId(id); } @@ -98,10 +99,8 @@ public void onOpened() { if (depth == SortOrderSystem.DEFAULT_DEPTH) { setDepthAuto(); } - if (SortOrderSystem.isInitialized()) { - if (!SortOrderSystem.getUsed().contains(depth)) { - SortOrderSystem.getUsed().add(depth); - } + if (SortOrderSystem.isInitialized() && !SortOrderSystem.getUsed().contains(depth)) { + SortOrderSystem.getUsed().add(depth); } modifyingList = false; activateBindEvent = false; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/layers/NUIEditorScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/layers/NUIEditorScreen.java index f9fbc337b70..ea11760b404 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/layers/NUIEditorScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/layers/NUIEditorScreen.java @@ -61,7 +61,7 @@ /** * The main NUI editor screen. - * Contains file selection, editing & preview widgets. + * Contains file selection, editing & preview widgets. */ @SuppressWarnings("unchecked") public final class NUIEditorScreen extends AbstractEditorScreen { diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java index 7c74aeca676..268c2e64d9b 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java @@ -349,7 +349,7 @@ private Object getFieldValue(Field field, Class clazz) throws IllegalAccessExcep value = field.get(newInstance(clazz)); } - if (value != null && value instanceof Boolean) { + if (value instanceof Boolean) { value = !(Boolean) value; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java index f2c1384bbd5..e43b6f39070 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java @@ -265,11 +265,6 @@ private void closeScreen(ResourceUrn screenUri, boolean sendEvents) { } } - private void closeScreenWithoutEvent(ResourceUrn screenUri) { - boolean sendEvents = false; - closeScreen(screenUri, sendEvents); - } - @Override public ResourceUrn getUri(UIScreenLayer screen) { BiMap lookup = HashBiMap.create(screenLookup); @@ -720,20 +715,17 @@ public void mouseWheelEvent(MouseWheelEvent event, EntityRef entity) { @ReceiveEvent(components = ClientComponent.class) public void charEvent(CharEvent ev, EntityRef entity) { NUICharEvent nuiEvent = new NUICharEvent(mouse, keyboard, ev.getCharacter()); - if (focus != null) { - if (focus.onCharEvent(nuiEvent)) { - ev.consume(); - } + if (focus != null && focus.onCharEvent(nuiEvent)) { + ev.consume(); } // send event to screen stack if not yet consumed if (!ev.isConsumed()) { for (UIScreenLayer screen : screens) { - if (screen != focus) { // explicit identity check - if (screen.onCharEvent(nuiEvent)) { - ev.consume(); - break; - } + if (screen != focus && screen.onCharEvent(nuiEvent)) { + // explicit identity check + ev.consume(); + break; } if (screen.isModal()) { break; @@ -747,20 +739,17 @@ public void charEvent(CharEvent ev, EntityRef entity) { @ReceiveEvent(components = ClientComponent.class) public void keyEvent(KeyEvent ev, EntityRef entity) { NUIKeyEvent nuiEvent = new NUIKeyEvent(mouse, keyboard, ev.getKey(), ev.getState()); - if (focus != null) { - if (focus.onKeyEvent(nuiEvent)) { - ev.consume(); - } + if (focus != null && focus.onKeyEvent(nuiEvent)) { + ev.consume(); } // send event to screen stack if not yet consumed if (!ev.isConsumed()) { for (UIScreenLayer screen : screens) { - if (screen != focus) { // explicit identity check - if (screen.onKeyEvent(nuiEvent)) { - ev.consume(); - break; - } + if (screen != focus && screen.onKeyEvent(nuiEvent)) { + // explicit identity check + ev.consume(); + break; } if (screen.isModal()) { break; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/ingame/metrics/DebugMetricsSystem.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/ingame/metrics/DebugMetricsSystem.java index 4a82c26ba37..4f96b8afe2a 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/ingame/metrics/DebugMetricsSystem.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/ingame/metrics/DebugMetricsSystem.java @@ -75,7 +75,7 @@ public MetricsMode getCurrentMode() { * Iterates through the set of registered MetricsMode and returns the first instance whose method isAvailable() * returns true. Notice that this could be the MetricsMode that was current at the time this method was invoked. * - * @returns a MetricsMode instance + * @return a MetricsMode instance */ public MetricsMode toggle() { do { diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/AddServerPopup.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/AddServerPopup.java index ee616c3821c..d272c7439ed 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/AddServerPopup.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/AddServerPopup.java @@ -112,11 +112,6 @@ public void onOpened() { getManager().setFocus(nameText); } - @Override - public void onClosed() { - super.onClosed(); - } - public void setServerInfo(ServerInfo serverInfo) { this.serverInfo = serverInfo; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/GameManifestProvider.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/GameManifestProvider.java index 37f44b6b133..6ea129a913c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/GameManifestProvider.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/GameManifestProvider.java @@ -39,7 +39,7 @@ private GameManifestProvider() { /** * Generates game manifest with default settings (title, seed) if not specified. * Uses default world generator, and modules selection. - * @TODO: rewrite/fix it when code will be more stable + * TODO: rewrite/fix it when code will be more stable * * @param universeWrapper contains the universe level properties * @param moduleManager resolves modules diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/JoinGameScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/JoinGameScreen.java index e6cf83ad02a..7429eefc1c8 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/JoinGameScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/JoinGameScreen.java @@ -191,8 +191,7 @@ public boolean isLowerLayerVisible() { private void join(final String address, final int port) { Callable operation = () -> { - JoinStatus joinStatus = networkSystem.join(address, port); - return joinStatus; + return networkSystem.join(address, port); }; final WaitPopup popup = getManager().pushScreen(WaitPopup.ASSET_URI, WaitPopup.class); diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/inputSettings/UIInputBind.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/inputSettings/UIInputBind.java index 60c61d7d11c..05e5e1a1a9f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/inputSettings/UIInputBind.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/inputSettings/UIInputBind.java @@ -104,12 +104,10 @@ public void onMouseWheelEvent(NUIMouseWheelEvent event) { @Override public boolean onKeyEvent(NUIKeyEvent event) { - if (event.isDown()) { - if (capturingInput) { - setNewInput(InputType.KEY.getInput(event.getKey().getId())); - capturingInput = false; - return true; - } + if (event.isDown() && capturingInput) { + setNewInput(InputType.KEY.getInput(event.getKey().getId())); + capturingInput = false; + return true; } return false; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/GameProvider.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/GameProvider.java index e950fad2805..fb4a6853cce 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/GameProvider.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/GameProvider.java @@ -113,16 +113,16 @@ public static String getNextGameName() { * game. * *
-     *     1. "Game"    -> "Game"
-     *     2. "Game"    -> "Game 1"
-     *     3. "Game 1"  -> "Game 2"
+     *     1. "Game"    → "Game"
+     *     2. "Game"    → "Game 1"
+     *     3. "Game 1"  → "Game 2"
      * 
*

* When incrementing the number the currently highest number is incremented by one (i.e., "gaps" are not filled). * *

-     *     1. "Gooey 3"     -> "Gooey 3"
-     *     2. "Gooey"       -> "Gooey 4"
+     *     1. "Gooey 3"     → "Gooey 3"
+     *     2. "Gooey"       → "Gooey 4"
      * 
* * @param gameName will to use as game prefix, if saves contains this game name diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/NumberedGameName.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/NumberedGameName.java index efa6416f10f..aa24d1cd4b2 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/NumberedGameName.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/savedGames/NumberedGameName.java @@ -33,9 +33,9 @@ public NumberedGameName(String namePrefix, Optional number) { * * These examples will be parsed as follows: *
-     *      "Gooey's 1st Game"  -> ("Gooey's 1st Game", None)
-     *      "Gooey 42"          -> ("Gooey", Optional(42))
-     *      "42"                -> ("42", None)
+     *      "Gooey's 1st Game"  → ("Gooey's 1st Game", None)
+     *      "Gooey 42"          → ("Gooey", Optional(42))
+     *      "42"                → ("42", None)
      * 
*

* The input string will be trimmed before matching. @@ -70,9 +70,9 @@ static NumberedGameName fromString(String fullName) { * the name prefix will be returned. * *

-     *      ("Gooey's 1st Game", None)  -> "Gooey's 1st Game"
-     *      ("Gooey", Optional(42))     -> "Gooey 42"
-     *      ("42", None)                -> "42"
+     *      ("Gooey's 1st Game", None)  → "Gooey's 1st Game"
+     *      ("Gooey", Optional(42))     → "Gooey 42"
+     *      ("42", None)                → "42"
      * 
* * @return a textual representation of the numbered game version diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/settings/PlayerSettingsScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/settings/PlayerSettingsScreen.java index b86f8c6d3a7..a68d695813e 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/settings/PlayerSettingsScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/settings/PlayerSettingsScreen.java @@ -41,12 +41,6 @@ public class PlayerSettingsScreen extends CoreScreenLayer { private StorageServiceWorkerStatus storageServiceWorkerStatus; - @Override - public void onOpened() { - super.onOpened(); - } - - @Override public void initialise() { setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation()); diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/DisplayModeSetting.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/DisplayModeSetting.java index f6738f3bb71..544873af52e 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/DisplayModeSetting.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/DisplayModeSetting.java @@ -4,10 +4,12 @@ /** * Used to determine the display mode. + *
    *
  • {@link #FULLSCREEN} - Sets the screen to fullscreen and prevents the mouse from moving out of the game.
  • *
  • {@link #WINDOWED_FULLSCREEN} - Sets the screen to borderless windowed fullscreen allowing the player to move the * mouse out of the game without minimizing.
  • *
  • {@link #WINDOWED} - Sets the screen to windowed with borders allowing the player to resize the window.
  • + *
*/ public enum DisplayModeSetting { diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java index 7ef41bb9682..e63715a2972 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java @@ -147,8 +147,6 @@ private String[] createCommand(String... arguments) { * Sets the {@link UIButtonWebBrowser#url} value and sets * {@link UIButtonWebBrowser#confirmed} to true if the given URL or Hostname is * already trusted, otherwise confirmed is false. - * - * @throws MalformedURLException */ public UIButtonWebBrowser setUrl(String url) { boolean trustedHostName = false; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/basic/HTMLLikeParser.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/basic/HTMLLikeParser.java index fb441caa202..95f5a1397d7 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/basic/HTMLLikeParser.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/basic/HTMLLikeParser.java @@ -69,10 +69,9 @@ public static Collection parseHTMLLike(String text) { if (text == null) { return null; } - StringReader reader = new StringReader(text); int character; - try { + try (StringReader reader = new StringReader(text)) { StringBuilder sb = new StringBuilder(); Font font = null; Color color = null; @@ -153,6 +152,7 @@ public static Collection parseHTMLLike(String text) { if (sb.length() > 0) { result.add(new TextFlowRenderable(sb.toString(), new DefaultTextRenderStyle(font, color), hyperlink)); } + return result; } catch (IOException exp) { // Ignore - can't happen diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/HTMLDocumentHandler.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/HTMLDocumentHandler.java index 363842b606d..a390ce142d9 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/HTMLDocumentHandler.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/HTMLDocumentHandler.java @@ -32,10 +32,8 @@ public void endDocument() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { - if (currentDocumentBuilder == null) { - if (!qName.equalsIgnoreCase("body")) { - throw new HTMLParseException("Expected tag"); - } + if (currentDocumentBuilder == null && !qName.equalsIgnoreCase("body")) { + throw new HTMLParseException("Expected tag"); } processStartTag(qName, attributes); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/basic/list/UnorderedListDecorator.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/basic/list/UnorderedListDecorator.java index a19200766ba..ac692a669d8 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/basic/list/UnorderedListDecorator.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/browser/data/html/basic/list/UnorderedListDecorator.java @@ -23,9 +23,8 @@ public class UnorderedListDecorator implements ListDecorator { @Override public ParagraphData wrapParagraph(ParagraphData paragraphData) { - DefaultParagraphData defaultParagraphData = new DefaultParagraphData(paragraphData.getParagraphRenderStyle(), + return new DefaultParagraphData(paragraphData.getParagraphRenderStyle(), new UnorderedListParagraphRenderable(paragraphData)); - return defaultParagraphData; } private int getMaxIndent(Font font) { diff --git a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java index 9c31f081178..d2ccde78cf5 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java +++ b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java @@ -61,7 +61,7 @@ * This implementation works closely with a number of support objects, in particular: *

* TODO: update this section to include new, relevant objects - a RenderableWorld instance, providing acceleration - * structures caching blocks requiring different rendering treatments
+ * structures caching blocks requiring different rendering treatments
*/ public final class WorldRendererImpl implements WorldRenderer { /* diff --git a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryField.java b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryField.java index 2530553d66a..db283c4089b 100644 --- a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryField.java +++ b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryField.java @@ -11,7 +11,7 @@ /** * All telemetry fields should have this annotation. - * {@link org.terasology.engine.telemetry.metrics.Metric} finds all the telemetry fields & values via this annotation. + * {@link org.terasology.engine.telemetry.metrics.Metric} finds all telemetry fields and values via this annotation. */ @API @Target(ElementType.FIELD) diff --git a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryScreen.java b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryScreen.java index 312adbd0310..f4f58115213 100644 --- a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryScreen.java +++ b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryScreen.java @@ -50,6 +50,7 @@ public class TelemetryScreen extends CoreScreenLayer { public static final ResourceUrn ASSET_URI = new ResourceUrn("engine:telemetryScreen"); private static final Logger logger = LoggerFactory.getLogger(TelemetryScreen.class); + private static final int horizontalSpacing = 12; @In private Config config; @@ -69,7 +70,6 @@ public class TelemetryScreen extends CoreScreenLayer { @In private Emitter emitter; - private final int horizontalSpacing = 12; private Map telemetryCategories; diff --git a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryUtils.java b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryUtils.java index 47f6551ad43..ba11312e2a4 100644 --- a/engine/src/main/java/org/terasology/engine/telemetry/TelemetryUtils.java +++ b/engine/src/main/java/org/terasology/engine/telemetry/TelemetryUtils.java @@ -99,12 +99,9 @@ public static void trackMetric(Emitter emitter, String nameSpace, Unstructured e trackMetric(emitter, nameSpace, event); } else if (telemetryConfiguration.fetchBindingSize() != 0) { TelemetryCategory telemetryCategory = metric.getClass().getAnnotation(TelemetryCategory.class); - if (telemetryCategory != null) { - if (telemetryConfiguration.containsField(telemetryCategory.id())) { - if ((telemetryConfiguration.get(telemetryCategory.id()))) { - trackMetric(emitter, nameSpace, event); - } - } + if (telemetryCategory != null && telemetryConfiguration.containsField(telemetryCategory.id()) + && telemetryConfiguration.get(telemetryCategory.id())) { + trackMetric(emitter, nameSpace, event); } } return null; @@ -128,12 +125,8 @@ public static void trackMetric(Emitter emitter, String nameSpace, Unstructured e trackMetric(emitter, nameSpace, event); } else if (bindingMap.size() != 0) { TelemetryCategory telemetryCategory = metric.getClass().getAnnotation(TelemetryCategory.class); - if (telemetryCategory != null) { - if (bindingMap.containsKey(telemetryCategory.id())) { - if ((bindingMap.get(telemetryCategory.id()))) { - trackMetric(emitter, nameSpace, event); - } - } + if (telemetryCategory != null && bindingMap.containsKey(telemetryCategory.id()) && bindingMap.get(telemetryCategory.id())) { + trackMetric(emitter, nameSpace, event); } } return null; diff --git a/engine/src/main/java/org/terasology/engine/telemetry/metrics/GameConfigurationMetric.java b/engine/src/main/java/org/terasology/engine/telemetry/metrics/GameConfigurationMetric.java index ea20763760b..a5af7854715 100644 --- a/engine/src/main/java/org/terasology/engine/telemetry/metrics/GameConfigurationMetric.java +++ b/engine/src/main/java/org/terasology/engine/telemetry/metrics/GameConfigurationMetric.java @@ -80,7 +80,6 @@ private void fetchNetworkMode() { } private void fetchConfig() { - Config config = context.get(Config.class); SystemConfig systemConfig = context.get(SystemConfig.class); language = systemConfig.locale.get().toString(); diff --git a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskMaster.java b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskMaster.java index 858f6de5112..27cf0fd9119 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskMaster.java +++ b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskMaster.java @@ -30,7 +30,7 @@ *

* When you create a TaskMaster, it is important to shut it down after you're finished with it, generally in the * shutdown method of a ComponentSystem. A basic usage example follows: - *

+ *
*

  * {@literal
  * TaskMaster taskMaster = TaskMaster.createFIFOTaskMaster("MyTaskMaster", 1);
@@ -144,11 +144,9 @@ public void restart() {
     /**
      * Get the {@link ExecutorService} underlying this TaskMaster. Note that by default the service will have a
      * {@link TaskProcessor} enqueued for each thread. In order to use the ExecutorService directly you will need to
-     * {@method offer} a {@link ShutdownTask} as shown:
+     * {@link TaskMaster#offer(Task)} a {@link ShutdownTask} as shown:
      * 

- * {@code - * taskMaster.offer(new ShutdownTask()); - * } + * {@code taskMaster.offer(new ShutdownTask());} * @return the {@link ExecutorService} used by this instance */ public ExecutorService getExecutorService() { diff --git a/engine/src/main/java/org/terasology/engine/utilities/modifiable/ModifiableValue.java b/engine/src/main/java/org/terasology/engine/utilities/modifiable/ModifiableValue.java index 1e9bca48e71..9308500b775 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/modifiable/ModifiableValue.java +++ b/engine/src/main/java/org/terasology/engine/utilities/modifiable/ModifiableValue.java @@ -49,11 +49,9 @@ public ModifiableValue postAdd(float amount) { * Calculates the result value from the base value and given modifiers and multiplier. *

* The value is calculated based on the following formula: - *

 {@code
-     *      result = ( + Σ ) * Π  + Σ 
-     * } 
+ * {@code result = ( + Σ ) * Π + Σ } * - * non-negativity of the value is not ensured and must be checked by the system if needed + * non-negativity of the value is not ensured and must be checked by the system if needed */ public float getValue() { return (baseValue + preModifier) * multiplier + postModifier; diff --git a/engine/src/main/java/org/terasology/engine/utilities/procedural/HeightmapFileReader.java b/engine/src/main/java/org/terasology/engine/utilities/procedural/HeightmapFileReader.java index 8457d9b7996..07ca710ee4e 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/procedural/HeightmapFileReader.java +++ b/engine/src/main/java/org/terasology/engine/utilities/procedural/HeightmapFileReader.java @@ -66,30 +66,28 @@ public static float[][] readFile() throws IOException { public static float[][] readValues(java.io.InputStream in, String delimiter) throws java.io.IOException, java.lang.NumberFormatException { String thisLine; - java.io.BufferedInputStream s = new java.io.BufferedInputStream(in); - java.io.BufferedReader myInput = new java.io.BufferedReader(new java.io.InputStreamReader(s, Charsets.UTF_8)); - int index = 0; float min = 0; float max = 0; float[][] theMap = new float[512][512]; - while ((thisLine = myInput.readLine()) != null) { - - // scan it line by line - java.util.StringTokenizer st = new java.util.StringTokenizer(thisLine, delimiter); - float a = Float.valueOf(st.nextToken()); - theMap[index / 512][index % 512] = a; - index++; - min = a < min ? a : min; - max = a > max ? a : max; - if (index / 512 > 511) { - break; + try (java.io.BufferedInputStream s = new java.io.BufferedInputStream(in); + java.io.BufferedReader myInput = new java.io.BufferedReader(new java.io.InputStreamReader(s, Charsets.UTF_8))) { + while ((thisLine = myInput.readLine()) != null) { + + // scan it line by line + java.util.StringTokenizer st = new java.util.StringTokenizer(thisLine, delimiter); + float a = Float.valueOf(st.nextToken()); + theMap[index / 512][index % 512] = a; + index++; + min = a < min ? a : min; + max = a > max ? a : max; + if (index / 512 > 511) { + break; + } } } -// System.out.println("min " + min); -// System.out.println("max " + max); return (theMap); } } diff --git a/engine/src/main/java/org/terasology/engine/utilities/tree/SpaceTree.java b/engine/src/main/java/org/terasology/engine/utilities/tree/SpaceTree.java index d757125098d..7f17d431c40 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/tree/SpaceTree.java +++ b/engine/src/main/java/org/terasology/engine/utilities/tree/SpaceTree.java @@ -197,10 +197,9 @@ private void executeSearchInNode(float[] position, Node node, TreeSearch tree } for (Node subNode : node.subNodes) { - if (subNode != null) { - if (distanceFunction.getPointRegionDistance(position, subNode.minValues, subNode.maxValues) <= treeSearch.maxDistance) { - executeSearchInNode(position, subNode, treeSearch); - } + if (subNode != null && distanceFunction.getPointRegionDistance(position, subNode.minValues, subNode.maxValues) + <= treeSearch.maxDistance) { + executeSearchInNode(position, subNode, treeSearch); } } } else { @@ -358,10 +357,8 @@ private int getSubNodeIndex(float[] position, float[] center) { increment *= 2; } - if (index == 0) { - if (distanceFunction.getDistance(position, center) == 0) { - return -1; - } + if (index == 0 && distanceFunction.getDistance(position, center) == 0) { + return -1; } return index; } diff --git a/engine/src/main/java/org/terasology/engine/world/block/BlockAreac.java b/engine/src/main/java/org/terasology/engine/world/block/BlockAreac.java index 81a307170f8..60f80459390 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/BlockAreac.java +++ b/engine/src/main/java/org/terasology/engine/world/block/BlockAreac.java @@ -235,8 +235,8 @@ default Vector2i getSize(Vector2i dest) { /** * Set the size of the block area from the minimum corner. * - * @param x the x coordinate to set the size; must be > 0 - * @param y the y coordinate to set the size; must be > 0 + * @param x the x coordinate to set the size; must be greater than 0 + * @param y the y coordinate to set the size; must be greater than 0 * @param dest destination; will hold the result * @return {@code dest} (after modification) * @throws IllegalArgumentException if the size is smaller than or equal to 0 in any dimension @@ -246,7 +246,7 @@ default Vector2i getSize(Vector2i dest) { /** * Set the size of the block area from the minimum corner. * - * @param size the size to set; all dimensions must be > 0 + * @param size the size to set; all dimensions must be greater than 0 * @param dest destination; will hold the result * @return {@code dest} (after modification) * @throws IllegalArgumentException if the size is smaller than or equal to 0 in any dimension @@ -335,7 +335,7 @@ default BlockArea union(Vector2ic pos, BlockArea dest) { * * @param other {@link BlockArea} * @param dest destination; will hold the result - * @return @code dest} (after modification) + * @return dest (after modification) */ default BlockArea union(BlockAreac other, BlockArea dest) { return this.union(other.minX(), other.minY(), dest) diff --git a/engine/src/main/java/org/terasology/engine/world/block/BlockRegionc.java b/engine/src/main/java/org/terasology/engine/world/block/BlockRegionc.java index c62225ec0b7..0f526a5f024 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/BlockRegionc.java +++ b/engine/src/main/java/org/terasology/engine/world/block/BlockRegionc.java @@ -280,9 +280,9 @@ default Vector3i getSize(Vector3i dest) { /** * Set the size of the block region from the minimum corner. * - * @param x the x coordinate to set the size; must be > 0 - * @param y the y coordinate to set the size; must be > 0 - * @param z the z coordinate to set the size; must be > + * @param x the x coordinate to set the size; must be greater than 0 + * @param y the y coordinate to set the size; must be greater than 0 + * @param z the z coordinate to set the size; must be greater than 0 * @param dest destination; will hold the result * @return {@code dest} (after modification) * @throws IllegalArgumentException if the size is smaller than or equal to 0 in any dimension @@ -292,7 +292,7 @@ default Vector3i getSize(Vector3i dest) { /** * Set the size of the block region from the minimum corner. * - * @param size the size to set; all dimensions must be > 0 + * @param size the size to set; all dimensions must be greater than 0 * @param dest destination; will hold the result * @return {@code dest} (after modification) * @throws IllegalArgumentException if the size is smaller than or equal to 0 in any dimension @@ -386,7 +386,7 @@ default BlockRegion union(Vector3ic pos, BlockRegion dest) { * * @param other {@link BlockRegion} * @param dest destination; will hold the result - * @return @code dest} (after modification) + * @return dest (after modification) */ default BlockRegion union(BlockRegionc other, BlockRegion dest) { return this.union(other.minX(), other.minY(), other.minZ(), dest) diff --git a/engine/src/main/java/org/terasology/engine/world/block/family/AbstractBlockFamily.java b/engine/src/main/java/org/terasology/engine/world/block/family/AbstractBlockFamily.java index 8acea8be9eb..52876e01b00 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/family/AbstractBlockFamily.java +++ b/engine/src/main/java/org/terasology/engine/world/block/family/AbstractBlockFamily.java @@ -3,10 +3,10 @@ package org.terasology.engine.world.block.family; import com.google.common.collect.Sets; -import org.terasology.engine.world.block.loader.BlockFamilyDefinition; -import org.terasology.engine.world.block.shapes.BlockShape; import org.terasology.engine.world.block.BlockBuilderHelper; import org.terasology.engine.world.block.BlockUri; +import org.terasology.engine.world.block.loader.BlockFamilyDefinition; +import org.terasology.engine.world.block.shapes.BlockShape; import java.util.Locale; import java.util.Set; diff --git a/engine/src/main/java/org/terasology/engine/world/block/family/AttachedToSurfaceFamily.java b/engine/src/main/java/org/terasology/engine/world/block/family/AttachedToSurfaceFamily.java index 1cbef39ea7c..8f41b01a5a4 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/family/AttachedToSurfaceFamily.java +++ b/engine/src/main/java/org/terasology/engine/world/block/family/AttachedToSurfaceFamily.java @@ -6,12 +6,12 @@ import org.terasology.engine.math.Pitch; import org.terasology.engine.math.Rotation; import org.terasology.engine.math.Side; -import org.terasology.engine.world.block.loader.BlockFamilyDefinition; -import org.terasology.engine.world.block.shapes.BlockShape; -import org.terasology.gestalt.naming.Name; import org.terasology.engine.world.block.Block; import org.terasology.engine.world.block.BlockBuilderHelper; import org.terasology.engine.world.block.BlockUri; +import org.terasology.engine.world.block.loader.BlockFamilyDefinition; +import org.terasology.engine.world.block.shapes.BlockShape; +import org.terasology.gestalt.naming.Name; import java.util.Locale; import java.util.Map; diff --git a/engine/src/main/java/org/terasology/engine/world/block/family/MultiConnectFamily.java b/engine/src/main/java/org/terasology/engine/world/block/family/MultiConnectFamily.java index 1ba2a445c5e..2a5293af8b6 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/family/MultiConnectFamily.java +++ b/engine/src/main/java/org/terasology/engine/world/block/family/MultiConnectFamily.java @@ -54,7 +54,6 @@ public MultiConnectFamily(BlockFamilyDefinition definition, BlockShape shape, Bl * Constructor for a regular block * * @param definition Family definition - * @param blockBuilder The builder to make the blocks for the family */ public MultiConnectFamily(BlockFamilyDefinition definition, BlockBuilderHelper blockBuilder) { super(definition, blockBuilder); diff --git a/engine/src/main/java/org/terasology/engine/world/block/loader/BlockFamilyDefinitionData.java b/engine/src/main/java/org/terasology/engine/world/block/loader/BlockFamilyDefinitionData.java index 14a8f7a91e3..38e63e6a4e4 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/loader/BlockFamilyDefinitionData.java +++ b/engine/src/main/java/org/terasology/engine/world/block/loader/BlockFamilyDefinitionData.java @@ -4,9 +4,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import org.terasology.engine.world.block.family.AbstractBlockFamily; import org.terasology.gestalt.assets.AssetData; import org.terasology.gestalt.module.sandbox.API; -import org.terasology.engine.world.block.family.AbstractBlockFamily; import java.util.List; import java.util.Map; diff --git a/engine/src/main/java/org/terasology/engine/world/block/shapes/JsonBlockShapeLoader.java b/engine/src/main/java/org/terasology/engine/world/block/shapes/JsonBlockShapeLoader.java index 4b8ee4066d5..3190d043826 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/shapes/JsonBlockShapeLoader.java +++ b/engine/src/main/java/org/terasology/engine/world/block/shapes/JsonBlockShapeLoader.java @@ -123,10 +123,8 @@ private void processCollision(JsonDeserializationContext context, BlockShapeData } if (collisionInfo.has(SYMMETRIC) && collisionInfo.get(SYMMETRIC).isJsonPrimitive() - && collisionInfo.get(SYMMETRIC).getAsJsonPrimitive().isBoolean()) { - if (collisionInfo.get(SYMMETRIC).getAsBoolean()) { - shape.setCollisionSymmetric(true); - } + && collisionInfo.get(SYMMETRIC).getAsJsonPrimitive().isBoolean() && collisionInfo.get(SYMMETRIC).getAsBoolean()) { + shape.setCollisionSymmetric(true); } if (collisionInfo.has(CONVEX_HULL) && collisionInfo.get(CONVEX_HULL).isJsonPrimitive() diff --git a/engine/src/main/java/org/terasology/engine/world/block/structure/AttachSupportRequired.java b/engine/src/main/java/org/terasology/engine/world/block/structure/AttachSupportRequired.java index 584520ad008..cb0715da5eb 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/structure/AttachSupportRequired.java +++ b/engine/src/main/java/org/terasology/engine/world/block/structure/AttachSupportRequired.java @@ -36,13 +36,8 @@ public boolean shouldBeRemovedDueToChange(Vector3i location, Side sideChanged) { private boolean hasRequiredSupportOnSideForBlock(Vector3ic location, Side sideChanged, Block block) { final BlockMeshPart part = block.getPrimaryAppearance().getPart(BlockPart.fromSide(sideChanged)); - if (part != null) { - // This block has mesh on this side, therefore it requires a support on that side - if (!hasSupportFromBlockOnSide(location, sideChanged, Collections.emptyMap())) { - return false; - } - } - return true; + // This block has mesh on this side, therefore it requires a support on that side + return part == null || hasSupportFromBlockOnSide(location, sideChanged, Collections.emptyMap()); } @Override diff --git a/engine/src/main/java/org/terasology/engine/world/block/structure/SideBlockSupportRequired.java b/engine/src/main/java/org/terasology/engine/world/block/structure/SideBlockSupportRequired.java index cc265e397c7..0fae063821e 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/structure/SideBlockSupportRequired.java +++ b/engine/src/main/java/org/terasology/engine/world/block/structure/SideBlockSupportRequired.java @@ -52,12 +52,11 @@ public boolean shouldBeRemovedDueToChange(Vector3i location, Side sideChanged) { @ReceiveEvent public void checkForSupport(DelayedActionTriggeredEvent event, EntityRef entity, BlockComponent block, SideBlockSupportRequiredComponent supportRequired) { - if (event.getActionId().equals(SUPPORT_CHECK_ACTION_ID)) { - if (!isSufficientlySupported(block.getPosition(), null, Collections.emptyMap(), supportRequired)) { - PrefabManager prefabManager = CoreRegistry.get(PrefabManager.class); - entity.send(new DestroyEvent(entity, EntityRef.NULL, prefabManager.getPrefab("engine" + - ":supportRemovedDamage"))); - } + if (event.getActionId().equals(SUPPORT_CHECK_ACTION_ID) + && !isSufficientlySupported(block.getPosition(), null, Collections.emptyMap(), supportRequired)) { + PrefabManager prefabManager = CoreRegistry.get(PrefabManager.class); + entity.send(new DestroyEvent(entity, EntityRef.NULL, prefabManager.getPrefab("engine" + + ":supportRemovedDamage"))); } } diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/LodChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/LodChunkProvider.java index dc61fa4a5e8..6647b193d0a 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/LodChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/LodChunkProvider.java @@ -283,15 +283,6 @@ public void shutdown() { } } - /** - * Make the chunk a bit darker, so that it can be visually distinguished from an ordinary chunk. - */ - private void tintChunk(Chunk chunk) { - for (Vector3ic pos : Chunks.CHUNK_REGION) { - chunk.setSunlight(pos, (byte) (0.75f * chunk.getSunlight(pos))); - } - } - public int getChunkLods() { return chunkLods; } diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java index 662a1e1e3ab..6668963d894 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java @@ -32,15 +32,15 @@ * public static method annotated with @RegisterExtraData which determines, for each block, * whether the field is applicable for that block. For example: * - * {@code - * @ExtraDataSystem + *
+ * {@code @ExtraDataSystem}
  * public class ExampleExtraDataSystem {
- *     @RegisterExtraData(name="exampleModule.grassNutrients", bitSize=8)
+ *     {@code @RegisterExtraData(name="exampleModule.grassNutrients", bitSize=8)}
  *     public static boolean shouldHaveNutrients(Block block) {
  *         return block.isGrass();
  *     }
  *  }
- *  }
+ * 
*/ @API public class ExtraBlockDataManager { diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/RegisterExtraData.java b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/RegisterExtraData.java index 063e2d6b43f..91034e8bc46 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/RegisterExtraData.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/RegisterExtraData.java @@ -15,12 +15,12 @@ * These must be inside classes annotated with {@link ExtraDataSystem}. * The valid values for bitSize are 4, 8 and 16. * The correct format is - * {@code - * @RegisterExtraData(name="exampleModule.grassNutrients", bitSize=8) + *
+ * {@code @RegisterExtraData(name="exampleModule.grassNutrients", bitSize=8)}
  * public static boolean shouldHaveNutrients(Block block) {
  *     return block.isGrass();
  * }
- * }.
+ * 
*/ @API @Retention(RetentionPolicy.RUNTIME) diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/internal/ChunkSerializer.java b/engine/src/main/java/org/terasology/engine/world/chunks/internal/ChunkSerializer.java index ff70a97e914..177c2e6a09c 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/internal/ChunkSerializer.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/internal/ChunkSerializer.java @@ -3,19 +3,15 @@ package org.terasology.engine.world.chunks.internal; import com.google.common.base.Preconditions; -import com.google.protobuf.ByteString; -import gnu.trove.list.TByteList; -import gnu.trove.list.array.TByteArrayList; import org.joml.Vector3i; import org.joml.Vector3ic; +import org.terasology.engine.world.block.BlockManager; +import org.terasology.engine.world.chunks.Chunk; +import org.terasology.engine.world.chunks.Chunks; import org.terasology.engine.world.chunks.blockdata.ExtraBlockDataManager; import org.terasology.engine.world.chunks.blockdata.TeraArray; import org.terasology.engine.world.chunks.blockdata.TeraDenseArray16Bit; -import org.terasology.engine.world.chunks.blockdata.TeraDenseArray8Bit; import org.terasology.protobuf.EntityData; -import org.terasology.engine.world.block.BlockManager; -import org.terasology.engine.world.chunks.Chunk; -import org.terasology.engine.world.chunks.Chunks; public final class ChunkSerializer { @@ -76,34 +72,6 @@ private static EntityData.RunLengthEncoding16 runLengthEncode16(TeraArray array) return builder.build(); } - private static EntityData.RunLengthEncoding8 runLengthEncode8(TeraArray array) { - EntityData.RunLengthEncoding8.Builder builder = EntityData.RunLengthEncoding8.newBuilder(); - TByteList values = new TByteArrayList(16384); - byte lastItem = (byte) array.get(0, 0, 0); - int counter = 0; - for (int y = 0; y < array.getSizeY(); ++y) { - for (int z = 0; z < array.getSizeZ(); ++z) { - for (int x = 0; x < array.getSizeX(); ++x) { - byte item = (byte) array.get(x, y, z); - if (lastItem != item) { - builder.addRunLengths(counter); - values.add(lastItem); - lastItem = item; - counter = 1; - } else { - counter++; - } - } - } - } - if (lastItem != 0) { - builder.addRunLengths(counter); - values.add(lastItem); - } - builder.setValues(ByteString.copyFrom(values.toArray())); - return builder.build(); - } - private static TeraArray runLengthDecode(EntityData.RunLengthEncoding16 data) { Preconditions.checkState(data.getValuesCount() == data.getRunLengthsCount(), "Expected same number of values as runs"); short[] decodedData = new short[Chunks.SIZE_X * Chunks.SIZE_Y * Chunks.SIZE_Z]; @@ -118,21 +86,6 @@ private static TeraArray runLengthDecode(EntityData.RunLengthEncoding16 data) { return new TeraDenseArray16Bit(Chunks.SIZE_X, Chunks.SIZE_Y, Chunks.SIZE_Z, decodedData); } - private static TeraArray runLengthDecode(EntityData.RunLengthEncoding8 data) { - Preconditions.checkState(data.getValues().size() == data.getRunLengthsCount(), "Expected same number of values as runs"); - byte[] decodedData = new byte[Chunks.SIZE_X * Chunks.SIZE_Y * Chunks.SIZE_Z]; - int index = 0; - ByteString.ByteIterator valueSource = data.getValues().iterator(); - for (int pos = 0; pos < data.getRunLengthsCount(); ++pos) { - int length = data.getRunLengths(pos); - byte value = valueSource.nextByte(); - for (int i = 0; i < length; ++i) { - decodedData[index++] = value; - } - } - return new TeraDenseArray8Bit(Chunks.SIZE_X, Chunks.SIZE_Y, Chunks.SIZE_Z, decodedData); - } - /** * Decode compressed data into an existing TeraArray. * Generic w.r.t. TeraArray subclasses, allowing the data to be used for any type of TeraArray. diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java index 01083e30437..e8a93093244 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java @@ -62,22 +62,22 @@ * Provides chunks. Chunks placed in this JVM. Also generated Chunks if needed. *

* Loading/Unload chunks dependent on {@link RelevanceSystem} - *

+ *

* Produces events: *

* {@link OnChunkGenerated} when chunk was generated {@link WorldGenerator} *

* {@link OnChunkLoaded} when chunk was loaded from {@link StorageManager} *

- * {@link OnActivatedBlocks} when load/generate chunk and chunk have blocks with lifecycle (?) {@see - * https://github.com/MovingBlocks/Terasology/issues/3244} + * {@link OnActivatedBlocks} when load/generate chunk and chunk have blocks with lifecycle *

- * {@link OnAddedBlocks} when load/generate chunk and chunk have blocks with lifecycle (?) {@see - * https://github.com/MovingBlocks/Terasology/issues/3244} + * {@link OnAddedBlocks} when load/generate chunk and chunk have blocks with lifecycle (?) *

* {@link BeforeChunkUnload} when chunk ready to remove from provider. *

* {@link BeforeDeactivateBlocks} when chunk ready to remove and have block lifecycle. + *

+ * @see Terasology Issue 3244 */ public class LocalChunkProvider implements ChunkProvider { diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/remoteChunkProvider/RemoteChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/remoteChunkProvider/RemoteChunkProvider.java index 463a2837a2c..caa369aa772 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/remoteChunkProvider/RemoteChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/remoteChunkProvider/RemoteChunkProvider.java @@ -41,7 +41,7 @@ * Provides chunks received from remote source. *

* Loading/Unload chunks dependent on {@link org.terasology.engine.network.Server} - *

+ *

* Produce events: *

* {@link OnChunkLoaded} when chunk received from server and processed. diff --git a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java index 120f070875f..4152d645ea3 100644 --- a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java +++ b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java @@ -239,11 +239,10 @@ private void addProviderChain(Class facet, boolean scalabl } for (FacetProvider provider : providersList) { - if (updatesFacet(provider, facet) && (!scalable || provider instanceof ScalableFacetProvider)) { - if (updatePriority(provider, facet) > minPriority) { - providedBy.put(facet, provider); - addRequirements(facet, provider, scalable, orderedProviders); - } + if (updatesFacet(provider, facet) && (!scalable || provider instanceof ScalableFacetProvider) + && updatePriority(provider, facet) > minPriority) { + providedBy.put(facet, provider); + addRequirements(facet, provider, scalable, orderedProviders); } } } @@ -413,7 +412,6 @@ public FacetedWorldConfigurator createConfigurator() { configurables.add((ConfigurableFacetProvider) facetProvider); } } - FacetedWorldConfigurator worldConfigurator = new FacetedWorldConfigurator(configurables); - return worldConfigurator; + return new FacetedWorldConfigurator(configurables); } } diff --git a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java index 14150fdecfd..832498c5a8e 100644 --- a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java +++ b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java @@ -159,12 +159,7 @@ private static WorldGenerator loadGenerator(Class generatorClass, SimpleUri u private static boolean isValidWorldGenerator(Class generatorClass) { try { - if (WorldGenerator.class.isAssignableFrom(generatorClass)) { - if (generatorClass.getConstructor(SimpleUri.class) != null) { - return true; - } - } - return false; + return WorldGenerator.class.isAssignableFrom(generatorClass) && generatorClass.getConstructor(SimpleUri.class) != null; // Being generous in catching here, because if the module is broken due to code changes or missing classes // the world generator is invalid } catch (NoSuchMethodException | RuntimeException e) { diff --git a/engine/src/main/java/org/terasology/engine/world/internal/EntityAwareWorldProvider.java b/engine/src/main/java/org/terasology/engine/world/internal/EntityAwareWorldProvider.java index b05fe13349e..97c24c58563 100644 --- a/engine/src/main/java/org/terasology/engine/world/internal/EntityAwareWorldProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/internal/EntityAwareWorldProvider.java @@ -247,10 +247,8 @@ private boolean isTemporaryBlock(ComponentContainer entity, Block block, Class metadata : entityManager.getComponentLibrary().iterateComponentMetadata()) { - if (metadata.isForceBlockActive() && ignoreComponent != metadata.getType()) { - if (entity.hasComponent(metadata.getType())) { - return false; - } + if (metadata.isForceBlockActive() && ignoreComponent != metadata.getType() && entity.hasComponent(metadata.getType())) { + return false; } } return true; diff --git a/engine/src/main/java/org/terasology/engine/world/internal/WorldProviderCore.java b/engine/src/main/java/org/terasology/engine/world/internal/WorldProviderCore.java index 79dbbe42c4d..befc5b09a41 100644 --- a/engine/src/main/java/org/terasology/engine/world/internal/WorldProviderCore.java +++ b/engine/src/main/java/org/terasology/engine/world/internal/WorldProviderCore.java @@ -97,7 +97,7 @@ public interface WorldProviderCore { /** * Places all given blocks of specific types at their corresponding positions - *

+ *

* Chunks are * * @param blocks A mapping from world position to change to the type of block to set diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/TileThreadFactory.java b/engine/src/main/java/org/terasology/engine/world/viewer/TileThreadFactory.java index 24e9c5d8475..4cf0ccd5b63 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/TileThreadFactory.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/TileThreadFactory.java @@ -11,8 +11,8 @@ */ public class TileThreadFactory implements ThreadFactory { + private static final String namePrefix = "TileThreadPool-thread-"; private final AtomicInteger threadNumber = new AtomicInteger(1); - private final String namePrefix = "TileThreadPool-thread-"; @Override public Thread newThread(Runnable r) { diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderArgb.java b/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderArgb.java index e51eaaf66f5..8688c57752a 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderArgb.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderArgb.java @@ -41,7 +41,6 @@ public int blend(int src, int dst) { int mg = (a * sg + (0xFF - a) * dg) / 0xFF; int mr = (a * sr + (0xFF - a) * dr) / 0xFF; - int mix = 0xFF000000 | mb | (mg << 8) | (mr << 16); - return mix; + return 0xFF000000 | mb | (mg << 8) | (mr << 16); } } diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderRgba.java b/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderRgba.java index 41134b17491..fde5aa45557 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderRgba.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/color/ColorBlenderRgba.java @@ -46,7 +46,6 @@ public int blend(int src, int dst) { int mg = (a * sg + (0xFF - a) * dg) / 0xFF; int mr = (a * sr + (0xFF - a) * dr) / 0xFF; - int mix = (mb << 8) | (mg << 16) | (mr << 24) | 0xFF; - return mix; + return (mb << 8) | (mg << 16) | (mr << 24) | 0xFF; } } diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/picker/CirclePickerClosest.java b/engine/src/main/java/org/terasology/engine/world/viewer/picker/CirclePickerClosest.java index c3979bc5c26..2271c1375eb 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/picker/CirclePickerClosest.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/picker/CirclePickerClosest.java @@ -47,11 +47,9 @@ public void offer(float locX, float locY, T object) { float distSq = dx * dx + dy * dy; float rad = radiusFunc.apply(object).floatValue(); - if (distSq < rad * rad) { - if (distSq < minDistSq) { - minDistSq = distSq; - closest = object; - } + if (distSq < rad * rad && distSq < minDistSq) { + minDistSq = distSq; + closest = object; } } diff --git a/subsystems/TypeHandlerLibrary/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java b/subsystems/TypeHandlerLibrary/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java index 519ed719f0d..8cf6faa9944 100644 --- a/subsystems/TypeHandlerLibrary/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java +++ b/subsystems/TypeHandlerLibrary/src/main/java/org/terasology/persistence/typeHandling/coreTypes/ObjectFieldMapTypeHandler.java @@ -20,7 +20,7 @@ import java.util.Optional; /** - * Serializes objects as a fieldName -> fieldValue map. It is used as the last resort while serializing an + * Serializes objects as a fieldName → fieldValue map. It is used as the last resort while serializing an * object through a {@link TypeHandlerLibrary}. */ public class ObjectFieldMapTypeHandler extends TypeHandler {