Search in sources :

Example 16 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class CreateWorldEntity method step.

@Override
public boolean step() {
    this.entityManager = context.get(EntityManager.class);
    this.worldGenerator = context.get(WorldGenerator.class);
    this.config = context.get(Config.class);
    this.chunkProvider = context.get(ChunkProvider.class);
    this.worldConfigurator = worldGenerator.getConfigurator();
    Iterator<EntityRef> worldEntityIterator = entityManager.getEntitiesWith(WorldComponent.class).iterator();
    if (worldEntityIterator.hasNext()) {
        EntityRef worldEntity = worldEntityIterator.next();
        worldEntityIterator.forEachRemaining(w -> logger.warn("Ignored extra world {}", w));
        chunkProvider.setWorldEntity(worldEntity);
        // replace the world generator values from the components in the world entity
        worldConfigurator.getProperties().forEach((key, currentComponent) -> {
            Component component = worldEntity.getComponent(currentComponent.getClass());
            if (component != null) {
                worldConfigurator.setProperty(key, component);
            }
        });
    } else {
        // create world entity if one does not exist.
        EntityRef worldEntity = createWorldPoolsAndEntity();
        chunkProvider.setWorldEntity(worldEntity);
        // transfer all world generation parameters from Config to WorldEntity
        SimpleUri generatorUri = worldGenerator.getUri();
        worldConfigurator.getProperties().forEach((key, currentComponent) -> {
            Class<? extends Component> clazz = currentComponent.getClass();
            Component moduleComponent = gameManifest.getModuleConfig(generatorUri, key, clazz);
            if (moduleComponent != null) {
                // configure entity from component
                worldEntity.addComponent(moduleComponent);
                worldConfigurator.setProperty(key, moduleComponent);
            } else {
                worldEntity.addComponent(currentComponent);
            }
        });
    }
    return true;
}
Also used : EntityManager(org.terasology.engine.entitySystem.entity.EntityManager) WorldGenerator(org.terasology.engine.world.generator.WorldGenerator) Config(org.terasology.engine.config.Config) SimpleUri(org.terasology.engine.core.SimpleUri) ChunkProvider(org.terasology.engine.world.chunks.ChunkProvider) WorldComponent(org.terasology.engine.world.WorldComponent) Component(org.terasology.gestalt.entitysystem.component.Component) NetworkComponent(org.terasology.engine.network.NetworkComponent) WorldComponent(org.terasology.engine.world.WorldComponent) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef)

Example 17 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class BlockTypeEntityGenerator method generateBlockTypeEntity.

private void generateBlockTypeEntity(Block block) {
    EntityBuilder builder = entityManager.newBuilder(blockTypePrefab);
    builder.getComponent(BlockTypeComponent.class).block = block;
    // TODO: Copy across settings as necessary
    Optional<Prefab> prefab = block.getPrefab();
    if (prefab.isPresent()) {
        for (Component comp : prefab.get().iterateComponents()) {
            if (!(comp instanceof NetworkComponent)) {
                builder.addComponent(entityManager.getComponentLibrary().copy(comp));
            }
        }
    }
    block.setEntity(builder.build());
}
Also used : NetworkComponent(org.terasology.engine.network.NetworkComponent) EntityBuilder(org.terasology.engine.entitySystem.entity.EntityBuilder) Component(org.terasology.gestalt.entitysystem.component.Component) NetworkComponent(org.terasology.engine.network.NetworkComponent) Prefab(org.terasology.engine.entitySystem.prefab.Prefab)

Example 18 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class CoreCommands method spawnPrefab.

/**
 * Spawns an instance of a prefab in the world
 *
 * @param sender     Sender of command
 * @param prefabName String containing prefab name
 * @return String containing final message
 */
@Command(shortDescription = "Spawns an instance of a prefab in the world", runOnServer = true, requiredPermission = PermissionManager.CHEAT_PERMISSION)
public String spawnPrefab(@Sender EntityRef sender, @CommandParam("prefabId") String prefabName) {
    ClientComponent clientComponent = sender.getComponent(ClientComponent.class);
    LocationComponent characterLocation = clientComponent.character.getComponent(LocationComponent.class);
    Vector3f spawnPos = characterLocation.getWorldPosition(new Vector3f());
    Vector3f offset = characterLocation.getWorldDirection(new Vector3f());
    offset.mul(2);
    spawnPos.add(offset);
    Vector3f dir = characterLocation.getWorldDirection(new Vector3f());
    dir.y = 0;
    if (dir.lengthSquared() > 0.001f) {
        dir.normalize();
    } else {
        dir.set(Direction.FORWARD.asVector3f());
    }
    return Assets.getPrefab(prefabName).map(prefab -> {
        LocationComponent loc = prefab.getComponent(LocationComponent.class);
        if (loc != null) {
            entityManager.create(prefab, spawnPos);
            return "Done";
        } else {
            return "Prefab cannot be spawned (no location component)";
        }
    }).orElse("Unknown prefab");
}
Also used : DropItemEvent(org.terasology.engine.logic.inventory.events.DropItemEvent) Server(org.terasology.engine.network.Server) Arrays(java.util.Arrays) Component(org.terasology.gestalt.entitysystem.component.Component) In(org.terasology.engine.registry.In) SystemConfig(org.terasology.engine.config.SystemConfig) Sender(org.terasology.engine.logic.console.commandSystem.annotations.Sender) Console(org.terasology.engine.logic.console.Console) SkinSuggester(org.terasology.engine.logic.console.suggesters.SkinSuggester) DisplayDevice(org.terasology.engine.core.subsystem.DisplayDevice) NUIEditorScreen(org.terasology.engine.rendering.nui.editor.layers.NUIEditorScreen) Locale(java.util.Locale) BlockUri(org.terasology.engine.world.block.BlockUri) FontColor(org.terasology.nui.FontColor) Vector3f(org.joml.Vector3f) TranslationProject(org.terasology.engine.i18n.TranslationProject) Path(java.nio.file.Path) StateLoading(org.terasology.engine.core.modes.StateLoading) Command(org.terasology.engine.logic.console.commandSystem.annotations.Command) TranslationSystem(org.terasology.engine.i18n.TranslationSystem) ConsoleCommand(org.terasology.engine.logic.console.commandSystem.ConsoleCommand) CommandParam(org.terasology.engine.logic.console.commandSystem.annotations.CommandParam) ConsoleColors(org.terasology.engine.logic.console.ConsoleColors) GameEngine(org.terasology.engine.core.GameEngine) CommandNameSuggester(org.terasology.engine.logic.console.suggesters.CommandNameSuggester) WaitPopup(org.terasology.engine.rendering.nui.layers.mainMenu.WaitPopup) Set(java.util.Set) StateMainMenu(org.terasology.engine.core.modes.StateMainMenu) NUISkinEditorSystem(org.terasology.engine.rendering.nui.editor.systems.NUISkinEditorSystem) Streams(com.google.common.collect.Streams) BlockFamilyDefinition(org.terasology.engine.world.block.loader.BlockFamilyDefinition) Instant(java.time.Instant) UISkinAsset(org.terasology.nui.skin.UISkinAsset) Collectors(java.util.stream.Collectors) Direction(org.terasology.engine.math.Direction) NUIManager(org.terasology.engine.rendering.nui.NUIManager) List(java.util.List) EntityRef(org.terasology.engine.entitySystem.entity.EntityRef) RegisterSystem(org.terasology.engine.entitySystem.systems.RegisterSystem) NUISkinEditorScreen(org.terasology.engine.rendering.nui.editor.layers.NUISkinEditorScreen) ScreenSuggester(org.terasology.engine.logic.console.suggesters.ScreenSuggester) Optional(java.util.Optional) Name(org.terasology.gestalt.naming.Name) TerasologyConstants(org.terasology.engine.core.TerasologyConstants) UIElement(org.terasology.nui.asset.UIElement) ModuleManager(org.terasology.engine.core.module.ModuleManager) EngineEntityManager(org.terasology.engine.entitySystem.entity.internal.EngineEntityManager) NetworkMode(org.terasology.engine.network.NetworkMode) Callable(java.util.concurrent.Callable) BlockItemFactory(org.terasology.engine.world.block.items.BlockItemFactory) ArrayList(java.util.ArrayList) WorldDumper(org.terasology.engine.persistence.WorldDumper) ResourceUrn(org.terasology.gestalt.assets.ResourceUrn) Time(org.terasology.engine.core.Time) StreamSupport(java.util.stream.StreamSupport) AssetManager(org.terasology.gestalt.assets.management.AssetManager) PingService(org.terasology.engine.network.PingService) MessagePopup(org.terasology.engine.rendering.nui.layers.mainMenu.MessagePopup) Assets(org.terasology.engine.utilities.Assets) BlockFamily(org.terasology.engine.world.block.family.BlockFamily) PermissionManager(org.terasology.engine.logic.permission.PermissionManager) NUIEditorSystem(org.terasology.engine.rendering.nui.editor.systems.NUIEditorSystem) LocationComponent(org.terasology.engine.logic.location.LocationComponent) ClientComponent(org.terasology.engine.network.ClientComponent) EntityManager(org.terasology.engine.entitySystem.entity.EntityManager) PrefabManager(org.terasology.engine.entitySystem.prefab.PrefabManager) IOException(java.io.IOException) Prefab(org.terasology.engine.entitySystem.prefab.Prefab) UnknownHostException(java.net.UnknownHostException) BaseComponentSystem(org.terasology.engine.entitySystem.systems.BaseComponentSystem) Ordering(com.google.common.collect.Ordering) BlockManager(org.terasology.engine.world.block.BlockManager) PrefabSerializer(org.terasology.engine.persistence.serializers.PrefabSerializer) JoinStatus(org.terasology.engine.network.JoinStatus) NetworkSystem(org.terasology.engine.network.NetworkSystem) PathManager(org.terasology.engine.core.PathManager) Vector3f(org.joml.Vector3f) ClientComponent(org.terasology.engine.network.ClientComponent) LocationComponent(org.terasology.engine.logic.location.LocationComponent) Command(org.terasology.engine.logic.console.commandSystem.annotations.Command) ConsoleCommand(org.terasology.engine.logic.console.commandSystem.ConsoleCommand)

Example 19 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class EventSystemReplayImpl method registerEventHandler.

@Override
public void registerEventHandler(ComponentSystem handler) {
    Class handlerClass = handler.getClass();
    if (!Modifier.isPublic(handlerClass.getModifiers())) {
        logger.error("Cannot register handler {}, must be public", handler.getClass().getName());
        return;
    }
    logger.debug("Registering event handler " + handlerClass.getName());
    for (Method method : handlerClass.getMethods()) {
        ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class);
        if (receiveEventAnnotation != null) {
            if (!receiveEventAnnotation.netFilter().isValidFor(networkSystem.getMode().isAuthority(), false)) {
                continue;
            }
            Set<Class<? extends Component>> requiredComponents = Sets.newLinkedHashSet();
            method.setAccessible(true);
            Class<?>[] types = method.getParameterTypes();
            logger.debug("Found method: " + method.toString());
            if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) {
                logger.error("Invalid event handler method: {}", method.getName());
                return;
            }
            requiredComponents.addAll(Arrays.asList(receiveEventAnnotation.components()));
            List<Class<? extends Component>> componentParams = Lists.newArrayList();
            for (int i = 2; i < types.length; ++i) {
                if (!Component.class.isAssignableFrom(types[i])) {
                    logger.error("Invalid event handler method: {} - {} is not a component class", method.getName(), types[i]);
                    return;
                }
                requiredComponents.add((Class<? extends Component>) types[i]);
                componentParams.add((Class<? extends Component>) types[i]);
            }
            EventSystemReplayImpl.ByteCodeEventHandlerInfo handlerInfo = new EventSystemReplayImpl.ByteCodeEventHandlerInfo(handler, method, receiveEventAnnotation.priority(), receiveEventAnnotation.activity(), requiredComponents, componentParams);
            addEventHandler((Class<? extends Event>) types[0], handlerInfo, requiredComponents);
        }
    }
}
Also used : ReceiveEvent(org.terasology.engine.entitySystem.event.ReceiveEvent) Method(java.lang.reflect.Method) Component(org.terasology.gestalt.entitysystem.component.Component) NetworkComponent(org.terasology.engine.network.NetworkComponent) BlockComponent(org.terasology.engine.world.block.BlockComponent)

Example 20 with Component

use of org.terasology.gestalt.entitysystem.component.Component in project Terasology by MovingBlocks.

the class EventSystemReplayImpl method originalSend.

// send method of EventSystemImpl
private void originalSend(EntityRef entity, Event event, Component component) {
    if (Thread.currentThread() != mainThread) {
        pendingEvents.offer(new PendingEvent(entity, event, component));
    } else {
        SetMultimap<Class<? extends Component>, EventSystemReplayImpl.EventHandlerInfo> handlers = componentSpecificHandlers.get(event.getClass());
        if (handlers != null) {
            List<EventSystemReplayImpl.EventHandlerInfo> eventHandlers = Lists.newArrayList(handlers.get(component.getClass()));
            eventHandlers.sort(priorityComparator);
            for (EventSystemReplayImpl.EventHandlerInfo eventHandler : eventHandlers) {
                if (eventHandler.isValidFor(entity)) {
                    eventHandler.invoke(entity, event);
                }
            }
        }
    }
}
Also used : PendingEvent(org.terasology.engine.entitySystem.event.PendingEvent) Component(org.terasology.gestalt.entitysystem.component.Component) NetworkComponent(org.terasology.engine.network.NetworkComponent) BlockComponent(org.terasology.engine.world.block.BlockComponent)

Aggregations

Component (org.terasology.gestalt.entitysystem.component.Component)57 EntityRef (org.terasology.engine.entitySystem.entity.EntityRef)20 Prefab (org.terasology.engine.entitySystem.prefab.Prefab)12 LocationComponent (org.terasology.engine.logic.location.LocationComponent)12 OnActivatedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnActivatedComponent)11 NetworkComponent (org.terasology.engine.network.NetworkComponent)10 OnChangedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnChangedComponent)9 EntityData (org.terasology.protobuf.EntityData)8 BeforeDeactivateComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent)7 OnAddedComponent (org.terasology.engine.entitySystem.entity.lifecycleEvents.OnAddedComponent)7 BlockComponent (org.terasology.engine.world.block.BlockComponent)7 EntityInfoComponent (org.terasology.engine.entitySystem.entity.internal.EntityInfoComponent)6 ReceiveEvent (org.terasology.engine.entitySystem.event.ReceiveEvent)6 EntityManager (org.terasology.engine.entitySystem.entity.EntityManager)5 ClientComponent (org.terasology.engine.network.ClientComponent)5 List (java.util.List)4 Map (java.util.Map)4 Optional (java.util.Optional)4 FieldMetadata (org.terasology.reflection.metadata.FieldMetadata)4 ByteString (com.google.protobuf.ByteString)3