Search in sources :

Example 1 with FastRandom

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

the class CreateGameScreen method initialise.

@Override
@SuppressWarnings("unchecked")
public void initialise() {
    setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation());
    UILabel gameTypeTitle = find("gameTypeTitle", UILabel.class);
    if (gameTypeTitle != null) {
        gameTypeTitle.bindText(new ReadOnlyBinding<String>() {

            @Override
            public String get() {
                if (loadingAsServer) {
                    return translationSystem.translate("${engine:menu#select-multiplayer-game-sub-title}");
                } else {
                    return translationSystem.translate("${engine:menu#select-singleplayer-game-sub-title}");
                }
            }
        });
    }
    final UIText worldName = find("worldName", UIText.class);
    setGameName(worldName);
    final UIText seed = find("seed", UIText.class);
    if (seed != null) {
        seed.setText(new FastRandom().nextString(32));
    }
    final UIDropdownScrollable<Module> gameplay = find("gameplay", UIDropdownScrollable.class);
    gameplay.setOptions(getGameplayModules());
    gameplay.setVisibleOptions(3);
    gameplay.bindSelection(new Binding<Module>() {

        Module selected;

        @Override
        public Module get() {
            return selected;
        }

        @Override
        public void set(Module value) {
            setSelectedGameplayModule(value);
            selected = value;
        }
    });
    gameplay.setOptionRenderer(new StringTextRenderer<Module>() {

        @Override
        public String getString(Module value) {
            return value.getMetadata().getDisplayName().value();
        }

        @Override
        public void draw(Module value, Canvas canvas) {
            canvas.getCurrentStyle().setTextColor(validateModuleDependencies(value.getId()) ? Color.WHITE : Color.RED);
            super.draw(value, canvas);
            canvas.getCurrentStyle().setTextColor(Color.WHITE);
        }
    });
    UILabel gameplayDescription = find("gameplayDescription", UILabel.class);
    gameplayDescription.bindText(new ReadOnlyBinding<String>() {

        @Override
        public String get() {
            Module selectedModule = gameplay.getSelection();
            if (selectedModule != null) {
                return selectedModule.getMetadata().getDescription().value();
            } else {
                return "";
            }
        }
    });
    final UIDropdownScrollable<WorldGeneratorInfo> worldGenerator = find("worldGenerator", UIDropdownScrollable.class);
    if (worldGenerator != null) {
        worldGenerator.bindOptions(new ReadOnlyBinding<List<WorldGeneratorInfo>>() {

            @Override
            public List<WorldGeneratorInfo> get() {
                // grab all the module names and their dependencies
                // This grabs modules from `config.getDefaultModSelection()` which is updated in SelectModulesScreen
                Set<Name> enabledModuleNames = getAllEnabledModuleNames().stream().collect(Collectors.toSet());
                List<WorldGeneratorInfo> result = Lists.newArrayList();
                for (WorldGeneratorInfo option : worldGeneratorManager.getWorldGenerators()) {
                    if (enabledModuleNames.contains(option.getUri().getModuleName())) {
                        result.add(option);
                    }
                }
                return result;
            }
        });
        worldGenerator.setVisibleOptions(3);
        worldGenerator.bindSelection(new Binding<WorldGeneratorInfo>() {

            @Override
            public WorldGeneratorInfo get() {
                // get the default generator from the config. This is likely to have a user triggered selection.
                WorldGeneratorInfo info = worldGeneratorManager.getWorldGeneratorInfo(config.getWorldGeneration().getDefaultGenerator());
                if (info != null && getAllEnabledModuleNames().contains(info.getUri().getModuleName())) {
                    return info;
                }
                // just use the first available generator
                for (WorldGeneratorInfo worldGenInfo : worldGeneratorManager.getWorldGenerators()) {
                    if (getAllEnabledModuleNames().contains(worldGenInfo.getUri().getModuleName())) {
                        set(worldGenInfo);
                        return worldGenInfo;
                    }
                }
                return null;
            }

            @Override
            public void set(WorldGeneratorInfo value) {
                if (value != null) {
                    config.getWorldGeneration().setDefaultGenerator(value.getUri());
                }
            }
        });
        worldGenerator.setOptionRenderer(new StringTextRenderer<WorldGeneratorInfo>() {

            @Override
            public String getString(WorldGeneratorInfo value) {
                if (value != null) {
                    return value.getDisplayName();
                }
                return "";
            }
        });
        final UIButton playButton = find("play", UIButton.class);
        playButton.bindEnabled(new Binding<Boolean>() {

            @Override
            public Boolean get() {
                return validateModuleDependencies(gameplay.getSelection().getId());
            }

            @Override
            public void set(Boolean value) {
                playButton.setEnabled(value);
            }
        });
    }
    WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation());
    WidgetUtil.trySubscribe(this, "play", button -> {
        if (worldGenerator.getSelection() == null) {
            MessagePopup errorMessagePopup = getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class);
            if (errorMessagePopup != null) {
                errorMessagePopup.setMessage("No World Generator Selected", "Select a world generator (you may need to activate a mod with a generator first).");
            }
        } else {
            GameManifest gameManifest = new GameManifest();
            gameManifest.setTitle(worldName.getText());
            gameManifest.setSeed(seed.getText());
            DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry());
            ResolutionResult result = resolver.resolve(config.getDefaultModSelection().listModules());
            if (!result.isSuccess()) {
                MessagePopup errorMessagePopup = getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class);
                if (errorMessagePopup != null) {
                    errorMessagePopup.setMessage("Invalid Module Selection", "Please review your module seleciton and try again");
                }
                return;
            }
            for (Module module : result.getModules()) {
                gameManifest.addModule(module.getId(), module.getVersion());
            }
            // Time at dawn + little offset to spawn in a brighter env.
            float timeOffset = 0.25f + 0.025f;
            WorldInfo worldInfo = new WorldInfo(TerasologyConstants.MAIN_WORLD, gameManifest.getSeed(), (long) (WorldTime.DAY_LENGTH * timeOffset), worldGenerator.getSelection().getUri());
            gameManifest.addWorld(worldInfo);
            gameEngine.changeState(new StateLoading(gameManifest, (loadingAsServer) ? NetworkMode.DEDICATED_SERVER : NetworkMode.NONE));
        }
    });
    UIButton previewSeed = find("previewSeed", UIButton.class);
    ReadOnlyBinding<Boolean> worldGeneratorSelected = new ReadOnlyBinding<Boolean>() {

        @Override
        public Boolean get() {
            return worldGenerator != null && worldGenerator.getSelection() != null;
        }
    };
    previewSeed.bindEnabled(worldGeneratorSelected);
    PreviewWorldScreen screen = getManager().createScreen(PreviewWorldScreen.ASSET_URI, PreviewWorldScreen.class);
    WidgetUtil.trySubscribe(this, "previewSeed", button -> {
        if (screen != null) {
            screen.bindSeed(BindHelper.bindBeanProperty("text", seed, String.class));
            try {
                screen.setEnvironment();
                triggerForwardAnimation(screen);
            } catch (Exception e) {
                String msg = "Unable to load world for a 2D preview:\n" + e.toString();
                getManager().pushScreen(MessagePopup.ASSET_URI, MessagePopup.class).setMessage("Error", msg);
                logger.error("Unable to load world for a 2D preview", e);
            }
        }
    });
    WidgetUtil.trySubscribe(this, "mods", w -> triggerForwardAnimation(SelectModulesScreen.ASSET_URI));
}
Also used : Set(java.util.Set) ResolutionResult(org.terasology.module.ResolutionResult) WorldGeneratorInfo(org.terasology.world.generator.internal.WorldGeneratorInfo) UIButton(org.terasology.rendering.nui.widgets.UIButton) UIText(org.terasology.rendering.nui.widgets.UIText) WorldInfo(org.terasology.world.internal.WorldInfo) List(java.util.List) UILabel(org.terasology.rendering.nui.widgets.UILabel) StateLoading(org.terasology.engine.modes.StateLoading) ReadOnlyBinding(org.terasology.rendering.nui.databinding.ReadOnlyBinding) Canvas(org.terasology.rendering.nui.Canvas) FastRandom(org.terasology.utilities.random.FastRandom) DependencyResolver(org.terasology.module.DependencyResolver) GameManifest(org.terasology.game.GameManifest) Module(org.terasology.module.Module)

Example 2 with FastRandom

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

the class BlockEntitySystem method initialise.

@Override
public void initialise() {
    blockItemFactory = new BlockItemFactory(entityManager);
    random = new FastRandom();
}
Also used : BlockItemFactory(org.terasology.world.block.items.BlockItemFactory) FastRandom(org.terasology.utilities.random.FastRandom)

Example 3 with FastRandom

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

the class InitialiseWorld method step.

@Override
public boolean step() {
    BlockManager blockManager = context.get(BlockManager.class);
    BiomeManager biomeManager = context.get(BiomeManager.class);
    ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment();
    context.put(WorldGeneratorPluginLibrary.class, new DefaultWorldGeneratorPluginLibrary(environment, context));
    WorldInfo worldInfo = gameManifest.getWorldInfo(TerasologyConstants.MAIN_WORLD);
    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(Config.class).getSystem().isWriteSaveGamesEnabled();
    Path savePath = PathManager.getInstance().getSavePath(gameManifest.getTitle());
    StorageManager storageManager;
    try {
        storageManager = writeSaveGamesEnabled ? new ReadWriteStorageManager(savePath, environment, entityManager, blockManager, biomeManager) : new ReadOnlyStorageManager(savePath, environment, entityManager, blockManager, biomeManager);
    } 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, biomeManager);
    context.get(ComponentSystemManager.class).register(new RelevanceSystem(chunkProvider), "engine: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);
    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;
    BackdropRenderer backdropRenderer = skysphere;
    context.put(BackdropProvider.class, backdropProvider);
    context.put(BackdropRenderer.class, backdropRenderer);
    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
    context.put(LocalPlayer.class, new LocalPlayer());
    context.put(Camera.class, worldRenderer.getActiveCamera());
    return true;
}
Also used : WorldGenerator(org.terasology.world.generator.WorldGenerator) WorldGeneratorManager(org.terasology.world.generator.internal.WorldGeneratorManager) UnresolvedWorldGeneratorException(org.terasology.world.generator.UnresolvedWorldGeneratorException) LocalChunkProvider(org.terasology.world.chunks.localChunkProvider.LocalChunkProvider) LocalPlayer(org.terasology.logic.players.LocalPlayer) WorldProviderWrapper(org.terasology.world.internal.WorldProviderWrapper) ReadOnlyStorageManager(org.terasology.persistence.internal.ReadOnlyStorageManager) ReadWriteStorageManager(org.terasology.persistence.internal.ReadWriteStorageManager) StorageManager(org.terasology.persistence.StorageManager) ModuleManager(org.terasology.engine.module.ModuleManager) EntityAwareWorldProvider(org.terasology.world.internal.EntityAwareWorldProvider) BackdropProvider(org.terasology.rendering.backdrop.BackdropProvider) ComponentSystemManager(org.terasology.engine.ComponentSystemManager) DefaultWorldGeneratorPluginLibrary(org.terasology.world.generator.plugin.DefaultWorldGeneratorPluginLibrary) EntityAwareWorldProvider(org.terasology.world.internal.EntityAwareWorldProvider) WorldProvider(org.terasology.world.WorldProvider) WorldInfo(org.terasology.world.internal.WorldInfo) BiomeManager(org.terasology.world.biomes.BiomeManager) EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) Path(java.nio.file.Path) FastRandom(org.terasology.utilities.random.FastRandom) IOException(java.io.IOException) WorldProviderCoreImpl(org.terasology.world.internal.WorldProviderCoreImpl) DefaultCelestialSystem(org.terasology.world.sun.DefaultCelestialSystem) RenderingSubsystemFactory(org.terasology.engine.subsystem.RenderingSubsystemFactory) WorldRenderer(org.terasology.rendering.world.WorldRenderer) BasicCelestialModel(org.terasology.world.sun.BasicCelestialModel) EntityManager(org.terasology.entitySystem.entity.EntityManager) EngineEntityManager(org.terasology.entitySystem.entity.internal.EngineEntityManager) BlockManager(org.terasology.world.block.BlockManager) ModuleEnvironment(org.terasology.module.ModuleEnvironment) StateMainMenu(org.terasology.engine.modes.StateMainMenu) Skysphere(org.terasology.rendering.backdrop.Skysphere) Block(org.terasology.world.block.Block) ReadWriteStorageManager(org.terasology.persistence.internal.ReadWriteStorageManager) ReadOnlyStorageManager(org.terasology.persistence.internal.ReadOnlyStorageManager) RelevanceSystem(org.terasology.world.chunks.localChunkProvider.RelevanceSystem) BackdropRenderer(org.terasology.rendering.backdrop.BackdropRenderer)

Example 4 with FastRandom

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

the class IterateMultipleComponentBenchmark method setup.

@Override
public void setup() {
    FastRandom rand = new FastRandom(0L);
    rawEntityData = Lists.newArrayList();
    for (int i = 0; i < 1000; ++i) {
        List<Component> entityData = Lists.newArrayList();
        if (rand.nextFloat() < 0.75f) {
            entityData.add(new LocationComponent());
        }
        if (rand.nextFloat() < 0.5f) {
            entityData.add(new MeshComponent());
        }
        if (rand.nextFloat() < 0.25f) {
            entityData.add(new BlockComponent());
        }
        rawEntityData.add(entityData);
    }
    entityManager = new PojoEntityManager();
    for (List<Component> rawEntity : rawEntityData) {
        entityManager.create(rawEntity);
    }
}
Also used : BlockComponent(org.terasology.world.block.BlockComponent) MeshComponent(org.terasology.rendering.logic.MeshComponent) PojoEntityManager(org.terasology.entitySystem.entity.internal.PojoEntityManager) FastRandom(org.terasology.utilities.random.FastRandom) MeshComponent(org.terasology.rendering.logic.MeshComponent) BlockComponent(org.terasology.world.block.BlockComponent) Component(org.terasology.entitySystem.Component) LocationComponent(org.terasology.logic.location.LocationComponent) LocationComponent(org.terasology.logic.location.LocationComponent)

Example 5 with FastRandom

use of org.terasology.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);
        Assert.assertEquals(rgba, firstPixel);
    }
}
Also used : Random(org.terasology.utilities.random.Random) FastRandom(org.terasology.utilities.random.FastRandom) Color(org.terasology.rendering.nui.Color) FastRandom(org.terasology.utilities.random.FastRandom) ResourceUrn(org.terasology.assets.ResourceUrn) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Aggregations

FastRandom (org.terasology.utilities.random.FastRandom)14 LocationComponent (org.terasology.logic.location.LocationComponent)4 Random (org.terasology.utilities.random.Random)4 Test (org.junit.Test)3 Component (org.terasology.entitySystem.Component)3 MeshComponent (org.terasology.rendering.logic.MeshComponent)3 ByteBuffer (java.nio.ByteBuffer)2 PojoEntityManager (org.terasology.entitySystem.entity.internal.PojoEntityManager)2 Color (org.terasology.rendering.nui.Color)2 BlockComponent (org.terasology.world.block.BlockComponent)2 WorldInfo (org.terasology.world.internal.WorldInfo)2 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 ResourceUrn (org.terasology.assets.ResourceUrn)1 TreeFacet (org.terasology.core.world.generator.facets.TreeFacet)1 TreeGenerator (org.terasology.core.world.generator.trees.TreeGenerator)1 ComponentSystemManager (org.terasology.engine.ComponentSystemManager)1