Search in sources :

Example 1 with FastRandom

use of org.terasology.engine.utilities.random.FastRandom in project Terasology by MovingBlocks.

the class TextureAssetResolverTest method testColorTextures.

@Test
public void testColorTextures() {
    Random r = new FastRandom(123456);
    for (int i = 0; i < 10; i++) {
        int rgba = r.nextInt();
        Color red = new Color(rgba);
        ResourceUrn textureUriForColor = TextureUtil.getTextureUriForColor(red);
        String simpleString = textureUriForColor.toString();
        Optional<Texture> tex = Assets.getTexture(simpleString);
        assertTrue(tex.isPresent());
        ByteBuffer dataBuffer = tex.get().getData().getBuffers()[0];
        int firstPixel = dataBuffer.asIntBuffer().get(0);
        assertEquals(rgba, firstPixel);
    }
}
Also used : Random(org.terasology.engine.utilities.random.Random) FastRandom(org.terasology.engine.utilities.random.FastRandom) Color(org.terasology.nui.Color) FastRandom(org.terasology.engine.utilities.random.FastRandom) ResourceUrn(org.terasology.gestalt.assets.ResourceUrn) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.jupiter.api.Test)

Example 2 with FastRandom

use of org.terasology.engine.utilities.random.FastRandom in project Terasology by MovingBlocks.

the class TextureDataFactory method createWhiteNoiseTexture.

public static TextureData createWhiteNoiseTexture(int size, long seed, int min, int max) {
    int width = size;
    int height = size;
    ByteBuffer data = ByteBuffer.allocateDirect(4 * width * height);
    Random rng = new FastRandom(seed);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            data.put((byte) TeraMath.clamp(rng.nextInt(min, max), 0, 255));
            data.put((byte) TeraMath.clamp(rng.nextInt(min, max), 0, 255));
            data.put((byte) TeraMath.clamp(rng.nextInt(min, max), 0, 255));
            data.put((byte) 255);
        }
    }
    // The buffer must be reset back to the initial position before passing it onward.
    data.rewind();
    return new TextureData(width, height, new ByteBuffer[] { data }, WrapMode.REPEAT, FilterMode.NEAREST);
}
Also used : Random(org.terasology.engine.utilities.random.Random) FastRandom(org.terasology.engine.utilities.random.FastRandom) FastRandom(org.terasology.engine.utilities.random.FastRandom) ByteBuffer(java.nio.ByteBuffer)

Example 3 with FastRandom

use of org.terasology.engine.utilities.random.FastRandom in project Terasology by MovingBlocks.

the class PlayerConfig method defaultPlayerColor.

/**
 * Randomly generates a default color for the player via a random int generator using FastRandom object.
 *
 * @return a Color object with the player's default color.
 */
private Color defaultPlayerColor() {
    Random rng = new FastRandom();
    List<Color> colors = CieCamColors.L65C65;
    return colors.get(rng.nextInt(colors.size()));
}
Also used : Random(org.terasology.engine.utilities.random.Random) FastRandom(org.terasology.engine.utilities.random.FastRandom) Color(org.terasology.nui.Color) FastRandom(org.terasology.engine.utilities.random.FastRandom)

Example 4 with FastRandom

use of org.terasology.engine.utilities.random.FastRandom in project Terasology by MovingBlocks.

the class InitialiseWorld method step.

@Override
public boolean step() {
    BlockManager blockManager = context.get(BlockManager.class);
    ExtraBlockDataManager extraDataManager = context.get(ExtraBlockDataManager.class);
    ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment();
    context.put(WorldGeneratorPluginLibrary.class, new DefaultWorldGeneratorPluginLibrary(environment, context));
    WorldInfo worldInfo = gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD);
    verify(worldInfo.getWorldGenerator().isValid(), "Game manifest did not specify world type.");
    if (worldInfo.getSeed() == null || worldInfo.getSeed().isEmpty()) {
        FastRandom random = new FastRandom();
        worldInfo.setSeed(random.nextString(16));
    }
    logger.info("World seed: \"{}\"", worldInfo.getSeed());
    // TODO: Separate WorldRenderer from world handling in general
    WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class);
    WorldGenerator worldGenerator;
    try {
        worldGenerator = WorldGeneratorManager.createGenerator(worldInfo.getWorldGenerator(), context);
        // setting the world seed will create the world builder
        worldGenerator.setWorldSeed(worldInfo.getSeed());
        context.put(WorldGenerator.class, worldGenerator);
    } catch (UnresolvedWorldGeneratorException e) {
        logger.error("Unable to load world generator {}. Available world generators: {}", worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators());
        context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator."));
        // We need to return true, otherwise the loading state will just call us again immediately
        return true;
    }
    // Init. a new world
    EngineEntityManager entityManager = (EngineEntityManager) context.get(EntityManager.class);
    boolean writeSaveGamesEnabled = context.get(SystemConfig.class).writeSaveGamesEnabled.get();
    // Gets save data from a normal save or from a recording if it is a replay
    Path saveOrRecordingPath = getSaveOrRecordingPath();
    StorageManager storageManager;
    RecordAndReplaySerializer recordAndReplaySerializer = context.get(RecordAndReplaySerializer.class);
    RecordAndReplayUtils recordAndReplayUtils = context.get(RecordAndReplayUtils.class);
    RecordAndReplayCurrentStatus recordAndReplayCurrentStatus = context.get(RecordAndReplayCurrentStatus.class);
    try {
        storageManager = writeSaveGamesEnabled ? new ReadWriteStorageManager(saveOrRecordingPath, environment, entityManager, blockManager, extraDataManager, recordAndReplaySerializer, recordAndReplayUtils, recordAndReplayCurrentStatus) : new ReadOnlyStorageManager(saveOrRecordingPath, environment, entityManager, blockManager, extraDataManager);
    } catch (IOException e) {
        logger.error("Unable to create storage manager!", e);
        context.get(GameEngine.class).changeState(new StateMainMenu("Unable to create storage manager!"));
        // We need to return true, otherwise the loading state will just call us again immediately
        return true;
    }
    context.put(StorageManager.class, storageManager);
    LocalChunkProvider chunkProvider = new LocalChunkProvider(storageManager, entityManager, worldGenerator, blockManager, extraDataManager, Maps.newConcurrentMap());
    RelevanceSystem relevanceSystem = new RelevanceSystem(chunkProvider);
    context.put(RelevanceSystem.class, relevanceSystem);
    context.get(ComponentSystemManager.class).register(relevanceSystem, "engine:relevanceSystem");
    chunkProvider.setRelevanceSystem(relevanceSystem);
    Block unloadedBlock = blockManager.getBlock(BlockManager.UNLOADED_ID);
    WorldProviderCoreImpl worldProviderCore = new WorldProviderCoreImpl(worldInfo, chunkProvider, unloadedBlock, context);
    EntityAwareWorldProvider entityWorldProvider = new EntityAwareWorldProvider(worldProviderCore, context);
    WorldProvider worldProvider = new WorldProviderWrapper(entityWorldProvider, extraDataManager);
    context.put(WorldProvider.class, worldProvider);
    chunkProvider.setBlockEntityRegistry(entityWorldProvider);
    context.put(BlockEntityRegistry.class, entityWorldProvider);
    context.get(ComponentSystemManager.class).register(entityWorldProvider, "engine:BlockEntityRegistry");
    DefaultCelestialSystem celestialSystem = new DefaultCelestialSystem(new BasicCelestialModel(), context);
    context.put(CelestialSystem.class, celestialSystem);
    context.get(ComponentSystemManager.class).register(celestialSystem);
    Skysphere skysphere = new Skysphere(context);
    BackdropProvider backdropProvider = skysphere;
    context.put(BackdropProvider.class, backdropProvider);
    RenderingSubsystemFactory engineSubsystemFactory = context.get(RenderingSubsystemFactory.class);
    WorldRenderer worldRenderer = engineSubsystemFactory.createWorldRenderer(context);
    context.put(WorldRenderer.class, worldRenderer);
    // TODO: These shouldn't be done here, nor so strongly tied to the world renderer
    LocalPlayer localPlayer = new LocalPlayer();
    localPlayer.setRecordAndReplayClasses(context.get(DirectionAndOriginPosRecorderList.class), context.get(RecordAndReplayCurrentStatus.class));
    context.put(LocalPlayer.class, localPlayer);
    context.put(Camera.class, worldRenderer.getActiveCamera());
    return true;
}
Also used : WorldGenerator(org.terasology.engine.world.generator.WorldGenerator) WorldGeneratorManager(org.terasology.engine.world.generator.internal.WorldGeneratorManager) UnresolvedWorldGeneratorException(org.terasology.engine.world.generator.UnresolvedWorldGeneratorException) LocalChunkProvider(org.terasology.engine.world.chunks.localChunkProvider.LocalChunkProvider) LocalPlayer(org.terasology.engine.logic.players.LocalPlayer) WorldProviderWrapper(org.terasology.engine.world.internal.WorldProviderWrapper) ReadOnlyStorageManager(org.terasology.engine.persistence.internal.ReadOnlyStorageManager) StorageManager(org.terasology.engine.persistence.StorageManager) ReadWriteStorageManager(org.terasology.engine.persistence.internal.ReadWriteStorageManager) ModuleManager(org.terasology.engine.core.module.ModuleManager) EntityAwareWorldProvider(org.terasology.engine.world.internal.EntityAwareWorldProvider) BackdropProvider(org.terasology.engine.rendering.backdrop.BackdropProvider) RecordAndReplaySerializer(org.terasology.engine.recording.RecordAndReplaySerializer) ComponentSystemManager(org.terasology.engine.core.ComponentSystemManager) RecordAndReplayUtils(org.terasology.engine.recording.RecordAndReplayUtils) DefaultWorldGeneratorPluginLibrary(org.terasology.engine.world.generator.plugin.DefaultWorldGeneratorPluginLibrary) WorldProvider(org.terasology.engine.world.WorldProvider) EntityAwareWorldProvider(org.terasology.engine.world.internal.EntityAwareWorldProvider) WorldInfo(org.terasology.engine.world.internal.WorldInfo) EngineEntityManager(org.terasology.engine.entitySystem.entity.internal.EngineEntityManager) Path(java.nio.file.Path) FastRandom(org.terasology.engine.utilities.random.FastRandom) IOException(java.io.IOException) WorldProviderCoreImpl(org.terasology.engine.world.internal.WorldProviderCoreImpl) ExtraBlockDataManager(org.terasology.engine.world.chunks.blockdata.ExtraBlockDataManager) DefaultCelestialSystem(org.terasology.engine.world.sun.DefaultCelestialSystem) RenderingSubsystemFactory(org.terasology.engine.core.subsystem.RenderingSubsystemFactory) WorldRenderer(org.terasology.engine.rendering.world.WorldRenderer) BasicCelestialModel(org.terasology.engine.world.sun.BasicCelestialModel) DirectionAndOriginPosRecorderList(org.terasology.engine.recording.DirectionAndOriginPosRecorderList) EngineEntityManager(org.terasology.engine.entitySystem.entity.internal.EngineEntityManager) EntityManager(org.terasology.engine.entitySystem.entity.EntityManager) BlockManager(org.terasology.engine.world.block.BlockManager) ModuleEnvironment(org.terasology.gestalt.module.ModuleEnvironment) StateMainMenu(org.terasology.engine.core.modes.StateMainMenu) Skysphere(org.terasology.engine.rendering.backdrop.Skysphere) Block(org.terasology.engine.world.block.Block) RecordAndReplayCurrentStatus(org.terasology.engine.recording.RecordAndReplayCurrentStatus) ReadWriteStorageManager(org.terasology.engine.persistence.internal.ReadWriteStorageManager) ReadOnlyStorageManager(org.terasology.engine.persistence.internal.ReadOnlyStorageManager) RelevanceSystem(org.terasology.engine.world.chunks.localChunkProvider.RelevanceSystem)

Example 5 with FastRandom

use of org.terasology.engine.utilities.random.FastRandom in project Terasology by MovingBlocks.

the class MersenneRandomTest method testSpeed.

/**
 * Perform some speed tests and write results to logger
 */
@Test
public void testSpeed() {
    final long seed = 4357;
    final int warmUpCount = 10000;
    final int count = 10000000;
    int sum;
    long start;
    logger.info("Time to test grabbing {} ints", count);
    // -------------------------------------------------------
    java.util.Random rr = new java.util.Random(seed);
    // warmup
    sum = 0;
    for (int j = 0; j < warmUpCount; j++) {
        sum += rr.nextInt();
    }
    sum = 0;
    start = System.nanoTime();
    for (int j = 0; j < count; j++) {
        sum += rr.nextInt();
    }
    logger.info("java.util.Random: {}ms.", (System.nanoTime() - start) / 1000000);
    logger.trace("Use the result so that JVM doesn't skip the computation - here it is: {}", sum);
    // -------------------------------------------------------
    FastRandom fr = new FastRandom(seed);
    // warmup
    sum = 0;
    for (int j = 0; j < warmUpCount; j++) {
        sum += fr.nextInt();
    }
    sum = 0;
    start = System.nanoTime();
    for (int j = 0; j < count; j++) {
        sum += fr.nextInt();
    }
    logger.info("FastRandom: {}ms.", (System.nanoTime() - start) / 1000000);
    logger.trace("Use the result so that JVM doesn't skip the computation - here it is: {}", sum);
    // -------------------------------------------------------
    MersenneRandom r = new MersenneRandom(seed);
    // warmup
    sum = 0;
    for (int j = 0; j < warmUpCount; j++) {
        sum += r.nextInt();
    }
    sum = 0;
    start = System.nanoTime();
    for (int j = 0; j < count; j++) {
        sum += r.nextInt();
    }
    logger.info("MersenneRandom: {}ms.", (System.nanoTime() - start) / 1000000);
    logger.trace("Use the result so that JVM doesn't skip the computation - here it is: {}", sum);
}
Also used : MersenneRandom(org.terasology.engine.utilities.random.MersenneRandom) MersenneRandom(org.terasology.engine.utilities.random.MersenneRandom) FastRandom(org.terasology.engine.utilities.random.FastRandom) FastRandom(org.terasology.engine.utilities.random.FastRandom) Test(org.junit.jupiter.api.Test)

Aggregations

FastRandom (org.terasology.engine.utilities.random.FastRandom)8 Test (org.junit.jupiter.api.Test)3 ByteBuffer (java.nio.ByteBuffer)2 ModuleManager (org.terasology.engine.core.module.ModuleManager)2 Random (org.terasology.engine.utilities.random.Random)2 WorldGeneratorManager (org.terasology.engine.world.generator.internal.WorldGeneratorManager)2 TargetLengthBasedClassNameAbbreviator (ch.qos.logback.classic.pattern.TargetLengthBasedClassNameAbbreviator)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Lists (com.google.common.collect.Lists)1 Maps (com.google.common.collect.Maps)1 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Comparator (java.util.Comparator)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1