repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
SpongePowered/Sponge
23,957
src/main/java/org/spongepowered/common/event/tracking/TrackingUtil.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.event.tracking; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockEventData; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.material.FluidState; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.transaction.BlockTransactionReceipt; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.block.TickBlockEvent; import org.spongepowered.api.world.BlockChangeFlag; import org.spongepowered.api.world.BlockChangeFlags; import org.spongepowered.api.world.LocatableBlock; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.block.SpongeBlockSnapshot; import org.spongepowered.common.bridge.CreatorTrackedBridge; import org.spongepowered.common.bridge.TrackableBridge; import org.spongepowered.common.bridge.world.TrackedWorldBridge; import org.spongepowered.common.bridge.world.inventory.ViewableInventoryBridge; import org.spongepowered.common.bridge.world.level.TrackableBlockEventDataBridge; import org.spongepowered.common.bridge.world.level.chunk.LevelChunkBridge; import org.spongepowered.common.entity.PlayerTracker; import org.spongepowered.common.event.ShouldFire; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; import org.spongepowered.common.event.tracking.phase.tick.BlockEventTickContext; import org.spongepowered.common.event.tracking.phase.tick.BlockTickContext; import org.spongepowered.common.event.tracking.phase.tick.EntityTickContext; import org.spongepowered.common.event.tracking.phase.tick.FluidTickContext; import org.spongepowered.common.event.tracking.phase.tick.TickPhase; import org.spongepowered.common.event.tracking.phase.tick.TileEntityTickContext; import org.spongepowered.common.util.Preconditions; import org.spongepowered.common.util.PrettyPrinter; import org.spongepowered.common.util.VecHelper; import org.spongepowered.common.world.BlockChange; import org.spongepowered.common.world.server.SpongeLocatableBlockBuilder; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.BooleanSupplier; import java.util.function.Supplier; /** * A simple utility for aiding in tracking, either with resolving notifiers * and owners, or proxying out the logic for ticking a block, entity, etc. */ @SuppressWarnings({"unchecked", "rawtypes"}) public final class TrackingUtil { public static final Marker ENTITY_TICK = MarkerManager.getMarker("ENTITY TICK"); public static final Marker BLOCK_ENTITY_TICK = MarkerManager.getMarker("TILE ENTITY TICK"); public static final Marker PLAYER_TICK = MarkerManager.getMarker("PLAYER TICK"); public static final Marker BLOCK_TICK = MarkerManager.getMarker("BLOCK TICK"); public static final Marker FLUID_TICK = MarkerManager.getMarker("FLUID TICK"); public static final int WIDTH = 40; public static void tickEntity(final net.minecraft.world.entity.Entity entity, final Runnable tick) { Preconditions.checkArgument(entity instanceof Entity, () -> String.format("Entity %s is not an instance of SpongeAPI's Entity!", entity)); Objects.requireNonNull(entity, "Cannot capture on a null ticking entity!"); if (!((TrackableBridge) entity).bridge$shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext(PhaseTracker.SERVER).source(entity); try (final EntityTickContext context = tickContext) { if (entity instanceof CreatorTrackedBridge ctb) { ctb.tracker$getNotifierUUID().ifPresent(context::notifier); ctb.tracker$getCreatorUUID().ifPresent(context::creator); } context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.ENTITY_TICK, () -> "Wrapping Entity Tick: " + entity.toString()); tick.run(); if (ShouldFire.MOVE_ENTITY_EVENT) { SpongeCommonEventFactory.callNaturalMoveEntityEvent(entity); } if (ShouldFire.ROTATE_ENTITY_EVENT) { SpongeCommonEventFactory.callNaturalRotateEntityEvent(entity); } } catch (final Exception e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, tickContext); } } @SuppressWarnings({"unused", "try"}) public static void tickTileEntity(final BlockEntity blockEntity, final Runnable tick) { Objects.requireNonNull(blockEntity, "Cannot capture on a null ticking tile entity!"); if (!((org.spongepowered.api.block.entity.BlockEntity) blockEntity).isTicking()) { return; } if (!((TrackableBridge) blockEntity).bridge$shouldTick()) { return; } final TileEntityTickContext context = TickPhase.Tick.TILE_ENTITY.createPhaseContext(PhaseTracker.SERVER).source(blockEntity); try (final PhaseContext<@NonNull ?> phaseContext = context) { if (blockEntity instanceof CreatorTrackedBridge ctb) { // Add notifier and owner so we don't have to perform lookups during the phases and other processing ctb.tracker$getNotifierUUID().ifPresent(phaseContext::notifier); // Allow the tile entity to validate the owner of itself. As long as the tile entity // chunk is already loaded and activated, and the tile entity has already loaded // the owner of itself. ctb.tracker$getCreatorUUID().ifPresent(phaseContext::creator); } // Finally, switch the context now that we have the owner and notifier phaseContext.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.BLOCK_ENTITY_TICK, () -> "Wrapping Entity Tick: " + blockEntity); tick.run(); // If we know the viewers force broadcast now to associate the inventory change with its blockentity // otherwise the viewing players update this during their ticking if (blockEntity instanceof ViewableInventoryBridge vib) { final Set<ServerPlayer> players = vib.viewableBridge$getViewers(); if (!players.isEmpty()) { players.forEach(player -> player.containerMenu.broadcastChanges()); } } } catch (final Exception e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, context); } } public static void updateTickBlock( final TrackedWorldBridge mixinWorld, final net.minecraft.world.level.block.state.BlockState block, final BlockPos pos, final Runnable tick) { final ServerLevel world = (ServerLevel) mixinWorld; final org.spongepowered.api.world.server.ServerWorld apiWorld = (org.spongepowered.api.world.server.ServerWorld) world; if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot snapshot = mixinWorld.bridge$createSnapshot(block, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventScheduled(PhaseTracker.getInstance().currentCause(), snapshot); SpongeCommon.post(event); if (event.isCancelled()) { return; } } final LocatableBlock locatable = new SpongeLocatableBlockBuilder().world(apiWorld).position(pos.getX(), pos.getY(), pos.getZ()).state((BlockState)block).build(); final BlockTickContext phaseContext = TickPhase.Tick.BLOCK.createPhaseContext(PhaseTracker.SERVER).source(locatable); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseContext<@NonNull ?> currentContext = PhaseTracker.getInstance().getPhaseContext(); currentContext.appendNotifierPreBlockTick(world, pos, phaseContext); // Now actually switch to the new phase try (final PhaseContext<@NonNull ?> context = phaseContext) { context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.BLOCK_TICK, () -> "Wrapping Block Tick: " + block.toString()); tick.run(); } catch (final Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, phaseContext); } } public static void updateTickFluid( final TrackedWorldBridge mixinWorld, final FluidState fluidState, final BlockPos pos, final Runnable tick ) { final ServerLevel world = (ServerLevel) mixinWorld; final org.spongepowered.api.world.server.ServerWorld apiWorld = (org.spongepowered.api.world.server.ServerWorld) world; final net.minecraft.world.level.block.state.BlockState blockState = fluidState.createLegacyBlock(); if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot snapshot = mixinWorld.bridge$createSnapshot(blockState, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventScheduled(PhaseTracker.getInstance().currentCause(), snapshot); SpongeCommon.post(event); if (event.isCancelled()) { return; } } final LocatableBlock locatable = new SpongeLocatableBlockBuilder().world(apiWorld).position(pos.getX(), pos.getY(), pos.getZ()).state((BlockState) blockState).build(); final FluidTickContext phaseContext = TickPhase.Tick.FLUID.createPhaseContext(PhaseTracker.SERVER) .source(locatable) .fluid(fluidState); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseContext<@NonNull ?> currentContext = PhaseTracker.getInstance().getPhaseContext(); currentContext.appendNotifierPreBlockTick(world, pos, phaseContext); // Now actually switch to the new phase try (final PhaseContext<?> context = phaseContext) { context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.FLUID_TICK, () -> "Wrapping Fluid Tick: " + fluidState.toString()); tick.run(); } catch (final Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, phaseContext); } } @SuppressWarnings("rawtypes") public static void randomTickBlock( final TrackedWorldBridge mixinWorld, final net.minecraft.world.level.block.state.BlockState state, final BlockPos pos, final RandomSource random, final Runnable tick ) { final ServerLevel world = (ServerLevel) mixinWorld; final org.spongepowered.api.world.server.ServerWorld apiWorld = (org.spongepowered.api.world.server.ServerWorld) world; if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot currentTickBlock = mixinWorld.bridge$createSnapshot(state, pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventRandom(PhaseTracker.getInstance().currentCause(), currentTickBlock); SpongeCommon.post(event); if (event.isCancelled()) { return; } } final LocatableBlock locatable = new SpongeLocatableBlockBuilder() .world(apiWorld) .position(pos.getX(), pos.getY(), pos.getZ()) .state((BlockState) state) .build(); final BlockTickContext phaseContext = TickPhase.Tick.RANDOM_BLOCK.createPhaseContext(PhaseTracker.SERVER).source(locatable); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseContext<@NonNull ?> currentContext = PhaseTracker.getInstance().getPhaseContext(); currentContext.appendNotifierPreBlockTick(world, pos, phaseContext); // Now actually switch to the new phase try (final PhaseContext<@NonNull ?> context = phaseContext) { context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.BLOCK_TICK, "Wrapping Random Block Tick: {}", state); tick.run(); } catch (final Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, phaseContext); } } @SuppressWarnings("rawtypes") public static void randomTickFluid( final TrackedWorldBridge mixinWorld, final FluidState state, final BlockPos pos, final RandomSource random, final Runnable tick ) { final ServerLevel world = (ServerLevel) mixinWorld; final org.spongepowered.api.world.server.ServerWorld apiWorld = (org.spongepowered.api.world.server.ServerWorld) world; if (ShouldFire.TICK_BLOCK_EVENT) { final BlockSnapshot currentTickBlock = mixinWorld.bridge$createSnapshot(state.createLegacyBlock(), pos, BlockChangeFlags.NONE); final TickBlockEvent event = SpongeEventFactory.createTickBlockEventRandom(PhaseTracker.getInstance().currentCause(), currentTickBlock); SpongeCommon.post(event); if (event.isCancelled()) { return; } } final LocatableBlock locatable = new SpongeLocatableBlockBuilder() .world(apiWorld) .position(pos.getX(), pos.getY(), pos.getZ()) .state((BlockState) state.createLegacyBlock()) .build(); final FluidTickContext phaseContext = TickPhase.Tick.RANDOM_FLUID.createPhaseContext(PhaseTracker.SERVER) .source(locatable) .fluid(state); // We have to associate any notifiers in case of scheduled block updates from other sources final PhaseContext<@NonNull ?> currentContext = PhaseTracker.getInstance().getPhaseContext(); currentContext.appendNotifierPreBlockTick(world, pos, phaseContext); // Now actually switch to the new phase try (final PhaseContext<@NonNull ?> context = phaseContext) { context.buildAndSwitch(); PhaseTracker.LOGGER.trace(TrackingUtil.FLUID_TICK, () -> "Wrapping Random Fluid Tick: " + state.toString()); tick.run(); } catch (final Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, phaseContext); } } public static boolean fireMinecraftBlockEvent( final BlockEventData event, final BooleanSupplier tick ) { final TrackableBlockEventDataBridge blockEvent = (TrackableBlockEventDataBridge) (Object) event; final @Nullable Object source = blockEvent.bridge$getTileEntity() != null ? blockEvent.bridge$getTileEntity() : blockEvent.bridge$getTickingLocatable(); if (source == null) { // No source present which means we are ignoring the phase state return tick.getAsBoolean(); } final BlockEventTickContext phaseContext = TickPhase.Tick.BLOCK_EVENT.createPhaseContext(PhaseTracker.SERVER); phaseContext.source(source); final UUID user = ((TrackableBlockEventDataBridge) (Object) event).bridge$getSourceUserUUID(); if (user != null) { phaseContext.creator = user; phaseContext.notifier = user; } boolean result = true; try (final BlockEventTickContext o = phaseContext) { o.buildAndSwitch(); phaseContext.setEventSucceeded(tick.getAsBoolean()); // We need to grab the result here as the phase context close will trigger a reset result = phaseContext.wasNotCancelled(); } // We can't return onBlockEventReceived because the phase state may have cancelled all transactions // at which point we want to keep track of the return value from the target, and from the block events. return result; } private TrackingUtil() { } public static @Nullable UUID getNotifierOrOwnerFromBlock(final ServerLevel world, final BlockPos blockPos) { final LevelChunkBridge mixinChunk = (LevelChunkBridge) world.getChunkAt(blockPos); final UUID notifier = mixinChunk.bridge$getBlockNotifierUUID(blockPos).orElse(null); if (notifier != null) { return notifier; } return mixinChunk.bridge$getBlockCreatorUUID(blockPos).orElse(null); } public static Supplier<IllegalStateException> throwWithContext(final String s, final PhaseContext<?> phaseContext) { return () -> { final PrettyPrinter printer = new PrettyPrinter(60); printer.add("Exception trying to process over a phase!").centre().hr(); printer.addWrapped(TrackingUtil.WIDTH, "%s : %s", "State", phaseContext.state); printer.addWrapped(TrackingUtil.WIDTH, "%s :", "PhaseContext"); PhasePrinter.CONTEXT_PRINTER.accept(printer, phaseContext); printer.add("Stacktrace:"); final IllegalStateException exception = new IllegalStateException(s + " Please analyze the current phase context. "); printer.add(exception); printer.trace(System.err, SpongeCommon.logger(), Level.ERROR); return exception; }; } public static boolean processBlockCaptures(final PhaseContext<@NonNull ?> context) { final TransactionalCaptureSupplier transactor = context.getTransactor(); // Fail fast and check if it's empty. if (transactor.isEmpty()) { return false; } // Start the hybrid depth first batched iteration of transactions // Some rules of the iteration: /* 1) Each transaction can be potentially turned into a Transaction<BlockSnapshot> 2) If a transaction has children side effects, stop and throw the related event(s) to verify - the event was not cancelled - the event result was the same 3) If there are child side effects, repeat the process. */ return transactor.processTransactions(context); } public static void associateTrackerToTarget(final BlockChange blockChange, final BlockTransactionReceipt receipt, final UUID uuid) { final BlockSnapshot finalSnapshot = receipt.finalBlock(); final SpongeBlockSnapshot spongeSnapshot = (SpongeBlockSnapshot) finalSnapshot; final BlockPos pos = spongeSnapshot.getBlockPos(); final Block block = ((net.minecraft.world.level.block.state.BlockState) spongeSnapshot.state()).getBlock(); spongeSnapshot.getServerWorld() .map(world -> world.getChunkAt(pos)) .map(chunk -> (LevelChunkBridge) chunk) .ifPresent(spongeChunk -> { final PlayerTracker.Type trackerType = blockChange == BlockChange.PLACE ? PlayerTracker.Type.CREATOR : PlayerTracker.Type.NOTIFIER; spongeChunk.bridge$addTrackedBlockPosition(block, pos, uuid, trackerType); }); } public static void setCreatorReference(List<Entity> entities, ServerPlayer player) { for (final Entity currentEntity : entities) { if (currentEntity instanceof CreatorTrackedBridge) { ((CreatorTrackedBridge) currentEntity).tracker$setTrackedUUID(PlayerTracker.Type.CREATOR, ((org.spongepowered.api.entity.living.player.server.ServerPlayer) player).uniqueId()); } else { currentEntity.offer(Keys.CREATOR, player.getUUID()); } } } public static void addTileEntityToBuilder(final net.minecraft.world.level.block.entity.BlockEntity existing, final SpongeBlockSnapshot.BuilderImpl builder) { // TODO - gather custom data. try { final CompoundTag compound = existing.saveWithFullMetadata(existing.getLevel().registryAccess()); builder.addUnsafeCompound(compound); } catch (final Throwable t) { // ignore } } public static String phaseStateToString(final String type, final IPhaseState<?> state) { return TrackingUtil.phaseStateToString(type, null, state); } public static String phaseStateToString(final String type, final @Nullable String extra, final IPhaseState<?> state) { String name = state.getClass().getSimpleName(); name = name.replace("Phase", ""); name = name.replace("State", ""); name = name.replace(type, ""); if (extra == null) { return type + "{" + name + "}"; } else if (name.isEmpty()) { return type + "{" + extra + "}"; } else { return type + "{" + name + ":" + extra + "}"; } } public static SpongeBlockSnapshot createPooledSnapshot(final net.minecraft.world.level.block.state.BlockState state, final BlockPos pos, final BlockChangeFlag updateFlag, final int limit, final net.minecraft.world.level.block.entity.@Nullable BlockEntity blockEntity, final Supplier<ServerLevel> worldSupplier, final Supplier<Optional<UUID>> creatorSupplier, final Supplier<Optional<UUID>> notifierSupplier ) { final SpongeBlockSnapshot.BuilderImpl builder = SpongeBlockSnapshot.BuilderImpl.pooled(); builder.reset(); builder.blockState(state) .world(worldSupplier.get()) .position(VecHelper.toVector3i(pos)); creatorSupplier.get().ifPresent(builder::creator); notifierSupplier.get().ifPresent(builder::notifier); if (blockEntity != null) { TrackingUtil.addTileEntityToBuilder(blockEntity, builder); } builder.flag(updateFlag); return builder.build(); } }
0
0.968079
1
0.968079
game-dev
MEDIA
0.972804
game-dev
0.845386
1
0.845386
Cataclysm-TLG/Cataclysm-TLG
73,539
src/savegame.cpp
#include "game.h" // IWYU pragma: associated #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "achievement.h" #include "avatar.h" #include "basecamp.h" #include "cata_io.h" #include "cata_path.h" #include "city.h" #include "coordinates.h" #include "creature_tracker.h" #include "debug.h" #include "faction.h" #include "hash_utils.h" #include "input.h" #include "json.h" #include "json_loader.h" #include "kill_tracker.h" #include "map.h" #include "messages.h" #include "mission.h" #include "mongroup.h" #include "monster.h" #include "npc.h" #include "omdata.h" #include "options.h" #include "overmap.h" #include "overmapbuffer.h" #include "overmap_types.h" #include "path_info.h" #include "regional_settings.h" #include "scent_map.h" #include "stats_tracker.h" #include "timed_event.h" class overmap_connection; static const oter_str_id oter_forest( "forest" ); static const oter_str_id oter_forest_thick( "forest_thick" ); static const oter_str_id oter_lake_bed( "lake_bed" ); static const oter_str_id oter_lake_shore( "lake_shore" ); static const oter_str_id oter_lake_surface( "lake_surface" ); static const oter_str_id oter_lake_water_cube( "lake_water_cube" ); static const oter_str_id oter_ocean_bed( "ocean_bed" ); static const oter_str_id oter_ocean_shore( "ocean_shore" ); static const oter_str_id oter_ocean_surface( "ocean_surface" ); static const oter_str_id oter_ocean_water_cube( "ocean_water_cube" ); static const oter_str_id oter_omt_obsolete( "omt_obsolete" ); static const string_id<overmap_connection> overmap_connection_local_road( "local_road" ); #if defined(__ANDROID__) #include "input.h" extern std::map<std::string, std::list<input_event>> quick_shortcuts_map; #endif /* * Changes that break backwards compatibility should bump this number, so the game can * load a legacy format loader. */ const int savegame_version = 35; /* * This is a global set by detected version header in .sav, maps.txt, or overmap. * This allows loaders for classes that exist in multiple files (such as item) to have * support for backwards compatibility as well. */ int savegame_loading_version = savegame_version; /* * Save to opened character.sav */ void game::serialize_json( std::ostream &fout ) { /* * Format version 12: Fully json, save the header. Weather and memorial exist elsewhere. * To prevent (or encourage) confusion, there is no version 8. (cata 0.8 uses v7) */ // Header JsonOut json( fout, true ); // pretty-print json.start_object(); // basic game state information. json.member( "savegame_loading_version", savegame_version ); json.member( "turn", calendar::turn ); json.member( "calendar_start", calendar::start_of_cataclysm ); json.member( "game_start", calendar::start_of_game ); json.member( "initial_season", static_cast<int>( calendar::initial_season ) ); json.member( "auto_travel_mode", auto_travel_mode ); json.member( "run_mode", static_cast<int>( safe_mode ) ); json.member( "mostseen", mostseen ); // current map coordinates tripoint_abs_sm pos_abs_sm = get_map().get_abs_sub(); point_abs_om pos_om; tripoint_om_sm pos_sm; std::tie( pos_om, pos_sm ) = project_remain<coords::om>( pos_abs_sm ); json.member( "levx", pos_sm.x() ); json.member( "levy", pos_sm.y() ); json.member( "levz", pos_sm.z() ); json.member( "om_x", pos_om.x() ); json.member( "om_y", pos_om.y() ); // view offset json.member( "view_offset_x", u.view_offset.x() ); json.member( "view_offset_y", u.view_offset.y() ); json.member( "view_offset_z", u.view_offset.z() ); json.member( "grscent", scent.serialize() ); json.member( "typescent", scent.serialize( true ) ); // Then each monster json.member( "active_monsters", *critter_tracker ); json.member( "driving_view_offset", driving_view_offset ); json.member( "turnssincelastmon", turnssincelastmon ); json.member( "bVMonsterLookFire", bVMonsterLookFire ); // save stats. json.member( "kill_tracker", *kill_tracker_ptr ); json.member( "stats_tracker", *stats_tracker_ptr ); json.member( "achievements_tracker", *achievements_tracker_ptr ); json.member( "player", u ); json.member( "inactive_global_effect_on_condition_vector", inactive_global_effect_on_condition_vector ); //save queued effect_on_conditions queued_eocs temp_queued( queued_global_effect_on_conditions ); json.member( "queued_global_effect_on_conditions" ); json.start_array(); while( !temp_queued.empty() ) { json.start_object(); json.member( "time", temp_queued.top().time ); json.member( "eoc", temp_queued.top().eoc ); json.member( "context", temp_queued.top().context ); json.end_object(); temp_queued.pop(); } json.end_array(); global_variables_instance.serialize( json ); Messages::serialize( json ); json.member( "unique_npcs", unique_npcs ); json.end_object(); } std::string scent_map::serialize( bool is_type ) const { std::ostringstream rle_out; rle_out.imbue( std::locale::classic() ); if( is_type ) { rle_out << typescent.str(); } else { int rle_lastval = -1; int rle_count = 0; for( const auto &elem : grscent ) { for( const int &val : elem ) { if( val == rle_lastval ) { rle_count++; } else { if( rle_count ) { rle_out << rle_count << " "; } rle_out << val << " "; rle_lastval = val; rle_count = 1; } } } rle_out << rle_count; } return rle_out.str(); } static size_t chkversion( std::istream &fin ) { if( fin.peek() == '#' ) { std::string vline; getline( fin, vline ); std::string tmphash; std::string tmpver; int savedver = -1; std::stringstream vliness( vline ); vliness >> tmphash >> tmpver >> savedver; if( tmpver == "version" && savedver != -1 ) { savegame_loading_version = savedver; } } return fin.tellg(); } /* * Parse an open .sav file. */ void game::unserialize( std::istream &fin, const cata_path &path ) { try { size_t json_file_offset = chkversion( fin ); JsonObject data = json_loader::from_path_at_offset( path, json_file_offset ); if( data.has_member( "savegame_loading_version" ) ) { data.read( "savegame_loading_version", savegame_loading_version ); } unserialize_impl( data ); } catch( const JsonError &jsonerr ) { debugmsg( "Bad save json\n%s", jsonerr.c_str() ); return; } } void game::unserialize( std::string fin ) { try { JsonObject data = json_loader::from_string( std::move( fin ) ); savegame_loading_version = data.get_int( "savegame_loading_version" ); unserialize_impl( data ); } catch( const JsonError &jsonerr ) { debugmsg( "Bad save json\n%s", jsonerr.c_str() ); return; } } void game::unserialize_impl( const JsonObject &data ) { int tmpturn = 0; int tmpcalstart = 0; int tmprun = 0; tripoint_om_sm lev; point_abs_om com; data.read( "turn", tmpturn ); data.read( "calendar_start", tmpcalstart ); calendar::initial_season = static_cast<season_type>( data.get_int( "initial_season", static_cast<int>( SPRING ) ) ); data.read( "auto_travel_mode", auto_travel_mode ); data.read( "run_mode", tmprun ); data.read( "mostseen", mostseen ); data.read( "levx", lev.x() ); data.read( "levy", lev.y() ); data.read( "levz", lev.z() ); data.read( "om_x", com.x() ); data.read( "om_y", com.y() ); data.read( "view_offset_x", u.view_offset.x() ); data.read( "view_offset_y", u.view_offset.y() ); data.read( "view_offset_z", u.view_offset.z() ); calendar::turn = time_point( tmpturn ); calendar::start_of_cataclysm = time_point( tmpcalstart ); if( !data.read( "game_start", calendar::start_of_game ) ) { calendar::start_of_game = calendar::start_of_cataclysm; } load_map( project_combine( com, lev ), /*pump_events=*/true ); safe_mode = static_cast<safe_mode_type>( tmprun ); if( get_option<bool>( "SAFEMODE" ) && safe_mode == SAFE_MODE_OFF ) { safe_mode = SAFE_MODE_ON; } std::string linebuff; std::string linebuf; if( data.read( "grscent", linebuf ) && data.read( "typescent", linebuff ) ) { scent.deserialize( linebuf ); scent.deserialize( linebuff, true ); } else { scent.reset(); } data.read( "active_monsters", *critter_tracker ); data.has_null( "stair_monsters" ); // TEMPORARY until 0.G data.has_null( "monstairz" ); // TEMPORARY until 0.G data.read( "driving_view_offset", driving_view_offset ); data.read( "turnssincelastmon", turnssincelastmon ); data.read( "bVMonsterLookFire", bVMonsterLookFire ); data.read( "kill_tracker", *kill_tracker_ptr ); data.read( "player", u ); data.read( "inactive_global_effect_on_condition_vector", inactive_global_effect_on_condition_vector ); //load queued_eocs for( JsonObject elem : data.get_array( "queued_global_effect_on_conditions" ) ) { queued_eoc temp; temp.time = time_point( elem.get_int( "time" ) ); temp.eoc = effect_on_condition_id( elem.get_string( "eoc" ) ); elem.read( "context", temp.context ); queued_global_effect_on_conditions.push( temp ); } global_variables_instance.unserialize( data ); data.read( "unique_npcs", unique_npcs ); inp_mngr.pump_events(); data.read( "stats_tracker", *stats_tracker_ptr ); data.read( "achievements_tracker", *achievements_tracker_ptr ); inp_mngr.pump_events(); Messages::deserialize( data ); } void scent_map::deserialize( const std::string &data, bool is_type ) { std::istringstream buffer( data ); buffer.imbue( std::locale::classic() ); if( is_type ) { std::string str; buffer >> str; typescent = scenttype_id( str ); } else { int stmp = 0; int count = 0; for( auto &elem : grscent ) { for( int &val : elem ) { if( count == 0 ) { buffer >> stmp >> count; } count--; val = stmp; } } } } #if defined(__ANDROID__) ///// quick shortcuts void game::load_shortcuts( const cata_path &path ) { try { JsonValue jsin = json_loader::from_path( path ); JsonObject data = jsin.get_object(); if( get_option<bool>( "ANDROID_SHORTCUT_PERSISTENCE" ) ) { quick_shortcuts_map.clear(); for( const JsonMember &member : data.get_object( "quick_shortcuts" ) ) { std::list<input_event> &qslist = quick_shortcuts_map[member.name()]; for( const int i : member.get_array() ) { qslist.push_back( input_event( i, input_event_t::keyboard_char ) ); } } } } catch( const JsonError &jsonerr ) { debugmsg( "Bad shortcuts json\n%s", jsonerr.c_str() ); return; } } void game::save_shortcuts( std::ostream &fout ) { JsonOut json( fout, true ); // pretty-print json.start_object(); if( get_option<bool>( "ANDROID_SHORTCUT_PERSISTENCE" ) ) { json.member( "quick_shortcuts" ); json.start_object(); for( auto &e : quick_shortcuts_map ) { json.member( e.first ); const std::list<input_event> &qsl = e.second; json.start_array(); for( const auto &event : qsl ) { json.write( event.get_first_input() ); } json.end_array(); } json.end_object(); } json.end_object(); } #endif void overmap::load_monster_groups( const JsonArray &jsin ) { for( JsonArray mongroup_with_tripoints : jsin ) { mongroup new_group; new_group.deserialize( mongroup_with_tripoints.next_object() ); bool reset_target = false; if( new_group.target == point_abs_sm() ) { // Remove after 0.I reset_target = true; } JsonArray tripoints_json = mongroup_with_tripoints.next_array(); tripoint_om_sm temp; for( JsonValue tripoint_json : tripoints_json ) { temp.deserialize( tripoint_json ); new_group.abs_pos = project_combine( pos(), temp ); if( reset_target ) { // Remove after 0.I new_group.set_target( new_group.abs_pos.xy() ); } add_mon_group( new_group ); } if( mongroup_with_tripoints.has_more() ) { mongroup_with_tripoints.throw_error( 2, "Unexpected value for mongroups json" ); } } } void overmap::load_legacy_monstergroups( const JsonArray &jsin ) { for( JsonObject mongroup_json : jsin ) { mongroup new_group; new_group.deserialize_legacy( mongroup_json ); add_mon_group( new_group ); } } // throws std::exception void overmap::unserialize( const cata_path &file_name, std::istream &fin ) { size_t json_offset = chkversion( fin ); JsonValue jsin = json_loader::from_path_at_offset( file_name, json_offset ); unserialize( jsin.get_object() ); } void overmap::unserialize( std::istream &fin ) { chkversion( fin ); std::string s = std::string( std::istreambuf_iterator<char>( fin ), std::istreambuf_iterator<char>() ); JsonValue jsin = json_loader::from_string( std::move( s ) ); unserialize( jsin.get_object() ); } void overmap::unserialize( const JsonObject &jsobj ) { // These must be read in this order. if( jsobj.has_member( "mapgen_arg_storage" ) ) { jsobj.read( "mapgen_arg_storage", mapgen_arg_storage, true ); } if( jsobj.has_member( "mapgen_arg_index" ) ) { std::vector<std::pair<tripoint_om_omt, int>> flat_index; jsobj.read( "mapgen_arg_index", flat_index, true ); for( const std::pair<tripoint_om_omt, int> &p : flat_index ) { auto it = mapgen_arg_storage.get_iterator_from_index( p.second ); mapgen_args_index.emplace( p.first, &*it ); } } // Extract layers first so predecessor deduplication can happen. if( jsobj.has_member( "layers" ) ) { std::unordered_map<tripoint_om_omt, std::string> oter_id_migrations; std::vector<tripoint_abs_omt> camps_to_place; JsonArray layers_json = jsobj.get_array( "layers" ); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { JsonArray layer_json = layers_json.next_array(); int count = 0; std::string tmp_ter; oter_id tmp_otid( 0 ); for( int j = 0; j < OMAPY; j++ ) { for( int i = 0; i < OMAPX; i++ ) { if( count == 0 ) { { JsonArray rle_terrain = layer_json.next_array(); tmp_ter = rle_terrain.next_string(); count = rle_terrain.next_int(); if( rle_terrain.has_more() ) { rle_terrain.throw_error( 2, "Unexpected value in RLE encoding" ); } } if( is_oter_id_obsolete( tmp_ter ) ) { for( int p = i; p < i + count; p++ ) { oter_id_migrations.emplace( tripoint_om_omt( p, j, z - OVERMAP_DEPTH ), tmp_ter ); } } else if( oter_str_id( tmp_ter ).is_valid() ) { tmp_otid = oter_id( tmp_ter ); } else { debugmsg( "Loaded invalid oter_id '%s'", tmp_ter.c_str() ); tmp_otid = oter_omt_obsolete; } if( oter_id_should_have_camp( oter_str_id( tmp_ter )->get_type_id() ) ) { for( int p = i; p < i + count; p++ ) { camps_to_place.emplace_back( project_combine( pos(), tripoint_om_omt( p, j, z - OVERMAP_DEPTH ) ) ); } } } count--; layer[z].terrain[i][j] = tmp_otid; } } } migrate_oter_ids( oter_id_migrations ); migrate_camps( camps_to_place ); } for( JsonMember om_member : jsobj ) { const std::string name = om_member.name(); if( name == "region_id" ) { std::string new_region_id; om_member.read( new_region_id ); if( settings->id != new_region_id ) { t_regional_settings_map_citr rit = region_settings_map.find( new_region_id ); if( rit != region_settings_map.end() ) { // TODO: optimize settings = &rit->second; } } } else if( name == "mongroups" ) { load_legacy_monstergroups( om_member ); } else if( name == "monster_groups" ) { load_monster_groups( om_member ); } else if( name == "cities" ) { JsonArray cities_json = om_member; for( JsonObject city_json : cities_json ) { city new_city; for( JsonMember city_member : city_json ) { std::string city_member_name = city_member.name(); if( city_member_name == "name" ) { city_member.read( new_city.name ); } else if( city_member_name == "id" ) { city_member.read( new_city.id ); } else if( city_member_name == "database_id" ) { city_member.read( new_city.database_id ); } else if( city_member_name == "pos" ) { city_member.read( new_city.pos ); } else if( city_member_name == "pos_om" ) { city_member.read( new_city.pos_om ); } else if( city_member_name == "x" ) { city_member.read( new_city.pos.x() ); } else if( city_member_name == "y" ) { city_member.read( new_city.pos.y() ); } else if( city_member_name == "population" ) { city_member.read( new_city.population ); } else if( city_member_name == "size" ) { city_member.read( new_city.size ); } } cities.push_back( new_city ); } } else if( name == "city_tiles" ) { om_member.read( city_tiles ); } else if( name == "rivers" ) { JsonArray rivers_json = om_member; for( JsonObject river_json : rivers_json ) { point_om_omt start_point; point_om_omt end_point; point_om_omt control_1; point_om_omt control_2; uint64_t size; mandatory( river_json, false, "entry", start_point ); mandatory( river_json, false, "exit", end_point ); optional( river_json, false, "control1", control_1, point_om_omt::invalid ); optional( river_json, false, "control2", control_2, point_om_omt::invalid ); mandatory( river_json, false, "size", size ); rivers.push_back( overmap_river_node{ start_point, end_point, control_1, control_2, static_cast<size_t>( size ) } ); } } else if( name == "connections_out" ) { om_member.read( connections_out ); } else if( name == "roads_out" ) { // Legacy data, superseded by that stored in the "connections_out" member. A load and save // cycle will migrate this to "connections_out". std::vector<tripoint_om_omt> &roads_out = connections_out[overmap_connection_local_road]; JsonArray roads_json = om_member; for( JsonObject road_json : roads_json ) { tripoint_om_omt new_road; for( JsonMember road_member : road_json ) { std::string road_member_name = road_member.name(); if( road_member_name == "x" ) { road_member.read( new_road.x() ); } else if( road_member_name == "y" ) { road_member.read( new_road.y() ); } } roads_out.push_back( new_road ); } } else if( name == "radios" ) { JsonArray radios_json = om_member; for( JsonObject radio_json : radios_json ) { radio_tower new_radio{ point_om_sm::invalid }; for( JsonMember radio_member : radio_json ) { const std::string radio_member_name = radio_member.name(); if( radio_member_name == "type" ) { const std::string radio_name = radio_member.get_string(); const auto mapping = find_if( radio_type_names.begin(), radio_type_names.end(), [radio_name]( const std::pair<radio_type, std::string> &p ) { return p.second == radio_name; } ); if( mapping != radio_type_names.end() ) { new_radio.type = mapping->first; } } else if( radio_member_name == "x" ) { radio_member.read( new_radio.pos.x() ); } else if( radio_member_name == "y" ) { radio_member.read( new_radio.pos.y() ); } else if( radio_member_name == "strength" ) { radio_member.read( new_radio.strength ); } else if( radio_member_name == "message" ) { radio_member.read( new_radio.message ); } else if( radio_member_name == "frequency" ) { radio_member.read( new_radio.frequency ); } } radios.push_back( new_radio ); } } else if( name == "monster_map" ) { JsonArray monster_map_json = om_member; while( monster_map_json.has_more() ) { tripoint_om_sm monster_location; monster new_monster; monster_location.deserialize( monster_map_json.next_value() ); new_monster.deserialize( monster_map_json.next_object(), project_combine( loc, monster_location ) ); monster_map.insert( std::make_pair( monster_location, std::move( new_monster ) ) ); } } else if( name == "tracked_vehicles" ) { JsonArray tracked_vehicles_json = om_member; for( JsonObject tracked_vehicle_json : tracked_vehicles_json ) { om_vehicle new_tracker; int id; for( JsonMember tracker_member : tracked_vehicle_json ) { std::string tracker_member_name = tracker_member.name(); if( tracker_member_name == "id" ) { tracker_member.read( id ); } else if( tracker_member_name == "x" ) { tracker_member.read( new_tracker.p.x() ); } else if( tracker_member_name == "y" ) { tracker_member.read( new_tracker.p.y() ); } else if( tracker_member_name == "name" ) { tracker_member.read( new_tracker.name ); } } vehicles[id] = new_tracker; } } else if( name == "scent_traces" ) { JsonArray scents_json = om_member; for( JsonObject scent_json : scents_json ) { tripoint_abs_omt pos; time_point time = calendar::before_time_starts; int strength = 0; for( JsonMember scent_member : scent_json ) { std::string scent_member_name = scent_member.name(); if( scent_member_name == "pos" ) { scent_member.read( pos ); } else if( scent_member_name == "time" ) { scent_member.read( time ); } else if( scent_member_name == "strength" ) { scent_member.read( strength ); } } scents[pos] = scent_trace( time, strength ); } } else if( name == "npcs" ) { JsonArray npcs_json = om_member; for( JsonObject npc_json : npcs_json ) { shared_ptr_fast<npc> new_npc = make_shared_fast<npc>(); new_npc->deserialize( npc_json ); if( !new_npc->get_fac_id().str().empty() ) { new_npc->set_fac( new_npc->get_fac_id() ); } npcs.push_back( new_npc ); } } else if( name == "camps" ) { JsonArray camps_json = om_member; for( JsonObject camp_json : camps_json ) { basecamp new_camp; new_camp.deserialize( camp_json ); camps.push_back( new_camp ); } } else if( name == "overmap_special_placements" ) { JsonArray special_placements_json = om_member; for( JsonObject special_placement_json : special_placements_json ) { overmap_special_id s; bool is_safe_zone = false; if( special_placement_json.has_member( "special" ) ) { special_placement_json.read( "special", s ); s = overmap_special_migration::migrate( s ); if( !s.is_null() ) { is_safe_zone = s->has_flag( "SAFE_AT_WORLDGEN" ); } } for( JsonMember special_placement_member : special_placement_json ) { std::string name = special_placement_member.name(); if( name == "placements" ) { JsonArray placements_json = special_placement_member; for( JsonObject placement_json : placements_json ) { for( JsonMember placement_member : placement_json ) { std::string name = placement_member.name(); if( name == "points" ) { JsonArray points_json = placement_member; for( JsonObject point_json : points_json ) { tripoint_om_omt p; for( JsonMember point_member : point_json ) { std::string name = point_member.name(); if( name == "p" ) { point_member.read( p ); if( !s.is_null() ) { overmap_special_placements[p] = s; if( is_safe_zone ) { safe_at_worldgen.emplace( p ); } } } } } } } } } } } } else if( name == "joins_used" ) { std::vector<std::pair<om_pos_dir, std::string>> flat_index; om_member.read( flat_index, true ); for( const std::pair<om_pos_dir, std::string> &p : flat_index ) { joins_used.insert( p ); } } else if( name == "predecessors" ) { std::vector<std::pair<tripoint_om_omt, std::vector<oter_id>>> flattened_predecessors; JsonArray predecessors_json = om_member; for( JsonArray point_and_predecessors : predecessors_json ) { if( point_and_predecessors.size() != 2 ) { point_and_predecessors.throw_error( 2, "Invalid overmap predecessors: expected a point and an array" ); } tripoint_om_omt point; point_and_predecessors.read( 0, point, true ); std::vector<oter_id> predecessors; for( std::string oterid : point_and_predecessors.get_array( 1 ) ) { predecessors.push_back( get_or_migrate_oter( oterid ) ); } flattened_predecessors.emplace_back( point, std::move( predecessors ) ); } std::vector<oter_id> om_predecessors; for( auto& [p, serialized_predecessors] : flattened_predecessors ) { if( !serialized_predecessors.empty() ) { // TODO remove after 0.H release. // JSONizing roads caused some bad mapgen data to get saved to disk. Fixup bad saves to conform. // The logic to do this is to emulate setting overmap::set_ter repeatedly. The difference is the // 'original' terrain is lost, all we have is a chain of predecessors. // This doesn't matter for the sake of deduplicating predecessors. // // Mapgen refinement can push multiple different roads over each other. // Roads require a predecessor. A road pushed over a road might cause a // road to be a predecessor to another road. That causes too many spawns // to happen. So when pushing a predecessor, if the predecessor to-be-pushed // is linear and the previous predecessor is linear, overwrite it. // This way only the 'last' rotation/variation generated is kept. om_predecessors.reserve( serialized_predecessors.size() ); oter_id current_oter; auto local_set_ter = [&]( oter_id & id ) { const oter_type_str_id &current_type_id = current_oter->get_type_id(); const oter_type_str_id &incoming_type_id = id->get_type_id(); const bool current_type_same = current_type_id == incoming_type_id; if( om_predecessors.empty() || ( !current_oter->is_linear() && !current_type_same ) ) { // If we need a predecessor, we must have a predecessor no matter what. // Or, if the oter to-be-pushed is not linear, push it only if the incoming oter is different. om_predecessors.push_back( current_oter ); } else if( !current_type_same ) { // Current oter is linear, incoming oter is different from current. // If the last predecessor is the same type as the current type, overwrite. // Else push the current type. oter_id &last_predecessor = om_predecessors.back(); if( last_predecessor->get_type_id() == current_type_id ) { last_predecessor = current_oter; } else { om_predecessors.push_back( current_oter ); } } current_oter = id; }; current_oter = serialized_predecessors.front(); for( size_t i = 1; i < serialized_predecessors.size(); ++i ) { local_set_ter( serialized_predecessors[i] ); } local_set_ter( layer[p.z() + OVERMAP_DEPTH].terrain[p.xy()] ); } predecessors_.insert_or_assign( p, std::move( om_predecessors ) ); // Reuse allocations because it's a good habit. om_predecessors = std::move( serialized_predecessors ); om_predecessors.clear(); } } } } // throws std::exception void overmap::unserialize_omap( const JsonValue &jsin, const cata_path &json_path ) { JsonArray ja = jsin.get_array(); JsonObject jo = ja.next_object(); std::string type; point_abs_om om_pos = point_abs_om::invalid; int z = 0; jo.read( "type", type ); jo.read( "om_pos", om_pos ); jo.read( "z", z ); JsonArray jal = jo.get_array( "layers" ); std::vector<tripoint_om_omt> lake_points; std::vector<tripoint_om_omt> ocean_points; std::vector<tripoint_om_omt> forest_points; if( type == "overmap" ) { std::unordered_map<tripoint_om_omt, std::string> oter_id_migrations; if( om_pos != pos() ) { debugmsg( "Loaded invalid overmap from omap file %s. Loaded %s, expected %s", json_path.generic_u8string(), om_pos.to_string(), pos().to_string() ); } else { int count = 0; std::string tmp_ter; oter_id tmp_otid( 0 ); for( int j = 0; j < OMAPY; j++ ) { for( int i = 0; i < OMAPX; i++ ) { if( count == 0 ) { JsonArray jat = jal.next_array(); tmp_ter = jat.next_string(); count = jat.next_int(); if( is_oter_id_obsolete( tmp_ter ) ) { for( int p = i; p < i + count; p++ ) { oter_id_migrations.emplace( tripoint_om_omt( p, j, z - OVERMAP_DEPTH ), tmp_ter ); } } else if( oter_str_id( tmp_ter ).is_valid() ) { tmp_otid = oter_id( tmp_ter ); } else { debugmsg( "Loaded invalid oter_id '%s'", tmp_ter.c_str() ); tmp_otid = oter_omt_obsolete; } } count--; layer[z + OVERMAP_DEPTH].terrain[i][j] = tmp_otid; if( tmp_otid == oter_lake_shore || tmp_otid == oter_lake_surface ) { lake_points.emplace_back( i, j, z ); } if( tmp_otid == oter_ocean_shore || tmp_otid == oter_ocean_surface ) { ocean_points.emplace_back( i, j, z ); } if( tmp_otid == oter_forest || tmp_otid == oter_forest_thick ) { forest_points.emplace_back( i, j, z ); } } } } migrate_oter_ids( oter_id_migrations ); } std::unordered_set<tripoint_om_omt> lake_set; for( auto &p : lake_points ) { lake_set.emplace( p ); } for( auto &p : lake_points ) { if( !inbounds( p ) ) { continue; } bool shore = false; for( int ni = -1; ni <= 1 && !shore; ni++ ) { for( int nj = -1; nj <= 1 && !shore; nj++ ) { const tripoint_om_omt n = p + point( ni, nj ); if( inbounds( n, 1 ) && lake_set.find( n ) == lake_set.end() ) { shore = true; } } } ter_set( p, shore ? oter_lake_shore : oter_lake_surface ); // If this is not a shore, we'll make our subsurface lake cubes and beds. if( !shore ) { for( int z = -1; z > settings->overmap_lake.lake_depth; z-- ) { ter_set( tripoint_om_omt( p.xy(), z ), oter_lake_water_cube ); } ter_set( tripoint_om_omt( p.xy(), settings->overmap_lake.lake_depth ), oter_lake_bed ); layer[p.z() + OVERMAP_DEPTH].terrain[p.x()][p.y()] = oter_lake_surface; } } std::unordered_set<tripoint_om_omt> ocean_set; for( auto &p : ocean_points ) { ocean_set.emplace( p ); } for( auto &p : ocean_points ) { if( !inbounds( p ) ) { continue; } bool shore = false; for( int ni = -1; ni <= 1 && !shore; ni++ ) { for( int nj = -1; nj <= 1 && !shore; nj++ ) { const tripoint_om_omt n = p + point( ni, nj ); if( inbounds( n, 1 ) && ocean_set.find( n ) == ocean_set.end() ) { shore = true; } } } ter_set( p, shore ? oter_ocean_shore : oter_ocean_surface ); // If this is not a shore, we'll make our subsurface ocean cubes and beds. if( !shore ) { for( int z = -1; z > settings->overmap_ocean.ocean_depth; z-- ) { ter_set( tripoint_om_omt( p.xy(), z ), oter_ocean_water_cube ); } ter_set( tripoint_om_omt( p.xy(), settings->overmap_ocean.ocean_depth ), oter_ocean_bed ); layer[p.z() + OVERMAP_DEPTH].terrain[p.x()][p.y()] = oter_ocean_surface; } } std::unordered_set<tripoint_om_omt> forest_set; for( auto &p : forest_points ) { forest_set.emplace( p ); } for( auto &p : forest_points ) { if( !inbounds( p ) ) { continue; } bool forest_border = false; for( int ni = -1; ni <= 1 && !forest_border; ni++ ) { for( int nj = -1; nj <= 1 && !forest_border; nj++ ) { const tripoint_om_omt n = p + point( ni, nj ); if( inbounds( n, 1 ) && forest_set.find( n ) == forest_set.end() ) { forest_border = true; } } } ter_set( p, forest_border ? oter_forest : oter_forest_thick ); } } template<typename MdArray> static void unserialize_array_from_compacted_sequence( JsonArray &ja, MdArray &array ) { int count = 0; using Value = typename MdArray::value_type; Value value = Value(); for( size_t j = 0; j < MdArray::size_y; ++j ) { for( size_t i = 0; i < MdArray::size_x; ++i ) { if( count == 0 ) { JsonArray sequence = ja.next_array(); sequence.read_next( value ); sequence.read_next( count ); if( sequence.size() > 2 ) { sequence.throw_error( "Too many values for compacted sequence" ); } } count--; array[i][j] = value; } } } // throws std::exception void overmap::unserialize_view( const cata_path &file_name, std::istream &fin ) { size_t json_offset = chkversion( fin ); JsonValue jsin = json_loader::from_path_at_offset( file_name, json_offset ); unserialize_view( jsin.get_object() ); } void overmap::unserialize_view( const JsonObject &jsobj ) { for( JsonMember view_member : jsobj ) { const std::string name = view_member.name(); if( name == "visible" ) { JsonArray visible_json = view_member; for( int z = 0; z < OVERMAP_LAYERS; ++z ) { JsonArray visible_by_z_json = visible_json.next_array(); if( savegame_loading_version < 34 ) { cata::mdarray<bool, point_om_omt> old_vision; unserialize_array_from_compacted_sequence( visible_by_z_json, old_vision ); for( int y = 0; y < OMAPY; ++y ) { for( int x = 0; x < OMAPX; ++x ) { point_om_omt idx( x, y ); layer[z].visible[idx] = old_vision[idx] ? om_vision_level::full : om_vision_level::unseen; } } } else { unserialize_array_from_compacted_sequence( visible_by_z_json, layer[z].visible ); } if( visible_by_z_json.has_more() ) { visible_by_z_json.throw_error( "Too many sequences for z visible view" ); } } if( visible_json.has_more() ) { visible_json.throw_error( "Too many views by z count" ); } } else if( name == "explored" ) { JsonArray explored_json = view_member; for( int z = 0; z < OVERMAP_LAYERS; ++z ) { JsonArray explored_by_z_json = explored_json.next_array(); unserialize_array_from_compacted_sequence( explored_by_z_json, layer[z].explored ); if( explored_by_z_json.has_more() ) { explored_by_z_json.throw_error( "Too many sequences for z explored view" ); } } if( explored_json.has_more() ) { explored_json.throw_error( "Too many views by z count" ); } } else if( name == "notes" ) { JsonArray notes_json = view_member; for( int z = 0; z < OVERMAP_LAYERS; ++z ) { JsonArray notes_by_z_json = notes_json.next_array(); for( JsonArray note_json : notes_by_z_json ) { om_note tmp; note_json.read_next( tmp.p.x() ); note_json.read_next( tmp.p.y() ); note_json.read_next( tmp.text ); note_json.read_next( tmp.dangerous ); note_json.read_next( tmp.danger_radius ); if( note_json.size() > 5 ) { note_json.throw_error( "Too many values for note" ); } layer[z].notes.push_back( tmp ); } } if( notes_json.has_more() ) { notes_json.throw_error( "Too many notes by z count" ); } } else if( name == "extras" ) { JsonArray extras_json = view_member; for( int z = 0; z < OVERMAP_LAYERS; ++z ) { JsonArray extras_by_z = extras_json.next_array(); for( JsonArray extra_json : extras_by_z ) { om_map_extra tmp; extra_json.read_next( tmp.p.x() ); extra_json.read_next( tmp.p.y() ); extra_json.read_next( tmp.id ); if( extra_json.has_more() ) { extra_json.throw_error( "Too many values for extra" ); } // obsoleted extras can still appear here, so skip them if( tmp.id.is_valid() ) { layer[z].extras.push_back( tmp ); } } } if( extras_json.has_more() ) { extras_json.throw_error( "Too many extras by z count" ); } } } } template<typename MdArray> static void serialize_enum_array_to_compacted_sequence( JsonOut &json, const MdArray &array ) { using enum_type = typename MdArray::value_type; int count = 0; enum_type lastval = enum_traits<enum_type>::last; for( size_t j = 0; j < MdArray::size_y; ++j ) { for( size_t i = 0; i < MdArray::size_x; ++i ) { const enum_type value = array[i][j]; if( value == lastval ) { ++count; continue; } if( count != 0 ) { json.write( count ); json.end_array(); } lastval = value; json.start_array(); json.write( value ); count = 1; } } json.write( count ); json.end_array(); } template<typename MdArray> static void serialize_array_to_compacted_sequence( JsonOut &json, const MdArray &array ) { static_assert( std::is_same_v<typename MdArray::value_type, bool>, "This implementation assumes bool, in that the initial value of lastval has " "to not be a valid value of the content" ); int count = 0; int lastval = -1; for( size_t j = 0; j < MdArray::size_y; ++j ) { for( size_t i = 0; i < MdArray::size_x; ++i ) { const int value = array[i][j]; if( value != lastval ) { if( count ) { json.write( count ); json.end_array(); } lastval = value; json.start_array(); json.write( static_cast<bool>( value ) ); count = 1; } else { count++; } } } json.write( count ); json.end_array(); } void overmap::serialize_view( std::ostream &fout ) const { fout << "# version " << savegame_version << std::endl; JsonOut json( fout, false ); json.start_object(); json.member( "visible" ); json.start_array(); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { json.start_array(); serialize_enum_array_to_compacted_sequence( json, layer[z].visible ); json.end_array(); fout << std::endl; } json.end_array(); json.member( "explored" ); json.start_array(); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { json.start_array(); serialize_array_to_compacted_sequence( json, layer[z].explored ); json.end_array(); fout << std::endl; } json.end_array(); json.member( "notes" ); json.start_array(); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { json.start_array(); for( const om_note &i : layer[z].notes ) { json.start_array(); json.write( i.p.x() ); json.write( i.p.y() ); json.write( i.text ); json.write( i.dangerous ); json.write( i.danger_radius ); json.end_array(); fout << std::endl; } json.end_array(); } json.end_array(); json.member( "extras" ); json.start_array(); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { json.start_array(); for( const om_map_extra &i : layer[z].extras ) { json.start_array(); json.write( i.p.x() ); json.write( i.p.y() ); json.write( i.id ); json.end_array(); fout << std::endl; } json.end_array(); } json.end_array(); json.end_object(); } // Compares all fields except position and monsters // If any group has monsters, it is never equal to any group (because monsters are unique) struct mongroup_bin_eq { bool operator()( const mongroup &a, const mongroup &b ) const { return a.monsters.empty() && b.monsters.empty() && a.type == b.type && a.population == b.population && a.target == b.target && a.interest == b.interest && a.dying == b.dying && a.horde == b.horde && a.behaviour == b.behaviour; } }; struct mongroup_hash { std::size_t operator()( const mongroup &mg ) const { // Note: not hashing monsters or position size_t ret = std::hash<mongroup_id>()( mg.type ); cata::hash_combine( ret, mg.population ); cata::hash_combine( ret, mg.target ); cata::hash_combine( ret, mg.interest ); cata::hash_combine( ret, mg.dying ); cata::hash_combine( ret, mg.horde ); cata::hash_combine( ret, mg.behaviour ); return ret; } }; void overmap::save_monster_groups( JsonOut &jout ) const { jout.member( "monster_groups" ); jout.start_array(); // Bin groups by their fields, except positions and monsters std::unordered_map<mongroup, std::list<tripoint_om_sm>, mongroup_hash, mongroup_bin_eq> binned_groups; binned_groups.reserve( zg.size() ); for( const auto &pos_group : zg ) { // Each group in bin adds only position // so that 100 identical groups are 1 group data and 100 tripoints std::list<tripoint_om_sm> &positions = binned_groups[pos_group.second]; positions.emplace_back( pos_group.first ); } for( auto &group_bin : binned_groups ) { jout.start_array(); // Zero the bin position so that it isn't serialized // The position is stored separately, in the list // TODO: Do it without the copy mongroup saved_group = group_bin.first; saved_group.abs_pos = tripoint_abs_sm::zero; jout.write( saved_group ); jout.write( group_bin.second ); jout.end_array(); } jout.end_array(); } void overmap::serialize( std::ostream &fout ) const { fout << "# version " << savegame_version << std::endl; JsonOut json( fout, false ); json.start_object(); json.member( "layers" ); json.start_array(); for( int z = 0; z < OVERMAP_LAYERS; ++z ) { const auto &layer_terrain = layer[z].terrain; int count = 0; oter_id last_tertype( -1 ); json.start_array(); for( int j = 0; j < OMAPY; j++ ) { // NOLINTNEXTLINE(modernize-loop-convert) for( int i = 0; i < OMAPX; i++ ) { oter_id t = layer_terrain[i][j]; if( t != last_tertype ) { if( count ) { json.write( count ); json.end_array(); } last_tertype = t; json.start_array(); json.write( t.id() ); count = 1; } else { count++; } } } json.write( count ); // End the last entry for a z-level. json.end_array(); // End the z-level json.end_array(); // Insert a newline occasionally so the file isn't totally unreadable. fout << std::endl; } json.end_array(); // temporary, to allow user to manually switch regions during play until regionmap is done. json.member( "region_id", settings->id ); fout << std::endl; save_monster_groups( json ); fout << std::endl; json.member( "cities" ); json.start_array(); for( const city &i : cities ) { json.start_object(); json.member( "name", i.name ); json.member( "id", i.id ); json.member( "database_id", i.database_id ); json.member( "pos_om", i.pos_om ); json.member( "pos", i.pos ); json.member( "population", i.population ); json.member( "size", i.size ); json.end_object(); } json.end_array(); fout << std::endl; json.member( "city_tiles", city_tiles ); json.member( "rivers" ); json.start_array(); for( const overmap_river_node &i : rivers ) { json.start_object(); json.member( "entry", i.river_start ); json.member( "exit", i.river_end ); json.member( "size", i.size ); if( !i.control_p1.is_invalid() ) { json.member( "control1", i.control_p1 ); } if( !i.control_p2.is_invalid() ) { json.member( "control2", i.control_p2 ); } json.end_object(); } json.end_array(); fout << std::endl; json.member( "connections_out", connections_out ); fout << std::endl; json.member( "radios" ); json.start_array(); for( const radio_tower &i : radios ) { json.start_object(); json.member( "x", i.pos.x() ); json.member( "y", i.pos.y() ); json.member( "strength", i.strength ); json.member( "type", radio_type_names[i.type] ); json.member( "message", i.message ); json.member( "frequency", i.frequency ); json.end_object(); } json.end_array(); fout << std::endl; json.member( "monster_map" ); json.start_array(); for( const auto &i : monster_map ) { i.first.serialize( json ); i.second.serialize( json ); } json.end_array(); fout << std::endl; json.member( "tracked_vehicles" ); json.start_array(); for( const auto &i : vehicles ) { json.start_object(); json.member( "id", i.first ); json.member( "name", i.second.name ); json.member( "x", i.second.p.x() ); json.member( "y", i.second.p.y() ); json.end_object(); } json.end_array(); fout << std::endl; json.member( "scent_traces" ); json.start_array(); for( const auto &scent : scents ) { json.start_object(); json.member( "pos", scent.first ); json.member( "time", scent.second.creation_time ); json.member( "strength", scent.second.initial_strength ); json.end_object(); } json.end_array(); fout << std::endl; json.member( "npcs" ); json.start_array(); for( const auto &i : npcs ) { json.write( *i ); } json.end_array(); fout << std::endl; json.member( "camps" ); json.start_array(); for( const basecamp &i : camps ) { json.write( i ); } json.end_array(); fout << std::endl; // Condense the overmap special placements so that all placements of a given special // are grouped under a single key for that special. std::map<overmap_special_id, std::vector<tripoint_om_omt>> condensed_overmap_special_placements; for( const auto &placement : overmap_special_placements ) { condensed_overmap_special_placements[placement.second].emplace_back( placement.first ); } json.member( "overmap_special_placements" ); json.start_array(); for( const auto &placement : condensed_overmap_special_placements ) { json.start_object(); json.member( "special", placement.first ); json.member( "placements" ); json.start_array(); // When we have a discriminator for different instances of a given special, // we'd use that that group them, but since that doesn't exist yet we'll // dump all the points of a given special into a single entry. json.start_object(); json.member( "points" ); json.start_array(); for( const tripoint_om_omt &pos : placement.second ) { json.start_object(); json.member( "p", pos ); json.end_object(); } json.end_array(); json.end_object(); json.end_array(); json.end_object(); } json.end_array(); fout << std::endl; json.member( "mapgen_arg_storage", mapgen_arg_storage ); fout << std::endl; json.member( "mapgen_arg_index" ); json.start_array(); for( const std::pair<const tripoint_om_omt, std::optional<mapgen_arguments> *> &p : mapgen_args_index ) { json.start_array(); json.write( p.first ); auto it = mapgen_arg_storage.get_iterator_from_pointer( p.second ); int index = mapgen_arg_storage.get_index_from_iterator( it ); json.write( index ); json.end_array(); } json.end_array(); fout << std::endl; std::vector<std::pair<om_pos_dir, std::string>> flattened_joins_used( joins_used.begin(), joins_used.end() ); json.member( "joins_used", flattened_joins_used ); fout << std::endl; std::vector<std::pair<tripoint_om_omt, std::vector<oter_id>>> flattened_predecessors( predecessors_.begin(), predecessors_.end() ); json.member( "predecessors", flattened_predecessors ); fout << std::endl; json.end_object(); fout << std::endl; } //////////////////////////////////////////////////////////////////////////////////////// ///// mongroup template<typename Archive> void mongroup::io( Archive &archive ) { archive.io( "type", type ); archive.io( "abs_pos", abs_pos, tripoint_abs_sm::zero ); archive.io( "population", population, 1u ); archive.io( "dying", dying, false ); archive.io( "horde", horde, false ); archive.io( "target", target, point_abs_sm::zero ); archive.io( "nemesis_target", nemesis_target, point_abs_sm::zero ); archive.io( "interest", interest, 0 ); archive.io( "horde_behaviour", behaviour, horde_behaviour::none ); archive.io( "monsters", monsters, io::empty_default_tag() ); } void mongroup::deserialize( const JsonObject &jo ) { jo.allow_omitted_members(); io::JsonObjectInputArchive archive( jo ); io( archive ); } void mongroup::serialize( JsonOut &json ) const { io::JsonObjectOutputArchive archive( json ); const_cast<mongroup *>( this )->io( archive ); } void mongroup::deserialize_legacy( const JsonObject &jo ) { for( JsonMember json : jo ) { std::string name = json.name(); if( name == "type" ) { type = mongroup_id( json.get_string() ); } else if( name == "abs_pos" ) { abs_pos.deserialize( json ); } else if( name == "population" ) { population = json.get_int(); } else if( name == "dying" ) { dying = json.get_bool(); } else if( name == "horde" ) { horde = json.get_bool(); } else if( name == "target" ) { target.deserialize( json ); } else if( name == "nemesis_target" ) { nemesis_target.deserialize( json ); } else if( name == "interest" ) { interest = json.get_int(); } else if( name == "horde_behaviour" ) { json.read( behaviour ); } else if( name == "monsters" ) { JsonArray ja = json; for( JsonObject monster_json : ja ) { monster new_monster; new_monster.deserialize( monster_json ); monsters.push_back( new_monster ); } } } } //////////////////////////////////////////////////////////////////////////////////////// ///// mapbuffer /////////////////////////////////////////////////////////////////////////////////////// ///// SAVE_MASTER (i.e. master.gsav) void mission::unserialize_all( const JsonArray &ja ) { for( JsonObject jo : ja ) { mission mis; mis.deserialize( jo ); add_existing( mis ); } } void game::unserialize_master( const cata_path &file_name, std::istream &fin ) { savegame_loading_version = 0; size_t json_offset = chkversion( fin ); try { JsonValue jv = json_loader::from_path_at_offset( file_name, json_offset ); unserialize_master( jv ); } catch( const JsonError &e ) { debugmsg( "error loading %s: %s", SAVE_MASTER, e.c_str() ); } } void game::unserialize_master( const JsonValue &jv ) { JsonObject game_json = jv; for( JsonMember jsin : game_json ) { std::string name = jsin.name(); if( name == "next_mission_id" ) { next_mission_id = jsin.get_int(); } else if( name == "next_npc_id" ) { next_npc_id.deserialize( jsin ); } else if( name == "active_missions" ) { mission::unserialize_all( jsin ); } else if( name == "factions" ) { jsin.read( *faction_manager_ptr ); } else if( name == "seed" ) { jsin.read( seed ); } else if( name == "weather" ) { weather_manager::unserialize_all( jsin ); } else if( name == "timed_events" ) { timed_event_manager::unserialize_all( jsin ); } else if( name == "overmapbuffer" ) { overmap_buffer.deserialize_overmap_global_state( jsin ); } else if( name == "placed_unique_specials" ) { overmap_buffer.deserialize_placed_unique_specials( jsin ); } } } void mission::serialize_all( JsonOut &json ) { json.start_array(); for( mission *&e : get_all_active() ) { e->serialize( json ); } json.end_array(); } void weather_manager::serialize_all( JsonOut &json ) { weather_manager &weather = get_weather(); json.start_object(); json.member( "lightning", weather.lightning_active ); json.member( "weather_id", weather.weather_id ); json.member( "next_weather", weather.nextweather ); json.member( "temperature", units::to_fahrenheit( weather.temperature ) ); json.member( "winddirection", weather.winddirection ); json.member( "windspeed", weather.windspeed ); if( weather.forced_temperature ) { json.member( "forced_temperature", units::to_fahrenheit( *weather.forced_temperature ) ); } json.end_object(); } void weather_manager::unserialize_all( const JsonObject &w ) { w.read( "lightning", get_weather().lightning_active ); w.read( "weather_id", get_weather().weather_id ); w.read( "next_weather", get_weather().nextweather ); float read_temperature; w.read( "temperature", read_temperature ); get_weather().temperature = units::from_fahrenheit( read_temperature ); w.read( "winddirection", get_weather().winddirection ); w.read( "windspeed", get_weather().windspeed ); if( w.has_member( "forced_temperature" ) ) { float read_forced_temp; w.read( "forced_temperature", read_forced_temp ); get_weather().forced_temperature = units::from_fahrenheit( read_forced_temp ); } else { get_weather().forced_temperature.reset(); } } void global_variables::unserialize( const JsonObject &jo ) { // global variables jo.read( "global_vals", global_values ); // potentially migrate some variable names for( std::pair<std::string, std::string> migration : migrations ) { if( global_values.count( migration.first ) != 0 ) { auto extracted = global_values.extract( migration.first ); extracted.key() = migration.second; global_values.insert( std::move( extracted ) ); } } game::legacy_migrate_npctalk_var_prefix( global_values ); } void timed_event_manager::unserialize_all( const JsonArray &ja ) { for( JsonObject jo : ja ) { int type; time_point when; int faction_id; int strength; tripoint_abs_ms map_square; tripoint_abs_sm map_point; std::string string_id; std::string key; submap revert; jo.read( "faction", faction_id ); jo.read( "map_point", map_point ); jo.read( "map_square", map_square, false ); jo.read( "strength", strength ); jo.read( "string_id", string_id ); jo.read( "type", type ); jo.read( "when", when ); jo.read( "key", key ); point_sm_ms pt; if( jo.has_string( "revert" ) ) { revert.set_all_ter( ter_id( jo.get_string( "revert" ) ), true ); } else { for( JsonObject jp : jo.get_array( "revert" ) ) { if( jp.has_member( "point" ) ) { jp.get_member( "point" ).read( pt, false ); } revert.set_furn( pt, furn_id( jp.get_string( "furn" ) ) ); revert.set_ter( pt, ter_id( jp.get_string( "ter" ) ) ); revert.set_trap( pt, trap_id( jp.get_string( "trap" ) ) ); if( jp.has_member( "items" ) ) { cata::colony<item> itm; jp.get_member( "items" ).read( itm, false ); revert.get_items( pt ) = std::move( itm ); } // We didn't always save the point, this is the original logic, it doesn't work right but for older saves at least they won't crash if( !jp.has_member( "point" ) ) { if( pt.x()++ < SEEX ) { pt.x() = 0; pt.y()++; } } } } get_timed_events().add( static_cast<timed_event_type>( type ), when, faction_id, map_square, strength, string_id, std::move( revert ), key ); } } void game::serialize_master( std::ostream &fout ) { fout << "# version " << savegame_version << std::endl; try { JsonOut json( fout, true ); // pretty-print json.start_object(); json.member( "next_mission_id", next_mission_id ); json.member( "next_npc_id", next_npc_id ); json.member( "active_missions" ); mission::serialize_all( json ); json.member( "overmapbuffer" ); overmap_buffer.serialize_overmap_global_state( json ); json.member( "timed_events" ); timed_event_manager::serialize_all( json ); json.member( "factions", *faction_manager_ptr ); json.member( "seed", seed ); json.member( "weather" ); weather_manager::serialize_all( json ); json.end_object(); } catch( const JsonError &e ) { debugmsg( "error saving to %s: %s", SAVE_MASTER, e.c_str() ); } } void faction_manager::serialize( JsonOut &jsout ) const { std::vector<faction> local_facs; local_facs.reserve( factions.size() ); for( const auto &elem : factions ) { local_facs.push_back( elem.second ); } jsout.write( local_facs ); } void global_variables::serialize( JsonOut &jsout ) const { jsout.member( "global_vals", global_values ); } void global_variables::load_migrations( const JsonObject &jo, const std::string_view & ) { const std::string from( jo.get_string( "from" ) ); const std::string to = jo.has_string( "to" ) ? jo.get_string( "to" ) : "NULL_VALUE"; get_globals().migrations.emplace( from, to ); } void timed_event_manager::serialize_all( JsonOut &jsout ) { jsout.start_array(); for( const timed_event &elem : get_timed_events().events ) { jsout.start_object(); jsout.member( "faction", elem.faction_id ); jsout.member( "map_point", elem.map_point ); jsout.member( "map_square", elem.map_square ); jsout.member( "strength", elem.strength ); jsout.member( "string_id", elem.string_id ); jsout.member( "type", elem.type ); jsout.member( "when", elem.when ); jsout.member( "key", elem.key ); if( elem.revert.is_uniform() ) { jsout.member( "revert", elem.revert.get_ter( point_sm_ms::zero ) ); } else { jsout.member( "revert" ); jsout.start_array(); for( int y = 0; y < SEEY; y++ ) { for( int x = 0; x < SEEX; x++ ) { jsout.start_object(); point_sm_ms pt( x, y ); jsout.member( "point", pt ); jsout.member( "furn", elem.revert.get_furn( pt ) ); jsout.member( "ter", elem.revert.get_ter( pt ) ); jsout.member( "trap", elem.revert.get_trap( pt ) ); jsout.member( "items", elem.revert.get_items( pt ) ); jsout.end_object(); } } jsout.end_array(); } jsout.end_object(); } jsout.end_array(); } void faction_manager::deserialize( const JsonValue &jv ) { if( jv.test_object() ) { // whoops - this recovers factions saved under the wrong format. JsonObject jo = jv; for( JsonMember jm : jo ) { faction add_fac; add_fac.id = faction_id( jm.name() ); jm.read( add_fac ); faction *old_fac = get( add_fac.id, false ); if( old_fac ) { *old_fac = add_fac; // force a revalidation of add_fac get( add_fac.id, false ); } else { factions[add_fac.id] = add_fac; } } } else if( jv.test_array() ) { // how it should have been serialized. JsonArray ja = jv; for( JsonValue jav : ja ) { faction add_fac; jav.read( add_fac ); faction *old_fac = get( add_fac.id, false ); if( old_fac ) { *old_fac = add_fac; // force a revalidation of add_fac get( add_fac.id, false ); } else { factions[add_fac.id] = add_fac; } } } } void creature_tracker::deserialize( const JsonArray &ja ) { monsters_list.clear(); monsters_by_location.clear(); for( JsonValue jv : ja ) { // TODO: would be nice if monster had a constructor using JsonIn or similar, so this could be one statement. shared_ptr_fast<monster> mptr = make_shared_fast<monster>(); jv.read( *mptr ); add( mptr ); } } void creature_tracker::serialize( JsonOut &jsout ) const { jsout.start_array(); for( const auto &monster_ptr : monsters_list ) { jsout.write( *monster_ptr ); } jsout.end_array(); } void overmapbuffer::serialize_overmap_global_state( JsonOut &json ) const { json.start_object(); json.member( "placed_unique_specials" ); json.write_as_array( placed_unique_specials ); json.member( "overmap_count", overmap_buffer.overmap_count ); json.member( "unique_special_count", unique_special_count ); json.end_object(); } void overmapbuffer::deserialize_overmap_global_state( const JsonObject &json ) { placed_unique_specials.clear(); JsonArray ja = json.get_array( "placed_unique_specials" ); for( const JsonValue &special : ja ) { placed_unique_specials.emplace( special.get_string() ); } unique_special_count.clear(); json.read( "unique_special_count", unique_special_count ); json.read( "overmap_count", overmap_count ); } void overmapbuffer::deserialize_placed_unique_specials( const JsonValue &jsin ) { placed_unique_specials.clear(); JsonArray ja = jsin.get_array(); for( const JsonValue &special : ja ) { placed_unique_specials.emplace( special.get_string() ); } } void npc::import_and_clean( const cata_path &path ) { std::ifstream fin( path.get_unrelative_path(), std::ios::binary ); size_t json_offset = chkversion( fin ); JsonValue jsin = json_loader::from_path_at_offset( path, json_offset ); import_and_clean( jsin.get_object() ); } void npc::import_and_clean( const JsonObject &data ) { deserialize( data ); npc defaults; // to avoid hardcoding defaults here // avoid duplicate id setID( g->assign_npc_id(), /* force */ true ); // timestamps are irrelevant if importing into a different world last_updated = defaults.last_updated; lifespan_end = defaults.lifespan_end; effects->clear(); consumption_history = defaults.consumption_history; last_sleep_check = defaults.last_sleep_check; queued_effect_on_conditions = defaults.queued_effect_on_conditions; // space coordinates are irrelevant if importing into a different world set_pos_abs_only( defaults.pos_abs() ); omt_path = defaults.omt_path; known_traps.clear(); camps = defaults.camps; last_player_seen_pos = defaults.last_player_seen_pos; guard_pos = defaults.guard_pos; pulp_location = defaults.pulp_location; chair_pos = defaults.chair_pos; wander_pos = defaults.wander_pos; goal = defaults.goal; assigned_camp = defaults.assigned_camp; job = defaults.job; // mission related mission = defaults.mission; previous_mission = defaults.previous_mission; reset_companion_mission(); companion_mission_role_id = defaults.companion_mission_role_id; companion_mission_points = defaults.companion_mission_points; companion_mission_time = defaults.companion_mission_time; companion_mission_time_ret = defaults.companion_mission_time_ret; companion_mission_inv.clear(); chatbin.missions.clear(); chatbin.missions_assigned.clear(); chatbin.mission_selected = nullptr; // activity related activity = defaults.activity; backlog = defaults.backlog; clear_destination(); stashed_outbounds_activity = defaults.stashed_outbounds_activity; stashed_outbounds_backlog = defaults.stashed_outbounds_backlog; activity_vehicle_part_index = defaults.activity_vehicle_part_index; current_activity_id = defaults.current_activity_id; // miscellaneous in_vehicle = defaults.in_vehicle; warning_record = defaults.warning_record; complaints = defaults.complaints; unique_id = defaults.unique_id; } void npc::export_to( const cata_path &path ) const { write_to_file( path, [&]( std::ostream & fout ) { fout << "# version " << savegame_version << std::endl; JsonOut jsout( fout ); serialize( jsout ); } ); }
0
0.918656
1
0.918656
game-dev
MEDIA
0.587034
game-dev
0.934994
1
0.934994
H-uru/Plasma
7,854
Sources/Plasma/PubUtilLib/plMessage/plLoadCloneMsg.cpp
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "plLoadCloneMsg.h" #include "HeadSpin.h" #include "hsResMgr.h" #include "hsStream.h" #include "pnNetCommon/plNetApp.h" // CTOR / default plLoadCloneMsg::plLoadCloneMsg() : fValidMsg(), fOriginatingPlayerID(), fTriggerMsg() { SetBCastFlag(plMessage::kNetPropagate); }; // CTOR uoidToClone, requestorKey, userData, isLoading // this form is for creating new clones plLoadCloneMsg::plLoadCloneMsg(const plUoid &uoidToClone, plKey requestorKey, uint32_t userData) : fRequestorKey(std::move(requestorKey)), fUserData(userData), fValidMsg(), fTriggerMsg(), fIsLoading(true) // this constructor form is only used for loading { SetBCastFlag(plMessage::kNetPropagate); hsKeyedObject * koRequestor = fRequestorKey->ObjectIsLoaded(); if(koRequestor) { plNetClientApp *app = plNetClientApp::GetInstance(); plKey originalKey = hsgResMgr::ResMgr()->FindKey(uoidToClone); if(originalKey) { // all is well. finish it off. fCloneKey = hsgResMgr::ResMgr()->CloneKey(originalKey); fOriginatingPlayerID = app->GetPlayerID(); fValidMsg = true; this->AddReceiver(plNetApp::GetInstance()->GetKey()); } else { char buffer[128]; sprintf(buffer, "Can't find key named %s", uoidToClone.GetObjectName().c_str()); hsAssert(0, buffer); } } else { hsStatusMessage("Clone requestor is not loaded."); } } // CTOR existing, requestor, userData, isLoading // this form is for unloading or other operations on existing clones plLoadCloneMsg::plLoadCloneMsg(plKey existing, plKey requestor, uint32_t userData, bool isLoading) : fCloneKey(std::move(existing)), fRequestorKey(std::move(requestor)), fUserData(userData), fValidMsg(true), fTriggerMsg(), fIsLoading(isLoading) { if (plNetApp::GetInstance()) { SetBCastFlag(plMessage::kNetPropagate); AddReceiver(plNetApp::GetInstance()->GetKey()); } if (plNetClientApp::GetInstance()) fOriginatingPlayerID = plNetClientApp::GetInstance()->GetPlayerID(); hsAssert(fRequestorKey->ObjectIsLoaded(), "Clone (unloading) requestor is not loaded."); } plLoadCloneMsg::~plLoadCloneMsg() { hsRefCnt_SafeUnRef(fTriggerMsg); } // READ void plLoadCloneMsg::Read(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgRead(stream, mgr); fCloneKey = mgr->ReadKey(stream); fRequestorKey = mgr->ReadKey(stream); fOriginatingPlayerID = stream->ReadLE32(); fUserData = stream->ReadLE32(); fValidMsg = stream->ReadBool(); fIsLoading = stream->ReadBool(); fTriggerMsg = plMessage::ConvertNoRef(mgr->ReadCreatable(stream)); } // WRITE void plLoadCloneMsg::Write(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgWrite(stream,mgr); mgr->WriteKey(stream, fCloneKey); mgr->WriteKey(stream, fRequestorKey); stream->WriteLE32(fOriginatingPlayerID); stream->WriteLE32(fUserData); stream->WriteBool(fValidMsg); stream->WriteBool(fIsLoading); mgr->WriteCreatable(stream, fTriggerMsg); } enum LoadCloneMsgFlags { kLoadCloneMsgCloneKey, kLoadCloneMsgRequestorKey, kLoadCloneMsgOrigPlayerID, kLoadCloneMsgUserData, kLoadCloneMsgValidMsg, kLoadCloneMsgIsLoading, kLoadCloneMsgTriggerMsg, }; void plLoadCloneMsg::ReadVersion(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgReadVersion(stream, mgr); hsBitVector contentFlags; contentFlags.Read(stream); if (contentFlags.IsBitSet(kLoadCloneMsgCloneKey)) fCloneKey = mgr->ReadKey(stream); if (contentFlags.IsBitSet(kLoadCloneMsgRequestorKey)) fRequestorKey = mgr->ReadKey(stream); if (contentFlags.IsBitSet(kLoadCloneMsgOrigPlayerID)) fOriginatingPlayerID = stream->ReadLE32(); if (contentFlags.IsBitSet(kLoadCloneMsgUserData)) fUserData = stream->ReadLE32(); if (contentFlags.IsBitSet(kLoadCloneMsgValidMsg)) fValidMsg = stream->ReadBool(); if (contentFlags.IsBitSet(kLoadCloneMsgIsLoading)) fIsLoading = stream->ReadBool(); if (contentFlags.IsBitSet(kLoadCloneMsgTriggerMsg)) fTriggerMsg = plMessage::ConvertNoRef(mgr->ReadCreatable(stream)); } void plLoadCloneMsg::WriteVersion(hsStream* stream, hsResMgr* mgr) { plMessage::IMsgWriteVersion(stream,mgr); hsBitVector contentFlags; contentFlags.SetBit(kLoadCloneMsgCloneKey); contentFlags.SetBit(kLoadCloneMsgRequestorKey); contentFlags.SetBit(kLoadCloneMsgOrigPlayerID); contentFlags.SetBit(kLoadCloneMsgUserData); contentFlags.SetBit(kLoadCloneMsgValidMsg); contentFlags.SetBit(kLoadCloneMsgIsLoading); contentFlags.SetBit(kLoadCloneMsgTriggerMsg); contentFlags.Write(stream); // kLoadCloneMsgCloneKey mgr->WriteKey(stream, fCloneKey); // kLoadCloneMsgRequestorKey mgr->WriteKey(stream, fRequestorKey); // kLoadCloneMsgOrigPlayerID stream->WriteLE32(fOriginatingPlayerID); // kLoadCloneMsgUserData stream->WriteLE32(fUserData); // kLoadCloneMsgValidMsg stream->WriteBool(fValidMsg); // kLoadCloneMsgIsLoading stream->WriteBool(fIsLoading); // kLoadCloneMsgTriggerMSg mgr->WriteCreatable(stream, fTriggerMsg); } plKey plLoadCloneMsg::GetCloneKey() const { return fCloneKey; } plKey plLoadCloneMsg::GetRequestorKey() const { return fRequestorKey; } bool plLoadCloneMsg::IsValidMessage() const { return fValidMsg; } uint32_t plLoadCloneMsg::GetUserData() const { return fUserData; } uint32_t plLoadCloneMsg::GetOriginatingPlayerID() const { return fOriginatingPlayerID; } void plLoadCloneMsg::SetOriginatingPlayerID(uint32_t playerId) { fOriginatingPlayerID = playerId; } bool plLoadCloneMsg::GetIsLoading() const { return fIsLoading; } void plLoadCloneMsg::SetTriggerMsg(plMessage *msg) { if (fTriggerMsg != nullptr) hsRefCnt_SafeUnRef(fTriggerMsg); hsRefCnt_SafeRef(msg); fTriggerMsg = msg; } plMessage *plLoadCloneMsg::GetTriggerMsg() const { return fTriggerMsg; }
0
0.902987
1
0.902987
game-dev
MEDIA
0.759825
game-dev
0.789482
1
0.789482
latte-soft/datamodelpatch
3,618
src/PatchRoot/DataModelInstances/CoreGui/RobloxGui/Modules/Server/ServerChat/DefaultChatModules/ChatMessageValidator.luau
local l_Chat_0 = game:GetService("Chat"); local l_RunService_0 = game:GetService("RunService"); local l_ClientChatModules_0 = l_Chat_0:WaitForChild("ClientChatModules"); local l_ChatSettings_0 = require(l_ClientChatModules_0:WaitForChild("ChatSettings")); local l_ChatConstants_0 = require(l_ClientChatModules_0:WaitForChild("ChatConstants")); local v5 = nil; pcall(function() v5 = require(game:GetService("Chat").ClientChatModules.ChatLocalization); end); if v5 == nil then v5 = {}; end; if not (v5.FormatMessageToSend and v5.LocalizeFormattedMessage) then v5.FormatMessageToSend = function(_, _, v8) return v8; end; end; local v9 = { "\n", "\r", "\t", "\v", "\f" }; if l_ChatSettings_0.DisallowedWhiteSpace then v9 = l_ChatSettings_0.DisallowedWhiteSpace; end; local function v11(v10) if l_ChatSettings_0.MaximumMessageLength * 6 < v10:len() then return false; elseif utf8.len(v10) == nil then return false; elseif l_ChatSettings_0.MaximumMessageLength < utf8.len(utf8.nfcnormalize(v10)) then return false; else return true; end; end; local function _(v12) if not l_RunService_0:IsStudio() then local l_status_0, l_result_0 = pcall(function() return l_Chat_0:CanUserChatAsync(v12.UserId); end); return l_status_0 and l_result_0; else return true; end; end; return function(v16) v16:RegisterProcessCommandsFunction("message_validation", function(v17, v18, v19) local l_v16_Speaker_0 = v16:GetSpeaker(v17); local l_l_v16_Speaker_0_Player_0 = l_v16_Speaker_0:GetPlayer(); if l_v16_Speaker_0 then if l_l_v16_Speaker_0_Player_0 then if not l_RunService_0:IsStudio() and l_l_v16_Speaker_0_Player_0.UserId < 1 then return true; else local v22; if not l_RunService_0:IsStudio() then local l_status_1, l_result_1 = pcall(function() return l_Chat_0:CanUserChatAsync(l_l_v16_Speaker_0_Player_0.UserId); end); v22 = l_status_1 and l_result_1; else v22 = true; end; if v22 then if v11(v18) then for _, v26 in pairs(v9) do if v18:find(v26) then l_v16_Speaker_0:SendSystemMessage(v5:FormatMessageToSend("GameChat_ChatMessageValidator_WhitespaceError", "Your message contains whitespace that is not allowed."), v19); return true; end; end; return false; else l_v16_Speaker_0:SendSystemMessage(v5:FormatMessageToSend("GameChat_ChatMessageValidator_MaxLengthError", "Your message exceeds the maximum message length."), v19); return true; end; else l_v16_Speaker_0:SendSystemMessage(v5:FormatMessageToSend("GameChat_ChatMessageValidator_SettingsError", "Your chat settings prevent you from sending messages."), v19); return true; end; end; else return false; end; else return false; end; end, l_ChatConstants_0.VeryHighPriority); end;
0
0.907018
1
0.907018
game-dev
MEDIA
0.539431
game-dev
0.827042
1
0.827042
Revolutionary-Games/Thrive
1,520
src/stage_starters/AscensionStageStarter.cs
using System; using Godot; /// <summary> /// Started for ascension stage (basically starts <see cref="MainGameState.SpaceStage"/> with ascended mode enabled) /// </summary> public partial class AscensionStageStarter : ComplexStageStarterBase { protected override MainGameState SimplyLoadableGameState => throw new InvalidOperationException("Should be unused"); public static SpaceStage SetupNewAscendedSpaceStage(GameProperties? currentGame) { currentGame ??= GameProperties.StartAscensionStageGame(new WorldGenerationSettings()); var spaceStage = SceneManager.Instance.LoadScene(MainGameState.SpaceStage).Instantiate<SpaceStage>(); spaceStage.CurrentGame = currentGame; return spaceStage; } public static void PrepareSpaceStageForFreshAscension(SpaceStage createdScene) { // We need to setup things here like done when coming from the industrial stage createdScene.SetupForExistingGameFromAnotherStage(true, SimulationParameters.Instance.GetUnitType("advancedSpaceship"), null); createdScene.OnBecomeAscended(); } protected override Node LoadScene() { return SetupNewAscendedSpaceStage(null); } protected override void CustomizeLoadedScene(Node scene) { } protected override void CustomizeAttachedScene(Node scene) { base.CustomizeAttachedScene(scene); var spaceStage = (SpaceStage)scene; PrepareSpaceStageForFreshAscension(spaceStage); } }
0
0.550263
1
0.550263
game-dev
MEDIA
0.926748
game-dev
0.685693
1
0.685693
DignitySAMP/SP-RP
7,545
gamemodes/lowrider/game.pwn
// This command details the entirety of the lowrider challenge system. It's where the magic happens: CMD:lowrider(playerid, params[]) { new option[16], targetid = INVALID_PLAYER_ID; if(sscanf(params, "s[64]k<player>", option, targetid)){ return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "/lowrider [challenge, accept, cancel]"); } if(!IsPlayerConnected(targetid)) { return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "The player you challenged is not connected."); } new string[128]; if(!strcmp(option, "challenge", true)) { #warning Make this autoexpire after x minutes // Are both players available and proper to do the challenge? if(IsChallengeValid(playerid, targetid)) { Lowrider[playerid][E_LOWRIDER_OFFER] = true; Lowrider[playerid][E_LOWRIDER_RIVAL] = targetid; Lowrider[targetid][E_LOWRIDER_OFFER] = true; Lowrider[targetid][E_LOWRIDER_RIVAL] = playerid; format(string, sizeof(string), "%s{DEDEDE} has challenged you to lowrider duel. To decide type {A3A3A3}/lowrider accept{DEDEDE} or {A3A3A3}/lowrider cancel", ReturnSettingsName(playerid, targetid, true, true)); SendServerMessage(targetid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", string); format(string, sizeof(string), "Waiting for response from %s{DEDEDE}. To cancel type {A3A3A3}/lowrider cancel", ReturnSettingsName(targetid, playerid, true, true)); SendServerMessage(targetid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", string); } // No need for an error message here - errors are handled by IsChallengeValid. } else if(!strcmp(option, "accept", true)) { new challenger = Lowrider[playerid][E_LOWRIDER_RIVAL]; if(IsPlayerConnected(challenger)) { if(Lowrider[challenger][E_LOWRIDER_OFFER] && Lowrider[playerid][E_LOWRIDER_OFFER]) { Lowrider[challenger][E_LOWRIDER_OFFER] = false; Lowrider[playerid][E_LOWRIDER_OFFER] = false; SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You have accepted the lowrider duel challenge."); SendServerMessage(challenger, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "They have accepted the lowrider duel challenge."); // Active is set to true in the following function, after tds etc are made. StartLowriderChallenge(playerid, challenger); } else return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Both you and your rival must have an open offer pending."); } else return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Your rival has either cancelled the offer or has disconnected."); } else if(!strcmp(option, "cancel", true)) { new challenger = Lowrider[playerid][E_LOWRIDER_RIVAL]; if(!IsPlayerConnected(challenger)) { Lowrider[playerid][E_LOWRIDER_OFFER] = false; Lowrider[playerid][E_LOWRIDER_ACTIVE] = false; Lowrider[playerid][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; StopLowriderChallenge(playerid, INVALID_PLAYER_ID); SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Your rival has disconnected. You have been removed from the challenge."); return 1; } if(Lowrider[playerid][E_LOWRIDER_ACTIVE]) { // Resetting player variables Lowrider[playerid][E_LOWRIDER_OFFER] = false; Lowrider[playerid][E_LOWRIDER_ACTIVE] = false; Lowrider[playerid][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You have forfeited the lowrider challenge. You lose!"); // Resetting challenger variables Lowrider[challenger][E_LOWRIDER_OFFER] = false; Lowrider[challenger][E_LOWRIDER_ACTIVE] = false; Lowrider[challenger][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; SendServerMessage(challenger, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Your rival has forfeited the lowrider challenge. You win!"); StopLowriderChallenge(playerid, challenger); return 1; } else { // Cancel outstanding offer. if(Lowrider[playerid][E_LOWRIDER_OFFER] && Lowrider[playerid][E_LOWRIDER_RIVAL] == challenger) { if(Lowrider[challenger][E_LOWRIDER_OFFER] && Lowrider[challenger][E_LOWRIDER_RIVAL] == playerid) { // Resetting challenger variables Lowrider[challenger][E_LOWRIDER_OFFER] = false; Lowrider[challenger][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; SendServerMessage(challenger, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Your lowrider challenge offer has been refused."); // Resetting player variables Lowrider[playerid][E_LOWRIDER_OFFER] = false; Lowrider[playerid][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You have refused the lowrider challenge offer."); return true; } else { // Challenger doesn't have a valid outstanding offer, just reset the player and inform them. Lowrider[playerid][E_LOWRIDER_OFFER] = false; Lowrider[playerid][E_LOWRIDER_RIVAL] = INVALID_PLAYER_ID; return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Your rival has either cancelled the offer or has disconnected."); } } else return SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You do not have an active offer to cancel."); } } return 1; } IsChallengeValid(playerid, rival) { // TODO: Check if player and rival are both in a lowrider compatible vehicle (IsLowriderVehicle) // Player checks if(Lowrider[playerid][E_LOWRIDER_ACTIVE]) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You're already in an active game. Use {A3A3A3}/lowrider cancel{DEDEDE}."); return false; } if(Lowrider[playerid][E_LOWRIDER_RIVAL] != INVALID_PLAYER_ID) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You already have a rival! Use {A3A3A3}/lowrider cancel{DEDEDE}."); return false; } if(Lowrider[playerid][E_LOWRIDER_OFFER]) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "You already have an offer! Use {A3A3A3}/lowrider accept{DEDEDE} or {A3A3A3}/lowrider cancel{DEDEDE}."); return false; } // Rival checks if(Lowrider[rival][E_LOWRIDER_ACTIVE]) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Player is already in an active game."); return false; } if(Lowrider[rival][E_LOWRIDER_RIVAL] != INVALID_PLAYER_ID) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Player already has a rival!"); return false; } if(Lowrider[rival][E_LOWRIDER_OFFER]) { SendServerMessage(playerid, COLOR_LOWRIDER, "Lowrider", "DEDEDE", "Player already has an offer!"); return false; } return true; }
0
0.637289
1
0.637289
game-dev
MEDIA
0.947593
game-dev
0.792262
1
0.792262
DaFuqs/Spectrum
2,131
src/main/java/de/dafuqs/spectrum/api/item/GravitableItem.java
package de.dafuqs.spectrum.api.item; import de.dafuqs.spectrum.progression.*; import net.minecraft.server.level.*; import net.minecraft.world.entity.*; import net.minecraft.world.entity.item.*; import net.minecraft.world.entity.player.*; import net.minecraft.world.item.*; import net.minecraft.world.level.*; public interface GravitableItem { float getGravityMod(ItemStack stack); /** * This one is for LivingEntities, like players * Makes entities lighter / heavier, depending on the gravity effect of the item stack * * @return The additional Y Velocity that was applied */ default double applyGravity(ItemStack stack, Level world, Entity entity) { if (world != null && entity != null) { // don't affect creative/spectators/... players or immune boss mobs if (entity.isPushable() && !entity.isNoGravity() && !entity.isSpectator()) { if (entity instanceof Player player && player.getAbilities().flying) { return 0; } double additionalYVelocity = getGravityMod(stack) * stack.getCount(); entity.push(0, additionalYVelocity, 0); // if falling very slowly => reset fall distance / damage if (additionalYVelocity > 0 && entity.getDeltaMovement().y > -0.4) { entity.fallDistance = 0; } if (world.getGameTime() % 20 == 0 && entity instanceof ServerPlayer serverPlayerEntity) { GravityAdvancementsManager.processAppliedGravityForAdvancements(serverPlayerEntity, additionalYVelocity); } return additionalYVelocity; } } return 0; } /** * This one is for ItemEntities * Since an ItemEntity is much lighter than a player, we can x10 the gravity effect */ default void applyGravity(ItemStack stack, Level world, ItemEntity itemEntity) { if (itemEntity.isNoGravity()) { return; } if (itemEntity.position().y() > world.getMaxBuildHeight() + 200) { itemEntity.discard(); } else { // since an ItemEntity is much lighter than a player, we can x10 the gravity effect // this is not affected by item entity stack count to make it more predictable itemEntity.push(0, getGravityMod(stack) * 10, 0); } } }
0
0.761985
1
0.761985
game-dev
MEDIA
0.983447
game-dev
0.739903
1
0.739903
blendogames/quadrilateralcowboy
124,855
d3xp/anim/Anim_Blend.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" static const char *channelNames[ ANIM_NumAnimChannels ] = { "all", "torso", "legs", "head", "eyelids" }; /*********************************************************************** idAnim ***********************************************************************/ /* ===================== idAnim::idAnim ===================== */ idAnim::idAnim() { modelDef = NULL; numAnims = 0; memset( anims, 0, sizeof( anims ) ); memset( &flags, 0, sizeof( flags ) ); } /* ===================== idAnim::idAnim ===================== */ idAnim::idAnim( const idDeclModelDef *modelDef, const idAnim *anim ) { int i; this->modelDef = modelDef; numAnims = anim->numAnims; name = anim->name; realname = anim->realname; flags = anim->flags; memset( anims, 0, sizeof( anims ) ); for( i = 0; i < numAnims; i++ ) { anims[ i ] = anim->anims[ i ]; anims[ i ]->IncreaseRefs(); } frameLookup.SetNum( anim->frameLookup.Num() ); memcpy( frameLookup.Ptr(), anim->frameLookup.Ptr(), frameLookup.MemoryUsed() ); frameCommands.SetNum( anim->frameCommands.Num() ); for( i = 0; i < frameCommands.Num(); i++ ) { frameCommands[ i ] = anim->frameCommands[ i ]; if ( anim->frameCommands[ i ].string ) { frameCommands[ i ].string = new idStr( *anim->frameCommands[ i ].string ); } } } /* ===================== idAnim::~idAnim ===================== */ idAnim::~idAnim() { int i; for( i = 0; i < numAnims; i++ ) { anims[ i ]->DecreaseRefs(); } for( i = 0; i < frameCommands.Num(); i++ ) { delete frameCommands[ i ].string; } } /* ===================== idAnim::SetAnim ===================== */ void idAnim::SetAnim( const idDeclModelDef *modelDef, const char *sourcename, const char *animname, int num, const idMD5Anim *md5anims[ ANIM_MaxSyncedAnims ] ) { int i; this->modelDef = modelDef; for( i = 0; i < numAnims; i++ ) { anims[ i ]->DecreaseRefs(); anims[ i ] = NULL; } assert( ( num > 0 ) && ( num <= ANIM_MaxSyncedAnims ) ); numAnims = num; realname = sourcename; name = animname; for( i = 0; i < num; i++ ) { anims[ i ] = md5anims[ i ]; anims[ i ]->IncreaseRefs(); } memset( &flags, 0, sizeof( flags ) ); for( i = 0; i < frameCommands.Num(); i++ ) { delete frameCommands[ i ].string; } frameLookup.Clear(); frameCommands.Clear(); } /* ===================== idAnim::Name ===================== */ const char *idAnim::Name( void ) const { return name; } /* ===================== idAnim::FullName ===================== */ const char *idAnim::FullName( void ) const { return realname; } /* ===================== idAnim::MD5Anim index 0 will never be NULL. Any anim >= NumAnims will return NULL. ===================== */ const idMD5Anim *idAnim::MD5Anim( int num ) const { if ( anims == NULL || anims[0] == NULL ) { return NULL; } return anims[ num ]; } /* ===================== idAnim::ModelDef ===================== */ const idDeclModelDef *idAnim::ModelDef( void ) const { return modelDef; } /* ===================== idAnim::Length ===================== */ int idAnim::Length( void ) const { if ( !anims[ 0 ] ) { return 0; } return anims[ 0 ]->Length(); } /* ===================== idAnim::NumFrames ===================== */ int idAnim::NumFrames( void ) const { if ( !anims[ 0 ] ) { return 0; } return anims[ 0 ]->NumFrames(); } /* ===================== idAnim::NumAnims ===================== */ int idAnim::NumAnims( void ) const { return numAnims; } /* ===================== idAnim::TotalMovementDelta ===================== */ const idVec3 &idAnim::TotalMovementDelta( void ) const { if ( !anims[ 0 ] ) { return vec3_zero; } return anims[ 0 ]->TotalMovementDelta(); } /* ===================== idAnim::GetOrigin ===================== */ bool idAnim::GetOrigin( idVec3 &offset, int animNum, int currentTime, int cyclecount ) const { if ( !anims[ animNum ] ) { offset.Zero(); return false; } anims[ animNum ]->GetOrigin( offset, currentTime, cyclecount ); return true; } /* ===================== idAnim::GetOriginRotation ===================== */ bool idAnim::GetOriginRotation( idQuat &rotation, int animNum, int currentTime, int cyclecount ) const { if ( !anims[ animNum ] ) { rotation.Set( 0.0f, 0.0f, 0.0f, 1.0f ); return false; } anims[ animNum ]->GetOriginRotation( rotation, currentTime, cyclecount ); return true; } /* ===================== idAnim::GetBounds ===================== */ ID_INLINE bool idAnim::GetBounds( idBounds &bounds, int animNum, int currentTime, int cyclecount ) const { if ( !anims[ animNum ] ) { return false; } anims[ animNum ]->GetBounds( bounds, currentTime, cyclecount ); return true; } /* ===================== idAnim::AddFrameCommand Returns NULL if no error. ===================== */ const char *idAnim::AddFrameCommand( const idDeclModelDef *modelDef, int framenum, idLexer &src, const idDict *def ) { int i; int index; idStr text; idStr funcname; frameCommand_t fc; idToken token; const jointInfo_t *jointInfo; // make sure we're within bounds if ( ( framenum < 1 ) || ( framenum > anims[ 0 ]->NumFrames() ) ) { return va( "Frame %d out of range", framenum ); } // frame numbers are 1 based in .def files, but 0 based internally framenum--; memset( &fc, 0, sizeof( fc ) ); if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( token == "call" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SCRIPTFUNCTION; fc.function = gameLocal.program.FindFunction( token ); if ( !fc.function ) { return va( "Function '%s' not found", token.c_str() ); } } else if ( token == "object_call" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SCRIPTFUNCTIONOBJECT; fc.string = new idStr( token ); } else if ( token == "event" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_EVENTFUNCTION; const idEventDef *ev = idEventDef::FindEvent( token ); if ( !ev ) { return va( "Event '%s' not found", token.c_str() ); } if ( ev->GetNumArgs() != 0 ) { return va( "Event '%s' has arguments", token.c_str() ); } fc.string = new idStr( token ); } else if ( token == "sound" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_voice" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_VOICE; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_voice2" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_VOICE2; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_body" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_BODY; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_body2" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_BODY2; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_body3" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_BODY3; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_weapon" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_WEAPON; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_global" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_GLOBAL; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_item" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_ITEM; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "sound_chatter" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SOUND_CHATTER; if ( !token.Cmpn( "snd_", 4 ) ) { fc.string = new idStr( token ); } else { fc.soundShader = declManager->FindSound( token ); if ( fc.soundShader->GetState() == DS_DEFAULTED ) { gameLocal.Warning( "Sound '%s' not found", token.c_str() ); } } } else if ( token == "skin" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_SKIN; if ( token == "none" ) { fc.skin = NULL; } else { fc.skin = declManager->FindSkin( token ); if ( !fc.skin ) { return va( "Skin '%s' not found", token.c_str() ); } } } else if ( token == "fx" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_FX; if ( !declManager->FindType( DECL_FX, token.c_str() ) ) { return va( "fx '%s' not found", token.c_str() ); } fc.string = new idStr( token ); } else if ( token == "trigger" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_TRIGGER; fc.string = new idStr( token ); } else if ( token == "triggerSmokeParticle" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_TRIGGER_SMOKE_PARTICLE; fc.string = new idStr( token ); } else if ( token == "particle" ) { idStr str; if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } jointInfo = modelDef->FindJoint( token ); if ( !jointInfo ) { return va( "Joint '%s' not found", token.c_str() ); } if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } str += token; fc.type = FC_PARTICLE; fc.string = new idStr( str ); //particle name. fc.index = jointInfo->num; //joint to fire the effect. } else if ( token == "melee" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_MELEE; if ( !gameLocal.FindEntityDef( token.c_str(), false ) ) { return va( "Unknown entityDef '%s'", token.c_str() ); } fc.string = new idStr( token ); } else if ( token == "direct_damage" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_DIRECTDAMAGE; if ( !gameLocal.FindEntityDef( token.c_str(), false ) ) { return va( "Unknown entityDef '%s'", token.c_str() ); } fc.string = new idStr( token ); } else if ( token == "attack_begin" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_BEGINATTACK; if ( !gameLocal.FindEntityDef( token.c_str(), false ) ) { return va( "Unknown entityDef '%s'", token.c_str() ); } fc.string = new idStr( token ); } else if ( token == "attack_end" ) { fc.type = FC_ENDATTACK; } else if ( token == "muzzle_flash" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( ( token != "" ) && !modelDef->FindJoint( token ) ) { return va( "Joint '%s' not found", token.c_str() ); } fc.type = FC_MUZZLEFLASH; fc.string = new idStr( token ); } else if ( token == "muzzle_flash" ) { fc.type = FC_MUZZLEFLASH; fc.string = new idStr( "" ); } else if ( token == "create_missile" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( !modelDef->FindJoint( token ) ) { return va( "Joint '%s' not found", token.c_str() ); } fc.type = FC_CREATEMISSILE; fc.string = new idStr( token ); } else if ( token == "launch_missile" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( !modelDef->FindJoint( token ) ) { return va( "Joint '%s' not found", token.c_str() ); } fc.type = FC_LAUNCHMISSILE; fc.string = new idStr( token ); } else if ( token == "fire_missile_at_target" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } jointInfo = modelDef->FindJoint( token ); if ( !jointInfo ) { return va( "Joint '%s' not found", token.c_str() ); } if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_FIREMISSILEATTARGET; fc.string = new idStr( token ); fc.index = jointInfo->num; #ifdef _D3XP } else if ( token == "launch_projectile" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( !declManager->FindDeclWithoutParsing( DECL_ENTITYDEF, token, false ) ) { return "Unknown projectile def"; } fc.type = FC_LAUNCH_PROJECTILE; fc.string = new idStr( token ); } else if ( token == "trigger_fx" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } jointInfo = modelDef->FindJoint( token ); if ( !jointInfo ) { return va( "Joint '%s' not found", token.c_str() ); } if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } if ( !declManager->FindType( DECL_FX, token, false ) ) { return "Unknown FX def"; } fc.type = FC_TRIGGER_FX; fc.string = new idStr( token ); fc.index = jointInfo->num; } else if ( token == "start_emitter" ) { idStr str; if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } str = token + " "; if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } jointInfo = modelDef->FindJoint( token ); if ( !jointInfo ) { return va( "Joint '%s' not found", token.c_str() ); } if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } str += token; fc.type = FC_START_EMITTER; fc.string = new idStr( str ); fc.index = jointInfo->num; } else if ( token == "stop_emitter" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_STOP_EMITTER; fc.string = new idStr( token ); #endif } else if ( token == "footstep" ) { fc.type = FC_FOOTSTEP; } else if ( token == "leftfoot" ) { fc.type = FC_LEFTFOOT; } else if ( token == "rightfoot" ) { fc.type = FC_RIGHTFOOT; } else if ( token == "enableEyeFocus" ) { fc.type = FC_ENABLE_EYE_FOCUS; } else if ( token == "disableEyeFocus" ) { fc.type = FC_DISABLE_EYE_FOCUS; } else if ( token == "disableGravity" ) { fc.type = FC_DISABLE_GRAVITY; } else if ( token == "enableGravity" ) { fc.type = FC_ENABLE_GRAVITY; } else if ( token == "jump" ) { fc.type = FC_JUMP; } else if ( token == "enableClip" ) { fc.type = FC_ENABLE_CLIP; } else if ( token == "disableClip" ) { fc.type = FC_DISABLE_CLIP; } else if ( token == "enableWalkIK" ) { fc.type = FC_ENABLE_WALK_IK; } else if ( token == "disableWalkIK" ) { fc.type = FC_DISABLE_WALK_IK; } else if ( token == "enableLegIK" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_ENABLE_LEG_IK; fc.index = atoi( token ); } else if ( token == "disableLegIK" ) { if( !src.ReadTokenOnLine( &token ) ) { return "Unexpected end of line"; } fc.type = FC_DISABLE_LEG_IK; fc.index = atoi( token ); } else if ( token == "recordDemo" ) { fc.type = FC_RECORDDEMO; if( src.ReadTokenOnLine( &token ) ) { fc.string = new idStr( token ); } } else if ( token == "aviGame" ) { fc.type = FC_AVIGAME; if( src.ReadTokenOnLine( &token ) ) { fc.string = new idStr( token ); } } else { return va( "Unknown command '%s'", token.c_str() ); } // check if we've initialized the frame loopup table if ( !frameLookup.Num() ) { // we haven't, so allocate the table and initialize it frameLookup.SetGranularity( 1 ); frameLookup.SetNum( anims[ 0 ]->NumFrames() ); for( i = 0; i < frameLookup.Num(); i++ ) { frameLookup[ i ].num = 0; frameLookup[ i ].firstCommand = 0; } } // allocate space for a new command frameCommands.Alloc(); // calculate the index of the new command index = frameLookup[ framenum ].firstCommand + frameLookup[ framenum ].num; // move all commands from our index onward up one to give us space for our new command for( i = frameCommands.Num() - 1; i > index; i-- ) { frameCommands[ i ] = frameCommands[ i - 1 ]; } // fix the indices of any later frames to account for the inserted command for( i = framenum + 1; i < frameLookup.Num(); i++ ) { frameLookup[ i ].firstCommand++; } // store the new command frameCommands[ index ] = fc; // increase the number of commands on this frame frameLookup[ framenum ].num++; // return with no error return NULL; } /* ===================== idAnim::CallFrameCommands ===================== */ void idAnim::CallFrameCommands( idEntity *ent, int from, int to ) const { int index; int end; int frame; int numframes; numframes = anims[ 0 ]->NumFrames(); frame = from; while( frame != to ) { frame++; if ( frame >= numframes ) { frame = 0; } index = frameLookup[ frame ].firstCommand; end = index + frameLookup[ frame ].num; while( index < end ) { const frameCommand_t &command = frameCommands[ index++ ]; switch( command.type ) { case FC_SCRIPTFUNCTION: { gameLocal.CallFrameCommand( ent, command.function ); break; } case FC_SCRIPTFUNCTIONOBJECT: { gameLocal.CallObjectFrameCommand( ent, command.string->c_str() ); break; } case FC_EVENTFUNCTION: { const idEventDef *ev = idEventDef::FindEvent( command.string->c_str() ); ent->ProcessEvent( ev ); break; } case FC_SOUND: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_ANY, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_ANY, 0, false, NULL ); } break; } case FC_SOUND_VOICE: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_VOICE, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_voice' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_VOICE, 0, false, NULL ); } break; } case FC_SOUND_VOICE2: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_VOICE2, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_voice2' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_VOICE2, 0, false, NULL ); } break; } case FC_SOUND_BODY: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_BODY, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_body' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_BODY, 0, false, NULL ); } break; } case FC_SOUND_BODY2: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_BODY2, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_body2' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_BODY2, 0, false, NULL ); } break; } case FC_SOUND_BODY3: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_BODY3, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_body3' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_BODY3, 0, false, NULL ); } break; } case FC_SOUND_WEAPON: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_WEAPON, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_weapon' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_WEAPON, 0, false, NULL ); } break; } case FC_SOUND_GLOBAL: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_global' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ); } break; } case FC_SOUND_ITEM: { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_ITEM, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_item' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_ITEM, 0, false, NULL ); } break; } case FC_SOUND_CHATTER: { if ( ent->CanPlayChatterSounds() ) { if ( !command.soundShader ) { if ( !ent->StartSound( command.string->c_str(), SND_CHANNEL_VOICE, 0, false, NULL ) ) { gameLocal.Warning( "Framecommand 'sound_chatter' on entity '%s', anim '%s', frame %d: Could not find sound '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } } else { ent->StartSoundShader( command.soundShader, SND_CHANNEL_VOICE, 0, false, NULL ); } } break; } case FC_FX: { idEntityFx::StartFx( command.string->c_str(), NULL, NULL, ent, true ); break; } case FC_SKIN: { ent->SetSkin( command.skin ); break; } case FC_TRIGGER: { idEntity *target; target = gameLocal.FindEntity( command.string->c_str() ); if ( target ) { #ifdef _D3XP SetTimeState ts(target->timeGroup); #endif target->Signal( SIG_TRIGGER ); target->ProcessEvent( &EV_Activate, ent ); target->TriggerGuis(); } else { gameLocal.Warning( "Framecommand 'trigger' on entity '%s', anim '%s', frame %d: Could not find entity '%s'", ent->name.c_str(), FullName(), frame + 1, command.string->c_str() ); } break; } case FC_TRIGGER_SMOKE_PARTICLE: { ent->ProcessEvent( &AI_TriggerParticles, command.string->c_str() ); break; } case FC_MELEE: { ent->ProcessEvent( &AI_AttackMelee, command.string->c_str() ); break; } case FC_DIRECTDAMAGE: { ent->ProcessEvent( &AI_DirectDamage, command.string->c_str() ); break; } case FC_BEGINATTACK: { ent->ProcessEvent( &AI_BeginAttack, command.string->c_str() ); break; } case FC_ENDATTACK: { ent->ProcessEvent( &AI_EndAttack ); break; } case FC_MUZZLEFLASH: { ent->ProcessEvent( &AI_MuzzleFlash, command.string->c_str() ); break; } case FC_CREATEMISSILE: { ent->ProcessEvent( &AI_CreateMissile, command.string->c_str() ); break; } case FC_LAUNCHMISSILE: { ent->ProcessEvent( &AI_AttackMissile, command.string->c_str() ); break; } case FC_FIREMISSILEATTARGET: { ent->ProcessEvent( &AI_FireMissileAtTarget, modelDef->GetJointName( command.index ), command.string->c_str() ); break; } #ifdef _D3XP case FC_LAUNCH_PROJECTILE: { ent->ProcessEvent( &AI_LaunchProjectile, command.string->c_str() ); break; } case FC_TRIGGER_FX: { ent->ProcessEvent( &AI_TriggerFX, modelDef->GetJointName( command.index ), command.string->c_str() ); break; } case FC_PARTICLE: { //bc //ent->ProcessEvent( &AI_StartEmitter, modelDef->GetJointName( command.index ), command.string->c_str() ); const idDeclParticle *smokeFly = NULL; smokeFly = static_cast<const idDeclParticle *>( declManager->FindType( DECL_PARTICLE, command.string->c_str() ) ); if (smokeFly) { jointHandle_t jointNum; jointNum = ent->GetAnimator()->GetJointHandle( modelDef->GetJointName( command.index ) ); idVec3 offset; idMat3 axis; //ent->GetAnimator()->GetJointTransform( jointNum, gameLocal.time, offset, axis ); ent->GetAnimator()->GetJointTransform( jointNum, gameLocal.time, offset, axis ); offset = ent->GetPhysics()->GetOrigin() + offset * ent->GetPhysics()->GetAxis(); axis = axis * ent->GetPhysics()->GetAxis(); gameLocal.smokeParticles->EmitSmoke( smokeFly, gameLocal.time, 0, offset, axis, 0 ); } } case FC_START_EMITTER: { int index = command.string->Find(" "); if(index >= 0) { idStr name = command.string->Left(index); idStr particle = command.string->Right(command.string->Length() - index - 1); ent->ProcessEvent( &AI_StartEmitter, name.c_str(), modelDef->GetJointName( command.index ), particle.c_str() ); } } case FC_STOP_EMITTER: { ent->ProcessEvent( &AI_StopEmitter, command.string->c_str() ); } #endif case FC_FOOTSTEP : { ent->ProcessEvent( &EV_Footstep ); break; } case FC_LEFTFOOT: { ent->ProcessEvent( &EV_FootstepLeft ); break; } case FC_RIGHTFOOT: { ent->ProcessEvent( &EV_FootstepRight ); break; } case FC_ENABLE_EYE_FOCUS: { ent->ProcessEvent( &AI_EnableEyeFocus ); break; } case FC_DISABLE_EYE_FOCUS: { ent->ProcessEvent( &AI_DisableEyeFocus ); break; } case FC_DISABLE_GRAVITY: { ent->ProcessEvent( &AI_DisableGravity ); break; } case FC_ENABLE_GRAVITY: { ent->ProcessEvent( &AI_EnableGravity ); break; } case FC_JUMP: { ent->ProcessEvent( &AI_JumpFrame ); break; } case FC_ENABLE_CLIP: { ent->ProcessEvent( &AI_EnableClip ); break; } case FC_DISABLE_CLIP: { ent->ProcessEvent( &AI_DisableClip ); break; } case FC_ENABLE_WALK_IK: { ent->ProcessEvent( &EV_EnableWalkIK ); break; } case FC_DISABLE_WALK_IK: { ent->ProcessEvent( &EV_DisableWalkIK ); break; } case FC_ENABLE_LEG_IK: { ent->ProcessEvent( &EV_EnableLegIK, command.index ); break; } case FC_DISABLE_LEG_IK: { ent->ProcessEvent( &EV_DisableLegIK, command.index ); break; } case FC_RECORDDEMO: { if ( command.string ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "recordDemo %s", command.string->c_str() ) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "stoprecording" ); } break; } case FC_AVIGAME: { if ( command.string ) { cmdSystem->BufferCommandText( CMD_EXEC_NOW, va( "aviGame %s", command.string->c_str() ) ); } else { cmdSystem->BufferCommandText( CMD_EXEC_NOW, "aviGame" ); } break; } } } } } /* ===================== idAnim::FindFrameForFrameCommand ===================== */ int idAnim::FindFrameForFrameCommand( frameCommandType_t framecommand, const frameCommand_t **command ) const { int frame; int index; int numframes; int end; if ( !frameCommands.Num() ) { return -1; } numframes = anims[ 0 ]->NumFrames(); for( frame = 0; frame < numframes; frame++ ) { end = frameLookup[ frame ].firstCommand + frameLookup[ frame ].num; for( index = frameLookup[ frame ].firstCommand; index < end; index++ ) { if ( frameCommands[ index ].type == framecommand ) { if ( command ) { *command = &frameCommands[ index ]; } return frame; } } } if ( command ) { *command = NULL; } return -1; } /* ===================== idAnim::HasFrameCommands ===================== */ bool idAnim::HasFrameCommands( void ) const { if ( !frameCommands.Num() ) { return false; } return true; } /* ===================== idAnim::SetAnimFlags ===================== */ void idAnim::SetAnimFlags( const animFlags_t &animflags ) { flags = animflags; } /* ===================== idAnim::GetAnimFlags ===================== */ const animFlags_t &idAnim::GetAnimFlags( void ) const { return flags; } /*********************************************************************** idAnimBlend ***********************************************************************/ /* ===================== idAnimBlend::idAnimBlend ===================== */ idAnimBlend::idAnimBlend( void ) { Reset( NULL ); } /* ===================== idAnimBlend::Save archives object for save game file ===================== */ void idAnimBlend::Save( idSaveGame *savefile ) const { int i; savefile->WriteInt( starttime ); savefile->WriteInt( endtime ); savefile->WriteInt( timeOffset ); savefile->WriteFloat( rate ); savefile->WriteInt( blendStartTime ); savefile->WriteInt( blendDuration ); savefile->WriteFloat( blendStartValue ); savefile->WriteFloat( blendEndValue ); for( i = 0; i < ANIM_MaxSyncedAnims; i++ ) { savefile->WriteFloat( animWeights[ i ] ); } savefile->WriteShort( cycle ); savefile->WriteShort( frame ); savefile->WriteShort( animNum ); savefile->WriteBool( allowMove ); savefile->WriteBool( allowFrameCommands ); } /* ===================== idAnimBlend::Restore unarchives object from save game file ===================== */ void idAnimBlend::Restore( idRestoreGame *savefile, const idDeclModelDef *modelDef ) { int i; this->modelDef = modelDef; savefile->ReadInt( starttime ); savefile->ReadInt( endtime ); savefile->ReadInt( timeOffset ); savefile->ReadFloat( rate ); savefile->ReadInt( blendStartTime ); savefile->ReadInt( blendDuration ); savefile->ReadFloat( blendStartValue ); savefile->ReadFloat( blendEndValue ); for( i = 0; i < ANIM_MaxSyncedAnims; i++ ) { savefile->ReadFloat( animWeights[ i ] ); } savefile->ReadShort( cycle ); savefile->ReadShort( frame ); savefile->ReadShort( animNum ); if ( !modelDef ) { animNum = 0; } else if ( ( animNum < 0 ) || ( animNum > modelDef->NumAnims() ) ) { gameLocal.Warning( "Anim number %d out of range for model '%s' during save game", animNum, modelDef->GetModelName() ); animNum = 0; } savefile->ReadBool( allowMove ); savefile->ReadBool( allowFrameCommands ); } /* ===================== idAnimBlend::Reset ===================== */ void idAnimBlend::Reset( const idDeclModelDef *_modelDef ) { modelDef = _modelDef; cycle = 1; starttime = 0; endtime = 0; timeOffset = 0; rate = 1.0f; frame = 0; allowMove = true; allowFrameCommands = true; animNum = 0; memset( animWeights, 0, sizeof( animWeights ) ); blendStartValue = 0.0f; blendEndValue = 0.0f; blendStartTime = 0; blendDuration = 0; } /* ===================== idAnimBlend::FullName ===================== */ const char *idAnimBlend::AnimFullName( void ) const { const idAnim *anim = Anim(); if ( !anim ) { return ""; } return anim->FullName(); } /* ===================== idAnimBlend::AnimName ===================== */ const char *idAnimBlend::AnimName( void ) const { const idAnim *anim = Anim(); if ( !anim ) { return ""; } return anim->Name(); } /* ===================== idAnimBlend::NumFrames ===================== */ int idAnimBlend::NumFrames( void ) const { const idAnim *anim = Anim(); if ( !anim ) { return 0; } return anim->NumFrames(); } /* ===================== idAnimBlend::Length ===================== */ int idAnimBlend::Length( void ) const { const idAnim *anim = Anim(); if ( !anim ) { return 0; } return anim->Length(); } /* ===================== idAnimBlend::GetWeight ===================== */ float idAnimBlend::GetWeight( int currentTime ) const { int timeDelta; float frac; float w; timeDelta = currentTime - blendStartTime; if ( timeDelta <= 0 ) { w = blendStartValue; } else if ( timeDelta >= blendDuration ) { w = blendEndValue; } else { frac = ( float )timeDelta / ( float )blendDuration; w = blendStartValue + ( blendEndValue - blendStartValue ) * frac; } return w; } /* ===================== idAnimBlend::GetFinalWeight ===================== */ float idAnimBlend::GetFinalWeight( void ) const { return blendEndValue; } /* ===================== idAnimBlend::SetWeight ===================== */ void idAnimBlend::SetWeight( float newweight, int currentTime, int blendTime ) { blendStartValue = GetWeight( currentTime ); blendEndValue = newweight; blendStartTime = currentTime - 1; blendDuration = blendTime; if ( !newweight ) { endtime = currentTime + blendTime; } } /* ===================== idAnimBlend::NumSyncedAnims ===================== */ int idAnimBlend::NumSyncedAnims( void ) const { const idAnim *anim = Anim(); if ( !anim ) { return 0; } return anim->NumAnims(); } /* ===================== idAnimBlend::SetSyncedAnimWeight ===================== */ bool idAnimBlend::SetSyncedAnimWeight( int num, float weight ) { const idAnim *anim = Anim(); if ( !anim ) { return false; } if ( ( num < 0 ) || ( num > anim->NumAnims() ) ) { return false; } animWeights[ num ] = weight; return true; } /* ===================== idAnimBlend::SetFrame ===================== */ void idAnimBlend::SetFrame( const idDeclModelDef *modelDef, int _animNum, int _frame, int currentTime, int blendTime ) { Reset( modelDef ); if ( !modelDef ) { return; } const idAnim *_anim = modelDef->GetAnim( _animNum ); if ( !_anim ) { return; } const idMD5Anim *md5anim = _anim->MD5Anim( 0 ); if ( modelDef->Joints().Num() != md5anim->NumJoints() ) { gameLocal.Warning( "Model '%s' has different # of joints than anim '%s'", modelDef->GetModelName(), md5anim->Name() ); return; } animNum = _animNum; starttime = currentTime; endtime = -1; cycle = -1; animWeights[ 0 ] = 1.0f; frame = _frame; // a frame of 0 means it's not a single frame blend, so we set it to frame + 1 if ( frame <= 0 ) { frame = 1; } else if ( frame > _anim->NumFrames() ) { frame = _anim->NumFrames(); } // set up blend blendEndValue = 1.0f; blendStartTime = currentTime - 1; blendDuration = blendTime; blendStartValue = 0.0f; } /* ===================== idAnimBlend::CycleAnim ===================== */ void idAnimBlend::CycleAnim( const idDeclModelDef *modelDef, int _animNum, int currentTime, int blendTime ) { Reset( modelDef ); if ( !modelDef ) { return; } const idAnim *_anim = modelDef->GetAnim( _animNum ); if ( !_anim ) { return; } const idMD5Anim *md5anim = _anim->MD5Anim( 0 ); if ( modelDef->Joints().Num() != md5anim->NumJoints() ) { gameLocal.Warning( "Model '%s' has different # of joints than anim '%s'", modelDef->GetModelName(), md5anim->Name() ); return; } animNum = _animNum; animWeights[ 0 ] = 1.0f; endtime = -1; cycle = -1; if ( _anim->GetAnimFlags().random_cycle_start ) { // start the animation at a random time so that characters don't walk in sync starttime = currentTime - gameLocal.random.RandomFloat() * _anim->Length(); } else { starttime = currentTime; } // set up blend blendEndValue = 1.0f; blendStartTime = currentTime - 1; blendDuration = blendTime; blendStartValue = 0.0f; } /* ===================== idAnimBlend::PlayAnim ===================== */ void idAnimBlend::PlayAnim( const idDeclModelDef *modelDef, int _animNum, int currentTime, int blendTime ) { Reset( modelDef ); if ( !modelDef ) { return; } const idAnim *_anim = modelDef->GetAnim( _animNum ); if ( !_anim ) { return; } const idMD5Anim *md5anim = _anim->MD5Anim( 0 ); if ( modelDef->Joints().Num() != md5anim->NumJoints() ) { gameLocal.Warning( "Model '%s' has different # of joints than anim '%s'", modelDef->GetModelName(), md5anim->Name() ); return; } animNum = _animNum; starttime = currentTime; endtime = starttime + _anim->Length(); cycle = 1; animWeights[ 0 ] = 1.0f; // set up blend blendEndValue = 1.0f; blendStartTime = currentTime - 1; blendDuration = blendTime; blendStartValue = 0.0f; } /* ===================== idAnimBlend::Clear ===================== */ void idAnimBlend::Clear( int currentTime, int clearTime ) { if ( !clearTime ) { Reset( modelDef ); } else { SetWeight( 0.0f, currentTime, clearTime ); } } /* ===================== idAnimBlend::IsDone ===================== */ bool idAnimBlend::IsDone( int currentTime ) const { if ( !frame && ( endtime > 0 ) && ( currentTime >= endtime ) ) { return true; } if ( ( blendEndValue <= 0.0f ) && ( currentTime >= ( blendStartTime + blendDuration ) ) ) { return true; } return false; } /* ===================== idAnimBlend::FrameHasChanged ===================== */ bool idAnimBlend::FrameHasChanged( int currentTime ) const { // if we don't have an anim, no change if ( !animNum ) { return false; } // if anim is done playing, no change if ( ( endtime > 0 ) && ( currentTime > endtime ) ) { return false; } // if our blend weight changes, we need to update if ( ( currentTime < ( blendStartTime + blendDuration ) && ( blendStartValue != blendEndValue ) ) ) { return true; } // if we're a single frame anim and this isn't the frame we started on, we don't need to update if ( ( frame || ( NumFrames() == 1 ) ) && ( currentTime != starttime ) ) { return false; } return true; } /* ===================== idAnimBlend::GetCycleCount ===================== */ int idAnimBlend::GetCycleCount( void ) const { return cycle; } /* ===================== idAnimBlend::SetCycleCount ===================== */ void idAnimBlend::SetCycleCount( int count ) { const idAnim *anim = Anim(); if ( !anim ) { cycle = -1; endtime = 0; } else { cycle = count; if ( cycle < 0 ) { cycle = -1; endtime = -1; } else if ( cycle == 0 ) { cycle = 1; // most of the time we're running at the original frame rate, so avoid the int-to-float-to-int conversion if ( rate == 1.0f ) { endtime = starttime - timeOffset + anim->Length(); } else if ( rate != 0.0f ) { endtime = starttime - timeOffset + anim->Length() / rate; } else { endtime = -1; } } else { // most of the time we're running at the original frame rate, so avoid the int-to-float-to-int conversion if ( rate == 1.0f ) { endtime = starttime - timeOffset + anim->Length() * cycle; } else if ( rate != 0.0f ) { endtime = starttime - timeOffset + ( anim->Length() * cycle ) / rate; } else { endtime = -1; } } } } /* ===================== idAnimBlend::SetPlaybackRate ===================== */ void idAnimBlend::SetPlaybackRate( int currentTime, float newRate ) { int animTime; if ( rate == newRate ) { return; } animTime = AnimTime( currentTime ); if ( newRate == 1.0f ) { timeOffset = animTime - ( currentTime - starttime ); } else { timeOffset = animTime - ( currentTime - starttime ) * newRate; } rate = newRate; // update the anim endtime SetCycleCount( cycle ); } /* ===================== idAnimBlend::GetPlaybackRate ===================== */ float idAnimBlend::GetPlaybackRate( void ) const { return rate; } /* ===================== idAnimBlend::SetStartTime ===================== */ void idAnimBlend::SetStartTime( int _startTime ) { starttime = _startTime; // update the anim endtime SetCycleCount( cycle ); } /* ===================== idAnimBlend::GetStartTime ===================== */ int idAnimBlend::GetStartTime( void ) const { if ( !animNum ) { return 0; } return starttime; } /* ===================== idAnimBlend::GetEndTime ===================== */ int idAnimBlend::GetEndTime( void ) const { if ( !animNum ) { return 0; } return endtime; } /* ===================== idAnimBlend::PlayLength ===================== */ int idAnimBlend::PlayLength( void ) const { if ( !animNum ) { return 0; } if ( endtime < 0 ) { return -1; } return endtime - starttime + timeOffset; } /* ===================== idAnimBlend::AllowMovement ===================== */ void idAnimBlend::AllowMovement( bool allow ) { allowMove = allow; } /* ===================== idAnimBlend::AllowFrameCommands ===================== */ void idAnimBlend::AllowFrameCommands( bool allow ) { allowFrameCommands = allow; } /* ===================== idAnimBlend::Anim ===================== */ const idAnim *idAnimBlend::Anim( void ) const { if ( !modelDef ) { return NULL; } const idAnim *anim = modelDef->GetAnim( animNum ); return anim; } /* ===================== idAnimBlend::AnimNum ===================== */ int idAnimBlend::AnimNum( void ) const { return animNum; } /* ===================== idAnimBlend::AnimTime ===================== */ int idAnimBlend::AnimTime( int currentTime ) const { int time; int length; const idAnim *anim = Anim(); if ( anim ) { if ( frame ) { return FRAME2MS( frame - 1 ); } // most of the time we're running at the original frame rate, so avoid the int-to-float-to-int conversion if ( rate == 1.0f ) { time = currentTime - starttime + timeOffset; } else { time = static_cast<int>( ( currentTime - starttime ) * rate ) + timeOffset; } // given enough time, we can easily wrap time around in our frame calculations, so // keep cycling animations' time within the length of the anim. length = anim->Length(); if ( ( cycle < 0 ) && ( length > 0 ) ) { time %= length; // time will wrap after 24 days (oh no!), resulting in negative results for the %. // adding the length gives us the proper result. if ( time < 0 ) { time += length; } } return time; } else { return 0; } } /* ===================== idAnimBlend::GetFrameNumber ===================== */ int idAnimBlend::GetFrameNumber( int currentTime ) const { const idMD5Anim *md5anim; frameBlend_t frameinfo; int animTime; const idAnim *anim = Anim(); if ( !anim ) { return 1; } if ( frame ) { return frame; } md5anim = anim->MD5Anim( 0 ); animTime = AnimTime( currentTime ); md5anim->ConvertTimeToFrame( animTime, cycle, frameinfo ); return frameinfo.frame1 + 1; } /* ===================== idAnimBlend::CallFrameCommands ===================== */ void idAnimBlend::CallFrameCommands( idEntity *ent, int fromtime, int totime ) const { const idMD5Anim *md5anim; frameBlend_t frame1; frameBlend_t frame2; int fromFrameTime; int toFrameTime; if ( !allowFrameCommands || !ent || frame || ( ( endtime > 0 ) && ( fromtime > endtime ) ) ) { return; } const idAnim *anim = Anim(); if ( !anim || !anim->HasFrameCommands() ) { return; } if ( totime <= starttime ) { // don't play until next frame or we'll play commands twice. // this happens on the player sometimes. return; } fromFrameTime = AnimTime( fromtime ); toFrameTime = AnimTime( totime ); if ( toFrameTime < fromFrameTime ) { toFrameTime += anim->Length(); } md5anim = anim->MD5Anim( 0 ); md5anim->ConvertTimeToFrame( fromFrameTime, cycle, frame1 ); md5anim->ConvertTimeToFrame( toFrameTime, cycle, frame2 ); if ( fromFrameTime <= 0 ) { // make sure first frame is called anim->CallFrameCommands( ent, -1, frame2.frame1 ); } else { anim->CallFrameCommands( ent, frame1.frame1, frame2.frame1 ); } } /* ===================== idAnimBlend::BlendAnim ===================== */ bool idAnimBlend::BlendAnim( int currentTime, int channel, int numJoints, idJointQuat *blendFrame, float &blendWeight, bool removeOriginOffset, bool overrideBlend, bool printInfo ) const { int i; float lerp; float mixWeight; const idMD5Anim *md5anim; idJointQuat *ptr; frameBlend_t frametime; idJointQuat *jointFrame; idJointQuat *mixFrame; int numAnims; int time; const idAnim *anim = Anim(); if ( !anim ) { return false; } float weight = GetWeight( currentTime ); if ( blendWeight > 0.0f ) { if ( ( endtime >= 0 ) && ( currentTime >= endtime ) ) { return false; } if ( !weight ) { return false; } if ( overrideBlend ) { blendWeight = 1.0f - weight; } } if ( ( channel == ANIMCHANNEL_ALL ) && !blendWeight ) { // we don't need a temporary buffer, so just store it directly in the blend frame jointFrame = blendFrame; } else { // allocate a temporary buffer to copy the joints from jointFrame = ( idJointQuat * )_alloca16( numJoints * sizeof( *jointFrame ) ); } time = AnimTime( currentTime ); numAnims = anim->NumAnims(); if ( numAnims == 1 ) { md5anim = anim->MD5Anim( 0 ); if ( frame ) { md5anim->GetSingleFrame( frame - 1, jointFrame, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } else { md5anim->ConvertTimeToFrame( time, cycle, frametime ); md5anim->GetInterpolatedFrame( frametime, jointFrame, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } } else { // // need to mix the multipoint anim together first // // allocate a temporary buffer to copy the joints to mixFrame = ( idJointQuat * )_alloca16( numJoints * sizeof( *jointFrame ) ); if ( !frame ) { anim->MD5Anim( 0 )->ConvertTimeToFrame( time, cycle, frametime ); } ptr = jointFrame; mixWeight = 0.0f; for( i = 0; i < numAnims; i++ ) { if ( animWeights[ i ] > 0.0f ) { mixWeight += animWeights[ i ]; lerp = animWeights[ i ] / mixWeight; md5anim = anim->MD5Anim( i ); if ( frame ) { md5anim->GetSingleFrame( frame - 1, ptr, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } else { md5anim->GetInterpolatedFrame( frametime, ptr, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } // only blend after the first anim is mixed in if ( ptr != jointFrame ) { SIMDProcessor->BlendJoints( jointFrame, ptr, lerp, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } ptr = mixFrame; } } if ( !mixWeight ) { return false; } } if ( removeOriginOffset ) { if ( allowMove ) { #ifdef VELOCITY_MOVE jointFrame[ 0 ].t.x = 0.0f; #else jointFrame[ 0 ].t.Zero(); #endif } if ( anim->GetAnimFlags().anim_turn ) { jointFrame[ 0 ].q.Set( -0.70710677f, 0.0f, 0.0f, 0.70710677f ); } } if ( !blendWeight ) { blendWeight = weight; if ( channel != ANIMCHANNEL_ALL ) { const int *index = modelDef->GetChannelJoints( channel ); const int num = modelDef->NumJointsOnChannel( channel ); for( i = 0; i < num; i++ ) { int j = index[i]; blendFrame[j].t = jointFrame[j].t; blendFrame[j].q = jointFrame[j].q; } } } else { blendWeight += weight; lerp = weight / blendWeight; SIMDProcessor->BlendJoints( blendFrame, jointFrame, lerp, modelDef->GetChannelJoints( channel ), modelDef->NumJointsOnChannel( channel ) ); } if ( printInfo ) { if ( frame ) { gameLocal.Printf( " %s: '%s', %d, %.2f%%\n", channelNames[ channel ], anim->FullName(), frame, weight * 100.0f ); } else { gameLocal.Printf( " %s: '%s', %.3f, %.2f%%\n", channelNames[ channel ], anim->FullName(), ( float )frametime.frame1 + frametime.backlerp, weight * 100.0f ); } } return true; } /* ===================== idAnimBlend::BlendOrigin ===================== */ void idAnimBlend::BlendOrigin( int currentTime, idVec3 &blendPos, float &blendWeight, bool removeOriginOffset ) const { float lerp; idVec3 animpos; idVec3 pos; int time; int num; int i; if ( frame || ( ( endtime > 0 ) && ( currentTime > endtime ) ) ) { return; } const idAnim *anim = Anim(); if ( !anim ) { return; } if ( allowMove && removeOriginOffset ) { return; } float weight = GetWeight( currentTime ); if ( !weight ) { return; } time = AnimTime( currentTime ); pos.Zero(); num = anim->NumAnims(); for( i = 0; i < num; i++ ) { anim->GetOrigin( animpos, i, time, cycle ); pos += animpos * animWeights[ i ]; } if ( !blendWeight ) { blendPos = pos; blendWeight = weight; } else { lerp = weight / ( blendWeight + weight ); blendPos += lerp * ( pos - blendPos ); blendWeight += weight; } } /* ===================== idAnimBlend::BlendDelta ===================== */ void idAnimBlend::BlendDelta( int fromtime, int totime, idVec3 &blendDelta, float &blendWeight ) const { idVec3 pos1; idVec3 pos2; idVec3 animpos; idVec3 delta; int time1; int time2; float lerp; int num; int i; if ( frame || !allowMove || ( ( endtime > 0 ) && ( fromtime > endtime ) ) ) { return; } const idAnim *anim = Anim(); if ( !anim ) { return; } float weight = GetWeight( totime ); if ( !weight ) { return; } time1 = AnimTime( fromtime ); time2 = AnimTime( totime ); if ( time2 < time1 ) { time2 += anim->Length(); } num = anim->NumAnims(); pos1.Zero(); pos2.Zero(); for( i = 0; i < num; i++ ) { anim->GetOrigin( animpos, i, time1, cycle ); pos1 += animpos * animWeights[ i ]; anim->GetOrigin( animpos, i, time2, cycle ); pos2 += animpos * animWeights[ i ]; } delta = pos2 - pos1; if ( !blendWeight ) { blendDelta = delta; blendWeight = weight; } else { lerp = weight / ( blendWeight + weight ); blendDelta += lerp * ( delta - blendDelta ); blendWeight += weight; } } /* ===================== idAnimBlend::BlendDeltaRotation ===================== */ void idAnimBlend::BlendDeltaRotation( int fromtime, int totime, idQuat &blendDelta, float &blendWeight ) const { idQuat q1; idQuat q2; idQuat q3; int time1; int time2; float lerp; float mixWeight; int num; int i; if ( frame || !allowMove || ( ( endtime > 0 ) && ( fromtime > endtime ) ) ) { return; } const idAnim *anim = Anim(); if ( !anim || !anim->GetAnimFlags().anim_turn ) { return; } float weight = GetWeight( totime ); if ( !weight ) { return; } time1 = AnimTime( fromtime ); time2 = AnimTime( totime ); if ( time2 < time1 ) { time2 += anim->Length(); } q1.Set( 0.0f, 0.0f, 0.0f, 1.0f ); q2.Set( 0.0f, 0.0f, 0.0f, 1.0f ); mixWeight = 0.0f; num = anim->NumAnims(); for( i = 0; i < num; i++ ) { if ( animWeights[ i ] > 0.0f ) { mixWeight += animWeights[ i ]; if ( animWeights[ i ] == mixWeight ) { anim->GetOriginRotation( q1, i, time1, cycle ); anim->GetOriginRotation( q2, i, time2, cycle ); } else { lerp = animWeights[ i ] / mixWeight; anim->GetOriginRotation( q3, i, time1, cycle ); q1.Slerp( q1, q3, lerp ); anim->GetOriginRotation( q3, i, time2, cycle ); q2.Slerp( q1, q3, lerp ); } } } q3 = q1.Inverse() * q2; if ( !blendWeight ) { blendDelta = q3; blendWeight = weight; } else { lerp = weight / ( blendWeight + weight ); blendDelta.Slerp( blendDelta, q3, lerp ); blendWeight += weight; } } /* ===================== idAnimBlend::AddBounds ===================== */ bool idAnimBlend::AddBounds( int currentTime, idBounds &bounds, bool removeOriginOffset ) const { int i; int num; idBounds b; int time; idVec3 pos; bool addorigin; if ( ( endtime > 0 ) && ( currentTime > endtime ) ) { return false; } const idAnim *anim = Anim(); if ( !anim ) { return false; } float weight = GetWeight( currentTime ); if ( !weight ) { return false; } time = AnimTime( currentTime ); num = anim->NumAnims(); addorigin = !allowMove || !removeOriginOffset; for( i = 0; i < num; i++ ) { if ( anim->GetBounds( b, i, time, cycle ) ) { if ( addorigin ) { anim->GetOrigin( pos, i, time, cycle ); b.TranslateSelf( pos ); } bounds.AddBounds( b ); } } return true; } /*********************************************************************** idDeclModelDef ***********************************************************************/ /* ===================== idDeclModelDef::idDeclModelDef ===================== */ idDeclModelDef::idDeclModelDef() { modelHandle = NULL; skin = NULL; offset.Zero(); for ( int i = 0; i < ANIM_NumAnimChannels; i++ ) { channelJoints[i].Clear(); } } /* ===================== idDeclModelDef::~idDeclModelDef ===================== */ idDeclModelDef::~idDeclModelDef() { FreeData(); } /* ================= idDeclModelDef::Size ================= */ size_t idDeclModelDef::Size( void ) const { return sizeof( idDeclModelDef ); } /* ===================== idDeclModelDef::CopyDecl ===================== */ void idDeclModelDef::CopyDecl( const idDeclModelDef *decl ) { int i; FreeData(); offset = decl->offset; modelHandle = decl->modelHandle; skin = decl->skin; anims.SetNum( decl->anims.Num() ); for( i = 0; i < anims.Num(); i++ ) { anims[ i ] = new idAnim( this, decl->anims[ i ] ); } joints.SetNum( decl->joints.Num() ); memcpy( joints.Ptr(), decl->joints.Ptr(), decl->joints.Num() * sizeof( joints[0] ) ); jointParents.SetNum( decl->jointParents.Num() ); memcpy( jointParents.Ptr(), decl->jointParents.Ptr(), decl->jointParents.Num() * sizeof( jointParents[0] ) ); for ( i = 0; i < ANIM_NumAnimChannels; i++ ) { channelJoints[i] = decl->channelJoints[i]; } } /* ===================== idDeclModelDef::FreeData ===================== */ void idDeclModelDef::FreeData( void ) { anims.DeleteContents( true ); joints.Clear(); jointParents.Clear(); modelHandle = NULL; skin = NULL; offset.Zero(); for ( int i = 0; i < ANIM_NumAnimChannels; i++ ) { channelJoints[i].Clear(); } } /* ================ idDeclModelDef::DefaultDefinition ================ */ const char *idDeclModelDef::DefaultDefinition( void ) const { return "{ }"; } /* ==================== idDeclModelDef::FindJoint ==================== */ const jointInfo_t *idDeclModelDef::FindJoint( const char *name ) const { int i; const idMD5Joint *joint; if ( !modelHandle ) { return NULL; } joint = modelHandle->GetJoints(); for( i = 0; i < joints.Num(); i++, joint++ ) { if ( !joint->name.Icmp( name ) ) { return &joints[ i ]; } } return NULL; } /* ===================== idDeclModelDef::ModelHandle ===================== */ idRenderModel *idDeclModelDef::ModelHandle( void ) const { return ( idRenderModel * )modelHandle; } /* ===================== idDeclModelDef::GetJointList ===================== */ void idDeclModelDef::GetJointList( const char *jointnames, idList<jointHandle_t> &jointList ) const { const char *pos; idStr jointname; const jointInfo_t *joint; const jointInfo_t *child; int i; int num; bool getChildren; bool subtract; if ( !modelHandle ) { return; } jointList.Clear(); num = modelHandle->NumJoints(); // scan through list of joints and add each to the joint list pos = jointnames; while( *pos ) { // skip over whitespace while( ( *pos != 0 ) && isspace( *pos ) ) { pos++; } if ( !*pos ) { // no more names break; } // copy joint name jointname = ""; if ( *pos == '-' ) { subtract = true; pos++; } else { subtract = false; } if ( *pos == '*' ) { getChildren = true; pos++; } else { getChildren = false; } while( ( *pos != 0 ) && !isspace( *pos ) ) { jointname += *pos; pos++; } joint = FindJoint( jointname ); if ( !joint ) { gameLocal.Warning( "Unknown joint '%s' in '%s' for model '%s'", jointname.c_str(), jointnames, GetName() ); continue; } if ( !subtract ) { jointList.AddUnique( joint->num ); } else { jointList.Remove( joint->num ); } if ( getChildren ) { // include all joint's children child = joint + 1; for( i = joint->num + 1; i < num; i++, child++ ) { // all children of the joint should follow it in the list. // once we reach a joint without a parent or with a parent // who is earlier in the list than the specified joint, then // we've gone through all it's children. if ( child->parentNum < joint->num ) { break; } if ( !subtract ) { jointList.AddUnique( child->num ); } else { jointList.Remove( child->num ); } } } } } /* ===================== idDeclModelDef::Touch ===================== */ void idDeclModelDef::Touch( void ) const { if ( modelHandle ) { renderModelManager->FindModel( modelHandle->Name() ); } } /* ===================== idDeclModelDef::GetDefaultSkin ===================== */ const idDeclSkin *idDeclModelDef::GetDefaultSkin( void ) const { return skin; } /* ===================== idDeclModelDef::GetDefaultPose ===================== */ const idJointQuat *idDeclModelDef::GetDefaultPose( void ) const { return modelHandle->GetDefaultPose(); } /* ===================== idDeclModelDef::SetupJoints ===================== */ void idDeclModelDef::SetupJoints( int *numJoints, idJointMat **jointList, idBounds &frameBounds, bool removeOriginOffset ) const { int num; const idJointQuat *pose; idJointMat *list; if ( !modelHandle || modelHandle->IsDefaultModel() ) { Mem_Free16( (*jointList) ); (*jointList) = NULL; frameBounds.Clear(); return; } // get the number of joints num = modelHandle->NumJoints(); if ( !num ) { gameLocal.Error( "model '%s' has no joints", modelHandle->Name() ); } // set up initial pose for model (with no pose, model is just a jumbled mess) list = (idJointMat *) Mem_Alloc16( num * sizeof( list[0] ) ); pose = GetDefaultPose(); // convert the joint quaternions to joint matrices SIMDProcessor->ConvertJointQuatsToJointMats( list, pose, joints.Num() ); // check if we offset the model by the origin joint if ( removeOriginOffset ) { #ifdef VELOCITY_MOVE list[ 0 ].SetTranslation( idVec3( offset.x, offset.y + pose[0].t.y, offset.z + pose[0].t.z ) ); #else list[ 0 ].SetTranslation( offset ); #endif } else { list[ 0 ].SetTranslation( pose[0].t + offset ); } // transform the joint hierarchy SIMDProcessor->TransformJoints( list, jointParents.Ptr(), 1, joints.Num() - 1 ); *numJoints = num; *jointList = list; // get the bounds of the default pose frameBounds = modelHandle->Bounds( NULL ); } /* ===================== idDeclModelDef::ParseAnim ===================== */ bool idDeclModelDef::ParseAnim( idLexer &src, int numDefaultAnims ) { int i; int len; idAnim *anim; const idMD5Anim *md5anims[ ANIM_MaxSyncedAnims ]; const idMD5Anim *md5anim; idStr alias; idToken realname; idToken token; int numAnims; animFlags_t flags; numAnims = 0; memset( md5anims, 0, sizeof( md5anims ) ); if( !src.ReadToken( &realname ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } alias = realname; for( i = 0; i < anims.Num(); i++ ) { if ( !strcmp( anims[ i ]->FullName(), realname ) ) { break; } } if ( ( i < anims.Num() ) && ( i >= numDefaultAnims ) ) { src.Warning( "Duplicate anim '%s'", realname.c_str() ); MakeDefault(); return false; } if ( i < numDefaultAnims ) { anim = anims[ i ]; } else { // create the alias associated with this animation anim = new idAnim(); anims.Append( anim ); } // random anims end with a number. find the numeric suffix of the animation. len = alias.Length(); for( i = len - 1; i > 0; i-- ) { if ( !isdigit( alias[ i ] ) ) { break; } } // check for zero length name, or a purely numeric name if ( i <= 0 ) { src.Warning( "Invalid animation name '%s'", alias.c_str() ); MakeDefault(); return false; } // remove the numeric suffix alias.CapLength( i + 1 ); // parse the anims from the string do { if( !src.ReadToken( &token ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } // lookup the animation md5anim = animationLib.GetAnim( token ); if ( !md5anim ) { src.Warning( "Couldn't load anim '%s'", token.c_str() ); MakeDefault(); return false; } md5anim->CheckModelHierarchy( modelHandle ); if ( numAnims > 0 ) { // make sure it's the same length as the other anims if ( md5anim->Length() != md5anims[ 0 ]->Length() ) { src.Warning( "Anim '%s' does not match length of anim '%s'", md5anim->Name(), md5anims[ 0 ]->Name() ); MakeDefault(); return false; } } if ( numAnims >= ANIM_MaxSyncedAnims ) { src.Warning( "Exceeded max synced anims (%d)", ANIM_MaxSyncedAnims ); MakeDefault(); return false; } // add it to our list md5anims[ numAnims ] = md5anim; numAnims++; } while ( src.CheckTokenString( "," ) ); if ( !numAnims ) { src.Warning( "No animation specified" ); MakeDefault(); return false; } anim->SetAnim( this, realname, alias, numAnims, md5anims ); memset( &flags, 0, sizeof( flags ) ); // parse any frame commands or animflags if ( src.CheckTokenString( "{" ) ) { while( 1 ) { if( !src.ReadToken( &token ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } if ( token == "}" ) { break; }else if ( token == "prevent_idle_override" ) { flags.prevent_idle_override = true; } else if ( token == "random_cycle_start" ) { flags.random_cycle_start = true; } else if ( token == "ai_no_turn" ) { flags.ai_no_turn = true; } else if ( token == "anim_turn" ) { flags.anim_turn = true; } else if ( token == "frame" ) { // create a frame command int framenum; const char *err; // make sure we don't have any line breaks while reading the frame command so the error line # will be correct if ( !src.ReadTokenOnLine( &token ) ) { src.Warning( "Missing frame # after 'frame'" ); MakeDefault(); return false; } if ( token.type == TT_PUNCTUATION && token == "-" ) { src.Warning( "Invalid frame # after 'frame'" ); MakeDefault(); return false; } else if ( token.type != TT_NUMBER || token.subtype == TT_FLOAT ) { src.Error( "expected integer value, found '%s'", token.c_str() ); } // get the frame number framenum = token.GetIntValue(); // put the command on the specified frame of the animation err = anim->AddFrameCommand( this, framenum, src, NULL ); if ( err ) { src.Warning( "%s", err ); MakeDefault(); return false; } } else { src.Warning( "Unknown command '%s'", token.c_str() ); MakeDefault(); return false; } } } // set the flags anim->SetAnimFlags( flags ); return true; } /* ================ idDeclModelDef::Parse ================ */ bool idDeclModelDef::Parse( const char *text, const int textLength ) { int i; int num; idStr filename; idStr extension; const idMD5Joint *md5joint; const idMD5Joint *md5joints; idLexer src; idToken token; idToken token2; idStr jointnames; int channel; jointHandle_t jointnum; idList<jointHandle_t> jointList; int numDefaultAnims; src.LoadMemory( text, textLength, GetFileName(), GetLineNum() ); src.SetFlags( DECL_LEXER_FLAGS ); src.SkipUntilString( "{" ); numDefaultAnims = 0; while( 1 ) { if ( !src.ReadToken( &token ) ) { break; } if ( !token.Icmp( "}" ) ) { break; } if ( token == "inherit" ) { if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } const idDeclModelDef *copy = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, token2, false ) ); if ( !copy ) { common->Warning( "Unknown model definition '%s'", token2.c_str() ); } else if ( copy->GetState() == DS_DEFAULTED ) { common->Warning( "inherited model definition '%s' defaulted", token2.c_str() ); MakeDefault(); return false; } else { CopyDecl( copy ); numDefaultAnims = anims.Num(); } } else if ( token == "skin" ) { if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } skin = declManager->FindSkin( token2 ); if ( !skin ) { src.Warning( "Skin '%s' not found", token2.c_str() ); MakeDefault(); return false; } } else if ( token == "mesh" ) { if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } filename = token2; filename.ExtractFileExtension( extension ); if ( extension != MD5_MESH_EXT ) { src.Warning( "Invalid model for MD5 mesh" ); MakeDefault(); return false; } modelHandle = renderModelManager->FindModel( filename ); if ( !modelHandle ) { src.Warning( "Model '%s' not found", filename.c_str() ); MakeDefault(); return false; } if ( modelHandle->IsDefaultModel() ) { src.Warning( "Model '%s' defaulted", filename.c_str() ); MakeDefault(); return false; } // get the number of joints num = modelHandle->NumJoints(); if ( !num ) { src.Warning( "Model '%s' has no joints", filename.c_str() ); } // set up the joint hierarchy joints.SetGranularity( 1 ); joints.SetNum( num ); jointParents.SetNum( num ); channelJoints[0].SetNum( num ); md5joints = modelHandle->GetJoints(); md5joint = md5joints; for( i = 0; i < num; i++, md5joint++ ) { joints[i].channel = ANIMCHANNEL_ALL; joints[i].num = static_cast<jointHandle_t>( i ); if ( md5joint->parent ) { joints[i].parentNum = static_cast<jointHandle_t>( md5joint->parent - md5joints ); } else { joints[i].parentNum = INVALID_JOINT; } jointParents[i] = joints[i].parentNum; channelJoints[0][i] = i; } } else if ( token == "remove" ) { // removes any anims whos name matches if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } num = 0; for( i = 0; i < anims.Num(); i++ ) { if ( ( token2 == anims[ i ]->Name() ) || ( token2 == anims[ i ]->FullName() ) ) { delete anims[ i ]; anims.RemoveIndex( i ); if ( i >= numDefaultAnims ) { src.Warning( "Anim '%s' was not inherited. Anim should be removed from the model def.", token2.c_str() ); MakeDefault(); return false; } i--; numDefaultAnims--; num++; continue; } } if ( !num ) { src.Warning( "Couldn't find anim '%s' to remove", token2.c_str() ); MakeDefault(); return false; } } else if ( token == "anim" ) { if ( !modelHandle ) { src.Warning( "Must specify mesh before defining anims" ); MakeDefault(); return false; } if ( !ParseAnim( src, numDefaultAnims ) ) { MakeDefault(); return false; } } else if ( token == "offset" ) { if ( !src.Parse1DMatrix( 3, offset.ToFloatPtr() ) ) { src.Warning( "Expected vector following 'offset'" ); MakeDefault(); return false; } } else if ( token == "channel" ) { if ( !modelHandle ) { src.Warning( "Must specify mesh before defining channels" ); MakeDefault(); return false; } // set the channel for a group of joints if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } if ( !src.CheckTokenString( "(" ) ) { src.Warning( "Expected { after '%s'\n", token2.c_str() ); MakeDefault(); return false; } for( i = ANIMCHANNEL_ALL + 1; i < ANIM_NumAnimChannels; i++ ) { if ( !idStr::Icmp( channelNames[ i ], token2 ) ) { break; } } if ( i >= ANIM_NumAnimChannels ) { src.Warning( "Unknown channel '%s'", token2.c_str() ); MakeDefault(); return false; } channel = i; jointnames = ""; while( !src.CheckTokenString( ")" ) ) { if( !src.ReadToken( &token2 ) ) { src.Warning( "Unexpected end of file" ); MakeDefault(); return false; } jointnames += token2; if ( ( token2 != "*" ) && ( token2 != "-" ) ) { jointnames += " "; } } GetJointList( jointnames, jointList ); channelJoints[ channel ].SetNum( jointList.Num() ); for( num = i = 0; i < jointList.Num(); i++ ) { jointnum = jointList[ i ]; if ( joints[ jointnum ].channel != ANIMCHANNEL_ALL ) { src.Warning( "Joint '%s' assigned to multiple channels", modelHandle->GetJointName( jointnum ) ); continue; } joints[ jointnum ].channel = channel; channelJoints[ channel ][ num++ ] = jointnum; } channelJoints[ channel ].SetNum( num ); } else { src.Warning( "unknown token '%s'", token.c_str() ); MakeDefault(); return false; } } // shrink the anim list down to save space anims.SetGranularity( 1 ); anims.SetNum( anims.Num() ); return true; } /* ===================== idDeclModelDef::HasAnim ===================== */ bool idDeclModelDef::HasAnim( const char *name ) const { int i; // find any animations with same name for( i = 0; i < anims.Num(); i++ ) { if ( !strcmp( anims[ i ]->Name(), name ) ) { return true; } } return false; } /* ===================== idDeclModelDef::NumAnims ===================== */ int idDeclModelDef::NumAnims( void ) const { return anims.Num() + 1; } /* ===================== idDeclModelDef::GetSpecificAnim Gets the exact anim for the name, without randomization. ===================== */ int idDeclModelDef::GetSpecificAnim( const char *name ) const { int i; // find a specific animation for( i = 0; i < anims.Num(); i++ ) { if ( !strcmp( anims[ i ]->FullName(), name ) ) { return i + 1; } } // didn't find it return 0; } /* ===================== idDeclModelDef::GetAnim ===================== */ const idAnim *idDeclModelDef::GetAnim( int index ) const { if ( ( index < 1 ) || ( index > anims.Num() ) ) { return NULL; } return anims[ index - 1 ]; } /* ===================== idDeclModelDef::GetAnim ===================== */ int idDeclModelDef::GetAnim( const char *name ) const { int i; int which; const int MAX_ANIMS = 64; int animList[ MAX_ANIMS ]; int numAnims; int len; len = strlen( name ); if ( len && idStr::CharIsNumeric( name[ len - 1 ] ) ) { // find a specific animation return GetSpecificAnim( name ); } // find all animations with same name numAnims = 0; for( i = 0; i < anims.Num(); i++ ) { if ( !strcmp( anims[ i ]->Name(), name ) ) { animList[ numAnims++ ] = i; if ( numAnims >= MAX_ANIMS ) { break; } } } if ( !numAnims ) { return 0; } // get a random anim //FIXME: don't access gameLocal here? which = gameLocal.random.RandomInt( numAnims ); return animList[ which ] + 1; } /* ===================== idDeclModelDef::GetSkin ===================== */ const idDeclSkin *idDeclModelDef::GetSkin( void ) const { return skin; } /* ===================== idDeclModelDef::GetModelName ===================== */ const char *idDeclModelDef::GetModelName( void ) const { if ( modelHandle ) { return modelHandle->Name(); } else { return ""; } } /* ===================== idDeclModelDef::Joints ===================== */ const idList<jointInfo_t> &idDeclModelDef::Joints( void ) const { return joints; } /* ===================== idDeclModelDef::JointParents ===================== */ const int * idDeclModelDef::JointParents( void ) const { return jointParents.Ptr(); } /* ===================== idDeclModelDef::NumJoints ===================== */ int idDeclModelDef::NumJoints( void ) const { return joints.Num(); } /* ===================== idDeclModelDef::GetJoint ===================== */ const jointInfo_t *idDeclModelDef::GetJoint( int jointHandle ) const { if ( ( jointHandle < 0 ) || ( jointHandle > joints.Num() ) ) { gameLocal.Error( "idDeclModelDef::GetJoint : joint handle out of range" ); } return &joints[ jointHandle ]; } /* ==================== idDeclModelDef::GetJointName ==================== */ const char *idDeclModelDef::GetJointName( int jointHandle ) const { const idMD5Joint *joint; if ( !modelHandle ) { return NULL; } if ( ( jointHandle < 0 ) || ( jointHandle > joints.Num() ) ) { gameLocal.Error( "idDeclModelDef::GetJointName : joint handle out of range" ); } joint = modelHandle->GetJoints(); return joint[ jointHandle ].name.c_str(); } /* ===================== idDeclModelDef::NumJointsOnChannel ===================== */ int idDeclModelDef::NumJointsOnChannel( int channel ) const { if ( ( channel < 0 ) || ( channel >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idDeclModelDef::NumJointsOnChannel : channel out of range" ); } return channelJoints[ channel ].Num(); } /* ===================== idDeclModelDef::GetChannelJoints ===================== */ const int * idDeclModelDef::GetChannelJoints( int channel ) const { if ( ( channel < 0 ) || ( channel >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idDeclModelDef::GetChannelJoints : channel out of range" ); } return channelJoints[ channel ].Ptr(); } /* ===================== idDeclModelDef::GetVisualOffset ===================== */ const idVec3 &idDeclModelDef::GetVisualOffset( void ) const { return offset; } /*********************************************************************** idAnimator ***********************************************************************/ /* ===================== idAnimator::idAnimator ===================== */ idAnimator::idAnimator() { int i, j; modelDef = NULL; entity = NULL; numJoints = 0; joints = NULL; lastTransformTime = -1; stoppedAnimatingUpdate = false; removeOriginOffset = false; forceUpdate = false; frameBounds.Clear(); AFPoseJoints.SetGranularity( 1 ); AFPoseJointMods.SetGranularity( 1 ); AFPoseJointFrame.SetGranularity( 1 ); ClearAFPose(); for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++ ) { channels[ i ][ j ].Reset( NULL ); } } } /* ===================== idAnimator::~idAnimator ===================== */ idAnimator::~idAnimator() { FreeData(); } /* ===================== idAnimator::Allocated ===================== */ size_t idAnimator::Allocated( void ) const { size_t size; size = jointMods.Allocated() + numJoints * sizeof( joints[0] ) + jointMods.Num() * sizeof( jointMods[ 0 ] ) + AFPoseJointMods.Allocated() + AFPoseJointFrame.Allocated() + AFPoseJoints.Allocated(); return size; } /* ===================== idAnimator::Save archives object for save game file ===================== */ void idAnimator::Save( idSaveGame *savefile ) const { int i; int j; savefile->WriteModelDef( modelDef ); savefile->WriteObject( entity ); savefile->WriteInt( jointMods.Num() ); for( i = 0; i < jointMods.Num(); i++ ) { savefile->WriteInt( jointMods[ i ]->jointnum ); savefile->WriteMat3( jointMods[ i ]->mat ); savefile->WriteVec3( jointMods[ i ]->pos ); savefile->WriteInt( (int&)jointMods[ i ]->transform_pos ); savefile->WriteInt( (int&)jointMods[ i ]->transform_axis ); } savefile->WriteInt( numJoints ); for ( i = 0; i < numJoints; i++ ) { float *data = joints[i].ToFloatPtr(); for ( j = 0; j < 12; j++ ) { savefile->WriteFloat( data[j] ); } } savefile->WriteInt( lastTransformTime ); savefile->WriteBool( stoppedAnimatingUpdate ); savefile->WriteBool( forceUpdate ); savefile->WriteBounds( frameBounds ); savefile->WriteFloat( AFPoseBlendWeight ); savefile->WriteInt( AFPoseJoints.Num() ); for ( i = 0; i < AFPoseJoints.Num(); i++ ) { savefile->WriteInt( AFPoseJoints[i] ); } savefile->WriteInt( AFPoseJointMods.Num() ); for ( i = 0; i < AFPoseJointMods.Num(); i++ ) { savefile->WriteInt( (int&)AFPoseJointMods[i].mod ); savefile->WriteMat3( AFPoseJointMods[i].axis ); savefile->WriteVec3( AFPoseJointMods[i].origin ); } savefile->WriteInt( AFPoseJointFrame.Num() ); for ( i = 0; i < AFPoseJointFrame.Num(); i++ ) { savefile->WriteFloat( AFPoseJointFrame[i].q.x ); savefile->WriteFloat( AFPoseJointFrame[i].q.y ); savefile->WriteFloat( AFPoseJointFrame[i].q.z ); savefile->WriteFloat( AFPoseJointFrame[i].q.w ); savefile->WriteVec3( AFPoseJointFrame[i].t ); } savefile->WriteBounds( AFPoseBounds ); savefile->WriteInt( AFPoseTime ); savefile->WriteBool( removeOriginOffset ); for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++ ) { channels[ i ][ j ].Save( savefile ); } } } /* ===================== idAnimator::Restore unarchives object from save game file ===================== */ void idAnimator::Restore( idRestoreGame *savefile ) { int i; int j; int num; savefile->ReadModelDef( modelDef ); savefile->ReadObject( reinterpret_cast<idClass *&>( entity ) ); savefile->ReadInt( num ); jointMods.SetNum( num ); for( i = 0; i < num; i++ ) { jointMods[ i ] = new jointMod_t; savefile->ReadInt( (int&)jointMods[ i ]->jointnum ); savefile->ReadMat3( jointMods[ i ]->mat ); savefile->ReadVec3( jointMods[ i ]->pos ); savefile->ReadInt( (int&)jointMods[ i ]->transform_pos ); savefile->ReadInt( (int&)jointMods[ i ]->transform_axis ); } savefile->ReadInt( numJoints ); joints = (idJointMat *) Mem_Alloc16( numJoints * sizeof( joints[0] ) ); for ( i = 0; i < numJoints; i++ ) { float *data = joints[i].ToFloatPtr(); for ( j = 0; j < 12; j++ ) { savefile->ReadFloat( data[j] ); } } savefile->ReadInt( lastTransformTime ); savefile->ReadBool( stoppedAnimatingUpdate ); savefile->ReadBool( forceUpdate ); savefile->ReadBounds( frameBounds ); savefile->ReadFloat( AFPoseBlendWeight ); savefile->ReadInt( num ); AFPoseJoints.SetGranularity( 1 ); AFPoseJoints.SetNum( num ); for ( i = 0; i < AFPoseJoints.Num(); i++ ) { savefile->ReadInt( AFPoseJoints[i] ); } savefile->ReadInt( num ); AFPoseJointMods.SetGranularity( 1 ); AFPoseJointMods.SetNum( num ); for ( i = 0; i < AFPoseJointMods.Num(); i++ ) { savefile->ReadInt( (int&)AFPoseJointMods[i].mod ); savefile->ReadMat3( AFPoseJointMods[i].axis ); savefile->ReadVec3( AFPoseJointMods[i].origin ); } savefile->ReadInt( num ); AFPoseJointFrame.SetGranularity( 1 ); AFPoseJointFrame.SetNum( num ); for ( i = 0; i < AFPoseJointFrame.Num(); i++ ) { savefile->ReadFloat( AFPoseJointFrame[i].q.x ); savefile->ReadFloat( AFPoseJointFrame[i].q.y ); savefile->ReadFloat( AFPoseJointFrame[i].q.z ); savefile->ReadFloat( AFPoseJointFrame[i].q.w ); savefile->ReadVec3( AFPoseJointFrame[i].t ); } savefile->ReadBounds( AFPoseBounds ); savefile->ReadInt( AFPoseTime ); savefile->ReadBool( removeOriginOffset ); for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++ ) { channels[ i ][ j ].Restore( savefile, modelDef ); } } } /* ===================== idAnimator::FreeData ===================== */ void idAnimator::FreeData( void ) { int i, j; if ( entity ) { entity->BecomeInactive( TH_ANIMATE ); } for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++ ) { channels[ i ][ j ].Reset( NULL ); } } jointMods.DeleteContents( true ); Mem_Free16( joints ); joints = NULL; numJoints = 0; modelDef = NULL; ForceUpdate(); } /* ===================== idAnimator::PushAnims ===================== */ void idAnimator::PushAnims( int channelNum, int currentTime, int blendTime ) { int i; idAnimBlend *channel; channel = channels[ channelNum ]; if ( !channel[ 0 ].GetWeight( currentTime ) || ( channel[ 0 ].starttime == currentTime ) ) { return; } for( i = ANIM_MaxAnimsPerChannel - 1; i > 0; i-- ) { channel[ i ] = channel[ i - 1 ]; } channel[ 0 ].Reset( modelDef ); channel[ 1 ].Clear( currentTime, blendTime ); ForceUpdate(); } /* ===================== idAnimator::SetModel ===================== */ idRenderModel *idAnimator::SetModel( const char *modelname ) { int i, j; FreeData(); // check if we're just clearing the model if ( !modelname || !*modelname ) { return NULL; } modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, modelname, false ) ); if ( !modelDef ) { return NULL; } idRenderModel *renderModel = modelDef->ModelHandle(); if ( !renderModel ) { modelDef = NULL; return NULL; } // make sure model hasn't been purged modelDef->Touch(); modelDef->SetupJoints( &numJoints, &joints, frameBounds, removeOriginOffset ); modelDef->ModelHandle()->Reset(); // set the modelDef on all channels for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++ ) { channels[ i ][ j ].Reset( modelDef ); } } return modelDef->ModelHandle(); } /* ===================== idAnimator::Size ===================== */ size_t idAnimator::Size( void ) const { return sizeof( *this ) + Allocated(); } /* ===================== idAnimator::SetEntity ===================== */ void idAnimator::SetEntity( idEntity *ent ) { entity = ent; } /* ===================== idAnimator::GetEntity ===================== */ idEntity *idAnimator::GetEntity( void ) const { return entity; } /* ===================== idAnimator::RemoveOriginOffset ===================== */ void idAnimator::RemoveOriginOffset( bool remove ) { removeOriginOffset = remove; } /* ===================== idAnimator::RemoveOrigin ===================== */ bool idAnimator::RemoveOrigin( void ) const { return removeOriginOffset; } /* ===================== idAnimator::GetJointList ===================== */ void idAnimator::GetJointList( const char *jointnames, idList<jointHandle_t> &jointList ) const { if ( modelDef ) { modelDef->GetJointList( jointnames, jointList ); } } /* ===================== idAnimator::NumAnims ===================== */ int idAnimator::NumAnims( void ) const { if ( !modelDef ) { return 0; } return modelDef->NumAnims(); } /* ===================== idAnimator::GetAnim ===================== */ const idAnim *idAnimator::GetAnim( int index ) const { if ( !modelDef ) { return NULL; } return modelDef->GetAnim( index ); } /* ===================== idAnimator::GetAnim ===================== */ int idAnimator::GetAnim( const char *name ) const { if ( !modelDef ) { return 0; } return modelDef->GetAnim( name ); } /* ===================== idAnimator::HasAnim ===================== */ bool idAnimator::HasAnim( const char *name ) const { if ( !modelDef ) { return false; } return modelDef->HasAnim( name ); } /* ===================== idAnimator::NumJoints ===================== */ int idAnimator::NumJoints( void ) const { return numJoints; } /* ===================== idAnimator::ModelHandle ===================== */ idRenderModel *idAnimator::ModelHandle( void ) const { if ( !modelDef ) { return NULL; } return modelDef->ModelHandle(); } /* ===================== idAnimator::ModelDef ===================== */ const idDeclModelDef *idAnimator::ModelDef( void ) const { return modelDef; } /* ===================== idAnimator::CurrentAnim ===================== */ idAnimBlend *idAnimator::CurrentAnim( int channelNum ) { if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::CurrentAnim : channel out of range" ); } return &channels[ channelNum ][ 0 ]; } /* ===================== idAnimator::Clear ===================== */ void idAnimator::Clear( int channelNum, int currentTime, int cleartime ) { int i; idAnimBlend *blend; if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::Clear : channel out of range" ); } blend = channels[ channelNum ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->Clear( currentTime, cleartime ); } ForceUpdate(); } /* ===================== idAnimator::SetFrame ===================== */ void idAnimator::SetFrame( int channelNum, int animNum, int frame, int currentTime, int blendTime ) { if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::SetFrame : channel out of range" ); } if ( !modelDef || !modelDef->GetAnim( animNum ) ) { return; } PushAnims( channelNum, currentTime, blendTime ); channels[ channelNum ][ 0 ].SetFrame( modelDef, animNum, frame, currentTime, blendTime ); if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } } /* ===================== idAnimator::CycleAnim ===================== */ void idAnimator::CycleAnim( int channelNum, int animNum, int currentTime, int blendTime ) { if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::CycleAnim : channel out of range" ); } if ( !modelDef || !modelDef->GetAnim( animNum ) ) { return; } PushAnims( channelNum, currentTime, blendTime ); channels[ channelNum ][ 0 ].CycleAnim( modelDef, animNum, currentTime, blendTime ); if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } } /* ===================== idAnimator::PlayAnim ===================== */ void idAnimator::PlayAnim( int channelNum, int animNum, int currentTime, int blendTime ) { if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::PlayAnim : channel out of range" ); } if ( !modelDef || !modelDef->GetAnim( animNum ) ) { return; } PushAnims( channelNum, currentTime, blendTime ); channels[ channelNum ][ 0 ].PlayAnim( modelDef, animNum, currentTime, blendTime ); if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } } /* ===================== idAnimator::SyncAnimChannels ===================== */ void idAnimator::SyncAnimChannels( int channelNum, int fromChannelNum, int currentTime, int blendTime ) { if ( ( channelNum < 0 ) || ( channelNum >= ANIM_NumAnimChannels ) || ( fromChannelNum < 0 ) || ( fromChannelNum >= ANIM_NumAnimChannels ) ) { gameLocal.Error( "idAnimator::SyncToChannel : channel out of range" ); } idAnimBlend &fromBlend = channels[ fromChannelNum ][ 0 ]; idAnimBlend &toBlend = channels[ channelNum ][ 0 ]; float weight = fromBlend.blendEndValue; if ( ( fromBlend.Anim() != toBlend.Anim() ) || ( fromBlend.GetStartTime() != toBlend.GetStartTime() ) || ( fromBlend.GetEndTime() != toBlend.GetEndTime() ) ) { PushAnims( channelNum, currentTime, blendTime ); toBlend = fromBlend; toBlend.blendStartValue = 0.0f; toBlend.blendEndValue = 0.0f; } toBlend.SetWeight( weight, currentTime - 1, blendTime ); // disable framecommands on the current channel so that commands aren't called twice toBlend.AllowFrameCommands( false ); if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } } /* ===================== idAnimator::SetJointPos ===================== */ void idAnimator::SetJointPos( jointHandle_t jointnum, jointModTransform_t transform_type, const idVec3 &pos ) { int i; jointMod_t *jointMod; if ( !modelDef || !modelDef->ModelHandle() || ( jointnum < 0 ) || ( jointnum >= numJoints ) ) { return; } jointMod = NULL; for( i = 0; i < jointMods.Num(); i++ ) { if ( jointMods[ i ]->jointnum == jointnum ) { jointMod = jointMods[ i ]; break; } else if ( jointMods[ i ]->jointnum > jointnum ) { break; } } if ( !jointMod ) { jointMod = new jointMod_t; jointMod->jointnum = jointnum; jointMod->mat.Identity(); jointMod->transform_axis = JOINTMOD_NONE; jointMods.Insert( jointMod, i ); } jointMod->pos = pos; jointMod->transform_pos = transform_type; if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } ForceUpdate(); } /* ===================== idAnimator::SetJointAxis ===================== */ void idAnimator::SetJointAxis( jointHandle_t jointnum, jointModTransform_t transform_type, const idMat3 &mat ) { int i; jointMod_t *jointMod; if ( !modelDef || !modelDef->ModelHandle() || ( jointnum < 0 ) || ( jointnum >= numJoints ) ) { return; } jointMod = NULL; for( i = 0; i < jointMods.Num(); i++ ) { if ( jointMods[ i ]->jointnum == jointnum ) { jointMod = jointMods[ i ]; break; } else if ( jointMods[ i ]->jointnum > jointnum ) { break; } } if ( !jointMod ) { jointMod = new jointMod_t; jointMod->jointnum = jointnum; jointMod->pos.Zero(); jointMod->transform_pos = JOINTMOD_NONE; jointMods.Insert( jointMod, i ); } jointMod->mat = mat; jointMod->transform_axis = transform_type; if ( entity ) { entity->BecomeActive( TH_ANIMATE ); } ForceUpdate(); } /* ===================== idAnimator::ClearJoint ===================== */ void idAnimator::ClearJoint( jointHandle_t jointnum ) { int i; if ( !modelDef || !modelDef->ModelHandle() || ( jointnum < 0 ) || ( jointnum >= numJoints ) ) { return; } for( i = 0; i < jointMods.Num(); i++ ) { if ( jointMods[ i ]->jointnum == jointnum ) { delete jointMods[ i ]; jointMods.RemoveIndex( i ); ForceUpdate(); break; } else if ( jointMods[ i ]->jointnum > jointnum ) { break; } } } /* ===================== idAnimator::ClearAllJoints ===================== */ void idAnimator::ClearAllJoints( void ) { if ( jointMods.Num() ) { ForceUpdate(); } jointMods.DeleteContents( true ); } /* ===================== idAnimator::ClearAllAnims ===================== */ void idAnimator::ClearAllAnims( int currentTime, int cleartime ) { int i; for( i = 0; i < ANIM_NumAnimChannels; i++ ) { Clear( i, currentTime, cleartime ); } ClearAFPose(); ForceUpdate(); } /* ==================== idAnimator::GetDelta ==================== */ void idAnimator::GetDelta( int fromtime, int totime, idVec3 &delta ) const { int i; const idAnimBlend *blend; float blendWeight; if ( !modelDef || !modelDef->ModelHandle() || ( fromtime == totime ) ) { delta.Zero(); return; } delta.Zero(); blendWeight = 0.0f; blend = channels[ ANIMCHANNEL_ALL ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendDelta( fromtime, totime, delta, blendWeight ); } if ( modelDef->Joints()[ 0 ].channel ) { blend = channels[ modelDef->Joints()[ 0 ].channel ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendDelta( fromtime, totime, delta, blendWeight ); } } } /* ==================== idAnimator::GetDeltaRotation ==================== */ bool idAnimator::GetDeltaRotation( int fromtime, int totime, idMat3 &delta ) const { int i; const idAnimBlend *blend; float blendWeight; idQuat q; if ( !modelDef || !modelDef->ModelHandle() || ( fromtime == totime ) ) { delta.Identity(); return false; } q.Set( 0.0f, 0.0f, 0.0f, 1.0f ); blendWeight = 0.0f; blend = channels[ ANIMCHANNEL_ALL ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendDeltaRotation( fromtime, totime, q, blendWeight ); } if ( modelDef->Joints()[ 0 ].channel ) { blend = channels[ modelDef->Joints()[ 0 ].channel ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendDeltaRotation( fromtime, totime, q, blendWeight ); } } if ( blendWeight > 0.0f ) { delta = q.ToMat3(); return true; } else { delta.Identity(); return false; } } /* ==================== idAnimator::GetOrigin ==================== */ void idAnimator::GetOrigin( int currentTime, idVec3 &pos ) const { int i; const idAnimBlend *blend; float blendWeight; if ( !modelDef || !modelDef->ModelHandle() ) { pos.Zero(); return; } pos.Zero(); blendWeight = 0.0f; blend = channels[ ANIMCHANNEL_ALL ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendOrigin( currentTime, pos, blendWeight, removeOriginOffset ); } if ( modelDef->Joints()[ 0 ].channel ) { blend = channels[ modelDef->Joints()[ 0 ].channel ]; for( i = 0; i < ANIM_MaxAnimsPerChannel; i++, blend++ ) { blend->BlendOrigin( currentTime, pos, blendWeight, removeOriginOffset ); } } pos += modelDef->GetVisualOffset(); } /* ==================== idAnimator::GetBounds ==================== */ bool idAnimator::GetBounds( int currentTime, idBounds &bounds ) { int i, j; const idAnimBlend *blend; int count; if ( !modelDef || !modelDef->ModelHandle() ) { return false; } if ( AFPoseJoints.Num() ) { bounds = AFPoseBounds; count = 1; } else { bounds.Clear(); count = 0; } blend = channels[ 0 ]; for( i = ANIMCHANNEL_ALL; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( blend->AddBounds( currentTime, bounds, removeOriginOffset ) ) { count++; } } } if ( !count ) { if ( !frameBounds.IsCleared() ) { bounds = frameBounds; return true; } else { bounds.Zero(); return false; } } bounds.TranslateSelf( modelDef->GetVisualOffset() ); if ( g_debugBounds.GetBool() ) { if ( bounds[1][0] - bounds[0][0] > 2048 || bounds[1][1] - bounds[0][1] > 2048 ) { if ( entity ) { gameLocal.Warning( "big frameBounds on entity '%s' with model '%s': %f,%f", entity->name.c_str(), modelDef->ModelHandle()->Name(), bounds[1][0] - bounds[0][0], bounds[1][1] - bounds[0][1] ); } else { gameLocal.Warning( "big frameBounds on model '%s': %f,%f", modelDef->ModelHandle()->Name(), bounds[1][0] - bounds[0][0], bounds[1][1] - bounds[0][1] ); } } } frameBounds = bounds; return true; } /* ===================== idAnimator::InitAFPose ===================== */ void idAnimator::InitAFPose( void ) { if ( !modelDef ) { return; } AFPoseJoints.SetNum( modelDef->Joints().Num(), false ); AFPoseJoints.SetNum( 0, false ); AFPoseJointMods.SetNum( modelDef->Joints().Num(), false ); AFPoseJointFrame.SetNum( modelDef->Joints().Num(), false ); } /* ===================== idAnimator::SetAFPoseJointMod ===================== */ void idAnimator::SetAFPoseJointMod( const jointHandle_t jointNum, const AFJointModType_t mod, const idMat3 &axis, const idVec3 &origin ) { AFPoseJointMods[jointNum].mod = mod; AFPoseJointMods[jointNum].axis = axis; AFPoseJointMods[jointNum].origin = origin; int index = idBinSearch_GreaterEqual<int>( AFPoseJoints.Ptr(), AFPoseJoints.Num(), jointNum ); if ( index >= AFPoseJoints.Num() || jointNum != AFPoseJoints[index] ) { AFPoseJoints.Insert( jointNum, index ); } } /* ===================== idAnimator::FinishAFPose ===================== */ void idAnimator::FinishAFPose( int animNum, const idBounds &bounds, const int time ) { int i, j; int numJoints; int parentNum; int jointMod; int jointNum; const int * jointParent; if ( !modelDef ) { return; } const idAnim *anim = modelDef->GetAnim( animNum ); if ( !anim ) { return; } numJoints = modelDef->Joints().Num(); if ( !numJoints ) { return; } idRenderModel *md5 = modelDef->ModelHandle(); const idMD5Anim *md5anim = anim->MD5Anim( 0 ); if ( numJoints != md5anim->NumJoints() ) { gameLocal.Warning( "Model '%s' has different # of joints than anim '%s'", md5->Name(), md5anim->Name() ); return; } idJointQuat *jointFrame = ( idJointQuat * )_alloca16( numJoints * sizeof( *jointFrame ) ); md5anim->GetSingleFrame( 0, jointFrame, modelDef->GetChannelJoints( ANIMCHANNEL_ALL ), modelDef->NumJointsOnChannel( ANIMCHANNEL_ALL ) ); if ( removeOriginOffset ) { #ifdef VELOCITY_MOVE jointFrame[ 0 ].t.x = 0.0f; #else jointFrame[ 0 ].t.Zero(); #endif } idJointMat *joints = ( idJointMat * )_alloca16( numJoints * sizeof( *joints ) ); // convert the joint quaternions to joint matrices SIMDProcessor->ConvertJointQuatsToJointMats( joints, jointFrame, numJoints ); // first joint is always root of entire hierarchy if ( AFPoseJoints.Num() && AFPoseJoints[0] == 0 ) { switch( AFPoseJointMods[0].mod ) { case AF_JOINTMOD_AXIS: { joints[0].SetRotation( AFPoseJointMods[0].axis ); break; } case AF_JOINTMOD_ORIGIN: { joints[0].SetTranslation( AFPoseJointMods[0].origin ); break; } case AF_JOINTMOD_BOTH: { joints[0].SetRotation( AFPoseJointMods[0].axis ); joints[0].SetTranslation( AFPoseJointMods[0].origin ); break; } } j = 1; } else { j = 0; } // pointer to joint info jointParent = modelDef->JointParents(); // transform the child joints for( i = 1; j < AFPoseJoints.Num(); j++, i++ ) { jointMod = AFPoseJoints[j]; // transform any joints preceding the joint modifier SIMDProcessor->TransformJoints( joints, jointParent, i, jointMod - 1 ); i = jointMod; parentNum = jointParent[i]; switch( AFPoseJointMods[jointMod].mod ) { case AF_JOINTMOD_AXIS: { joints[i].SetRotation( AFPoseJointMods[jointMod].axis ); joints[i].SetTranslation( joints[parentNum].ToVec3() + joints[i].ToVec3() * joints[parentNum].ToMat3() ); break; } case AF_JOINTMOD_ORIGIN: { joints[i].SetRotation( joints[i].ToMat3() * joints[parentNum].ToMat3() ); joints[i].SetTranslation( AFPoseJointMods[jointMod].origin ); break; } case AF_JOINTMOD_BOTH: { joints[i].SetRotation( AFPoseJointMods[jointMod].axis ); joints[i].SetTranslation( AFPoseJointMods[jointMod].origin ); break; } } } // transform the rest of the hierarchy SIMDProcessor->TransformJoints( joints, jointParent, i, numJoints - 1 ); // untransform hierarchy SIMDProcessor->UntransformJoints( joints, jointParent, 1, numJoints - 1 ); // convert joint matrices back to joint quaternions SIMDProcessor->ConvertJointMatsToJointQuats( AFPoseJointFrame.Ptr(), joints, numJoints ); // find all modified joints and their parents bool *blendJoints = (bool *) _alloca16( numJoints * sizeof( bool ) ); memset( blendJoints, 0, numJoints * sizeof( bool ) ); // mark all modified joints and their parents for( i = 0; i < AFPoseJoints.Num(); i++ ) { for( jointNum = AFPoseJoints[i]; jointNum != INVALID_JOINT; jointNum = jointParent[jointNum] ) { blendJoints[jointNum] = true; } } // lock all parents of modified joints AFPoseJoints.SetNum( 0, false ); for ( i = 0; i < numJoints; i++ ) { if ( blendJoints[i] ) { AFPoseJoints.Append( i ); } } AFPoseBounds = bounds; AFPoseTime = time; ForceUpdate(); } /* ===================== idAnimator::SetAFPoseBlendWeight ===================== */ void idAnimator::SetAFPoseBlendWeight( float blendWeight ) { AFPoseBlendWeight = blendWeight; } /* ===================== idAnimator::BlendAFPose ===================== */ bool idAnimator::BlendAFPose( idJointQuat *blendFrame ) const { if ( !AFPoseJoints.Num() ) { return false; } SIMDProcessor->BlendJoints( blendFrame, AFPoseJointFrame.Ptr(), AFPoseBlendWeight, AFPoseJoints.Ptr(), AFPoseJoints.Num() ); return true; } /* ===================== idAnimator::ClearAFPose ===================== */ void idAnimator::ClearAFPose( void ) { if ( AFPoseJoints.Num() ) { ForceUpdate(); } AFPoseBlendWeight = 1.0f; AFPoseJoints.SetNum( 0, false ); AFPoseBounds.Clear(); AFPoseTime = 0; } /* ===================== idAnimator::ServiceAnims ===================== */ void idAnimator::ServiceAnims( int fromtime, int totime ) { int i, j; idAnimBlend *blend; if ( !modelDef ) { return; } if ( modelDef->ModelHandle() ) { blend = channels[ 0 ]; for( i = 0; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { blend->CallFrameCommands( entity, fromtime, totime ); } } } if ( !IsAnimating( totime ) ) { stoppedAnimatingUpdate = true; if ( entity ) { entity->BecomeInactive( TH_ANIMATE ); // present one more time with stopped animations so the renderer can properly recreate interactions entity->BecomeActive( TH_UPDATEVISUALS ); } } } /* ===================== idAnimator::IsAnimating ===================== */ bool idAnimator::IsAnimating( int currentTime ) const { int i, j; const idAnimBlend *blend; if ( !modelDef || !modelDef->ModelHandle() ) { return false; } // if animating with an articulated figure if ( AFPoseJoints.Num() && currentTime <= AFPoseTime ) { return true; } blend = channels[ 0 ]; for( i = 0; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( !blend->IsDone( currentTime ) ) { return true; } } } return false; } /* ===================== idAnimator::FrameHasChanged ===================== */ bool idAnimator::FrameHasChanged( int currentTime ) const { int i, j; const idAnimBlend *blend; if ( !modelDef || !modelDef->ModelHandle() ) { return false; } // if animating with an articulated figure if ( AFPoseJoints.Num() && currentTime <= AFPoseTime ) { return true; } blend = channels[ 0 ]; for( i = 0; i < ANIM_NumAnimChannels; i++ ) { for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( blend->FrameHasChanged( currentTime ) ) { return true; } } } if ( forceUpdate && IsAnimating( currentTime ) ) { return true; } return false; } /* ===================== idAnimator::CreateFrame ===================== */ bool idAnimator::CreateFrame( int currentTime, bool force ) { int i, j; int numJoints; int parentNum; bool hasAnim; bool debugInfo; float baseBlend; float blendWeight; const idAnimBlend * blend; const int * jointParent; const jointMod_t * jointMod; const idJointQuat * defaultPose; static idCVar r_showSkel( "r_showSkel", "0", CVAR_RENDERER | CVAR_INTEGER, "", 0, 2, idCmdSystem::ArgCompletion_Integer<0,2> ); if ( gameLocal.inCinematic && gameLocal.skipCinematic ) { return false; } if ( !modelDef || !modelDef->ModelHandle() ) { return false; } if ( !force && !r_showSkel.GetInteger() ) { if ( lastTransformTime == currentTime ) { return false; } if ( lastTransformTime != -1 && !stoppedAnimatingUpdate && !IsAnimating( currentTime ) ) { return false; } } lastTransformTime = currentTime; stoppedAnimatingUpdate = false; if ( entity && ( ( g_debugAnim.GetInteger() == entity->entityNumber ) || ( g_debugAnim.GetInteger() == -2 ) ) ) { debugInfo = true; gameLocal.Printf( "---------------\n%d: entity '%s':\n", gameLocal.time, entity->GetName() ); gameLocal.Printf( "model '%s':\n", modelDef->GetModelName() ); } else { debugInfo = false; } // init the joint buffer if ( AFPoseJoints.Num() ) { // initialize with AF pose anim for the case where there are no other animations and no AF pose joint modifications defaultPose = AFPoseJointFrame.Ptr(); } else { defaultPose = modelDef->GetDefaultPose(); } if ( !defaultPose ) { //gameLocal.Warning( "idAnimator::CreateFrame: no defaultPose on '%s'", modelDef->Name() ); return false; } numJoints = modelDef->Joints().Num(); idJointQuat *jointFrame = ( idJointQuat * )_alloca16( numJoints * sizeof( jointFrame[0] ) ); SIMDProcessor->Memcpy( jointFrame, defaultPose, numJoints * sizeof( jointFrame[0] ) ); hasAnim = false; // blend the all channel baseBlend = 0.0f; blend = channels[ ANIMCHANNEL_ALL ]; for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( blend->BlendAnim( currentTime, ANIMCHANNEL_ALL, numJoints, jointFrame, baseBlend, removeOriginOffset, false, debugInfo ) ) { hasAnim = true; if ( baseBlend >= 1.0f ) { break; } } } // only blend other channels if there's enough space to blend into if ( baseBlend < 1.0f ) { for( i = ANIMCHANNEL_ALL + 1; i < ANIM_NumAnimChannels; i++ ) { if ( !modelDef->NumJointsOnChannel( i ) ) { continue; } if ( i == ANIMCHANNEL_EYELIDS ) { // eyelids blend over any previous anims, so skip it and blend it later continue; } blendWeight = baseBlend; blend = channels[ i ]; for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( blend->BlendAnim( currentTime, i, numJoints, jointFrame, blendWeight, removeOriginOffset, false, debugInfo ) ) { hasAnim = true; if ( blendWeight >= 1.0f ) { // fully blended break; } } } if ( debugInfo && !AFPoseJoints.Num() && !blendWeight ) { gameLocal.Printf( "%d: %s using default pose in model '%s'\n", gameLocal.time, channelNames[ i ], modelDef->GetModelName() ); } } } // blend in the eyelids if ( modelDef->NumJointsOnChannel( ANIMCHANNEL_EYELIDS ) ) { blend = channels[ ANIMCHANNEL_EYELIDS ]; blendWeight = baseBlend; for( j = 0; j < ANIM_MaxAnimsPerChannel; j++, blend++ ) { if ( blend->BlendAnim( currentTime, ANIMCHANNEL_EYELIDS, numJoints, jointFrame, blendWeight, removeOriginOffset, true, debugInfo ) ) { hasAnim = true; if ( blendWeight >= 1.0f ) { // fully blended break; } } } } // blend the articulated figure pose if ( BlendAFPose( jointFrame ) ) { hasAnim = true; } if ( !hasAnim && !jointMods.Num() ) { // no animations were updated return false; } // convert the joint quaternions to rotation matrices SIMDProcessor->ConvertJointQuatsToJointMats( joints, jointFrame, numJoints ); // check if we need to modify the origin if ( jointMods.Num() && ( jointMods[0]->jointnum == 0 ) ) { jointMod = jointMods[0]; switch( jointMod->transform_axis ) { case JOINTMOD_NONE: break; case JOINTMOD_LOCAL: joints[0].SetRotation( jointMod->mat * joints[0].ToMat3() ); break; case JOINTMOD_WORLD: joints[0].SetRotation( joints[0].ToMat3() * jointMod->mat ); break; case JOINTMOD_LOCAL_OVERRIDE: case JOINTMOD_WORLD_OVERRIDE: joints[0].SetRotation( jointMod->mat ); break; } switch( jointMod->transform_pos ) { case JOINTMOD_NONE: break; case JOINTMOD_LOCAL: joints[0].SetTranslation( joints[0].ToVec3() + jointMod->pos ); break; case JOINTMOD_LOCAL_OVERRIDE: case JOINTMOD_WORLD: case JOINTMOD_WORLD_OVERRIDE: joints[0].SetTranslation( jointMod->pos ); break; } j = 1; } else { j = 0; } // add in the model offset joints[0].SetTranslation( joints[0].ToVec3() + modelDef->GetVisualOffset() ); // pointer to joint info jointParent = modelDef->JointParents(); // add in any joint modifications for( i = 1; j < jointMods.Num(); j++, i++ ) { jointMod = jointMods[j]; // transform any joints preceding the joint modifier SIMDProcessor->TransformJoints( joints, jointParent, i, jointMod->jointnum - 1 ); i = jointMod->jointnum; parentNum = jointParent[i]; // modify the axis switch( jointMod->transform_axis ) { case JOINTMOD_NONE: joints[i].SetRotation( joints[i].ToMat3() * joints[ parentNum ].ToMat3() ); break; case JOINTMOD_LOCAL: joints[i].SetRotation( jointMod->mat * ( joints[i].ToMat3() * joints[parentNum].ToMat3() ) ); break; case JOINTMOD_LOCAL_OVERRIDE: joints[i].SetRotation( jointMod->mat * joints[parentNum].ToMat3() ); break; case JOINTMOD_WORLD: joints[i].SetRotation( ( joints[i].ToMat3() * joints[parentNum].ToMat3() ) * jointMod->mat ); break; case JOINTMOD_WORLD_OVERRIDE: joints[i].SetRotation( jointMod->mat ); break; } // modify the position switch( jointMod->transform_pos ) { case JOINTMOD_NONE: joints[i].SetTranslation( joints[parentNum].ToVec3() + joints[i].ToVec3() * joints[parentNum].ToMat3() ); break; case JOINTMOD_LOCAL: joints[i].SetTranslation( joints[parentNum].ToVec3() + ( joints[i].ToVec3() + jointMod->pos ) * joints[parentNum].ToMat3() ); break; case JOINTMOD_LOCAL_OVERRIDE: joints[i].SetTranslation( joints[parentNum].ToVec3() + jointMod->pos * joints[parentNum].ToMat3() ); break; case JOINTMOD_WORLD: joints[i].SetTranslation( joints[parentNum].ToVec3() + joints[i].ToVec3() * joints[parentNum].ToMat3() + jointMod->pos ); break; case JOINTMOD_WORLD_OVERRIDE: joints[i].SetTranslation( jointMod->pos ); break; } } // transform the rest of the hierarchy SIMDProcessor->TransformJoints( joints, jointParent, i, numJoints - 1 ); return true; } /* ===================== idAnimator::ForceUpdate ===================== */ void idAnimator::ForceUpdate( void ) { lastTransformTime = -1; forceUpdate = true; } /* ===================== idAnimator::ClearForceUpdate ===================== */ void idAnimator::ClearForceUpdate( void ) { forceUpdate = false; } /* ===================== idAnimator::GetJointTransform> gamex86.dll!idAnimator::ForceUpdate() Line 4268 C++ ===================== */ bool idAnimator::GetJointTransform( jointHandle_t jointHandle, int currentTime, idVec3 &offset, idMat3 &axis ) { if ( !modelDef || ( jointHandle < 0 ) || ( jointHandle >= modelDef->NumJoints() ) ) { return false; } CreateFrame( currentTime, false ); offset = joints[ jointHandle ].ToVec3(); axis = joints[ jointHandle ].ToMat3(); return true; } /* ===================== idAnimator::GetJointLocalTransform ===================== */ bool idAnimator::GetJointLocalTransform( jointHandle_t jointHandle, int currentTime, idVec3 &offset, idMat3 &axis ) { if ( !modelDef ) { return false; } const idList<jointInfo_t> &modelJoints = modelDef->Joints(); if ( ( jointHandle < 0 ) || ( jointHandle >= modelJoints.Num() ) ) { return false; } // FIXME: overkill CreateFrame( currentTime, false ); if ( jointHandle > 0 ) { idJointMat m = joints[ jointHandle ]; m /= joints[ modelJoints[ jointHandle ].parentNum ]; offset = m.ToVec3(); axis = m.ToMat3(); } else { offset = joints[ jointHandle ].ToVec3(); axis = joints[ jointHandle ].ToMat3(); } return true; } /* ===================== idAnimator::GetJointHandle ===================== */ jointHandle_t idAnimator::GetJointHandle( const char *name ) const { if ( !modelDef || !modelDef->ModelHandle() ) { return INVALID_JOINT; } return modelDef->ModelHandle()->GetJointHandle( name ); } /* ===================== idAnimator::GetJointName ===================== */ const char *idAnimator::GetJointName( jointHandle_t handle ) const { if ( !modelDef || !modelDef->ModelHandle() ) { return ""; } return modelDef->ModelHandle()->GetJointName( handle ); } /* ===================== idAnimator::GetChannelForJoint ===================== */ int idAnimator::GetChannelForJoint( jointHandle_t joint ) const { if ( !modelDef ) { gameLocal.Error( "idAnimator::GetChannelForJoint: NULL model" ); } if ( ( joint < 0 ) || ( joint >= numJoints ) ) { gameLocal.Error( "idAnimator::GetChannelForJoint: invalid joint num (%d)", joint ); } return modelDef->GetJoint( joint )->channel; } /* ===================== idAnimator::GetFirstChild ===================== */ jointHandle_t idAnimator::GetFirstChild( const char *name ) const { return GetFirstChild( GetJointHandle( name ) ); } /* ===================== idAnimator::GetFirstChild ===================== */ jointHandle_t idAnimator::GetFirstChild( jointHandle_t jointnum ) const { int i; int num; const jointInfo_t *joint; if ( !modelDef ) { return INVALID_JOINT; } num = modelDef->NumJoints(); if ( !num ) { return jointnum; } joint = modelDef->GetJoint( 0 ); for( i = 0; i < num; i++, joint++ ) { if ( joint->parentNum == jointnum ) { return ( jointHandle_t )joint->num; } } return jointnum; } /* ===================== idAnimator::GetJoints ===================== */ void idAnimator::GetJoints( int *numJoints, idJointMat **jointsPtr ) { *numJoints = this->numJoints; *jointsPtr = this->joints; } /* ===================== idAnimator::GetAnimFlags ===================== */ const animFlags_t idAnimator::GetAnimFlags( int animNum ) const { animFlags_t result; const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->GetAnimFlags(); } memset( &result, 0, sizeof( result ) ); return result; } /* ===================== idAnimator::NumFrames ===================== */ int idAnimator::NumFrames( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->NumFrames(); } else { return 0; } } /* ===================== idAnimator::NumSyncedAnims ===================== */ int idAnimator::NumSyncedAnims( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->NumAnims(); } else { return 0; } } /* ===================== idAnimator::AnimName ===================== */ const char *idAnimator::AnimName( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->Name(); } else { return ""; } } /* ===================== idAnimator::AnimFullName ===================== */ const char *idAnimator::AnimFullName( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->FullName(); } else { return ""; } } /* ===================== idAnimator::AnimLength ===================== */ int idAnimator::AnimLength( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->Length(); } else { return 0; } } /* ===================== idAnimator::TotalMovementDelta ===================== */ const idVec3 &idAnimator::TotalMovementDelta( int animNum ) const { const idAnim *anim = GetAnim( animNum ); if ( anim ) { return anim->TotalMovementDelta(); } else { return vec3_origin; } } /*********************************************************************** Util functions ***********************************************************************/ /* ===================== ANIM_GetModelDefFromEntityDef ===================== */ const idDeclModelDef *ANIM_GetModelDefFromEntityDef( const idDict *args ) { const idDeclModelDef *modelDef; idStr name = args->GetString( "model" ); modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, name, false ) ); if ( modelDef && modelDef->ModelHandle() ) { return modelDef; } return NULL; } /* ===================== idGameEdit::ANIM_GetModelFromEntityDef ===================== */ idRenderModel *idGameEdit::ANIM_GetModelFromEntityDef( const idDict *args ) { idRenderModel *model; const idDeclModelDef *modelDef; model = NULL; idStr name = args->GetString( "model" ); modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, name, false ) ); if ( modelDef ) { model = modelDef->ModelHandle(); } if ( !model ) { model = renderModelManager->FindModel( name ); } if ( model && model->IsDefaultModel() ) { return NULL; } return model; } /* ===================== idGameEdit::ANIM_GetModelFromEntityDef ===================== */ idRenderModel *idGameEdit::ANIM_GetModelFromEntityDef( const char *classname ) { const idDict *args; args = gameLocal.FindEntityDefDict( classname, false ); if ( !args ) { return NULL; } return ANIM_GetModelFromEntityDef( args ); } /* ===================== idGameEdit::ANIM_GetModelOffsetFromEntityDef ===================== */ const idVec3 &idGameEdit::ANIM_GetModelOffsetFromEntityDef( const char *classname ) { const idDict *args; const idDeclModelDef *modelDef; args = gameLocal.FindEntityDefDict( classname, false ); if ( !args ) { return vec3_origin; } modelDef = ANIM_GetModelDefFromEntityDef( args ); if ( !modelDef ) { return vec3_origin; } return modelDef->GetVisualOffset(); } /* ===================== idGameEdit::ANIM_GetModelFromName ===================== */ idRenderModel *idGameEdit::ANIM_GetModelFromName( const char *modelName ) { const idDeclModelDef *modelDef; idRenderModel *model; model = NULL; modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, modelName, false ) ); if ( modelDef ) { model = modelDef->ModelHandle(); } if ( !model ) { model = renderModelManager->FindModel( modelName ); } return model; } /* ===================== idGameEdit::ANIM_GetAnimFromEntityDef ===================== */ const idMD5Anim *idGameEdit::ANIM_GetAnimFromEntityDef( const char *classname, const char *animname ) { const idDict *args; const idMD5Anim *md5anim; const idAnim *anim; int animNum; const char *modelname; const idDeclModelDef *modelDef; args = gameLocal.FindEntityDefDict( classname, false ); if ( !args ) { return NULL; } md5anim = NULL; modelname = args->GetString( "model" ); modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, modelname, false ) ); if ( modelDef ) { animNum = modelDef->GetAnim( animname ); if ( animNum ) { anim = modelDef->GetAnim( animNum ); if ( anim ) { md5anim = anim->MD5Anim( 0 ); } } } return md5anim; } /* ===================== idGameEdit::ANIM_GetNumAnimsFromEntityDef ===================== */ int idGameEdit::ANIM_GetNumAnimsFromEntityDef( const idDict *args ) { const char *modelname; const idDeclModelDef *modelDef; modelname = args->GetString( "model" ); modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, modelname, false ) ); if ( modelDef ) { return modelDef->NumAnims(); } return 0; } /* ===================== idGameEdit::ANIM_GetAnimNameFromEntityDef ===================== */ const char *idGameEdit::ANIM_GetAnimNameFromEntityDef( const idDict *args, int animNum ) { const char *modelname; const idDeclModelDef *modelDef; modelname = args->GetString( "model" ); modelDef = static_cast<const idDeclModelDef *>( declManager->FindType( DECL_MODELDEF, modelname, false ) ); if ( modelDef ) { const idAnim* anim = modelDef->GetAnim( animNum ); if ( anim ) { return anim->FullName(); } } return ""; } /* ===================== idGameEdit::ANIM_GetAnim ===================== */ const idMD5Anim *idGameEdit::ANIM_GetAnim( const char *fileName ) { return animationLib.GetAnim( fileName ); } /* ===================== idGameEdit::ANIM_GetLength ===================== */ int idGameEdit::ANIM_GetLength( const idMD5Anim *anim ) { if ( !anim ) { return 0; } return anim->Length(); } /* ===================== idGameEdit::ANIM_GetNumFrames ===================== */ int idGameEdit::ANIM_GetNumFrames( const idMD5Anim *anim ) { if ( !anim ) { return 0; } return anim->NumFrames(); } /* ===================== idGameEdit::ANIM_CreateAnimFrame ===================== */ void idGameEdit::ANIM_CreateAnimFrame( const idRenderModel *model, const idMD5Anim *anim, int numJoints, idJointMat *joints, int time, const idVec3 &offset, bool remove_origin_offset ) { int i; frameBlend_t frame; const idMD5Joint *md5joints; int *index; if ( !model || model->IsDefaultModel() || !anim ) { return; } if ( numJoints != model->NumJoints() ) { gameLocal.Error( "ANIM_CreateAnimFrame: different # of joints in renderEntity_t than in model (%s)", model->Name() ); } if ( !model->NumJoints() ) { // FIXME: Print out a warning? return; } if ( !joints ) { gameLocal.Error( "ANIM_CreateAnimFrame: NULL joint frame pointer on model (%s)", model->Name() ); } if ( numJoints != anim->NumJoints() ) { gameLocal.Warning( "Model '%s' has different # of joints than anim '%s'", model->Name(), anim->Name() ); for( i = 0; i < numJoints; i++ ) { joints[i].SetRotation( mat3_identity ); joints[i].SetTranslation( offset ); } return; } // create index for all joints index = ( int * )_alloca16( numJoints * sizeof( int ) ); for ( i = 0; i < numJoints; i++ ) { index[i] = i; } // create the frame anim->ConvertTimeToFrame( time, 1, frame ); idJointQuat *jointFrame = ( idJointQuat * )_alloca16( numJoints * sizeof( *jointFrame ) ); anim->GetInterpolatedFrame( frame, jointFrame, index, numJoints ); // convert joint quaternions to joint matrices SIMDProcessor->ConvertJointQuatsToJointMats( joints, jointFrame, numJoints ); // first joint is always root of entire hierarchy if ( remove_origin_offset ) { joints[0].SetTranslation( offset ); } else { joints[0].SetTranslation( joints[0].ToVec3() + offset ); } // transform the children md5joints = model->GetJoints(); for( i = 1; i < numJoints; i++ ) { joints[i] *= joints[ md5joints[i].parent - md5joints ]; } } /* ===================== idGameEdit::ANIM_CreateMeshForAnim ===================== */ idRenderModel *idGameEdit::ANIM_CreateMeshForAnim( idRenderModel *model, const char *classname, const char *animname, int frame, bool remove_origin_offset ) { renderEntity_t ent; const idDict *args; const char *temp; idRenderModel *newmodel; const idMD5Anim *md5anim; idStr filename; idStr extension; const idAnim *anim; int animNum; idVec3 offset; const idDeclModelDef *modelDef; if ( !model || model->IsDefaultModel() ) { return NULL; } args = gameLocal.FindEntityDefDict( classname, false ); if ( !args ) { return NULL; } memset( &ent, 0, sizeof( ent ) ); ent.bounds.Clear(); ent.suppressSurfaceInViewID = 0; modelDef = ANIM_GetModelDefFromEntityDef( args ); if ( modelDef ) { animNum = modelDef->GetAnim( animname ); if ( !animNum ) { return NULL; } anim = modelDef->GetAnim( animNum ); if ( !anim ) { return NULL; } md5anim = anim->MD5Anim( 0 ); ent.customSkin = modelDef->GetDefaultSkin(); offset = modelDef->GetVisualOffset(); } else { filename = animname; filename.ExtractFileExtension( extension ); if ( !extension.Length() ) { animname = args->GetString( va( "anim %s", animname ) ); } md5anim = animationLib.GetAnim( animname ); offset.Zero(); } if ( !md5anim ) { return NULL; } temp = args->GetString( "skin", "" ); if ( temp[ 0 ] ) { ent.customSkin = declManager->FindSkin( temp ); } ent.numJoints = model->NumJoints(); ent.joints = ( idJointMat * )Mem_Alloc16( ent.numJoints * sizeof( *ent.joints ) ); ANIM_CreateAnimFrame( model, md5anim, ent.numJoints, ent.joints, FRAME2MS( frame ), offset, remove_origin_offset ); newmodel = model->InstantiateDynamicModel( &ent, NULL, NULL ); Mem_Free16( ent.joints ); ent.joints = NULL; return newmodel; }
0
0.832541
1
0.832541
game-dev
MEDIA
0.788019
game-dev
0.910851
1
0.910851
HyDevelop/PicqBotX
1,081
src/test/java/cc/moecraft/test/icq/commands/CommandRecallThis.java
package cc.moecraft.test.icq.commands; import cc.moecraft.icq.command.CommandProperties; import cc.moecraft.icq.command.interfaces.GroupCommand; import cc.moecraft.icq.event.events.message.EventGroupMessage; import cc.moecraft.icq.sender.returndata.ReturnStatus; import cc.moecraft.icq.user.Group; import cc.moecraft.icq.user.GroupUser; import java.util.ArrayList; /** * 此类由 Hykilpikonna 在 2018/07/22 创建! * Created by Hykilpikonna on 2018/07/22! * Github: https://github.com/hykilpikonna * Meow! * * @author Hykilpikonna */ public class CommandRecallThis implements GroupCommand { @Override public String groupMessage(EventGroupMessage event, GroupUser sender, Group group, String command, ArrayList<String> args) { if (sender.isAdmin()) return "不好意思不好意思权限狗打扰了"; if (!event.isAdmin()) return "但我不是管理员"; if (event.delete().getStatus() == ReturnStatus.ok) return "已撤回"; else return "撤回失败!"; } @Override public CommandProperties properties() { return new CommandProperties("recallthis", "撤回这条"); } }
0
0.50908
1
0.50908
game-dev
MEDIA
0.682506
game-dev
0.569949
1
0.569949
Goob-Station/Goob-Station
1,594
Content.Server/EntityEffects/Effects/PlantSpeciesChange.cs
// SPDX-FileCopyrightText: 2024 drakewill-CRL <46307022+drakewill-CRL@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Server.Botany; using Content.Server.Botany.Components; using Content.Shared.EntityEffects; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Serilog; namespace Content.Server.EntityEffects.Effects; /// <summary> /// Changes a plant into one of the species its able to mutate into. /// </summary> public sealed partial class PlantSpeciesChange : EntityEffect { public override void Effect(EntityEffectBaseArgs args) { var prototypeManager = IoCManager.Resolve<IPrototypeManager>(); var plantholder = args.EntityManager.GetComponent<PlantHolderComponent>(args.TargetEntity); if (plantholder.Seed == null) return; if (plantholder.Seed.MutationPrototypes.Count == 0) return; var random = IoCManager.Resolve<IRobustRandom>(); var targetProto = random.Pick(plantholder.Seed.MutationPrototypes); prototypeManager.TryIndex(targetProto, out SeedPrototype? protoSeed); if (protoSeed == null) { Log.Error($"Seed prototype could not be found: {targetProto}!"); return; } plantholder.Seed = plantholder.Seed.SpeciesChange(protoSeed); } protected override string? ReagentEffectGuidebookText(IPrototypeManager prototype, IEntitySystemManager entSys) { return "TODO"; } }
0
0.846293
1
0.846293
game-dev
MEDIA
0.831843
game-dev
0.87483
1
0.87483
SSNTails/SRB2Xmas90Restored
2,196
Code/ST_STUFF.H
// Status bar code. // Does the face/direction indicator animatin. // Does palette indicators as well (red pain/berserk, bright pickup) #ifndef __STSTUFF_H__ #define __STSTUFF_H__ #include "doomtype.h" #include "d_event.h" #include "d_player.h" //software mode : position according to resolution, not scaled //hardware mode : original coords, scaled to current resolution, correct aspect #define ST_Y (rendermode==render_soft ? vid.height - ST_HEIGHT : BASEVIDHEIGHT - ST_HEIGHT) // // STATUS BAR // // Called by main loop. boolean ST_Responder (event_t* ev); // Called by main loop. void ST_Ticker (void); // Called by main loop. void ST_Drawer (boolean fullscreen, boolean refresh); // Called when the console player is spawned on each level. void ST_Start (void); // Called by startup code. void ST_Init (void); // Called by G_Responder() when pressing F12 while viewing a demo. void ST_changeDemoView (void); // Add status bar related commands & vars void ST_AddCommands (void); // need this for SCR_Recalc() coz widgets coords change with resolutions extern boolean st_recalc; // States for status bar code. typedef enum { AutomapState, FirstPersonState } st_stateenum_t; // States for the chat code. typedef enum { StartChatState, WaitDestState, GetChatState } st_chatstateenum_t; boolean ST_Responder(event_t* ev); // face load/unload graphics, called when skin changes void ST_loadFaceGraphics (char *facestr); void ST_unloadFaceGraphics (void); // return if player a is in the same team of the player b boolean ST_SameTeam(player_t *a,player_t *b); // get the frags of the player // only one function for calculation : more simple code int ST_PlayerFrags (int playernum); //-------------------- // status bar overlay //-------------------- extern boolean st_overlay; // sb overlay on or off when fullscreen void ST_overlayDrawer (void); // draw vital info overlay when fullscreen #endif //----------------------------------------------------------------------------- // // $Log:$ // //-----------------------------------------------------------------------------
0
0.855424
1
0.855424
game-dev
MEDIA
0.401118
game-dev
0.574354
1
0.574354
LiXizhi/NPLRuntime
21,521
Client/trunk/externals/bullet3/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp
/* * Copyright (c) 2005 Erwin Coumans http://continuousphysics.com/Bullet/ * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies. * Erwin Coumans makes no representations about the suitability * of this software for any purpose. * It is provided "as is" without express or implied warranty. */ #include "LinearMath/btVector3.h" #include "btRaycastVehicle.h" #include "BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h" #include "BulletDynamics/ConstraintSolver/btJacobianEntry.h" #include "LinearMath/btQuaternion.h" #include "BulletDynamics/Dynamics/btDynamicsWorld.h" #include "btVehicleRaycaster.h" #include "btWheelInfo.h" #include "LinearMath/btMinMax.h" #include "LinearMath/btIDebugDraw.h" #include "BulletDynamics/ConstraintSolver/btContactConstraint.h" #define ROLLING_INFLUENCE_FIX btRigidBody& btActionInterface::getFixedBody() { static btRigidBody s_fixed(0, 0,0); s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.))); return s_fixed; } btRaycastVehicle::btRaycastVehicle(const btVehicleTuning& tuning,btRigidBody* chassis, btVehicleRaycaster* raycaster ) :m_vehicleRaycaster(raycaster), m_pitchControl(btScalar(0.)) { m_chassisBody = chassis; m_indexRightAxis = 0; m_indexUpAxis = 2; m_indexForwardAxis = 1; defaultInit(tuning); } void btRaycastVehicle::defaultInit(const btVehicleTuning& tuning) { (void)tuning; m_currentVehicleSpeedKmHour = btScalar(0.); m_steeringValue = btScalar(0.); } btRaycastVehicle::~btRaycastVehicle() { } // // basically most of the code is general for 2 or 4 wheel vehicles, but some of it needs to be reviewed // btWheelInfo& btRaycastVehicle::addWheel( const btVector3& connectionPointCS, const btVector3& wheelDirectionCS0,const btVector3& wheelAxleCS, btScalar suspensionRestLength, btScalar wheelRadius,const btVehicleTuning& tuning, bool isFrontWheel) { btWheelInfoConstructionInfo ci; ci.m_chassisConnectionCS = connectionPointCS; ci.m_wheelDirectionCS = wheelDirectionCS0; ci.m_wheelAxleCS = wheelAxleCS; ci.m_suspensionRestLength = suspensionRestLength; ci.m_wheelRadius = wheelRadius; ci.m_suspensionStiffness = tuning.m_suspensionStiffness; ci.m_wheelsDampingCompression = tuning.m_suspensionCompression; ci.m_wheelsDampingRelaxation = tuning.m_suspensionDamping; ci.m_frictionSlip = tuning.m_frictionSlip; ci.m_bIsFrontWheel = isFrontWheel; ci.m_maxSuspensionTravelCm = tuning.m_maxSuspensionTravelCm; ci.m_maxSuspensionForce = tuning.m_maxSuspensionForce; m_wheelInfo.push_back( btWheelInfo(ci)); btWheelInfo& wheel = m_wheelInfo[getNumWheels()-1]; updateWheelTransformsWS( wheel , false ); updateWheelTransform(getNumWheels()-1,false); return wheel; } const btTransform& btRaycastVehicle::getWheelTransformWS( int wheelIndex ) const { btAssert(wheelIndex < getNumWheels()); const btWheelInfo& wheel = m_wheelInfo[wheelIndex]; return wheel.m_worldTransform; } void btRaycastVehicle::updateWheelTransform( int wheelIndex , bool interpolatedTransform) { btWheelInfo& wheel = m_wheelInfo[ wheelIndex ]; updateWheelTransformsWS(wheel,interpolatedTransform); btVector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS; const btVector3& right = wheel.m_raycastInfo.m_wheelAxleWS; btVector3 fwd = up.cross(right); fwd = fwd.normalize(); // up = right.cross(fwd); // up.normalize(); //rotate around steering over de wheelAxleWS btScalar steering = wheel.m_steering; btQuaternion steeringOrn(up,steering);//wheel.m_steering); btMatrix3x3 steeringMat(steeringOrn); btQuaternion rotatingOrn(right,-wheel.m_rotation); btMatrix3x3 rotatingMat(rotatingOrn); btMatrix3x3 basis2( right[0],fwd[0],up[0], right[1],fwd[1],up[1], right[2],fwd[2],up[2] ); wheel.m_worldTransform.setBasis(steeringMat * rotatingMat * basis2); wheel.m_worldTransform.setOrigin( wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength ); } void btRaycastVehicle::resetSuspension() { int i; for (i=0;i<m_wheelInfo.size(); i++) { btWheelInfo& wheel = m_wheelInfo[i]; wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength(); wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS; //wheel_info.setContactFriction(btScalar(0.0)); wheel.m_clippedInvContactDotSuspension = btScalar(1.0); } } void btRaycastVehicle::updateWheelTransformsWS(btWheelInfo& wheel , bool interpolatedTransform) { wheel.m_raycastInfo.m_isInContact = false; btTransform chassisTrans = getChassisWorldTransform(); if (interpolatedTransform && (getRigidBody()->getMotionState())) { getRigidBody()->getMotionState()->getWorldTransform(chassisTrans); } wheel.m_raycastInfo.m_hardPointWS = chassisTrans( wheel.m_chassisConnectionPointCS ); wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.getBasis() * wheel.m_wheelDirectionCS ; wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.getBasis() * wheel.m_wheelAxleCS; } btScalar btRaycastVehicle::rayCast(btWheelInfo& wheel) { updateWheelTransformsWS( wheel,false); btScalar depth = -1; btScalar raylen = wheel.getSuspensionRestLength()+wheel.m_wheelsRadius; btVector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen); const btVector3& source = wheel.m_raycastInfo.m_hardPointWS; wheel.m_raycastInfo.m_contactPointWS = source + rayvector; const btVector3& target = wheel.m_raycastInfo.m_contactPointWS; btScalar param = btScalar(0.); btVehicleRaycaster::btVehicleRaycasterResult rayResults; btAssert(m_vehicleRaycaster); void* object = m_vehicleRaycaster->castRay(source,target,rayResults); wheel.m_raycastInfo.m_groundObject = 0; if (object) { param = rayResults.m_distFraction; depth = raylen * rayResults.m_distFraction; wheel.m_raycastInfo.m_contactNormalWS = rayResults.m_hitNormalInWorld; wheel.m_raycastInfo.m_isInContact = true; wheel.m_raycastInfo.m_groundObject = &getFixedBody();///@todo for driving on dynamic/movable objects!; //wheel.m_raycastInfo.m_groundObject = object; btScalar hitDistance = param*raylen; wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelsRadius; //clamp on max suspension travel btScalar minSuspensionLength = wheel.getSuspensionRestLength() - wheel.m_maxSuspensionTravelCm*btScalar(0.01); btScalar maxSuspensionLength = wheel.getSuspensionRestLength()+ wheel.m_maxSuspensionTravelCm*btScalar(0.01); if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength; } if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) { wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength; } wheel.m_raycastInfo.m_contactPointWS = rayResults.m_hitPointInWorld; btScalar denominator= wheel.m_raycastInfo.m_contactNormalWS.dot( wheel.m_raycastInfo.m_wheelDirectionWS ); btVector3 chassis_velocity_at_contactPoint; btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition(); chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos); btScalar projVel = wheel.m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint ); if ( denominator >= btScalar(-0.1)) { wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_clippedInvContactDotSuspension = btScalar(1.0) / btScalar(0.1); } else { btScalar inv = btScalar(-1.) / denominator; wheel.m_suspensionRelativeVelocity = projVel * inv; wheel.m_clippedInvContactDotSuspension = inv; } } else { //put wheel info as in rest position wheel.m_raycastInfo.m_suspensionLength = wheel.getSuspensionRestLength(); wheel.m_suspensionRelativeVelocity = btScalar(0.0); wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS; wheel.m_clippedInvContactDotSuspension = btScalar(1.0); } return depth; } const btTransform& btRaycastVehicle::getChassisWorldTransform() const { /*if (getRigidBody()->getMotionState()) { btTransform chassisWorldTrans; getRigidBody()->getMotionState()->getWorldTransform(chassisWorldTrans); return chassisWorldTrans; } */ return getRigidBody()->getCenterOfMassTransform(); } void btRaycastVehicle::updateVehicle( btScalar step ) { { for (int i=0;i<getNumWheels();i++) { updateWheelTransform(i,false); } } m_currentVehicleSpeedKmHour = btScalar(3.6) * getRigidBody()->getLinearVelocity().length(); const btTransform& chassisTrans = getChassisWorldTransform(); btVector3 forwardW ( chassisTrans.getBasis()[0][m_indexForwardAxis], chassisTrans.getBasis()[1][m_indexForwardAxis], chassisTrans.getBasis()[2][m_indexForwardAxis]); if (forwardW.dot(getRigidBody()->getLinearVelocity()) < btScalar(0.)) { m_currentVehicleSpeedKmHour *= btScalar(-1.); } // // simulate suspension // int i=0; for (i=0;i<m_wheelInfo.size();i++) { //btScalar depth; //depth = rayCast( m_wheelInfo[i]); } updateSuspension(step); for (i=0;i<m_wheelInfo.size();i++) { //apply suspension force btWheelInfo& wheel = m_wheelInfo[i]; btScalar suspensionForce = wheel.m_wheelsSuspensionForce; if (suspensionForce > wheel.m_maxSuspensionForce) { suspensionForce = wheel.m_maxSuspensionForce; } btVector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step; btVector3 relpos = wheel.m_raycastInfo.m_contactPointWS - getRigidBody()->getCenterOfMassPosition(); getRigidBody()->applyImpulse(impulse, relpos); } updateFriction( step); for (i=0;i<m_wheelInfo.size();i++) { btWheelInfo& wheel = m_wheelInfo[i]; btVector3 relpos = wheel.m_raycastInfo.m_hardPointWS - getRigidBody()->getCenterOfMassPosition(); btVector3 vel = getRigidBody()->getVelocityInLocalPoint( relpos ); if (wheel.m_raycastInfo.m_isInContact) { const btTransform& chassisWorldTransform = getChassisWorldTransform(); btVector3 fwd ( chassisWorldTransform.getBasis()[0][m_indexForwardAxis], chassisWorldTransform.getBasis()[1][m_indexForwardAxis], chassisWorldTransform.getBasis()[2][m_indexForwardAxis]); btScalar proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS); fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj; btScalar proj2 = fwd.dot(vel); wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelsRadius); wheel.m_rotation += wheel.m_deltaRotation; } else { wheel.m_rotation += wheel.m_deltaRotation; } wheel.m_deltaRotation *= btScalar(0.99);//damping of rotation when not in contact } } void btRaycastVehicle::setSteeringValue(btScalar steering,int wheel) { btAssert(wheel>=0 && wheel < getNumWheels()); btWheelInfo& wheelInfo = getWheelInfo(wheel); wheelInfo.m_steering = steering; } btScalar btRaycastVehicle::getSteeringValue(int wheel) const { return getWheelInfo(wheel).m_steering; } void btRaycastVehicle::applyEngineForce(btScalar force, int wheel) { btAssert(wheel>=0 && wheel < getNumWheels()); btWheelInfo& wheelInfo = getWheelInfo(wheel); wheelInfo.m_engineForce = force; } const btWheelInfo& btRaycastVehicle::getWheelInfo(int index) const { btAssert((index >= 0) && (index < getNumWheels())); return m_wheelInfo[index]; } btWheelInfo& btRaycastVehicle::getWheelInfo(int index) { btAssert((index >= 0) && (index < getNumWheels())); return m_wheelInfo[index]; } void btRaycastVehicle::setBrake(btScalar brake,int wheelIndex) { btAssert((wheelIndex >= 0) && (wheelIndex < getNumWheels())); getWheelInfo(wheelIndex).m_brake = brake; } void btRaycastVehicle::updateSuspension(btScalar deltaTime) { (void)deltaTime; btScalar chassisMass = btScalar(1.) / m_chassisBody->getInvMass(); for (int w_it=0; w_it<getNumWheels(); w_it++) { btWheelInfo &wheel_info = m_wheelInfo[w_it]; if ( wheel_info.m_raycastInfo.m_isInContact ) { btScalar force; // Spring { btScalar susp_length = wheel_info.getSuspensionRestLength(); btScalar current_length = wheel_info.m_raycastInfo.m_suspensionLength; btScalar length_diff = (susp_length - current_length); force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension; } // Damper { btScalar projected_rel_vel = wheel_info.m_suspensionRelativeVelocity; { btScalar susp_damping; if ( projected_rel_vel < btScalar(0.0) ) { susp_damping = wheel_info.m_wheelsDampingCompression; } else { susp_damping = wheel_info.m_wheelsDampingRelaxation; } force -= susp_damping * projected_rel_vel; } } // RESULT wheel_info.m_wheelsSuspensionForce = force * chassisMass; if (wheel_info.m_wheelsSuspensionForce < btScalar(0.)) { wheel_info.m_wheelsSuspensionForce = btScalar(0.); } } else { wheel_info.m_wheelsSuspensionForce = btScalar(0.0); } } } struct btWheelContactPoint { btRigidBody* m_body0; btRigidBody* m_body1; btVector3 m_frictionPositionWorld; btVector3 m_frictionDirectionWorld; btScalar m_jacDiagABInv; btScalar m_maxImpulse; btWheelContactPoint(btRigidBody* body0,btRigidBody* body1,const btVector3& frictionPosWorld,const btVector3& frictionDirectionWorld, btScalar maxImpulse) :m_body0(body0), m_body1(body1), m_frictionPositionWorld(frictionPosWorld), m_frictionDirectionWorld(frictionDirectionWorld), m_maxImpulse(maxImpulse) { btScalar denom0 = body0->computeImpulseDenominator(frictionPosWorld,frictionDirectionWorld); btScalar denom1 = body1->computeImpulseDenominator(frictionPosWorld,frictionDirectionWorld); btScalar relaxation = 1.f; m_jacDiagABInv = relaxation/(denom0+denom1); } }; btScalar calcRollingFriction(btWheelContactPoint& contactPoint); btScalar calcRollingFriction(btWheelContactPoint& contactPoint) { btScalar j1=0.f; const btVector3& contactPosWorld = contactPoint.m_frictionPositionWorld; btVector3 rel_pos1 = contactPosWorld - contactPoint.m_body0->getCenterOfMassPosition(); btVector3 rel_pos2 = contactPosWorld - contactPoint.m_body1->getCenterOfMassPosition(); btScalar maxImpulse = contactPoint.m_maxImpulse; btVector3 vel1 = contactPoint.m_body0->getVelocityInLocalPoint(rel_pos1); btVector3 vel2 = contactPoint.m_body1->getVelocityInLocalPoint(rel_pos2); btVector3 vel = vel1 - vel2; btScalar vrel = contactPoint.m_frictionDirectionWorld.dot(vel); // calculate j that moves us to zero relative velocity j1 = -vrel * contactPoint.m_jacDiagABInv; btSetMin(j1, maxImpulse); btSetMax(j1, -maxImpulse); return j1; } btScalar sideFrictionStiffness2 = btScalar(1.0); void btRaycastVehicle::updateFriction(btScalar timeStep) { //calculate the impulse, so that the wheels don't move sidewards int numWheel = getNumWheels(); if (!numWheel) return; m_forwardWS.resize(numWheel); m_axle.resize(numWheel); m_forwardImpulse.resize(numWheel); m_sideImpulse.resize(numWheel); int numWheelsOnGround = 0; //collapse all those loops into one! for (int i=0;i<getNumWheels();i++) { btWheelInfo& wheelInfo = m_wheelInfo[i]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; if (groundObject) numWheelsOnGround++; m_sideImpulse[i] = btScalar(0.); m_forwardImpulse[i] = btScalar(0.); } { for (int i=0;i<getNumWheels();i++) { btWheelInfo& wheelInfo = m_wheelInfo[i]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; if (groundObject) { const btTransform& wheelTrans = getWheelTransformWS( i ); btMatrix3x3 wheelBasis0 = wheelTrans.getBasis(); m_axle[i] = btVector3( wheelBasis0[0][m_indexRightAxis], wheelBasis0[1][m_indexRightAxis], wheelBasis0[2][m_indexRightAxis]); const btVector3& surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS; btScalar proj = m_axle[i].dot(surfNormalWS); m_axle[i] -= surfNormalWS * proj; m_axle[i] = m_axle[i].normalize(); m_forwardWS[i] = surfNormalWS.cross(m_axle[i]); m_forwardWS[i].normalize(); resolveSingleBilateral(*m_chassisBody, wheelInfo.m_raycastInfo.m_contactPointWS, *groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, btScalar(0.), m_axle[i],m_sideImpulse[i],timeStep); m_sideImpulse[i] *= sideFrictionStiffness2; } } } btScalar sideFactor = btScalar(1.); btScalar fwdFactor = 0.5; bool sliding = false; { for (int wheel =0;wheel <getNumWheels();wheel++) { btWheelInfo& wheelInfo = m_wheelInfo[wheel]; class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; btScalar rollingFriction = 0.f; if (groundObject) { if (wheelInfo.m_engineForce != 0.f) { rollingFriction = wheelInfo.m_engineForce* timeStep; } else { btScalar defaultRollingFrictionImpulse = 0.f; btScalar maxImpulse = wheelInfo.m_brake ? wheelInfo.m_brake : defaultRollingFrictionImpulse; btWheelContactPoint contactPt(m_chassisBody,groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,m_forwardWS[wheel],maxImpulse); rollingFriction = calcRollingFriction(contactPt); } } //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break) m_forwardImpulse[wheel] = btScalar(0.); m_wheelInfo[wheel].m_skidInfo= btScalar(1.); if (groundObject) { m_wheelInfo[wheel].m_skidInfo= btScalar(1.); btScalar maximp = wheelInfo.m_wheelsSuspensionForce * timeStep * wheelInfo.m_frictionSlip; btScalar maximpSide = maximp; btScalar maximpSquared = maximp * maximpSide; m_forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep; btScalar x = (m_forwardImpulse[wheel] ) * fwdFactor; btScalar y = (m_sideImpulse[wheel] ) * sideFactor; btScalar impulseSquared = (x*x + y*y); if (impulseSquared > maximpSquared) { sliding = true; btScalar factor = maximp / btSqrt(impulseSquared); m_wheelInfo[wheel].m_skidInfo *= factor; } } } } if (sliding) { for (int wheel = 0;wheel < getNumWheels(); wheel++) { if (m_sideImpulse[wheel] != btScalar(0.)) { if (m_wheelInfo[wheel].m_skidInfo< btScalar(1.)) { m_forwardImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; m_sideImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; } } } } // apply the impulses { for (int wheel = 0;wheel<getNumWheels() ; wheel++) { btWheelInfo& wheelInfo = m_wheelInfo[wheel]; btVector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS - m_chassisBody->getCenterOfMassPosition(); if (m_forwardImpulse[wheel] != btScalar(0.)) { m_chassisBody->applyImpulse(m_forwardWS[wheel]*(m_forwardImpulse[wheel]),rel_pos); } if (m_sideImpulse[wheel] != btScalar(0.)) { class btRigidBody* groundObject = (class btRigidBody*) m_wheelInfo[wheel].m_raycastInfo.m_groundObject; btVector3 rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->getCenterOfMassPosition(); btVector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel]; #if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT. btVector3 vChassisWorldUp = getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis); rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f-wheelInfo.m_rollInfluence)); #else rel_pos[m_indexUpAxis] *= wheelInfo.m_rollInfluence; #endif m_chassisBody->applyImpulse(sideImp,rel_pos); //apply friction impulse on the ground groundObject->applyImpulse(-sideImp,rel_pos2); } } } } void btRaycastVehicle::debugDraw(btIDebugDraw* debugDrawer) { for (int v=0;v<this->getNumWheels();v++) { btVector3 wheelColor(0,1,1); if (getWheelInfo(v).m_raycastInfo.m_isInContact) { wheelColor.setValue(0,0,1); } else { wheelColor.setValue(1,0,1); } btVector3 wheelPosWS = getWheelInfo(v).m_worldTransform.getOrigin(); btVector3 axle = btVector3( getWheelInfo(v).m_worldTransform.getBasis()[0][getRightAxis()], getWheelInfo(v).m_worldTransform.getBasis()[1][getRightAxis()], getWheelInfo(v).m_worldTransform.getBasis()[2][getRightAxis()]); //debug wheels (cylinders) debugDrawer->drawLine(wheelPosWS,wheelPosWS+axle,wheelColor); debugDrawer->drawLine(wheelPosWS,getWheelInfo(v).m_raycastInfo.m_contactPointWS,wheelColor); } } void* btDefaultVehicleRaycaster::castRay(const btVector3& from,const btVector3& to, btVehicleRaycasterResult& result) { // RayResultCallback& resultCallback; btCollisionWorld::ClosestRayResultCallback rayCallback(from,to); m_dynamicsWorld->rayTest(from, to, rayCallback); if (rayCallback.hasHit()) { const btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); if (body && body->hasContactResponse()) { result.m_hitPointInWorld = rayCallback.m_hitPointWorld; result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld; result.m_hitNormalInWorld.normalize(); result.m_distFraction = rayCallback.m_closestHitFraction; return (void*)body; } } return 0; }
0
0.85333
1
0.85333
game-dev
MEDIA
0.911273
game-dev
0.979591
1
0.979591
wilhantian/BadGame
4,698
Classes/FinishScene.cpp
#include "FinishScene.h" #include "DynamicData.h" #include "ConfigData.h" #include "GameManager.h" #include "LevelScene.h" #include "GameScene.h" #include "Hero.h" #include "HelloWorldScene.h" #include "TextData.h" #include "JINTools.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //ͳͷ #include "MobClickCpp.h" #endif USING_NS_CC; cocos2d::Scene* FinishScene::createScene(int coin) { Scene* scene = Scene::create(); Layer* layer = FinishScene::create(coin); scene->addChild(layer); return scene; } bool FinishScene::init(int coin) { if (!LayerColor::initWithColor(Color4B(111, 240, 255, 255))) { return false; } //ʾ JINTools::showAdScreen(); setCoin(coin); //setLevel(level); Sprite* down_bk = Sprite::create("UI/FINISH/redBk.png"); down_bk->setAnchorPoint(Vec2(0, 0)); down_bk->setPosition(0, 0-80); this->addChild(down_bk); // Sprite* coin_sprite = Sprite::create("HUD/hud_coins.png"); coin_sprite->setPosition(CD_FLOAT("finish_scence_coin_x"), CD_FLOAT("finish_scence_coin_y")); this->addChild(coin_sprite); LabelAtlas* plabelAtlas = LabelAtlas::create("0123456789", "HUD/hud_num.png", 32, 40, '0'); plabelAtlas->setAnchorPoint(Vec2(0.5, 0.5)); plabelAtlas->setPosition(CD_FLOAT("finish_scence_num_x") + 30, CD_FLOAT("finish_scence_num_y")); this->addChild(plabelAtlas); char c_coin[6]; sprintf(c_coin, "%d", coin); plabelAtlas->setString(c_coin); //next //ʼť Menu* menu = Menu::create(); menu->setAnchorPoint(Vec2(0, 0)); menu->setPosition(0, 0); this->addChild(menu); Size size(960, 640); if (!GameManager::getInstance()->hero->isDie()) // ִ² { // int random = CCRANDOM_0_1() * 2 + 1; //1-3. char tagName[24]; sprintf(tagName, "h%d", random); TTFConfig ttfConfig("fonts/font.ttf", 40); auto bad_game_en = Label::createWithTTF(ttfConfig, TD_STRING(tagName)); bad_game_en->setTextColor(Color4B(251, 96, 104, 255)); bad_game_en->setPosition(960 / 2, TD_FLOAT("finish_text_y")); this->addChild(bad_game_en); //ť MenuItemImage* buttonStart = MenuItemImage::create("UI/GAME/next1.png", "UI/GAME/next2.png", "UI/GAME/next2.png", CC_CALLBACK_1(FinishScene::nextCallBack, this)); buttonStart->setPosition(CD_FLOAT("finish_scence_next_x"), CD_FLOAT("finish_scence_next_y")); menu->addChild(buttonStart); log("--------------------NEXT LEVEL----------------------"); } else { // int random = CCRANDOM_0_1() * 2 + 1; //1-3 char tagName[24]; sprintf(tagName, "s%d", random); TTFConfig ttfConfig("fonts/font.ttf", 40); auto bad_game_en = Label::createWithTTF(ttfConfig, TD_STRING(tagName)); bad_game_en->setTextColor(Color4B(251, 96, 104, 255)); bad_game_en->setPosition(960 / 2, TD_FLOAT("finish_text_y")); this->addChild(bad_game_en); //ť MenuItemImage* buttonStart = MenuItemImage::create("UI/GAME/up_break.png", "UI/GAME/down_break.png", "UI/START_UI_UP_0003__.png", CC_CALLBACK_1(FinishScene::againCallBack, this)); buttonStart->setPosition(CD_FLOAT("finish_scence_next_x"), CD_FLOAT("finish_scence_next_y")); menu->addChild(buttonStart); log("--------------------BACK LEVEL---------------------"); } return true; } void FinishScene::setCoin(int coin) { FinishScene::coin = coin; } // void FinishScene::setLevel(int Level) // { // FinishScene::level = Level; // } void FinishScene::nextCallBack(cocos2d::Ref* ref) { // DynamicData::getInstance()->addCoin(coin); //log("Data Coin ========= %d", DynamicData::getInstance()->getCoin()); //level int lastLevel = DynamicData::getInstance()->getLevel(); //log("lastLevel ========= %d", lastLevel); if (lastLevel <= GameScene::level) //ؿ { DynamicData::getInstance()->setLevel(GameScene::level+1); } GameManager::destroyInstance(); //ͳ- char levelStr[5]; sprintf(levelStr, "level_%d_", GameScene::level); #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) umeng::MobClickCpp::finishLevel(levelStr); #endif if (GameScene::level >= 8) { Scene* scene = TransitionFade::create(1.0f, HelloWorld::createScene(), Color3B(0, 0, 0)); Director::getInstance()->replaceScene(scene); } else { Scene* scene = TransitionFade::create(1.0f, GameScene::createScene(GameScene::level + 1), Color3B(0, 0, 0)); Director::getInstance()->replaceScene(scene); } } void FinishScene::againCallBack(cocos2d::Ref* ref) { // DynamicData::getInstance()->addCoin(coin); GameManager::destroyInstance(); //ͳ-ʧ char levelStr[5]; sprintf(levelStr, "level_%d_", GameScene::level); #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) umeng::MobClickCpp::failLevel(levelStr); #endif //ת Scene* scene = TransitionFade::create(1.0f, GameScene::createScene(GameScene::level), Color3B(0, 0, 0)); Director::getInstance()->replaceScene(scene); }
0
0.785044
1
0.785044
game-dev
MEDIA
0.952623
game-dev
0.910623
1
0.910623
ImLegiitXD/Ambient
10,537
src/main/java/net/minecraft/entity/projectile/EntityFireball.java
package net.minecraft.entity.projectile; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.*; import net.minecraft.world.World; import java.util.List; public abstract class EntityFireball extends Entity { private int xTile = -1; private int yTile = -1; private int zTile = -1; private Block inTile; private boolean inGround; public EntityLivingBase shootingEntity; private int ticksAlive; private int ticksInAir; public double accelerationX; public double accelerationY; public double accelerationZ; public EntityFireball(World worldIn) { super(worldIn); this.setSize(1.0F, 1.0F); } protected void entityInit() { } public boolean isInRangeToRenderDist(double distance) { double d0 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; if (Double.isNaN(d0)) { d0 = 4.0D; } d0 = d0 * 64.0D; return distance < d0 * d0; } public EntityFireball(World worldIn, double x, double y, double z, double accelX, double accelY, double accelZ) { super(worldIn); this.setSize(1.0F, 1.0F); this.setLocationAndAngles(x, y, z, this.rotationYaw, this.rotationPitch); this.setPosition(x, y, z); double d0 = MathHelper.sqrt_double(accelX * accelX + accelY * accelY + accelZ * accelZ); this.accelerationX = accelX / d0 * 0.1D; this.accelerationY = accelY / d0 * 0.1D; this.accelerationZ = accelZ / d0 * 0.1D; } public EntityFireball(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { super(worldIn); this.shootingEntity = shooter; this.setSize(1.0F, 1.0F); this.setLocationAndAngles(shooter.posX, shooter.posY, shooter.posZ, shooter.rotationYaw, shooter.rotationPitch); this.setPosition(this.posX, this.posY, this.posZ); this.motionX = this.motionY = this.motionZ = 0.0D; accelX = accelX + this.rand.nextGaussian() * 0.4D; accelY = accelY + this.rand.nextGaussian() * 0.4D; accelZ = accelZ + this.rand.nextGaussian() * 0.4D; double d0 = MathHelper.sqrt_double(accelX * accelX + accelY * accelY + accelZ * accelZ); this.accelerationX = accelX / d0 * 0.1D; this.accelerationY = accelY / d0 * 0.1D; this.accelerationZ = accelZ / d0 * 0.1D; } public void onUpdate() { if (this.worldObj.isRemote || (this.shootingEntity == null || !this.shootingEntity.isDead) && this.worldObj.isBlockLoaded(new BlockPos(this))) { super.onUpdate(); this.setFire(1); if (this.inGround) { if (this.worldObj.getBlockState(new BlockPos(this.xTile, this.yTile, this.zTile)).getBlock() == this.inTile) { ++this.ticksAlive; if (this.ticksAlive == 600) { this.setDead(); } return; } this.inGround = false; this.motionX *= this.rand.nextFloat() * 0.2F; this.motionY *= this.rand.nextFloat() * 0.2F; this.motionZ *= this.rand.nextFloat() * 0.2F; this.ticksAlive = 0; this.ticksInAir = 0; } else { ++this.ticksInAir; } Vec3 vec3 = new Vec3(this.posX, this.posY, this.posZ); Vec3 vec31 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); MovingObjectPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, vec31); vec3 = new Vec3(this.posX, this.posY, this.posZ); vec31 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); if (movingobjectposition != null) { vec31 = new Vec3(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord); } Entity entity = null; List<Entity> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); double d0 = 0.0D; for (Entity entity1 : list) { if (entity1.canBeCollidedWith() && (!entity1.isEntityEqual(this.shootingEntity) || this.ticksInAir >= 25)) { float f = 0.3F; AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand(f, f, f); MovingObjectPosition movingobjectposition1 = axisalignedbb.calculateIntercept(vec3, vec31); if (movingobjectposition1 != null) { double d1 = vec3.squareDistanceTo(movingobjectposition1.hitVec); if (d1 < d0 || d0 == 0.0D) { entity = entity1; d0 = d1; } } } } if (entity != null) { movingobjectposition = new MovingObjectPosition(entity); } if (movingobjectposition != null) { this.onImpact(movingobjectposition); } this.posX += this.motionX; this.posY += this.motionY; this.posZ += this.motionZ; float f1 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); this.rotationYaw = (float) (MathHelper.atan2(this.motionZ, this.motionX) * 180.0D / Math.PI) + 90.0F; for (this.rotationPitch = (float) (MathHelper.atan2(f1, this.motionY) * 180.0D / Math.PI) - 90.0F; this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F) { } while (this.rotationPitch - this.prevRotationPitch >= 180.0F) { this.prevRotationPitch += 360.0F; } while (this.rotationYaw - this.prevRotationYaw < -180.0F) { this.prevRotationYaw -= 360.0F; } while (this.rotationYaw - this.prevRotationYaw >= 180.0F) { this.prevRotationYaw += 360.0F; } this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F; this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F; float f2 = this.getMotionFactor(); if (this.isInWater()) { for (int j = 0; j < 4; ++j) { float f3 = 0.25F; this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX - this.motionX * (double) f3, this.posY - this.motionY * (double) f3, this.posZ - this.motionZ * (double) f3, this.motionX, this.motionY, this.motionZ); } f2 = 0.8F; } this.motionX += this.accelerationX; this.motionY += this.accelerationY; this.motionZ += this.accelerationZ; this.motionX *= f2; this.motionY *= f2; this.motionZ *= f2; this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY + 0.5D, this.posZ, 0.0D, 0.0D, 0.0D); this.setPosition(this.posX, this.posY, this.posZ); } else { this.setDead(); } } protected float getMotionFactor() { return 0.95F; } protected abstract void onImpact(MovingObjectPosition movingObject); public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("xTile", (short) this.xTile); tagCompound.setShort("yTile", (short) this.yTile); tagCompound.setShort("zTile", (short) this.zTile); ResourceLocation resourcelocation = Block.blockRegistry.getNameForObject(this.inTile); tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); tagCompound.setTag("direction", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); } public void readEntityFromNBT(NBTTagCompound tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); if (tagCompund.hasKey("inTile", 8)) { this.inTile = Block.getBlockFromName(tagCompund.getString("inTile")); } else { this.inTile = Block.getBlockById(tagCompund.getByte("inTile") & 255); } this.inGround = tagCompund.getByte("inGround") == 1; if (tagCompund.hasKey("direction", 9)) { NBTTagList nbttaglist = tagCompund.getTagList("direction", 6); this.motionX = nbttaglist.getDoubleAt(0); this.motionY = nbttaglist.getDoubleAt(1); this.motionZ = nbttaglist.getDoubleAt(2); } else { this.setDead(); } } public boolean canBeCollidedWith() { return true; } public float getCollisionBorderSize() { return 1.0F; } public boolean attackEntityFrom(DamageSource source, float amount) { if (this.isEntityInvulnerable(source)) { return false; } else { this.setBeenAttacked(); if (source.getEntity() != null) { Vec3 vec3 = source.getEntity().getLookVec(); if (vec3 != null) { this.motionX = vec3.xCoord; this.motionY = vec3.yCoord; this.motionZ = vec3.zCoord; this.accelerationX = this.motionX * 0.1D; this.accelerationY = this.motionY * 0.1D; this.accelerationZ = this.motionZ * 0.1D; } if (source.getEntity() instanceof EntityLivingBase) { this.shootingEntity = (EntityLivingBase) source.getEntity(); } return true; } else { return false; } } } public float getBrightness(float partialTicks) { return 1.0F; } public int getBrightnessForRender(float partialTicks) { return 15728880; } }
0
0.831702
1
0.831702
game-dev
MEDIA
0.81189
game-dev
0.965523
1
0.965523
ssquadteam/ApiaryMC
6,964
patches/server/0045-Leaf-Optimize-check-nearby-fire-or-lava-on-entity-mo.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: AltronMaxX <max06112004@gmail.com> Date: Tue, 20 Aug 2024 17:25:30 +0400 Subject: [PATCH] Leaf: Optimize check nearby fire or lava on entity move diff --git a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java index 5c3e7f346271c21dbff8cd9308f91fe4e2024aed..49ab0ca06f19cf2f85862e4c1c22f5e36587ba8c 100644 --- a/src/main/java/net/minecraft/world/entity/Entity.java +++ b/src/main/java/net/minecraft/world/entity/Entity.java @@ -1312,9 +1312,12 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess float f = this.getBlockSpeedFactor(); this.setDeltaMovement(this.getDeltaMovement().multiply((double) f, 1.0D, (double) f)); - if (this.level().getBlockStatesIfLoaded(this.getBoundingBox().deflate(1.0E-6D)).noneMatch((iblockdata2) -> { - return iblockdata2.is(BlockTags.FIRE) || iblockdata2.is(Blocks.LAVA); - })) { + // Leaf start - Optimize check nearby fire or lava on entity move + if (nearByBlockStateNoneMatch( + this.level().getBlockStatesListIfLoaded(this.getBoundingBox().deflate(1.0E-6D), new java.util.ArrayList<>()), + iblockdata2 -> iblockdata2.is(BlockTags.FIRE) || iblockdata2.is(Blocks.LAVA) + )) { + // Leaf end - Optimize check nearby fire or lava on entity move if (this.remainingFireTicks <= 0) { this.setRemainingFireTicks(-this.getFireImmuneTicks()); } @@ -1340,6 +1343,20 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess // Paper end - detailed watchdog information } + // Leaf start - Optimize check nearby fire or lava on entity move + private boolean nearByBlockStateNoneMatch(java.util.List<BlockState> into, Predicate<BlockState> predicate) { + if (into.isEmpty()) return true; + + for (BlockState iblockdata : into) { + if (predicate.test(iblockdata)) { + return false; + } + } + + return true; + } + // Leaf end - Optimize check nearby fire or lava on entity move + private boolean isStateClimbable(BlockState state) { return state.is(BlockTags.CLIMBABLE) || state.is(Blocks.POWDER_SNOW); } diff --git a/src/main/java/net/minecraft/world/entity/Entity.java.rej b/src/main/java/net/minecraft/world/entity/Entity.java.rej new file mode 100644 index 0000000000000000000000000000000000000000..eea763eab872b794fc1080d4434c67a5ff7a776a --- /dev/null +++ b/src/main/java/net/minecraft/world/entity/Entity.java.rej @@ -0,0 +1,17 @@ +diff a/src/main/java/net/minecraft/world/entity/Entity.java b/src/main/java/net/minecraft/world/entity/Entity.java (rejected hunks) +@@ -1337,9 +1337,12 @@ public abstract class Entity implements SyncedDataHolder, Nameable, EntityAccess + } + } + // Gale end - skip negligible planar movement multiplication +- if (this.level().getBlockStatesIfLoaded(this.getBoundingBox().deflate(1.0E-6D)).noneMatch((iblockdata2) -> { +- return iblockdata2.is(BlockTags.FIRE) || iblockdata2.is(Blocks.LAVA); +- })) { ++ // Leaf start - Optimize check nearby fire or lava on entity move ++ if (nearByBlockStateNoneMatch( ++ this.level().getBlockStatesListIfLoaded(this.getBoundingBox().deflate(1.0E-6D), new java.util.ArrayList<>()), ++ iblockdata2 -> iblockdata2.is(BlockTags.FIRE) || iblockdata2.is(Blocks.LAVA) ++ )) { ++ // Leaf end - Optimize check nearby fire or lava on entity move + if (this.remainingFireTicks <= 0) { + this.setRemainingFireTicks(-this.getFireImmuneTicks()); + } diff --git a/src/main/java/net/minecraft/world/level/BlockGetter.java b/src/main/java/net/minecraft/world/level/BlockGetter.java index 0fa131a6c98adb498fc8d534e0e39647e80c6923..b2c9a14c22eade293ff4fee71663001ff0701744 100644 --- a/src/main/java/net/minecraft/world/level/BlockGetter.java +++ b/src/main/java/net/minecraft/world/level/BlockGetter.java @@ -55,6 +55,24 @@ public interface BlockGetter extends LevelHeightAccessor { return BlockPos.betweenClosedStream(box).map(this::getBlockState); } + // Leaf start - Optimize check nearby fire or lava on entity move + public default java.util.List<BlockState> getBlockStatesList(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, java.util.List<BlockState> into) { + int rangeX = maxX - minX + 1; + int rangeY = maxY - minY + 1; + int rangeZ = maxZ - minZ + 1; + + for (int x = 0; x < rangeX; x++) { + for (int y = 0; y < rangeY; y++) { + for (int z = 0; z < rangeZ; z++) { + into.add(getBlockState(new BlockPos(minX + x, minY + y, minZ + z))); + } + } + } + + return into; + } + // Leaf end - Optimize check nearby fire or lava on entity move + default BlockHitResult isBlockInLine(ClipBlockStateContext context) { return (BlockHitResult) BlockGetter.traverseBlocks(context.getFrom(), context.getTo(), context, (clipblockstatecontext1, blockposition) -> { BlockState iblockdata = this.getBlockState(blockposition); diff --git a/src/main/java/net/minecraft/world/level/LevelReader.java b/src/main/java/net/minecraft/world/level/LevelReader.java index 345090afeab4f6396244c50bdbe8320887e15d7e..2a94d773890ae2170908c8a33166df2845726d6b 100644 --- a/src/main/java/net/minecraft/world/level/LevelReader.java +++ b/src/main/java/net/minecraft/world/level/LevelReader.java @@ -63,6 +63,18 @@ public interface LevelReader extends ca.spottedleaf.moonrise.patches.chunk_syste return this.hasChunksAt(i, k, m, j, l, n) ? this.getBlockStates(box) : Stream.empty(); } + // Leaf start - Optimize check nearby fire or lava on entity move + default java.util.List<BlockState> getBlockStatesListIfLoaded(AABB box, java.util.List<BlockState> into) { + int i = Mth.floor(box.minX); + int j = Mth.floor(box.maxX); + int k = Mth.floor(box.minY); + int l = Mth.floor(box.maxY); + int m = Mth.floor(box.minZ); + int n = Mth.floor(box.maxZ); + return this.hasChunksAt(i, k, m, j, l, n) ? this.getBlockStatesList(i, k, m, j, l, n , into) : into; + } + // Leaf end - Optimize check nearby fire or lava on entity move + @Override default int getBlockTint(BlockPos pos, ColorResolver colorResolver) { return colorResolver.getColor(this.getBiome(pos).value(), (double)pos.getX(), (double)pos.getZ());
0
0.504788
1
0.504788
game-dev
MEDIA
0.959401
game-dev
0.786765
1
0.786765
emilyploszaj/emi
2,053
xplat/src/main/java/dev/emi/emi/screen/widget/ResolutionButtonWidget.java
package dev.emi.emi.screen.widget; import java.util.List; import java.util.function.Supplier; import dev.emi.emi.EmiPort; import dev.emi.emi.EmiRenderHelper; import dev.emi.emi.api.render.EmiTexture; import dev.emi.emi.api.stack.EmiIngredient; import dev.emi.emi.api.widget.SlotWidget; import dev.emi.emi.api.widget.Widget; import dev.emi.emi.bom.BoM; import dev.emi.emi.runtime.EmiDrawContext; import dev.emi.emi.runtime.EmiHistory; import dev.emi.emi.widget.RecipeDefaultButtonWidget; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.widget.ButtonWidget; public class ResolutionButtonWidget extends ButtonWidget { public Supplier<Widget> hoveredWidget; public EmiIngredient stack; public ResolutionButtonWidget(int x, int y, int width, int height, EmiIngredient stack, Supplier<Widget> hoveredWidget) { super(x, y, width, height, EmiPort.literal(""), button -> { BoM.tree.addResolution(stack, null); EmiHistory.pop(); }, s -> s.get()); this.stack = stack; this.hoveredWidget = hoveredWidget; } @Override public void renderWidget(DrawContext raw, int mouseX, int mouseY, float delta) { EmiDrawContext context = EmiDrawContext.wrap(raw); int u = 0; if (this.isHovered()) { u = 18; } else { Widget widget = hoveredWidget.get(); if ((widget instanceof SlotWidget slot && slot.getRecipe() != null) || widget instanceof RecipeDefaultButtonWidget) { u = 36; } } EmiTexture.SLOT.render(context.raw(), x, y, delta); context.drawTexture(EmiRenderHelper.WIDGETS, x, y, u, 128, width, height); if (this.isHovered()) { MinecraftClient client = MinecraftClient.getInstance(); raw.drawTooltip(client.textRenderer, List.of( EmiPort.translatable("tooltip.emi.resolution"), EmiPort.translatable("tooltip.emi.select_resolution"), EmiPort.translatable("tooltip.emi.default_resolution"), EmiPort.translatable("tooltip.emi.clear_resolution") ), mouseX, mouseY); } stack.render(raw, x + 1, y + 1, delta); } }
0
0.615792
1
0.615792
game-dev
MEDIA
0.33572
game-dev
0.69099
1
0.69099
splhack/Hello-LWF-Cocos2d-x
2,578
cocos2d/external/chipmunk/include/chipmunk/constraints/cpDampedSpring.h
/* Copyright (c) 2007 Scott Lembcke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /// @defgroup cpDampedSpring cpDampedSpring /// @{ typedef struct cpDampedSpring cpDampedSpring; typedef cpFloat (*cpDampedSpringForceFunc)(cpConstraint *spring, cpFloat dist); const cpConstraintClass *cpDampedSpringGetClass(void); /// @private struct cpDampedSpring { cpConstraint constraint; cpVect anchr1, anchr2; cpFloat restLength; cpFloat stiffness; cpFloat damping; cpDampedSpringForceFunc springForceFunc; cpFloat target_vrn; cpFloat v_coef; cpVect r1, r2; cpFloat nMass; cpVect n; cpFloat jAcc; }; /// Allocate a damped spring. cpDampedSpring* cpDampedSpringAlloc(void); /// Initialize a damped spring. cpDampedSpring* cpDampedSpringInit(cpDampedSpring *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping); /// Allocate and initialize a damped spring. cpConstraint* cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping); CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr1, Anchr1) CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr2, Anchr2) CP_DefineConstraintProperty(cpDampedSpring, cpFloat, restLength, RestLength) CP_DefineConstraintProperty(cpDampedSpring, cpFloat, stiffness, Stiffness) CP_DefineConstraintProperty(cpDampedSpring, cpFloat, damping, Damping) CP_DefineConstraintProperty(cpDampedSpring, cpDampedSpringForceFunc, springForceFunc, SpringForceFunc) /// @}
0
0.655975
1
0.655975
game-dev
MEDIA
0.662573
game-dev
0.634006
1
0.634006
pw32x/Downland_C
1,501
game_8bit/game_data.h
#ifndef GAME_TYPES #define GAME_TYPES #include "base_types.h" #include "base_defines.h" #include "door_types.h" #include "drops_types.h" #include "rooms/rooms.h" #include "resource_types.h" #include "pickup_types.h" #include "string_utils.h" #include "ball.h" #include "bird.h" #include "player.h" #define NUM_PLAYERS 2 #define PLAYER_ONE 0 #define PLAYER_TWO 1 // contains the global state of the game extern dl_u8* gameData_cleanBackground; // the game background without UI or objects. Used for terrain collision detection. // objects extern PlayerData gameData_playerData[NUM_PLAYERS]; // there's no distinct player one or player two // the pointers swap every time a player dies. extern PlayerData* gameData_currentPlayerData; extern PlayerData* gameData_otherPlayerData; extern dl_u8 gameData_numPlayers; extern const Room* gameData_currentRoom; // used for screen transitions extern dl_u8 gameData_transitionRoomNumber; extern dl_u16 gameData_transitionInitialDelay; extern dl_u8 gameData_transitionCurrentLine; extern dl_u8 gameData_transitionFrameDelay; // strings. Number of expected characters + 0xff ending value extern dl_u8 gameData_string_roomNumber[ROOM_NUMBER_STRING_SIZE]; extern dl_u8 gameData_string_timer[TIMER_STRING_SIZE]; // max timer is 65535 extern dl_u8 gameData_string_highScore[SCORE_STRING_SIZE]; extern dl_u32 gameData_highScore; extern dl_u8 gameData_paused; extern RoomPickups gameData_pickups; extern dl_u8 gameData_doorStateData[DOOR_TOTAL_COUNT]; #endif
0
0.57195
1
0.57195
game-dev
MEDIA
0.852339
game-dev
0.628459
1
0.628459
horatio-sans-serif/pygameui
10,726
pygameui/view.py
import pygame import render import theme import callback import resource import focus import kvc class View(object): """A rectangular portion of the window. Views may have zero or more child views contained within it. Signals on_mouse_down(view, button, point) on_mouse_up(view, button, point) on_mouse_motion(view, point) on_mouse_drag(view, point, delta) on_key_down(view, key, code) on_key_up(view, key) on_parented(view) on_orphaned(view) (from parent view) on_focused(view) on_blurred(view) on_selected(view) on_enabled(view) on_disabled(view) on_state_changed(view) All mouse points passed to event methods and to slots are in local view coordinates. Use `to_parent` and `to_window` to convert. """ def __init__(self, frame=None): self.frame = frame self.parent = None self.children = [] # back->front self._state = 'normal' self._enabled = True self.hidden = False self.draggable = False self.shadow_image = None self.on_focused = callback.Signal() self.on_blurred = callback.Signal() self.on_selected = callback.Signal() self.on_enabled = callback.Signal() self.on_disabled = callback.Signal() self.on_state_changed = callback.Signal() self.on_mouse_up = callback.Signal() self.on_mouse_down = callback.Signal() self.on_mouse_motion = callback.Signal() self.on_mouse_drag = callback.Signal() self.on_key_down = callback.Signal() self.on_key_up = callback.Signal() self.on_parented = callback.Signal() self.on_orphaned = callback.Signal() def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame.Surface( shadowed_frame_size, pygame.SRCALPHA, 32) shadow_image = resource.get_image('shadow') self.shadow_image = resource.scale_image(shadow_image, shadowed_frame_size) else: self.surface = pygame.Surface(self.frame.size, pygame.SRCALPHA, 32) self.shadow_image = None def size_to_fit(self): rect = self.frame for child in self.children: rect = rect.union(child.frame) self.frame = rect self.layout() def update(self, dt): for child in self.children: child.update(dt) def to_parent(self, point): return (point[0] + self.frame.topleft[0], point[1] + self.frame.topleft[1]) def from_parent(self, point): return (point[0] - self.frame.topleft[0], point[1] - self.frame.topleft[1]) def from_window(self, point): curr = self ancestors = [curr] while curr.parent: ancestors.append(curr.parent) curr = curr.parent for a in reversed(ancestors): point = a.from_parent(point) return point def to_window(self, point): curr = self while curr: point = curr.to_parent(point) curr = curr.parent return point def mouse_up(self, button, point): self.on_mouse_up(self, button, point) def mouse_down(self, button, point): self.on_mouse_down(self, button, point) def mouse_motion(self, point): self.on_mouse_motion(self, point) # only called on drag event if .draggable is True def mouse_drag(self, point, delta): self.on_mouse_drag(self, point, delta) self.frame.topleft = (self.frame.topleft[0] + delta[0], self.frame.topleft[1] + delta[1]) if self.parent: self.parent._child_dragged(self) def key_down(self, key, code): self.on_key_down(self, key, code) def key_up(self, key): self.on_key_up(self, key) @property def state(self): """The state of the view. Potential values are 'normal', 'focused', 'selected', 'disabled'. """ return self._state @state.setter def state(self, new_state): if self._state != new_state: self._state = new_state self.stylize() self.on_state_changed() def focus(self): focus.set(self) def has_focus(self): return focus.view == self def focused(self): self.state = 'focused' self.on_focused() def blurred(self): self.state = 'normal' self.on_blurred() def selected(self): self.state = 'selected' self.on_selected() @property def enabled(self): return self._enabled @enabled.setter def enabled(self, yesno): if self._enabled != yesno: self._enabled = yesno if yesno: self.enabled() else: self.disabled() def enabled(self): self.state = 'normal' self.on_enabled() def disabled(self): self.state = 'disabled' self.on_disabled() def stylize(self): """Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled. """ # do children first in case parent needs to override their style for child in self.children: child.stylize() style = theme.current.get_dict(self) preserve_child = False try: preserve_child = getattr(theme.current, 'preserve_child') except: preserve_child = False for key, val in style.iteritems(): kvc.set_value_for_keypath(self, key, val, preserve_child) self.layout() def draw(self): """Do not call directly.""" if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children: if not child.hidden: child.draw() topleft = child.frame.topleft if child.shadowed: shadow_size = theme.current.shadow_size shadow_topleft = (topleft[0] - shadow_size // 2, topleft[1] - shadow_size // 2) self.surface.blit(child.shadow_image, shadow_topleft) self.surface.blit(child.surface, topleft) if child.border_color and child.border_widths is not None: if (type(child.border_widths) is int and child.border_widths > 0): pygame.draw.rect(self.surface, child.border_color, child.frame, child.border_widths) else: tw, lw, bw, rw = child.get_border_widths() tl = (child.frame.left, child.frame.top) tr = (child.frame.right - 1, child.frame.top) bl = (child.frame.left, child.frame.bottom - 1) br = (child.frame.right - 1, child.frame.bottom - 1) if tw > 0: pygame.draw.line(self.surface, child.border_color, tl, tr, tw) if lw > 0: pygame.draw.line(self.surface, child.border_color, tl, bl, lw) if bw > 0: pygame.draw.line(self.surface, child.border_color, bl, br, bw) if rw > 0: pygame.draw.line(self.surface, child.border_color, tr, br, rw) return True def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths def hit(self, pt): """Find the view (self, child, or None) under the point `pt`.""" if self.hidden or not self._enabled: return None if not self.frame.collidepoint(pt): return None local_pt = (pt[0] - self.frame.topleft[0], pt[1] - self.frame.topleft[1]) for child in reversed(self.children): # front to back hit_view = child.hit(local_pt) if hit_view is not None: return hit_view return self def center(self): if self.parent is not None: self.frame.center = (self.parent.frame.w // 2, self.parent.frame.h // 2) def add_child(self, child): assert child is not None self.rm_child(child) self.children.append(child) child.parent = self child.parented() import scene if scene.current is not None: child.stylize() def rm_child(self, child): for index, ch in enumerate(self.children): if ch == child: ch.orphaned() del self.children[index] break def rm(self): if self.parent: self.parent.rm_child(self) def parented(self): self.on_parented() def orphaned(self): self.on_orphaned() def iter_ancestors(self): curr = self while curr.parent: yield curr.parent curr = curr.parent def iter_children(self): for child in self.children: yield child def bring_to_front(self): """TODO: explain depth sorting""" if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[-1], ch[index] = ch[index], ch[-1] def move_to_back(self): if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[0], ch[index] = ch[index], ch[0]
0
0.84197
1
0.84197
game-dev
MEDIA
0.645204
game-dev,desktop-app
0.966749
1
0.966749
pret/pokeheartgold
4,137
asm/overlay_80_022384D8.s
.include "asm/macros.inc" .include "overlay_80_022384D8.inc" .include "global.inc" .text thumb_func_start ov80_022384D8 ov80_022384D8: ; 0x022384D8 push {r3, r4, r5, lr} add r5, r0, #0 mov r0, #0x65 mov r1, #8 bl Heap_Alloc mov r1, #0 mov r2, #8 add r4, r0, #0 bl MI_CpuFill8 add r0, r5, #0 bl ov80_022384FC str r0, [r4, #4] add r0, r4, #0 pop {r3, r4, r5, pc} .balign 4, 0 thumb_func_end ov80_022384D8 thumb_func_start ov80_022384FC ov80_022384FC: ; 0x022384FC push {r3, r4, r5, lr} add r5, r0, #0 mov r0, #0x65 mov r1, #0xc bl Heap_Alloc add r4, r0, #0 mov r1, #0 mov r2, #0xc bl MI_CpuFill8 str r5, [r4, #4] mov r0, #0 strh r0, [r4, #8] ldr r0, _02238528 ; =ov80_02238530 ldr r2, _0223852C ; =0x0001368C add r1, r4, #0 bl SysTask_CreateOnMainQueue str r0, [r4] add r0, r4, #0 pop {r3, r4, r5, pc} .balign 4, 0 _02238528: .word ov80_02238530 _0223852C: .word 0x0001368C thumb_func_end ov80_022384FC thumb_func_start ov80_02238530 ov80_02238530: ; 0x02238530 push {r3, r4, lr} sub sp, #0x14 add r4, r1, #0 ldrh r0, [r4, #0xa] cmp r0, #2 bhs _02238544 add r0, r0, #1 add sp, #0x14 strh r0, [r4, #0xa] pop {r3, r4, pc} _02238544: mov r0, #0 strh r0, [r4, #0xa] ldrh r1, [r4, #8] mov r0, #1 eor r0, r1 strh r0, [r4, #8] ldrh r1, [r4, #8] add r0, sp, #0xc lsl r1, r1, #0x18 lsr r1, r1, #0x18 bl ov80_0223857C mov r0, #2 str r0, [sp] str r0, [sp, #4] str r0, [sp, #8] ldr r0, [r4, #4] mov r1, #3 add r2, sp, #0xc mov r3, #0xe bl LoadRectToBgTilemapRect ldr r0, [r4, #4] mov r1, #3 bl ScheduleBgTilemapBufferTransfer add sp, #0x14 pop {r3, r4, pc} thumb_func_end ov80_02238530 thumb_func_start ov80_0223857C ov80_0223857C: ; 0x0223857C push {r4, r5, r6, r7} cmp r1, #0 bne _02238586 mov r6, #0xc b _02238588 _02238586: mov r6, #0xe _02238588: mov r1, #0 mov r3, #0x60 add r4, r1, #0 _0223858E: lsl r5, r4, #1 mov r2, #0 add r5, r0, r5 _02238594: add r7, r6, r2 add r7, r3, r7 strh r7, [r5] add r2, r2, #1 add r5, r5, #2 cmp r2, #2 blo _02238594 add r1, r1, #1 add r3, #0x10 add r4, r4, #2 cmp r1, #2 blo _0223858E pop {r4, r5, r6, r7} bx lr thumb_func_end ov80_0223857C thumb_func_start ov80_022385B0 ov80_022385B0: ; 0x022385B0 push {r4, lr} add r4, r0, #0 ldr r0, [r4, #4] bl ov80_022385C4 add r0, r4, #0 bl Heap_Free pop {r4, pc} .balign 4, 0 thumb_func_end ov80_022385B0 thumb_func_start ov80_022385C4 ov80_022385C4: ; 0x022385C4 push {r4, lr} add r4, r0, #0 ldr r0, [r4] bl SysTask_Destroy add r0, r4, #0 bl Heap_Free pop {r4, pc} .balign 4, 0 thumb_func_end ov80_022385C4 thumb_func_start ov80_022385D8 ov80_022385D8: ; 0x022385D8 cmp r0, #6 bhi _0223860C add r1, r0, r0 add r1, pc ldrh r1, [r1, #6] lsl r1, r1, #0x10 asr r1, r1, #0x10 add pc, r1 _022385E8: ; jump table .short _0223860C - _022385E8 - 2 ; case 0 .short _0223860A - _022385E8 - 2 ; case 1 .short _022385F6 - _022385E8 - 2 ; case 2 .short _022385FA - _022385E8 - 2 ; case 3 .short _022385FE - _022385E8 - 2 ; case 4 .short _02238602 - _022385E8 - 2 ; case 5 .short _02238606 - _022385E8 - 2 ; case 6 _022385F6: mov r0, #0x73 bx lr _022385FA: mov r0, #0x77 bx lr _022385FE: mov r0, #0x87 bx lr _02238602: mov r0, #0x7b bx lr _02238606: mov r0, #0x8f bx lr _0223860A: mov r0, #0x71 _0223860C: bx lr .balign 4, 0 thumb_func_end ov80_022385D8 thumb_func_start ov80_02238610 ov80_02238610: ; 0x02238610 cmp r0, #6 bhi _02238644 add r1, r0, r0 add r1, pc ldrh r1, [r1, #6] lsl r1, r1, #0x10 asr r1, r1, #0x10 add pc, r1 _02238620: ; jump table .short _02238644 - _02238620 - 2 ; case 0 .short _02238642 - _02238620 - 2 ; case 1 .short _0223862E - _02238620 - 2 ; case 2 .short _02238632 - _02238620 - 2 ; case 3 .short _02238636 - _02238620 - 2 ; case 4 .short _0223863A - _02238620 - 2 ; case 5 .short _0223863E - _02238620 - 2 ; case 6 _0223862E: mov r0, #0x66 bx lr _02238632: mov r0, #0x68 bx lr _02238636: mov r0, #0x6c bx lr _0223863A: mov r0, #0x6a bx lr _0223863E: mov r0, #0x6e bx lr _02238642: mov r0, #0x64 _02238644: bx lr .balign 4, 0 thumb_func_end ov80_02238610
0
0.825009
1
0.825009
game-dev
MEDIA
0.766717
game-dev
0.957187
1
0.957187
DarkstarProject/darkstar
2,048
scripts/globals/spells/noctohelix.lua
-------------------------------------- -- Spell: Noctohelix -- Deals dark damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") -------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) -- get helix acc/att merits local merit = caster:getMerit(dsp.merit.HELIX_MAGIC_ACC_ATT) -- calculate raw damage local params = {} params.dmg = 35 params.multiplier = 1 params.skillType = dsp.skill.ELEMENTAL_MAGIC params.attribute = dsp.mod.INT params.hasMultipleTargetReduction = false local dmg = calculateMagicDamage(caster, target, spell, params) dmg = dmg + caster:getMod(dsp.mod.HELIX_EFFECT) -- get resist multiplier (1x if no resist) local params = {} params.diff = caster:getStat(dsp.mod.INT)-target:getStat(dsp.mod.INT) params.attribute = dsp.mod.INT params.skillType = dsp.skill.ELEMENTAL_MAGIC -- bonus accuracy from merit params.bonus = merit*3 local resist = applyResistance(caster, target, spell, params) -- get the resisted damage dmg = dmg*resist -- add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,params) -- add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()) -- helix MAB merits are actually a percentage increase dmg = dmg * ((100 + merit*2)/100) local dot = dmg -- add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg) -- calculate Damage over time dot = target:magicDmgTaken(dot) local duration = getHelixDuration(caster) + caster:getMod(dsp.mod.HELIX_DURATION) duration = duration * (resist/2) if (dot > 0) then target:addStatusEffect(dsp.effect.HELIX,dot,3,duration) end return dmg end
0
0.581442
1
0.581442
game-dev
MEDIA
0.976378
game-dev
0.906209
1
0.906209
neokabuto/OpenTKTutorialContent
6,083
OpenTKTutorial9-3/OpenTKTutorial9-3/ShaderProgram.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenTK.Graphics.OpenGL; using System.IO; namespace OpenTKTutorial9 { class ShaderProgram { public int ProgramID = -1; public int VShaderID = -1; public int FShaderID = -1; public int AttributeCount = 0; public int UniformCount = 0; public Dictionary<String, AttributeInfo> Attributes = new Dictionary<string, AttributeInfo>(); public Dictionary<String, UniformInfo> Uniforms = new Dictionary<string, UniformInfo>(); public Dictionary<String, uint> Buffers = new Dictionary<string, uint>(); public ShaderProgram() { ProgramID = GL.CreateProgram(); } private void loadShader(String code, ShaderType type, out int address) { address = GL.CreateShader(type); GL.ShaderSource(address, code); GL.CompileShader(address); GL.AttachShader(ProgramID, address); Console.WriteLine(GL.GetShaderInfoLog(address)); } public void LoadShaderFromString(String code, ShaderType type) { if (type == ShaderType.VertexShader) { loadShader(code, type, out VShaderID); } else if (type == ShaderType.FragmentShader) { loadShader(code, type, out FShaderID); } } public void LoadShaderFromFile(String filename, ShaderType type) { using (StreamReader sr = new StreamReader(filename)) { if (type == ShaderType.VertexShader) { loadShader(sr.ReadToEnd(), type, out VShaderID); } else if (type == ShaderType.FragmentShader) { loadShader(sr.ReadToEnd(), type, out FShaderID); } } } public void Link() { GL.LinkProgram(ProgramID); Console.WriteLine(GL.GetProgramInfoLog(ProgramID)); GL.GetProgram(ProgramID, ProgramParameter.ActiveAttributes, out AttributeCount); GL.GetProgram(ProgramID, ProgramParameter.ActiveUniforms, out UniformCount); for (int i = 0; i < AttributeCount; i++) { AttributeInfo info = new AttributeInfo(); int length = 0; StringBuilder name = new StringBuilder(); GL.GetActiveAttrib(ProgramID, i, 256, out length, out info.size, out info.type, name); info.name = name.ToString(); info.address = GL.GetAttribLocation(ProgramID, info.name); Attributes.Add(name.ToString(), info); } for (int i = 0; i < UniformCount; i++) { UniformInfo info = new UniformInfo(); int length = 0; StringBuilder name = new StringBuilder(); GL.GetActiveUniform(ProgramID, i, 256, out length, out info.size, out info.type, name); info.name = name.ToString(); Uniforms.Add(name.ToString(), info); info.address = GL.GetUniformLocation(ProgramID, info.name); } } public void GenBuffers() { for (int i = 0; i < Attributes.Count; i++) { uint buffer = 0; GL.GenBuffers(1, out buffer); Buffers.Add(Attributes.Values.ElementAt(i).name, buffer); } for (int i = 0; i < Uniforms.Count; i++) { uint buffer = 0; GL.GenBuffers(1, out buffer); Buffers.Add(Uniforms.Values.ElementAt(i).name, buffer); } } public void EnableVertexAttribArrays() { for (int i = 0; i < Attributes.Count; i++) { GL.EnableVertexAttribArray(Attributes.Values.ElementAt(i).address); } } public void DisableVertexAttribArrays() { for (int i = 0; i < Attributes.Count; i++) { GL.DisableVertexAttribArray(Attributes.Values.ElementAt(i).address); } } public int GetAttribute(string name) { if (Attributes.ContainsKey(name)) { return Attributes[name].address; } else { return -1; } } public int GetUniform(string name) { if (Uniforms.ContainsKey(name)) { return Uniforms[name].address; } else { return -1; } } public uint GetBuffer(string name) { if (Buffers.ContainsKey(name)) { return Buffers[name]; } else { return 0; } } public ShaderProgram(String vshader, String fshader, bool fromFile = false) { ProgramID = GL.CreateProgram(); if (fromFile) { LoadShaderFromFile(vshader, ShaderType.VertexShader); LoadShaderFromFile(fshader, ShaderType.FragmentShader); } else { LoadShaderFromString(vshader, ShaderType.VertexShader); LoadShaderFromString(fshader, ShaderType.FragmentShader); } Link(); GenBuffers(); } public class UniformInfo { public String name = ""; public int address = -1; public int size = 0; public ActiveUniformType type; } public class AttributeInfo { public String name = ""; public int address = -1; public int size = 0; public ActiveAttribType type; } } }
0
0.684723
1
0.684723
game-dev
MEDIA
0.39348
game-dev
0.913182
1
0.913182
JakubNei/mcs-ICodeCompiler
8,428
source of mcs/external/ikvm/reflect/PropertyInfo.cs
/* Copyright (C) 2009-2012 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters jeroen@frijters.net */ using System; using System.Collections.Generic; namespace IKVM.Reflection { public abstract class PropertyInfo : MemberInfo { // prevent external subclasses internal PropertyInfo() { } public sealed override MemberTypes MemberType { get { return MemberTypes.Property; } } public abstract PropertyAttributes Attributes { get; } public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public abstract MethodInfo GetGetMethod(bool nonPublic); public abstract MethodInfo GetSetMethod(bool nonPublic); public abstract MethodInfo[] GetAccessors(bool nonPublic); public abstract object GetRawConstantValue(); internal abstract bool IsPublic { get; } internal abstract bool IsNonPrivate { get; } internal abstract bool IsStatic { get; } internal abstract PropertySignature PropertySignature { get; } private sealed class ParameterInfoImpl : ParameterInfo { private readonly PropertyInfo property; private readonly int parameter; internal ParameterInfoImpl(PropertyInfo property, int parameter) { this.property = property; this.parameter = parameter; } public override string Name { get { return null; } } public override Type ParameterType { get { return property.PropertySignature.GetParameter(parameter); } } public override ParameterAttributes Attributes { get { return ParameterAttributes.None; } } public override int Position { get { return parameter; } } public override object RawDefaultValue { get { throw new InvalidOperationException(); } } public override CustomModifiers __GetCustomModifiers() { return property.PropertySignature.GetParameterCustomModifiers(parameter); } public override bool __TryGetFieldMarshal(out FieldMarshal fieldMarshal) { fieldMarshal = new FieldMarshal(); return false; } public override MemberInfo Member { get { return property; } } public override int MetadataToken { get { return 0x08000000; } } internal override Module Module { get { return property.Module; } } } public virtual ParameterInfo[] GetIndexParameters() { ParameterInfo[] parameters = new ParameterInfo[this.PropertySignature.ParameterCount]; for (int i = 0; i < parameters.Length; i++) { parameters[i] = new ParameterInfoImpl(this, i); } return parameters; } public Type PropertyType { get { return this.PropertySignature.PropertyType; } } public CustomModifiers __GetCustomModifiers() { return this.PropertySignature.GetCustomModifiers(); } public Type[] GetRequiredCustomModifiers() { return __GetCustomModifiers().GetRequired(); } public Type[] GetOptionalCustomModifiers() { return __GetCustomModifiers().GetOptional(); } public bool IsSpecialName { get { return (Attributes & PropertyAttributes.SpecialName) != 0; } } public MethodInfo GetMethod { get { return GetGetMethod(true); } } public MethodInfo SetMethod { get { return GetSetMethod(true); } } public MethodInfo GetGetMethod() { return GetGetMethod(false); } public MethodInfo GetSetMethod() { return GetSetMethod(false); } public MethodInfo[] GetAccessors() { return GetAccessors(false); } public CallingConventions __CallingConvention { get { return this.PropertySignature.CallingConvention; } } internal virtual PropertyInfo BindTypeParameters(Type type) { return new GenericPropertyInfo(this.DeclaringType.BindTypeParameters(type), this); } public override string ToString() { return this.DeclaringType.ToString() + " " + Name; } internal sealed override bool BindingFlagsMatch(BindingFlags flags) { return BindingFlagsMatch(IsPublic, flags, BindingFlags.Public, BindingFlags.NonPublic) && BindingFlagsMatch(IsStatic, flags, BindingFlags.Static, BindingFlags.Instance); } internal sealed override bool BindingFlagsMatchInherited(BindingFlags flags) { return IsNonPrivate && BindingFlagsMatch(IsPublic, flags, BindingFlags.Public, BindingFlags.NonPublic) && BindingFlagsMatch(IsStatic, flags, BindingFlags.Static | BindingFlags.FlattenHierarchy, BindingFlags.Instance); } internal sealed override MemberInfo SetReflectedType(Type type) { return new PropertyInfoWithReflectedType(type, this); } internal sealed override List<CustomAttributeData> GetPseudoCustomAttributes(Type attributeType) { // properties don't have pseudo custom attributes return null; } } sealed class PropertyInfoWithReflectedType : PropertyInfo { private readonly Type reflectedType; private readonly PropertyInfo property; internal PropertyInfoWithReflectedType(Type reflectedType, PropertyInfo property) { this.reflectedType = reflectedType; this.property = property; } public override PropertyAttributes Attributes { get { return property.Attributes; } } public override bool CanRead { get { return property.CanRead; } } public override bool CanWrite { get { return property.CanWrite; } } public override MethodInfo GetGetMethod(bool nonPublic) { return SetReflectedType(property.GetGetMethod(nonPublic), reflectedType); } public override MethodInfo GetSetMethod(bool nonPublic) { return SetReflectedType(property.GetSetMethod(nonPublic), reflectedType); } public override MethodInfo[] GetAccessors(bool nonPublic) { return SetReflectedType(property.GetAccessors(nonPublic), reflectedType); } public override object GetRawConstantValue() { return property.GetRawConstantValue(); } internal override bool IsPublic { get { return property.IsPublic; } } internal override bool IsNonPrivate { get { return property.IsNonPrivate; } } internal override bool IsStatic { get { return property.IsStatic; } } internal override PropertySignature PropertySignature { get { return property.PropertySignature; } } public override ParameterInfo[] GetIndexParameters() { ParameterInfo[] parameters = property.GetIndexParameters(); for (int i = 0; i < parameters.Length; i++) { parameters[i] = new ParameterInfoWrapper(this, parameters[i]); } return parameters; } internal override PropertyInfo BindTypeParameters(Type type) { return property.BindTypeParameters(type); } public override string ToString() { return property.ToString(); } public override bool __IsMissing { get { return property.__IsMissing; } } public override Type DeclaringType { get { return property.DeclaringType; } } public override Type ReflectedType { get { return reflectedType; } } public override bool Equals(object obj) { PropertyInfoWithReflectedType other = obj as PropertyInfoWithReflectedType; return other != null && other.reflectedType == reflectedType && other.property == property; } public override int GetHashCode() { return reflectedType.GetHashCode() ^ property.GetHashCode(); } public override int MetadataToken { get { return property.MetadataToken; } } public override Module Module { get { return property.Module; } } public override string Name { get { return property.Name; } } internal override bool IsBaked { get { return property.IsBaked; } } internal override int GetCurrentToken() { return property.GetCurrentToken(); } } }
0
0.905492
1
0.905492
game-dev
MEDIA
0.366518
game-dev
0.82966
1
0.82966
PugrillaDev/Raven-Scripts
11,952
AutoHypixel.java
long lastJoinTs = 0L, lastQuitTs = 0L; int joinCount = 0, quitCount = 0; void onLoad() { modules.registerDescription("Lobby Messages"); modules.registerButton("Disable lobby joins", true); modules.registerButton("Disable ticket machine", true); modules.registerButton("Claim daily rewards", true); modules.registerButton("Show party sizes", true); } boolean onChat(String msg) { String stripped = util.strip(msg); String text = stripped.toLowerCase(); if (modules.getButton(scriptName, "Show party sizes")) { handleJoinLine(stripped); handleQuitLine(stripped); } if (modules.getButton(scriptName, "Disable lobby joins") && filterLobbyJoin(stripped)) { return false; } if (modules.getButton(scriptName, "Disable ticket machine") && filterTicketMachine(stripped)) { return false; } if (modules.getButton(scriptName, "Claim daily rewards")) { handleReward(text); } return true; } void onPreUpdate() { handleParties(); } void handleParties() { long now = System.nanoTime(); if (joinCount > 0 && now - lastJoinTs >= 10000000) { if (joinCount > 1) client.print("&8[&cQueue&8] &7Party of &c" + joinCount + " &7joined."); joinCount = 0; } if (quitCount > 0 && now - lastQuitTs >= 10000000) { if (quitCount > 1) client.print("&8[&cQueue&8] &7Party of &c" + quitCount + " &7quit."); quitCount = 0; } } void handleJoinLine(String l) { int i = l.indexOf(" has joined ("); if (i < 0 || l.charAt(l.length() - 2) != ')' || l.charAt(l.length() - 1) != '!') return; if (l.indexOf('/', i + 13) < 0) return; lastJoinTs = System.nanoTime(); joinCount++; } void handleQuitLine(String l) { int i = l.indexOf(" has quit!"); if (i < 0 || l.charAt(l.length() - 1) != '!') return; lastQuitTs = System.nanoTime(); quitCount++; } boolean filterLobbyJoin(String msg) { return (msg.startsWith(" >>>") && msg.endsWith("lobby! <<<")) || (msg.startsWith("[") && msg.endsWith("lobby!")); } boolean filterTicketMachine(String msg) { return msg.contains(" has found a ") && (msg.contains(" COMMON ") || msg.contains(" RARE ") || msg.contains(" EPIC ") || msg.contains(" LEGENDARY ")); } void handleReward(String text) { text = text.toLowerCase(); int idx = text.indexOf("hypixel.net/claim-reward/"); if (idx == -1) return; int start = text.lastIndexOf("http", idx); int end = text.indexOf(" ", idx); if (start == -1) return; if (end == -1) end = text.length(); String rewardLink = text.substring(start, end).replace("https://hypixel.net/", "https://rewards.hypixel.net/"); int codeStart = rewardLink.lastIndexOf("/") + 1; String code = rewardLink.substring(codeStart); if (code.length() != 8) return; if (!rewardLink.startsWith("https://rewards.hypixel.net/claim-reward/")) return; client.async(() -> { try { long now = client.time(); client.print("&8[&cReward&8] &7Found reward link. Claiming..."); Request req1 = new Request("GET", rewardLink); req1.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"); Response res1 = req1.fetch(); if (res1 == null) { return; } String html = res1.string(); String token = extractBetween(html, "window.securityToken = \"", "\""); String data = extractBetween(html, "window.appData = '", "';").replace("\\'", "'"); if (token.isEmpty() || data.isEmpty()) { client.print("&8[&cReward&8] &7Reward was already claimed or is invalid."); return; } String csrfCookie = ""; for (String[] h : res1.headers()) { if (h[0].equalsIgnoreCase("set-cookie") && h[1].startsWith("_csrf=")) { csrfCookie = h[1].split(";", 2)[0]; break; } } Json appData = Json.parse(data); List<Json> cards = appData.get("rewards").asArray(); Map<String, Integer> rarityBonus = new HashMap<>(); rarityBonus.put("COMMON", 0); rarityBonus.put("RARE", 50); rarityBonus.put("EPIC", 150); rarityBonus.put("LEGENDARY", 500); String best = ""; double bestScore = -1; int index = 0; client.print("&8[&cReward&8] &7Rewards offered:"); for (int i = 0; i < cards.size(); i++) { Json c = cards.get(i); String gameType = c.has("gameType") ? c.get("gameType").asString() : ""; String type = c.has("reward") ? c.get("reward").asString() : "Unknown"; String rarity = c.has("rarity") ? c.get("rarity").asString() : "COMMON"; int amount = c.has("amount") ? c.get("amount").asInt() : 0; double score = 1; if (type.equals("adsense_token")) score = amount * 250; else if (type.equals("experience")) score = amount * 0.002; else if (type.equals("dust")) score = amount * 4; else if (type.equals("coins") || type.equals("tokens")) score = amount * 0.001; else if (type.equals("housing_package")) score = 10; if (!type.equals("coins") && !type.equals("tokens")) { score += rarityBonus.getOrDefault(rarity, 0); } String name = prettyReward(type); if (type.equals("housing_package")) name = prettyHousingBlock(c.get("package").asString()) + " " + name; if (!gameType.isEmpty()) name = prettyGameType(gameType) + " " + name; String displayRarity = prettyRarity(rarity); String msg = rarityColor(rarity) + displayRarity + "&7" + (amount > 0 ? " " + amount + "x " : " ") + name; client.print("&8[&cReward&8] " + msg); if (score > bestScore) { bestScore = score; best = msg; index = i; } } String claim = "https://rewards.hypixel.net/claim-reward/claim?id=" + appData.get("id").asString() + "&option=" + index + "&activeAd=" + appData.get("activeAd").asString() + "&_csrf=" + token; Request req2 = new Request("POST", claim); req2.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"); if (!csrfCookie.isEmpty()) req2.addHeader("Cookie", csrfCookie); Response res2 = req2.fetch(); long finished = client.time(); if (res2 == null) { client.print("&8[&cReward&8] &7Failed to claim reward. Request timed out."); return; } int status = res2.code(); if (status == 200) { client.print("&8[&cReward&8] &7Claimed " + best + " &8(&c" + (finished - now) + "ms&8)"); } else if (status == 400) { client.print("&8[&cReward&8] &7Reward was already claimed. &8(&c" + (finished - now) + "ms&8)"); } else { client.print("&8[&cReward&8] &7Failed to claim reward. Status &c" + status); } } catch (Exception e) { client.print(Arrays.toString(e.getStackTrace())); client.print("&8[&cReward&8] &7Error while claiming reward: &c" + e); } }); } String extractBetween(String src, String a, String b) { int start = src.indexOf(a); if (start == -1) return ""; start += a.length(); int end = src.indexOf(b, start); if (end == -1) return ""; return src.substring(start, end); } String prettyRarity(String rarity) { if (rarity == null || rarity.isEmpty()) return "Common"; return rarity.substring(0, 1).toUpperCase() + rarity.substring(1).toLowerCase(); } String prettyReward(String raw) { Map<String, String> rewardsData = new HashMap<>(); rewardsData.put("adsense_token", "Reward Token"); rewardsData.put("housing_package", "Housing Block"); rewardsData.put("dust", "Mystery Dust"); if (rewardsData.containsKey(raw)) return rewardsData.get(raw); String[] parts = raw.replace('_', ' ').split(" "); StringBuilder sb = new StringBuilder(); for (String part : parts) { if (part.length() > 0) { sb.append(Character.toUpperCase(part.charAt(0))).append(part.substring(1).toLowerCase()); } sb.append(" "); } return sb.toString().trim(); } String prettyHousingBlock(String raw) { Map<String, String> housingData = new HashMap<>(); housingData.put("specialoccasion_reward_card_skull_red_treasure_chest", "Red Treasure Chest"); housingData.put("specialoccasion_reward_card_skull_gold_nugget", "Gold Nugget"); housingData.put("specialoccasion_reward_card_skull_pot_o'_gold", "Pot O' Gold"); housingData.put("specialoccasion_reward_card_skull_rubik's_cube", "Rubik's Cube"); housingData.put("specialoccasion_reward_card_skull_piggy_bank", "Piggy Bank"); housingData.put("specialoccasion_reward_card_skull_health_potion", "Health Potion"); housingData.put("specialoccasion_reward_card_skull_green_treasure_chest", "Green Treasure Chest"); housingData.put("specialoccasion_reward_card_skull_coin_bag", "Coin Bag"); housingData.put("specialoccasion_reward_card_skull_ornamental_helmet", "Ornamental Helmet"); housingData.put("specialoccasion_reward_card_skull_pocket_galaxy", "Pocket Galaxy"); housingData.put("specialoccasion_reward_card_skull_mystic_pearl", "Mystic Pearl"); housingData.put("specialoccasion_reward_card_skull_agility_potion", "Agility Potion"); housingData.put("specialoccasion_reward_card_skull_blue_treasure_chest", "Blue Treasure Chest"); housingData.put("specialoccasion_reward_card_skull_golden_chalice", "Golden Chalice"); housingData.put("specialoccasion_reward_card_skull_jewelery_box", "Jewelry Box"); housingData.put("specialoccasion_reward_card_skull_crown", "Crown"); housingData.put("specialoccasion_reward_card_skull_molten_core", "Molten Core"); housingData.put("specialoccasion_reward_card_skull_mana_potion", "Mana Potion"); if (housingData.containsKey(raw)) return housingData.get(raw); return raw.replace('_', ' ').toLowerCase(); } String prettyGameType(String raw) { Map<String, String> gameTypes = new HashMap<>(); gameTypes.put("walls3", "Mega Walls"); gameTypes.put("quakecraft", "Quakecraft"); gameTypes.put("walls", "Walls"); gameTypes.put("paintball", "Paintball"); gameTypes.put("survival_games", "Blitz SG"); gameTypes.put("tntgames", "TNT Games"); gameTypes.put("vampirez", "VampireZ"); gameTypes.put("arcade", "Arcade"); gameTypes.put("arena", "Arena"); gameTypes.put("uhc", "UHC"); gameTypes.put("mcgo", "Cops and Crims"); gameTypes.put("battleground", "Warlords"); gameTypes.put("super_smash", "Smash Heroes"); gameTypes.put("gingerbread", "Turbo Kart Racers"); gameTypes.put("skywars", "SkyWars"); gameTypes.put("true_combat", "Crazy Walls"); gameTypes.put("speeduhc", "Speed UHC"); gameTypes.put("bedwars", "Bed Wars"); gameTypes.put("build_battle", "Build Battle"); gameTypes.put("murder_mystery", "Murder Mystery"); gameTypes.put("duels", "Duels"); gameTypes.put("legacy", "Classic"); return gameTypes.getOrDefault(raw.toLowerCase(), raw.replace('_', ' ').toLowerCase()); } String rarityColor(String rarity) { return rarity.equalsIgnoreCase("COMMON") ? "&f" : rarity.equalsIgnoreCase("RARE") ? "&9" : rarity.equalsIgnoreCase("EPIC") ? "&d" : rarity.equalsIgnoreCase("LEGENDARY") ? "&6" : "&f"; }
0
0.881809
1
0.881809
game-dev
MEDIA
0.377477
game-dev
0.927822
1
0.927822
mixandjam/BoTW-Stasis
5,614
Assets/Scripts/StasisCharacter.cs
using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; using Cinemachine; using DG.Tweening; using System; public class StasisCharacter : MonoBehaviour { [Header("Collision")] public LayerMask layerMask; private MovementInput input; public Animator anim; [Space] [Header("Aim and Zoom")] public bool stasisAim; public CinemachineFreeLook thirdPersonCamera; public float zoomDuration = .3f; private float originalFOV; public float zoomFOV; private Vector3 originalCameraOffset; public Vector3 zoomCameraOffset; [Space] [Header("Target")] public Transform target; [Space] [Header("Colors")] public Color highligthedColor; public Color normalColor; public Color finalColor; // Start is called before the first frame update void Start() { Cursor.visible = false; input = GetComponent<MovementInput>(); anim = GetComponent<Animator>(); originalFOV = thirdPersonCamera.m_Lens.FieldOfView; originalCameraOffset = thirdPersonCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>().m_TrackedObjectOffset; } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(1)) { StasisAim(true); } if (Input.GetMouseButtonUp(1)) { StasisAim(false); } if (stasisAim) { RaycastHit hit; Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward); if(Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask)) { if (target != hit.transform) { if(target!= null && target.GetComponent<StasisObject>() != null) target.GetComponent<Renderer>().material.SetColor("_EmissionColor", normalColor); target = hit.transform; if (target.GetComponent<StasisObject>() != null) { if (!target.GetComponent<StasisObject>().activated) target.GetComponent<Renderer>().material.SetColor("_EmissionColor", highligthedColor); InterfaceAnimation.instance.Target(true); } else { InterfaceAnimation.instance.Target(false); } } } else { if (target != null) { if(target.GetComponent<StasisObject>()!= null) if (!target.GetComponent<StasisObject>().activated) target.GetComponent<Renderer>().material.SetColor("_EmissionColor", normalColor); target = null; InterfaceAnimation.instance.Target(false); } } } if (Input.GetMouseButtonDown(0)) { if (!stasisAim) { anim.SetTrigger("slash"); StartCoroutine(WaitFrame()); } else { if (target != null && target.GetComponent<StasisObject>()!=null) { bool stasis = target.GetComponent<StasisObject>().activated; target.GetComponent<StasisObject>().SetStasis(!stasis); StasisAim(false); } } } // RestartHotkey(); } IEnumerator WaitFrame() { yield return new WaitForEndOfFrame(); if(!anim.GetBool("attacking")) anim.SetBool("attacking", true); } void StasisAim(bool state) { stasisAim = state; float fov = state ? zoomFOV : originalFOV; Vector3 offset = state ? zoomCameraOffset : originalCameraOffset; float stasisEffect = state ? .4f : 0; CinemachineComposer composer = thirdPersonCamera.GetRig(1).GetCinemachineComponent<CinemachineComposer>(); DOVirtual.Float(thirdPersonCamera.m_Lens.FieldOfView, fov, zoomDuration, SetFieldOfView); DOVirtual.Float(composer.m_TrackedObjectOffset.x, offset.x, zoomDuration, SetCameraOffsetX); DOVirtual.Float(composer.m_TrackedObjectOffset.y, offset.y, zoomDuration, SetCameraOffsetY); StasisObject[] stasisObjects = FindObjectsOfType<StasisObject>(); foreach(StasisObject obj in stasisObjects) { if (!obj.activated) { obj.GetComponent<Renderer>().material.SetColor("_EmissionColor", normalColor); obj.GetComponent<Renderer>().material.SetFloat("_StasisAmount", stasisEffect); } } InterfaceAnimation.instance.Show(state); } void SetFieldOfView(float x) { thirdPersonCamera.m_Lens.FieldOfView = x; } void SetCameraOffsetX(float x) { for (int i = 0; i < 3; i++) { thirdPersonCamera.GetRig(i).GetCinemachineComponent<CinemachineComposer>().m_TrackedObjectOffset.x = x; } } void SetCameraOffsetY(float y) { for (int i = 0; i < 3; i++) { thirdPersonCamera.GetRig(i).GetCinemachineComponent<CinemachineComposer>().m_TrackedObjectOffset.y = y; } } void RestartHotkey() { if (Input.GetKeyDown(KeyCode.R)) { SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().name); } } }
0
0.892713
1
0.892713
game-dev
MEDIA
0.901242
game-dev,graphics-rendering
0.98695
1
0.98695
ElspethThePict/S1Forever
2,280
SonLVLObjDefs/MZ/FallingBlock.cs
using SonicRetro.SonLVL.API; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; namespace S1ObjectDefinitions.MZ { class FallingBlock : ObjectDefinition { private PropertySpec[] properties = new PropertySpec[1]; private Sprite sprite; private Sprite debug; public override void Init(ObjectData data) { sprite = new Sprite(LevelData.GetSpriteSheet("MZ/Objects.gif").GetSection(191, 289, 32, 32), -16, -16); // tagging this area with LevelData.ColorWhite BitmapBits bitmap = new BitmapBits(1, 16); bitmap.DrawLine(6, 0, 0, 0, 3); bitmap.DrawLine(6, 0, 6, 0, 9); bitmap.DrawLine(6, 0, 12, 0, 15); debug = new Sprite(bitmap, 0, 14); // Sonic Origins gives some blocks a prop val of 5... but that's literally the same thing as using a prop val of 0 // various base game blocks have prop vals greater than 4 already, too // in-game, though, any invalid prop vals are reset to 0 properties[0] = new PropertySpec("Behaviour", typeof(int), "Extended", "How this Block should act.", null, new Dictionary<string, int> { { "Static", 0 }, { "Floating (Hover)", 1 }, { "Floating (Drop)", 2 }, // 3 is the falling state, but we don't wanna spawn that { "Floating (In Lava)", 4 } }, (obj) => ((obj.PropertyValue & 7) > 4) ? 0 : (obj.PropertyValue & 7), (obj, value) => obj.PropertyValue = (byte)((int)value)); } public override ReadOnlyCollection<byte> Subtypes { get { return new ReadOnlyCollection<byte>(new byte[] {0, 1, 2, 4}); } } public override PropertySpec[] CustomProperties { get { return properties; } } public override string SubtypeName(byte subtype) { if (subtype > 4) subtype = 0; string[] names = {"Static", "Floating (Hover)", "Floating (Drop)", "Falling", "Floating (In Lava)"}; // falling shouldn't be used return names[subtype]; } public override Sprite Image { get { return sprite; } } public override Sprite SubtypeImage(byte subtype) { return sprite; } public override Sprite GetSprite(ObjectEntry obj) { return sprite; } public override Sprite GetDebugOverlay(ObjectEntry obj) { return ((obj.PropertyValue & 7) == 2) ? debug : null; } } }
0
0.780905
1
0.780905
game-dev
MEDIA
0.819209
game-dev,graphics-rendering
0.96336
1
0.96336
Maxlego08/zEssentials
1,622
src/main/java/fr/maxlego08/essentials/commands/commands/kits/CommandKitCreate.java
package fr.maxlego08.essentials.commands.commands.kits; import fr.maxlego08.essentials.api.EssentialsPlugin; import fr.maxlego08.essentials.api.commands.CommandResultType; import fr.maxlego08.essentials.api.commands.Permission; import fr.maxlego08.essentials.api.kit.Kit; import fr.maxlego08.essentials.api.messages.Message; import fr.maxlego08.essentials.module.modules.kit.KitModule; import fr.maxlego08.essentials.zutils.utils.commands.VCommand; import java.time.Duration; import java.util.Optional; public class CommandKitCreate extends VCommand { public CommandKitCreate(EssentialsPlugin plugin) { super(plugin); this.setModule(KitModule.class); this.setPermission(Permission.ESSENTIALS_KIT_CREATE); this.setDescription(Message.DESCRIPTION_KIT_CREATE); this.addRequireArg("name", (a, b) -> plugin.getModuleManager().getModule(KitModule.class).getKitNames()); this.addRequireArg("cooldown", (a, b) -> this.cooldowns); } @Override protected CommandResultType perform(EssentialsPlugin plugin) { KitModule kitModule = plugin.getModuleManager().getModule(KitModule.class); String kitName = this.argAsString(0); Duration duration = this.argAsDuration(1); Optional<Kit> optional = kitModule.getKit(kitName); if (optional.isPresent()) { message(sender, Message.COMMAND_KIT_ALREADY_EXISTS, "%kit%", kitName); return CommandResultType.DEFAULT; } kitModule.createKit(this.player, kitName, Math.max(0L, duration.toSeconds())); return CommandResultType.SUCCESS; } }
0
0.819742
1
0.819742
game-dev
MEDIA
0.845542
game-dev
0.75692
1
0.75692
etternagame/etterna
1,294
src/Etterna/Globals/rngthing.h
#include <random> using RandomGen = std::mt19937; extern RandomGen g_RandomNumberGenerator; void seed_lua_prng(); inline auto random_up_to(RandomGen& rng, int limit) -> int { RandomGen::result_type res = rng(); // Cutting off the incomplete [0,n) chunk at the max value makes the result // more evenly distributed. -Kyz RandomGen::result_type up_to_max = RandomGen::max() - (RandomGen::max() % limit); while (res > up_to_max) { res = rng(); } return static_cast<int>(res % limit); } inline auto random_up_to(int limit) -> int { return random_up_to(g_RandomNumberGenerator, limit); } inline auto RandomFloat() -> float { return static_cast<float>(g_RandomNumberGenerator() / 4294967296.0); } inline auto RandomFloat(float fLow, float fHigh) -> float { // SCALE() but l1 = 0 and h1 = 1 so simplifies to this return (RandomFloat() * (fHigh - fLow)) + fLow; } inline auto RandomInt(int low, int high) -> int { return random_up_to(g_RandomNumberGenerator, high - low + 1) + low; } inline auto RandomInt(int n) -> int { return random_up_to(g_RandomNumberGenerator, n); } inline auto RandomInt(RandomGen& rng, int n) -> int { return random_up_to(rng, n); } inline auto randomf(const float low = -1.F, const float high = 1.F) -> float { return RandomFloat(low, high); }
0
0.759261
1
0.759261
game-dev
MEDIA
0.71406
game-dev
0.860334
1
0.860334
OTCv8/otclientv8
4,071
modules/gamelib/market.lua
MarketMaxAmount = 2000 MarketMaxAmountStackable = 64000 MarketMaxPrice = 999999999 MarketMaxOffers = 100 MarketAction = { Buy = 0, Sell = 1 } MarketRequest = { MyOffers = 0xFFFE, MyHistory = 0xFFFF } MarketOfferState = { Active = 0, Cancelled = 1, Expired = 2, Accepted = 3, AcceptedEx = 255 } MarketCategory = { All = 0, Armors = 1, Amulets = 2, Boots = 3, Containers = 4, Decoration = 5, Food = 6, HelmetsHats = 7, Legs = 8, Others = 9, Potions = 10, Rings = 11, Runes = 12, Shields = 13, Tools = 14, Valuables = 15, Ammunition = 16, Axes = 17, Clubs = 18, DistanceWeapons = 19, Swords = 20, WandsRods = 21, PremiumScrolls = 22, TibiaCoins = 23, CreatureProducs = 24, Unknown1 = 25, Unknown2 = 26, StashRetrieve = 27, Unknown3 = 28, Unknown4 = 29, Gold = 30, Unassigned = 31, MetaWeapons = 255 } MarketCategory.First = MarketCategory.Armors MarketCategory.Last = MarketCategory.Unassigned MarketCategoryWeapons = { [MarketCategory.Ammunition] = { slots = {255} }, [MarketCategory.Axes] = { slots = {255, InventorySlotOther, InventorySlotLeft} }, [MarketCategory.Clubs] = { slots = {255, InventorySlotOther, InventorySlotLeft} }, [MarketCategory.DistanceWeapons] = { slots = {255, InventorySlotOther, InventorySlotLeft} }, [MarketCategory.Swords] = { slots = {255, InventorySlotOther, InventorySlotLeft} }, [MarketCategory.WandsRods] = { slots = {255, InventorySlotOther, InventorySlotLeft} } } MarketCategoryStrings = { [0] = 'All', [1] = 'Armors', [2] = 'Amulets', [3] = 'Boots', [4] = 'Containers', [5] = 'Decoration', [6] = 'Food', [7] = 'Helmets and Hats', [8] = 'Legs', [9] = 'Others', [10] = 'Potions', [11] = 'Rings', [12] = 'Runes', [13] = 'Shields', [14] = 'Tools', [15] = 'Valuables', [16] = 'Ammunition', [17] = 'Axes', [18] = 'Clubs', [19] = 'Distance Weapons', [20] = 'Swords', [21] = 'Wands and Rods', [22] = 'Premium Scrolls', [23] = 'Tibia Coins', [24] = 'Creature Products', [25] = 'Unknown 1', [26] = 'Unknown 2', [27] = 'Stash Retrieve', [28] = 'Unknown 3', [29] = 'Unknown 4', [30] = 'Gold', [31] = 'Unassigned', [255] = 'Weapons' } function getMarketCategoryName(id) if table.haskey(MarketCategoryStrings, id) then return MarketCategoryStrings[id] end end function getMarketCategoryId(name) local id = table.find(MarketCategoryStrings, name) if id then return id end end MarketItemDescription = { Armor = 1, Attack = 2, Container = 3, Defense = 4, General = 5, DecayTime = 6, Combat = 7, MinLevel = 8, MinMagicLevel = 9, Vocation = 10, Rune = 11, Ability = 12, Charges = 13, WeaponName = 14, Weight = 15, Imbuements = 16 } MarketItemDescription.First = MarketItemDescription.Armor MarketItemDescription.Last = MarketItemDescription.Weight MarketItemDescriptionStrings = { [1] = 'Armor', [2] = 'Attack', [3] = 'Container', [4] = 'Defense', [5] = 'Description', [6] = 'Use Time', [7] = 'Combat', [8] = 'Min Level', [9] = 'Min Magic Level', [10] = 'Vocation', [11] = 'Rune', [12] = 'Ability', [13] = 'Charges', [14] = 'Weapon Type', [15] = 'Weight', [16] = 'Imbuements' } function getMarketDescriptionName(id) if table.haskey(MarketItemDescriptionStrings, id) then return MarketItemDescriptionStrings[id] end end function getMarketDescriptionId(name) local id = table.find(MarketItemDescriptionStrings, name) if id then return id end end MarketSlotFilters = { [InventorySlotOther] = "Two-Handed", [InventorySlotLeft] = "One-Handed", [255] = "Any" } MarketFilters = { Vocation = 1, Level = 2, Depot = 3, SearchAll = 4 } MarketFilters.First = MarketFilters.Vocation MarketFilters.Last = MarketFilters.Depot function getMarketSlotFilterId(name) local id = table.find(MarketSlotFilters, name) if id then return id end end function getMarketSlotFilterName(id) if table.haskey(MarketSlotFilters, id) then return MarketSlotFilters[id] end end
0
0.658062
1
0.658062
game-dev
MEDIA
0.713345
game-dev
0.804984
1
0.804984
Gaby-Station/Gaby-Station
17,006
Content.Server/Bed/Cryostorage/CryostorageSystem.cs
// SPDX-FileCopyrightText: 2024 12rabbits <53499656+12rabbits@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Alzore <140123969+Blackern5000@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 ArtisticRoomba <145879011+ArtisticRoomba@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Brandon Hu <103440971+Brandon-Huu@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Dimastra <65184747+Dimastra@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Dimastra <dimastra@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 DrSmugleaf <drsmugleaf@gmail.com> // SPDX-FileCopyrightText: 2024 Ed <96445749+TheShuEd@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Emisse <99158783+Emisse@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Eoin Mcloughlin <helloworld@eoinrul.es> // SPDX-FileCopyrightText: 2024 IProduceWidgets <107586145+IProduceWidgets@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 JIPDawg <51352440+JIPDawg@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 JIPDawg <JIPDawg93@gmail.com> // SPDX-FileCopyrightText: 2024 Mervill <mervills.email@gmail.com> // SPDX-FileCopyrightText: 2024 Moomoobeef <62638182+Moomoobeef@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Nemanja <98561806+EmoGarbage404@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 PJBot <pieterjan.briers+bot@gmail.com> // SPDX-FileCopyrightText: 2024 Pieter-Jan Briers <pieterjan.briers+git@gmail.com> // SPDX-FileCopyrightText: 2024 Pieter-Jan Briers <pieterjan.briers@gmail.com> // SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me> // SPDX-FileCopyrightText: 2024 PopGamer46 <yt1popgamer@gmail.com> // SPDX-FileCopyrightText: 2024 PursuitInAshes <pursuitinashes@gmail.com> // SPDX-FileCopyrightText: 2024 QueerNB <176353696+QueerNB@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Saphire Lattice <lattice@saphi.re> // SPDX-FileCopyrightText: 2024 ShadowCommander <10494922+ShadowCommander@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Simon <63975668+Simyon264@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Spessmann <156740760+Spessmann@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Tayrtahn <tayrtahn@gmail.com> // SPDX-FileCopyrightText: 2024 Thomas <87614336+Aeshus@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 Winkarst <74284083+Winkarst-cpu@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 c4llv07e <38111072+c4llv07e@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org> // SPDX-FileCopyrightText: 2024 eoineoineoin <github@eoinrul.es> // SPDX-FileCopyrightText: 2024 github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 lunarcomets <140772713+lunarcomets@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 lzk <124214523+lzk228@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 metalgearsloth <comedian_vs_clown@hotmail.com> // SPDX-FileCopyrightText: 2024 slarticodefast <161409025+slarticodefast@users.noreply.github.com> // SPDX-FileCopyrightText: 2024 stellar-novas <stellar_novas@riseup.net> // SPDX-FileCopyrightText: 2024 themias <89101928+themias@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using System.Globalization; using Content.Server.Chat.Managers; using Content.Server.Chat.Systems; using Content.Server.Ghost; using Content.Server.Hands.Systems; using Content.Server.Inventory; using Content.Server.Popups; using Content.Server.Station.Components; using Content.Server.Station.Systems; using Content.Server.StationRecords; using Content.Server.StationRecords.Systems; using Content.Shared.Access.Systems; using Content.Shared.Bed.Cryostorage; using Content.Shared.Chat; using Content.Shared.Climbing.Systems; using Content.Shared.Database; using Content.Shared.GameTicking; using Content.Shared.Hands.Components; using Content.Shared.Mind.Components; using Content.Shared.StationRecords; using Content.Shared.UserInterface; using Robust.Server.Audio; using Robust.Server.Containers; using Robust.Server.GameObjects; using Robust.Server.Player; using Robust.Shared.Containers; using Robust.Shared.Enums; using Robust.Shared.Network; using Robust.Shared.Player; namespace Content.Server.Bed.Cryostorage; /// <inheritdoc/> public sealed class CryostorageSystem : SharedCryostorageSystem { [Dependency] private readonly IChatManager _chatManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly AudioSystem _audio = default!; [Dependency] private readonly AccessReaderSystem _accessReader = default!; [Dependency] private readonly ChatSystem _chatSystem = default!; [Dependency] private readonly ClimbSystem _climb = default!; [Dependency] private readonly ContainerSystem _container = default!; [Dependency] private readonly GhostSystem _ghostSystem = default!; [Dependency] private readonly HandsSystem _hands = default!; [Dependency] private readonly ServerInventorySystem _inventory = default!; [Dependency] private readonly PopupSystem _popup = default!; [Dependency] private readonly StationSystem _station = default!; [Dependency] private readonly StationJobsSystem _stationJobs = default!; [Dependency] private readonly StationRecordsSystem _stationRecords = default!; [Dependency] private readonly TransformSystem _transform = default!; [Dependency] private readonly UserInterfaceSystem _ui = default!; /// <inheritdoc/> public override void Initialize() { base.Initialize(); SubscribeLocalEvent<CryostorageComponent, BeforeActivatableUIOpenEvent>(OnBeforeUIOpened); SubscribeLocalEvent<CryostorageComponent, CryostorageRemoveItemBuiMessage>(OnRemoveItemBuiMessage); SubscribeLocalEvent<CryostorageContainedComponent, PlayerSpawnCompleteEvent>(OnPlayerSpawned); SubscribeLocalEvent<CryostorageContainedComponent, MindRemovedMessage>(OnMindRemoved); _playerManager.PlayerStatusChanged += PlayerStatusChanged; } public override void Shutdown() { base.Shutdown(); _playerManager.PlayerStatusChanged -= PlayerStatusChanged; } private void OnBeforeUIOpened(Entity<CryostorageComponent> ent, ref BeforeActivatableUIOpenEvent args) { UpdateCryostorageUIState(ent); } private void OnRemoveItemBuiMessage(Entity<CryostorageComponent> ent, ref CryostorageRemoveItemBuiMessage args) { var (_, comp) = ent; var attachedEntity = args.Actor; var cryoContained = GetEntity(args.StoredEntity); if (!comp.StoredPlayers.Contains(cryoContained) || !IsInPausedMap(cryoContained)) return; if (!HasComp<HandsComponent>(attachedEntity)) return; if (!_accessReader.IsAllowed(attachedEntity, ent)) { _popup.PopupEntity(Loc.GetString("cryostorage-popup-access-denied"), attachedEntity, attachedEntity); return; } EntityUid? entity = null; if (args.Type == CryostorageRemoveItemBuiMessage.RemovalType.Hand) { entity = _hands.GetHeldItem(cryoContained, args.Key); } else { if (_inventory.TryGetSlotContainer(cryoContained, args.Key, out var slot, out _)) entity = slot.ContainedEntity; } if (entity == null) return; AdminLog.Add(LogType.Action, LogImpact.High, $"{ToPrettyString(attachedEntity):player} removed item {ToPrettyString(entity)} from cryostorage-contained player " + $"{ToPrettyString(cryoContained):player}, stored in cryostorage {ToPrettyString(ent)}"); _container.TryRemoveFromContainer(entity.Value); _transform.SetCoordinates(entity.Value, Transform(attachedEntity).Coordinates); _hands.PickupOrDrop(attachedEntity, entity.Value); UpdateCryostorageUIState(ent); } private void UpdateCryostorageUIState(Entity<CryostorageComponent> ent) { var state = new CryostorageBuiState(GetAllContainedData(ent)); _ui.SetUiState(ent.Owner, CryostorageUIKey.Key, state); } private void OnPlayerSpawned(Entity<CryostorageContainedComponent> ent, ref PlayerSpawnCompleteEvent args) { // if you spawned into cryostorage, we're not gonna round-remove you. ent.Comp.GracePeriodEndTime = null; } private void OnMindRemoved(Entity<CryostorageContainedComponent> ent, ref MindRemovedMessage args) { var comp = ent.Comp; if (!TryComp<CryostorageComponent>(comp.Cryostorage, out var cryostorageComponent)) return; if (comp.GracePeriodEndTime != null) comp.GracePeriodEndTime = Timing.CurTime + cryostorageComponent.NoMindGracePeriod; comp.AllowReEnteringBody = false; comp.UserId = args.Mind.Comp.UserId; } private void PlayerStatusChanged(object? sender, SessionStatusEventArgs args) { if (args.Session.AttachedEntity is not { } entity) return; if (!TryComp<CryostorageContainedComponent>(entity, out var containedComponent)) return; if (args.NewStatus is SessionStatus.Disconnected or SessionStatus.Zombie) { containedComponent.AllowReEnteringBody = true; var delay = CompOrNull<CryostorageComponent>(containedComponent.Cryostorage)?.NoMindGracePeriod ?? TimeSpan.Zero; containedComponent.GracePeriodEndTime = Timing.CurTime + delay; containedComponent.UserId = args.Session.UserId; } else if (args.NewStatus == SessionStatus.InGame) { HandleCryostorageReconnection((entity, containedComponent)); } } public void HandleEnterCryostorage(Entity<CryostorageContainedComponent> ent, NetUserId? userId) { var comp = ent.Comp; var cryostorageEnt = ent.Comp.Cryostorage; var station = _station.GetOwningStation(ent); var name = Name(ent.Owner); if (!TryComp<CryostorageComponent>(cryostorageEnt, out var cryostorageComponent)) return; // if we have a session, we use that to add back in all the job slots the player had. if (userId != null) { foreach (var uniqueStation in _station.GetStationsSet()) { if (!TryComp<StationJobsComponent>(uniqueStation, out var stationJobs)) continue; if (!_stationJobs.TryGetPlayerJobs(uniqueStation, userId.Value, out var jobs, stationJobs)) continue; foreach (var job in jobs) { _stationJobs.TryAdjustJobSlot(uniqueStation, job, 1, clamp: true); } _stationJobs.TryRemovePlayerJobs(uniqueStation, userId.Value, stationJobs); } } _audio.PlayPvs(cryostorageComponent.RemoveSound, ent); EnsurePausedMap(); if (PausedMap == null) { Log.Error("CryoSleep map was unexpectedly null"); return; } if (!CryoSleepRejoiningEnabled || !comp.AllowReEnteringBody) { if (userId != null && Mind.TryGetMind(userId.Value, out var mind) && HasComp<CryostorageContainedComponent>(mind.Value.Comp.CurrentEntity)) { _ghostSystem.OnGhostAttempt(mind.Value, false); } } comp.AllowReEnteringBody = false; _transform.SetParent(ent, PausedMap.Value); cryostorageComponent.StoredPlayers.Add(ent); Dirty(ent, comp); UpdateCryostorageUIState((cryostorageEnt.Value, cryostorageComponent)); AdminLog.Add(LogType.Action, LogImpact.High, $"{ToPrettyString(ent):player} was entered into cryostorage inside of {ToPrettyString(cryostorageEnt.Value)}"); if (!TryComp<StationRecordsComponent>(station, out var stationRecords)) return; var jobName = Loc.GetString("earlyleave-cryo-job-unknown"); var recordId = _stationRecords.GetRecordByName(station.Value, name); if (recordId != null) { var key = new StationRecordKey(recordId.Value, station.Value); if (_stationRecords.TryGetRecord<GeneralStationRecord>(key, out var entry, stationRecords)) jobName = entry.JobTitle; _stationRecords.RemoveRecord(key, stationRecords); } _chatSystem.DispatchStationAnnouncement(station.Value, Loc.GetString( "earlyleave-cryo-announcement", ("character", name), ("entity", ent.Owner), // gender things for supporting downstreams with other languages ("job", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(jobName)) ), Loc.GetString("earlyleave-cryo-sender"), playDefaultSound: false ); } private void HandleCryostorageReconnection(Entity<CryostorageContainedComponent> entity) { var (uid, comp) = entity; if (!CryoSleepRejoiningEnabled || !IsInPausedMap(uid)) return; // how did you destroy these? they're indestructible. if (comp.Cryostorage is not { } cryostorage || TerminatingOrDeleted(cryostorage) || !TryComp<CryostorageComponent>(cryostorage, out var cryostorageComponent)) { QueueDel(entity); return; } var cryoXform = Transform(cryostorage); _transform.SetParent(uid, cryoXform.ParentUid); _transform.SetCoordinates(uid, cryoXform.Coordinates); if (!_container.TryGetContainer(cryostorage, cryostorageComponent.ContainerId, out var container) || !_container.Insert(uid, container, cryoXform)) { _climb.ForciblySetClimbing(uid, cryostorage); } comp.GracePeriodEndTime = null; cryostorageComponent.StoredPlayers.Remove(uid); AdminLog.Add(LogType.Action, LogImpact.High, $"{ToPrettyString(entity):player} re-entered the game from cryostorage {ToPrettyString(cryostorage)}"); UpdateCryostorageUIState((cryostorage, cryostorageComponent)); } protected override void OnInsertedContainer(Entity<CryostorageComponent> ent, ref EntInsertedIntoContainerMessage args) { var (uid, comp) = ent; if (args.Container.ID != comp.ContainerId) return; base.OnInsertedContainer(ent, ref args); var locKey = CryoSleepRejoiningEnabled ? "cryostorage-insert-message-temp" : "cryostorage-insert-message-permanent"; var msg = Loc.GetString(locKey, ("time", comp.GracePeriod.TotalMinutes)); if (TryComp<ActorComponent>(args.Entity, out var actor)) _chatManager.ChatMessageToOne(ChatChannel.Server, msg, msg, uid, false, actor.PlayerSession.Channel); } private List<CryostorageContainedPlayerData> GetAllContainedData(Entity<CryostorageComponent> ent) { var data = new List<CryostorageContainedPlayerData>(); data.EnsureCapacity(ent.Comp.StoredPlayers.Count); foreach (var contained in ent.Comp.StoredPlayers) { data.Add(GetContainedData(contained)); } return data; } private CryostorageContainedPlayerData GetContainedData(EntityUid uid) { var data = new CryostorageContainedPlayerData(); data.PlayerName = Name(uid); data.PlayerEnt = GetNetEntity(uid); var enumerator = _inventory.GetSlotEnumerator(uid); while (enumerator.NextItem(out var item, out var slotDef)) { data.ItemSlots.Add(slotDef.Name, Name(item)); } foreach (var hand in _hands.EnumerateHands(uid)) { if (!_hands.TryGetHeldItem(uid, hand, out var heldEntity)) continue; data.HeldItems.Add(hand, Name(heldEntity.Value)); } return data; } public override void Update(float frameTime) { base.Update(frameTime); var query = EntityQueryEnumerator<CryostorageContainedComponent>(); while (query.MoveNext(out var uid, out var containedComp)) { if (containedComp.GracePeriodEndTime == null) continue; if (Timing.CurTime < containedComp.GracePeriodEndTime) continue; Mind.TryGetMind(uid, out _, out var mindComp); var id = mindComp?.UserId ?? containedComp.UserId; HandleEnterCryostorage((uid, containedComp), id); } } }
0
0.965287
1
0.965287
game-dev
MEDIA
0.912443
game-dev
0.92553
1
0.92553
PrimeSonic/PrimeSonicSubnauticaMods
1,877
CyclopsSolarUpgrades/Craftables/CyclopsSolarCharger.cs
namespace CyclopsSolarUpgrades.Craftables { using System.IO; using System.Reflection; using MoreCyclopsUpgrades.API; using MoreCyclopsUpgrades.API.Upgrades; using SMLHelper.V2.Crafting; using SMLHelper.V2.Handlers; internal class CyclopsSolarCharger : CyclopsUpgrade { private const string MaxSolarReachedKey = "MaxSolarMsg"; internal static string MaxSolarReached() { return Language.main.Get(MaxSolarReachedKey); } public CyclopsSolarCharger() : base("CyclopsSolarCharger", "Cyclops Solar Charger", "Recharges the Cyclops power cells while in sunlight.\nStacks with other solar chargers.") { OnFinishedPatching += () => { LanguageHandler.SetLanguageLine(MaxSolarReachedKey, "Max number of solar chargers reached."); }; } public override CraftTree.Type FabricatorType { get; } = CraftTree.Type.CyclopsFabricator; public override string AssetsFolder => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets"); public override string[] StepsToFabricatorTab { get; } = MCUServices.CrossMod.StepsToCyclopsModulesTabInCyclopsFabricator; public override TechType RequiredForUnlock { get; } = TechType.SeamothSolarCharge; protected override TechData GetBlueprintRecipe() { return new TechData() { craftAmount = 1, Ingredients = { new Ingredient(TechType.AdvancedWiringKit, 1), new Ingredient(TechType.Glass, 1), new Ingredient(TechType.EnameledGlass, 1), new Ingredient(TechType.Titanium, 1), } }; } } }
0
0.801225
1
0.801225
game-dev
MEDIA
0.925116
game-dev
0.908043
1
0.908043
QuangHaiNguyen/Oscilloscope_STM32F746
3,540
oscilloscope/Middlewares/ST/touchgfx/framework/include/touchgfx/transitions/Transition.hpp
/****************************************************************************** * Copyright (c) 2018(-2023) STMicroelectronics. * All rights reserved. * * This file is part of the TouchGFX 4.22.1 distribution. * * This software is licensed under terms that can be found in the LICENSE file in * the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * *******************************************************************************/ /** * @file touchgfx/transitions/Transition.hpp * * Declares the touchgfx::Transition class. */ #ifndef TOUCHGFX_TRANSITION_HPP #define TOUCHGFX_TRANSITION_HPP #include <touchgfx/Application.hpp> #include <touchgfx/containers/Container.hpp> #include <touchgfx/hal/Types.hpp> #include <touchgfx/widgets/Widget.hpp> namespace touchgfx { /** * The Transition class is the base class for Transitions. Implementations of Transition defines * what happens when transitioning between Screens, which typically involves visual * effects. An example of a transition implementation can be seen in example * custom_transition_example. The most basic transition is the NoTransition class that * does a transition without any visual effects. * * @see NoTransition, SlideTransition */ class Transition { public: /** Initializes a new instance of the Transition class. */ Transition() : screenContainer(0), done(false) { } /** Finalizes an instance of the Transition class. */ virtual ~Transition() { } /** Called for every tick when transitioning. */ virtual void handleTickEvent() { } /** * Query if the transition is done transitioning. It is the responsibility of the * inheriting class to set the underlying done flag once the transition has been * completed. * * @return True if the transition is done, false otherwise. */ bool isDone() const { return done; } /** * Tears down the Animation. Called before the destructor is called, when the * application changes the transition. */ virtual void tearDown() { } /** * Initializes the transition. Called after the constructor is called, when the * application changes the transition. */ virtual void init() { } /** * Invalidates the screen when starting the Transition. Default is * to invalidate the whole screen. Subclasses can do partial * invalidation. */ virtual void invalidate() { Application::getInstance()->invalidate(); } /** * Sets the Screen Container. Is used by Screen to enable the transition to access the * Container. * * @param [in] cont The Container the transition should have access to. */ virtual void setScreenContainer(Container& cont) { screenContainer = &cont; } protected: /** * A Widget that reports solid and but does not draw anything. */ class FullSolidRect : public Widget { public: virtual Rect getSolidRect() const { return Rect(0, 0, rect.width, rect.height); } virtual void draw(const Rect& area) const { } }; Container* screenContainer; ///< The screen Container of the Screen transitioning to. bool done; ///< Flag that indicates when the transition is done. This should be set by implementing classes. }; } // namespace touchgfx #endif // TOUCHGFX_TRANSITION_HPP
0
0.789525
1
0.789525
game-dev
MEDIA
0.231139
game-dev
0.554639
1
0.554639
danielah05/UndertaleDecomp
1,482
objects/obj_alabdoor_l/Draw_0.gml
if (side == 0) { if (active == true) { if instance_exists(obj_mainchara) { if (distance_to_object(obj_mainchara) < 40) { if (open == 0) caster_play(snd_elecdoor_open, 1, 1) open = 1 } if (distance_to_object(obj_mainchara) > 50) { if (open == 1) caster_play(snd_elecdoor_close, 1, 1) open = 0 } } } if (open == -1) open = 0 if (doorx < 7) draw_sprite_part(spr_alabdoor_piece, 0, 0, 0, (8 - doorx), 61, x, (y + 4)) if (doorx < 7) draw_sprite_part(spr_alabdoor_piece, 0, doorx, 0, (8 - doorx), 61, ((x + 6) + doorx), (y + 10)) if (open == 1) { if (doorx < 8) doorx += 1 } if (open == 0) { if (doorx > 0) doorx -= 1 } draw_sprite(spr_labdoor_hang, 0, x, y) } if (side == 1) { if (active == true) { if instance_exists(obj_mainchara) { if (distance_to_object(obj_mainchara) < 30) { if (open == 0) caster_play(snd_elecdoor_open, 1, 1) open = 1 } if (distance_to_object(obj_mainchara) > 50) { if (open == 1) caster_play(snd_elecdoor_close, 1, 1) open = 0 } } } if (open == -1) open = 0 if (doorx < 7) draw_sprite_part(spr_alabdoor_piece_r, 0, 0, 0, (8 - doorx), 61, (x + 19), (y + 10)) if (doorx < 7) draw_sprite_part(spr_alabdoor_piece_r, 0, doorx, 0, (8 - doorx), 61, ((x + 25) + doorx), (y + 4)) if (open == 1) { if (doorx < 8) doorx += 1 } if (open == 0) { if (doorx > 0) doorx -= 1 } draw_sprite(spr_labdoor_hang_r, 0, x, y) }
0
0.86494
1
0.86494
game-dev
MEDIA
0.940311
game-dev
0.823622
1
0.823622
bizzancoin/egret-H5-qipai-game
13,882
h5-admin/huohua-admin/src/main/java/com/idealighter/game/dao/dic/po/WknhRoom.java
package com.idealighter.game.dao.dic.po; import java.io.Serializable; import java.util.Date; /** * @author */ public class WknhRoom implements Serializable { /** * 房间id */ private Integer id; /** * 房间名称 */ private String name; /** * 平台类型(1是,0否) */ private Integer phone; /** * 房间类型(jcby_room_type) */ private Integer type; /** * 鱼的场景 */ private String scences; /** * 李逵的fishId */ private Integer likui; /** * 每次兑换鱼币的金币数量 */ private Integer exchangeper; /** * 能量炮出现倍率 */ private Integer powerbatterymultiple; /** * 能量炮出现概率(万分比) */ private Integer powerbatterypro; /** * 能量炮时间(秒) */ private Integer powerbatterytime; /** * 房间最大人数 */ private Integer maxnum; /** * 空闲状态人数 */ private Integer free; /** * 普通状态人数 */ private Integer general; /** * 拥挤状态人数 */ private Integer crowded; /** * 进入下限 */ private Integer lower; /** * 进入上限 */ private Integer upper; /** * 普通玩家进入人数百分比 */ private Integer ordinarpeople; /** * 金币与筹码比例(金币) */ private Integer proportiongold; /** * 金币与筹码比例(筹码) */ private Integer proportionchips; /** * 桌子数 */ private Integer table; /** * 每桌椅子数 */ private Integer chair; /** * 台费(进桌扣一次) */ private Integer afee; /** * 进入类型(0点击入座,1自动分配) */ private Integer intype; /** * 客户端展示的属性列信息 */ private String displays; /** * 客户端展示的属性列信息占位符 */ private String placeholder; /** * 状态(0:关闭,1:开启) */ private Byte isactive; /** * 创建时间 */ private Date timecreate; /** * 开启时间 */ private Date timeopen; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPhone() { return phone; } public void setPhone(Integer phone) { this.phone = phone; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getScences() { return scences; } public void setScences(String scences) { this.scences = scences; } public Integer getLikui() { return likui; } public void setLikui(Integer likui) { this.likui = likui; } public Integer getExchangeper() { return exchangeper; } public void setExchangeper(Integer exchangeper) { this.exchangeper = exchangeper; } public Integer getPowerbatterymultiple() { return powerbatterymultiple; } public void setPowerbatterymultiple(Integer powerbatterymultiple) { this.powerbatterymultiple = powerbatterymultiple; } public Integer getPowerbatterypro() { return powerbatterypro; } public void setPowerbatterypro(Integer powerbatterypro) { this.powerbatterypro = powerbatterypro; } public Integer getPowerbatterytime() { return powerbatterytime; } public void setPowerbatterytime(Integer powerbatterytime) { this.powerbatterytime = powerbatterytime; } public Integer getMaxnum() { return maxnum; } public void setMaxnum(Integer maxnum) { this.maxnum = maxnum; } public Integer getFree() { return free; } public void setFree(Integer free) { this.free = free; } public Integer getGeneral() { return general; } public void setGeneral(Integer general) { this.general = general; } public Integer getCrowded() { return crowded; } public void setCrowded(Integer crowded) { this.crowded = crowded; } public Integer getLower() { return lower; } public void setLower(Integer lower) { this.lower = lower; } public Integer getUpper() { return upper; } public void setUpper(Integer upper) { this.upper = upper; } public Integer getOrdinarpeople() { return ordinarpeople; } public void setOrdinarpeople(Integer ordinarpeople) { this.ordinarpeople = ordinarpeople; } public Integer getProportiongold() { return proportiongold; } public void setProportiongold(Integer proportiongold) { this.proportiongold = proportiongold; } public Integer getProportionchips() { return proportionchips; } public void setProportionchips(Integer proportionchips) { this.proportionchips = proportionchips; } public Integer getTable() { return table; } public void setTable(Integer table) { this.table = table; } public Integer getChair() { return chair; } public void setChair(Integer chair) { this.chair = chair; } public Integer getAfee() { return afee; } public void setAfee(Integer afee) { this.afee = afee; } public Integer getIntype() { return intype; } public void setIntype(Integer intype) { this.intype = intype; } public String getDisplays() { return displays; } public void setDisplays(String displays) { this.displays = displays; } public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public Byte getIsactive() { return isactive; } public void setIsactive(Byte isactive) { this.isactive = isactive; } public Date getTimecreate() { return timecreate; } public void setTimecreate(Date timecreate) { this.timecreate = timecreate; } public Date getTimeopen() { return timeopen; } public void setTimeopen(Date timeopen) { this.timeopen = timeopen; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } WknhRoom other = (WknhRoom) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType())) && (this.getScences() == null ? other.getScences() == null : this.getScences().equals(other.getScences())) && (this.getLikui() == null ? other.getLikui() == null : this.getLikui().equals(other.getLikui())) && (this.getExchangeper() == null ? other.getExchangeper() == null : this.getExchangeper().equals(other.getExchangeper())) && (this.getPowerbatterymultiple() == null ? other.getPowerbatterymultiple() == null : this.getPowerbatterymultiple().equals(other.getPowerbatterymultiple())) && (this.getPowerbatterypro() == null ? other.getPowerbatterypro() == null : this.getPowerbatterypro().equals(other.getPowerbatterypro())) && (this.getPowerbatterytime() == null ? other.getPowerbatterytime() == null : this.getPowerbatterytime().equals(other.getPowerbatterytime())) && (this.getMaxnum() == null ? other.getMaxnum() == null : this.getMaxnum().equals(other.getMaxnum())) && (this.getFree() == null ? other.getFree() == null : this.getFree().equals(other.getFree())) && (this.getGeneral() == null ? other.getGeneral() == null : this.getGeneral().equals(other.getGeneral())) && (this.getCrowded() == null ? other.getCrowded() == null : this.getCrowded().equals(other.getCrowded())) && (this.getLower() == null ? other.getLower() == null : this.getLower().equals(other.getLower())) && (this.getUpper() == null ? other.getUpper() == null : this.getUpper().equals(other.getUpper())) && (this.getOrdinarpeople() == null ? other.getOrdinarpeople() == null : this.getOrdinarpeople().equals(other.getOrdinarpeople())) && (this.getProportiongold() == null ? other.getProportiongold() == null : this.getProportiongold().equals(other.getProportiongold())) && (this.getProportionchips() == null ? other.getProportionchips() == null : this.getProportionchips().equals(other.getProportionchips())) && (this.getTable() == null ? other.getTable() == null : this.getTable().equals(other.getTable())) && (this.getChair() == null ? other.getChair() == null : this.getChair().equals(other.getChair())) && (this.getAfee() == null ? other.getAfee() == null : this.getAfee().equals(other.getAfee())) && (this.getIntype() == null ? other.getIntype() == null : this.getIntype().equals(other.getIntype())) && (this.getDisplays() == null ? other.getDisplays() == null : this.getDisplays().equals(other.getDisplays())) && (this.getPlaceholder() == null ? other.getPlaceholder() == null : this.getPlaceholder().equals(other.getPlaceholder())) && (this.getIsactive() == null ? other.getIsactive() == null : this.getIsactive().equals(other.getIsactive())) && (this.getTimecreate() == null ? other.getTimecreate() == null : this.getTimecreate().equals(other.getTimecreate())) && (this.getTimeopen() == null ? other.getTimeopen() == null : this.getTimeopen().equals(other.getTimeopen())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getType() == null) ? 0 : getType().hashCode()); result = prime * result + ((getScences() == null) ? 0 : getScences().hashCode()); result = prime * result + ((getLikui() == null) ? 0 : getLikui().hashCode()); result = prime * result + ((getExchangeper() == null) ? 0 : getExchangeper().hashCode()); result = prime * result + ((getPowerbatterymultiple() == null) ? 0 : getPowerbatterymultiple().hashCode()); result = prime * result + ((getPowerbatterypro() == null) ? 0 : getPowerbatterypro().hashCode()); result = prime * result + ((getPowerbatterytime() == null) ? 0 : getPowerbatterytime().hashCode()); result = prime * result + ((getMaxnum() == null) ? 0 : getMaxnum().hashCode()); result = prime * result + ((getFree() == null) ? 0 : getFree().hashCode()); result = prime * result + ((getGeneral() == null) ? 0 : getGeneral().hashCode()); result = prime * result + ((getCrowded() == null) ? 0 : getCrowded().hashCode()); result = prime * result + ((getLower() == null) ? 0 : getLower().hashCode()); result = prime * result + ((getUpper() == null) ? 0 : getUpper().hashCode()); result = prime * result + ((getOrdinarpeople() == null) ? 0 : getOrdinarpeople().hashCode()); result = prime * result + ((getProportiongold() == null) ? 0 : getProportiongold().hashCode()); result = prime * result + ((getProportionchips() == null) ? 0 : getProportionchips().hashCode()); result = prime * result + ((getTable() == null) ? 0 : getTable().hashCode()); result = prime * result + ((getChair() == null) ? 0 : getChair().hashCode()); result = prime * result + ((getAfee() == null) ? 0 : getAfee().hashCode()); result = prime * result + ((getIntype() == null) ? 0 : getIntype().hashCode()); result = prime * result + ((getDisplays() == null) ? 0 : getDisplays().hashCode()); result = prime * result + ((getPlaceholder() == null) ? 0 : getPlaceholder().hashCode()); result = prime * result + ((getIsactive() == null) ? 0 : getIsactive().hashCode()); result = prime * result + ((getTimecreate() == null) ? 0 : getTimecreate().hashCode()); result = prime * result + ((getTimeopen() == null) ? 0 : getTimeopen().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", phone=").append(phone); sb.append(", type=").append(type); sb.append(", scences=").append(scences); sb.append(", likui=").append(likui); sb.append(", exchangeper=").append(exchangeper); sb.append(", powerbatterymultiple=").append(powerbatterymultiple); sb.append(", powerbatterypro=").append(powerbatterypro); sb.append(", powerbatterytime=").append(powerbatterytime); sb.append(", maxnum=").append(maxnum); sb.append(", free=").append(free); sb.append(", general=").append(general); sb.append(", crowded=").append(crowded); sb.append(", lower=").append(lower); sb.append(", upper=").append(upper); sb.append(", ordinarpeople=").append(ordinarpeople); sb.append(", proportiongold=").append(proportiongold); sb.append(", proportionchips=").append(proportionchips); sb.append(", table=").append(table); sb.append(", chair=").append(chair); sb.append(", afee=").append(afee); sb.append(", intype=").append(intype); sb.append(", displays=").append(displays); sb.append(", placeholder=").append(placeholder); sb.append(", isactive=").append(isactive); sb.append(", timecreate=").append(timecreate); sb.append(", timeopen=").append(timeopen); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
0
0.65548
1
0.65548
game-dev
MEDIA
0.489689
game-dev
0.856762
1
0.856762
fr1tz/terminal-overload
4,483
Engine/lib/bullet/src/BulletCollision/NarrowPhaseCollision/btManifoldPoint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_MANIFOLD_CONTACT_POINT_H #define BT_MANIFOLD_CONTACT_POINT_H #include "LinearMath/btVector3.h" #include "LinearMath/btTransformUtil.h" #ifdef PFX_USE_FREE_VECTORMATH #include "physics_effects/base_level/solver/pfx_constraint_row.h" typedef sce::PhysicsEffects::PfxConstraintRow btConstraintRow; #else // Don't change following order of parameters ATTRIBUTE_ALIGNED16(struct) btConstraintRow { btScalar m_normal[3]; btScalar m_rhs; btScalar m_jacDiagInv; btScalar m_lowerLimit; btScalar m_upperLimit; btScalar m_accumImpulse; }; typedef btConstraintRow PfxConstraintRow; #endif //PFX_USE_FREE_VECTORMATH /// ManifoldContactPoint collects and maintains persistent contactpoints. /// used to improve stability and performance of rigidbody dynamics response. class btManifoldPoint { public: btManifoldPoint() :m_userPersistentData(0), m_lateralFrictionInitialized(false), m_appliedImpulse(0.f), m_appliedImpulseLateral1(0.f), m_appliedImpulseLateral2(0.f), m_contactMotion1(0.f), m_contactMotion2(0.f), m_contactCFM1(0.f), m_contactCFM2(0.f), m_lifeTime(0) { } btManifoldPoint( const btVector3 &pointA, const btVector3 &pointB, const btVector3 &normal, btScalar distance ) : m_localPointA( pointA ), m_localPointB( pointB ), m_normalWorldOnB( normal ), m_distance1( distance ), m_combinedFriction(btScalar(0.)), m_combinedRollingFriction(btScalar(0.)), m_combinedRestitution(btScalar(0.)), m_userPersistentData(0), m_lateralFrictionInitialized(false), m_appliedImpulse(0.f), m_appliedImpulseLateral1(0.f), m_appliedImpulseLateral2(0.f), m_contactMotion1(0.f), m_contactMotion2(0.f), m_contactCFM1(0.f), m_contactCFM2(0.f), m_lifeTime(0) { } btVector3 m_localPointA; btVector3 m_localPointB; btVector3 m_positionWorldOnB; ///m_positionWorldOnA is redundant information, see getPositionWorldOnA(), but for clarity btVector3 m_positionWorldOnA; btVector3 m_normalWorldOnB; btScalar m_distance1; btScalar m_combinedFriction; btScalar m_combinedRollingFriction; btScalar m_combinedRestitution; //BP mod, store contact triangles. int m_partId0; int m_partId1; int m_index0; int m_index1; mutable void* m_userPersistentData; bool m_lateralFrictionInitialized; btScalar m_appliedImpulse; btScalar m_appliedImpulseLateral1; btScalar m_appliedImpulseLateral2; btScalar m_contactMotion1; btScalar m_contactMotion2; btScalar m_contactCFM1; btScalar m_contactCFM2; int m_lifeTime;//lifetime of the contactpoint in frames btVector3 m_lateralFrictionDir1; btVector3 m_lateralFrictionDir2; btScalar getDistance() const { return m_distance1; } int getLifeTime() const { return m_lifeTime; } const btVector3& getPositionWorldOnA() const { return m_positionWorldOnA; // return m_positionWorldOnB + m_normalWorldOnB * m_distance1; } const btVector3& getPositionWorldOnB() const { return m_positionWorldOnB; } void setDistance(btScalar dist) { m_distance1 = dist; } ///this returns the most recent applied impulse, to satisfy contact constraints by the constraint solver btScalar getAppliedImpulse() const { return m_appliedImpulse; } }; #endif //BT_MANIFOLD_CONTACT_POINT_H
0
0.836315
1
0.836315
game-dev
MEDIA
0.986196
game-dev
0.981673
1
0.981673
oot-pc-port/oot-pc-port
7,801
asm/non_matchings/overlays/actors/ovl_En_Dog/func_809FB6C4.s
glabel func_809FB6C4 /* 006F4 809FB6C4 27BDFFB0 */ addiu $sp, $sp, 0xFFB0 ## $sp = FFFFFFB0 /* 006F8 809FB6C8 3C0F80A0 */ lui $t7, %hi(D_809FC008) ## $t7 = 80A00000 /* 006FC 809FB6CC AFBF0024 */ sw $ra, 0x0024($sp) /* 00700 809FB6D0 AFB00020 */ sw $s0, 0x0020($sp) /* 00704 809FB6D4 AFA50054 */ sw $a1, 0x0054($sp) /* 00708 809FB6D8 25EFC008 */ addiu $t7, $t7, %lo(D_809FC008) ## $t7 = 809FC008 /* 0070C 809FB6DC 8DF90000 */ lw $t9, 0x0000($t7) ## 809FC008 /* 00710 809FB6E0 27AE0044 */ addiu $t6, $sp, 0x0044 ## $t6 = FFFFFFF4 /* 00714 809FB6E4 8DF80004 */ lw $t8, 0x0004($t7) ## 809FC00C /* 00718 809FB6E8 ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFFF4 /* 0071C 809FB6EC 8DF90008 */ lw $t9, 0x0008($t7) ## 809FC010 /* 00720 809FB6F0 3C0980A0 */ lui $t1, %hi(D_809FC014) ## $t1 = 80A00000 /* 00724 809FB6F4 2529C014 */ addiu $t1, $t1, %lo(D_809FC014) ## $t1 = 809FC014 /* 00728 809FB6F8 ADD80004 */ sw $t8, 0x0004($t6) ## FFFFFFF8 /* 0072C 809FB6FC ADD90008 */ sw $t9, 0x0008($t6) ## FFFFFFFC /* 00730 809FB700 8D2B0000 */ lw $t3, 0x0000($t1) ## 809FC014 /* 00734 809FB704 27A80038 */ addiu $t0, $sp, 0x0038 ## $t0 = FFFFFFE8 /* 00738 809FB708 8D2A0004 */ lw $t2, 0x0004($t1) ## 809FC018 /* 0073C 809FB70C AD0B0000 */ sw $t3, 0x0000($t0) ## FFFFFFE8 /* 00740 809FB710 8D2B0008 */ lw $t3, 0x0008($t1) ## 809FC01C /* 00744 809FB714 AD0A0004 */ sw $t2, 0x0004($t0) ## FFFFFFEC /* 00748 809FB718 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000 /* 0074C 809FB71C AD0B0008 */ sw $t3, 0x0008($t0) ## FFFFFFF0 /* 00750 809FB720 0C27ECA7 */ jal func_809FB29C /* 00754 809FB724 8FA50054 */ lw $a1, 0x0054($sp) /* 00758 809FB728 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001 /* 0075C 809FB72C 14410003 */ bne $v0, $at, .L809FB73C /* 00760 809FB730 3C0C80A0 */ lui $t4, %hi(func_809FB940) ## $t4 = 80A00000 /* 00764 809FB734 258CB940 */ addiu $t4, $t4, %lo(func_809FB940) ## $t4 = 809FB940 /* 00768 809FB738 AE0C0190 */ sw $t4, 0x0190($s0) ## 00000190 .L809FB73C: /* 0076C 809FB73C 860201EC */ lh $v0, 0x01EC($s0) ## 000001EC /* 00770 809FB740 26040068 */ addiu $a0, $s0, 0x0068 ## $a0 = 00000068 /* 00774 809FB744 3C063ECC */ lui $a2, 0x3ECC ## $a2 = 3ECC0000 /* 00778 809FB748 14400003 */ bne $v0, $zero, .L809FB758 /* 0077C 809FB74C 244DFFFF */ addiu $t5, $v0, 0xFFFF ## $t5 = FFFFFFFF /* 00780 809FB750 10000003 */ beq $zero, $zero, .L809FB760 /* 00784 809FB754 00001825 */ or $v1, $zero, $zero ## $v1 = 00000000 .L809FB758: /* 00788 809FB758 A60D01EC */ sh $t5, 0x01EC($s0) ## 000001EC /* 0078C 809FB75C 860301EC */ lh $v1, 0x01EC($s0) ## 000001EC .L809FB760: /* 00790 809FB760 10600028 */ beq $v1, $zero, .L809FB804 /* 00794 809FB764 8FAC0054 */ lw $t4, 0x0054($sp) /* 00798 809FB768 860E01F0 */ lh $t6, 0x01F0($s0) ## 000001F0 /* 0079C 809FB76C 44802000 */ mtc1 $zero, $f4 ## $f4 = 0.00 /* 007A0 809FB770 34C6CCCD */ ori $a2, $a2, 0xCCCD ## $a2 = 3ECCCCCD /* 007A4 809FB774 15C00005 */ bne $t6, $zero, .L809FB78C /* 007A8 809FB778 3C073F80 */ lui $a3, 0x3F80 ## $a3 = 3F800000 /* 007AC 809FB77C 3C013F80 */ lui $at, 0x3F80 ## $at = 3F800000 /* 007B0 809FB780 44810000 */ mtc1 $at, $f0 ## $f0 = 1.00 /* 007B4 809FB784 10000005 */ beq $zero, $zero, .L809FB79C /* 007B8 809FB788 44050000 */ mfc1 $a1, $f0 .L809FB78C: /* 007BC 809FB78C 3C014080 */ lui $at, 0x4080 ## $at = 40800000 /* 007C0 809FB790 44810000 */ mtc1 $at, $f0 ## $f0 = 4.00 /* 007C4 809FB794 00000000 */ nop /* 007C8 809FB798 44050000 */ mfc1 $a1, $f0 .L809FB79C: /* 007CC 809FB79C 0C01E0C4 */ jal Math_SmoothScaleMaxMinF /* 007D0 809FB7A0 E7A40010 */ swc1 $f4, 0x0010($sp) /* 007D4 809FB7A4 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000 /* 007D8 809FB7A8 0C27ECEB */ jal func_809FB3AC /* 007DC 809FB7AC 8FA50054 */ lw $a1, 0x0054($sp) /* 007E0 809FB7B0 8A180030 */ lwl $t8, 0x0030($s0) ## 00000030 /* 007E4 809FB7B4 9A180033 */ lwr $t8, 0x0033($s0) ## 00000033 /* 007E8 809FB7B8 861901E6 */ lh $t9, 0x01E6($s0) ## 000001E6 /* 007EC 809FB7BC 3C028016 */ lui $v0, 0x8016 ## $v0 = 80160000 /* 007F0 809FB7C0 AA1800B4 */ swl $t8, 0x00B4($s0) ## 000000B4 /* 007F4 809FB7C4 BA1800B7 */ swr $t8, 0x00B7($s0) ## 000000B7 /* 007F8 809FB7C8 96180034 */ lhu $t8, 0x0034($s0) ## 00000034 /* 007FC 809FB7CC 2B210009 */ slti $at, $t9, 0x0009 /* 00800 809FB7D0 10200007 */ beq $at, $zero, .L809FB7F0 /* 00804 809FB7D4 A61800B8 */ sh $t8, 0x00B8($s0) ## 000000B8 /* 00808 809FB7D8 3C028016 */ lui $v0, 0x8016 ## $v0 = 80160000 /* 0080C 809FB7DC 2442E660 */ addiu $v0, $v0, 0xE660 ## $v0 = 8015E660 /* 00810 809FB7E0 94481400 */ lhu $t0, 0x1400($v0) ## 8015FA60 /* 00814 809FB7E4 35090001 */ ori $t1, $t0, 0x0001 ## $t1 = 00000001 /* 00818 809FB7E8 10000016 */ beq $zero, $zero, .L809FB844 /* 0081C 809FB7EC A4491400 */ sh $t1, 0x1400($v0) ## 8015FA60 .L809FB7F0: /* 00820 809FB7F0 2442E660 */ addiu $v0, $v0, 0xE660 ## $v0 = 8015CCC0 /* 00824 809FB7F4 944A1400 */ lhu $t2, 0x1400($v0) ## 8015E0C0 /* 00828 809FB7F8 314BFFFE */ andi $t3, $t2, 0xFFFE ## $t3 = 00000000 /* 0082C 809FB7FC 10000011 */ beq $zero, $zero, .L809FB844 /* 00830 809FB800 A44B1400 */ sh $t3, 0x1400($v0) ## 8015E0C0 .L809FB804: /* 00834 809FB804 8D83009C */ lw $v1, 0x009C($t4) ## 0000009C /* 00838 809FB808 24010003 */ addiu $at, $zero, 0x0003 ## $at = 00000003 /* 0083C 809FB80C 27AE0044 */ addiu $t6, $sp, 0x0044 ## $t6 = FFFFFFF4 /* 00840 809FB810 0061001B */ divu $zero, $v1, $at /* 00844 809FB814 00001810 */ mfhi $v1 /* 00848 809FB818 00036880 */ sll $t5, $v1, 2 /* 0084C 809FB81C 01AE1021 */ addu $v0, $t5, $t6 /* 00850 809FB820 8C4F0000 */ lw $t7, 0x0000($v0) ## 8015CCC0 /* 00854 809FB824 2404003C */ addiu $a0, $zero, 0x003C ## $a0 = 0000003C /* 00858 809FB828 A60F01F0 */ sh $t7, 0x01F0($s0) ## 000001F0 /* 0085C 809FB82C 0C01DF64 */ jal Math_Rand_S16Offset /* 00860 809FB830 84450002 */ lh $a1, 0x0002($v0) ## 8015CCC2 /* 00864 809FB834 3C1880A0 */ lui $t8, %hi(func_809FB858) ## $t8 = 80A00000 /* 00868 809FB838 2718B858 */ addiu $t8, $t8, %lo(func_809FB858) ## $t8 = 809FB858 /* 0086C 809FB83C A60201EC */ sh $v0, 0x01EC($s0) ## 000001EC /* 00870 809FB840 AE180190 */ sw $t8, 0x0190($s0) ## 00000190 .L809FB844: /* 00874 809FB844 8FBF0024 */ lw $ra, 0x0024($sp) /* 00878 809FB848 8FB00020 */ lw $s0, 0x0020($sp) /* 0087C 809FB84C 27BD0050 */ addiu $sp, $sp, 0x0050 ## $sp = 00000000 /* 00880 809FB850 03E00008 */ jr $ra /* 00884 809FB854 00000000 */ nop
0
0.625051
1
0.625051
game-dev
MEDIA
0.985473
game-dev
0.515832
1
0.515832
Nebukam/PCGExtendedToolkit
16,686
Source/PCGExtendedToolkit/Private/AssetStaging/PCGExAssetStaging.cpp
// Copyright 2025 Timothé Lapetite and contributors // Released under the MIT license https://opensource.org/license/MIT/ #include "AssetStaging/PCGExAssetStaging.h" #include "PCGExRandom.h" #include "PCGExScopedContainers.h" #define LOCTEXT_NAMESPACE "PCGExAssetStagingElement" #define PCGEX_NAMESPACE AssetStaging PCGEX_INITIALIZE_ELEMENT(AssetStaging) PCGEX_ELEMENT_BATCH_POINT_IMPL(AssetStaging) TArray<FPCGPinProperties> UPCGExAssetStagingSettings::InputPinProperties() const { TArray<FPCGPinProperties> PinProperties = Super::InputPinProperties(); if (CollectionSource == EPCGExCollectionSource::AttributeSet) { PCGEX_PIN_PARAM(PCGExAssetCollection::SourceAssetCollection, "Attribute set to be used as collection.", Required) } return PinProperties; } TArray<FPCGPinProperties> UPCGExAssetStagingSettings::OutputPinProperties() const { TArray<FPCGPinProperties> PinProperties = Super::OutputPinProperties(); if (OutputMode == EPCGExStagingOutputMode::CollectionMap) { PCGEX_PIN_PARAM(PCGExStaging::OutputCollectionMapLabel, "Collection map generated by a staging node.", Normal) } if (bDoOutputSockets) { PCGEX_PIN_POINTS(PCGExStaging::OutputSocketLabel, "Socket points.", Normal) } return PinProperties; } bool FPCGExAssetStagingElement::Boot(FPCGExContext* InContext) const { if (!FPCGExPointsProcessorElement::Boot(InContext)) { return false; } PCGEX_CONTEXT_AND_SETTINGS(AssetStaging) if (Settings->bOutputMaterialPicks) { PCGEX_VALIDATE_NAME(Settings->MaterialAttributePrefix) Context->bPickMaterials = true; } if (Settings->CollectionSource == EPCGExCollectionSource::Asset) { Context->MainCollection = PCGExHelpers::LoadBlocking_AnyThread(Settings->AssetCollection); if (!Context->MainCollection) { PCGE_LOG(Error, GraphAndLog, FTEXT("Missing asset collection.")); return false; } } else { if (Settings->OutputMode == EPCGExStagingOutputMode::CollectionMap) { PCGE_LOG(Error, GraphAndLog, FTEXT("Collection Map output is not supported with collections built from attribute sets.")); return false; } Context->MainCollection = Settings->AttributeSetDetails.TryBuildCollection(Context, PCGExAssetCollection::SourceAssetCollection, false); if (!Context->MainCollection) { PCGE_LOG(Error, GraphAndLog, FTEXT("Failed to build collection from attribute set.")); return false; } } if (Context->bPickMaterials && Context->MainCollection->GetType() != PCGExAssetCollection::EType::Mesh) { Context->bPickMaterials = false; PCGE_LOG(Warning, GraphAndLog, FTEXT("Pick Material is set to true, but the selected collection doesn't support material picking.")); } PCGEX_VALIDATE_NAME(Settings->AssetPathAttributeName) if (Settings->WeightToAttribute == EPCGExWeightOutputMode::Raw || Settings->WeightToAttribute == EPCGExWeightOutputMode::Normalized) { PCGEX_VALIDATE_NAME_CONSUMABLE(Settings->WeightAttributeName) } if (Settings->OutputMode == EPCGExStagingOutputMode::CollectionMap) { Context->CollectionPickDatasetPacker = MakeShared<PCGExStaging::FPickPacker>(Context); } if (Settings->bDoOutputSockets) { PCGEX_FWD(OutputSocketDetails) if (!Context->OutputSocketDetails.Init(Context)) { return false; } Context->SocketsCollection = MakeShared<PCGExData::FPointIOCollection>(Context); Context->SocketsCollection->OutputPin = PCGExStaging::OutputSocketLabel; } return true; } void FPCGExAssetStagingContext::RegisterAssetDependencies() { FPCGExPointsProcessorContext::RegisterAssetDependencies(); PCGEX_SETTINGS_LOCAL(AssetStaging) if (Settings->CollectionSource == EPCGExCollectionSource::AttributeSet) { MainCollection->GetAssetPaths(GetRequiredAssets(), PCGExAssetCollection::ELoadingFlags::Recursive); } else { MainCollection->GetAssetPaths(GetRequiredAssets(), PCGExAssetCollection::ELoadingFlags::RecursiveCollectionsOnly); } } void FPCGExAssetStagingElement::PostLoadAssetsDependencies(FPCGExContext* InContext) const { FPCGExPointsProcessorElement::PostLoadAssetsDependencies(InContext); PCGEX_CONTEXT_AND_SETTINGS(AssetStaging) if (Settings->CollectionSource == EPCGExCollectionSource::AttributeSet) { // Internal collection, assets have been loaded at this point Context->MainCollection->RebuildStagingData(true); } } bool FPCGExAssetStagingElement::PostBoot(FPCGExContext* InContext) const { PCGEX_CONTEXT_AND_SETTINGS(AssetStaging) if (Context->MainCollection->LoadCache()->IsEmpty()) { if (!Settings->bQuietEmptyCollectionError) { PCGE_LOG_C(Error, GraphAndLog, Context, FTEXT("Selected asset collection is empty.")); } return false; } return FPCGExPointsProcessorElement::PostBoot(InContext); } bool FPCGExAssetStagingElement::ExecuteInternal(FPCGContext* InContext) const { TRACE_CPUPROFILER_EVENT_SCOPE(FPCGExAssetStagingElement::Execute); PCGEX_CONTEXT_AND_SETTINGS(AssetStaging) PCGEX_EXECUTION_CHECK PCGEX_ON_INITIAL_EXECUTION { if (!Context->StartBatchProcessingPoints( [&](const TSharedPtr<PCGExData::FPointIO>& Entry) { return true; }, [&](const TSharedPtr<PCGExPointsMT::IBatch>& NewBatch) { NewBatch->bRequiresWriteStep = Settings->bPruneEmptyPoints; })) { return Context->CancelExecution(TEXT("Could not find any points to process.")); } } PCGEX_POINTS_BATCH_PROCESSING(PCGExCommon::State_Done) Context->MainPoints->StageOutputs(); if (Settings->OutputMode == EPCGExStagingOutputMode::CollectionMap) { UPCGParamData* OutputSet = Context->ManagedObjects->New<UPCGParamData>(); Context->CollectionPickDatasetPacker->PackToDataset(OutputSet); FPCGTaggedData& OutData = Context->OutputData.TaggedData.Emplace_GetRef(); OutData.Pin = PCGExStaging::OutputCollectionMapLabel; OutData.Data = OutputSet; } if (Context->SocketsCollection) { Context->SocketsCollection->StageOutputs(); } return Context->TryComplete(); } bool FPCGExAssetStagingElement::CanExecuteOnlyOnMainThread(FPCGContext* Context) const { // Loading collection and/or creating one from attributes return Context ? Context->CurrentPhase == EPCGExecutionPhase::PrepareData : false; } namespace PCGExAssetStaging { bool FProcessor::Process(const TSharedPtr<PCGExMT::FTaskManager>& InAsyncManager) { TRACE_CPUPROFILER_EVENT_SCOPE(PCGExAssetStaging::Process); // Must be set before process for filters PointDataFacade->bSupportsScopedGet = Context->bScopedAttributeGet; if (!IProcessor::Process(InAsyncManager)) { return false; } PCGEX_INIT_IO(PointDataFacade->Source, PCGExData::EIOInit::Duplicate) NumPoints = PointDataFacade->GetNum(); if (Context->bPickMaterials) { CachedPicks.Init(nullptr, NumPoints); MaterialPick.Init(-1, NumPoints); } FittingHandler.ScaleToFit = Settings->ScaleToFit; FittingHandler.Justification = Settings->Justification; if (!FittingHandler.Init(ExecutionContext, PointDataFacade)) { return false; } Variations = Settings->Variations; Variations.Init(Settings->Seed); Helper = MakeShared<PCGExStaging::TDistributionHelper<UPCGExAssetCollection, FPCGExAssetCollectionEntry>>(Context->MainCollection, Settings->DistributionSettings); if (!Helper->Init(PointDataFacade)) { return false; } if (Settings->bDoOutputSockets) { SocketHelper = MakeShared<PCGExStaging::FSocketHelper>(&Context->OutputSocketDetails, NumPoints); } bOutputWeight = Settings->WeightToAttribute != EPCGExWeightOutputMode::NoOutput; bNormalizedWeight = Settings->WeightToAttribute != EPCGExWeightOutputMode::Raw; bOneMinusWeight = Settings->WeightToAttribute == EPCGExWeightOutputMode::NormalizedInverted || Settings->WeightToAttribute == EPCGExWeightOutputMode::NormalizedInvertedToDensity; if (Settings->WeightToAttribute == EPCGExWeightOutputMode::Raw) { WeightWriter = PointDataFacade->GetWritable<int32>(Settings->WeightAttributeName, PCGExData::EBufferInit::New); } else if (Settings->WeightToAttribute == EPCGExWeightOutputMode::Normalized) { NormalizedWeightWriter = PointDataFacade->GetWritable<double>(Settings->WeightAttributeName, PCGExData::EBufferInit::New); } if (Settings->OutputMode == EPCGExStagingOutputMode::Attributes) { bInherit = PointDataFacade->GetIn()->Metadata->HasAttribute(Settings->AssetPathAttributeName); PathWriter = PointDataFacade->GetWritable<FSoftObjectPath>(Settings->AssetPathAttributeName, bInherit ? PCGExData::EBufferInit::Inherit : PCGExData::EBufferInit::New); } else { bInherit = PointDataFacade->GetIn()->Metadata->HasAttribute(PCGExStaging::Tag_EntryIdx); HashWriter = PointDataFacade->GetWritable<int64>(PCGExStaging::Tag_EntryIdx, bInherit ? PCGExData::EBufferInit::Inherit : PCGExData::EBufferInit::New); } // Cherry pick native properties allocations EPCGPointNativeProperties AllocateFor = EPCGPointNativeProperties::None; AllocateFor |= EPCGPointNativeProperties::BoundsMin; AllocateFor |= EPCGPointNativeProperties::BoundsMax; AllocateFor |= EPCGPointNativeProperties::Transform; if (bOutputWeight && !WeightWriter && !NormalizedWeightWriter) { bUsesDensity = true; AllocateFor |= EPCGPointNativeProperties::Density; } PointDataFacade->GetOut()->AllocateProperties(AllocateFor); if (Settings->bPruneEmptyPoints) { Mask.Init(1, PointDataFacade->GetNum()); } StartParallelLoopForPoints(); return true; } void FProcessor::PrepareLoopScopesForPoints(const TArray<PCGExMT::FScope>& Loops) { HighestSlotIndex = MakeShared<PCGExMT::TScopedNumericValue<int8>>(Loops, -1); } void FProcessor::ProcessPoints(const PCGExMT::FScope& Scope) { TRACE_CPUPROFILER_EVENT_SCOPE(PCGEx::AssetStaging::ProcessPoints); PointDataFacade->Fetch(Scope); FilterScope(Scope); UPCGBasePointData* OutPointData = PointDataFacade->GetOut(); const TPCGValueRange<FTransform> OutTransforms = OutPointData->GetTransformValueRange(false); const TPCGValueRange<FVector> OutBoundsMin = OutPointData->GetBoundsMinValueRange(false); const TPCGValueRange<FVector> OutBoundsMax = OutPointData->GetBoundsMaxValueRange(false); const TConstPCGValueRange<int32> Seeds = OutPointData->GetConstSeedValueRange(); const TPCGValueRange<float> Densities = bUsesDensity ? OutPointData->GetDensityValueRange(false) : TPCGValueRange<float>(); int32 LocalNumInvalid = 0; auto InvalidPoint = [&](const int32 Index) { if (bInherit) { return; } if (Settings->bPruneEmptyPoints) { Mask[Index] = 0; LocalNumInvalid++; return; } if (PathWriter) { PathWriter->SetValue(Index, FSoftObjectPath{}); } else { HashWriter->SetValue(Index, -1); } if (bOutputWeight) { if (WeightWriter) { WeightWriter->SetValue(Index, -1); } else if (NormalizedWeightWriter) { NormalizedWeightWriter->SetValue(Index, -1); } } if (Context->bPickMaterials) { MaterialPick[Index] = -1; } }; const UPCGComponent* Component = Context->GetComponent(); PCGEX_SCOPE_LOOP(Index) { if (!PointFilterCache[Index]) { InvalidPoint(Index); continue; } FTransform& OutTransform = OutTransforms[Index]; const FPCGExAssetCollectionEntry* Entry = nullptr; const UPCGExAssetCollection* EntryHost = nullptr; const int32 Seed = PCGExRandom::GetSeed( Seeds[Index], Helper->Details.SeedComponents, Helper->Details.LocalSeed, Settings, Component); Helper->GetEntry(Entry, Index, Seed, EntryHost); if (!Entry || !Entry->Staging.Bounds.IsValid) { InvalidPoint(Index); continue; } int16 SecondaryIndex = -1; if (Entry->MicroCache && Entry->MicroCache->GetType() == PCGExAssetCollection::EType::Mesh) { TSharedPtr<PCGExMeshCollection::FMicroCache> EntryMicroCache = StaticCastSharedPtr<PCGExMeshCollection::FMicroCache>(Entry->MicroCache); if (Context->bPickMaterials) { MaterialPick[Index] = EntryMicroCache->GetPickRandomWeighted(Seed); HighestSlotIndex->Set(Scope, FMath::Max(FMath::Max(0, EntryMicroCache->GetHighestIndex()), HighestSlotIndex->Get(Scope))); CachedPicks[Index] = Entry; } else { SecondaryIndex = EntryMicroCache->GetPickRandomWeighted(Seed); } } else if (Context->bPickMaterials) { MaterialPick[Index] = -1; } if (bOutputWeight) { double Weight = bNormalizedWeight ? static_cast<double>(Entry->Weight) / static_cast<double>(Context->MainCollection->LoadCache()->WeightSum) : Entry->Weight; if (bOneMinusWeight) { Weight = 1 - Weight; } if (WeightWriter) { WeightWriter->SetValue(Index, Weight); } if (NormalizedWeightWriter) { NormalizedWeightWriter->SetValue(Index, Weight); } else { Densities[Index] = Weight; } } if (PathWriter) { PathWriter->SetValue(Index, Entry->Staging.Path); } else { HashWriter->SetValue(Index, Context->CollectionPickDatasetPacker->GetPickIdx(EntryHost, Entry->Staging.InternalIndex, SecondaryIndex)); } FBox OutBounds = Entry->Staging.Bounds; if (Variations.bEnabledBefore) { FTransform LocalXForm = FTransform::Identity; if (EntryHost->GlobalVariationMode == EPCGExGlobalVariationRule::Overrule || Entry->VariationMode == EPCGExEntryVariationMode::Global) { Variations.Apply(Seed, LocalXForm, EntryHost->GlobalVariations, EPCGExVariationMode::Before); } else { Variations.Apply(Seed, LocalXForm, Entry->Variations, EPCGExVariationMode::Before); } FittingHandler.ComputeLocalTransform(Index, LocalXForm, OutTransform, OutBounds); } else { FittingHandler.ComputeTransform(Index, OutTransform, OutBounds); } OutBoundsMin[Index] = OutBounds.Min; OutBoundsMax[Index] = OutBounds.Max; if (Variations.bEnabledAfter) { if (EntryHost->GlobalVariationMode == EPCGExGlobalVariationRule::Overrule || Entry->VariationMode == EPCGExEntryVariationMode::Global) { Variations.Apply(Seed, OutTransform, EntryHost->GlobalVariations, EPCGExVariationMode::After); } else { Variations.Apply(Seed, OutTransform, Entry->Variations, EPCGExVariationMode::After); } } if (SocketHelper) { // Register entry uint64 EntryHash = PCGEx::H64(EntryHost->GetUniqueID(), Entry->Staging.InternalIndex); SocketHelper->Add(Index, EntryHash, Entry); } } FPlatformAtomics::InterlockedAdd(&NumInvalid, LocalNumInvalid); } void FProcessor::CompleteWork() { if (SocketHelper) { SocketHelper->Compile(AsyncManager, PointDataFacade, Context->SocketsCollection); } if (Context->bPickMaterials) { int8 WriterCount = HighestSlotIndex->Max() + 1; if (Settings->MaxMaterialPicks > 0) { WriterCount = Settings->MaxMaterialPicks; } if (WriterCount > 0) { MaterialWriters.Init(nullptr, WriterCount); for (int i = 0; i < WriterCount; i++) { const FName AttributeName = FName(FString::Printf(TEXT("%s_%d"), *Settings->MaterialAttributePrefix.ToString(), i)); MaterialWriters[i] = PointDataFacade->GetWritable<FSoftObjectPath>(AttributeName, FSoftObjectPath(), true, PCGExData::EBufferInit::New); } StartParallelLoopForRange(NumPoints); return; } PCGE_LOG_C(Warning, GraphAndLog, Context, FTEXT("No material were picked -- no attribute will be written.")); } PointDataFacade->WriteFastest(AsyncManager); } void FProcessor::ProcessRange(const PCGExMT::FScope& Scope) { PCGEX_SCOPE_LOOP(Index) { const int32 Pick = MaterialPick[Index]; if (Pick == -1 || (Settings->bPruneEmptyPoints && !Mask[Index])) { continue; } const FPCGExMeshCollectionEntry* Entry = static_cast<const FPCGExMeshCollectionEntry*>(CachedPicks[Index]); if (Entry->MaterialVariants == EPCGExMaterialVariantsMode::None) { continue; } if (Entry->MaterialVariants == EPCGExMaterialVariantsMode::Single) { if (!MaterialWriters.IsValidIndex(Entry->SlotIndex)) { continue; } MaterialWriters[Entry->SlotIndex]->SetValue(Index, Entry->MaterialOverrideVariants[Pick].Material.ToSoftObjectPath()); } else if (Entry->MaterialVariants == EPCGExMaterialVariantsMode::Multi) { const FPCGExMaterialOverrideCollection& MEntry = Entry->MaterialOverrideVariantsList[Pick]; for (int i = 0; i < MEntry.Overrides.Num(); i++) { const FPCGExMaterialOverrideEntry& SlotEntry = MEntry.Overrides[i]; const int32 SlotIndex = SlotEntry.SlotIndex == -1 ? 0 : SlotEntry.SlotIndex; if (!MaterialWriters.IsValidIndex(SlotIndex)) { continue; } MaterialWriters[SlotIndex]->SetValue(Index, SlotEntry.Material.ToSoftObjectPath()); } } } } void FProcessor::OnRangeProcessingComplete() { PointDataFacade->WriteFastest(AsyncManager); } void FProcessor::Write() { (void)PointDataFacade->Source->Gather(Mask); } } #undef LOCTEXT_NAMESPACE #undef PCGEX_NAMESPACE
0
0.940504
1
0.940504
game-dev
MEDIA
0.640971
game-dev
0.774436
1
0.774436
ggnkua/Atari_ST_Sources
28,290
ASM/Persistence of Vision (POV)/POV93/source/POV93.S
opt o+,w- ************************************************************************* * P.O.V. 93 * * --------- * * * * Written By MACHINE SYSTEM DATA of PERSISTENCE OF VISION * * Date: 10/8/91 * * * * All code P.O.V. 1991 * * * ************************************************************************* BOB_DEPTH=72 ;bob depth in pixels BOB_WIDTH=9 ;bob width in words BORDER_COLOUR=0 ;Change this for border colours bsr set_super ;set supervisor mode move.l #go,$24.w go move.b #$12,$fffffc02.w ;Disable mouse bsr save_pal ;save old palette bsr get_base ;get present screen base bsr get_rez bsr black_out ;make all colours black bsr calc_screen ;calc our own screen address ;so we are not restricted ;to a fixed screen address ;512 + 1024K compatable move.l screen_1,a0 ;new screen base bsr set_low_rez ;go into low rez move.l screen_1,present_base move.l screen_2,last_base bsr shift_bob ;draw bob to screen and shift 16 times bsr clear_below_screen ;clear area below screen move.b $484,old484 ;save keyboard click/speed, etc clr.b $484 ;disable repeat/click/bell ;************************************************************************ ;* UNKNOWN * ;* ------- * ;* Stolen by: MAC SYS DATA of P.O.V. 14/08/91 19:45 * ;* From: AUTOMATION disc 474 * ;* Include files:- * ;* 474.IMG into TUNE * ;************************************************************************ ;* music by NIK ALDERTON ;**************************************************************** ; There is more than one tune in this code.... ; 0=off with music ; 1=tune 1 ; 2=tune 2 ; 3=tune 3 ; 4=sound effect ; 5=sound effect ; 6=sound effect ; 7=sound effect ; 8=sound effect ; 9=sound effect move.l #1,D0 BSR tune bsr set_palette ;set new colours bsr set_for_border ;knock out lower border bsr show_pic bsr flush ;flush keyboard buffer main_loop bsr flip_screen bsr vsync ; move.w #$123,$ffff8240.w bsr return_screen ; move.w #$700,$ffff8240.w bsr do_bob ; move.w #$070,$ffff8240.w bsr scroll ; move.w #$707,$ffff8240.w bsr clear_spec ; move.w #$321,$ffff8240.w bsr calc_spec ; move.w pic+2,$ffff8240.w move.b $fffffc02.w,d0 ; cmp.b #01,d0 ;escape? ; beq exit ;yes get out... cmp.b #$b,d0 ;0 key beq.s zero check_keys lea key_codes,a6 .loop cmp.b #$ff,(a6) ;end of table? beq.s main_loop ;yes cmp.b (a6)+,d0 ;is key one we want? beq.s load ;yes so load demo move.b (a6)+,d6 ;NO so get offset bra.s .loop ;check another key code load move.b (a6),-(sp) ;store offset on stack for later use bsr isr_off ;turn interrupts off move.l old_base,a0 ;put screen base back to original value bsr set_low_rez ;go low rez (again?) bsr black_out ;all black (where am I?) moveq #0,d0 ;clear D0.L move.b (sp)+,d0 ;get key value off stack *** new piece of filename selector.... lea filename_table,a0 lsl.w #2,d0 ;multiply D0 by 4 (one long word) add.w d0,a0 move.l (a0),a1 ;get filename address *** now move filename into $200 for AUTORUN4 to find lea $200.w,a0 movem.l (a1),d0/d1/d2/d3 ;move 16 bytes movem.l d0-d3,(a0) ;into $200 *** now check hertz and exit cleanly... tst.w hertz_switch ;has hertz been pressed? beq.s hz50 ;no so it stays in 50Hz eor.b #2,$ffff820a.w ;yes so go 60Hz hz50 move.b #8,$fffffc02.w ;mouse back on bsr user_mode ;go user mode clr.w -(sp) ;exit to next prog in AUTO folder trap #1 ;or desktop zero tst.w zero_counter bne.s check_keys eor.w #$123,bor+2 ;show a hertz change eor.w #$ffff,hertz_switch ;toggle a check move.w #10,zero_counter ;delay in between hertz switches bra main_loop exit bsr isr_off ;off with the interrupts move.l old_base,a0 ;put screen back to original bsr set_org_rez ;go org rez for assembler/desktop bsr restore_pal ;restore colours move.b #8,$fffffc02.w ;mouse back on move.b old484,$484.w ;keyclick, etc bsr flush ;clear keyboard buffer bsr user_mode ;use mode clr.w -(sp) ;assembler/desktop trap #1 ;BYE! *************** * Subroutines * *************** ****************************** * * * Spectrum Analyser routines * * * ****************************** MAX_BARS equ 80 AFINE equ 0 ACOURSE equ 1 BFINE equ 2 BCOURSE equ 3 CFINE equ 4 CCOURSE equ 5 AAMP equ 8 BAMP equ 9 CAMP equ 10 clear_spec move.l last_base,a1 add.l #(160*204),a1 moveq #0,d0 REPT (20*26) move.w d0,(a1) addq.w #8,a1 ENDR rts calc_spec lea spec_values,a0 moveq #(MAX_BARS-1),d0 .cnt_down tst.b (a0)+ beq.s .next subq.b #1,-1(a0) .next dbf d0,.cnt_down lea $ffff8800.w,a1 lea spec_values,a2 lea spec_data,a3 moveq #12,d2 move.b #AAMP,(a1) move.b (a1),d1 and.b #15,d1 beq.s bchan moveq #0,d0 move.b #ACOURSE,(a1) move.b (a1),d0 lsl.w #8,d0 move.b #AFINE,(a1) move.b (a1),d0 tst.w d0 beq.s bchan add.w d0,d0 move.w (a3,d0),d0 bmi.s bchan move.b d2,(a2,d0) ****************** bchan move.b #BAMP,(a1) move.b (a1),d1 and.b #15,d1 beq.s cchan moveq #0,d0 move.b #BCOURSE,(a1) move.b (a1),d0 lsl.w #8,d0 move.b #BFINE,(a1) move.b (a1),d0 tst.w d0 beq.s cchan add.w d0,d0 move.w (a3,d0),d0 bmi.s cchan move.b d2,(a2,d0) ****************** cchan move.b #CAMP,(a1) move.b (a1),d1 and.b #15,d1 beq.s ps moveq #0,d0 move.b #CCOURSE,(a1) move.b (a1),d0 lsl.w #8,d0 move.b #CFINE,(a1) move.b (a1),d0 tst.w d0 beq.s ps add.w d0,d0 move.w (a3,d0),d0 bmi.s ps move.b d2,(a2,d0) ******************** print speccy ******************* ps move.l last_base,a0 add.l #32000+(16*160),a0 lea spec_values,a2 move.w #(80/4)-1,d1 .loop move.l a0,a1 lea 160(a0),a3 moveq.l #0,d0 move.b (a2)+,d0 beq.s .nib2 and.w #15,d0 move.b #%11100000,d2 .loop1 move.b d2,(a1) move.b d2,(a3) lea -160(a1),a1 lea 160(a3),a3 dbf d0,.loop1 .nib2 move.b (a2)+,d0 beq.s .nib3 and.w #15,d0 move.l a0,a1 lea 160(a0),a3 move.b #%00001110,d2 .loop2 or.b d2,(a1) or.b d2,(a3) lea -160(a1),a1 lea 160(a3),a3 dbf d0,.loop2 .nib3 moveq.l #0,d0 move.b (a2)+,d0 beq.s .nib4 and.w #15,d0 move.l a0,a1 lea 160(a0),a3 move.b #%11100000,d2 .loop3 or.b d2,1(a1) or.b d2,1(a3) lea -160(a1),a1 lea 160(a3),a3 dbf d0,.loop3 .nib4 moveq.l #0,d0 move.b (a2)+,d0 beq.s .nonib and.w #15,d0 move.l a0,a1 lea 160(a0),a3 move.b #%00001110,d2 .loop4 or.b d2,1(a1) or.b d2,1(a3) lea -160(a1),a1 lea 160(a3),a3 dbf d0,.loop4 .nonib add.w #8,a0 dbf d1,.loop rts ************************************************** return_screen ;wipe over old bob move.l mid_pos,d0 move.l last_position,mid_pos move.l last_base,a0 add.l d0,a0 lea pic+34,a1 add.l d0,a1 ***************************************************************** ***** Customized return bob routine for MINI_POV (saves CPU time) ***************************************************************** * BOB is 10 words wide in 16 colours...... REPT 9 movem.l 24(a1),d0-d3 movem.l d0-d3,24(a0) lea 160(a0),a0 lea 160(a1),a1 ENDR REPT 16 movem.l 16(a1),d0-d7 movem.l d0-d7,16(a0) lea 160(a0),a0 lea 160(a1),a1 ENDR REPT 17 movem.l 8(a1),d0-d7/a2-a5 movem.l d0-d7/a2-a5,8(a0) lea 160(a0),a0 lea 160(a1),a1 ENDR REPT BOB_DEPTH-(9+16+17) movem.l (a1),d0-d7/a2-a5 movem.l d0-d7/a2-a5,(a0) movem.l 48(a1),d0-d7/a2-a5 movem.l d0-d7/a2-a5,48(a0) movem.l 96(a1),d0-d5 movem.l d0-d5,96(a0) lea 160(a0),a0 lea 160(a1),a1 ENDR rts * the bob path is a table of values with a Y offset and a X offset * the table is calculated in FAST BASIC and the file created is * INCBINed into the assembler. To change the table edit the SINE.BSC * file and run it in FAST BASIC the output file is automatically * made. do_bob move.l table_pos,a0 ;get position in SINE table cmp.w #-1,(a0) ;is end of table? bne.s .no_reset ;NO lea sine,a0 ;YES move.l a0,table_pos .no_reset moveq.l #0,d0 ;clear 3 registers move.l d0,d1 move.l d0,d2 move.w (a0)+,d0 ;get word/offset move.w (a0)+,d1 ;get y offset (post*160) move.l a0,table_pos ;update SINE table pos * Calculate the word offset across the screen... move.b d0,d2 lsr.w #4,d0 ;word offset lsl.w #3,d0 ;*8 add.w d1,d0 ;add to Y line offset move.l last_base,a0 add.w d0,a0 ;address on screen of bob * store offset from screen base for clear bob routine later.. move.l d0,last_position lea bob,a1 ;grafix and.w #$f,d2 ;calculate which grafix to use (1 of 16) mulu #(8*BOB_WIDTH*BOB_DEPTH),d2 add.l d2,a1 ;add to first grafix add.l d2,a1 ;add again to get over mask lea 8*BOB_WIDTH*BOB_DEPTH(a1),a2 ;find mask for that grafic ************************************************** ; CUSTOM PRINT BOB ROUTINE FOR **MINI_POV** BOB ************************************************** REPT 9 move.l 24(a2),d1 ;get mask data move.l 24(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 24(a1),d0 ;put grafix into hole move.l d0,24(a0) ;put grafix on screen move.l 28(a0),d0 and.l d1,d0 ;same mask as first word or.l 28(a1),d0 move.l d0,28(a0) move.l 32(a2),d1 ;get mask data move.l 32(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 32(a1),d0 ;put grafix into hole move.l d0,32(a0) ;put grafix on screen move.l 36(a0),d0 and.l d1,d0 or.l 36(a1),d0 move.l d0,36(a0) add.w #BOB_WIDTH*8,a1 add.w #BOB_WIDTH*8,a2 lea 160(a0),a0 ENDR REPT 16 move.l 16(a2),d1 ;get mask data move.l 16(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 16(a1),d0 ;put grafix into hole move.l d0,16(a0) ;put grafix on screen move.l 20(a0),d0 and.l d1,d0 or.l 20(a1),d0 move.l d0,20(a0) move.l 24(a2),d1 ;get mask data move.l 24(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 24(a1),d0 ;put grafix into hole move.l d0,24(a0) ;put grafix on screen move.l 28(a0),d0 and.l d1,d0 or.l 28(a1),d0 move.l d0,28(a0) move.l 32(a2),d1 ;get mask data move.l 32(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 32(a1),d0 ;put grafix into hole move.l d0,32(a0) ;put grafix on screen move.l 36(a0),d0 and.l d1,d0 or.l 36(a1),d0 move.l d0,36(a0) move.l 40(a2),d1 ;get mask data move.l 40(a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l 40(a1),d0 ;put grafix into hole move.l d0,40(a0) ;put grafix on screen move.l 44(a0),d0 and.l d1,d0 or.l 44(a1),d0 move.l d0,44(a0) add.w #BOB_WIDTH*8,a1 add.w #BOB_WIDTH*8,a2 lea 160(a0),a0 ENDR add.w #8,a0 add.w #8,a1 add.w #8,a2 REPT 17 move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ move.l (a2)+,d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen move.l (a2)+,d1 move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ add.w #16+8,a0 add.w #16+8,a1 add.w #16+8,a2 add.w #160-(BOB_WIDTH*8),a0 ENDR sub.w #8,a0 sub.w #8,a1 sub.w #8,a2 move.w #(BOB_DEPTH-(9+16+17))-1,d7 .loop REPT BOB_WIDTH * do first word (8 colours) move.l (a2),d1 ;get mask data move.l (a0),d0 ;get screen data and.l d1,d0 ;get rid of screen within mask or.l (a1)+,d0 ;put grafix into hole move.l d0,(a0)+ ;put grafix on screen * do second word (8 colours) move.l (a0),d0 and.l d1,d0 or.l (a1)+,d0 move.l d0,(a0)+ addq.w #8,a2 ENDR add.w #160-(BOB_WIDTH*8),a0 ;drop down one screen line dbf d7,.loop ;do until finsihed rts *------------------------------------------------------------------- scroll move.l last_base,a1 add.l #(160*200)+2,a1 ;into border lea font_offsets,a2 ;font lookup table lea font,a3 ;font itself move.l scroll_pointer,a4 ;pointer into text move.l a4,a5 moveq #0,d4 moveq #40,d5 ;40 words across screen move.w char_offset,d6 ;char offset is a toggle ;for bytes/words next_char move.b (a5),d7 ;get a letter sub.b #32,d7 ;rid of ASCII ext.w d7 moveq #0,d0 move.l a3,a0 move.b (a2,d7),d0 ;find correct offset lsl.w #7,d0 add.w d0,a0 ;add to font start move.w d6,d0 ;char offset lsl.w #5,d0 add.w d0,a0 ;we now point to character in A0 ** this bit prints 1 byte wide blocks of the font, this method makes ** it possible to redraw the scroller every screen refresh and makes ** it so the we do not have to shift the scroller. The bad part is that ** it scrolls bloody fast at 8 bits every screen refresh. ** If I didn't use this then the bob may have to be made smaller 'cause ** of the CPU time... .column OFF set 0 REPT 32 ;32 lines deep font move.b (a0)+,OFF(a1) OFF set OFF+160 ;go down a line ENDR subq.w #1,d5 ;column value beq.s .finish ;last column then finish addq.w #1,a1 ;lower byte of word tst.w d4 beq.s .skip ;if D4=0 then do next byte add.w #6,a1 ;else goto next word on screen .skip not.w d4 addq.w #1,d6 ;character offset and.w #3,d6 bne .column addq.w #1,a5 ;scroll pointer tst.b (a5) ;is end of text? bpl next_char ;NO! lea scroll_text,a5 ;do reset scrolline bra next_char .finish addq.w #1,char_offset and.w #3,char_offset bne.s .end addq.w #1,a4 tst.b (a4) ;is scroll text end? bpl.s .end ;NO! lea scroll_text,a4 ;reset scroll text .end move.l a4,scroll_pointer rts ******************** * SERVICE ROUTINES * ******************** flip_screen ;flip between 2 screens to stop bob flickering move.l present_base,last_base move.l screen_1,a0 move.w screen_number,d0 beq .1 move.l screen_2,a0 .1 move.l a0,present_base eor.w #-1,screen_number move.l a0,d0 lsr.l #8,d0 lea $fffff8201.w,a0 movep.w d0,(a0) rts flush btst.b #0,$fffffC00.w ;flush keyboard beq.s flush2 move.b $fffffC02.w,d0 bra.s flush flush2 rts vsync move.w #$ffff,vsync_flag ;custom routine to wait vs tst.w vsync_flag ;for screen refresh bne.s vs rts set_super clr.l -(sp) ;set supervisor mode move.w #32,-(sp) trap #1 addq.l #6,sp move.l d0,stack_save rts user_mode move.l stack_save,-(sp) move.w #$20,-(sp) trap #1 addq.l #6,sp rts save_pal ;save old colours lea old_pal,a1 lea $ffff8240.w,a0 movem.l (a0),d0-d7 movem.l d0-d7,(a1) rts restore_pal ;put back original colours lea old_pal,a0 bra.s set_p set_palette lea pic+2,a0 set_p lea $ffff8240.w,a1 movem.l (a0),d0-d7 movem.l d0-d7,(a1) rts get_base ;get org screen address move.w #3,-(sp) trap #14 addq.l #2,sp move.l d0,old_base rts get_rez move.w #4,-(sp) trap #14 addq.l #2,sp move.w d0,org_rez rts calc_screen ;calc our own screen address... lea screen,a0 move.l a0,d0 clr.b d0 move.l d0,screen_1 add.l #40192,d0 move.l d0,screen_2 rts set_med_rez move.w #1,-(sp) bra.s set_rez set_org_rez move.w org_rez,-(sp) bra.s set_rez set_low_rez clr.w -(sp) set_rez move.l a0,-(sp) ;screen address is in A0 move.l (sp),-(sp) move.w #5,-(sp) trap #14 add.l #12,sp rts show_pic ;show the pic lea pic+34,a0 move.l present_base,a1 lea 32000-160(a0),a2 lea 32000-160(a1),a3 move.w #200/2-1,d7 .loop bsr vsync movem.l (a0),d0-d6 ;28 bytes movem.l d0-d6,(a1) movem.l 28(a0),d0-d6 ;56 movem.l d0-d6,28(a1) movem.l 56(a0),d0-d6 ;84 movem.l d0-d6,56(a1) movem.l 84(a0),d0-d6 ;112 movem.l d0-d6,84(a1) movem.l 112(a0),d0-d6 ;140 movem.l d0-d6,112(a1) movem.l 140(a0),d0-d4 ;160 movem.l d0-d4,140(a1) lea 320(a0),a0 lea 320(a1),a1 movem.l (a2),d0-d6 ;28 bytes movem.l d0-d6,(a3) movem.l 28(a2),d0-d6 ;56 movem.l d0-d6,28(a3) movem.l 56(a2),d0-d6 ;84 movem.l d0-d6,56(a3) movem.l 84(a2),d0-d6 ;112 movem.l d0-d6,84(a3) movem.l 112(a2),d0-d6 ;140 movem.l d0-d6,112(a3) movem.l 140(a2),d0-d4 ;160 movem.l d0-d4,140(a3) lea -320(a2),a2 lea -320(a3),a3 dbf d7,.loop move.l present_base,a0 ;copy to second screen move.l screen_2,a1 ;for flip screen move.w #32000/4-1,d1 copy move.l (a0)+,(a1)+ dbf d1,copy rts black_out ;all colours black movem.l black,d0-d7 movem.l d0-d7,$ffff8240.w rts v_sync movem.l d0-d3/a0-a3,-(sp) ;ROM wait for screen update move.w #$25,-(sp) trap #14 addq.l #2,sp movem.l (sp)+,d0-d3/a0-a3 rts clear_below_screen ;clear crap under screen for move.l present_base,a0 ;border code lea 32000(a0),a0 move.l a0,a1 add.l #40192,a1 move.w #20,d0 clr1: move.w #8*40-1,d1 clr2: clr.l (a0)+ clr.l (a1)+ dbf d1,clr2 dbf d0,clr1 rts set_for_border ;save old interrupt values ori.w #$700,sr move.l $70,old70 move.l $120,old120 move.b $fffffa07,olda07 move.b $fffffa09,olda09 move.b $fffffa17,olda17 move.b $fffffa1b,olda1b move.b $fffffa21,olda21 MOVE.L #vert_isr,$70.W ;set new interrupt values MOVE.L #new120,$120.W MOVE.B #1,$FFFFFA07.W CLR.B $FFFFFA09.W BCLR #0,$FFFFFA0F.W BSET #0,$FFFFFA13.W bclr #3,$fffffa17.w ;enable auto A-INTERRUPT IN SERVICE clear CLR.B $FFFFFA1B.W CLR.B $FFFFFA21.W MOVE.W #$2300,SR rts ;ISRs are now running isr_off bsr vsync ;shut the interrupts down move.w #$2700,sr ;quick before she blows up!! move.l old120,$120 move.l old70,$70 MOVE.B olda07,$FFFFFA07 MOVE.B olda09,$FFFFFA09 MOVE.B olda17,$FFFFFA17 move.b olda1b,$fffffa1b move.b olda21,$fffffa21 MOVE.W #$2300,SR endmusic ;turn da music off man! moveq #0,d0 bsr tune rts shift_bob ;make 16 values of bob so smooth scroll lea bob_pic+34,a0 move.l present_base,a1 move.w #32000/4-1,d0 .loop move.l (a0)+,(a1)+ dbf d0,.loop lea bob,a1 move.w #16-1,d7 shift_loop move.l present_base,a0 move.l a0,a6 add.w #8,a0 move.w #BOB_DEPTH-1,d2 repeat OFF set 0 REPT BOB_WIDTH ;in words move.l OFF(a0),(a1)+ OFF SET OFF+4 move.l OFF(a0),(a1)+ OFF SET OFF+4 ENDR add.w #160,a0 dbf d2,repeat move.w #BOB_DEPTH-1,d2 repeat2 OFF set 0 REPT BOB_WIDTH ;in words move.l OFF(a0),(a1)+ OFF SET OFF+4 move.l OFF(a0),(a1)+ OFF SET OFF+4 ENDR add.w #160,a0 dbf d2,repeat2 move.l a6,a0 move.w #(BOB_DEPTH*2)+8-1,d6 .loop sub.w d4,d4 OFF set 0 REPT BOB_WIDTH roxr.w OFF(a0) OFF SET OFF+8 ENDR add.w #2,a0 sub.w d4,d4 OFF set 0 REPT BOB_WIDTH roxr.w OFF(a0) OFF SET OFF+8 ENDR add.w #2,a0 sub.w d4,d4 OFF set 0 REPT BOB_WIDTH roxr.w OFF(a0) OFF SET OFF+8 ENDR add.w #2,a0 sub.w d4,d4 OFF set 0 REPT BOB_WIDTH roxr.w OFF(a0) OFF SET OFF+8 ENDR sub.w #6,a0 add.w #160,a0 dbf d6,.loop dbf d7,shift_loop ;now clear screen move.l present_base,a0 moveq #0,d0 move.w #32000/4-1,d1 loop move.l d0,(a0)+ dbf d1,loop rts ********* * ISRs * ********* vert_isr ;every screen update... movem.l d0-d7/a0-a6,-(sp) ;preserve regs movem.l pic+2,d0-d7 ;set colours after isr movem.l d0-d7,$ffff8240.w bsr tune+2 ;do COUNT ZERO music clr.w vsync_flag ;own screen update rout tst.w zero_counter beq.s .clear sub.w #1,zero_counter .clear movem.l (sp)+,d0-d7/a0-a6 move.b #8,$fffffa1b.w ;set interrupt method move.b #199,$fffffa21.w ;next interrupt to occur 199 lines down rte ;let's leave before interrupt occurs new120 clr.b $fffffa1b.w ;DI all other interrupts REPT 102 ;wait until we are next to right border nop ENDR clr.b $ffff820a.w ;60 hertz *** this bit of code here is important for timing the border *** do NOT change or you will lose STE compatability and probably the *** lower border *** *** I do the following 3 lines here to prevent the use from seeing *** the colour change in the scroller *** movem.l d0/a0/a1,-(sp) ;save regs move.l colours_pos,a0 ;colours for font lea spec_colours,a1 ;colours for spectrum anal move.w #32-1,d0 ;set up D0 here to save time later *** *** REPT 31-28 ;wait a while nop ENDR bor move.w #BORDER_COLOUR,$ffff8240.w ;hertz color show move.b #2,$ffff820a.w ;back to 50 hertz **** WOW dudes we are in the lower border....... .loop move.w (a0),$ffff8244.w ;show colours in scroll move.w (a0)+,$ffff8246.w move.w (a1)+,$ffff8242.w ;speecy colours REPT 113 nop ENDR dbf d0,.loop move.w #BORDER_COLOUR,$ffff8240.w add.l #2,colours_pos move.l colours_pos,a0 cmp.l #colours_end,a0 bge.s .reset_cols movem.l (sp)+,d0/a0/a1 rte .reset_cols move.l #colours,colours_pos movem.l (sp)+,d0/a0/a1 rte ******** * Data * ******** SECTION DATA colours_pos dc.l colours colours dc.w 0 ;for scroller dc.w $200,$300,$400,$500,$600,$700,$710 dc.w $720,$730,$740,$750,$760,$770,$670 dc.w $570,$470,$370,$271,$172,$073,$074 dc.w $075,$076,$077,$067,$057,$047,$037 dc.w $027,$017,$007 dc.w $106,$205,$304,$403,$502,$601,$700 dc.w $710,$720,$730,$740,$750,$760,$770 dc.w $671,$572,$473,$374,$275,$176,$077 dc.w $167,$257,$347,$437,$527,$617,$707 dc.w $706,$705,$604,$503,$402,$301 colours_end dc.w $200,$300,$400,$500,$600,$700,$710 dc.w $720,$730,$740,$750,$760,$770,$670 dc.w $570,$470,$370,$271,$172,$073,$074 dc.w $075,$076,$077,$067,$057,$047,$037 dc.w $027,$017,$007 zero_counter dc.w 0 screen_number dc.w 0 present_base dc.l 0 last_base dc.l 0 screen_1 dc.l 0 screen_2 dc.l 0 vsync_flag dc.w 0 *** store for old ISR data old70 dc.l 0 old120 dc.l 0 olda07 dc.b 0 olda09 dc.b 0 olda17 dc.b 0 olda1b dc.b 0 olda21 dc.b 0 even org_rez dc.w 0 ;original rez hertz_switch dc.w 0 ;hertz toggle check scroll_pointer dc.l scroll_text+7 scroll_text DC.B " " dc.b "P.O.V. 93. CREDITS: MENU CODED BY M.S.D. (THANX " dc.b "TO BORIS FOR OPTIMISING MY SPECTRUM ANALYSER ROUTINE - ONLY SLIGHTLY FASTER)" dc.b ", " dc.b "GRAFIX BY OZ AND MUSIC BY COUNT ZERO (WHERE FROM?). " DC.B "HERE ARE THE GREETINGS.. " DC.B "AUTOMATION, " DC.B "ABC CREW, " DC.B "BLACK CATS, " dc.b "DEL, " DC.B "DR.SYNE, " DC.B "ERIK PLANKTON (LIKE THE NEW DEMO - KNOCK, KNOCK!!!), " DC.B "EMPIRE, " DC.B "EQUINOX, " DC.B "GEORGE S, " DC.B "INNER CIRCLE, " DC.B "KGB (FRANCE), " DC.B "LOST BOYS, " DC.B "MARTIAN, " DC.B "MEDWAY BOYS, " dc.b "NOW 5, " DC.B "NORTH SIDE, " DC.B "OBERJE, " DC.B "POMPEY PIRATES, " DC.B "REPLICANTS, " DC.B "RIPPED OFF, " DC.B "SEWER SOFTWARE, " DC.B "SKUNK, " DC.B "SLAYTANIC CULTS, " DC.B "SOURCE, " DC.B "ST CNX, " DC.B "TEX, " DC.B "TCB, " dc.b "TNT CREW, " DC.B "AND " DC.B "WATCHMEN. " dc.b " WELL IT APPEARS THAT SOME PEOPLE DON'T LIKE WHAT WE " DC.B "DO, I MEAN WE MUST BE THE WORST PACKING CREW EVER IN THE " DC.B "HISTORY OF THE ST ACCORDING TO A CERTAIN ANON PERSON. " DC.B "HERE IS A QUOTE 'THE DISK CONTENTS AND PACKING ARE TERRIBLE, " DC.B "JUST CHECK OUT SOME OF THE RIPPED OFF CD'S, NEARLY ALL FILES " DC.B "ARE SMALLER - SOME UP TO 180K SMALLER.' WELL DO YOU " DC.B "AGREE? I WILL ADMIT THAT RIPPED OFF PUT A LOT OF " DC.B "SMALL DEMOS ON THEIR DISCS AND WE PUT LARGE SAMPLE DEMOS ON " DC.B "OURS, WE WILL CHANGE THAT WHEN WE GET SOME NEW STUFF. AS " DC.B "FOR OTHER PEOPLES PACKS BEING SMALLER THAN MINE, WELL I HAVE " DC.B "AN EXTREMELY GOOD SOURCE OF INFORMATION (BILBO OF RIPPED OFF) " DC.B "THAT THEY ALTER SAMPLES TO ENABLE THEM TO PACK THEM SMALLER. " DC.B "WHEN I PACK A SAMPLE I DO NOT ALTER IT IN ANY WAY SO THE " DC.B "QUALITY IS EXACTLY AS THE DEMO WRITER WANTED. I FIND IT " DC.B "STRANGE THAT IF I CANNOT PACK DEMOS THEN WHY AM I NOW SUPPLYING 'RIPPED OFF' " DC.B "WITH PACKED DEMOS FOR THEIR DISCS? AND WHY AM I GETTING " DC.B "THEIR DISCS, UNPACKING THE FILES AND REPACKING THEM SMALLER? " DC.B " WHY DO ALL OUR PACKS ALLOW THE DEMOS TO RUN IN THE MEMORY " DC.B "CONFIGURATION THAT THEY WERE ORIGINALLY MADE FOR (IF THE UNPACKED " DC.B "DEMO WORKS IN 512K SO WILL MY PACK). WELL MR ANON. IF " DC.B "WE ARE SO CRAP AT PACKING, WHY DON'T YOU GET OFF YOUR ARSE " DC.B "AND START PACKING SEEING YOU (QUOTE) 'KNOW WHAT YOU ARE TALKING " DC.B "ABOUT'. FUCK YOU ASSHOLE, EAT SHIT AND DIE. IF YOU " DC.B "DON'T LIKE WHAT YOU SEE THEN STOP GETTING P.O.V. DISCS YOU " DC.B "DICK WART. ONE LAST NOTE, WE AT P.O.V. WRITE ALL " DC.B "OUR OWN MENUS AND RIP ALL OUR MUSIC, BOTH 'RIPPED OFF' AND " DC.B "'THE SOURCE' GET OTHER PEOPLE TO CODE THEIR MENUS. " DC.B "WELL THAT'S IT FOR THIS DISC, I'LL BRING YOU SOME MORE " DC.B "POOR PACKS AS SOON AS I CAN GET SOMEBODY ELSE TO CODE " DC.B "ME A MENU!!!!! BYE - M.S.D. 7-9-91. " DC.B " " DC.B " " dc.b $ff even char_offset dc.w 0 font dcb.b 32*4,0 incbin 1plane.fnt font_offsets ; ! " # $ % & ' ( ) * + , - . / dc.b 0,38,43,00,00,00,00,43,40,41,45,00,44,42,39,00 ; 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ dc.b 27,28,29,30,31,32,33,34,35,36,45,00,00,00,00,37,00 ; A B C D E F G H I J K L M N O P Q dc.b 01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17 ; R S T U V W X Y Z [ \ ] ^ _ ` a b c dc.b 18,19,20,21,22,23,24,25,26,40,00,41,00,00,00,00,00,00 ; d e f g h i j k l m n o p q r s t u dc.b 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00 even tune incbin 474.img ;count zero music even pic incbin pic.PI1 ;main menu pic bob_pic incbin bob.pi1 ;pic with bob in top left mid_pos dc.l 0 ;buffer for bob last_position dc.l 0 ;last bob pos table_pos dc.l sine ;pointer into SINE table sine incbin sine.dat ;here is the sine table dc.w -1,-1 ;end of sine table black dcb.b 32,0 ;32 bytes of nothing... spec_colours dc.w 0,0,0,0 dc.w $300,$b80,$410,$c90,$520,$da0,$630 dc.w $eb0,$740,$fc0,$f50,$fd0,$f60,$fe0 dc.w $f70,$ff0,$040,$050,$060,$070,$071 dc.w $072,$073,$074,$075,$076 spec_data incbin SPECTRUM.DAT spec_values dcb.b MAX_BARS,0 ********** valid key press table key_codes dc.b 2,0 ;key 1, offset 0 dc.b 3,1 ;key 2, offset 1 dc.b 4,2 ;key 3, offset 2 dc.b 5,3 ;key 4 dc.b 6,4 ;key 5 dc.b $6d,0 ;keypad 1, offset 0 dc.b $6e,1 ;keypad 2, offset 1 dc.b $6f,2 dc.b $6a,3 ;keypad 4 dc.b $6b,3 ;keypad 5 dc.b $ff ;end of table even filename_table dc.l filename1 dc.l filename2 dc.l filename3 dc.l filename4 dc.l filename5 *** filenames no longer need to be 16 bytes long but must end *** in 0 and must be on an even address... filename1 dc.b "def_pack.MSD" dc.b 0 even filename2 dc.b "gen_pack.msd" dc.b 0 even filename3 dc.b "$$p_base.msd" dc.b 0 even filename4 dc.b "ninja_3.msd" dc.b 0 even filename5 dc.b "copier.pov" dc.b 0 even ************************* SECTION BSS ************************* old_base ds.l 1 ;old screen address old484 ds.w 1 stack_save ds.l 1 old_pal ds.b 32 ;old colours bob ds.b BOB_DEPTH*(BOB_WIDTH*8)*16 ;grafix ds.b BOB_DEPTH*(BOB_WIDTH*8)*16 ;masks even ds.b 256 ;workspace so screen in on 256 bytes boundry screen ds.b 40192 ;two screens ds.b 40192
0
0.937743
1
0.937743
game-dev
MEDIA
0.262907
game-dev
0.99625
1
0.99625
Geant4/geant4
6,984
source/processes/decay/src/G4UnknownDecay.cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // // // // -------------------------------------------------------------- // GEANT 4 class implementation file // // ------------------------------------------------------------ // #include "G4UnknownDecay.hh" #include "G4PhysicalConstants.hh" #include "G4SystemOfUnits.hh" #include "G4DynamicParticle.hh" #include "G4DecayProducts.hh" #include "G4PhysicsLogVector.hh" #include "G4ParticleChangeForDecay.hh" #include "G4DecayProcessType.hh" // constructor G4UnknownDecay::G4UnknownDecay(const G4String& processName) :G4VDiscreteProcess(processName, fDecay), verboseLevel(1), HighestValue(20.0) { // set Process Sub Type SetProcessSubType(static_cast<int>(DECAY_Unknown)); #ifdef G4VERBOSE if (GetVerboseLevel()>1) { G4cout << "G4UnknownDecay constructor " << " Name:" << processName << G4endl; } #endif pParticleChange = &fParticleChangeForDecay; } G4UnknownDecay::~G4UnknownDecay() { } G4bool G4UnknownDecay::IsApplicable(const G4ParticleDefinition& aParticleType) { if(aParticleType.GetParticleName()=="unknown") return true; return false; } G4double G4UnknownDecay::GetMeanFreePath(const G4Track& /*aTrack*/,G4double, G4ForceCondition*) { return 0.0; } void G4UnknownDecay::BuildPhysicsTable(const G4ParticleDefinition&) { return; } G4VParticleChange* G4UnknownDecay::DecayIt(const G4Track& aTrack, const G4Step& ) { // The DecayIt() method returns by pointer a particle-change object. // Units are expressed in GEANT4 internal units. // Initialize ParticleChange // all members of G4VParticleChange are set to equal to // corresponding member in G4Track fParticleChangeForDecay.Initialize(aTrack); // get particle const G4DynamicParticle* aParticle = aTrack.GetDynamicParticle(); //check if thePreAssignedDecayProducts exists const G4DecayProducts* o_products = (aParticle->GetPreAssignedDecayProducts()); G4bool isPreAssigned = (o_products != nullptr); G4DecayProducts* products = nullptr; if (!isPreAssigned ){ fParticleChangeForDecay.SetNumberOfSecondaries(0); // Kill the parent particle fParticleChangeForDecay.ProposeTrackStatus( fStopAndKill ) ; fParticleChangeForDecay.ProposeLocalEnergyDeposit(0.0); ClearNumberOfInteractionLengthLeft(); return &fParticleChangeForDecay ; } // copy decay products products = new G4DecayProducts(*o_products); // get parent particle information ................................... G4double ParentEnergy = aParticle->GetTotalEnergy(); G4double ParentMass = aParticle->GetMass(); if (ParentEnergy < ParentMass) { ParentEnergy = ParentMass; #ifdef G4VERBOSE if (GetVerboseLevel()>1) { G4cout << "G4UnknownDecay::DoIt : Total Energy is less than its mass" << G4endl; G4cout << " Particle: " << aParticle->GetDefinition()->GetParticleName(); G4cout << " Energy:" << ParentEnergy/MeV << "[MeV]"; G4cout << " Mass:" << ParentMass/MeV << "[MeV]"; G4cout << G4endl; } #endif } G4ThreeVector ParentDirection(aParticle->GetMomentumDirection()); G4double energyDeposit = 0.0; G4double finalGlobalTime = aTrack.GetGlobalTime(); //boost all decay products to laboratory frame //if the particle has traveled if(aParticle->GetPreAssignedDecayProperTime()>=0.) { products->Boost( ParentEnergy, ParentDirection); } //add products in fParticleChangeForDecay G4int numberOfSecondaries = products->entries(); fParticleChangeForDecay.SetNumberOfSecondaries(numberOfSecondaries); #ifdef G4VERBOSE if (GetVerboseLevel()>1) { G4cout << "G4UnknownDecay::DoIt : Decay vertex :"; G4cout << " Time: " << finalGlobalTime/ns << "[ns]"; G4cout << " X:" << (aTrack.GetPosition()).x() /cm << "[cm]"; G4cout << " Y:" << (aTrack.GetPosition()).y() /cm << "[cm]"; G4cout << " Z:" << (aTrack.GetPosition()).z() /cm << "[cm]"; G4cout << G4endl; G4cout << "G4UnknownDecay::DoIt : decay products in Lab. Frame" << G4endl; products->DumpInfo(); } #endif G4int index; G4ThreeVector currentPosition; const G4TouchableHandle thand = aTrack.GetTouchableHandle(); for (index=0; index < numberOfSecondaries; index++){ // get current position of the track currentPosition = aTrack.GetPosition(); // create a new track object G4Track* secondary = new G4Track( products->PopProducts(), finalGlobalTime , currentPosition ); // switch on good for tracking flag secondary->SetGoodForTrackingFlag(); secondary->SetTouchableHandle(thand); // add the secondary track in the List fParticleChangeForDecay.AddSecondary(secondary); } delete products; // Kill the parent particle fParticleChangeForDecay.ProposeTrackStatus( fStopAndKill ) ; fParticleChangeForDecay.ProposeLocalEnergyDeposit(energyDeposit); fParticleChangeForDecay.ProposeGlobalTime( finalGlobalTime ); // reset NumberOfInteractionLengthLeft ClearNumberOfInteractionLengthLeft(); return &fParticleChangeForDecay ; } void G4UnknownDecay::ProcessDescription(std::ostream& outFile) const { outFile << GetProcessName() << ": Decay of 'unknown' particles. \n" << "kinematics of daughters are dertermined " << "by PreAssignedDecayProducts. \n"; }
0
0.891896
1
0.891896
game-dev
MEDIA
0.325952
game-dev
0.847005
1
0.847005
TheDuriel/DurielUtilities
2,088
FancyTheme/FancyContainer.gd
@tool class_name FancyContainer extends MarginContainer const A_BOX_NAME: String = "a_box" const A_BOX_MARGIN_NAMES: Array[String] = [ "a_box_margin_left", "a_box_margin_up", "a_box_margin_right", "a_box_margin_down"] const B_BOX_NAME: String = "b_box" const B_BOX_MARGIN_NAMES: Array[String] = [ "b_box_margin_left", "b_box_margin_up", "b_box_margin_right", "b_box_margin_down"] const C_BOX_NAME: String = "c_box" const C_BOX_MARGIN_NAMES: Array[String] = [ "c_box_margin_left", "c_box_margin_up", "c_box_margin_right", "c_box_margin_down"] var _a_box: StyleBox: get: return get_theme_stylebox(A_BOX_NAME) var _b_box: StyleBox: get: return get_theme_stylebox(B_BOX_NAME) var _c_box: StyleBox: get: return get_theme_stylebox(C_BOX_NAME) var _a_box_margins: Array[int]: get: var a: Array[int] = [ get_theme_constant(A_BOX_MARGIN_NAMES[0]), get_theme_constant(A_BOX_MARGIN_NAMES[1]), get_theme_constant(A_BOX_MARGIN_NAMES[2]), get_theme_constant(A_BOX_MARGIN_NAMES[3])] return a var _b_box_margins: Array[int]: get: var b: Array[int] = [ get_theme_constant(B_BOX_MARGIN_NAMES[0]), get_theme_constant(B_BOX_MARGIN_NAMES[1]), get_theme_constant(B_BOX_MARGIN_NAMES[2]), get_theme_constant(B_BOX_MARGIN_NAMES[3])] return b var _c_box_margins: Array[int]: get: var c: Array[int] = [ get_theme_constant(C_BOX_MARGIN_NAMES[0]), get_theme_constant(C_BOX_MARGIN_NAMES[1]), get_theme_constant(C_BOX_MARGIN_NAMES[2]), get_theme_constant(C_BOX_MARGIN_NAMES[3])] return c func _draw() -> void: var a_box: StyleBox = _a_box if a_box: _draw_box(a_box, _a_box_margins) var b_box: StyleBox = _b_box if b_box: _draw_box(a_box, _b_box_margins) var c_box: StyleBox = _c_box if c_box: _draw_box(c_box, _c_box_margins) func _draw_box(box: StyleBox, margins: Array[int]) -> void: var margin_topleft: Vector2 = Vector2(margins[0], margins[1]) var margin_botright: Vector2 = Vector2(margins[0], margins[1]) var rect: Rect2 = Rect2( Vector2.ZERO + margin_topleft, size - (margin_topleft + margin_botright)) draw_style_box(box, rect)
0
0.596126
1
0.596126
game-dev
MEDIA
0.491568
game-dev,desktop-app
0.760918
1
0.760918
lzk228/space-axolotl-14
6,186
Content.Server/Salvage/SalvageSystem.Expeditions.cs
using System.Linq; using System.Threading; using Content.Server.Salvage.Expeditions; using Content.Shared.CCVar; using Content.Shared.Examine; using Content.Shared.Salvage.Expeditions; using Content.Shared.Shuttles.Components; using Robust.Shared.CPUJob.JobQueues; using Robust.Shared.CPUJob.JobQueues.Queues; using Robust.Shared.GameStates; namespace Content.Server.Salvage; public sealed partial class SalvageSystem { /* * Handles setup / teardown of salvage expeditions. */ private const int MissionLimit = 3; private readonly JobQueue _salvageQueue = new(); private readonly List<(SpawnSalvageMissionJob Job, CancellationTokenSource CancelToken)> _salvageJobs = new(); private const double SalvageJobTime = 0.002; private float _cooldown; private void InitializeExpeditions() { SubscribeLocalEvent<SalvageExpeditionConsoleComponent, ComponentInit>(OnSalvageConsoleInit); SubscribeLocalEvent<SalvageExpeditionConsoleComponent, EntParentChangedMessage>(OnSalvageConsoleParent); SubscribeLocalEvent<SalvageExpeditionConsoleComponent, ClaimSalvageMessage>(OnSalvageClaimMessage); SubscribeLocalEvent<SalvageExpeditionComponent, MapInitEvent>(OnExpeditionMapInit); SubscribeLocalEvent<SalvageExpeditionComponent, ComponentShutdown>(OnExpeditionShutdown); SubscribeLocalEvent<SalvageExpeditionComponent, ComponentGetState>(OnExpeditionGetState); _cooldown = _configurationManager.GetCVar(CCVars.SalvageExpeditionCooldown); Subs.CVar(_configurationManager, CCVars.SalvageExpeditionCooldown, SetCooldownChange); } private void OnExpeditionGetState(EntityUid uid, SalvageExpeditionComponent component, ref ComponentGetState args) { args.State = new SalvageExpeditionComponentState() { Stage = component.Stage }; } private void SetCooldownChange(float obj) { // Update the active cooldowns if we change it. var diff = obj - _cooldown; var query = AllEntityQuery<SalvageExpeditionDataComponent>(); while (query.MoveNext(out var comp)) { comp.NextOffer += TimeSpan.FromSeconds(diff); } _cooldown = obj; } private void OnExpeditionMapInit(EntityUid uid, SalvageExpeditionComponent component, MapInitEvent args) { component.SelectedSong = _audio.ResolveSound(component.Sound); } private void OnExpeditionShutdown(EntityUid uid, SalvageExpeditionComponent component, ComponentShutdown args) { component.Stream = _audio.Stop(component.Stream); // First wipe any disks referencing us var disks = AllEntityQuery<ShuttleDestinationCoordinatesComponent>(); while (disks.MoveNext(out var disk, out var diskComp) && diskComp.Destination == uid) { diskComp.Destination = null; Dirty(disk, diskComp); } foreach (var (job, cancelToken) in _salvageJobs.ToArray()) { if (job.Station == component.Station) { cancelToken.Cancel(); _salvageJobs.Remove((job, cancelToken)); } } if (Deleted(component.Station)) return; // Finish mission if (TryComp<SalvageExpeditionDataComponent>(component.Station, out var data)) { FinishExpedition((component.Station, data), uid); } } private void UpdateExpeditions() { var currentTime = _timing.CurTime; _salvageQueue.Process(); foreach (var (job, cancelToken) in _salvageJobs.ToArray()) { switch (job.Status) { case JobStatus.Finished: _salvageJobs.Remove((job, cancelToken)); break; } } var query = EntityQueryEnumerator<SalvageExpeditionDataComponent>(); while (query.MoveNext(out var uid, out var comp)) { // Update offers if (comp.NextOffer > currentTime || comp.Claimed) continue; comp.Cooldown = false; comp.NextOffer += TimeSpan.FromSeconds(_cooldown); GenerateMissions(comp); UpdateConsoles((uid, comp)); } } private void FinishExpedition(Entity<SalvageExpeditionDataComponent> expedition, EntityUid uid) { var component = expedition.Comp; component.NextOffer = _timing.CurTime + TimeSpan.FromSeconds(_cooldown); Announce(uid, Loc.GetString("salvage-expedition-completed")); component.ActiveMission = 0; component.Cooldown = true; UpdateConsoles(expedition); } private void GenerateMissions(SalvageExpeditionDataComponent component) { component.Missions.Clear(); for (var i = 0; i < MissionLimit; i++) { var mission = new SalvageMissionParams { Index = component.NextIndex, Seed = _random.Next(), Difficulty = "Moderate", }; component.Missions[component.NextIndex++] = mission; } } private SalvageExpeditionConsoleState GetState(SalvageExpeditionDataComponent component) { var missions = component.Missions.Values.ToList(); return new SalvageExpeditionConsoleState(component.NextOffer, component.Claimed, component.Cooldown, component.ActiveMission, missions); } private void SpawnMission(SalvageMissionParams missionParams, EntityUid station, EntityUid? coordinatesDisk) { var cancelToken = new CancellationTokenSource(); var job = new SpawnSalvageMissionJob( SalvageJobTime, EntityManager, _timing, _logManager, _prototypeManager, _anchorable, _biome, _dungeon, _metaData, _mapSystem, station, coordinatesDisk, missionParams, cancelToken.Token); _salvageJobs.Add((job, cancelToken)); _salvageQueue.EnqueueJob(job); } }
0
0.972825
1
0.972825
game-dev
MEDIA
0.93025
game-dev
0.978513
1
0.978513
serge-rgb/milton
2,547
third_party/SDL2-2.0.8/src/video/haiku/SDL_bclipboard.cc
/* Simple DirectMedia Layer Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_DRIVER_HAIKU /* BWindow based clipboard implementation */ #include <unistd.h> #include <TypeConstants.h> #include "SDL_BWin.h" #include "SDL_timer.h" #include "../SDL_sysvideo.h" #ifdef __cplusplus extern "C" { #endif int BE_SetClipboardText(_THIS, const char *text) { BMessage *clip = NULL; if(be_clipboard->Lock()) { be_clipboard->Clear(); if((clip = be_clipboard->Data())) { /* Presumably the string of characters is ascii-format */ ssize_t asciiLength = 0; for(; text[asciiLength] != 0; ++asciiLength) {} clip->AddData("text/plain", B_MIME_TYPE, text, asciiLength); be_clipboard->Commit(); } be_clipboard->Unlock(); } return 0; } char *BE_GetClipboardText(_THIS) { BMessage *clip = NULL; const char *text = NULL; ssize_t length; char *result; if(be_clipboard->Lock()) { if((clip = be_clipboard->Data())) { /* Presumably the string of characters is ascii-format */ clip->FindData("text/plain", B_MIME_TYPE, (const void**)&text, &length); } be_clipboard->Unlock(); } if (!text) { result = SDL_strdup(""); } else { /* Copy the data and pass on to SDL */ result = (char *)SDL_malloc((length + 1) * sizeof(char)); SDL_strlcpy(result, text, length + 1); } return result; } SDL_bool BE_HasClipboardText(_THIS) { SDL_bool result = SDL_FALSE; char *text = BE_GetClipboardText(_this); if (text) { result = text[0] != '\0' ? SDL_TRUE : SDL_FALSE; SDL_free(text); } return result; } #ifdef __cplusplus } #endif #endif /* SDL_VIDEO_DRIVER_HAIKU */ /* vi: set ts=4 sw=4 expandtab: */
0
0.7459
1
0.7459
game-dev
MEDIA
0.459439
game-dev
0.650327
1
0.650327
Sandern/lambdawars
3,441
src/game/client/python/modules/autogenerated/_gamerules/CAmmoDef_pypp.cpp
// This file has been generated by Py++. #include "cbase.h" // This file has been generated by Py++. #include "cbase.h" #include "gamerules.h" #include "multiplay_gamerules.h" #include "singleplay_gamerules.h" #include "teamplay_gamerules.h" #include "srcpy_gamerules.h" #include "ammodef.h" #include "takedamageinfo.h" #include "hl2wars_gamerules.h" #include "srcpy.h" #include "tier0/memdbgon.h" #include "CAmmoDef_pypp.hpp" namespace bp = boost::python; void register_CAmmoDef_class(){ bp::class_< CAmmoDef >( "CAmmoDef", bp::init< >() ) .def( "AddAmmoType" , (void ( ::CAmmoDef::* )( char const *,int,int,int,int,int,float,int,int,int ) )( &::CAmmoDef::AddAmmoType ) , ( bp::arg("name"), bp::arg("damageType"), bp::arg("tracerType"), bp::arg("plr_dmg"), bp::arg("npc_dmg"), bp::arg("carry"), bp::arg("physicsForceImpulse"), bp::arg("nFlags"), bp::arg("minSplashSize")=(int)(4), bp::arg("maxSplashSize")=(int)(8) ) ) .def( "AddAmmoType" , (void ( ::CAmmoDef::* )( char const *,int,int,char const *,char const *,char const *,float,int,int,int ) )( &::CAmmoDef::AddAmmoType ) , ( bp::arg("name"), bp::arg("damageType"), bp::arg("tracerType"), bp::arg("plr_cvar"), bp::arg("npc_var"), bp::arg("carry_cvar"), bp::arg("physicsForceImpulse"), bp::arg("nFlags"), bp::arg("minSplashSize")=(int)(4), bp::arg("maxSplashSize")=(int)(8) ) ) .def( "CanCarryInfiniteAmmo" , (bool ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::CanCarryInfiniteAmmo ) , ( bp::arg("nAmmoIndex") ) ) .def( "DamageForce" , (float ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::DamageForce ) , ( bp::arg("nAmmoIndex") ) ) .def( "DamageType" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::DamageType ) , ( bp::arg("nAmmoIndex") ) ) .def( "Flags" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::Flags ) , ( bp::arg("nAmmoIndex") ) ) .def( "Index" , (int ( ::CAmmoDef::* )( char const * ) )( &::CAmmoDef::Index ) , ( bp::arg("psz") ) ) .def( "MaxCarry" , (int ( ::CAmmoDef::* )( int,::C_BaseCombatCharacter const * ) )( &::CAmmoDef::MaxCarry ) , ( bp::arg("nAmmoIndex"), bp::arg("owner") ) ) .def( "MaxSplashSize" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::MaxSplashSize ) , ( bp::arg("nAmmoIndex") ) ) .def( "MinSplashSize" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::MinSplashSize ) , ( bp::arg("nAmmoIndex") ) ) .def( "NPCDamage" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::NPCDamage ) , ( bp::arg("nAmmoIndex") ) ) .def( "NumAmmoTypes" , (int ( ::CAmmoDef::* )( ) )( &::CAmmoDef::NumAmmoTypes ) ) .def( "PlrDamage" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::PlrDamage ) , ( bp::arg("nAmmoIndex") ) ) .def( "TracerType" , (int ( ::CAmmoDef::* )( int ) )( &::CAmmoDef::TracerType ) , ( bp::arg("nAmmoIndex") ) ) .def_readwrite( "ammoindex", &CAmmoDef::m_nAmmoIndex ); }
0
0.623123
1
0.623123
game-dev
MEDIA
0.520218
game-dev
0.69299
1
0.69299
minty-codes/TutorialClient1.8.8
10,523
net/minecraft/world/chunk/storage/AnvilSaveConverter.java
package net.minecraft.world.chunk.storage; import com.google.common.collect.Lists; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import net.minecraft.client.AnvilConverterException; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IProgressUpdate; import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.WorldChunkManager; import net.minecraft.world.biome.WorldChunkManagerHell; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.SaveFormatComparator; import net.minecraft.world.storage.SaveFormatOld; import net.minecraft.world.storage.WorldInfo; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class AnvilSaveConverter extends SaveFormatOld { private static final Logger logger = LogManager.getLogger(); public AnvilSaveConverter(File p_i2144_1_) { super(p_i2144_1_); } /** * Returns the name of the save format. */ public String getName() { return "Anvil"; } public List<SaveFormatComparator> getSaveList() throws AnvilConverterException { if (this.savesDirectory != null && this.savesDirectory.exists() && this.savesDirectory.isDirectory()) { List<SaveFormatComparator> list = Lists.<SaveFormatComparator>newArrayList(); File[] afile = this.savesDirectory.listFiles(); for (File file1 : afile) { if (file1.isDirectory()) { String s = file1.getName(); WorldInfo worldinfo = this.getWorldInfo(s); if (worldinfo != null && (worldinfo.getSaveVersion() == 19132 || worldinfo.getSaveVersion() == 19133)) { boolean flag = worldinfo.getSaveVersion() != this.getSaveVersion(); String s1 = worldinfo.getWorldName(); if (StringUtils.isEmpty(s1)) { s1 = s; } long i = 0L; list.add(new SaveFormatComparator(s, s1, worldinfo.getLastTimePlayed(), i, worldinfo.getGameType(), flag, worldinfo.isHardcoreModeEnabled(), worldinfo.areCommandsAllowed())); } } } return list; } else { throw new AnvilConverterException("Unable to read or access folder where game worlds are saved!"); } } protected int getSaveVersion() { return 19133; } public void flushCache() { RegionFileCache.clearRegionFileReferences(); } /** * Returns back a loader for the specified save directory */ public ISaveHandler getSaveLoader(String saveName, boolean storePlayerdata) { return new AnvilSaveHandler(this.savesDirectory, saveName, storePlayerdata); } public boolean func_154334_a(String saveName) { WorldInfo worldinfo = this.getWorldInfo(saveName); return worldinfo != null && worldinfo.getSaveVersion() == 19132; } /** * gets if the map is old chunk saving (true) or McRegion (false) */ public boolean isOldMapFormat(String saveName) { WorldInfo worldinfo = this.getWorldInfo(saveName); return worldinfo != null && worldinfo.getSaveVersion() != this.getSaveVersion(); } /** * converts the map to mcRegion */ public boolean convertMapFormat(String filename, IProgressUpdate progressCallback) { progressCallback.setLoadingProgress(0); List<File> list = Lists.<File>newArrayList(); List<File> list1 = Lists.<File>newArrayList(); List<File> list2 = Lists.<File>newArrayList(); File file1 = new File(this.savesDirectory, filename); File file2 = new File(file1, "DIM-1"); File file3 = new File(file1, "DIM1"); logger.info("Scanning folders..."); this.addRegionFilesToCollection(file1, list); if (file2.exists()) { this.addRegionFilesToCollection(file2, list1); } if (file3.exists()) { this.addRegionFilesToCollection(file3, list2); } int i = list.size() + list1.size() + list2.size(); logger.info("Total conversion count is " + i); WorldInfo worldinfo = this.getWorldInfo(filename); WorldChunkManager worldchunkmanager = null; if (worldinfo.getTerrainType() == WorldType.FLAT) { worldchunkmanager = new WorldChunkManagerHell(BiomeGenBase.plains, 0.5F); } else { worldchunkmanager = new WorldChunkManager(worldinfo.getSeed(), worldinfo.getTerrainType(), worldinfo.getGeneratorOptions()); } this.convertFile(new File(file1, "region"), list, worldchunkmanager, 0, i, progressCallback); this.convertFile(new File(file2, "region"), list1, new WorldChunkManagerHell(BiomeGenBase.hell, 0.0F), list.size(), i, progressCallback); this.convertFile(new File(file3, "region"), list2, new WorldChunkManagerHell(BiomeGenBase.sky, 0.0F), list.size() + list1.size(), i, progressCallback); worldinfo.setSaveVersion(19133); if (worldinfo.getTerrainType() == WorldType.DEFAULT_1_1) { worldinfo.setTerrainType(WorldType.DEFAULT); } this.createFile(filename); ISaveHandler isavehandler = this.getSaveLoader(filename, false); isavehandler.saveWorldInfo(worldinfo); return true; } /** * par: filename for the level.dat_mcr backup */ private void createFile(String filename) { File file1 = new File(this.savesDirectory, filename); if (!file1.exists()) { logger.warn("Unable to create level.dat_mcr backup"); } else { File file2 = new File(file1, "level.dat"); if (!file2.exists()) { logger.warn("Unable to create level.dat_mcr backup"); } else { File file3 = new File(file1, "level.dat_mcr"); if (!file2.renameTo(file3)) { logger.warn("Unable to create level.dat_mcr backup"); } } } } private void convertFile(File p_75813_1_, Iterable<File> p_75813_2_, WorldChunkManager p_75813_3_, int p_75813_4_, int p_75813_5_, IProgressUpdate p_75813_6_) { for (File file1 : p_75813_2_) { this.convertChunks(p_75813_1_, file1, p_75813_3_, p_75813_4_, p_75813_5_, p_75813_6_); ++p_75813_4_; int i = (int)Math.round(100.0D * (double)p_75813_4_ / (double)p_75813_5_); p_75813_6_.setLoadingProgress(i); } } /** * copies a 32x32 chunk set from par2File to par1File, via AnvilConverterData */ private void convertChunks(File p_75811_1_, File p_75811_2_, WorldChunkManager p_75811_3_, int p_75811_4_, int p_75811_5_, IProgressUpdate progressCallback) { try { String s = p_75811_2_.getName(); RegionFile regionfile = new RegionFile(p_75811_2_); RegionFile regionfile1 = new RegionFile(new File(p_75811_1_, s.substring(0, s.length() - ".mcr".length()) + ".mca")); for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { if (regionfile.isChunkSaved(i, j) && !regionfile1.isChunkSaved(i, j)) { DataInputStream datainputstream = regionfile.getChunkDataInputStream(i, j); if (datainputstream == null) { logger.warn("Failed to fetch input stream"); } else { NBTTagCompound nbttagcompound = CompressedStreamTools.read(datainputstream); datainputstream.close(); NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Level"); ChunkLoader.AnvilConverterData chunkloader$anvilconverterdata = ChunkLoader.load(nbttagcompound1); NBTTagCompound nbttagcompound2 = new NBTTagCompound(); NBTTagCompound nbttagcompound3 = new NBTTagCompound(); nbttagcompound2.setTag("Level", nbttagcompound3); ChunkLoader.convertToAnvilFormat(chunkloader$anvilconverterdata, nbttagcompound3, p_75811_3_); DataOutputStream dataoutputstream = regionfile1.getChunkDataOutputStream(i, j); CompressedStreamTools.write(nbttagcompound2, dataoutputstream); dataoutputstream.close(); } } } int k = (int)Math.round(100.0D * (double)(p_75811_4_ * 1024) / (double)(p_75811_5_ * 1024)); int l = (int)Math.round(100.0D * (double)((i + 1) * 32 + p_75811_4_ * 1024) / (double)(p_75811_5_ * 1024)); if (l > k) { progressCallback.setLoadingProgress(l); } } regionfile.close(); regionfile1.close(); } catch (IOException ioexception) { ioexception.printStackTrace(); } } /** * filters the files in the par1 directory, and adds them to the par2 collections */ private void addRegionFilesToCollection(File worldDir, Collection<File> collection) { File file1 = new File(worldDir, "region"); File[] afile = file1.listFiles(new FilenameFilter() { public boolean accept(File p_accept_1_, String p_accept_2_) { return p_accept_2_.endsWith(".mcr"); } }); if (afile != null) { Collections.addAll(collection, afile); } } }
0
0.935093
1
0.935093
game-dev
MEDIA
0.653999
game-dev
0.987461
1
0.987461
CommitteeOfZero/impacto
4,494
src/games/chlcc/tipsnotification.cpp
#include "tipsnotification.h" #include "../../profile/hud/tipsnotification.h" #include "../../profile/games/chlcc/tipsnotification.h" #include "../../data/tipssystem.h" #include "../../profile/game.h" namespace Impacto { namespace CHLCC { using namespace Impacto::Profile::TipsNotification; using namespace Impacto::Profile::CHLCC::TipsNotification; using namespace Impacto::UI::Widgets; TipsNotification::TipsNotification() { const auto headerText = Vm::ScriptGetTextTableStrAddress(TextTableId, HeaderMessageId); Header = Label(headerText, HeaderPosition, HeaderFontSize, RendererOutlineMode::BottomRight, HeaderColor); Header.OutlineAlphaEnabled = true; const auto beforeText = Vm::ScriptGetTextTableStrAddress( TextTableId, NotificationTextPart1MessageId); TextPartBefore = Label(beforeText, TextStartPosition, TextFontSize, RendererOutlineMode::BottomRight, 0); TextPartBefore.OutlineAlphaEnabled = true; const auto afterText = Vm::ScriptGetTextTableStrAddress( TextTableId, NotificationTextPart2MessageId); TextPartAfter = Label(afterText, TextStartPosition + glm::vec2(TextPartBefore.Bounds.Width, 0.0f), TextFontSize, RendererOutlineMode::BottomRight, 0); TextPartAfter.OutlineAlphaEnabled = true; TipName = Label( "", TextStartPosition + glm::vec2(TextPartBefore.Bounds.Width, 0.0f), TextFontSize, RendererOutlineMode::BottomRight, static_cast<int>(TipNameColorIndex)); TipName.OutlineAlphaEnabled = true; FadeAnimation.DurationIn = FadeInDuration; FadeAnimation.DurationOut = FadeOutDuration; FadeOutAnimation = FadeAnimation; SlideAnimation.DurationIn = SlideTime; HoldAnimation.DurationIn = HoldTime; TipsAnimation.AddAnimation(FadeAnimation, 0.0f); TipsAnimation.AddAnimation(SlideAnimation, 0.0f); TipsAnimation.AddAnimation(HoldAnimation); TipsAnimation.AddAnimation(FadeOutAnimation, AnimationDirection::Out); } void TipsNotification::Update(const float dt) { TipsAnimation.Update(dt); if (TipsAnimation.State == AnimationState::Stopped && !NotificationQueue.empty()) { // Start display animation const auto tipNameAdr = NotificationQueue.front(); const auto tipsScrBufId = TipsSystem::GetTipsScriptBufferId(); TipName.SetText({.ScriptBufferId = tipsScrBufId, .IpOffset = tipNameAdr}, TextFontSize, RendererOutlineMode::BottomRight, static_cast<int>(TipNameColorIndex)); NotificationQueue.pop(); TipsAnimation.StartIn(true); FirstIsRendering = FirstInQueue; FirstInQueue = false; } if (TipsAnimation.State != AnimationState::Stopped) { // Update labels const float slideProgress = std::sin(SlideAnimation.Progress * std::numbers::pi_v<float> / 2.0f); TextPartBefore.MoveTo(TextTargetPosition * slideProgress + TextStartPosition * (1.0f - slideProgress)); TipName.MoveTo(TextPartBefore.Bounds.GetPos() + glm::vec2(TextPartBefore.Bounds.Width, 0.0f)); TextPartAfter.MoveTo(TipName.Bounds.GetPos() + glm::vec2(TipName.Bounds.Width, 0.0f)); // Don't fade out if not the last entry in the queue, // and don't fade in if not the first float alpha = 1.0f; if (FadeOutAnimation.State == AnimationState::Playing) { // Fading out if (NotificationQueue.empty()) alpha = FadeOutAnimation.Progress; } else if (FirstIsRendering) { // Fading in alpha = FadeAnimation.Progress; } Header.Tint.a = alpha; TextPartBefore.Tint.a = alpha; TipName.Tint.a = alpha; TextPartAfter.Tint.a = alpha; Header.OutlineAlpha = alpha / 2.0f; TextPartBefore.OutlineAlpha = alpha / 2.0f; TipName.OutlineAlpha = alpha / 2.0f; TextPartAfter.OutlineAlpha = alpha / 2.0f; } } void TipsNotification::Render() { if (TipsAnimation.State == AnimationState::Stopped) return; Renderer->EnableScissor(); Renderer->SetScissorRect(RenderBounds); Header.Render(); TextPartBefore.Render(); TipName.Render(); TextPartAfter.Render(); Renderer->DisableScissor(); } void TipsNotification::AddTip(const int tipId) { FirstInQueue |= TipsAnimation.State == AnimationState::Stopped && NotificationQueue.empty(); const auto* const record = TipsSystem::GetTipRecord(tipId); NotificationQueue.push(record->StringAdr[1]); } } // namespace CHLCC } // namespace Impacto
0
0.888762
1
0.888762
game-dev
MEDIA
0.6105
game-dev,graphics-rendering
0.940471
1
0.940471
FireEmblemUniverse/fireemblem8u
50,072
src/savemenu.c
#include "global.h" #include "m4a.h" #include "soundwrapper.h" #include "fontgrp.h" #include "statscreen.h" #include "bmsave.h" #include "bmunit.h" #include "hardware.h" #include "uiutils.h" #include "bm.h" #include "ap.h" #include "gamecontrol.h" #include "bmlib.h" #include "eventinfo.h" #include "soundroom.h" #include "bonusclaim.h" #include "worldmap.h" #include "bonusclaim.h" #include "sysutil.h" #include "helpbox.h" #include "savemenu.h" #include "uisupport.h" #include "gba_sprites.h" #include "constants/event-flags.h" #include "constants/characters.h" #include "constants/chapters.h" #include "constants/songs.h" extern u16 gEndingTmScratchA[]; EWRAM_DATA struct SaveMenuRTextData gSaveMenuRTextData = { 0 }; // TODO: Implicit declaration int LoadBonusContentData(void *); //! FE8U = 0x080A882C void SaveMenu_NewGame(ProcPtr proc) { Proc_Goto(proc, PL_SAVEMENU_NEW_GAME); StartBgmVolumeChange(0xc0, 0, 0x10, 0); } //! FE8U = 0x080A8844 u8 SaveMenuGetBitfile(u8 bitfile, u32 number) { int i, count = 0; for (i = 0; i < CHAR_BIT; i++) { if (((bitfile >> i) & 1) != 0) { if (number == count) return (1 << i & 0xff); count++; } } return -1; } //! FE8U = 0x080A887C u8 SaveMenuGetBitfileByMask(u8 bitfile, u8 b) { int i; int count = 0; for (i = 0; i < CHAR_BIT; i++) { if (((bitfile >> i) & 1) != 0) { if (((b >> i) & 1) != 0) return count; count++; } } return -1; } //! FE8U = 0x080A88B8 u8 BitfileToIndex(u8 bitfile) { int i; for (i = 0; i < CHAR_BIT; i++) if (((bitfile >> i) & 1) != 0) return i; return -1; } //! FE8U = 0x080A88E0 void SaveMenuHandleHelpBox(struct SaveMenuProc * proc) { if ((proc->sus_slot_cur == (u8)-1) || (proc->cursor_config == 0)) { CloseHelpBox(); proc->hb_en = false; return; } switch (proc->main_sel_bitfile) { case MAIN_MENU_OPTION_RESTART: case MAIN_MENU_OPTION_NEW_GAME: case MAIN_MENU_OPTION_EXTRAS: if ((proc->cursor_config != 0) && (proc->hb_en == false)) { LoadHelpBoxGfx(OBJ_VRAM0 + OBJCHR_SAVEMENU_SLOTSEL_HELPBOX * TILE_SIZE_4BPP, OBJPAL_SAVEMENU_SLOTSEL_HELPBOX); StartHelpBoxExt_Unk(0x30, 0x30, 0x882); proc->hb_en = true; } break; } } //! FE8U = 0x080A8950 int LoadSaveMenuInfo(int slot) { int leaderId; struct GameSaveBlock *saveBase; int i; struct PlaySt chapterData; struct Unit unit; struct GMapData mapData; u8 localbuffer[4] __attribute__((unused)); if (!IsSaveValid(slot)) return 0; ReadGameSavePlaySt(slot, &chapterData); switch (chapterData.chapterModeIndex) { case CHAPTER_MODE_COMMON: case CHAPTER_MODE_EIRIKA: default: leaderId = CHARACTER_EIRIKA; break; case CHAPTER_MODE_EPHRAIM: leaderId = CHARACTER_EPHRAIM; break; } saveBase = GetSaveReadAddr(slot); for (i = 0; i < UNIT_SAVE_AMOUNT_BLUE; i++) { LoadSavedUnit(&saveBase->units[i], &unit); if (unit.pCharacterData != NULL && unit.pCharacterData->number == leaderId) break; } if (i < UNIT_SAVE_AMOUNT_BLUE) { gSaveMenuRTextData.pid = leaderId; gSaveMenuRTextData.level = unit.level; ReadWorldMapStuff(&saveBase->wmStuff, &mapData); gSaveMenuRTextData.nodeId = mapData.units[0].location; return 2; } InitSaveMenuHelpTextSt(); return 2; } //! FE8U = 0x080A89E4 bool SaveMenuWaitHelpBoxAnim(struct SaveMenuProc * proc) { /** * During open/close helpbox, player cannot control via button. * Here we give the helpbox 8 frame on switching. */ int time, _timer_default = CTRL_TIMER_MAX; if (proc->ctrl_timer == CTRL_TIMER_MAX) { if (gKeyStatusPtr->newKeys & (B_BUTTON | R_BUTTON | DPAD_ANY)) { CloseHelpBox(); proc->ctrl_timer = CTRL_TIMER_MAX - 1; } } else if (gKeyStatusPtr->newKeys & R_BUTTON) { switch (LoadSaveMenuInfo(proc->sus_slot)) { case 0: PlaySoundEffect(SONG_6C); break; case 1: case 2: LoadHelpBoxGfx(OBJ_VRAM0 + OBJCHR_SAVEMENU_SLOTSEL_HELPBOX * TILE_SIZE_4BPP, OBJPAL_SAVEMENU_SLOTSEL_HELPBOX); StartItemHelpBox(0x50, proc->sus_slot * 0x20 + 0x2c, (u16)-2); proc->ctrl_timer = _timer_default; break; } } time = proc->ctrl_timer; if (time == 0) return false; if (time < _timer_default) proc->ctrl_timer--; time = proc->ctrl_timer; if (time != 0) return true; return false; } //! FE8U = 0x080A8A9C void SaveMenuPutChapterTitle(struct SaveMenuProc * proc) { int i; PutChapterTitleBG(OBJ_PRIORITY(2) + OBJ_CHAR(OBJCHR_SAVEMENU_TITLEBG)); for (i = 0; i < 3; i++) { if (proc->chapter_idx[i] != (u8)-1) PutChapterTitleGfx((((OBJ_PRIORITY(2) + OBJCHR_SAVEMENU_TITLEGFX) * TILE_SIZE_4BPP + (0x800 * (u32)i)) & 0x1FFFF) / TILE_SIZE_4BPP, proc->chapter_idx[i]); else PutChapterTitleGfx((((OBJ_PRIORITY(2) + OBJCHR_SAVEMENU_TITLEGFX) * TILE_SIZE_4BPP + (0x800 * (u32)i)) & 0x1FFFF) / TILE_SIZE_4BPP, -1); } } u16 CONST_DATA gBgConfig_SaveMenu[] = { 0x0000, 0x6000, 0x0000, 0x0000, 0x6800, 0x0000, 0x8000, 0x7000, 0x0000, 0x8000, 0x7800, 0x0000, }; //! FE8U = 0x080A8AF0 void SaveMenu_SetLcdChapterIdx(void) { int node; u32 chapterId; if (!(gPlaySt.chapterStateBits & PLAY_FLAG_COMPLETE)) { chapterId = gPlaySt.chapterIndex; if ((gGMData.state.raw & 3) == 3) { if (chapterId > CHAPTER_L_1 && chapterId != CHAPTER_CASTLE_FRELIA) { node = GetNextUnclearedNode(&gGMData); if (node < 0) node = 0; gPlaySt.chapterIndex = WMLoc_GetChapterId(node); } } else if (gPlaySt.chapterIndex == CHAPTER_L_5 && CheckFlag(EVFLAG_136) != 0) gPlaySt.chapterIndex = CHAPTER_CASTLE_FRELIA; else if (chapterId != CHAPTER_L_1 && chapterId != CHAPTER_E_9 && chapterId != CHAPTER_I_9) { if (gPlaySt.save_menu_type != 2 && !(gBmSt.gameStateBits & BM_FLAG_PREPSCREEN)) gPlaySt.chapterIndex = GetChapterIndexOnWmNode(&gGMData); } } InitSaveMenuHelpTextSt(); SetupBackgrounds(gBgConfig_SaveMenu); SetDispEnable(0, 0, 0, 0, 0); gLCDControlBuffer.dispcnt.mode = DISPCNT_MODE_0; gLCDControlBuffer.bg0cnt.priority = 0; gLCDControlBuffer.bg1cnt.priority = 1; gLCDControlBuffer.bg2cnt.priority = 2; gLCDControlBuffer.bg3cnt.priority = 3; SetBlendTargetA(0, 0, 1, 0, 0); SetBlendTargetB(0, 0, 0, 1, 0); SetBlendBackdropA(0); SetBlendBackdropB(0); SetBlendConfig(1, 6, 0x10, 0); } //! FE8U = 0x080A8C2C void SaveMenu_Init(void) { InitSaveMenuHelpTextSt(); SetupBackgrounds(gBgConfig_SaveMenu); SetDispEnable(0, 0, 0, 0, 0); gLCDControlBuffer.dispcnt.mode = DISPCNT_MODE_0; gLCDControlBuffer.bg0cnt.priority = 0; gLCDControlBuffer.bg1cnt.priority = 1; gLCDControlBuffer.bg2cnt.priority = 2; gLCDControlBuffer.bg3cnt.priority = 3; SetBlendTargetA(0, 0, 1, 0, 0); SetBlendTargetB(0, 0, 0, 1, 0); SetBlendBackdropA(0); SetBlendBackdropB(0); SetBlendConfig(1, 6, 0x10, 0); } //! FE8U = 0x080A8CD4 void SaveMenu_InitScreen(struct SaveMenuProc * proc) { int i; ResetTextFont(); LoadUiFrameGraphics(); LoadObjUIGfx(); ApplyPalettes(Pal_SaveMenuBG, OBJPAL_SAVEMENU_TITLEBG, 8); Decompress(Img_SaveMenuBG, (void*)BG_VRAM + GetBackgroundTileDataOffset(BG_3)); CallARM_FillTileRect(gBG3TilemapBuffer, Tsa_SaveMenuBG, 0x8000); ApplyPalette(Pal_MainMenuBgFog, BGPAL_SAVEMENU_BGFOG); Decompress(Img_MainMenuBgFog, (void*)BG_VRAM + GetBackgroundTileDataOffset(BG_3) + BGCHR_SAVEMENU_BGFOG * TILE_SIZE_4BPP); Decompress(Tsa_MainMenuBgFog, gGenericBuffer); CallARM_FillTileRect( gBG2TilemapBuffer, gGenericBuffer, OBJ_PALETTE(BGPAL_SAVEMENU_BGFOG) + OBJ_PRIORITY(0) + OBJ_CHAR(BGCHR_SAVEMENU_BGFOG)); Decompress(Img_SaveScreenSprits, OBJ_VRAM0 + OBJCHR_SAVEMENU_SPRITES * TILE_SIZE_4BPP); ApplyPalettes(Pal_SaveScreenSprits, OBJPAL_SAVEMENU_SPRITES + 0x10, 8); ApplyPalette(Pal_08A295B4, 2); SaveMenuCopyPalette(PAL_OBJ(0x2), PAL_OBJ(0x1), 1); SaveMenuCopyPalette(gUnknown_08A2C23C, gEndingTmScratchA, 2); BG_EnableSyncByMask(BG0_SYNC_BIT | BG1_SYNC_BIT | BG2_SYNC_BIT | BG3_SYNC_BIT); proc->scroll_cnt = 0; gLCDControlBuffer.wincnt.win0_enableBlend = 1; gLCDControlBuffer.wincnt.win1_enableBlend = 1; proc->cursor_config = 0; proc->cursor_slot = -1; proc->unk_3d = 0; for (i = 0; i < 4; i++) { SetObjAffine( i, Div(+COS(0) * 16, 0x100), Div(-SIN(0) * 16, 0x100), Div(+SIN(0) * 16, 0x100), Div(+COS(0) * 16, 0x100) ); } proc->unk_44 = 0x100; proc->sus_slot_cur = -1; proc->hb_en = false; proc->ctrl_timer = 0; for (i = 0; i < 4; i++) SaveMenuInitSaveSlotData(i, proc); SaveMenuInitSlotPalette(proc->sus_slot); SaveMenuInitSubBoxText(); BG_EnableSyncByMask(BG1_SYNC_BIT); SetWinEnable(0, 0, 0); gPaletteBuffer[PAL_BACKDROP_OFFSET] = 0; EnablePaletteSync(); SaveMenuPutChapterTitle(proc); proc->savedraw = StartSaveDraw(proc); } //! FE8U = 0x080A8F04 void SaveMenu_LoadExtraMenuGraphics(struct SaveMenuProc * proc) { Decompress(Img_GameMainMenuObjs, OBJ_VRAM0 + OBJCHR_SAVEMENU_MAINCHOICE_STR * TILE_SIZE_4BPP); InitSaveMenuChoice(proc); if (proc->main_sel_bitfile == MAIN_MENU_OPTION_EXTRAS) { proc->main_select = SaveMenuGetValidMenuAmt(MAIN_MENU_OPTION_EXTRAS, proc); } else { proc->jump_label = PL_SAVEMENU_MAIN_LOOP; proc->sus_slot = 0; proc->main_select = 0; proc->extra_select = 0; proc->unk_46 = 0; proc->main_sel_bitfile = SaveMenuGetBitfile(proc->main_options, proc->main_select); } if (proc->jump_label == PL_SAVEMENU_MAIN_LOOP) proc->unk_2f = 0; if (proc->jump_label == PL_SAVEMENU_SAVE_SLOT_SEL) proc->unk_2f = 0xdc; } //! FE8U = 0x080A8F8C void SaveMenuInit(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_SAVE_SLOT_SEL; proc->sus_slot = ReadLastGameSaveId(); proc->main_select = 0; proc->extra_select = 0; proc->unk_46 = 0; proc->main_options = MAIN_MENU_OPTION_INVALID; proc->main_sel_bitfile = MAIN_MENU_OPTION_INVALID; proc->unk_31 = 0; proc->unk_2f = 0xdc; } //! FE8U = 0x080A8FD0 void SaveMenuInitUnused(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_SAVE_SLOT_SEL; proc->sus_slot = ReadLastGameSaveId(); proc->main_select = 0; proc->extra_select = 0; proc->unk_46 = 0; proc->main_options = MAIN_MENU_OPTION_7; proc->main_sel_bitfile = MAIN_MENU_OPTION_7; proc->unk_31 = 0; proc->unk_2f = 0xdc; } //! FE8U = 0x080A9014 void SaveMenu_JumpToTarget(struct SaveMenuProc * proc) { Proc_Goto(proc, proc->jump_label); } //! FE8U = 0x080A9024 void SameMenu_CtrlLoop(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_MAIN_LOOP; if (gKeyStatusPtr->repeatedKeys & DPAD_UP) { if (proc->main_select != 0) { proc->main_select--; PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } else { if (gKeyStatusPtr->newKeys & DPAD_UP) { proc->main_select = proc->unk_31 - 1; PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } } } else if (gKeyStatusPtr->repeatedKeys & DPAD_DOWN) { if (proc->main_select < proc->unk_31 - 1) { proc->main_select++; PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } else { if (gKeyStatusPtr->newKeys & DPAD_DOWN) { proc->main_select = 0; PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } } } if (gKeyStatusPtr->newKeys & A_BUTTON) { proc->main_sel_bitfile = SaveMenuGetBitfile(proc->main_options, proc->main_select); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); proc->scroll_cnt = 0; switch (proc->main_sel_bitfile) { case MAIN_MENU_OPTION_RESUME: proc->sus_slot = proc->sus_slot_cur; Proc_Goto(proc, PL_SAVEMENU_SCROLL_SLOT); break; case MAIN_MENU_OPTION_RESTART: case MAIN_MENU_OPTION_COPY: case MAIN_MENU_OPTION_ERASE: proc->sus_slot = SaveMenuModifySaveSlot(ReadLastGameSaveId(), 1, 1); Proc_Goto(proc, PL_SAVEMENU_SCROLL_SLOT); break; case MAIN_MENU_OPTION_NEW_GAME: proc->sus_slot = SaveMenuModifySaveSlot(proc->sus_slot, 0, 1); Proc_Goto(proc, PL_SAVEMENU_DIFFICULTY_SEL); StartBgmVolumeChange(0xC0, 0x100, 0x10, 0); break; case MAIN_MENU_OPTION_EXTRAS: if (proc->extra_select >= proc->max_choice) proc->extra_select = 0; Proc_Goto(proc, PL_SAVEMENU_8); break; default: return; } } else if (gKeyStatusPtr->newKeys & B_BUTTON) { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); Proc_Goto(proc, PL_SAVEMENU_NEW_GAME); proc->main_sel_bitfile = MAIN_MENU_OPTION_EXIT; } } //! FE8U = 0x080A9250 void SaveMenuWriteNewGame(struct SaveMenuProc * proc) { int isDifficult; s8 isTutorial; switch (proc->difficulty) { case 0: isTutorial = 0; isDifficult = 0; break; case 1: isTutorial = 1; isDifficult = 0; break; case 2: isTutorial = 1; isDifficult = 1; break; } WriteNewGameSave(proc->sus_slot, isDifficult, 1, isTutorial); } //! FE8U = 0x080A9290 void ExecSaveMenuMiscOption(struct SaveMenuProc * proc) { if (proc->cursor_config == 0) { PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); switch (proc->main_sel_bitfile) { case MAIN_MENU_OPTION_COPY: if (proc->cursor_slot == (u8)-1) { proc->cursor_slot = proc->sus_slot; SaveMenuTryMoveSaveSlotCursor(proc, 1); return; } CopyGameSave(proc->cursor_slot, proc->sus_slot); Proc_Goto(proc, PL_SAVEMENU_SLOT_SELECTED); return; case MAIN_MENU_OPTION_ERASE: proc->cursor_config = 2; SaveMenuDrawSubSelBox(proc, 1); break; case MAIN_MENU_OPTION_INVALID: proc->cursor_config = 1; SaveMenuDrawSubSelBox(proc, 1); break; case MAIN_MENU_OPTION_RESTART: case MAIN_MENU_OPTION_EXTRAS: case MAIN_MENU_OPTION_NEW_GAME: proc->cursor_config = 2; SaveMenuDrawSubSelBox(proc, 1); break; } SaveMenuHandleHelpBox(proc); return; } switch (proc->main_sel_bitfile) { case MAIN_MENU_OPTION_EXTRAS: if (proc->cursor_config == 1) { proc->unk_44 = 0xf0; ReadGameSave(proc->sus_slot); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); if (proc->extra_sel_bitfile != EXTRA_MENU_OPTION_MAP) { if (proc->extra_sel_bitfile == EXTRA_MENU_OPTION_BONUS_CLAIM) Proc_Goto(proc, PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION); break; } SaveMenu_NewGame(proc); } else { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } break; case MAIN_MENU_OPTION_RESTART: if (proc->cursor_config == 1) { proc->unk_44 = 0xf0; PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); SaveMenu_NewGame(proc); } else { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } break; case MAIN_MENU_OPTION_NEW_GAME: if (proc->cursor_config == 1) { SaveMenuWriteNewGame(proc); Proc_Goto(proc, PL_SAVEMENU_SLOT_SELECTED); PlaySoundEffect(SONG_60); } else { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } break; case MAIN_MENU_OPTION_ERASE: if (proc->cursor_config == 1) { InvalidateGameSave(proc->sus_slot); Proc_Goto(proc, PL_SAVEMENU_SLOT_SELECTED); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); } else { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } break; case MAIN_MENU_OPTION_INVALID: if (proc->cursor_config == 1) { WriteGameSave(proc->sus_slot); Proc_Goto(proc, PL_SAVEMENU_SLOT_SELECTED); PlaySoundEffect(SONG_60); } else { Proc_Goto(proc, PL_SAVEMENU_EXIT_FADE); proc->main_sel_bitfile |= MAIN_MENU_OPTION_EXIT; PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } break; } SaveMenuDrawSubSelBox(proc, 0); SaveMenuHandleHelpBox(proc); } //! FE8U = 0x080A9494 void SaveMenu_SaveSlotSelectLoop(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_SAVE_SLOT_SEL; if (SaveMenuWaitHelpBoxAnim(proc)) return; if (proc->cursor_config == 0) { if (gKeyStatusPtr->newKeys & DPAD_UP) { if (SaveMenuTryMoveSaveSlotCursor(proc, -1) != 0) { PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } } else if (gKeyStatusPtr->newKeys & DPAD_DOWN) { if (SaveMenuTryMoveSaveSlotCursor(proc, 1) != 0) { PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } } } else if (gKeyStatusPtr->newKeys & DPAD_LEFT) { if (proc->cursor_config != 1) { proc->cursor_config = 1; PlaySoundEffect(SONG_SE_SYS_CURSOR_LR1); SaveMenuHandleHelpBox(proc); } } else if (gKeyStatusPtr->newKeys & DPAD_RIGHT) { if (proc->cursor_config != 2) { proc->cursor_config = 2; PlaySoundEffect(SONG_SE_SYS_CURSOR_LR1); SaveMenuHandleHelpBox(proc); } } if (gKeyStatusPtr->newKeys & A_BUTTON) { proc->scroll_cnt = 0; switch (proc->main_sel_bitfile) { case MAIN_MENU_OPTION_RESTART: if (proc->sus_slot_cur != (u8)-1) { ExecSaveMenuMiscOption(proc); return; } PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); SaveMenu_NewGame(proc); return; case MAIN_MENU_OPTION_7: if (proc->sus_slot_cur != (u8)-1) proc->unk_44 = 0xf0; PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); SaveMenu_NewGame(proc); return; case MAIN_MENU_OPTION_RESUME: PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); SaveMenu_NewGame(proc); return; case MAIN_MENU_OPTION_NEW_GAME: if (proc->sus_slot_cur == (u8)-1) break; PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); ExecSaveMenuMiscOption(proc); return; case MAIN_MENU_OPTION_COPY: case MAIN_MENU_OPTION_ERASE: case MAIN_MENU_OPTION_INVALID: ExecSaveMenuMiscOption(proc); return; default: return; } SaveMenuWriteNewGame(proc); Proc_Goto(proc, PL_SAVEMENU_SLOT_SELECTED); PlaySoundEffect(SONG_60); return; } else if (gKeyStatusPtr->newKeys & B_BUTTON) { proc->scroll_cnt = 0; PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); if (proc->cursor_config != 0) { SaveMenuDrawSubSelBox(proc, 0); SaveMenuHandleHelpBox(proc); return; } if (proc->cursor_slot != (u8)-1) { proc->sus_slot = proc->cursor_slot; proc->cursor_slot = -1; return; } if (proc->main_sel_bitfile & (MAIN_MENU_OPTION_7 | MAIN_MENU_OPTION_INVALID)) { Proc_Goto(proc, PL_SAVEMENU_EXIT_FADE); proc->main_sel_bitfile |= MAIN_MENU_OPTION_EXIT; return; } Proc_Goto(proc, PL_SAVEMENU_BACK_TO_MAIN); } } //! FE8U = 0x080A96D0 void _ExecSaveMenuMiscOption(struct SaveMenuProc * proc) { ExecSaveMenuMiscOption(proc); } //! FE8U = 0x080A96DC void SaveMenuRegisterSlotSelected(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_SLOT_SELECTED; proc->scroll_cnt = 0; } //! FE8U = 0x080A96EC void SaveMenuWaitSlotBoxScrolling(struct SaveMenuProc * proc) { if (proc->scroll_cnt == 8) { SaveMenuInitSaveSlotData(proc->sus_slot, proc); SaveMenuInitSaveSlotData(4, proc); if (proc->chapter_idx[proc->sus_slot] != (u8)-1) PutChapterTitleGfx(((u32)(proc->sus_slot * 0x800 + (OBJ_PRIORITY(2) + OBJCHR_SAVEMENU_TITLEGFX) * TILE_SIZE_4BPP) & 0x0001FFFF) >> 5, proc->chapter_idx[proc->sus_slot]); else PutChapterTitleGfx(((u32)(proc->sus_slot * 0x800 + (OBJ_PRIORITY(2) + OBJCHR_SAVEMENU_TITLEGFX) * TILE_SIZE_4BPP) & 0x0001FFFF) >> 5, -1); SaveMenuInitSlotPalette(proc->sus_slot); } else if (proc->scroll_cnt == 0x20) { InitSaveMenuChoice(proc); if (proc->main_sel_bitfile == MAIN_MENU_OPTION_NEW_GAME) { Proc_Goto(proc, PL_SAVEMENU_NEW_GAME); StartBgmVolumeChange(0xc0, 0, 0x10, 0); } else if (proc->main_sel_bitfile == MAIN_MENU_OPTION_INVALID) { Proc_Goto(proc, PL_SAVEMENU_EXIT_FADE); } else if (SaveMenuHasOptions(proc)) { if (proc->cursor_slot != (u8)-1) { proc->sus_slot = proc->cursor_slot; proc->cursor_slot = -1; } else proc->sus_slot = SaveMenuModifySaveSlot(proc->sus_slot, 1, 1); Proc_Goto(proc, PL_SAVEMENU_SAVE_SLOT_SEL); } } else if (proc->scroll_cnt == 0x30) { proc->sus_slot = 0; proc->cursor_slot = -1; proc->scroll_cnt = 0; proc->main_select = 0; proc->main_sel_bitfile = SaveMenuGetBitfile(proc->main_options, 0); PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); Proc_Goto(proc, PL_SAVEMENU_BACK_TO_MAIN); return; } if (proc->scroll_cnt == 0x10) { SetObjAffine( proc->sus_slot, Div(+COS(0) * 16, 0x100), Div(-SIN(0) * 16, 0x100), Div(+SIN(0) * 16, 0x100), Div(+COS(0) * 16, 0x100) ); } else { if ((proc->scroll_cnt <= 7)) { SetObjAffine( proc->sus_slot, Div(+COS(0) * 16, 0x100), Div(-SIN(0) * 16, (proc->scroll_cnt * -0x20) + 0x100), Div(+SIN(0) * 16, 0x100), Div(+COS(0) * 16, (proc->scroll_cnt * -0x20) + 0x100) ); } else if ((proc->scroll_cnt < 0x10)) { SetObjAffine( proc->sus_slot, Div(+COS(0) * 16, 0x100), Div(-SIN(0) * 16, (proc->scroll_cnt * 0x20) - 0xE0), Div(+SIN(0) * 16, 0x100), Div(+COS(0) * 16, (proc->scroll_cnt * 0x20) - 0xE0) ); } } proc->scroll_cnt++; } //! FE8U = 0x080A99C0 void SaveMenuScrollSlot(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_SCROLL_SLOT; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_2f = -0x24 - (unk * 0xdc * unk / 0xc4); if (proc->scroll_cnt == 0xe) Proc_Break(proc); } //! FE8U = 0x080A9A08 void sub_80A9A08(struct SaveMenuProc * proc) { sub_80ABF74(proc->extra_sel_bitfile); } //! FE8U = 0x080A9A18 void SaveMenuScrollBackToMain(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_BACK_TO_MAIN; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_2f = (unk * 0xdc * unk / 0xc4); if (proc->scroll_cnt == 0xe) { Decompress(Img_GameMainMenuObjs, OBJ_VRAM0 + OBJCHR_SAVEMENU_MAINCHOICE_STR * TILE_SIZE_4BPP); Proc_Break(proc); } } //! FE8U = 0x080A9A68 void sub_80A9A68(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_8; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_46 = 0xdc - (unk * 0xdc * unk / 0xc4); if (proc->scroll_cnt == 0xe) { Proc_Goto(proc, PL_SAVEMENU_10); } } //! FE8U = 0x080A9AB0 void sub_80A9AB0(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_8; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_46 = (unk * 0xdc * unk / 0xc4); if (proc->scroll_cnt == 0xe) Proc_Goto(proc, PL_SAVEMENU_MAIN_LOOP); } //! FE8U = 0x080A9AF4 void sub_80A9AF4(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_12; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_46 = 0x1b8 - (unk * 0xdc * unk / 0xc4); proc->unk_2f = proc->unk_46 + 0x24; if (proc->scroll_cnt == 0xe) Proc_Goto(proc, PL_SAVEMENU_POST_BONUS_CLAIM); } //! FE8U = 0x080A9B44 void sub_80A9B44(struct SaveMenuProc * proc) { int unk; proc->jump_label = PL_SAVEMENU_13; proc->scroll_cnt++; unk = 0xe - proc->scroll_cnt; proc->unk_46 = 0xdc + (unk * 0xdc * unk / 0xc4); proc->unk_2f = proc->unk_46 - 0xdc; if (proc->scroll_cnt == 0xe) Proc_Goto(proc, PL_SAVEMENU_10); } //! FE8U = 0x080A9B90 void sub_80A9B90(struct SaveMenuProc * proc) { int previous = proc->extra_select; proc->jump_label = PL_SAVEMENU_10; if (gKeyStatusPtr->repeatedKeys & DPAD_UP) { if (proc->extra_select != 0) proc->extra_select--; else if (gKeyStatusPtr->newKeys & DPAD_UP) proc->extra_select = proc->max_choice - 1; } else if (gKeyStatusPtr->repeatedKeys & DPAD_DOWN) { if (proc->extra_select < proc->max_choice - 1) proc->extra_select++; else if (gKeyStatusPtr->newKeys & DPAD_DOWN) proc->extra_select = 0; } if (previous != proc->extra_select) { PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); } if (gKeyStatusPtr->newKeys & A_BUTTON) { proc->extra_sel_bitfile = SaveMenuGetBitfile(proc->extra_options, proc->extra_select); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); proc->scroll_cnt = 0; switch (proc->extra_sel_bitfile) { case EXTRA_MENU_OPTION_6: proc->sus_slot = SaveMenuModifySaveSlot(ReadLastGameSaveId(), 1, 1); sub_80A9D20(proc, 0); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); Proc_Goto(proc, PL_SAVEMENU_12); break; case EXTRA_MENU_OPTION_SOUND_ROOM: CallSomeSoundMaybe(SONG_NONE, 0xc0, 0, 0x18, 0); Proc_Goto(proc, PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION); break; case EXTRA_MENU_OPTION_SUPPORT: CallSomeSoundMaybe(SONG_DISTANT_ROADS, 0xc0, 0x100, 0x18, 0); Proc_Goto(proc, PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION); break; case EXTRA_MENU_OPTION_MAP: proc->sus_slot = SaveMenuModifySaveSlot(ReadLastGameSaveId(), 1, 1); sub_80A9D20(proc, 0); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); Proc_Goto(proc, PL_SAVEMENU_12); break; case EXTRA_MENU_OPTION_BONUS_CLAIM: proc->sus_slot = SaveMenuModifySaveSlot(ReadLastGameSaveId(), 1, 1); sub_80A9D20(proc, 0); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); Proc_Goto(proc, PL_SAVEMENU_12); break; default: SaveMenu_NewGame(proc); Proc_Goto(proc, PL_SAVEMENU_NEW_GAME); break; } } else if (gKeyStatusPtr->newKeys & B_BUTTON) { proc->scroll_cnt = 0; Proc_Goto(proc, PL_SAVEMENU_9); PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); } } //! FE8U = 0x080A9D20 s8 sub_80A9D20(struct SaveMenuProc * proc, int direction) { u8 unk = proc->sus_slot; if (unk > 2) { proc->sus_slot = 0; } if (direction == 0) { return 1; } if (direction > 0) { if (proc->sus_slot < 2) { proc->sus_slot = proc->sus_slot + 1; } else { proc->sus_slot = 0; } } else { if (proc->sus_slot == 0) { proc->sus_slot = 2; } else { proc->sus_slot = proc->sus_slot - 1; } } if (unk != proc->sus_slot) { PlaySoundEffect(SONG_SE_SYS_CURSOR_UD1); return 1; } return 0; } //! FE8U = 0x080A9D84 void sub_80A9D84(struct SaveMenu8A20068Proc * proc) { LoadHelpBoxGfx(OBJ_VRAM0 + OBJCHR_SAVEMENU_SLOTSEL_HELPBOX * TILE_SIZE_4BPP, OBJPAL_SAVEMENU_SLOTSEL_HELPBOX); StartHelpBoxExt_Unk(proc->x, proc->y, proc->msgId); PlaySoundEffect(SONG_70); } //! FE8U = 0x080A9DBC void sub_80A9DBC(struct SaveMenu8A20068Proc * proc) { if (gKeyStatusPtr->newKeys & (A_BUTTON | B_BUTTON | R_BUTTON)) { PlaySoundEffect(SONG_71); CloseHelpBox(); Proc_Break(proc); } } struct ProcCmd CONST_DATA gProcScr_08A20068[] = { PROC_YIELD, PROC_CALL(sub_80A9D84), PROC_SLEEP(8), PROC_REPEAT(sub_80A9DBC), PROC_SLEEP(8), PROC_END, }; //! FE8U = 0x080A9DFC void sub_80A9DFC(int x, int y, int msgId, ProcPtr parent) { struct SaveMenu8A20068Proc * proc = Proc_StartBlocking(gProcScr_08A20068, parent); proc->msgId = msgId; proc->x = x; proc->y = y; } //! FE8U = 0x080A9E1C void sub_80A9E1C(struct SaveMenuProc * proc) { proc->jump_label = PL_SAVEMENU_SAVE_SLOT_SEL; if (proc->cursor_config == 0) { if (gKeyStatusPtr->newKeys & DPAD_UP) sub_80A9D20(proc, -1); else if (gKeyStatusPtr->newKeys & DPAD_DOWN) sub_80A9D20(proc, 1); } else if (gKeyStatusPtr->newKeys & DPAD_LEFT) { if (proc->cursor_config != 1) { proc->cursor_config = 1; PlaySoundEffect(SONG_SE_SYS_CURSOR_LR1); } } else if (gKeyStatusPtr->newKeys & DPAD_RIGHT) { if (proc->cursor_config != 2) { proc->cursor_config = 2; PlaySoundEffect(SONG_SE_SYS_CURSOR_LR1); } } if (gKeyStatusPtr->newKeys & A_BUTTON) { switch (proc->extra_sel_bitfile) { case EXTRA_MENU_OPTION_6: if (((proc->unk_3a[proc->sus_slot]) & 1) != 0) { if (proc->sus_slot_cur != (u8)-1) { ExecSaveMenuMiscOption(proc); return; } ReadGameSave(proc->sus_slot); Proc_Goto(proc, PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); return; } sub_80A9DFC(0x40, 0x30, 0x892, proc); // TODO: msgid "This data[.][NL]can't be used[.][NL]on a trial map.[.]" return; case EXTRA_MENU_OPTION_BONUS_CLAIM: if (((proc->unk_3a[proc->sus_slot]) & 2) != 0) { if (proc->sus_slot_cur != (u8)-1) { ExecSaveMenuMiscOption(proc); return; } ReadGameSave(proc->sus_slot); Proc_Goto(proc, PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); return; } sub_80A9DFC(0x2e, 0x38, 0x891, proc); // TODO: msgid "Send data from[NL]Chapter 2+" return; case EXTRA_MENU_OPTION_MAP: if (((proc->unk_3a[proc->sus_slot]) & 4) != 0) { if (proc->sus_slot_cur == (u8)-1) { ReadGameSave(proc->sus_slot); SaveMenu_NewGame(proc); PlaySoundEffect(SONG_SE_SYS_WINDOW_SELECT1); return; } ExecSaveMenuMiscOption(proc); return; } sub_80A9DFC(0x2e, 0x38, 0x895, proc); // TODO: msgid "Select cleared save data.[.]" return; default: return; } } else if (gKeyStatusPtr->newKeys & B_BUTTON) { PlaySoundEffect(SONG_SE_SYS_WINDOW_CANSEL1); if (proc->cursor_config != 0) { SaveMenuDrawSubSelBox(proc, 0); SaveMenuHandleHelpBox(proc); return; } Decompress(Img_GameMainMenuObjs, OBJ_VRAM0 + OBJCHR_SAVEMENU_MAINCHOICE_STR * TILE_SIZE_4BPP); proc->scroll_cnt = 0; Proc_Goto(proc, PL_SAVEMENU_13); return; } } //! FE8U = 0x080AA018 void sub_80AA018(struct SaveMenuProc * proc) { StartSqMask(proc, 1, 2); Proc_Break(proc); } //! FE8U = 0x080AA030 void PostSaveMenuHandler(struct SaveMenuProc * proc) { if (proc->approc != 0) APProc_Delete(proc->approc); Proc_End(proc->savedraw); SetPrimaryHBlankHandler(0); if (proc->main_sel_bitfile == 0x20) { switch (proc->extra_sel_bitfile) { case 1: SetNextGameActionId(GAME_ACTION_6); return; case 0x10: SetNextGameActionId(GAME_ACTION_C); gPlaySt.chapterStateBits |= PLAY_FLAG_POSTGAME; return; } } else if (proc->main_sel_bitfile & 0x40) { return; } else if (proc->main_sel_bitfile & 0x100) { StartBgmVolumeChange(0xc0, 0x100, 0x10, 0); if ((proc->main_sel_bitfile & 0x80) != 0) { SetNextGameActionId(GAME_ACTION_A); } else { SetNextGameActionId(GAME_ACTION_5); } } else if (proc->main_sel_bitfile & 1) { ReadSuspendSave(3); SetNextGameActionId(GAME_ACTION_4); } else if (proc->main_sel_bitfile & 0x82) { ReadGameSave(proc->sus_slot); SetNextGameActionId(proc->sus_slot + 1); } else if (proc->main_sel_bitfile & 0x10) { SetNextGameActionId(GAME_ACTION_EVENT_RETURN); } } //! FE8U = 0x080AA100 void ExtraMapStartSomeBgm(struct SaveMenuProc * proc) { CallSomeSoundMaybe(SONG_NONE, 0xc0, 0, 0x18, proc); } //! FE8U = 0x080AA118 void ExecExtraMap(struct SaveMenuProc * proc) { SetNextGameActionId(GAME_ACTION_EXTRA_MAP); gPlaySt.chapterStateBits |= PLAY_FLAG_EXTRA_MAP; ReadExtraMapInfo(); gPlaySt.chapterIndex = CHAPTER_7F; Proc_End(proc->proc_parent); } struct ProcCmd CONST_DATA ProcScr_CallExtraMap[] = { PROC_CALL(ExtraMapStartSomeBgm), PROC_YIELD, PROC_CALL(ExecExtraMap), PROC_END, }; //! FE8U = 0x080AA144 void CallExtraMap(ProcPtr parent) { Proc_StartBlocking(ProcScr_CallExtraMap, parent); } //! FE8U = 0x080AA158 void SaveMenuStartExtraMiscScreen(struct SaveMenuProc * proc) { proc->main_sel_bitfile = MAIN_MENU_OPTION_EXTRAS; Proc_End(proc->savedraw); SetPrimaryHBlankHandler(0); if (proc->approc != 0) APProc_Delete(proc->approc); switch (proc->extra_sel_bitfile) { default: return; case EXTRA_MENU_OPTION_6: CallExtraMap(proc); return; case EXTRA_MENU_OPTION_BONUS_CLAIM: StartBonusClaimScreen(proc); return; case EXTRA_MENU_OPTION_SOUND_ROOM: StartSoundRoomScreen(proc); return; case EXTRA_MENU_OPTION_SUPPORT: StartSupportScreen(proc); return; } } //! FE8U = 0x080AA1BC void SaveMenuPostExtraMiscScreen(struct SaveMenuProc * proc) { switch (proc->extra_sel_bitfile) { case EXTRA_MENU_OPTION_MAP: case EXTRA_MENU_OPTION_BONUS_CLAIM: Proc_Goto(proc, PL_SAVEMENU_POST_BONUS_CLAIM); return; case EXTRA_MENU_OPTION_SUPPORT: case EXTRA_MENU_OPTION_SOUND_ROOM: Proc_Goto(proc, PL_SAVEMENU_10); return; } } //! FE8U = 0x080AA1EC void SaveMenu_ResetLcdFormDifficulty(struct SaveMenuProc * proc) { proc->scroll_cnt = 0; gLCDControlBuffer.dispcnt.win0_on = 0; gLCDControlBuffer.dispcnt.win1_on = 0; gLCDControlBuffer.dispcnt.objWin_on = 0; gLCDControlBuffer.wincnt.win0_enableBg0 = 1; gLCDControlBuffer.wincnt.win0_enableBg1 = 1; gLCDControlBuffer.wincnt.win0_enableBg2 = 1; gLCDControlBuffer.wincnt.win0_enableBg3 = 1; gLCDControlBuffer.wincnt.win0_enableObj = 1; gLCDControlBuffer.wincnt.wout_enableBg0 = 0; gLCDControlBuffer.wincnt.wout_enableBg1 = 0; gLCDControlBuffer.wincnt.wout_enableBg2 = 0; gLCDControlBuffer.wincnt.wout_enableBg3 = 0; gLCDControlBuffer.wincnt.wout_enableObj = 0; } //! FE8U = 0x080AA248 void sub_80AA248(struct SaveMenuProc * proc) { int unkA; int unkB; proc->scroll_cnt++; unkA = (0x10 - proc->scroll_cnt); unkB = 0x50 - ((unkA * 0x50 * unkA) / 256); gLCDControlBuffer.win0_left = 0; gLCDControlBuffer.win0_top = 0x50 - (unkB); gLCDControlBuffer.win0_right = 0xf0; gLCDControlBuffer.win0_bottom = unkB + 0x50; if (proc->scroll_cnt == 0x10) { Proc_Break(proc); } } //! FE8U = 0x080AA2A8 void sub_80AA2A8(struct SaveMenuProc * proc) { int unkA; int unkB; proc->scroll_cnt++; unkA = (0x10 - proc->scroll_cnt); unkB = 0x50 - ((unkA * 0x50 * unkA) / 256); gLCDControlBuffer.win0_left = 0; gLCDControlBuffer.win0_top = unkB; gLCDControlBuffer.win0_right = 0xf0; gLCDControlBuffer.win0_bottom = -0x60 - unkB; if (proc->scroll_cnt == 0x10) { Proc_Break(proc); } } //! FE8U = 0x080AA30C void SaveMenu_ReloadScreenFormDifficulty(struct SaveMenuProc * proc) { BG_Fill(gBG0TilemapBuffer, 0); BG_Fill(gBG1TilemapBuffer, 0); ResetTextFont(); LoadUiFrameGraphics(); LoadObjUIGfx(); ApplyPalettes(Pal_SaveMenuBG, 8, 8); Decompress(Img_SaveMenuBG, (void*)(GetBackgroundTileDataOffset(3) + VRAM)); CallARM_FillTileRect(gBG3TilemapBuffer, Tsa_SaveMenuBG, 0x8000); ApplyPalette(Pal_MainMenuBgFog, 7); Decompress(Img_MainMenuBgFog, (void*)(GetBackgroundTileDataOffset(3) + 0x06004C00)); Decompress(Tsa_MainMenuBgFog, gGenericBuffer); CallARM_FillTileRect(gBG2TilemapBuffer, gGenericBuffer, 0x00007260); Decompress(Img_SaveScreenSprits, (void*)0x06010800); ApplyPalettes(Pal_SaveScreenSprits, 0x12, 8); ApplyPalette(Pal_08A295B4, 2); SaveMenuCopyPalette(PAL_OBJ(0x2), PAL_OBJ(0x2) - 0x10, 1); Decompress(Img_GameMainMenuObjs, OBJ_VRAM0 + OBJCHR_SAVEMENU_MAINCHOICE_STR * TILE_SIZE_4BPP); SaveMenuInitSubBoxText(); SaveMenuPutChapterTitle(proc); SaveMenuInitSlotPalette(proc->sus_slot); Proc_UnblockEachMarked(PROC_MARK_SAVEDRAW); Proc_UnblockEachMarked(PROC_MARK_D); BG_EnableSyncByMask(3); if (proc->difficulty != 3) { proc->jump_label = PL_SAVEMENU_SAVE_SLOT_SEL; proc->unk_2f = 0xdc; } EnablePaletteSync(); } //! FE8U = 0x080AA458 void SaveMenu_PostDifficultHandler(struct SaveMenuProc * proc) { if (proc->difficulty == 3) Proc_Goto(proc, 2); else Proc_Goto(proc, 5); } //! FE8U = 0x080AA47C void SaveMenuSlotSelDrawSprite(struct SaveMenuProc * proc) { if (!(proc->main_sel_bitfile & MAIN_MENU_OPTION_NEW_GAME)) StartHelpPromptSprite(0xc0, 8, 8, proc); } //! FE8U = 0x080AA49C void SaveMenuStartBonusClaim(struct SaveMenuProc * proc) { if (proc->extra_sel_bitfile == EXTRA_MENU_OPTION_BONUS_CLAIM) StartBonusClaimMenu(proc); } //! FE8U = 0x080AA4B4 void SaveMenu_EndHelpPromptSprite(void) { EndHelpPromptSprite(); } struct ProcCmd CONST_DATA ProcScr_SaveMenu[] = { PROC_NAME("savemenu"), PROC_LABEL(PL_SAVEMENU_INIT), PROC_YIELD, PROC_CALL(SaveMenu_Init), PROC_YIELD, PROC_CALL(SaveMenu_InitScreen), PROC_CALL(SaveMenu_LoadExtraMenuGraphics), PROC_YIELD, PROC_CALL_ARG(NewFadeIn, 8), PROC_WHILE(FadeInExists), PROC_YIELD, PROC_WHILE(MusicProc4Exists), PROC_CALL(SaveMenu_JumpToTarget), // fallthrough PROC_LABEL(PL_SAVEMENU_MAIN_LOOP), PROC_REPEAT(SameMenu_CtrlLoop), PROC_GOTO(PL_SAVEMENU_EXIT), PROC_LABEL(PL_SAVEMENU_DIFFICULTY_SEL), PROC_CALL(SaveMenu_ResetLcdFormDifficulty), PROC_CALL_ARG(NewFadeOut, 8), PROC_WHILE(FadeOutExists), PROC_CALL(DisableAllGfx), PROC_CALL(NewNewGameDifficultySelect), PROC_YIELD, PROC_CALL(SaveMenu_ReloadScreenFormDifficulty), PROC_CALL(SaveMenu_ResetLcdFormDifficulty), PROC_CALL_ARG(NewFadeIn, 8), PROC_WHILE(FadeInExists), PROC_CALL(SaveMenu_PostDifficultHandler), // fallthrough PROC_LABEL(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_CALL(SaveMenuSlotSelDrawSprite), PROC_YIELD, PROC_REPEAT(SaveMenu_SaveSlotSelectLoop), PROC_GOTO(PL_SAVEMENU_EXIT), PROC_LABEL(PL_SAVEMENU_EXEC_MISC_OPTION), PROC_SLEEP(5), PROC_CALL(_ExecSaveMenuMiscOption), PROC_GOTO(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_LABEL(PL_SAVEMENU_SLOT_SELECTED), PROC_SLEEP(1), PROC_CALL(SaveMenuRegisterSlotSelected), PROC_SLEEP(1), PROC_REPEAT(SaveMenuWaitSlotBoxScrolling), PROC_GOTO(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_LABEL(PL_SAVEMENU_SCROLL_SLOT), PROC_REPEAT(SaveMenuScrollSlot), PROC_GOTO(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_LABEL(PL_SAVEMENU_BACK_TO_MAIN), PROC_CALL(SaveMenu_EndHelpPromptSprite), PROC_REPEAT(SaveMenuScrollBackToMain), PROC_GOTO(PL_SAVEMENU_MAIN_LOOP), PROC_LABEL(PL_SAVEMENU_8), PROC_REPEAT(sub_80A9A68), // fallthrough PROC_LABEL(PL_SAVEMENU_9), PROC_REPEAT(sub_80A9AB0), // fallthrough PROC_LABEL(PL_SAVEMENU_12), PROC_CALL(sub_80A9A08), PROC_REPEAT(sub_80A9AF4), // fallthrough PROC_LABEL(PL_SAVEMENU_13), PROC_REPEAT(sub_80A9B44), // fallthrough PROC_LABEL(PL_SAVEMENU_10), PROC_REPEAT(sub_80A9B90), // fallthrough PROC_LABEL(PL_SAVEMENU_POST_BONUS_CLAIM), PROC_CALL(SaveMenuStartBonusClaim), PROC_YIELD, PROC_REPEAT(sub_80A9E1C), // fallthrough PROC_LABEL(PL_SAVEMENU_EXEC_EXTRA_MISC_OPTION), PROC_CALL_ARG(NewFadeOut, 8), PROC_WHILE(FadeOutExists), PROC_WHILE(IsMusicProc2Running), PROC_CALL(SaveMenuStartExtraMiscScreen), PROC_YIELD, PROC_CALL(SaveMenu_Init), PROC_YIELD, PROC_CALL(SaveMenu_InitScreen), PROC_CALL(SaveMenu_LoadExtraMenuGraphics), PROC_YIELD, PROC_CALL_ARG(NewFadeIn, 8), PROC_WHILE(FadeInExists), PROC_WHILE(IsMusicProc2Running), PROC_CALL(SaveMenuPostExtraMiscScreen), // fallthrough PROC_LABEL(PL_SAVEMENU_BLOCKING), PROC_BLOCK, PROC_LABEL(PL_SAVEMENU_NEW_GAME), PROC_CALL_ARG(NewFadeOut, 4), PROC_WHILE(FadeOutExists), PROC_GOTO(PL_SAVEMENU_EXIT), PROC_LABEL(PL_SAVEMENU_EXIT_FADE), PROC_CALL_ARG(NewFadeOut, 8), PROC_WHILE(FadeOutExists), // fallthrough PROC_LABEL(PL_SAVEMENU_EXIT), PROC_YIELD, PROC_CALL(PostSaveMenuHandler), PROC_YIELD, PROC_END, }; //! FE8U = 0x080AA4C0 void StartSaveMenu(ProcPtr parent) { struct SaveMenuProc * proc = Proc_StartBlocking(ProcScr_SaveMenu, parent); proc->main_sel_bitfile = 0x100; proc->extra_sel_bitfile = 0; gPlaySt.config.textSpeed = 2; } //! FE8U = 0x080AA4F8 void SaveMenuDirectlySelectSlotOnPrepScreen(ProcPtr proc) { if (!(gBmSt.gameStateBits & BM_FLAG_PREPSCREEN)) Proc_Goto(proc, PL_SAVEMENU_SAVE_SLOT_SEL_FADEIN); } struct ProcCmd CONST_DATA gProcScr_SaveMenuPostChapter[] = { PROC_NAME("savemenu"), PROC_YIELD, PROC_CALL(SaveMenuInit), PROC_CALL(SaveMenu_SetLcdChapterIdx), PROC_YIELD, PROC_CALL(SaveMenu_InitScreen), PROC_YIELD, PROC_CALL(SaveMenuDirectlySelectSlotOnPrepScreen), PROC_CALL_ARG(NewFadeIn, 8), PROC_WHILE(FadeInExists), PROC_GOTO(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_LABEL(PL_SAVEMENU_SAVE_SLOT_SEL_FADEIN), PROC_CALL_ARG(NewFadeIn, 4), PROC_WHILE(FadeInExists), // fallthrough PROC_LABEL(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_REPEAT(SaveMenu_SaveSlotSelectLoop), PROC_GOTO(PL_SAVEMENU_EXIT), PROC_LABEL(PL_SAVEMENU_SLOT_SELECTED), PROC_SLEEP(1), PROC_CALL(SaveMenuRegisterSlotSelected), PROC_SLEEP(1), PROC_REPEAT(SaveMenuWaitSlotBoxScrolling), PROC_GOTO(PL_SAVEMENU_SAVE_SLOT_SEL), PROC_LABEL(18), PROC_CALL_ARG(NewFadeOut, 4), PROC_WHILE(FadeOutExists), PROC_GOTO(15), PROC_LABEL(17), PROC_CALL_ARG(NewFadeOut, 8), PROC_WHILE(FadeOutExists), // fallthrough PROC_LABEL(15), PROC_YIELD, PROC_CALL(PostSaveMenuHandler), PROC_END, }; //! FE8U = 0x080AA518 void Make6C_SaveMenuPostChapter(ProcPtr parent) { Proc_StartBlocking(gProcScr_SaveMenuPostChapter, parent); } //! FE8U = 0x080AA52C void SaveMenu_SetDifficultyChoice(int difficulty, int b) { struct SaveMenuProc * proc = Proc_Find(ProcScr_SaveMenu); if (proc) { proc->difficulty = difficulty; proc->unk_3d = b; } } struct BonusClaimEnt * CONST_DATA _gpBonusClaimData = gBonusClaimData; //! FE8U = 0x080AA550 void sub_80AA550(struct ProcBonusClaimMenu * proc) { int i; CpuFill16(0, _gpBonusClaimData, 0x144); if (LoadBonusContentData(_gpBonusClaimData) == 0) { Proc_Goto(proc, 10); return; } proc->unk_5c = 0; proc->unk_58 = 0; for (i = 0; i < 0x10; i++) { struct BonusClaimEnt * ent = _gpBonusClaimData + i; if ((ent->unseen & 3) != 1) { continue; } if (_gpBonusClaimData[i].kind == BONUSKIND_SONG3) { proc->unk_58 = 1; _gpBonusClaimData[i].unseen = (_gpBonusClaimData[i].unseen & ~3) + 2; UnlockSoundRoomSong(NULL, 0x75); } ent = _gpBonusClaimData + i; if (ent->kind == BONUSKIND_SONG4) { proc->unk_5c = 1; _gpBonusClaimData[i].unseen = (_gpBonusClaimData[i].unseen & ~3) + 2; UnlockSoundRoomSong(NULL, 0x76); } } if ((proc->unk_58 == 0) && (proc->unk_5c == 0)) { Proc_Goto(proc, 10); return; } LoadHelpBoxGfx(OBJ_VRAM0 + OBJCHR_SAVEMENU_SLOTSEL_HELPBOX * TILE_SIZE_4BPP, OBJPAL_SAVEMENU_SLOTSEL_HELPBOX); } //! FE8U = 0x080AA614 void sub_80AA614(struct ProcBonusClaimMenu * proc) { if (proc->unk_58 != 0) { proc->unk_4c = 0; StartHelpBoxExt_Unk(0x40, 0x30, 0x893); // TODO: msgid "Sacred Dragon[.][NL]added to[NL]Sound Room" PlaySoundEffect(SONG_5B); return; } Proc_Goto(proc, 0); } //! FE8U = 0x080AA658 void sub_80AA658(struct ProcBonusClaimMenu * proc) { if (proc->unk_5c != 0) { proc->unk_4c = 0; StartHelpBoxExt_Unk(0x40, 0x30, 0x894); // TODO: msgid "Palace Silezia[NL]added to[NL]Sound Room" PlaySoundEffect(SONG_5B); return; } Proc_Goto(proc, 1); } //! FE8U = 0x080AA69C void sub_80AA69C(struct ProcBonusClaimMenu * proc) { if (proc->unk_4c > 30) { if (gKeyStatusPtr->newKeys & (A_BUTTON | B_BUTTON | START_BUTTON)) { CloseHelpBox(); Proc_Break(proc); } return; } proc->unk_4c++; } //! FE8U = 0x080AA6D8 void sub_80AA6D8(void) { SaveBonusContentData(_gpBonusClaimData); } // clang-format off struct ProcCmd CONST_DATA ProcScr_BonusClaimMenu[] = { PROC_CALL(sub_80AA550), PROC_CALL(sub_80AA614), PROC_REPEAT(sub_80AA69C), PROC_SLEEP(16), PROC_LABEL(0), PROC_CALL(sub_80AA658), PROC_REPEAT(sub_80AA69C), PROC_SLEEP(16), // fallthrough PROC_LABEL(1), PROC_CALL(sub_80AA6D8), // fallthrough PROC_LABEL(10), PROC_END, }; // clang-format on //! FE8U = 0x080AA6EC void StartBonusClaimMenu(ProcPtr parent) { Proc_StartBlocking(ProcScr_BonusClaimMenu, parent); } //! FE8U = 0x080AA700 void InitSaveMenuHelpTextSt(void) { gSaveMenuRTextData.pid = 0; gSaveMenuRTextData.level = -1; gSaveMenuRTextData.nodeId = -1; } //! FE8U = 0x080AA718 const char * GetLeaderNameForSaveMenu(void) { if (gSaveMenuRTextData.pid == 0) { return NULL; } return GetStringFromIndex(gCharacterData[gSaveMenuRTextData.pid - 1].nameTextId); } //! FE8U = 0x080AA744 int GetLeaderLevelForSaveMenu(void) { if ((gSaveMenuRTextData.pid == 0) || (gSaveMenuRTextData.level < 0)) { return -1; } return gSaveMenuRTextData.level; } //! FE8U = 0x080AA768 const char * GetWMNodeNameForSaveMenu(void) { if ((gSaveMenuRTextData.pid == 0) || (gSaveMenuRTextData.nodeId < 0)) { return NULL; } return GetWorldMapNodeName(gSaveMenuRTextData.nodeId); } //! FE8U = 0x080AA790 void SaveMenuCopyPalette(u16 * src, u16 * dst, int count) { u16 * src_; count = count * 0x10; if (count <= 0) return; for (src_ = src; count != 0; count--) *dst++ = *src_++; } void sub_80AA7AC(int a, int b) { int offset = (a & 0x3F) >> 2; u16 * _src, * src = gPaletteBuffer; u16 * dst = Pal_08A28088 + offset; int val; val = *dst; src[0x111] = val; _src = src + (b * 0x20 + 0x1A1); _src[0] = *dst; EnablePaletteSync(); }
0
0.937282
1
0.937282
game-dev
MEDIA
0.730314
game-dev
0.945823
1
0.945823
oiuv/mud
3,365
kungfu/skill/dacidabei-shou/yin.c
#include <ansi.h> #include <combat.h> #include "/kungfu/skill/eff_msg.h"; inherit F_SSERVER; int perform(object me, object target) { string msg, dodge_skill; int damage, jiali, attack, defense, p; object armor; if (me->query_skill("buddhism", 1) < 200) return notify_fail("你的佛法修为不足,无法施展该绝招!\n"); if( !target ) target = offensive_target(me); if( !target || !me->is_fighting(target) || !living(target) ) return notify_fail("「大手印」只能在战斗中对对手使用。\n"); if( (int)me->query_skill("dacidabei-shou",1) < 180 ) return notify_fail("你的大慈大悲手不够娴熟,不会使用「大手印」!\n"); if( (int)me->query_skill("hand",1) < 180 ) return notify_fail("你的基本手法不够娴熟,不会使用「大手印」!\n"); if( (int)me->query_str() < 35 ) return notify_fail("你的臂力不够强,不能使用「大手印」!\n"); if( (int)me->query("max_neili") < 2000 ) return notify_fail("你的内力太弱,不能使用「大手印」!\n"); if( (int)me->query("neili") < 800 ) return notify_fail("你的内力太少了,无法使用出「大手印」!\n"); if (me->query_skill_prepared("hand") != "dacidabei-shou") return notify_fail("你还没有准备大慈大悲手,无法施展「大手印」!\n"); if( objectp(me->query_temp("weapon")) ) return notify_fail("你必须空手使用「大手印」!\n"); jiali = me->query("jiali")+1; attack = me->query("combat_exp")/1000; attack += me->query_skill("hand"); attack += me->query("neili")/5; defense = target->query("combat_exp")/1000; defense += target->query_skill("dodge"); defense += target->query("neili")/7; attack = (attack+random(attack+1))/2; damage = me->query_skill("dacidabei-shou", 1)/40 * jiali; message_vision(HIR "\n$N突然面色通红,低声默念禅宗真言,双臂骨节一阵爆响,猛然" "腾空而起,伸手向$n胸前按去,好一式「大手印」!\n"NOR,me,target); if( attack > defense ) { if( objectp(armor = target->query_temp("armor/cloth")) && armor->query("armor_prop/armor") < 200 && damage > 500){ message_vision(HIY"只见这斗大的手印正好印在$N的$n"HIY"上,越变越" "大,竟将它震得粉碎,裂成一块块掉在地上!\n"NOR, target, armor); armor->unequip(); armor->move(environment(target)); armor->set("name", "破碎的" + armor->query("name")); armor->set("value", 0); armor->set("armor_prop/armor", 0); target->reset_action(); } tell_object(target, RED"你只觉得霍的胸口一阵剧痛,已经被拍中了前胸!\n"NOR); target->receive_damage("qi", damage, me); target->receive_wound("qi", damage/3, me); p = (int)target->query("qi")*100/(int)target->query("max_qi"); msg = "( $n"+eff_status_msg(p)+" )\n"; message_vision(msg, me, target); me->add("neili", -jiali); } else { dodge_skill = target->query_skill_mapped("dodge"); if( !dodge_skill ) dodge_skill = "dodge"; message_vision(SKILL_D(dodge_skill)->query_dodge_msg(target, 1), me, target); } me->add("neili", -200); me->start_busy(2+random(2)); return 1; }
0
0.853457
1
0.853457
game-dev
MEDIA
0.991684
game-dev
0.939968
1
0.939968
mattmatterson111/IS12-Warfare-Two
1,650
code/game/machinery/kitchen/cooking_machines/fryer.dm
/obj/machinery/cooker/fryer name = "deep fryer" desc = "Deep fried <i>everything</i>." icon_state = "fryer_off" can_cook_mobs = 1 cook_type = "deep fried" on_icon = "fryer_on" off_icon = "fryer_off" food_color = "#ffad33" cooked_sound = 'sound/machines/ding.ogg' /obj/machinery/cooker/fryer/cook_mob(var/mob/living/victim, var/mob/user) if(!istype(victim)) return user.visible_message("<span class='danger'>\The [user] starts pushing \the [victim] into \the [src]!</span>") icon_state = on_icon cooking = 1 if(!do_mob(user, victim, 20)) cooking = 0 icon_state = off_icon return if(!victim || !victim.Adjacent(user)) to_chat(user, "<span class='danger'>Your victim slipped free!</span>") cooking = 0 icon_state = off_icon return var/target_zone = user.zone_sel.selecting if(ishuman(victim) && !(target_zone in list(BP_GROIN, BP_CHEST))) var/mob/living/carbon/human/H = victim var/obj/item/organ/external/E = H.get_organ(target_zone) if(!E) to_chat(user, "<span class='warning'>They are missing that body part!</span>") else visible_message("<span class='danger'>\The [user] shoves \the [victim][E ? "'s [E.name]" : ""] into \the [src]!</span>") var/blocked = H.run_armor_check(target_zone, "energy") H.apply_damage(rand(20,30), BURN, target_zone, blocked) else var/blocked = victim.run_armor_check(null, "energy") victim.apply_damage(rand(30,40), BURN, null, blocked) if(victim) admin_attack_log(user, victim, "Has [cook_type] their victim in \a [src]", "Has been [cook_type] in \a [src] by the attacker.", "[cook_type], in \a [src], ") icon_state = off_icon cooking = 0 return
0
0.914851
1
0.914851
game-dev
MEDIA
0.836344
game-dev
0.842057
1
0.842057
jonof/jfduke3d
237,867
src/actors.c
//------------------------------------------------------------------------- /* Copyright (C) 1996, 2003 - 3D Realms Entertainment This file is part of Duke Nukem 3D version 1.5 - Atomic Edition Duke Nukem 3D is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Original Source: 1996 - Todd Replogle Prepared for public release: 03/21/2003 - Charlie Wiederhold, 3D Realms Modifications for JonoF's port by Jonathon Fowler (jf@jonof.id.au) */ //------------------------------------------------------------------------- #include "duke3d.h" extern char numenvsnds,actor_tog; void updateinterpolations() //Stick at beginning of domovethings { int i; for(i=numinterpolations-1;i>=0;i--) oldipos[i] = *curipos[i]; } void setinterpolation(int *posptr) { int i; if (numinterpolations >= MAXINTERPOLATIONS) return; for(i=numinterpolations-1;i>=0;i--) if (curipos[i] == posptr) return; curipos[numinterpolations] = posptr; oldipos[numinterpolations] = *posptr; numinterpolations++; } void stopinterpolation(int *posptr) { int i; for(i=numinterpolations-1;i>=startofdynamicinterpolations;i--) if (curipos[i] == posptr) { numinterpolations--; oldipos[i] = oldipos[numinterpolations]; bakipos[i] = bakipos[numinterpolations]; curipos[i] = curipos[numinterpolations]; } } void dointerpolations(int smoothratio) //Stick at beginning of drawscreen { int i, j, odelta, ndelta; ndelta = 0; j = 0; for(i=numinterpolations-1;i>=0;i--) { bakipos[i] = *curipos[i]; odelta = ndelta; ndelta = (*curipos[i])-oldipos[i]; if (odelta != ndelta) j = mulscale16(ndelta,smoothratio); *curipos[i] = oldipos[i]+j; } } void restoreinterpolations() //Stick at end of drawscreen { int i; for(i=numinterpolations-1;i>=0;i--) *curipos[i] = bakipos[i]; } int ceilingspace(short sectnum) { if( (sector[sectnum].ceilingstat&1) && sector[sectnum].ceilingpal == 0 ) { switch(sector[sectnum].ceilingpicnum) { case MOONSKY1: case BIGORBIT1: return 1; } } return 0; } int floorspace(short sectnum) { if( (sector[sectnum].floorstat&1) && sector[sectnum].ceilingpal == 0 ) { switch(sector[sectnum].floorpicnum) { case MOONSKY1: case BIGORBIT1: return 1; } } return 0; } void addammo( short weapon,struct player_struct *p,short amount) { p->ammo_amount[weapon] += amount; if( p->ammo_amount[weapon] > max_ammo_amount[weapon] ) p->ammo_amount[weapon] = max_ammo_amount[weapon]; } void addweaponnoswitch( struct player_struct *p, short weapon) { if ( p->gotweapon[weapon] == 0 ) { p->gotweapon[weapon] = 1; if(weapon == SHRINKER_WEAPON) p->gotweapon[GROW_WEAPON] = 1; } switch(weapon) { case KNEE_WEAPON: case TRIPBOMB_WEAPON: case HANDREMOTE_WEAPON: case HANDBOMB_WEAPON: break; case SHOTGUN_WEAPON: spritesound(SHOTGUN_COCK,p->i);break; case PISTOL_WEAPON: spritesound(INSERT_CLIP,p->i);break; default: spritesound(SELECT_WEAPON,p->i);break; } } void addweapon( struct player_struct *p,short weapon) { addweaponnoswitch(p,weapon); p->random_club_frame = 0; if(p->holster_weapon == 0) { p->weapon_pos = -1; p->last_weapon = p->curr_weapon; } else { p->weapon_pos = 10; p->holster_weapon = 0; p->last_weapon = -1; } p->kickback_pic = 0; p->curr_weapon = weapon; } void checkavailinven( struct player_struct *p ) { if(p->firstaid_amount > 0) p->inven_icon = 1; else if(p->steroids_amount > 0) p->inven_icon = 2; else if(p->holoduke_amount > 0) p->inven_icon = 3; else if(p->jetpack_amount > 0) p->inven_icon = 4; else if(p->heat_amount > 0) p->inven_icon = 5; else if(p->scuba_amount > 0) p->inven_icon = 6; else if(p->boot_amount > 0) p->inven_icon = 7; else p->inven_icon = 0; } void checkavailweapon( struct player_struct *p ) { short i,snum; int32 weap; if(p->wantweaponfire >= 0) { weap = p->wantweaponfire; p->wantweaponfire = -1; if(weap == p->curr_weapon) return; else if( p->gotweapon[weap] && p->ammo_amount[weap] > 0 ) { addweapon(p,weap); return; } } weap = p->curr_weapon; if( p->gotweapon[weap] && p->ammo_amount[weap] > 0 ) return; if( p->gotweapon[weap] && !(p->weaponswitch & 2)) return; snum = sprite[p->i].yvel; for(i=0;i<10;i++) { weap = ud.wchoice[snum][i]; if (VOLUMEONE && weap > 6) continue; if(weap == 0) weap = 9; else weap--; if( weap == 0 || ( p->gotweapon[weap] && p->ammo_amount[weap] > 0 ) ) break; } if(i == 10) weap = 0; // Found the weapon p->last_weapon = p->curr_weapon; p->random_club_frame = 0; p->curr_weapon = weap; p->kickback_pic = 0; if(p->holster_weapon == 1) { p->holster_weapon = 0; p->weapon_pos = 10; } else p->weapon_pos = -1; } int ifsquished(short i, short p) { sectortype *sc; char squishme; int floorceildist; if(PN == APLAYER && ud.clipping) return 0; sc = &sector[SECT]; floorceildist = sc->floorz - sc->ceilingz; if(sc->lotag != 23) { if(sprite[i].pal == 1) squishme = floorceildist < (32<<8) && (sc->lotag&32768) == 0; else squishme = floorceildist < (12<<8); // && (sc->lotag&32768) == 0; } else squishme = 0; if( squishme ) { FTA(10,&ps[p]); if(badguy(&sprite[i])) sprite[i].xvel = 0; if(sprite[i].pal == 1) { hittype[i].picnum = SHOTSPARK1; hittype[i].extra = 1; return 0; } return 1; } return 0; } void hitradius( short i, int r, int hp1, int hp2, int hp3, int hp4 ) { spritetype *s,*sj; walltype *wal; int d, q, x1, y1; int sectcnt, sectend, dasect, startwall, endwall, nextsect; short j,k,p,x,nextj,sect; unsigned char statlist[] = {0,1,6,10,12,2,5}; short *tempshort = (short *)tempbuf; s = &sprite[i]; if(s->picnum == RPG && s->xrepeat < 11) goto SKIPWALLCHECK; if(s->picnum != SHRINKSPARK) { tempshort[0] = s->sectnum; dasect = s->sectnum; sectcnt = 0; sectend = 1; do { dasect = tempshort[sectcnt++]; if(((sector[dasect].ceilingz-s->z)>>8) < r) { d = klabs(wall[sector[dasect].wallptr].x-s->x)+klabs(wall[sector[dasect].wallptr].y-s->y); if(d < r) checkhitceiling(dasect); else { d = klabs(wall[wall[wall[sector[dasect].wallptr].point2].point2].x-s->x)+klabs(wall[wall[wall[sector[dasect].wallptr].point2].point2].y-s->y); if(d < r) checkhitceiling(dasect); } } startwall = sector[dasect].wallptr; endwall = startwall+sector[dasect].wallnum; for(x=startwall,wal=&wall[startwall];x<endwall;x++,wal++) if( ( klabs(wal->x-s->x)+klabs(wal->y-s->y) ) < r) { nextsect = wal->nextsector; if (nextsect >= 0) { for(dasect=sectend-1;dasect>=0;dasect--) if (tempshort[dasect] == nextsect) break; if (dasect < 0) tempshort[sectend++] = nextsect; } x1 = (((wal->x+wall[wal->point2].x)>>1)+s->x)>>1; y1 = (((wal->y+wall[wal->point2].y)>>1)+s->y)>>1; updatesector(x1,y1,&sect); if( sect >= 0 && cansee(x1,y1,s->z,sect,s->x,s->y,s->z,s->sectnum ) ) checkhitwall(i,x,wal->x,wal->y,s->z,s->picnum); } } while (sectcnt < sectend); } SKIPWALLCHECK: q = -(16<<8)+(TRAND&((32<<8)-1)); for(x = 0;x<7;x++) { j = headspritestat[statlist[x]]; while(j >= 0) { nextj = nextspritestat[j]; sj = &sprite[j]; if( x == 0 || x >= 5 || AFLAMABLE(sj->picnum) ) { if( s->picnum != SHRINKSPARK || (sj->cstat&257) ) if( dist( s, sj ) < r ) { if( badguy(sj) && !cansee( sj->x, sj->y,sj->z+q, sj->sectnum, s->x, s->y, s->z+q, s->sectnum) ) goto BOLT; checkhitsprite( j, i ); } } else if( sj->extra >= 0 && sj != s && ( sj->picnum == TRIPBOMB || badguy(sj) || sj->picnum == QUEBALL || sj->picnum == STRIPEBALL || (sj->cstat&257) || sj->picnum == DUKELYINGDEAD ) ) { if( s->picnum == SHRINKSPARK && sj->picnum != SHARK && ( j == s->owner || sj->xrepeat < 24 ) ) { j = nextj; continue; } if( s->picnum == MORTER && j == s->owner) { j = nextj; continue; } if(sj->picnum == APLAYER) sj->z -= PHEIGHT; d = dist( s, sj ); if(sj->picnum == APLAYER) sj->z += PHEIGHT; if ( d < r && cansee( sj->x, sj->y, sj->z-(8<<8), sj->sectnum, s->x, s->y, s->z-(12<<8), s->sectnum) ) { hittype[j].ang = getangle(sj->x-s->x,sj->y-s->y); if ( s->picnum == RPG && sj->extra > 0) hittype[j].picnum = RPG; else { if( s->picnum == SHRINKSPARK ) hittype[j].picnum = SHRINKSPARK; else hittype[j].picnum = RADIUSEXPLOSION; } if(s->picnum != SHRINKSPARK) { if ( d < r/3 ) { if(hp4 == hp3) hp4++; hittype[j].extra = hp3 + (TRAND%(hp4-hp3)); } else if ( d < 2*r/3 ) { if(hp3 == hp2) hp3++; hittype[j].extra = hp2 + (TRAND%(hp3-hp2)); } else if ( d < r ) { if(hp2 == hp1) hp2++; hittype[j].extra = hp1 + (TRAND%(hp2-hp1)); } if( sprite[j].picnum != TANK && sprite[j].picnum != ROTATEGUN && sprite[j].picnum != RECON && sprite[j].picnum != BOSS1 && sprite[j].picnum != BOSS2 && sprite[j].picnum != BOSS3 && sprite[j].picnum != BOSS4 ) { if(sj->xvel < 0) sj->xvel = 0; sj->xvel += (s->extra<<2); } if( sj->picnum == PODFEM1 || sj->picnum == FEM1 || sj->picnum == FEM2 || sj->picnum == FEM3 || sj->picnum == FEM4 || sj->picnum == FEM5 || sj->picnum == FEM6 || sj->picnum == FEM7 || sj->picnum == FEM8 || sj->picnum == FEM9 || sj->picnum == FEM10 || sj->picnum == STATUE || sj->picnum == STATUEFLASH || sj->picnum == SPACEMARINE || sj->picnum == QUEBALL || sj->picnum == STRIPEBALL) checkhitsprite( j, i ); } else if(s->extra == 0) hittype[j].extra = 0; if ( sj->picnum != RADIUSEXPLOSION && s->owner >= 0 && sprite[s->owner].statnum < MAXSTATUS ) { if(sj->picnum == APLAYER) { p = sj->yvel; if(ps[p].newowner >= 0) { ps[p].newowner = -1; ps[p].posx = ps[p].oposx; ps[p].posy = ps[p].oposy; ps[p].posz = ps[p].oposz; ps[p].ang = ps[p].oang; updatesector(ps[p].posx,ps[p].posy,&ps[p].cursectnum); setpal(&ps[p]); k = headspritestat[1]; while(k >= 0) { if(sprite[k].picnum==CAMERA1) sprite[k].yvel = 0; k = nextspritestat[k]; } } } hittype[j].owner = s->owner; } } } BOLT: j = nextj; } } } int movesprite(short spritenum, int xchange, int ychange, int zchange, unsigned int cliptype) { int daz,h, oldx, oldy; short retval, dasectnum, cd; char bg; bg = badguy(&sprite[spritenum]); if(sprite[spritenum].statnum == 5 || (bg && sprite[spritenum].xrepeat < 4 ) ) { sprite[spritenum].x += (xchange*TICSPERFRAME)>>2; sprite[spritenum].y += (ychange*TICSPERFRAME)>>2; sprite[spritenum].z += (zchange*TICSPERFRAME)>>2; if(bg) setsprite(spritenum,sprite[spritenum].x,sprite[spritenum].y,sprite[spritenum].z); return 0; } dasectnum = sprite[spritenum].sectnum; daz = sprite[spritenum].z; h = ((tilesizy[sprite[spritenum].picnum]*sprite[spritenum].yrepeat)<<1); daz -= h; if( bg ) { oldx = sprite[spritenum].x; oldy = sprite[spritenum].y; if( sprite[spritenum].xrepeat > 60 ) retval = clipmove(&sprite[spritenum].x,&sprite[spritenum].y,&daz,&dasectnum,((xchange*TICSPERFRAME)<<11),((ychange*TICSPERFRAME)<<11),1024L,(4<<8),(4<<8),cliptype); else { if(sprite[spritenum].picnum == LIZMAN) cd = 292L; else if( (actortype[sprite[spritenum].picnum]&3) ) cd = sprite[spritenum].clipdist<<2; else cd = 192L; retval = clipmove(&sprite[spritenum].x,&sprite[spritenum].y,&daz,&dasectnum,((xchange*TICSPERFRAME)<<11),((ychange*TICSPERFRAME)<<11),cd,(4<<8),(4<<8),cliptype); } if( dasectnum < 0 || ( dasectnum >= 0 && ( ( hittype[spritenum].actorstayput >= 0 && hittype[spritenum].actorstayput != dasectnum ) || ( ( sprite[spritenum].picnum == BOSS2 ) && sprite[spritenum].pal == 0 && sector[dasectnum].lotag != 3 ) || ( ( sprite[spritenum].picnum == BOSS1 || sprite[spritenum].picnum == BOSS2 ) && sector[dasectnum].lotag == 1 ) || ( sector[dasectnum].lotag == 1 && ( sprite[spritenum].picnum == LIZMAN || ( sprite[spritenum].picnum == LIZTROOP && sprite[spritenum].zvel == 0 ) ) ) ) ) ) { sprite[spritenum].x = oldx; sprite[spritenum].y = oldy; if(sector[dasectnum].lotag == 1 && sprite[spritenum].picnum == LIZMAN) sprite[spritenum].ang = (TRAND&2047); else if( (hittype[spritenum].temp_data[0]&3) == 1 && sprite[spritenum].picnum != COMMANDER ) sprite[spritenum].ang = (TRAND&2047); setsprite(spritenum,oldx,oldy,sprite[spritenum].z); if(dasectnum < 0) dasectnum = 0; return (16384+dasectnum); } if( (retval&49152) >= 32768 && (hittype[spritenum].cgg==0) ) sprite[spritenum].ang += 768; } else { if(sprite[spritenum].statnum == 4) retval = clipmove(&sprite[spritenum].x,&sprite[spritenum].y,&daz,&dasectnum,((xchange*TICSPERFRAME)<<11),((ychange*TICSPERFRAME)<<11),8L,(4<<8),(4<<8),cliptype); else retval = clipmove(&sprite[spritenum].x,&sprite[spritenum].y,&daz,&dasectnum,((xchange*TICSPERFRAME)<<11),((ychange*TICSPERFRAME)<<11),(int)(sprite[spritenum].clipdist<<2),(4<<8),(4<<8),cliptype); } if( dasectnum >= 0) if ( (dasectnum != sprite[spritenum].sectnum) ) changespritesect(spritenum,dasectnum); daz = sprite[spritenum].z + ((zchange*TICSPERFRAME)>>3); if ((daz > hittype[spritenum].ceilingz) && (daz <= hittype[spritenum].floorz)) sprite[spritenum].z = daz; else if (retval == 0) return(16384+dasectnum); return(retval); } short ssp(short i,unsigned int cliptype) //The set sprite function { spritetype *s; int movetype; s = &sprite[i]; movetype = movesprite(i, (s->xvel*(sintable[(s->ang+512)&2047]))>>14, (s->xvel*(sintable[s->ang&2047]))>>14,s->zvel, cliptype); return (movetype==0); } void insertspriteq(short i) { if(spriteqamount > 0) { if(spriteq[spriteqloc] >= 0) sprite[spriteq[spriteqloc]].xrepeat = 0; spriteq[spriteqloc] = i; spriteqloc = (spriteqloc+1)%spriteqamount; } else sprite[i].xrepeat = sprite[i].yrepeat = 0; } void lotsofmoney(spritetype *s, short n) { short i ,j; for(i=n;i>0;i--) { j = EGS(s->sectnum,s->x,s->y,s->z-(TRAND%(47<<8)),MONEY,-32,8,8,TRAND&2047,0,0,0,5); sprite[j].cstat = TRAND&12; } } void lotsofmail(spritetype *s, short n) { short i ,j; for(i=n;i>0;i--) { j = EGS(s->sectnum,s->x,s->y,s->z-(TRAND%(47<<8)),MAIL,-32,8,8,TRAND&2047,0,0,0,5); sprite[j].cstat = TRAND&12; } } void lotsofpaper(spritetype *s, short n) { short i ,j; for(i=n;i>0;i--) { j = EGS(s->sectnum,s->x,s->y,s->z-(TRAND%(47<<8)),PAPER,-32,8,8,TRAND&2047,0,0,0,5); sprite[j].cstat = TRAND&12; } } void guts(spritetype *s,short gtype, short n, short p) { int gutz,floorz; short i,a,j; char sx,sy; signed char pal; if(badguy(s) && s->xrepeat < 16) sx = sy = 8; else sx = sy = 32; gutz = s->z-(8<<8); floorz = getflorzofslope(s->sectnum,s->x,s->y); if( gutz > ( floorz-(8<<8) ) ) gutz = floorz-(8<<8); if(s->picnum == COMMANDER) gutz -= (24<<8); if( badguy(s) && s->pal == 6) pal = 6; else pal = 0; for(j=0;j<n;j++) { a = TRAND&2047; i = EGS(s->sectnum,s->x+(TRAND&255)-128,s->y+(TRAND&255)-128,gutz-(TRAND&8191),gtype,-32,sx,sy,a,48+(TRAND&31),-512-(TRAND&2047),ps[p].i,5); if(PN == JIBS2) { sprite[i].xrepeat >>= 2; sprite[i].yrepeat >>= 2; } if(pal == 6) sprite[i].pal = 6; } } void gutsdir(spritetype *s,short gtype, short n, short p) { int gutz,floorz; short a,j; char sx,sy; if(badguy(s) && s->xrepeat < 16) sx = sy = 8; else sx = sy = 32; gutz = s->z-(8<<8); floorz = getflorzofslope(s->sectnum,s->x,s->y); if( gutz > ( floorz-(8<<8) ) ) gutz = floorz-(8<<8); if(s->picnum == COMMANDER) gutz -= (24<<8); for(j=0;j<n;j++) { a = TRAND&2047; EGS(s->sectnum,s->x,s->y,gutz,gtype,-32,sx,sy,a,256+(TRAND&127),-512-(TRAND&2047),ps[p].i,5); } } void setsectinterpolate(short i) { int j, k, startwall,endwall; startwall = sector[SECT].wallptr; endwall = startwall+sector[SECT].wallnum; for(j=startwall;j<endwall;j++) { setinterpolation(&wall[j].x); setinterpolation(&wall[j].y); k = wall[j].nextwall; if(k >= 0) { setinterpolation(&wall[k].x); setinterpolation(&wall[k].y); k = wall[k].point2; setinterpolation(&wall[k].x); setinterpolation(&wall[k].y); } } } void clearsectinterpolate(short i) { short j,startwall,endwall; startwall = sector[SECT].wallptr; endwall = startwall+sector[SECT].wallnum; for(j=startwall;j<endwall;j++) { stopinterpolation(&wall[j].x); stopinterpolation(&wall[j].y); if(wall[j].nextwall >= 0) { stopinterpolation(&wall[wall[j].nextwall].x); stopinterpolation(&wall[wall[j].nextwall].y); } } } void ms(short i) { //T1,T2 and T3 are used for all the sector moving stuff!!! short startwall,endwall,x; int tx,ty,j,k; spritetype *s; s = &sprite[i]; s->x += (s->xvel*(sintable[(s->ang+512)&2047]))>>14; s->y += (s->xvel*(sintable[s->ang&2047]))>>14; j = T2; k = T3; startwall = sector[s->sectnum].wallptr; endwall = startwall+sector[s->sectnum].wallnum; for(x=startwall;x<endwall;x++) { rotatepoint( 0,0, msx[j],msy[j], k&2047,&tx,&ty); dragpoint(x,s->x+tx,s->y+ty); j++; } } void movefta(void) { int x, px, py, sx, sy; short i, j, p, psect, ssect, nexti; spritetype *s; i = headspritestat[2]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; p = findplayer(s,&x); ssect = psect = s->sectnum; if(sprite[ps[p].i].extra > 0 ) { if( x < 30000 ) { hittype[i].timetosleep++; if( hittype[i].timetosleep >= (x>>8) ) { int rz, orz; if(badguy(s)) { px = ps[p].oposx+64-(TRAND&127); py = ps[p].oposy+64-(TRAND&127); updatesector(px,py,&psect); if(psect == -1) { i = nexti; continue; } sx = s->x+64-(TRAND&127); sy = s->y+64-(TRAND&127); updatesector(px,py,&ssect); if(ssect == -1) { i = nexti; continue; } rz = TRAND; orz = TRAND; j = cansee(sx,sy,s->z-(rz%(52<<8)),s->sectnum,px,py,ps[p].oposz-(orz%(32<<8)),ps[p].cursectnum); } else { rz = TRAND; orz = TRAND; j = cansee(s->x,s->y,s->z-((rz&31)<<8),s->sectnum,ps[p].oposx,ps[p].oposy,ps[p].oposz-((orz&31)<<8),ps[p].cursectnum); } // j = 1; if(j) switch(s->picnum) { case RUBBERCAN: case EXPLODINGBARREL: case WOODENHORSE: case HORSEONSIDE: case CANWITHSOMETHING: case CANWITHSOMETHING2: case CANWITHSOMETHING3: case CANWITHSOMETHING4: case FIREBARREL: case FIREVASE: case NUKEBARREL: case NUKEBARRELDENTED: case NUKEBARRELLEAKED: case TRIPBOMB: if (sector[s->sectnum].ceilingstat&1) s->shade = sector[s->sectnum].ceilingshade; else s->shade = sector[s->sectnum].floorshade; hittype[i].timetosleep = 0; changespritestat(i,6); break; default: hittype[i].timetosleep = 0; check_fta_sounds(i); changespritestat(i,1); break; } else hittype[i].timetosleep = 0; } } if( badguy( s ) ) { if (sector[s->sectnum].ceilingstat&1) s->shade = sector[s->sectnum].ceilingshade; else s->shade = sector[s->sectnum].floorshade; } } i = nexti; } } short ifhitsectors(short sectnum) { short i; i = headspritestat[5]; while(i >= 0) { if( PN == EXPLOSION2 && sectnum == SECT ) return i; i = nextspritestat[i]; } return -1; } short ifhitbyweapon(short sn) { short j, p; spritetype *npc; if( hittype[sn].extra >= 0 ) { if(sprite[sn].extra >= 0 ) { npc = &sprite[sn]; if(npc->picnum == APLAYER) { if(ud.god && hittype[sn].picnum != SHRINKSPARK ) return -1; p = npc->yvel; j = hittype[sn].owner; if( j >= 0 && sprite[j].picnum == APLAYER && ud.coop == 1 && ud.ffire == 0 ) return -1; npc->extra -= hittype[sn].extra; if(j >= 0) { if(npc->extra <= 0 && hittype[sn].picnum != FREEZEBLAST) { npc->extra = 0; ps[p].wackedbyactor = j; if( sprite[hittype[sn].owner].picnum == APLAYER && p != sprite[hittype[sn].owner].yvel ) ps[p].frag_ps = sprite[j].yvel; hittype[sn].owner = ps[p].i; } } switch(hittype[sn].picnum) { case RADIUSEXPLOSION: case RPG: case HYDRENT: case HEAVYHBOMB: case SEENINE: case OOZFILTER: case EXPLODINGBARREL: ps[p].posxv += hittype[sn].extra*(sintable[(hittype[sn].ang+512)&2047])<<2; ps[p].posyv += hittype[sn].extra*(sintable[hittype[sn].ang&2047])<<2; break; default: ps[p].posxv += hittype[sn].extra*(sintable[(hittype[sn].ang+512)&2047])<<1; ps[p].posyv += hittype[sn].extra*(sintable[hittype[sn].ang&2047])<<1; break; } } else { if(hittype[sn].extra == 0 ) if( hittype[sn].picnum == SHRINKSPARK && npc->xrepeat < 24 ) return -1; npc->extra -= hittype[sn].extra; if(npc->picnum != RECON && npc->owner >= 0 && sprite[npc->owner].statnum < MAXSTATUS ) npc->owner = hittype[sn].owner; } hittype[sn].extra = -1; return hittype[sn].picnum; } } hittype[sn].extra = -1; return -1; } void movecyclers(void) { short q, j, x, t, s, *c; walltype *wal; unsigned char cshade; for(q=numcyclers-1;q>=0;q--) { c = &cyclers[q][0]; s = c[0]; t = c[3]; j = t+(sintable[c[1]&2047]>>10); cshade = c[2]; if( j < cshade ) j = cshade; else if( j > t ) j = t; c[1] += sector[s].extra; if(c[5]) { wal = &wall[sector[s].wallptr]; for(x = sector[s].wallnum;x>0;x--,wal++) if( wal->hitag != 1 ) { wal->shade = j; if( (wal->cstat&2) && wal->nextwall >= 0) wall[wal->nextwall].shade = j; } sector[s].floorshade = sector[s].ceilingshade = j; } } } void movedummyplayers(void) { short i, p, nexti; i = headspritestat[13]; while(i >= 0) { nexti = nextspritestat[i]; p = sprite[OW].yvel; if( ps[p].on_crane >= 0 || sector[ps[p].cursectnum].lotag != 1 || sprite[ps[p].i].extra <= 0 ) { ps[p].dummyplayersprite = -1; KILLIT(i); } else { if(ps[p].on_ground && ps[p].on_warping_sector == 1 && sector[ps[p].cursectnum].lotag == 1 ) { CS = 257; SZ = sector[SECT].ceilingz+(27<<8); SA = ps[p].ang; if(T1 == 8) T1 = 0; else T1++; } else { if(sector[SECT].lotag != 2) SZ = sector[SECT].floorz; CS = (short) 32768; } } SX += (ps[p].posx-ps[p].oposx); SY += (ps[p].posy-ps[p].oposy); setsprite(i,SX,SY,SZ); BOLT: i = nexti; } } short otherp; void moveplayers(void) //Players { short i , nexti; int otherx; spritetype *s; struct player_struct *p; i = headspritestat[10]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; p = &ps[s->yvel]; if(s->owner >= 0) { if(p->newowner >= 0 ) //Looking thru the camera { s->x = p->oposx; s->y = p->oposy; hittype[i].bposz = s->z = p->oposz+PHEIGHT; s->ang = p->oang; setsprite(i,s->x,s->y,s->z); } else { if(ud.multimode > 1) otherp = findotherplayer(s->yvel,&otherx); else { otherp = s->yvel; otherx = 0; } execute(i,s->yvel,otherx); if(ud.multimode > 1) if( sprite[ps[otherp].i].extra > 0 ) { if( s->yrepeat > 32 && sprite[ps[otherp].i].yrepeat < 32) { if( otherx < 1400 && p->knee_incs == 0 ) { p->knee_incs = 1; p->weapon_pos = -1; p->actorsqu = ps[otherp].i; } } } if(ud.god) { s->extra = max_player_health; s->cstat = 257; p->jetpack_amount = 1599; } if( s->extra > 0 ) { hittype[i].owner = i; if(ud.god == 0) if( ceilingspace(s->sectnum) || floorspace(s->sectnum) ) quickkill(p); } else { p->posx = s->x; p->posy = s->y; p->posz = s->z-(20<<8); p->newowner = -1; if( p->wackedbyactor >= 0 && sprite[p->wackedbyactor].statnum < MAXSTATUS ) { p->ang += getincangle(p->ang,getangle(sprite[p->wackedbyactor].x-p->posx,sprite[p->wackedbyactor].y-p->posy))>>1; p->ang &= 2047; } } s->ang = p->ang; } } else { if(p->holoduke_on == -1) KILLIT(i); hittype[i].bposx = s->x; hittype[i].bposy = s->y; hittype[i].bposz = s->z; s->cstat = 0; if(s->xrepeat < 42) { s->xrepeat += 4; s->cstat |= 2; } else s->xrepeat = 42; if(s->yrepeat < 36) s->yrepeat += 4; else { s->yrepeat = 36; if(sector[s->sectnum].lotag != 2) makeitfall(i); if(s->zvel == 0 && sector[s->sectnum].lotag == 1) s->z += (32<<8); } if(s->extra < 8) { s->xvel = 128; s->ang = p->ang; s->extra++; //IFMOVING; // JBF 20040825: is really "if (ssp(i,CLIPMASK0)) ;" which is probably ssp(i,CLIPMASK0); // not the safest of ideas because a zealous optimiser probably sees // it as redundant, so I'll call the "ssp(i,CLIPMASK0)" explicitly. } else { s->ang = 2047-p->ang; setsprite(i,s->x,s->y,s->z); } } if (sector[s->sectnum].ceilingstat&1) s->shade += (sector[s->sectnum].ceilingshade-s->shade)>>1; else s->shade += (sector[s->sectnum].floorshade-s->shade)>>1; BOLT: i = nexti; } } void movefx(void) { short i, j, nexti, p; int x, ht; spritetype *s; i = headspritestat[11]; while(i >= 0) { s = &sprite[i]; nexti = nextspritestat[i]; switch(s->picnum) { case RESPAWN: if(sprite[i].extra == 66) { j = spawn(i,SHT); // sprite[j].pal = sprite[i].pal; KILLIT(i); } else if(sprite[i].extra > (66-13)) sprite[i].extra++; break; case MUSICANDSFX: ht = s->hitag; if(T2 != SoundToggle) { T2 = SoundToggle; T1 = 0; } if(s->lotag >= 1000 && s->lotag < 2000) { x = ldist(&sprite[ps[screenpeek].i],s); if( x < ht && T1 == 0 ) { FX_SetReverb( s->lotag - 1000 ); T1 = 1; } if( x >= ht && T1 == 1 ) { FX_SetReverb(0); FX_SetReverbDelay(0); T1 = 0; } } else if(s->lotag < 999 && (unsigned)sector[s->sectnum].lotag < 9 && AmbienceToggle && sector[SECT].floorz != sector[SECT].ceilingz) { if( (soundm[s->lotag]&2) ) { x = dist(&sprite[ps[screenpeek].i],s); if( x < ht && T1 == 0 && FX_VoiceAvailable(soundpr[s->lotag]-1) ) { if(numenvsnds == NumVoices) { j = headspritestat[11]; while(j >= 0) { if( PN == MUSICANDSFX && j != i && sprite[j].lotag < 999 && hittype[j].temp_data[0] == 1 && dist(&sprite[j],&sprite[ps[screenpeek].i]) > x ) { stopenvsound(sprite[j].lotag,j); break; } j = nextspritestat[j]; } if(j == -1) goto BOLT; } spritesound(s->lotag,i); T1 = 1; } if( x >= ht && T1 == 1 ) { T1 = 0; stopenvsound(s->lotag,i); } } if( (soundm[s->lotag]&16) ) { if(T5 > 0) T5--; else for(p=connecthead;p>=0;p=connectpoint2[p]) if( p == myconnectindex && ps[p].cursectnum == s->sectnum ) { j = s->lotag+((unsigned)global_random%(s->hitag+1)); sound(j); T5 = 26*40 + (global_random%(26*40)); } } } break; } BOLT: i = nexti; } } void movefallers(void) { short i, nexti, sect, j; spritetype *s; int x; i = headspritestat[12]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; sect = s->sectnum; if( T1 == 0 ) { s->z -= (16<<8); T2 = s->ang; x = s->extra; IFHIT { if( j == FIREEXT || j == RPG || j == RADIUSEXPLOSION || j == SEENINE || j == OOZFILTER ) { if(s->extra <= 0) { T1 = 1; j = headspritestat[12]; while(j >= 0) { if(sprite[j].hitag == SHT) { hittype[j].temp_data[0] = 1; sprite[j].cstat &= (65535-64); if(sprite[j].picnum == CEILINGSTEAM || sprite[j].picnum == STEAM) sprite[j].cstat |= 32768; } j = nextspritestat[j]; } } } else { hittype[i].extra = 0; s->extra = x; } } s->ang = T2; s->z += (16<<8); } else if(T1 == 1) { if(s->lotag > 0) { s->lotag-=3; if(s->lotag <= 0) { s->xvel = (32+(TRAND&63)); s->zvel = -(1024+(TRAND&1023)); } } else { if( s->xvel > 0) { s->xvel -= 8; ssp(i,CLIPMASK0); } if( floorspace(s->sectnum) ) x = 0; else { if(ceilingspace(s->sectnum)) x = gc/6; else x = gc; } if( s->z < (sector[sect].floorz-FOURSLEIGHT) ) { s->zvel += x; if(s->zvel > 6144) s->zvel = 6144; s->z += s->zvel; } if( (sector[sect].floorz-s->z) < (16<<8) ) { j = 1+(TRAND&7); for(x=0;x<j;x++) RANDOMSCRAP; KILLIT(i); } } } BOLT: i = nexti; } } void movestandables(void) { short i, j, k, m, nexti, nextj, p=0, sect; int l=0, x, *t; spritetype *s; i = headspritestat[6]; while(i >= 0) { nexti = nextspritestat[i]; t = &hittype[i].temp_data[0]; s = &sprite[i]; sect = s->sectnum; if( sect < 0 ) KILLIT(i); hittype[i].bposx = s->x; hittype[i].bposy = s->y; hittype[i].bposz = s->z; IFWITHIN(CRANE,CRANE+3) { //t[0] = state //t[1] = checking sector number if(s->xvel) getglobalz(i); if( t[0] == 0 ) //Waiting to check the sector { j = headspritesect[t[1]]; while(j>=0) { nextj = nextspritesect[j]; switch( sprite[j].statnum ) { case 1: case 2: case 6: case 10: s->ang = getangle(msx[t[4]+1]-s->x,msy[t[4]+1]-s->y); setsprite(j,msx[t[4]+1],msy[t[4]+1],sprite[j].z); t[0]++; goto BOLT; } j = nextj; } } else if(t[0]==1) { if( s->xvel < 184 ) { s->picnum = CRANE+1; s->xvel += 8; } //IFMOVING; // JBF 20040825: see my rant above about this ssp(i,CLIPMASK0); if(sect == t[1]) t[0]++; } else if(t[0]==2 || t[0]==7) { s->z += (1024+512); if(t[0]==2) { if( (sector[sect].floorz - s->z) < (64<<8) ) if(s->picnum > CRANE) s->picnum--; if( (sector[sect].floorz - s->z) < (4096+1024)) t[0]++; } if(t[0]==7) { if( (sector[sect].floorz - s->z) < (64<<8) ) { if(s->picnum > CRANE) s->picnum--; else { if(s->owner==-2) { spritesound(DUKE_GRUNT,ps[p].i); p = findplayer(s,&x); if(ps[p].on_crane == i) ps[p].on_crane = -1; } t[0]++; s->owner = -1; } } } } else if(t[0]==3) { s->picnum++; if( s->picnum == (CRANE+2) ) { p = checkcursectnums(t[1]); if(p >= 0 && ps[p].on_ground) { s->owner = -2; ps[p].on_crane = i; spritesound(DUKE_GRUNT,ps[p].i); ps[p].ang = s->ang+1024; } else { j = headspritesect[t[1]]; while(j>=0) { switch( sprite[j].statnum ) { case 1: case 6: s->owner = j; break; } j = nextspritesect[j]; } } t[0]++;//Grabbed the sprite t[2]=0; goto BOLT; } } else if(t[0]==4) //Delay before going up { t[2]++; if(t[2] > 10) t[0]++; } else if(t[0]==5 || t[0] == 8) { if(t[0]==8 && s->picnum < (CRANE+2)) if( (sector[sect].floorz-s->z) > 8192) s->picnum++; if(s->z < msx[t[4]+2]) { t[0]++; s->xvel = 0; } else s->z -= (1024+512); } else if(t[0]==6) { if( s->xvel < 192 ) s->xvel += 8; s->ang = getangle(msx[t[4]]-s->x,msy[t[4]]-s->y); //IFMOVING; // JBF 20040825: see my rant above about this ssp(i,CLIPMASK0); if( ((s->x-msx[t[4]])*(s->x-msx[t[4]])+(s->y-msy[t[4]])*(s->y-msy[t[4]]) ) < (128*128) ) t[0]++; } else if(t[0]==9) t[0] = 0; setsprite(msy[t[4]+2],s->x,s->y,s->z-(34<<8)); if(s->owner != -1) { p = findplayer(s,&x); IFHIT { if(s->owner == -2) if(ps[p].on_crane == i) ps[p].on_crane = -1; s->owner = -1; s->picnum = CRANE; goto BOLT; } if(s->owner >= 0) { setsprite(s->owner,s->x,s->y,s->z); hittype[s->owner].bposx = s->x; hittype[s->owner].bposy = s->y; hittype[s->owner].bposz = s->z; s->zvel = 0; } else if(s->owner == -2) { ps[p].oposx = ps[p].posx = s->x-(sintable[(ps[p].ang+512)&2047]>>6); ps[p].oposy = ps[p].posy = s->y-(sintable[ps[p].ang&2047]>>6); ps[p].oposz = ps[p].posz = s->z+(2<<8); setsprite(ps[p].i,ps[p].posx,ps[p].posy,ps[p].posz); ps[p].cursectnum = sprite[ps[p].i].sectnum; } } goto BOLT; } IFWITHIN(WATERFOUNTAIN,WATERFOUNTAIN+3) { if(t[0] > 0) { if( t[0] < 20 ) { t[0]++; s->picnum++; if( s->picnum == ( WATERFOUNTAIN+3 ) ) s->picnum = WATERFOUNTAIN+1; } else { p = findplayer(s,&x); if(x > 512) { t[0] = 0; s->picnum = WATERFOUNTAIN; } else t[0] = 1; } } goto BOLT; } if( AFLAMABLE(s->picnum) ) { if(T1 == 1) { T2++; if( (T2&3) > 0) goto BOLT; if( s->picnum == TIRE && T2 == 32 ) { s->cstat = 0; j = spawn(i,BLOODPOOL); sprite[j].shade = 127; } else { if(s->shade < 64) s->shade++; else KILLIT(i); } j = s->xrepeat-(TRAND&7); if(j < 10) { KILLIT(i); } s->xrepeat = j; j = s->yrepeat-(TRAND&7); if(j < 4) { KILLIT(i); } s->yrepeat = j; } if(s->picnum == BOX) { makeitfall(i); hittype[i].ceilingz = sector[s->sectnum].ceilingz; } goto BOLT; } if(s->picnum == TRIPBOMB) { if(T3 > 0) { T3--; if(T3 == 8) { spritesound(LASERTRIP_EXPLODE,i); for(j=0;j<5;j++) RANDOMSCRAP; x = s->extra; hitradius( i, tripbombblastradius, x>>2,x>>1,x-(x>>2),x); j = spawn(i,EXPLOSION2); sprite[j].ang = s->ang; sprite[j].xvel = 348; ssp(j,CLIPMASK0); j = headspritestat[5]; while(j >= 0) { if(sprite[j].picnum == LASERLINE && s->hitag == sprite[j].hitag) sprite[j].xrepeat = sprite[j].yrepeat = 0; j = nextspritestat[j]; } KILLIT(i); } goto BOLT; } else { x = s->extra; s->extra = 1; l = s->ang; IFHIT { T3 = 16; } s->extra = x; s->ang = l; } if( T1 < 32 ) { p = findplayer(s,&x); if( x > 768 ) T1++; else if(T1 > 16) T1++; } if( T1 == 32 ) { l = s->ang; s->ang = T6; T4 = s->x;T5 = s->y; s->x += sintable[(T6+512)&2047]>>9; s->y += sintable[(T6)&2047]>>9; s->z -= (3<<8); setsprite(i,s->x,s->y,s->z); x = hitasprite(i,&m); hittype[i].lastvx = x; s->ang = l; k = 0; while(x > 0) { j = spawn(i,LASERLINE); setsprite(j,sprite[j].x,sprite[j].y,sprite[j].z); sprite[j].hitag = s->hitag; hittype[j].temp_data[1] = sprite[j].z; s->x += sintable[(T6+512)&2047]>>4; s->y += sintable[(T6)&2047]>>4; if( x < 1024 ) { sprite[j].xrepeat = x>>5; break; } x -= 1024; } T1++; s->x = T4;s->y = T5; s->z += (3<<8); setsprite(i,s->x,s->y,s->z); T4 = 0; if( m >= 0 ) { T3 = 13; spritesound(LASERTRIP_ARMING,i); } else T3 = 0; } if(T1 == 33) { T2++; T4 = s->x;T5 = s->y; s->x += sintable[(T6+512)&2047]>>9; s->y += sintable[(T6)&2047]>>9; s->z -= (3<<8); setsprite(i,s->x,s->y,s->z); x = hitasprite(i,&m); s->x = T4;s->y = T5; s->z += (3<<8); setsprite(i,s->x,s->y,s->z); if( hittype[i].lastvx != x ) { T3 = 13; spritesound(LASERTRIP_ARMING,i); } } goto BOLT; } if( s->picnum >= CRACK1 && s->picnum <= CRACK4 ) { if(s->hitag > 0) { t[0] = s->cstat; t[1] = s->ang; j = ifhitbyweapon(i); if(j == FIREEXT || j == RPG || j == RADIUSEXPLOSION || j == SEENINE || j == OOZFILTER ) { j = headspritestat[6]; while(j >= 0) { if(s->hitag == sprite[j].hitag && ( sprite[j].picnum == OOZFILTER || sprite[j].picnum == SEENINE ) ) if(sprite[j].shade != -32) sprite[j].shade = -32; j = nextspritestat[j]; } goto DETONATE; } else { s->cstat = t[0]; s->ang = t[1]; s->extra = 0; } } goto BOLT; } if( s->picnum == FIREEXT ) { j = ifhitbyweapon(i); if( j == -1 ) goto BOLT; for(k=0;k<16;k++) { j = EGS(SECT,SX,SY,SZ-(TRAND%(48<<8)),SCRAP3+(TRAND&3),-8,48,48,TRAND&2047,(TRAND&63)+64,-(TRAND&4095)-(sprite[i].zvel>>2),i,5); sprite[j].pal = 2; } spawn(i,EXPLOSION2); spritesound(PIPEBOMB_EXPLODE,i); spritesound(GLASS_HEAVYBREAK,i); if(s->hitag > 0) { j = headspritestat[6]; while(j >= 0) { if(s->hitag == sprite[j].hitag && ( sprite[j].picnum == OOZFILTER || sprite[j].picnum == SEENINE ) ) if(sprite[j].shade != -32) sprite[j].shade = -32; j = nextspritestat[j]; } x = s->extra; spawn(i,EXPLOSION2); hitradius( i, pipebombblastradius,x>>2, x-(x>>1),x-(x>>2), x); spritesound(PIPEBOMB_EXPLODE,i); goto DETONATE; } else { hitradius(i,seenineblastradius,10,15,20,25); KILLIT(i); } goto BOLT; } if(s->picnum == OOZFILTER || s->picnum == SEENINE || s->picnum == SEENINEDEAD || s->picnum == (SEENINEDEAD+1) ) { if(s->shade != -32 && s->shade != -33) { if(s->xrepeat) j = (ifhitbyweapon(i) >= 0); else j = 0; if( j || s->shade == -31 ) { if(j) s->lotag = 0; t[3] = 1; j = headspritestat[6]; while(j >= 0) { if(s->hitag == sprite[j].hitag && ( sprite[j].picnum == SEENINE || sprite[j].picnum == OOZFILTER ) ) sprite[j].shade = -32; j = nextspritestat[j]; } } } else { if(s->shade == -32) { if(s->lotag > 0) { s->lotag-=3; if(s->lotag <= 0) s->lotag = -99; } else s->shade = -33; } else { if( s->xrepeat > 0 ) { T3++; if(T3 == 3) { if( s->picnum == OOZFILTER ) { T3 = 0; goto DETONATE; } if( s->picnum != (SEENINEDEAD+1) ) { T3 = 0; if(s->picnum == SEENINEDEAD) s->picnum++; else if(s->picnum == SEENINE) s->picnum = SEENINEDEAD; } else goto DETONATE; } goto BOLT; } DETONATE: earthquaketime = 16; j = headspritestat[3]; while(j >= 0) { if( s->hitag == sprite[j].hitag ) { if(sprite[j].lotag == 13) { if( hittype[j].temp_data[2] == 0 ) hittype[j].temp_data[2] = 1; } else if(sprite[j].lotag == 8) hittype[j].temp_data[4] = 1; else if(sprite[j].lotag == 18) { if(hittype[j].temp_data[0] == 0) hittype[j].temp_data[0] = 1; } else if(sprite[j].lotag == 21) hittype[j].temp_data[0] = 1; } j = nextspritestat[j]; } s->z -= (32<<8); if( ( t[3] == 1 && s->xrepeat ) || s->lotag == -99 ) { x = s->extra; spawn(i,EXPLOSION2); hitradius( i,seenineblastradius,x>>2, x-(x>>1),x-(x>>2), x); spritesound(PIPEBOMB_EXPLODE,i); } if(s->xrepeat) for(x=0;x<8;x++) RANDOMSCRAP; KILLIT(i); } } goto BOLT; } if(s->picnum == MASTERSWITCH) { if(s->yvel == 1) { s->hitag--; if(s->hitag <= 0) { operatesectors(sect,i); j = headspritesect[sect]; while(j >= 0) { if(sprite[j].statnum == 3) { switch(sprite[j].lotag) { case 2: case 21: case 31: case 32: case 36: hittype[j].temp_data[0] = 1; break; case 3: hittype[j].temp_data[4] = 1; break; } } else if(sprite[j].statnum == 6) { switch(sprite[j].picnum) { case SEENINE: case OOZFILTER: sprite[j].shade = -31; break; } } j = nextspritesect[j]; } KILLIT(i); } } goto BOLT; } switch(s->picnum) { case VIEWSCREEN: case VIEWSCREEN2: if(s->xrepeat == 0) KILLIT(i); p = findplayer(s, &x); if( x < 2048 ) { if( SP == 1 ) camsprite = i; } else if( camsprite != -1 && T1 == 1) { camsprite = -1; T1 = 0; //loadtile(s->picnum); //invalidatetile(s->picnum,-1,255); walock[TILE_VIEWSCR] = 199; } goto BOLT; case TRASH: if(s->xvel == 0) s->xvel = 1; IFMOVING { makeitfall(i); if(TRAND&1) s->zvel -= 256; if( klabs(s->xvel) < 48 ) s->xvel += (TRAND&3); } else KILLIT(i); break; case SIDEBOLT1: case SIDEBOLT1+1: case SIDEBOLT1+2: case SIDEBOLT1+3: p = findplayer(s, &x); if( x > 20480 ) goto BOLT; CLEAR_THE_BOLT2: if(t[2]) { t[2]--; goto BOLT; } if( (s->xrepeat|s->yrepeat) == 0 ) { s->xrepeat=t[0]; s->yrepeat=t[1]; } if( (TRAND&8) == 0 ) { t[0]=s->xrepeat; t[1]=s->yrepeat; t[2] = global_random&4; s->xrepeat=s->yrepeat=0; goto CLEAR_THE_BOLT2; } s->picnum++; if(l&1) s->cstat ^= 2; if( (TRAND&1) && sector[sect].floorpicnum == HURTRAIL ) spritesound(SHORT_CIRCUIT,i); if(s->picnum == SIDEBOLT1+4) s->picnum = SIDEBOLT1; goto BOLT; case BOLT1: case BOLT1+1: case BOLT1+2: case BOLT1+3: p = findplayer(s, &x); if( x > 20480 ) goto BOLT; if( t[3] == 0 ) t[3]=sector[sect].floorshade; CLEAR_THE_BOLT: if(t[2]) { t[2]--; sector[sect].floorshade = 20; sector[sect].ceilingshade = 20; goto BOLT; } if( (s->xrepeat|s->yrepeat) == 0 ) { s->xrepeat=t[0]; s->yrepeat=t[1]; } else if( (TRAND&8) == 0 ) { t[0]=s->xrepeat; t[1]=s->yrepeat; t[2] = global_random&4; s->xrepeat=s->yrepeat=0; goto CLEAR_THE_BOLT; } s->picnum++; l = global_random&7; s->xrepeat=l+8; if(l&1) s->cstat ^= 2; if( s->picnum == (BOLT1+1) && (TRAND&7) == 0 && sector[sect].floorpicnum == HURTRAIL ) spritesound(SHORT_CIRCUIT,i); if(s->picnum==BOLT1+4) s->picnum=BOLT1; if(s->picnum&1) { sector[sect].floorshade = 0; sector[sect].ceilingshade = 0; } else { sector[sect].floorshade = 20; sector[sect].ceilingshade = 20; } goto BOLT; case WATERDRIP: if( t[1] ) { t[1]--; if(t[1] == 0) s->cstat &= 32767; } else { makeitfall(i); ssp(i,CLIPMASK0); if(s->xvel > 0) s->xvel -= 2; if(s->zvel == 0) { s->cstat |= 32768; if(s->pal != 2 && s->hitag == 0) spritesound(SOMETHING_DRIPPING,i); if(sprite[s->owner].picnum != WATERDRIP) { KILLIT(i); } else { hittype[i].bposz = s->z = t[0]; t[1] = 48+(TRAND&31); } } } goto BOLT; case DOORSHOCK: j = klabs(sector[sect].ceilingz-sector[sect].floorz)>>9; s->yrepeat = j+4; s->xrepeat = 16; s->z = sector[sect].floorz; goto BOLT; case TOUCHPLATE: if( t[1] == 1 && s->hitag >= 0) //Move the sector floor { x = sector[sect].floorz; if(t[3] == 1) { if(x >= t[2]) { sector[sect].floorz = x; t[1] = 0; } else { sector[sect].floorz += sector[sect].extra; p = checkcursectnums(sect); if(p >= 0) ps[p].posz += sector[sect].extra; } } else { if(x <= s->z) { sector[sect].floorz = s->z; t[1] = 0; } else { sector[sect].floorz -= sector[sect].extra; p = checkcursectnums(sect); if(p >= 0) ps[p].posz -= sector[sect].extra; } } goto BOLT; } if(t[5] == 1) goto BOLT; p = checkcursectnums(sect); if( p >= 0 && ( ps[p].on_ground || s->ang == 512) ) { if( t[0] == 0 && !check_activator_motion(s->lotag) ) { t[0] = 1; t[1] = 1; t[3] = !t[3]; operatemasterswitches(s->lotag); operateactivators(s->lotag,p); if(s->hitag > 0) { s->hitag--; if(s->hitag == 0) t[5] = 1; } } } else t[0] = 0; if(t[1] == 1) { j = headspritestat[6]; while(j >= 0) { if(j != i && sprite[j].picnum == TOUCHPLATE && sprite[j].lotag == s->lotag) { hittype[j].temp_data[1] = 1; hittype[j].temp_data[3] = t[3]; } j = nextspritestat[j]; } } goto BOLT; case CANWITHSOMETHING: case CANWITHSOMETHING2: case CANWITHSOMETHING3: case CANWITHSOMETHING4: makeitfall(i); IFHIT { spritesound(VENT_BUST,i); for(j=0;j<10;j++) RANDOMSCRAP; if(s->lotag) spawn(i,s->lotag); KILLIT(i); } goto BOLT; case EXPLODINGBARREL: case WOODENHORSE: case HORSEONSIDE: case FLOORFLAME: case FIREBARREL: case FIREVASE: case NUKEBARREL: case NUKEBARRELDENTED: case NUKEBARRELLEAKED: case TOILETWATER: case RUBBERCAN: case STEAM: case CEILINGSTEAM: p = findplayer(s, &x); execute(i,p,x); goto BOLT; case WATERBUBBLEMAKER: p = findplayer(s, &x); execute(i,p,x); goto BOLT; } BOLT: i = nexti; } } void bounce(short i) { int k, l, daang, dax, day, daz, xvect, yvect, zvect; short hitsect; spritetype *s = &sprite[i]; xvect = mulscale10(s->xvel,sintable[(s->ang+512)&2047]); yvect = mulscale10(s->xvel,sintable[s->ang&2047]); zvect = s->zvel; hitsect = s->sectnum; k = sector[hitsect].wallptr; l = wall[k].point2; daang = getangle(wall[l].x-wall[k].x,wall[l].y-wall[k].y); if ( s->z < (hittype[i].floorz+hittype[i].ceilingz)>>1) k = sector[hitsect].ceilingheinum; else k = sector[hitsect].floorheinum; dax = mulscale14(k,sintable[(daang)&2047]); day = mulscale14(k,sintable[(daang+1536)&2047]); daz = 4096; k = xvect*dax+yvect*day+zvect*daz; l = dax*dax+day*day+daz*daz; if ((klabs(k)>>14) < l) { k = divscale17(k,l); xvect -= mulscale16(dax,k); yvect -= mulscale16(day,k); zvect -= mulscale16(daz,k); } s->zvel = zvect; s->xvel = ksqrt(dmulscale8(xvect,xvect,yvect,yvect)); s->ang = getangle(xvect,yvect); } void moveweapons(void) { short i, j, k, nexti, p, q; int dax,day,daz, x, ll; unsigned int qq; spritetype *s; i = headspritestat[4]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; if(s->sectnum < 0) KILLIT(i); hittype[i].bposx = s->x; hittype[i].bposy = s->y; hittype[i].bposz = s->z; switch(s->picnum) { case RADIUSEXPLOSION: case KNEE: KILLIT(i); case TONGUE: T1 = sintable[(T2)&2047]>>9; T2 += 32; if(T2 > 2047) KILLIT(i); if(sprite[s->owner].statnum == MAXSTATUS) if(badguy(&sprite[s->owner]) == 0) KILLIT(i); s->ang = sprite[s->owner].ang; s->x = sprite[s->owner].x; s->y = sprite[s->owner].y; if(sprite[s->owner].picnum == APLAYER) s->z = sprite[s->owner].z-(34<<8); for(k=0;k<T1;k++) { q = EGS(s->sectnum, s->x+((k*sintable[(s->ang+512)&2047])>>9), s->y+((k*sintable[s->ang&2047])>>9), s->z+((k*ksgn(s->zvel))*klabs(s->zvel/12)),TONGUE,-40+(k<<1), 8,8,0,0,0,i,5); sprite[q].cstat = 128; sprite[q].pal = 8; } q = EGS(s->sectnum, s->x+((k*sintable[(s->ang+512)&2047])>>9), s->y+((k*sintable[s->ang&2047])>>9), s->z+((k*ksgn(s->zvel))*klabs(s->zvel/12)),INNERJAW,-40, 32,32,0,0,0,i,5); sprite[q].cstat = 128; if( T2 > 512 && T2 < (1024) ) sprite[q].picnum = INNERJAW+1; goto BOLT; case FREEZEBLAST: if(s->yvel < 1 || s->extra < 2 || (s->xvel|s->zvel) == 0) { j = spawn(i,TRANSPORTERSTAR); sprite[j].pal = 1; sprite[j].xrepeat = 32; sprite[j].yrepeat = 32; KILLIT(i); } // fall through case SHRINKSPARK: case RPG: case FIRELASER: case SPIT: case COOLEXPLOSION1: if( s->picnum == COOLEXPLOSION1 ) if( !issoundplaying(WIERDSHOT_FLY, 1) ) spritesound(WIERDSHOT_FLY,i); p = -1; if(s->picnum == RPG && sector[s->sectnum].lotag == 2) { k = s->xvel>>1; ll = s->zvel>>1; } else { k = s->xvel; ll = s->zvel; } dax = s->x; day = s->y; daz = s->z; getglobalz(i); qq = CLIPMASK1; switch(s->picnum) { case RPG: if(hittype[i].picnum != BOSS2 && s->xrepeat >= 10 && sector[s->sectnum].lotag != 2) { j = spawn(i,SMALLSMOKE); sprite[j].z += (1<<8); } break; } j = movesprite(i, (k*(sintable[(s->ang+512)&2047]))>>14, (k*(sintable[s->ang&2047]))>>14,ll,qq); if(s->picnum == RPG && s->yvel >= 0) if( FindDistance2D(s->x-sprite[s->yvel].x,s->y-sprite[s->yvel].y) < 256 ) j = 49152|s->yvel; if(s->sectnum < 0) { KILLIT(i); } if( (j&49152) != 49152) if(s->picnum != FREEZEBLAST) { if(s->z < hittype[i].ceilingz) { j = 16384|(s->sectnum); s->zvel = -1; } else if( ( s->z > hittype[i].floorz && sector[s->sectnum].lotag != 1 ) || ( s->z > hittype[i].floorz+(16<<8) && sector[s->sectnum].lotag == 1 ) ) { j = 16384|(s->sectnum); if(sector[s->sectnum].lotag != 1) s->zvel = 1; } } if(s->picnum == FIRELASER) { for(k=-3;k<2;k++) { x = EGS(s->sectnum, s->x+((k*sintable[(s->ang+512)&2047])>>9), s->y+((k*sintable[s->ang&2047])>>9), s->z+((k*ksgn(s->zvel))*klabs(s->zvel/24)),FIRELASER,-40+(k<<2), s->xrepeat,s->yrepeat,0,0,0,s->owner,5); sprite[x].cstat = 128; sprite[x].pal = s->pal; } } else if(s->picnum == SPIT) if(s->zvel < 6144) s->zvel += gc-112; if( j != 0 ) { if(s->picnum == COOLEXPLOSION1) { if( (j&49152) == 49152 && sprite[j&(MAXSPRITES-1)].picnum != APLAYER) goto BOLT; s->xvel = 0; s->zvel = 0; } if( (j&49152) == 49152 ) { j &= (MAXSPRITES-1); if(s->picnum == FREEZEBLAST && sprite[j].pal == 1 ) if( badguy(&sprite[j]) || sprite[j].picnum == APLAYER ) { j = spawn(i,TRANSPORTERSTAR); sprite[j].pal = 1; sprite[j].xrepeat = 32; sprite[j].yrepeat = 32; KILLIT(i); } checkhitsprite(j,i); if(sprite[j].picnum == APLAYER) { p = sprite[j].yvel; spritesound(PISTOL_BODYHIT,j); if(s->picnum == SPIT) { ps[p].horiz += 32; ps[p].return_to_center = 8; if(ps[p].loogcnt == 0) { if(!isspritemakingsound(ps[p].i, DUKE_LONGTERM_PAIN)) spritesound(DUKE_LONGTERM_PAIN,ps[p].i); j = 3+(TRAND&3); ps[p].numloogs = j; ps[p].loogcnt = 24*4; for(x=0;x < j;x++) { ps[p].loogiex[x] = TRAND%xdim; ps[p].loogiey[x] = TRAND%ydim; } } } } } else if( (j&49152) == 32768 ) { j &= (MAXWALLS-1); if(s->picnum != RPG && s->picnum != FREEZEBLAST && s->picnum != SPIT && ( wall[j].overpicnum == MIRROR || wall[j].picnum == MIRROR ) ) { k = getangle( wall[wall[j].point2].x-wall[j].x, wall[wall[j].point2].y-wall[j].y); s->ang = ((k<<1) - s->ang)&2047; s->owner = i; spawn(i,TRANSPORTERSTAR); goto BOLT; } else { setsprite(i,dax,day,daz); checkhitwall(i,j,s->x,s->y,s->z,s->picnum); if(s->picnum == FREEZEBLAST) { if( wall[j].overpicnum != MIRROR && wall[j].picnum != MIRROR ) { s->extra >>= 1; s->yvel--; } k = getangle( wall[wall[j].point2].x-wall[j].x, wall[wall[j].point2].y-wall[j].y); s->ang = ((k<<1) - s->ang)&2047; goto BOLT; } } } else if( (j&49152) == 16384) { setsprite(i,dax,day,daz); if(s->zvel < 0) { if( sector[s->sectnum].ceilingstat&1 ) if(sector[s->sectnum].ceilingpal == 0) KILLIT(i); checkhitceiling(s->sectnum); } if(s->picnum == FREEZEBLAST) { bounce(i); ssp(i,qq); s->extra >>= 1; if(s->xrepeat > 8) s->xrepeat -= 2; if(s->yrepeat > 8) s->yrepeat -= 2; s->yvel--; goto BOLT; } } if(s->picnum != SPIT) { if(s->picnum == RPG) { k = spawn(i,EXPLOSION2); sprite[k].x = dax; sprite[k].y = day; sprite[k].z = daz; if(s->xrepeat < 10) { sprite[k].xrepeat = 6; sprite[k].yrepeat = 6; } else if( (j&49152) == 16384) { if( s->zvel > 0) spawn(i,EXPLOSION2BOT); else { sprite[k].cstat |= 8; sprite[k].z += (48<<8); } } } else if(s->picnum == SHRINKSPARK) { spawn(i,SHRINKEREXPLOSION); spritesound(SHRINKER_HIT,i); hitradius(i,shrinkerblastradius,0,0,0,0); } else if( s->picnum != COOLEXPLOSION1 && s->picnum != FREEZEBLAST && s->picnum != FIRELASER) { k = spawn(i,EXPLOSION2); sprite[k].xrepeat = sprite[k].yrepeat = s->xrepeat>>1; if( (j&49152) == 16384) { if( s->zvel < 0) { sprite[k].cstat |= 8; sprite[k].z += (72<<8); } } } if( s->picnum == RPG ) { spritesound(RPG_EXPLODE,i); if(s->xrepeat >= 10) { x = s->extra; hitradius( i,rpgblastradius, x>>2,x>>1,x-(x>>2),x); } else { x = s->extra+(global_random&3); hitradius( i,(rpgblastradius>>1),x>>2,x>>1,x-(x>>2),x); } } } if(s->picnum != COOLEXPLOSION1) KILLIT(i); } if(s->picnum == COOLEXPLOSION1) { s->shade++; if(s->shade >= 40) KILLIT(i); } else if(s->picnum == RPG && sector[s->sectnum].lotag == 2 && s->xrepeat >= 10 && rnd(140)) spawn(i,WATERBUBBLE); goto BOLT; case SHOTSPARK1: p = findplayer(s,&x); execute(i,p,x); goto BOLT; } BOLT: i = nexti; } } void movetransports(void) { char warpspriteto; short i, j, k, l, p, sect, sectlotag, nexti, nextj; int ll,onfloorz,q; i = headspritestat[9]; //Transporters while(i >= 0) { sect = SECT; sectlotag = sector[sect].lotag; nexti = nextspritestat[i]; if(OW == i) { i = nexti; continue; } onfloorz = T5; if(T1 > 0) T1--; j = headspritesect[sect]; while(j >= 0) { nextj = nextspritesect[j]; switch(sprite[j].statnum) { case 10: // Player if( sprite[j].owner != -1 ) { p = sprite[j].yvel; ps[p].on_warping_sector = 1; if( ps[p].transporter_hold == 0 && ps[p].jumping_counter == 0 ) { if(ps[p].on_ground && sectlotag == 0 && onfloorz && ps[p].jetpack_on == 0 ) { if(sprite[i].pal == 0) { spawn(i,TRANSPORTERBEAM); spritesound(TELEPORTER,i); } for(k=connecthead;k>=0;k=connectpoint2[k]) if(ps[k].cursectnum == sprite[OW].sectnum) { ps[k].frag_ps = p; sprite[ps[k].i].extra = 0; } ps[p].ang = sprite[OW].ang; if(sprite[OW].owner != OW) { T1 = 13; hittype[OW].temp_data[0] = 13; ps[p].transporter_hold = 13; } ps[p].bobposx = ps[p].oposx = ps[p].posx = sprite[OW].x; ps[p].bobposy = ps[p].oposy = ps[p].posy = sprite[OW].y; ps[p].oposz = ps[p].posz = sprite[OW].z-PHEIGHT; changespritesect(j,sprite[OW].sectnum); ps[p].cursectnum = sprite[j].sectnum; if(sprite[i].pal == 0) { k = spawn(OW,TRANSPORTERBEAM); spritesound(TELEPORTER,k); } break; } } else if( !(sectlotag == 1 && ps[p].on_ground == 1) ) break; if(onfloorz == 0 && klabs(SZ-ps[p].posz) < 6144 ) if( (ps[p].jetpack_on == 0 ) || (ps[p].jetpack_on && (sync[p].bits&1) ) || (ps[p].jetpack_on && (sync[p].bits&2) ) ) { ps[p].oposx = ps[p].posx += sprite[OW].x-SX; ps[p].oposy = ps[p].posy += sprite[OW].y-SY; if( ps[p].jetpack_on && ( (sync[p].bits&1) || ps[p].jetpack_on < 11 ) ) ps[p].posz = sprite[OW].z-6144; else ps[p].posz = sprite[OW].z+6144; ps[p].oposz = ps[p].posz; hittype[ps[p].i].bposx = ps[p].posx; hittype[ps[p].i].bposy = ps[p].posy; hittype[ps[p].i].bposz = ps[p].posz; changespritesect(j,sprite[OW].sectnum); ps[p].cursectnum = sprite[OW].sectnum; break; } k = 0; if( onfloorz && sectlotag == 1 && ps[p].on_ground && ps[p].posz > (sector[sect].floorz-(16<<8)) && ( (sync[p].bits&2) || ps[p].poszv > 2048 ) ) // if( onfloorz && sectlotag == 1 && ps[p].posz > (sector[sect].floorz-(6<<8)) ) { k = 1; if(screenpeek == p) { FX_StopAllSounds(); clearsoundlocks(); } if(sprite[ps[p].i].extra > 0) spritesound(DUKE_UNDERWATER,j); ps[p].oposz = ps[p].posz = sector[sprite[OW].sectnum].ceilingz+(7<<8); ps[p].posxv = 4096-(TRAND&8192); ps[p].posyv = 4096-(TRAND&8192); } if( onfloorz && sectlotag == 2 && ps[p].posz < (sector[sect].ceilingz+(6<<8)) ) { k = 1; // if( sprite[j].extra <= 0) break; if(screenpeek == p) { FX_StopAllSounds(); clearsoundlocks(); } spritesound(DUKE_GASP,j); ps[p].oposz = ps[p].posz = sector[sprite[OW].sectnum].floorz-(7<<8); ps[p].jumping_toggle = 1; ps[p].jumping_counter = 0; } if(k == 1) { ps[p].oposx = ps[p].posx += sprite[OW].x-SX; ps[p].oposy = ps[p].posy += sprite[OW].y-SY; if(sprite[OW].owner != OW) ps[p].transporter_hold = -2; ps[p].cursectnum = sprite[OW].sectnum; changespritesect(j,sprite[OW].sectnum); setsprite(ps[p].i,ps[p].posx,ps[p].posy,ps[p].posz+PHEIGHT); setpal(&ps[p]); if( (TRAND&255) < 32 ) spawn(j,WATERSPLASH2); if(sectlotag == 1) for(l = 0;l < 9;l++) { q = spawn(ps[p].i,WATERBUBBLE); sprite[q].z += TRAND&16383; } } } break; case 1: switch(sprite[j].picnum) { case SHARK: case COMMANDER: case OCTABRAIN: case GREENSLIME: case GREENSLIME+1: case GREENSLIME+2: case GREENSLIME+3: case GREENSLIME+4: case GREENSLIME+5: case GREENSLIME+6: case GREENSLIME+7: if(sprite[j].extra > 0) goto JBOLT; } // fall through case 4: case 5: case 12: case 13: ll = klabs(sprite[j].zvel); { warpspriteto = 0; if( ll && sectlotag == 2 && sprite[j].z < (sector[sect].ceilingz+ll) ) warpspriteto = 1; if( ll && sectlotag == 1 && sprite[j].z > (sector[sect].floorz-ll) ) warpspriteto = 1; if( sectlotag == 0 && ( onfloorz || klabs(sprite[j].z-SZ) < 4096) ) { if( sprite[OW].owner != OW && onfloorz && T1 > 0 && sprite[j].statnum != 5 ) { T1++; goto BOLT; } warpspriteto = 1; } if( warpspriteto ) switch(sprite[j].picnum) { case TRANSPORTERSTAR: case TRANSPORTERBEAM: case TRIPBOMB: case BULLETHOLE: case WATERSPLASH2: case BURNING: case BURNING2: case FIRE: case FIRE2: case TOILETWATER: case LASERLINE: goto JBOLT; case PLAYERONWATER: if(sectlotag == 2) { sprite[j].cstat &= 32767; break; } // fall through default: if(sprite[j].statnum == 5 && !(sectlotag == 1 || sectlotag == 2) ) break; // fall through case WATERBUBBLE: // if( rnd(192) && sprite[j].picnum == WATERBUBBLE) // break; if(sectlotag > 0) { k = spawn(j,WATERSPLASH2); if( sectlotag == 1 && sprite[j].statnum == 4 ) { sprite[k].xvel = sprite[j].xvel>>1; sprite[k].ang = sprite[j].ang; ssp(k,CLIPMASK0); } } switch(sectlotag) { case 0: if(onfloorz) { if( sprite[j].statnum == 4 || ( checkcursectnums(sect) == -1 && checkcursectnums(sprite[OW].sectnum) == -1 ) ) { sprite[j].x += (sprite[OW].x-SX); sprite[j].y += (sprite[OW].y-SY); sprite[j].z -= SZ - sector[sprite[OW].sectnum].floorz; sprite[j].ang = sprite[OW].ang; hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; hittype[j].bposz = sprite[j].z; if(sprite[i].pal == 0) { k = spawn(i,TRANSPORTERBEAM); spritesound(TELEPORTER,k); k = spawn(OW,TRANSPORTERBEAM); spritesound(TELEPORTER,k); } if( sprite[OW].owner != OW ) { T1 = 13; hittype[OW].temp_data[0] = 13; } changespritesect(j,sprite[OW].sectnum); } } else { sprite[j].x += (sprite[OW].x-SX); sprite[j].y += (sprite[OW].y-SY); sprite[j].z = sprite[OW].z+4096; hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; hittype[j].bposz = sprite[j].z; changespritesect(j,sprite[OW].sectnum); } break; case 1: sprite[j].x += (sprite[OW].x-SX); sprite[j].y += (sprite[OW].y-SY); sprite[j].z = sector[sprite[OW].sectnum].ceilingz+ll; hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; hittype[j].bposz = sprite[j].z; changespritesect(j,sprite[OW].sectnum); break; case 2: sprite[j].x += (sprite[OW].x-SX); sprite[j].y += (sprite[OW].y-SY); sprite[j].z = sector[sprite[OW].sectnum].floorz-ll; hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; hittype[j].bposz = sprite[j].z; changespritesect(j,sprite[OW].sectnum); break; } break; } } break; } JBOLT: j = nextj; } BOLT: i = nexti; } } void moveactors(void) { int x, m, l, *t; short a, i, j, nexti, nextj, sect, p; spritetype *s; unsigned short k; char namBoom = 0; i = headspritestat[1]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; sect = s->sectnum; if( s->xrepeat == 0 || sect < 0 || sect >= MAXSECTORS) KILLIT(i); t = &hittype[i].temp_data[0]; hittype[i].bposx = s->x; hittype[i].bposy = s->y; hittype[i].bposz = s->z; switch(s->picnum) { case DUCK: case TARGET: if(s->cstat&32) { t[0]++; if(t[0] > 60) { t[0] = 0; s->cstat = 128+257+16; s->extra = 1; } } else { j = ifhitbyweapon(i); if( j >= 0 ) { s->cstat = 32+128; k = 1; j = headspritestat[1]; while(j >= 0) { if( sprite[j].lotag == s->lotag && sprite[j].picnum == s->picnum ) { if( ( sprite[j].hitag && !(sprite[j].cstat&32) ) || ( !sprite[j].hitag && (sprite[j].cstat&32) ) ) { k = 0; break; } } j = nextspritestat[j]; } if(k == 1) { operateactivators(s->lotag,-1); operateforcefields(i,s->lotag); operatemasterswitches(s->lotag); } } } goto BOLT; case RESPAWNMARKERRED: case RESPAWNMARKERYELLOW: case RESPAWNMARKERGREEN: T1++; if(T1 > respawnitemtime) { KILLIT(i); } if( T1 >= (respawnitemtime>>1) && T1 < ((respawnitemtime>>1)+(respawnitemtime>>2)) ) PN = RESPAWNMARKERYELLOW; else if( T1 > ((respawnitemtime>>1)+(respawnitemtime>>2)) ) PN = RESPAWNMARKERGREEN; makeitfall(i); break; case HELECOPT: case DUKECAR: s->z += s->zvel; t[0]++; if(t[0] == 4) spritesound(WAR_AMBIENCE2,i); if( t[0] > (26*8) ) { sound(RPG_EXPLODE); for(j=0;j<32;j++) RANDOMSCRAP; earthquaketime = 16; KILLIT(i); } else if((t[0]&3) == 0) spawn(i,EXPLOSION2); ssp(i,CLIPMASK0); break; case RAT: makeitfall(i); IFMOVING { if( (TRAND&255) < 3 ) spritesound(RATTY,i); s->ang += (TRAND&31)-15+(sintable[(t[0]<<8)&2047]>>11); } else { T1++; if(T1 > 1) { KILLIT(i); } else s->ang = (TRAND&2047); } if(s->xvel < 128) s->xvel+=2; s->ang += (TRAND&3)-6; break; case QUEBALL: case STRIPEBALL: if(s->xvel) { j = headspritestat[0]; while(j >= 0) { nextj = nextspritestat[j]; if( sprite[j].picnum == POCKET && ldist(&sprite[j],s) < 52 ) KILLIT(i); j = nextj; } j = clipmove(&s->x,&s->y,&s->z,&s->sectnum, (((s->xvel*(sintable[(s->ang+512)&2047]))>>14)*TICSPERFRAME)<<11, (((s->xvel*(sintable[s->ang&2047]))>>14)*TICSPERFRAME)<<11, 24L,(4<<8),(4<<8),CLIPMASK1); if(j&49152) { if( (j&49152) == 32768 ) { j &= (MAXWALLS-1); k = getangle( wall[wall[j].point2].x-wall[j].x, wall[wall[j].point2].y-wall[j].y); s->ang = ((k<<1) - s->ang)&2047; } else if( (j&49152) == 49152 ) { j &= (MAXSPRITES-1); checkhitsprite(i,j); } } s->xvel --; if(s->xvel < 0) s->xvel = 0; if( s->picnum == STRIPEBALL ) { s->cstat = 257; s->cstat |= 4&s->xvel; s->cstat |= 8&s->xvel; } } else { p = findplayer(s,&x); if( x < 1596) { // if(s->pal == 12) { j = getincangle(ps[p].ang,getangle(s->x-ps[p].posx,s->y-ps[p].posy)); if( j > -64 && j < 64 && (sync[p].bits&(1<<29)) ) if(ps[p].toggle_key_flag == 1) { a = headspritestat[1]; while(a >= 0) { if(sprite[a].picnum == QUEBALL || sprite[a].picnum == STRIPEBALL) { j = getincangle(ps[p].ang,getangle(sprite[a].x-ps[p].posx,sprite[a].y-ps[p].posy)); if( j > -64 && j < 64 ) { findplayer(&sprite[a],&l); if(x > l) break; } } a = nextspritestat[a]; } if(a == -1) { if(s->pal == 12) s->xvel = 164; else s->xvel = 140; s->ang = ps[p].ang; ps[p].toggle_key_flag = 2; } } } } if( x < 512 && s->sectnum == ps[p].cursectnum ) { s->ang = getangle(s->x-ps[p].posx,s->y-ps[p].posy); s->xvel = 48; } } break; case FORCESPHERE: if(s->yvel == 0) { s->yvel = 1; for(l=512;l<(2048-512);l+= 128) for(j=0;j<2048;j += 128) { k = spawn(i,FORCESPHERE); sprite[k].cstat = 257+128; sprite[k].clipdist = 64; sprite[k].ang = j; sprite[k].zvel = sintable[l&2047]>>5; sprite[k].xvel = sintable[(l+512)&2047]>>9; sprite[k].owner = i; } } if(t[3] > 0) { if(s->zvel < 6144) s->zvel += 192; s->z += s->zvel; if(s->z > sector[sect].floorz) s->z = sector[sect].floorz; t[3]--; if(t[3] == 0) KILLIT(i); } else if(t[2] > 10) { j = headspritestat[5]; while(j >= 0) { if(sprite[j].owner == i && sprite[j].picnum == FORCESPHERE) hittype[j].temp_data[1] = 1+(TRAND&63); j = nextspritestat[j]; } t[3] = 64; } goto BOLT; case RECON: getglobalz(i); if (sector[s->sectnum].ceilingstat&1) s->shade += (sector[s->sectnum].ceilingshade-s->shade)>>1; else s->shade += (sector[s->sectnum].floorshade-s->shade)>>1; if( s->z < sector[sect].ceilingz+(32<<8) ) s->z = sector[sect].ceilingz+(32<<8); if( ud.multimode < 2 ) { if( actor_tog == 1) { s->cstat = (short)32768; goto BOLT; } else if(actor_tog == 2) s->cstat = 257; } IFHIT { if( s->extra < 0 && t[0] != -1 ) { t[0] = -1; s->extra = 0; } spritesound(RECO_PAIN,i); RANDOMSCRAP; } if(t[0] == -1) { s->z += 1024; t[2]++; if( (t[2]&3) == 0) spawn(i,EXPLOSION2); getglobalz(i); s->ang += 96; s->xvel = 128; j = ssp(i,CLIPMASK0); if(j != 1 || s->z > hittype[i].floorz) { for(l=0;l<16;l++) RANDOMSCRAP; spritesound(LASERTRIP_EXPLODE,i); spawn(i,PIGCOP); ps[myconnectindex].actors_killed++; KILLIT(i); } goto BOLT; } else { if( s->z > hittype[i].floorz-(48<<8) ) s->z = hittype[i].floorz-(48<<8); } p = findplayer(s,&x); j = s->owner; // 3 = findplayerz, 4 = shoot if( t[0] >= 4 ) { t[2]++; if( (t[2]&15) == 0 ) { a = s->ang; s->ang = hittype[i].tempang; spritesound(RECO_ATTACK,i); shoot(i,FIRELASER); s->ang = a; } if( t[2] > (26*3) || !cansee(s->x,s->y,s->z-(16<<8),s->sectnum, ps[p].posx,ps[p].posy,ps[p].posz,ps[p].cursectnum ) ) { t[0] = 0; t[2] = 0; } else hittype[i].tempang += getincangle(hittype[i].tempang,getangle(ps[p].posx-s->x,ps[p].posy-s->y))/3; } else if(t[0] == 2 || t[0] == 3) { t[3] = 0; if(s->xvel > 0) s->xvel -= 16; else s->xvel = 0; if(t[0] == 2) { l = ps[p].posz-s->z; if( klabs(l) < (48<<8) ) t[0] = 3; else s->z += ksgn(ps[p].posz-s->z)<<10; } else { t[2]++; if( t[2] > (26*3) || !cansee(s->x,s->y,s->z-(16<<8),s->sectnum, ps[p].posx,ps[p].posy,ps[p].posz,ps[p].cursectnum ) ) { t[0] = 1; t[2] = 0; } else if( (t[2]&15) == 0 ) { spritesound(RECO_ATTACK,i); shoot(i,FIRELASER); } } s->ang += getincangle(s->ang,getangle(ps[p].posx-s->x,ps[p].posy-s->y))>>2; } if( t[0] != 2 && t[0] != 3 ) { l = ldist(&sprite[j],s); if(l <= 1524) { a = s->ang; s->xvel >>= 1; } else a = getangle(sprite[j].x-s->x,sprite[j].y-s->y); if(t[0] == 1 || t[0] == 4) // Found a locator and going with it { l = dist(&sprite[j],s); if( l <= 1524 ) { if(t[0] == 1) t[0] = 0; else t[0] = 5; } else { // Control speed here if(l > 1524) { if( s->xvel < 256 ) s->xvel += 32; } else { if(s->xvel > 0) s->xvel -= 16; else s->xvel = 0; } } if(t[0] < 2) t[2]++; if( x < 6144 && t[0] < 2 && t[2] > (26*4) ) { t[0] = 2+(TRAND&2); t[2] = 0; hittype[i].tempang = s->ang; } } if(t[0] == 0 || t[0] == 5) { if(t[0] == 0) t[0] = 1; else t[0] = 4; j = s->owner = LocateTheLocator(s->hitag,-1); if(j == -1) { s->hitag = j = hittype[i].temp_data[5]; s->owner = LocateTheLocator(j,-1); j = s->owner; if(j == -1) KILLIT(i); } else s->hitag++; } t[3] = getincangle(s->ang,a); s->ang += t[3]>>3; if(s->z < sprite[j].z) s->z += 1024; else s->z -= 1024; } if(!isspritemakingsound(i,RECO_ROAM)) spritesound(RECO_ROAM,i); ssp(i,CLIPMASK0); goto BOLT; case OOZ: case OOZ2: getglobalz(i); j = (hittype[i].floorz-hittype[i].ceilingz)>>9; if(j > 255) j = 255; x = 25-(j>>1); if(x < 8) x = 8; else if(x > 48) x = 48; s->yrepeat = j; s->xrepeat = x; s->z = hittype[i].floorz; goto BOLT; case GREENSLIME: case GREENSLIME+1: case GREENSLIME+2: case GREENSLIME+3: case GREENSLIME+4: case GREENSLIME+5: case GREENSLIME+6: case GREENSLIME+7: // #ifndef VOLUMEONE if( ud.multimode < 2 ) { if( actor_tog == 1) { s->cstat = (short)32768; goto BOLT; } else if(actor_tog == 2) s->cstat = 257; } // #endif t[1]+=128; if(sector[sect].floorstat&1) KILLIT(i); p = findplayer(s,&x); if(x > 20480) { hittype[i].timetosleep++; if( hittype[i].timetosleep > SLEEPTIME ) { hittype[i].timetosleep = 0; changespritestat(i,2); goto BOLT; } } if(t[0] == -5) // FROZEN { t[3]++; if(t[3] > 280) { s->pal = 0; t[0] = 0; goto BOLT; } makeitfall(i); s->cstat = 257; s->picnum = GREENSLIME+2; s->extra = 1; s->pal = 1; IFHIT { if(j == FREEZEBLAST) goto BOLT; for(j=16; j >= 0 ;j--) { k = EGS(SECT,SX,SY,SZ,GLASSPIECES+(j%3),-32,36,36,TRAND&2047,32+(TRAND&63),1024-(TRAND&1023),i,5); sprite[k].pal = 1; } spritesound(GLASS_BREAKING,i); KILLIT(i); } else if(x < 1024 && ps[p].quick_kick == 0) { j = getincangle(ps[p].ang,getangle(SX-ps[p].posx,SY-ps[p].posy)); if( j > -128 && j < 128 ) ps[p].quick_kick = 14; } goto BOLT; } if(x < 1596) s->cstat = 0; else s->cstat = 257; if(t[0] == -4) //On the player { if( sprite[ps[p].i].extra < 1 ) { t[0] = 0; goto BOLT; } setsprite(i,s->x,s->y,s->z); s->ang = ps[p].ang; if( ( (sync[p].bits&4) || (ps[p].quick_kick > 0) ) && sprite[ps[p].i].extra > 0 ) if( ps[p].quick_kick > 0 || ( ps[p].curr_weapon != HANDREMOTE_WEAPON && ps[p].curr_weapon != HANDBOMB_WEAPON && ps[p].curr_weapon != TRIPBOMB_WEAPON && ps[p].ammo_amount[ps[p].curr_weapon] >= 0) ) { for(x=0;x<8;x++) { j = EGS(sect,s->x,s->y,s->z-(8<<8),SCRAP3+(TRAND&3),-8,48,48,TRAND&2047,(TRAND&63)+64,-(TRAND&4095)-(s->zvel>>2),i,5); sprite[j].pal = 6; } spritesound(SLIM_DYING,i); spritesound(SQUISHED,i); if( (TRAND&255) < 32 ) { j = spawn(i,BLOODPOOL); sprite[j].pal = 0; } ps[p].actors_killed ++; t[0] = -3; if(ps[p].somethingonplayer == i) ps[p].somethingonplayer = -1; KILLIT(i); } s->z = ps[p].posz+ps[p].pyoff-t[2]+(8<<8); s->z += (100-ps[p].horiz)<<4; if( t[2] > 512) t[2] -= 128; if( t[2] < 348) t[2] += 128; if(ps[p].newowner >= 0) { ps[p].newowner = -1; ps[p].posx = ps[p].oposx; ps[p].posy = ps[p].oposy; ps[p].posz = ps[p].oposz; ps[p].ang = ps[p].oang; updatesector(ps[p].posx,ps[p].posy,&ps[p].cursectnum); setpal(&ps[p]); j = headspritestat[1]; while(j >= 0) { if(sprite[j].picnum==CAMERA1) sprite[j].yvel = 0; j = nextspritestat[j]; } } if(t[3]>0) { short frames[] = {5,5,6,6,7,7,6,5}; s->picnum = GREENSLIME+frames[t[3]]; if( t[3] == 5 ) { sprite[ps[p].i].extra += -(5+(TRAND&3)); spritesound(SLIM_ATTACK,i); } if(t[3] < 7) t[3]++; else t[3] = 0; } else { s->picnum = GREENSLIME+5; if(rnd(32)) t[3] = 1; } s->xrepeat = 20+(sintable[t[1]&2047]>>13); s->yrepeat = 15+(sintable[t[1]&2047]>>13); s->x = ps[p].posx + (sintable[(ps[p].ang+512)&2047]>>7); s->y = ps[p].posy + (sintable[ps[p].ang&2047]>>7); goto BOLT; } else if(s->xvel < 64 && x < 768) { if(ps[p].somethingonplayer == -1) { ps[p].somethingonplayer = i; if(t[0] == 3 || t[0] == 2) //Falling downward t[2] = (12<<8); else t[2] = -(13<<8); //Climbing up duke t[0] = -4; } } IFHIT { spritesound(SLIM_DYING,i); ps[p].actors_killed ++; if(ps[p].somethingonplayer == i) ps[p].somethingonplayer = -1; if(j == FREEZEBLAST) { spritesound(SOMETHINGFROZE,i); t[0] = -5 ; t[3] = 0 ; goto BOLT; } if( (TRAND&255) < 32 ) { j = spawn(i,BLOODPOOL); sprite[j].pal = 0; } for(x=0;x<8;x++) { j = EGS(sect,s->x,s->y,s->z-(8<<8),SCRAP3+(TRAND&3),-8,48,48,TRAND&2047,(TRAND&63)+64,-(TRAND&4095)-(s->zvel>>2),i,5); sprite[j].pal = 6; } t[0] = -3; KILLIT(i); } // All weap if(t[0] == -1) //Shrinking down { makeitfall(i); s->cstat &= 65535-8; s->picnum = GREENSLIME+4; // if(s->yrepeat > 62) // guts(s,JIBS6,5,myconnectindex); if(s->xrepeat > 32) s->xrepeat -= TRAND&7; if(s->yrepeat > 16) s->yrepeat -= TRAND&7; else { s->xrepeat = 40; s->yrepeat = 16; t[5] = -1; t[0] = 0; } goto BOLT; } else if(t[0] != -2) getglobalz(i); if(t[0] == -2) //On top of somebody (an enemy) { makeitfall(i); sprite[t[5]].xvel = 0; l = sprite[t[5]].ang; s->z = sprite[t[5]].z; s->x = sprite[t[5]].x+(sintable[(l+512)&2047]>>11); s->y = sprite[t[5]].y+(sintable[l&2047]>>11); s->picnum = GREENSLIME+2+(global_random&1); if(s->yrepeat < 64) s->yrepeat+=2; else { if(s->xrepeat < 32) s->xrepeat += 4; else { t[0] = -1; x = ldist(s,&sprite[t[5]]); if(x < 768) { sprite[t[5]].xrepeat = 0; // JBF 20041129: a slimer eating another enemy really ought // to decrease the maximum kill count by one. // JBF 20051024: additionally, the enemy has to be alive for // the max enemy count to be decremented. if (sprite[t[5]].extra > 0) ps[myconnectindex].max_actors_killed--; } } } goto BOLT; } //Check randomly to see of there is an actor near if(rnd(32)) { j = headspritesect[sect]; while(j>=0) { switch(sprite[j].picnum) { case LIZTROOP: case LIZMAN: case PIGCOP: case NEWBEAST: if( ldist(s,&sprite[j]) < 768 && (klabs(s->z-sprite[j].z)<8192) ) //Gulp them { t[5] = j; t[0] = -2; t[1] = 0; goto BOLT; } } j = nextspritesect[j]; } } //Moving on the ground or ceiling if(t[0] == 0 || t[0] == 2) { s->picnum = GREENSLIME; if( (TRAND&511) == 0 ) spritesound(SLIM_ROAM,i); if(t[0]==2) { s->zvel = 0; s->cstat &= (65535-8); if( (sector[sect].ceilingstat&1) || (hittype[i].ceilingz+6144) < s->z) { s->z += 2048; t[0] = 3; goto BOLT; } } else { s->cstat |= 8; makeitfall(i); } if( everyothertime&1 ) ssp(i,CLIPMASK0); if(s->xvel > 96) { s->xvel -= 2; goto BOLT; } else { if(s->xvel < 32) s->xvel += 4; s->xvel = 64 - (sintable[(t[1]+512)&2047]>>9); s->ang += getincangle(s->ang, getangle(ps[p].posx-s->x,ps[p].posy-s->y))>>3; // TJR } s->xrepeat = 36 + (sintable[(t[1]+512)&2047]>>11); s->yrepeat = 16 + (sintable[t[1]&2047]>>13); if(rnd(4) && (sector[sect].ceilingstat&1) == 0 && klabs(hittype[i].floorz-hittype[i].ceilingz) < (192<<8) ) { s->zvel = 0; t[0]++; } } if(t[0]==1) { s->picnum = GREENSLIME; if(s->yrepeat < 40) s->yrepeat+=8; if(s->xrepeat > 8) s->xrepeat-=4; if(s->zvel > -(2048+1024)) s->zvel -= 348; s->z += s->zvel; if(s->z < hittype[i].ceilingz+4096) { s->z = hittype[i].ceilingz+4096; s->xvel = 0; t[0] = 2; } } if(t[0]==3) { s->picnum = GREENSLIME+1; makeitfall(i); if(s->z > hittype[i].floorz-(8<<8)) { s->yrepeat-=4; s->xrepeat+=2; } else { if(s->yrepeat < (40-4)) s->yrepeat+=8; if(s->xrepeat > 8) s->xrepeat-=4; } if(s->z > hittype[i].floorz-2048) { s->z = hittype[i].floorz-2048; t[0] = 0; s->xvel = 0; } } goto BOLT; case BOUNCEMINE: case MORTER: j = spawn(i, (PLUTOPAK ? FRAMEEFFECT1 : FRAMEEFFECT1_13) ); hittype[j].temp_data[0] = 3; // fall through case HEAVYHBOMB: if( (s->cstat&32768) ) { t[2]--; if(t[2] <= 0) { spritesound(TELEPORTER,i); spawn(i,TRANSPORTERSTAR); s->cstat = 257; } goto BOLT; } p = findplayer(s,&x); if( x < 1220 ) s->cstat &= ~257; else s->cstat |= 257; if(t[3] == 0 ) { j = ifhitbyweapon(i); if(j >= 0) { t[3] = 1; t[4] = 0; l = 0; s->xvel = 0; goto DETONATEB; } } if( s->picnum != BOUNCEMINE ) { makeitfall(i); if( sector[sect].lotag != 1 && s->z >= hittype[i].floorz-(FOURSLEIGHT) && s->yvel < 3 ) { if( s->yvel > 0 || (s->yvel == 0 && hittype[i].floorz == sector[sect].floorz )) spritesound(PIPEBOMB_BOUNCE,i); s->zvel = -((4-s->yvel)<<8); if(sector[s->sectnum].lotag== 2) s->zvel >>= 2; s->yvel++; } if( s->z < hittype[i].ceilingz ) // && sector[sect].lotag != 2 ) { s->z = hittype[i].ceilingz+(3<<8); s->zvel = 0; } } j = movesprite(i, (s->xvel*(sintable[(s->ang+512)&2047]))>>14, (s->xvel*(sintable[s->ang&2047]))>>14, s->zvel,CLIPMASK0); if(sector[SECT].lotag == 1 && s->zvel == 0) { s->z += (32<<8); if(t[5] == 0) { t[5] = 1; spawn(i,WATERSPLASH2); } } else t[5] = 0; if(t[3] == 0 && ( s->picnum == BOUNCEMINE || s->picnum == MORTER ) && (j || x < 844) ) { t[3] = 1; t[4] = 0; l = 0; s->xvel = 0; goto DETONATEB; } if(sprite[s->owner].picnum == APLAYER) l = sprite[s->owner].yvel; else l = -1; if(s->xvel > 0) { s->xvel -= 5; if(sector[sect].lotag == 2) s->xvel -= 10; if(s->xvel < 0) s->xvel = 0; if(s->xvel&8) s->cstat ^= 4; } if( (j&49152) == 32768 ) { j &= (MAXWALLS-1); checkhitwall(i,j,s->x,s->y,s->z,s->picnum); k = getangle( wall[wall[j].point2].x-wall[j].x, wall[wall[j].point2].y-wall[j].y); s->ang = ((k<<1) - s->ang)&2047; s->xvel >>= 1; } DETONATEB: namBoom = 0; if( ( l >= 0 && ps[l].hbomb_on == 0 ) || t[3] == 1) namBoom=1; if (NAM) { if( s->picnum == HEAVYHBOMB) { s->extra--; // FIXME: bug if(s->extra <= 0) namBoom=1; } } if (namBoom) { t[4]++; if(t[4] == 2) { x = s->extra; m = 0; switch(s->picnum) { case HEAVYHBOMB: m = pipebombblastradius;break; case MORTER: m = morterblastradius;break; case BOUNCEMINE: m = bouncemineblastradius;break; } hitradius( i, m,x>>2,x>>1,x-(x>>2),x); spawn(i,EXPLOSION2); if( s->zvel == 0 ) spawn(i,EXPLOSION2BOT); spritesound(PIPEBOMB_EXPLODE,i); for(x=0;x<8;x++) RANDOMSCRAP; } if(s->yrepeat) { s->yrepeat = 0; goto BOLT; } if(t[4] > 20) { if(s->owner != i || ud.respawn_items == 0) { KILLIT(i); } else { t[2] = respawnitemtime; spawn(i,RESPAWNMARKERRED); s->cstat = (short) 32768; s->yrepeat = 9; goto BOLT; } } } else if(s->picnum == HEAVYHBOMB && x < 788 && t[0] > 7 && s->xvel == 0) if( cansee(s->x,s->y,s->z-(8<<8),s->sectnum,ps[p].posx,ps[p].posy,ps[p].posz,ps[p].cursectnum) ) if(ps[p].ammo_amount[HANDBOMB_WEAPON] < max_ammo_amount[HANDBOMB_WEAPON] ) { if(ud.coop >= 1 && s->owner == i) { for(j=0;j<ps[p].weapreccnt;j++) if(ps[p].weaprecs[j] == s->picnum) goto BOLT; if(ps[p].weapreccnt < 255) ps[p].weaprecs[ps[p].weapreccnt++] = s->picnum; } addammo(HANDBOMB_WEAPON,&ps[p],1); spritesound(DUKE_GET,ps[p].i); if( ps[p].gotweapon[HANDBOMB_WEAPON] == 0 || s->owner == ps[p].i ) addweapon(&ps[p],HANDBOMB_WEAPON); if( sprite[s->owner].picnum != APLAYER ) { ps[p].pals[0] = 0; ps[p].pals[1] = 32; ps[p].pals[2] = 0; ps[p].pals_time = 32; } if( s->owner != i || ud.respawn_items == 0 ) { if(s->owner == i && ud.coop >= 1) goto BOLT; KILLIT(i); } else { t[2] = respawnitemtime; spawn(i,RESPAWNMARKERRED); s->cstat = (short) 32768; } } if(t[0] < 8) t[0]++; goto BOLT; case REACTORBURNT: case REACTOR2BURNT: goto BOLT; case REACTOR: case REACTOR2: if( t[4] == 1 ) { j = headspritesect[sect]; while(j >= 0) { switch(sprite[j].picnum) { case SECTOREFFECTOR: if(sprite[j].lotag == 1) { sprite[j].lotag = (short) 65535; sprite[j].hitag = (short) 65535; } break; case REACTOR: sprite[j].picnum = REACTORBURNT; break; case REACTOR2: sprite[j].picnum = REACTOR2BURNT; break; case REACTORSPARK: case REACTOR2SPARK: sprite[j].cstat = (short) 32768; break; } j = nextspritesect[j]; } goto BOLT; } if(t[1] >= 20) { t[4] = 1; goto BOLT; } p = findplayer(s,&x); t[2]++; if( t[2] == 4 ) t[2]=0; if( x < 4096 ) { if( (TRAND&255) < 16 ) { if(!isspritemakingsound(ps[p].i, DUKE_LONGTERM_PAIN)) spritesound(DUKE_LONGTERM_PAIN,ps[p].i); spritesound(SHORT_CIRCUIT,i); sprite[ps[p].i].extra --; ps[p].pals_time = 32; ps[p].pals[0] = 32; ps[p].pals[1] = 0; ps[p].pals[2] = 0; } t[0] += 128; if( t[3] == 0 ) t[3] = 1; } else t[3] = 0; if( t[1] ) { t[1]++; t[4] = s->z; s->z = sector[sect].floorz-(TRAND%(sector[sect].floorz-sector[sect].ceilingz)); switch( t[1] ) { case 3: //Turn on all of those flashing sectoreffector. hitradius( i, 4096, impact_damage<<2, impact_damage<<2, impact_damage<<2, impact_damage<<2 ); /* j = headspritestat[3]; while(j>=0) { if( sprite[j].lotag == 3 ) hittype[j].temp_data[4]=1; else if(sprite[j].lotag == 12) { hittype[j].temp_data[4] = 1; sprite[j].lotag = 3; sprite[j].owner = 0; hittype[j].temp_data[0] = s->shade; } j = nextspritestat[j]; } */ j = headspritestat[6]; while(j >= 0) { if(sprite[j].picnum == MASTERSWITCH) if(sprite[j].hitag == s->hitag) if(sprite[j].yvel == 0) sprite[j].yvel = 1; j = nextspritestat[j]; } break; case 4: case 7: case 10: case 15: j = headspritesect[sect]; while(j >= 0) { l = nextspritesect[j]; if(j != i) { deletesprite(j); break; } j = l; } break; } for(x=0;x<16;x++) RANDOMSCRAP; s->z = t[4]; t[4] = 0; } else { IFHIT { for(x=0;x<32;x++) RANDOMSCRAP; if(s->extra < 0) t[1] = 1; } } goto BOLT; case CAMERA1: if( t[0] == 0 ) { t[1]+=8; if(camerashitable) { IFHIT { t[0] = 1; // static s->cstat = (short)32768; for(x=0;x<5;x++) RANDOMSCRAP; goto BOLT; } } if(s->hitag > 0) { if(t[1]<s->hitag) s->ang+=8; else if(t[1]<(s->hitag*3)) s->ang-=8; else if(t[1] < (s->hitag<<2) ) s->ang+=8; else { t[1]=8; s->ang+=16; } } } goto BOLT; } // #ifndef VOLOMEONE if( ud.multimode < 2 && badguy(s) ) { if( actor_tog == 1) { s->cstat = (short)32768; goto BOLT; } else if(actor_tog == 2) s->cstat = 257; } // #endif p = findplayer(s,&x); execute(i,p,x); BOLT: i = nexti; } } void moveexplosions(void) // STATNUM 5 { short i, j, nexti, sect, p; int l, x, *t; spritetype *s; i = headspritestat[5]; while(i >= 0) { nexti = nextspritestat[i]; t = &hittype[i].temp_data[0]; s = &sprite[i]; sect = s->sectnum; if( sect < 0 || s->xrepeat == 0 ) KILLIT(i); hittype[i].bposx = s->x; hittype[i].bposy = s->y; hittype[i].bposz = s->z; switch(s->picnum) { case NEON1: case NEON2: case NEON3: case NEON4: case NEON5: case NEON6: if( (global_random/(s->lotag+1)&31) > 4) s->shade = -127; else s->shade = 127; goto BOLT; case BLOODSPLAT1: case BLOODSPLAT2: case BLOODSPLAT3: case BLOODSPLAT4: if( t[0] == 7*26 ) goto BOLT; s->z += 16+(TRAND&15); t[0]++; if( (t[0]%9) == 0 ) s->yrepeat++; goto BOLT; case NUKEBUTTON: case NUKEBUTTON+1: case NUKEBUTTON+2: case NUKEBUTTON+3: if(t[0]) { t[0]++; if(t[0] == 8) s->picnum = NUKEBUTTON+1; else if(t[0] == 16) { s->picnum = NUKEBUTTON+2; ps[sprite[s->owner].yvel].fist_incs = 1; } if( ps[sprite[s->owner].yvel].fist_incs == 26 ) s->picnum = NUKEBUTTON+3; } goto BOLT; case FORCESPHERE: l = s->xrepeat; if(t[1] > 0) { t[1]--; if(t[1] == 0) { KILLIT(i); } } if(hittype[s->owner].temp_data[1] == 0) { if(t[0] < 64) { t[0]++; l += 3; } } else if(t[0] > 64) { t[0]--; l -= 3; } s->x = sprite[s->owner].x; s->y = sprite[s->owner].y; s->z = sprite[s->owner].z; s->ang += hittype[s->owner].temp_data[0]; if(l > 64) l = 64; else if(l < 1) l = 1; s->xrepeat = l; s->yrepeat = l; s->shade = (l>>1)-48; for(j=t[0];j > 0;j--) ssp(i,CLIPMASK0); goto BOLT; case WATERSPLASH2: t[0]++; if(t[0] == 1 ) { if(sector[sect].lotag != 1 && sector[sect].lotag != 2) KILLIT(i); /* else { l = getflorzofslope(sect,s->x,s->y)-s->z; if( l > (16<<8) ) KILLIT(i); } else */ if (!issoundplaying(ITEM_SPLASH, 1)) spritesound(ITEM_SPLASH,i); } if(t[0] == 3) { t[0] = 0; t[1]++; } if(t[1] == 5) deletesprite(i); goto BOLT; case FRAMEEFFECT1_13: if (PLUTOPAK) goto BOLT; // JBF: ideally this should never happen... // fall through case FRAMEEFFECT1: if(s->owner >= 0) { t[0]++; if( t[0] > 7 ) { KILLIT(i); } else if( t[0] > 4 ) s->cstat |= 512+2; else if( t[0] > 2 ) s->cstat |= 2; s->xoffset = sprite[s->owner].xoffset; s->yoffset = sprite[s->owner].yoffset; } goto BOLT; case INNERJAW: case INNERJAW+1: p = findplayer(s,&x); if(x < 512) { ps[p].pals_time = 32; ps[p].pals[0] = 32; ps[p].pals[1] = 0; ps[p].pals[2] = 0; sprite[ps[p].i].extra -= 4; } // fall through case FIRELASER: if(s->extra != 999) s->extra = 999; else KILLIT(i); break; case TONGUE: KILLIT(i); case MONEY+1: case MAIL+1: case PAPER+1: hittype[i].floorz = s->z = getflorzofslope(s->sectnum,s->x,s->y); break; case MONEY: case MAIL: case PAPER: s->xvel = (TRAND&7)+(sintable[T1&2047]>>9); T1 += (TRAND&63); if( (T1&2047) > 512 && (T1&2047) < 1596) { if(sector[sect].lotag == 2) { if(s->zvel < 64) s->zvel += (gc>>5)+(TRAND&7); } else if(s->zvel < 144) s->zvel += (gc>>5)+(TRAND&7); } ssp(i,CLIPMASK0); if( (TRAND&3) == 0 ) setsprite(i,s->x,s->y,s->z); if(s->sectnum == -1) KILLIT(i); l = getflorzofslope(s->sectnum,s->x,s->y); if( s->z > l ) { s->z = l; insertspriteq(i); PN ++; j = headspritestat[5]; while(j >= 0) { if(sprite[j].picnum == BLOODPOOL) if(ldist(s,&sprite[j]) < 348) { s->pal = 2; break; } j = nextspritestat[j]; } } break; case JIBS1: case JIBS2: case JIBS3: case JIBS4: case JIBS5: case JIBS6: case HEADJIB1: case ARMJIB1: case LEGJIB1: case LIZMANHEAD1: case LIZMANARM1: case LIZMANLEG1: case DUKETORSO: case DUKEGUN: case DUKELEG: if(s->xvel > 0) s->xvel--; else s->xvel = 0; if( t[5] < 30*10 ) t[5]++; else { KILLIT(i); } if(s->zvel > 1024 && s->zvel < 1280) { setsprite(i,s->x,s->y,s->z); sect = s->sectnum; } l = getflorzofslope(sect,s->x,s->y); x = getceilzofslope(sect,s->x,s->y); if(x == l || sect < 0 || sect >= MAXSECTORS) KILLIT(i); if( s->z < l-(2<<8) ) { if(t[1] < 2) t[1]++; else if(sector[sect].lotag != 2) { t[1] = 0; if( s->picnum == DUKELEG || s->picnum == DUKETORSO || s->picnum == DUKEGUN ) { if(t[0] > 6) t[0] = 0; else t[0]++; } else { if(t[0] > 2) t[0] = 0; else t[0]++; } } if(s->zvel < 6144) { if(sector[sect].lotag == 2) { if(s->zvel < 1024) s->zvel += 48; else s->zvel = 1024; } else s->zvel += gc-50; } s->x += (s->xvel*sintable[(s->ang+512)&2047])>>14; s->y += (s->xvel*sintable[s->ang&2047])>>14; s->z += s->zvel; } else { if(t[2] == 0) { if( s->sectnum == -1) { KILLIT(i); } if( (sector[s->sectnum].floorstat&2) ) { KILLIT(i); } t[2]++; } l = getflorzofslope(s->sectnum,s->x,s->y); s->z = l-(2<<8); s->xvel = 0; if(s->picnum == JIBS6) { t[1]++; if( (t[1]&3) == 0 && t[0] < 7) t[0]++; if(t[1] > 20) KILLIT(i); } else { s->picnum = JIBS6; t[0] = 0; t[1] = 0; } } goto BOLT; case BLOODPOOL: case PUKE: if(t[0] == 0) { t[0] = 1; if(sector[sect].floorstat&2) { KILLIT(i); } else insertspriteq(i); } makeitfall(i); p = findplayer(s,&x); s->z = hittype[i].floorz-(FOURSLEIGHT); if(t[2] < 32) { t[2]++; if(hittype[i].picnum == TIRE) { if(s->xrepeat < 64 && s->yrepeat < 64) { s->xrepeat += TRAND&3; s->yrepeat += TRAND&3; } } else { if(s->xrepeat < 32 && s->yrepeat < 32) { s->xrepeat += TRAND&3; s->yrepeat += TRAND&3; } } } if(x < 844 && s->xrepeat > 6 && s->yrepeat > 6) { if( s->pal == 0 && (TRAND&255) < 16 && s->picnum != PUKE) { if(ps[p].boot_amount > 0) ps[p].boot_amount--; else { if(!isspritemakingsound(ps[p].i,DUKE_LONGTERM_PAIN)) spritesound(DUKE_LONGTERM_PAIN,ps[p].i); sprite[ps[p].i].extra --; ps[p].pals_time = 32; ps[p].pals[0] = 16; ps[p].pals[1] = 0; ps[p].pals[2] = 0; } } if(t[1] == 1) goto BOLT; t[1] = 1; if(hittype[i].picnum == TIRE) ps[p].footprintcount = 10; else ps[p].footprintcount = 3; ps[p].footprintpal = s->pal; ps[p].footprintshade = s->shade; if(t[2] == 32) { s->xrepeat -= 6; s->yrepeat -= 6; } } else t[1] = 0; goto BOLT; case BURNING: case BURNING2: case FECES: case WATERBUBBLE: case SMALLSMOKE: case EXPLOSION2: case SHRINKEREXPLOSION: case EXPLOSION2BOT: case BLOOD: case LASERSITE: case FORCERIPPLE: case TRANSPORTERSTAR: case TRANSPORTERBEAM: p = findplayer(s,&x); execute(i,p,x); goto BOLT; case SHELL: case SHOTGUNSHELL: ssp(i,CLIPMASK0); if(sect < 0 || ( sector[sect].floorz+(24<<8) ) < s->z ) KILLIT(i); if(sector[sect].lotag == 2) { t[1]++; if(t[1] > 8) { t[1] = 0; t[0]++; t[0] &= 3; } if(s->zvel < 128) s->zvel += (gc/13); // 8 else s->zvel -= 64; if(s->xvel > 0) s->xvel -= 4; else s->xvel = 0; } else { t[1]++; if(t[1] > 3) { t[1] = 0; t[0]++; t[0] &= 3; } if(s->zvel < 512) s->zvel += (gc/3); // 52; if(s->xvel > 0) s->xvel --; else KILLIT(i); } goto BOLT; case GLASSPIECES: case GLASSPIECES+1: case GLASSPIECES+2: makeitfall(i); if(s->zvel > 4096) s->zvel = 4096; if(sect < 0) KILLIT(i); if( s->z == hittype[i].floorz-(FOURSLEIGHT) && t[0] < 3) { s->zvel = -((3-t[0])<<8)-(TRAND&511); if(sector[sect].lotag == 2) s->zvel >>= 1; s->xrepeat >>= 1; s->yrepeat >>= 1; if( rnd(96) ) setsprite(i,s->x,s->y,s->z); t[0]++;//Number of bounces } else if( t[0] == 3 ) KILLIT(i); if(s->xvel > 0) { s->xvel -= 2; s->cstat = ((s->xvel&3)<<2); } else s->xvel = 0; ssp(i,CLIPMASK0); goto BOLT; } IFWITHIN(SCRAP6,SCRAP5+3) { if(s->xvel > 0) s->xvel--; else s->xvel = 0; if(s->zvel > 1024 && s->zvel < 1280) { setsprite(i,s->x,s->y,s->z); sect = s->sectnum; } if( s->z < sector[sect].floorz-(2<<8) ) { if(t[1] < 1) t[1]++; else { t[1] = 0; if(s->picnum < SCRAP6+8) { if(t[0] > 6) t[0] = 0; else t[0]++; } else { if(t[0] > 2) t[0] = 0; else t[0]++; } } if(s->zvel < 4096) s->zvel += gc-50; s->x += (s->xvel*sintable[(s->ang+512)&2047])>>14; s->y += (s->xvel*sintable[s->ang&2047])>>14; s->z += s->zvel; } else { if(s->picnum == SCRAP1 && s->yvel > 0) { j = spawn(i,s->yvel); setsprite(j,s->x,s->y,s->z); getglobalz(j); sprite[j].hitag = sprite[j].lotag = 0; } KILLIT(i); } goto BOLT; } BOLT: i = nexti; } } void moveeffectors(void) //STATNUM 3 { int q=0, l, m, x, st, j, *t; short i, k, nexti, nextk, p, sh, nextj; spritetype *s; sectortype *sc; walltype *wal; fricxv = fricyv = 0; i = headspritestat[3]; while(i >= 0) { nexti = nextspritestat[i]; s = &sprite[i]; sc = &sector[s->sectnum]; st = s->lotag; sh = s->hitag; t = &hittype[i].temp_data[0]; switch(st) { case 0: { int zchange = 0; zchange = 0; j = s->owner; if( sprite[j].lotag == (short) 65535 ) KILLIT(i); q = sc->extra>>3; l = 0; if(sc->lotag == 30) { q >>= 2; if( sprite[i].extra == 1 ) { if(hittype[i].tempang < 256) { hittype[i].tempang += 4; if(hittype[i].tempang >= 256) callsound(s->sectnum,i); if(s->clipdist) l = 1; else l = -1; } else hittype[i].tempang = 256; if( sc->floorz > s->z ) //z's are touching { sc->floorz -= 512; zchange = -512; if( sc->floorz < s->z ) sc->floorz = s->z; } else if( sc->floorz < s->z ) //z's are touching { sc->floorz += 512; zchange = 512; if( sc->floorz > s->z ) sc->floorz = s->z; } } else if(sprite[i].extra == 3) { if(hittype[i].tempang > 0) { hittype[i].tempang -= 4; if(hittype[i].tempang <= 0) callsound(s->sectnum,i); if( s->clipdist ) l = -1; else l = 1; } else hittype[i].tempang = 0; if( sc->floorz > T4 ) //z's are touching { sc->floorz -= 512; zchange = -512; if( sc->floorz < T4 ) sc->floorz = T4; } else if( sc->floorz < T4 ) //z's are touching { sc->floorz += 512; zchange = 512; if( sc->floorz > T4 ) sc->floorz = T4; } } s->ang += (l*q); t[2] += (l*q); } else { if( hittype[j].temp_data[0] == 0 ) break; if( hittype[j].temp_data[0] == 2 ) KILLIT(i); if( sprite[j].ang > 1024 ) l = -1; else l = 1; if( t[3] == 0 ) t[3] = ldist(s,&sprite[j]); s->xvel = t[3]; s->x = sprite[j].x; s->y = sprite[j].y; s->ang += (l*q); t[2] += (l*q); } if( l && (sc->floorstat&64) ) { for(p=connecthead;p>=0;p=connectpoint2[p]) { if( ps[p].cursectnum == s->sectnum && ps[p].on_ground == 1) { ps[p].ang += (l*q); ps[p].ang &= 2047; ps[p].posz += zchange; rotatepoint( sprite[j].x,sprite[j].y, ps[p].posx,ps[p].posy,(q*l), &m,&x); ps[p].bobposx += m-ps[p].posx; ps[p].bobposy += x-ps[p].posy; ps[p].posx = m; ps[p].posy = x; if(sprite[ps[p].i].extra <= 0) { sprite[ps[p].i].x = m; sprite[ps[p].i].y = x; } } } p = headspritesect[s->sectnum]; while(p >= 0) { if(sprite[p].statnum != 3 && sprite[p].statnum != 4) if( sprite[p].picnum != LASERLINE ) { if(sprite[p].picnum == APLAYER && sprite[p].owner >= 0) { p = nextspritesect[p]; continue; } sprite[p].ang += (l*q); sprite[p].ang &= 2047; sprite[p].z += zchange; rotatepoint(sprite[j].x,sprite[j].y, sprite[p].x,sprite[p].y,(q*l), &sprite[p].x,&sprite[p].y); } p = nextspritesect[p]; } } ms(i); } break; case 1: //Nothing for now used as the pivot if(s->owner == -1) //Init { s->owner = i; j = headspritestat[3]; while(j >= 0) { if( sprite[j].lotag == 19 && sprite[j].hitag == sh ) { t[0] = 0; break; } j = nextspritestat[j]; } } break; case 6: k = sc->extra; if(t[4] > 0) { t[4]--; if( t[4] >= (k-(k>>3)) ) s->xvel -= (k>>5); if( t[4] > ((k>>1)-1) && t[4] < (k-(k>>3)) ) s->xvel = 0; if( t[4] < (k>>1) ) s->xvel += (k>>5); if( t[4] < ((k>>1)-(k>>3)) ) { t[4] = 0; s->xvel = k; } } else s->xvel = k; j = headspritestat[3]; while( j >= 0) { if( (sprite[j].lotag == 14) && (sh == sprite[j].hitag) && (hittype[j].temp_data[0] == t[0]) ) { sprite[j].xvel = s->xvel; // if( t[4] == 1 ) { if(hittype[j].temp_data[5] == 0) hittype[j].temp_data[5] = dist(&sprite[j],s); x = ksgn( dist(&sprite[j],s)-hittype[j].temp_data[5] ); if(sprite[j].extra) x = -x; s->xvel += x; } hittype[j].temp_data[4] = t[4]; } j = nextspritestat[j]; } x = 0; // fall through case 14: if(s->owner==-1) s->owner = LocateTheLocator((short)t[3],(short)t[0]); if(s->owner == -1) { Bsprintf(buf,"Could not find any locators for SE# 6 and 14 with a hitag of %d.\n",t[3]); gameexit(buf); } j = ldist(&sprite[s->owner],s); if( j < 1024L ) { if(st==6) if(sprite[s->owner].hitag&1) t[4]=sc->extra; //Slow it down t[3]++; s->owner = LocateTheLocator(t[3],t[0]); if(s->owner==-1) { t[3]=0; s->owner = LocateTheLocator(0,t[0]); } } if(s->xvel) { x = getangle(sprite[s->owner].x-s->x,sprite[s->owner].y-s->y); q = getincangle(s->ang,x)>>3; t[2] += q; s->ang += q; if(s->xvel == sc->extra ) { if( (sc->floorstat&1) == 0 && (sc->ceilingstat&1) == 0 ) { if( !issoundplaying(hittype[i].lastvx, 1) ) spritesound(hittype[i].lastvx,i); } else if( ud.monsters_off == 0 && sc->floorpal == 0 && (sc->floorstat&1) && rnd(8) ) { p = findplayer(s,&x); if(x < 20480) { j = s->ang; s->ang = getangle(s->x-ps[p].posx,s->y-ps[p].posy); shoot(i,RPG); s->ang = j; } } } if(s->xvel <= 64 && (sc->floorstat&1) == 0 && (sc->ceilingstat&1) == 0 ) stopspritesound(hittype[i].lastvx,i); if( (sc->floorz-sc->ceilingz) < (108<<8) ) { if(ud.clipping == 0 && s->xvel >= 192) for(p=connecthead;p>=0;p=connectpoint2[p]) if(sprite[ps[p].i].extra > 0) { k = ps[p].cursectnum; updatesector(ps[p].posx,ps[p].posy,&k); if( ( k == -1 && ud.clipping == 0 ) || ( k == s->sectnum && ps[p].cursectnum != s->sectnum ) ) { ps[p].posx = s->x; ps[p].posy = s->y; ps[p].cursectnum = s->sectnum; setsprite(ps[p].i,s->x,s->y,s->z); quickkill(&ps[p]); } } } m = (s->xvel*sintable[(s->ang+512)&2047])>>14; x = (s->xvel*sintable[s->ang&2047])>>14; for(p = connecthead;p >= 0;p=connectpoint2[p]) if(sector[ps[p].cursectnum].lotag != 2) { if(po[p].os == s->sectnum) { po[p].ox += m; po[p].oy += x; } if(s->sectnum == sprite[ps[p].i].sectnum) { rotatepoint(s->x,s->y,ps[p].posx,ps[p].posy,q,&ps[p].posx,&ps[p].posy); ps[p].posx += m; ps[p].posy += x; ps[p].bobposx += m; ps[p].bobposy += x; ps[p].ang += q; if(numplayers > 1) { ps[p].oposx = ps[p].posx; ps[p].oposy = ps[p].posy; } if( sprite[ps[p].i].extra <= 0 ) { sprite[ps[p].i].x = ps[p].posx; sprite[ps[p].i].y = ps[p].posy; } } } j = headspritesect[s->sectnum]; while(j >= 0) { if (sprite[j].statnum != 10 && sector[sprite[j].sectnum].lotag != 2 && sprite[j].picnum != SECTOREFFECTOR && sprite[j].picnum != LOCATORS ) { rotatepoint(s->x,s->y, sprite[j].x,sprite[j].y,q, &sprite[j].x,&sprite[j].y); sprite[j].x+= m; sprite[j].y+= x; sprite[j].ang+=q; if(numplayers > 1) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; } } j = nextspritesect[j]; } ms(i); setsprite(i,s->x,s->y,s->z); if( (sc->floorz-sc->ceilingz) < (108<<8) ) { if(ud.clipping == 0 && s->xvel >= 192) for(p=connecthead;p>=0;p=connectpoint2[p]) if(sprite[ps[p].i].extra > 0) { k = ps[p].cursectnum; updatesector(ps[p].posx,ps[p].posy,&k); if( ( k == -1 && ud.clipping == 0 ) || ( k == s->sectnum && ps[p].cursectnum != s->sectnum ) ) { ps[p].oposx = ps[p].posx = s->x; ps[p].oposy = ps[p].posy = s->y; ps[p].cursectnum = s->sectnum; setsprite(ps[p].i,s->x,s->y,s->z); quickkill(&ps[p]); } } j = headspritesect[sprite[OW].sectnum]; while(j >= 0) { l = nextspritesect[j]; if (sprite[j].statnum == 1 && badguy(&sprite[j]) && sprite[j].picnum != SECTOREFFECTOR && sprite[j].picnum != LOCATORS ) { k = sprite[j].sectnum; updatesector(sprite[j].x,sprite[j].y,&k); if( sprite[j].extra >= 0 && k == s->sectnum ) { gutsdir(&sprite[j],JIBS6,72,myconnectindex); spritesound(SQUISHED,i); deletesprite(j); } } j = l; } } } break; case 30: if(s->owner == -1) { t[3] = !t[3]; s->owner = LocateTheLocator(t[3],t[0]); } else { if(t[4] == 1) // Starting to go { if( ldist( &sprite[s->owner],s ) < (2048-128) ) t[4] = 2; else { if(s->xvel == 0) operateactivators(s->hitag+(!t[3]),-1); if(s->xvel < 256) s->xvel += 16; } } if(t[4] == 2) { l = FindDistance2D(sprite[s->owner].x-s->x,sprite[s->owner].y-s->y); if(l <= 128) s->xvel = 0; if( s->xvel > 0 ) s->xvel -= 16; else { s->xvel = 0; operateactivators(s->hitag+(short)t[3],-1); s->owner = -1; s->ang += 1024; t[4] = 0; operateforcefields(i,s->hitag); j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum != SECTOREFFECTOR && sprite[j].picnum != LOCATORS ) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; } j = nextspritesect[j]; } } } } if(s->xvel) { l = (s->xvel*sintable[(s->ang+512)&2047])>>14; x = (s->xvel*sintable[s->ang&2047])>>14; if( (sc->floorz-sc->ceilingz) < (108<<8) ) if(ud.clipping == 0) for(p=connecthead;p>=0;p=connectpoint2[p]) if(sprite[ps[p].i].extra > 0) { k = ps[p].cursectnum; updatesector(ps[p].posx,ps[p].posy,&k); if( ( k == -1 && ud.clipping == 0 ) || ( k == s->sectnum && ps[p].cursectnum != s->sectnum ) ) { ps[p].posx = s->x; ps[p].posy = s->y; ps[p].cursectnum = s->sectnum; setsprite(ps[p].i,s->x,s->y,s->z); quickkill(&ps[p]); } } for(p = connecthead;p >= 0;p = connectpoint2[p]) { if( sprite[ps[p].i].sectnum == s->sectnum ) { ps[p].posx += l; ps[p].posy += x; if(numplayers > 1) { ps[p].oposx = ps[p].posx; ps[p].oposy = ps[p].posy; } ps[p].bobposx += l; ps[p].bobposy += x; } if( po[p].os == s->sectnum ) { po[p].ox += l; po[p].oy += x; } } j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum != SECTOREFFECTOR && sprite[j].picnum != LOCATORS ) { if(numplayers < 2) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; } sprite[j].x += l; sprite[j].y += x; if(numplayers > 1) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; } } j = nextspritesect[j]; } ms(i); setsprite(i,s->x,s->y,s->z); if( (sc->floorz-sc->ceilingz) < (108<<8) ) { if(ud.clipping == 0) for(p=connecthead;p>=0;p=connectpoint2[p]) if(sprite[ps[p].i].extra > 0) { k = ps[p].cursectnum; updatesector(ps[p].posx,ps[p].posy,&k); if( ( k == -1 && ud.clipping == 0 ) || ( k == s->sectnum && ps[p].cursectnum != s->sectnum ) ) { ps[p].posx = s->x; ps[p].posy = s->y; ps[p].oposx = ps[p].posx; ps[p].oposy = ps[p].posy; ps[p].cursectnum = s->sectnum; setsprite(ps[p].i,s->x,s->y,s->z); quickkill(&ps[p]); } } j = headspritesect[sprite[OW].sectnum]; while(j >= 0) { l = nextspritesect[j]; if (sprite[j].statnum == 1 && badguy(&sprite[j]) && sprite[j].picnum != SECTOREFFECTOR && sprite[j].picnum != LOCATORS ) { // if(sprite[j].sectnum != s->sectnum) { k = sprite[j].sectnum; updatesector(sprite[j].x,sprite[j].y,&k); if( sprite[j].extra >= 0 && k == s->sectnum ) { gutsdir(&sprite[j],JIBS6,24,myconnectindex); spritesound(SQUISHED,j); deletesprite(j); } } } j = l; } } } break; case 2://Quakes if(t[4] > 0 && t[0] == 0 ) { if( t[4] < sh ) t[4]++; else t[0] = 1; } if(t[0] > 0) { t[0]++; s->xvel = 3; if(t[0] > 96) { t[0] = -1; //Stop the quake t[4] = -1; KILLIT(i); } else { if( (t[0]&31) == 8 ) { earthquaketime = 48; spritesound(EARTHQUAKE,ps[screenpeek].i); } if( klabs( sc->floorheinum-t[5] ) < 8 ) sc->floorheinum = t[5]; else sc->floorheinum += ( ksgn(t[5]-sc->floorheinum)<<4 ); } m = (s->xvel*sintable[(s->ang+512)&2047])>>14; x = (s->xvel*sintable[s->ang&2047])>>14; for(p=connecthead;p>=0;p=connectpoint2[p]) if(ps[p].cursectnum == s->sectnum && ps[p].on_ground) { ps[p].posx += m; ps[p].posy += x; ps[p].bobposx += m; ps[p].bobposy += x; } j = headspritesect[s->sectnum]; while(j >= 0) { nextj = nextspritesect[j]; if (sprite[j].picnum != SECTOREFFECTOR) { sprite[j].x+=m; sprite[j].y+=x; setsprite(j,sprite[j].x,sprite[j].y,sprite[j].z); } j = nextj; } ms(i); setsprite(i,s->x,s->y,s->z); } break; //Flashing sector lights after reactor EXPLOSION2 case 3: if( t[4] == 0 ) break; p = findplayer(s,&x); // if(t[5] > 0) { t[5]--; break; } if( (global_random/(sh+1)&31) < 4 && !t[2]) { // t[5] = 4+(global_random&7); sc->ceilingpal = s->owner>>8; sc->floorpal = s->owner&0xff; t[0] = s->shade + (global_random&15); } else { // t[5] = 4+(global_random&3); sc->ceilingpal = s->pal; sc->floorpal = s->pal; t[0] = t[3]; } sc->ceilingshade = t[0]; sc->floorshade = t[0]; wal = &wall[sc->wallptr]; for(x=sc->wallnum;x > 0;x--,wal++) { if( wal->hitag != 1 ) { wal->shade = t[0]; if((wal->cstat&2) && wal->nextwall >= 0) { wall[wal->nextwall].shade = wal->shade; } } } break; case 4: if((global_random/(sh+1)&31) < 4 ) { t[1] = s->shade + (global_random&15);//Got really bright t[0] = s->shade + (global_random&15); sc->ceilingpal = s->owner>>8; sc->floorpal = s->owner&0xff; j = 1; } else { t[1] = t[2]; t[0] = t[3]; sc->ceilingpal = s->pal; sc->floorpal = s->pal; j = 0; } sc->floorshade = t[1]; sc->ceilingshade = t[1]; wal = &wall[sc->wallptr]; for(x=sc->wallnum;x > 0; x--,wal++) { if(j) wal->pal = (s->owner&0xff); else wal->pal = s->pal; if( wal->hitag != 1 ) { wal->shade = t[0]; if((wal->cstat&2) && wal->nextwall >= 0) wall[wal->nextwall].shade = wal->shade; } } j = headspritesect[SECT]; while(j >= 0) { if(sprite[j].cstat&16) { if (sc->ceilingstat&1) sprite[j].shade = sc->ceilingshade; else sprite[j].shade = sc->floorshade; } j = nextspritesect[j]; } if(t[4]) KILLIT(i); break; //BOSS case 5: p = findplayer(s,&x); if(x < 8192) { j = s->ang; s->ang = getangle(s->x-ps[p].posx,s->y-ps[p].posy); shoot(i,FIRELASER); s->ang = j; } if(s->owner==-1) //Start search { t[4]=0; l = 0x7fffffff; while(1) //Find the shortest dist { s->owner = LocateTheLocator((short)t[4],-1); //t[0] hold sectnum if(s->owner==-1) break; m = ldist(&sprite[ps[p].i],&sprite[s->owner]); if(l > m) { q = s->owner; l = m; } t[4]++; } s->owner = q; s->zvel = ksgn(sprite[q].z-s->z)<<4; } if(ldist(&sprite[s->owner],s) < 1024) { short ta; ta = s->ang; s->ang = getangle(ps[p].posx-s->x,ps[p].posy-s->y); s->ang = ta; s->owner = -1; goto BOLT; } else s->xvel=256; x = getangle(sprite[s->owner].x-s->x,sprite[s->owner].y-s->y); q = getincangle(s->ang,x)>>3; s->ang += q; if(rnd(32)) { t[2]+=q; sc->ceilingshade = 127; } else { t[2] += getincangle(t[2]+512,getangle(ps[p].posx-s->x,ps[p].posy-s->y))>>2; sc->ceilingshade = 0; } IFHIT { t[3]++; if(t[3] == 5) { s->zvel += 1024; FTA(7,&ps[myconnectindex]); } } s->z += s->zvel; sc->ceilingz += s->zvel; sector[t[0]].ceilingz += s->zvel; ms(i); setsprite(i,s->x,s->y,s->z); break; case 8: case 9: // work only if its moving j = -1; if(hittype[i].temp_data[4]) { hittype[i].temp_data[4]++; if( hittype[i].temp_data[4] > 8 ) KILLIT(i); j = 1; } else j = getanimationgoal(&sc->ceilingz); if( j >= 0 ) { short sn; if( (sc->lotag&0x8000) || hittype[i].temp_data[4] ) x = -t[3]; else x = t[3]; if ( st == 9 ) x = -x; j = headspritestat[3]; while(j >= 0) { if( ((sprite[j].lotag) == st ) && (sprite[j].hitag) == sh ) { sn = sprite[j].sectnum; m = sprite[j].shade; wal = &wall[sector[sn].wallptr]; for(l=sector[sn].wallnum;l>0;l--,wal++) { if( wal->hitag != 1 ) { wal->shade+=x; if(wal->shade < m) wal->shade = m; else if(wal->shade > hittype[j].temp_data[2]) wal->shade = hittype[j].temp_data[2]; if(wal->nextwall >= 0) if(wall[wal->nextwall].hitag != 1) wall[wal->nextwall].shade = wal->shade; } } sector[sn].floorshade += x; sector[sn].ceilingshade += x; if(sector[sn].floorshade < m) sector[sn].floorshade = m; else if(sector[sn].floorshade > hittype[j].temp_data[0]) sector[sn].floorshade = hittype[j].temp_data[0]; if(sector[sn].ceilingshade < m) sector[sn].ceilingshade = m; else if(sector[sn].ceilingshade > hittype[j].temp_data[1]) sector[sn].ceilingshade = hittype[j].temp_data[1]; } j = nextspritestat[j]; } } break; case 10: if( (sc->lotag&0xff) == 27 || ( sc->floorz > sc->ceilingz && (sc->lotag&0xff) != 23 ) || sc->lotag == (short) 32791 ) { j = 1; if( (sc->lotag&0xff) != 27) for(p=connecthead;p>=0;p=connectpoint2[p]) if( sc->lotag != 30 && sc->lotag != 31 && sc->lotag != 0 ) if(s->sectnum == sprite[ps[p].i].sectnum) j = 0; if(j == 1) { if(t[0] > sh ) switch(sector[s->sectnum].lotag) { case 20: case 21: case 22: case 26: if( getanimationgoal(&sector[s->sectnum].ceilingz) >= 0 ) break; // fall through default: activatebysector(s->sectnum,i); t[0] = 0; break; } else t[0]++; } } else t[0]=0; break; case 11: //Swingdoor if( t[5] > 0) { t[5]--; break; } if( t[4] ) { short startwall,endwall; startwall = sc->wallptr; endwall = startwall+sc->wallnum; for(j=startwall;j<endwall;j++) { k = headspritestat[1]; while(k >= 0) { if( sprite[k].extra > 0 && badguy(&sprite[k]) && clipinsidebox(sprite[k].x,sprite[k].y,j,256L) == 1 ) goto BOLT; k = nextspritestat[k]; } k = headspritestat[10]; while(k >= 0) { if( sprite[k].owner >= 0 && clipinsidebox(sprite[k].x,sprite[k].y,j,144L) == 1 ) { t[5] = 8; // Delay k = (SP>>3)*t[3]; t[2]-=k; t[4]-=k; ms(i); setsprite(i,s->x,s->y,s->z); goto BOLT; } k = nextspritestat[k]; } } k = (SP>>3)*t[3]; t[2]+=k; t[4]+=k; ms(i); setsprite(i,s->x,s->y,s->z); if(t[4] <= -511 || t[4] >= 512) { t[4] = 0; t[2] &= 0xffffff00; ms(i); setsprite(i,s->x,s->y,s->z); break; } } break; case 12: if( t[0] == 3 || t[3] == 1 ) //Lights going off { sc->floorpal = 0; sc->ceilingpal = 0; wal = &wall[sc->wallptr]; for(j = sc->wallnum;j > 0; j--, wal++) if(wal->hitag != 1) { wal->shade = t[1]; wal->pal = 0; } sc->floorshade = t[1]; sc->ceilingshade = t[2]; t[0]=0; j = headspritesect[SECT]; while(j >= 0) { if(sprite[j].cstat&16) { if (sc->ceilingstat&1) sprite[j].shade = sc->ceilingshade; else sprite[j].shade = sc->floorshade; } j = nextspritesect[j]; } if(t[3] == 1) KILLIT(i); } if( t[0] == 1 ) //Lights flickering on { if( sc->floorshade > s->shade ) { sc->floorpal = s->pal; sc->ceilingpal = s->pal; sc->floorshade -= 2; sc->ceilingshade -= 2; wal = &wall[sc->wallptr]; for(j=sc->wallnum;j>0;j--,wal++) if(wal->hitag != 1) { wal->pal = s->pal; wal->shade -= 2; } } else t[0] = 2; j = headspritesect[SECT]; while(j >= 0) { if(sprite[j].cstat&16) { if (sc->ceilingstat&1) sprite[j].shade = sc->ceilingshade; else sprite[j].shade = sc->floorshade; } j = nextspritesect[j]; } } break; case 13: if( t[2] ) { j = (SP<<5)|1; if( s->ang == 512 ) { if( s->owner ) { if( klabs(t[0]-sc->ceilingz) >= j ) sc->ceilingz += ksgn(t[0]-sc->ceilingz)*j; else sc->ceilingz = t[0]; } else { if( klabs(t[1]-sc->floorz) >= j ) sc->floorz += ksgn(t[1]-sc->floorz)*j; else sc->floorz = t[1]; } } else { if( klabs(t[1]-sc->floorz) >= j ) sc->floorz += ksgn(t[1]-sc->floorz)*j; else sc->floorz = t[1]; if( klabs(t[0]-sc->ceilingz) >= j ) sc->ceilingz += ksgn(t[0]-sc->ceilingz)*j; sc->ceilingz = t[0]; } if( t[3] == 1 ) { //Change the shades t[3]++; sc->ceilingstat ^= 1; if(s->ang == 512) { wal = &wall[sc->wallptr]; for(j=sc->wallnum;j>0;j--,wal++) wal->shade = s->shade; sc->floorshade = s->shade; if(ps[0].one_parallax_sectnum >= 0) { sc->ceilingpicnum = sector[ps[0].one_parallax_sectnum].ceilingpicnum; sc->ceilingshade = sector[ps[0].one_parallax_sectnum].ceilingshade; } } } t[2]++; if(t[2] > 256) KILLIT(i); } if( t[2] == 4 && s->ang != 512) for(x=0;x<7;x++) RANDOMSCRAP; break; case 15: if(t[4]) { s->xvel = 16; if(t[4] == 1) //Opening { if( t[3] >= (SP>>3) ) { t[4] = 0; //Turn off the sliders callsound(s->sectnum,i); break; } t[3]++; } else if(t[4] == 2) { if(t[3]<1) { t[4] = 0; callsound(s->sectnum,i); break; } t[3]--; } ms(i); setsprite(i,s->x,s->y,s->z); } break; case 16: //Reactor t[2]+=32; if(sc->floorz<sc->ceilingz) s->shade=0; else if( sc->ceilingz < t[3] ) { //The following code check to see if //there is any other sprites in the sector. //If there isn't, then kill this sectoreffector //itself..... j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == REACTOR || sprite[j].picnum == REACTOR2) break; j = nextspritesect[j]; } if(j == -1) { KILLIT(i); } else s->shade=1; } if(s->shade) sc->ceilingz+=1024; else sc->ceilingz-=512; ms(i); setsprite(i,s->x,s->y,s->z); break; case 17: q = t[0]*(SP<<2); sc->ceilingz += q; sc->floorz += q; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].statnum == 10 && sprite[j].owner >= 0) { p = sprite[j].yvel; if(numplayers < 2) ps[p].oposz = ps[p].posz; ps[p].posz += q; ps[p].truefz += q; ps[p].truecz += q; if(numplayers > 1) ps[p].oposz = ps[p].posz; } if( sprite[j].statnum != 3 ) { hittype[j].bposz = sprite[j].z; sprite[j].z += q; } hittype[j].floorz = sc->floorz; hittype[j].ceilingz = sc->ceilingz; j = nextspritesect[j]; } if( t[0] ) if(t[0]) //If in motion { if( klabs(sc->floorz-t[2]) <= SP) { activatewarpelevators(i,0); break; } if(t[0]==-1) { if( sc->floorz > t[3] ) break; } else if( sc->ceilingz < t[4] ) break; if( t[1] == 0 ) break; t[1] = 0; j = headspritestat[3]; while(j >= 0) { if( i != j && (sprite[j].lotag) == 17) if( (sc->hitag-t[0]) == (sector[sprite[j].sectnum].hitag) && sh == (sprite[j].hitag)) break; j = nextspritestat[j]; } if(j == -1) break; k = headspritesect[s->sectnum]; while(k >= 0) { nextk = nextspritesect[k]; if(sprite[k].statnum == 10 && sprite[k].owner >= 0) { p = sprite[k].yvel; ps[p].posx += sprite[j].x-s->x; ps[p].posy += sprite[j].y-s->y; ps[p].posz = sector[sprite[j].sectnum].floorz-(sc->floorz-ps[p].posz); hittype[k].floorz = sector[sprite[j].sectnum].floorz; hittype[k].ceilingz = sector[sprite[j].sectnum].ceilingz; ps[p].bobposx = ps[p].oposx = ps[p].posx; ps[p].bobposy = ps[p].oposy = ps[p].posy; ps[p].oposz = ps[p].posz; ps[p].truefz = hittype[k].floorz; ps[p].truecz = hittype[k].ceilingz; ps[p].bobcounter = 0; changespritesect(k,sprite[j].sectnum); ps[p].cursectnum = sprite[j].sectnum; } else if( sprite[k].statnum != 3 ) { sprite[k].x += sprite[j].x-s->x; sprite[k].y += sprite[j].y-s->y; sprite[k].z = sector[sprite[j].sectnum].floorz- (sc->floorz-sprite[k].z); hittype[k].bposx = sprite[k].x; hittype[k].bposy = sprite[k].y; hittype[k].bposz = sprite[k].z; changespritesect(k,sprite[j].sectnum); setsprite(k,sprite[k].x,sprite[k].y,sprite[k].z); hittype[k].floorz = sector[sprite[j].sectnum].floorz; hittype[k].ceilingz = sector[sprite[j].sectnum].ceilingz; } k = nextk; } } break; case 18: if(t[0]) { if(s->pal) { if(s->ang == 512) { sc->ceilingz -= sc->extra; if(sc->ceilingz <= t[1]) { sc->ceilingz = t[1]; KILLIT(i); } } else { sc->floorz += sc->extra; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz += sc->extra; if( sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4) { hittype[j].bposz = sprite[j].z += sc->extra; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } if(sc->floorz >= t[1]) { sc->floorz = t[1]; KILLIT(i); } } } else { if(s->ang == 512) { sc->ceilingz += sc->extra; if(sc->ceilingz >= s->z) { sc->ceilingz = s->z; KILLIT(i); } } else { sc->floorz -= sc->extra; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz -= sc->extra; if( sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4) { hittype[j].bposz = sprite[j].z -= sc->extra; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } if(sc->floorz <= s->z) { sc->floorz = s->z; KILLIT(i); } } } t[2]++; if(t[2] >= s->hitag) { t[2] = 0; t[0] = 0; } } break; case 19: //Battlestar galactia shields if(t[0]) { if(t[0] == 1) { t[0]++; x = sc->wallptr; q = x+sc->wallnum; for(j=x;j<q;j++) if(wall[j].overpicnum == BIGFORCE) { wall[j].cstat &= (128+32+8+4+2); wall[j].overpicnum = 0; if(wall[j].nextwall >= 0) { wall[wall[j].nextwall].overpicnum = 0; wall[wall[j].nextwall].cstat &= (128+32+8+4+2); } } } if(sc->ceilingz < sc->floorz) sc->ceilingz += SP; else { sc->ceilingz = sc->floorz; j = headspritestat[3]; while(j >= 0) { if(sprite[j].lotag == 0 && sprite[j].hitag==sh) { q = sprite[sprite[j].owner].sectnum; sector[sprite[j].sectnum].floorpal = sector[sprite[j].sectnum].ceilingpal = sector[q].floorpal; sector[sprite[j].sectnum].floorshade = sector[sprite[j].sectnum].ceilingshade = sector[q].floorshade; hittype[sprite[j].owner].temp_data[0] = 2; } j = nextspritestat[j]; } KILLIT(i); } } else //Not hit yet { IFHITSECT { FTA(8,&ps[myconnectindex]); l = headspritestat[3]; while(l >= 0) { x = sprite[l].lotag&0x7fff; switch( x ) { case 0: if(sprite[l].hitag == sh) { q = sprite[l].sectnum; sector[q].floorshade = sector[q].ceilingshade = sprite[sprite[l].owner].shade; sector[q].floorpal = sector[q].ceilingpal = sprite[sprite[l].owner].pal; } break; case 1: case 12: // case 18: case 19: if( sh == sprite[l].hitag ) if( hittype[l].temp_data[0] == 0 ) { hittype[l].temp_data[0] = 1; //Shut them all on sprite[l].owner = i; } break; } l = nextspritestat[l]; } } } break; case 20: //Extend-o-bridge if( t[0] == 0 ) break; if( t[0] == 1 ) s->xvel = 8; else s->xvel = -8; if( s->xvel ) //Moving { x = (s->xvel*sintable[(s->ang+512)&2047])>>14; l = (s->xvel*sintable[s->ang&2047])>>14; t[3] += s->xvel; s->x += x; s->y += l; if( t[3] <= 0 || (t[3]>>6) >= (SP>>6) ) { s->x -= x; s->y -= l; t[0] = 0; callsound(s->sectnum,i); break; } j = headspritesect[s->sectnum]; while(j >= 0) { nextj = nextspritesect[j]; if( sprite[j].statnum != 3 && sprite[j].zvel == 0) { sprite[j].x += x; sprite[j].y += l; setsprite(j,sprite[j].x,sprite[j].y,sprite[j].z); if( sector[sprite[j].sectnum].floorstat&2 ) if(sprite[j].statnum == 2) makeitfall(j); } j = nextj; } dragpoint((short)t[1],wall[t[1]].x+x,wall[t[1]].y+l); dragpoint((short)t[2],wall[t[2]].x+x,wall[t[2]].y+l); for(p=connecthead;p>=0;p=connectpoint2[p]) if(ps[p].cursectnum == s->sectnum && ps[p].on_ground) { ps[p].posx += x; ps[p].posy += l; ps[p].oposx = ps[p].posx; ps[p].oposy = ps[p].posy; setsprite(ps[p].i,ps[p].posx,ps[p].posy,ps[p].posz+PHEIGHT); } sc->floorxpanning-=x>>3; sc->floorypanning-=l>>3; sc->ceilingxpanning-=x>>3; sc->ceilingypanning-=l>>3; } break; case 21: // Cascading effect { int *lp; if( t[0] == 0 ) break; if( s->ang == 1536 ) lp = &sc->ceilingz; else lp = &sc->floorz; if( t[0] == 1 ) //Decide if the s->sectnum should go up or down { s->zvel = ksgn(s->z-(*lp)) * (SP<<4); t[0]++; } if( sc->extra == 0 ) { *lp += s->zvel; if(klabs((*lp)-s->z) < 1024) { *lp = s->z; KILLIT(i); //All done } } else sc->extra--; break; } case 22: if( t[1] ) { if(getanimationgoal(&sector[t[0]].ceilingz) >= 0) sc->ceilingz += sc->extra*9; else t[1] = 0; } break; case 24: case 34: if(t[4]) break; x = (SP*sintable[(s->ang+512)&2047])>>18; l = (SP*sintable[s->ang&2047])>>18; k = 0; j = headspritesect[s->sectnum]; while(j >= 0) { nextj = nextspritesect[j]; if(sprite[j].zvel >= 0) switch(sprite[j].statnum) { case 5: switch(sprite[j].picnum) { case BLOODPOOL: case PUKE: case FOOTPRINTS: case FOOTPRINTS2: case FOOTPRINTS3: case FOOTPRINTS4: case BULLETHOLE: case BLOODSPLAT1: case BLOODSPLAT2: case BLOODSPLAT3: case BLOODSPLAT4: sprite[j].xrepeat = sprite[j].yrepeat = 0; j = nextj; continue; case LASERLINE: j = nextj; continue; } // fall through case 6: if(sprite[j].picnum == TRIPBOMB) break; // fall through case 1: case 0: if( sprite[j].picnum == BOLT1 || sprite[j].picnum == BOLT1+1 || sprite[j].picnum == BOLT1+2 || sprite[j].picnum == BOLT1+3 || sprite[j].picnum == SIDEBOLT1 || sprite[j].picnum == SIDEBOLT1+1 || sprite[j].picnum == SIDEBOLT1+2 || sprite[j].picnum == SIDEBOLT1+3 || wallswitchcheck(j) ) break; if( !(sprite[j].picnum >= CRANE && sprite[j].picnum <= (CRANE+3))) { if( sprite[j].z > (hittype[j].floorz-(16<<8)) ) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; sprite[j].x += x>>2; sprite[j].y += l>>2; setsprite(j,sprite[j].x,sprite[j].y,sprite[j].z); if( sector[sprite[j].sectnum].floorstat&2 ) if(sprite[j].statnum == 2) makeitfall(j); } } break; } j = nextj; } p = myconnectindex; if(ps[p].cursectnum == s->sectnum && ps[p].on_ground) if( klabs(ps[p].posz-ps[p].truefz) < PHEIGHT+(9<<8) ) { fricxv += x<<3; fricyv += l<<3; } sc->floorxpanning += SP>>7; break; case 35: if(sc->ceilingz > s->z) for(j = 0;j < 8;j++) { s->ang += TRAND&511; k = spawn(i,SMALLSMOKE); sprite[k].xvel = 96+(TRAND&127); ssp(k,CLIPMASK0); setsprite(k,sprite[k].x,sprite[k].y,sprite[k].z); if( rnd(16) ) spawn(i,EXPLOSION2); } switch(t[0]) { case 0: sc->ceilingz += s->yvel; if(sc->ceilingz > sc->floorz) sc->floorz = sc->ceilingz; if(sc->ceilingz > s->z+(32<<8)) t[0]++; break; case 1: sc->ceilingz-=(s->yvel<<2); if(sc->ceilingz < t[4]) { sc->ceilingz = t[4]; t[0] = 0; } break; } break; case 25: //PISTONS if( t[4] == 0 ) break; if(sc->floorz <= sc->ceilingz) s->shade = 0; else if( sc->ceilingz <= t[3]) s->shade = 1; if(s->shade) { sc->ceilingz += SP<<4; if(sc->ceilingz > sc->floorz) sc->ceilingz = sc->floorz; } else { sc->ceilingz -= SP<<4; if(sc->ceilingz < t[3]) sc->ceilingz = t[3]; } break; case 26: s->xvel = 32; l = (s->xvel*sintable[(s->ang+512)&2047])>>14; x = (s->xvel*sintable[s->ang&2047])>>14; s->shade++; if( s->shade > 7 ) { s->x = t[3]; s->y = t[4]; sc->floorz -= ((s->zvel*s->shade)-s->zvel); s->shade = 0; } else sc->floorz += s->zvel; j = headspritesect[s->sectnum]; while( j >= 0 ) { nextj = nextspritesect[j]; if(sprite[j].statnum != 3 && sprite[j].statnum != 10) { hittype[j].bposx = sprite[j].x; hittype[j].bposy = sprite[j].y; sprite[j].x += l; sprite[j].y += x; sprite[j].z += s->zvel; setsprite(j,sprite[j].x,sprite[j].y,sprite[j].z); } j = nextj; } p = myconnectindex; if(sprite[ps[p].i].sectnum == s->sectnum && ps[p].on_ground) { fricxv += l<<5; fricyv += x<<5; } for(p = connecthead;p >= 0;p = connectpoint2[p]) if(sprite[ps[p].i].sectnum == s->sectnum && ps[p].on_ground) ps[p].posz += s->zvel; ms(i); setsprite(i,s->x,s->y,s->z); break; case 27: if(ud.recstat == 0) break; hittype[i].tempang = s->ang; p = findplayer(s,&x); if( sprite[ps[p].i].extra > 0 && myconnectindex == screenpeek) { if( t[0] < 0 ) { ud.camerasprite = i; t[0]++; } else if(ud.recstat == 2 && ps[p].newowner == -1) { if(cansee(s->x,s->y,s->z,SECT,ps[p].posx,ps[p].posy,ps[p].posz,ps[p].cursectnum)) { if(x < (int)((unsigned)sh)) { ud.camerasprite = i; t[0] = 999; s->ang += getincangle(s->ang,getangle(ps[p].posx-s->x,ps[p].posy-s->y))>>3; SP = 100+((s->z-ps[p].posz)/257); } else if(t[0] == 999) { if(ud.camerasprite == i) t[0] = 0; else t[0] = -10; ud.camerasprite = i; } } else { s->ang = getangle(ps[p].posx-s->x,ps[p].posy-s->y); if(t[0] == 999) { if(ud.camerasprite == i) t[0] = 0; else t[0] = -20; ud.camerasprite = i; } } } } break; case 28: if(t[5] > 0) { t[5]--; break; } if(T1 == 0) { p = findplayer(s,&x); if( x > 15500 ) break; T1 = 1; T2 = 64 + (TRAND&511); T3 = 0; } else { T3++; if(T3 > T2) { T1 = 0; ps[screenpeek].visibility = ud.const_visibility; break; } else if( T3 == (T2>>1) ) spritesound(THUNDER,i); else if(T3 == (T2>>3) ) spritesound(LIGHTNING_SLAP,i); else if( T3 == (T2>>2) ) { j = headspritestat[0]; while(j >= 0) { if( sprite[j].picnum == NATURALLIGHTNING && sprite[j].hitag == s->hitag) sprite[j].cstat |= 32768; j = nextspritestat[j]; } } else if(T3 > (T2>>3) && T3 < (T2>>2) ) { if( cansee(s->x,s->y,s->z,s->sectnum,ps[screenpeek].posx,ps[screenpeek].posy,ps[screenpeek].posz,ps[screenpeek].cursectnum ) ) j = 1; else j = 0; if( rnd(192) && (T3&1) ) { if(j) ps[screenpeek].visibility = 0; } else if(j) ps[screenpeek].visibility = ud.const_visibility; j = headspritestat[0]; while(j >= 0) { if( sprite[j].picnum == NATURALLIGHTNING && sprite[j].hitag == s->hitag) { if ( rnd(32) && (T3&1) ) { sprite[j].cstat &= 32767; spawn(j,SMALLSMOKE); p = findplayer(s,&x); x = ldist(&sprite[ps[p].i], &sprite[j]); if( x < 768 ) { if(!isspritemakingsound(ps[p].i,DUKE_LONGTERM_PAIN)) spritesound(DUKE_LONGTERM_PAIN,ps[p].i); spritesound(SHORT_CIRCUIT,ps[p].i); sprite[ps[p].i].extra -= 8+(TRAND&7); ps[p].pals_time = 32; ps[p].pals[0] = 16; ps[p].pals[1] = 0; ps[p].pals[2] = 0; } break; } else sprite[j].cstat |= 32768; } j = nextspritestat[j]; } } } break; case 29: s->hitag += 64; l = mulscale12((int)s->yvel,sintable[s->hitag&2047]); sc->floorz = s->z + l; break; case 31: // True Drop Floor if(t[0] == 1) { // Choose dir if(t[3] > 0) { t[3]--; break; } if(t[2] == 1) // Retract { if(SA != 1536) { if( klabs( sc->floorz - s->z ) < SP ) { sc->floorz = s->z; t[2] = 0; t[0] = 0; t[3] = s->hitag; callsound(s->sectnum,i); } else { l = ksgn(s->z-sc->floorz)*SP; sc->floorz += l; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz += l; if( sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4) { hittype[j].bposz = sprite[j].z += l; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } } } else { if( klabs( sc->floorz - t[1] ) < SP ) { sc->floorz = t[1]; callsound(s->sectnum,i); t[2] = 0; t[0] = 0; t[3] = s->hitag; } else { l = ksgn(t[1]-sc->floorz)*SP; sc->floorz += l; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz += l; if( sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4 ) { hittype[j].bposz = sprite[j].z += l; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } } } break; } if( (s->ang&2047) == 1536) { if( klabs( s->z-sc->floorz ) < SP ) { callsound(s->sectnum,i); t[0] = 0; t[2] = 1; t[3] = s->hitag; } else { l = ksgn(s->z-sc->floorz)*SP; sc->floorz += l; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz += l; if( sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4 ) { hittype[j].bposz = sprite[j].z += l; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } } } else { if( klabs( sc->floorz-t[1] ) < SP ) { t[0] = 0; callsound(s->sectnum,i); t[2] = 1; t[3] = s->hitag; } else { l = ksgn(s->z-t[1])*SP; sc->floorz -= l; j = headspritesect[s->sectnum]; while(j >= 0) { if(sprite[j].picnum == APLAYER && sprite[j].owner >= 0) if( ps[sprite[j].yvel].on_ground == 1 ) ps[sprite[j].yvel].posz -= l; if(sprite[j].zvel == 0 && sprite[j].statnum != 3 && sprite[j].statnum != 4 ) { hittype[j].bposz = sprite[j].z -= l; hittype[j].floorz = sc->floorz; } j = nextspritesect[j]; } } } } break; case 32: // True Drop Ceiling if(t[0] == 1) { // Choose dir if(t[2] == 1) // Retract { if(SA != 1536) { if( klabs( sc->ceilingz - s->z ) < (SP<<1) ) { sc->ceilingz = s->z; callsound(s->sectnum,i); t[2] = 0; t[0] = 0; } else sc->ceilingz += ksgn(s->z-sc->ceilingz)*SP; } else { if( klabs( sc->ceilingz - t[1] ) < (SP<<1) ) { sc->ceilingz = t[1]; callsound(s->sectnum,i); t[2] = 0; t[0] = 0; } else sc->ceilingz += ksgn(t[1]-sc->ceilingz)*SP; } break; } if( (s->ang&2047) == 1536) { if( klabs(sc->ceilingz-s->z ) < (SP<<1) ) { t[0] = 0; t[2] = !t[2]; callsound(s->sectnum,i); sc->ceilingz = s->z; } else sc->ceilingz += ksgn(s->z-sc->ceilingz)*SP; } else { if( klabs(sc->ceilingz-t[1] ) < (SP<<1) ) { t[0] = 0; t[2] = !t[2]; callsound(s->sectnum,i); } else sc->ceilingz -= ksgn(s->z-t[1])*SP; } } break; case 33: if( earthquaketime > 0 && (TRAND&7) == 0 ) RANDOMSCRAP; break; case 36: if( t[0] ) { if( t[0] == 1 ) shoot(i,sc->extra); else if( t[0] == 26*5 ) t[0] = 0; t[0]++; } break; case 128: //SE to control glass breakage wal = &wall[t[2]]; wal->cstat &= (255-32); wal->cstat |= 16; if(wal->nextwall >= 0) { wall[wal->nextwall].cstat &= (255-32); wall[wal->nextwall].cstat |= 16; } wal->overpicnum++; if(wal->nextwall >= 0) wall[wal->nextwall].overpicnum++; if(t[0] < t[1]) t[0]++; else { wal->cstat &= (128+32+8+4+2); if(wal->nextwall >= 0) wall[wal->nextwall].cstat &= (128+32+8+4+2); KILLIT(i); } break; case 130: if(t[0] > 80) { KILLIT(i); } else t[0]++; x = sc->floorz-sc->ceilingz; if( rnd(64) ) { k = spawn(i,EXPLOSION2); sprite[k].xrepeat = sprite[k].yrepeat = 2+(TRAND&7); sprite[k].z = sc->floorz-(TRAND%x); sprite[k].ang += 256-(TRAND%511); sprite[k].xvel = TRAND&127; ssp(k,CLIPMASK0); } break; case 131: if(t[0] > 40) { KILLIT(i); } else t[0]++; x = sc->floorz-sc->ceilingz; if( rnd(32) ) { k = spawn(i,EXPLOSION2); sprite[k].xrepeat = sprite[k].yrepeat = 2+(TRAND&3); sprite[k].z = sc->floorz-(TRAND%x); sprite[k].ang += 256-(TRAND%511); sprite[k].xvel = TRAND&127; ssp(k,CLIPMASK0); } break; } BOLT: i = nexti; } //Sloped sin-wave floors! for(i=headspritestat[3];i>=0;i=nextspritestat[i]) { s = &sprite[i]; if (s->lotag != 29) continue; sc = &sector[s->sectnum]; if (sc->wallnum != 4) continue; wal = &wall[sc->wallptr+2]; alignflorslope(s->sectnum,wal->x,wal->y,sector[wal->nextsector].floorz); } }
0
0.879565
1
0.879565
game-dev
MEDIA
0.981126
game-dev
0.987333
1
0.987333
SparkDevNetwork/Rock
10,504
Rock/Event/InteractiveExperiences/ActionTypeContainer.cs
// <copyright> // Copyright by the Spark Development Network // // Licensed under the Rock Community License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.rockrms.com/license // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using Rock.Attribute; using Rock.Data; using Rock.Extension; using Rock.Model; using Rock.Web.Cache; namespace Rock.Event.InteractiveExperiences { /** * 10/18/2022 - DSH * * Attributes for InteractiveExperienceActions are a little weird. We actually * put attributes from two different component types on the one entity. Because of * that we enforce that each component type starts with a specific prefix to * help us identify which attributes are which. The available prefixes are * "action" for ActionTypeComponent and "visualizer" for VisualizerTypeComponent. */ /// <summary> /// MEF Container class for Interactive Experience Action Type Components. /// </summary> internal class ActionTypeContainer : Container<ActionTypeComponent, IComponentData> { #region Fields /// <summary> /// Singleton instance /// </summary> private static readonly Lazy<ActionTypeContainer> _instance = new Lazy<ActionTypeContainer>( () => new ActionTypeContainer() ); #endregion #region Properties /// <summary> /// Gets the instance. /// </summary> /// <value> /// The instance. /// </value> public static ActionTypeContainer Instance => _instance.Value; /// <summary> /// Gets all action type components that have been found in the system. /// </summary> /// <value>All action type components that have been found in the system.</value> public IEnumerable<ActionTypeComponent> AllComponents => Components.Values.Select( v => v.Value ); /// <summary> /// Gets or sets the MEF components. /// </summary> /// <value> /// The MEF components. /// </value> [ImportMany( typeof( ActionTypeComponent ) )] protected override IEnumerable<Lazy<ActionTypeComponent, IComponentData>> MEFComponents { get; set; } #endregion #region Methods /// <summary> /// Uses reflection to find any <see cref="FieldAttribute" /> attributes /// for the specified type and will create and/or update a /// <see cref="Rock.Model.Attribute" /> record for each attribute defined. /// This is a custom variation of the standard one in <see cref="Helper.UpdateAttributes(Type, int?, string, string, RockContext)"/> /// that handles filtering by prefix. /// </summary> /// <param name="type">The type (should be a <see cref="IHasAttributes" /> object).</param> /// <param name="entityTypeId">The entity type id.</param> /// <param name="keyPrefix">The prefix that attribute keys must have in order to be included.</param> /// <param name="entityQualifierColumn">The entity qualifier column.</param> /// <param name="entityQualifierValue">The entity qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns><c>true</c> if any attributes were created/updated.</returns> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> internal static bool UpdateAttributes( Type type, int? entityTypeId, string keyPrefix, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext ) { bool attributesUpdated = false; bool attributesDeleted = false; if ( type == null ) { return false; } var entityProperties = new List<FieldAttribute>(); // Add any property attributes that were defined for the entity var customFieldAttributes = type.GetCustomAttributes( typeof( FieldAttribute ), true ) .Cast<FieldAttribute>() .Where( a => a.Key.StartsWith( keyPrefix ) ); foreach ( var customAttribute in customFieldAttributes ) { entityProperties.Add( customAttribute ); } rockContext = rockContext ?? new RockContext(); // Create any attributes that need to be created foreach ( var entityProperty in entityProperties ) { try { attributesUpdated = Helper.UpdateAttribute( entityProperty, entityTypeId, entityQualifierColumn, entityQualifierValue, rockContext ) || attributesUpdated; } catch ( Exception ex ) { ExceptionLogService.LogException( new Exception( string.Format( "Could not update an entity attribute ( Entity Type Id: {0}; Property Name: {1} ). ", entityTypeId, entityProperty.Name ), ex ), null ); } } // Remove any old attributes try { var attributeService = new Model.AttributeService( rockContext ); var existingKeys = entityProperties.Select( a => a.Key ).ToList(); foreach ( var a in attributeService.GetByEntityTypeQualifier( entityTypeId, entityQualifierColumn, entityQualifierValue, true ).ToList() ) { if ( !existingKeys.Contains( a.Key ) && a.Key.StartsWith( keyPrefix ) ) { attributeService.Delete( a ); attributesDeleted = true; } } if ( attributesDeleted ) { rockContext.SaveChanges(); } } catch ( Exception ex ) { ExceptionLogService.LogException( new Exception( "Could not delete one or more old attributes.", ex ), null ); } return attributesUpdated; } /// <summary> /// Forces a reloading of all the components /// </summary> public override void Refresh() { base.Refresh(); // Create any attributes that need to be created var actionEntityTypeId = EntityTypeCache.Get<InteractiveExperienceAction>().Id; using ( var rockContext = new RockContext() ) { foreach ( var actionComponent in AllComponents ) { var actionComponentType = actionComponent.GetType(); var actionComponentEntityTypeId = EntityTypeCache.Get( actionComponentType ).Id; UpdateAttributes( actionComponentType, actionEntityTypeId, "action", nameof( InteractiveExperienceAction.ActionEntityTypeId ), actionComponentEntityTypeId.ToString(), rockContext ); } } } /// <summary> /// Gets the component with the matching Entity Type Name. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <returns>An instance of <see cref="ActionTypeComponent"/> or <c>null</c> if it was not found.</returns> public static ActionTypeComponent GetComponent( string entityType ) { return Instance.GetComponentByEntity( entityType ); } /// <summary> /// Gets the component with the matching Entity Type identifier. /// </summary> /// <param name="entityTypeId">The <see cref="EntityType"/> identifier.</param> /// <returns>An instance of <see cref="ActionTypeComponent"/> or <c>null</c> if it was not found.</returns> public static ActionTypeComponent GetComponentFromEntityType( int entityTypeId ) { var entityTypeCache = EntityTypeCache.Get( entityTypeId ); var actionTypeType = entityTypeCache?.GetEntityType(); if ( actionTypeType == null ) { return null; } return GetComponent( actionTypeType.FullName ); } /// <summary> /// Gets the component matching the specified type. /// </summary> /// <returns>An instance of <see cref="ActionTypeComponent"/> or <c>null</c> if it was not found.</returns> public static ActionTypeComponent GetComponent<T>() { return GetComponent( typeof( T ).FullName ); } /// <summary> /// Gets the name of the component. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <returns>A <see cref="string"/> that represents the name of the component or an empty string if not found.</returns> public static string GetComponentName( string entityType ) { return Instance.GetComponentNameByEntity( entityType ); } /// <summary> /// Gets the name of the component. /// </summary> /// <returns>A <see cref="string"/> that represents the name of the component or an empty string if not found.</returns> public static string GetComponentName<T>() { return GetComponentName( typeof( T ).FullName ); } /// <summary> /// Gets the name of the component. /// </summary> /// <param name="component">The component whose name is to be determined.</param> /// <returns>A <see cref="string"/> that represents the name of the component or an empty string if not found.</returns> public static string GetComponentName( ActionTypeComponent component ) { if ( component == null ) { throw new ArgumentNullException( nameof( component ) ); } return GetComponentName( component.GetType().FullName ); } #endregion } }
0
0.813743
1
0.813743
game-dev
MEDIA
0.357454
game-dev
0.827948
1
0.827948
OpenStarbound/OpenStarbound
6,087
doc/lua/movementcontroller.md
# mcontroller The `mcontroller` table contains functions relating to the movement controller. This section of mcontroller documentation refers to the MovementController lua bindings. Other documentation may refer to ActorMovementController lua bindings. MovementController is used in: * projectiles * vehicles --- #### `MovementParameters` mcontroller.parameters() Returns a table containing the movement parameters for the movement controller. --- #### `void` mcontroller.applyParameters(`Json` parameters) Applies the given parameters to the movement controller. The provided parameters are merged into the current movement parameters. --- #### `void` mcontroller.resetParameters() Resets movement parameters to their original state. --- #### `float` mcontroller.mass() Returns the configured mass of the movement controller. --- #### `Vec2F` mcontroller.position() Returns the current position of the movement controller. --- #### `float` mcontroller.xPosition() Returns the current horizontal position of the movement controller. --- #### `float` mcontroller.yPosition() Returns the current vertical position of the movement controller. --- #### `Vec2F` mcontroller.velocity() Returns the current velocity of the movement controller. --- #### `float` mcontroller.xVelocity() Returns the current horizontal speed of the movement controller. --- #### `float` mcontroller.yVelocity() Returns the current vertical speed of the movement controller. --- #### `float` mcontroller.rotation() Returns the current rotation of the movement controller in radians. --- #### `PolyF` mcontroller.collisionPoly() Returns the collision poly of the movement controller, in local coordinates. --- #### `PolyF` mcontroller.collisionBody() Returns the collision poly of the movement controller, in world coordinates. --- #### `RectF` mcontroller.collisionBoundBox() Returns a rect containing the entire collision poly of the movement controller, in world coordinates. --- #### `RectF` mcontroller.localBoundBox() Returns a rect containing the entire collision of the movement controller, in local coordinates. --- #### `bool` mcontroller.isColliding() Returns whether the movement controller is currently colliding with world geometry or a PhysicsMovingCollision. --- #### `bool` mcontroller.isNullColliding() Returns whether the movement controller is currently colliding with null world geometry. Null collision occurs in unloaded sectors. --- #### `bool` mcontroller.isCollisionStuck() Returns whether the movement controller is currently stuck colliding. Movement controllers can stick if the `stickyCollision` movement parameter is set. --- #### `float` mcontroller.stickingDirection() Returns the angle that the movement controller is currently stuck at, in radians. --- #### `float` mcontroller.liquidPercentage() Returns the percentage of the collision poly currently submerged in liquid; --- #### `LiquidId` mcontroller.liquidId() Returns the liquid ID of the liquid that the movement controller is currently submerged in. If this is several liquids this returns the most plentiful one. --- #### `bool` mcontroller.onGround() Returns whether the movement controller is currently on ground. --- #### `bool` mcontroller.zeroG() Returns `true` if the movement controller is at a world position without gravity or if gravity has been disabled. --- #### `bool` mcontroller.atWorldLimit([`bool` bottomOnly]) Returns `true` if the movement controller is touching the bottom or the top (unless bottomOnly is specified) of the world. --- #### `void` mcontroller.setPosition(`Vec2F` position) Sets the position of the movement controller. --- #### `void` mcontroller.setXPosition(`float` x) Sets the horizontal position of the movement controller. --- #### `void` mcontroller.setYPosition(`float` y) Sets the vertical position of the movement controller. --- #### `void` mcontroller.translate(`Vec2F` direction) Moves the movement controller by the vector provided. --- #### `void` mcontroller.setVelocity(`Vec2F` velocity) Sets the velocity of the movement controller. --- #### `void` mcontroller.setXVelocity(`Vec2F` xVelocity) Sets the horizontal velocity of the movement controller. --- #### `void` mcontroller.setYVelocity(`Vec2F` yVelocity) Sets the vertical velocity of the movement controller. --- #### `void` mcontroller.addMomentum(`Vec2F` momentum) Adds (momentum / mass) velocity to the movement controller. --- #### `void` mcontroller.setRotation(`float` angle) Sets the rotation of the movement controller. Angle is in radians. --- #### `void` mcontroller.rotate(`float` angle) Rotates the movement controller by an angle relative to its current angle. Angle is in radians. --- #### `void` mcontroller.accelerate(`Vec2F` acceleration) Accelerates the movement controller by the given acceleration for one tick. --- #### `void` mcontroller.force(`Vec2F` force) Accelerates the movement controller by (force / mass) for one tick. --- #### `void` mcontroller.approachVelocity(`Vec2F` targetVelocity, `float` maxControlForce) Approaches the targetVelocity using the force provided. If the current velocity is higher than the provided targetVelocity, the targetVelocity will still be approached, effectively slowing down the entity. --- #### `void` mcontroller.approachVelocityAlongAngle(`float` angle, `float` targetVelocity, `float` maxControlForce, `bool` positiveOnly = false) Approaches the targetVelocity but only along the provided angle, not affecting velocity in the perpendicular axis. If positiveOnly, then it will not slow down the movementController if it is already moving faster than targetVelocity. --- #### `void` mcontroller.approachXVelocity(`float` targetVelocity, `float` maxControlForce) Approaches an X velocity. Same as using approachVelocityAlongAngle with angle 0. --- #### `void` mcontroller.approachYVelocity(`float` targetVelocity, `float` maxControlForce) Approaches a Y velocity. Same as using approachVelocityAlongAngle with angle (Pi / 2).
0
0.760628
1
0.760628
game-dev
MEDIA
0.972145
game-dev
0.943889
1
0.943889
DanceManiac/Advanced-X-Ray-Public
2,136
SourcesAXR/xrGameCS/GameMtlLib_Engine.cpp
//--------------------------------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "GameMtlLib.h" void DestroySounds(SoundVec& lst) { for (SoundIt it=lst.begin(); lst.end() != it; ++it) it->destroy(); } void DestroyMarks(ShaderVec& lst) { for (ShaderIt it=lst.begin(); lst.end() != it; ++it) it->destroy(); } void DestroyPSs(PSVec& lst) { // for (PSIt it=lst.begin(); lst.end() != it; ++it) // Device.Resources->Delete(*it); } void CreateSounds(SoundVec& lst, LPCSTR buf) { string128 tmp; int cnt = _GetItemCount(buf); R_ASSERT(cnt<=GAMEMTL_SUBITEM_COUNT); lst.resize (cnt); for (int k=0; k<cnt; ++k) lst[k].create (_GetItem(buf,k,tmp),st_Effect,sg_SourceType); } void CreateMarks(ShaderVec& lst, LPCSTR buf) { string256 tmp; int cnt =_GetItemCount(buf); R_ASSERT(cnt<=GAMEMTL_SUBITEM_COUNT); ref_shader s; for (int k=0; k<cnt; ++k) { s.create ("effects\\wallmark",_GetItem(buf,k,tmp)); lst.push_back (s); } } void CreatePSs(PSVec& lst, LPCSTR buf) { string256 tmp; int cnt=_GetItemCount(buf); R_ASSERT(cnt<=GAMEMTL_SUBITEM_COUNT); for (int k=0; k<cnt; ++k) lst.push_back (_GetItem(buf,k,tmp)); } SGameMtlPair::~SGameMtlPair() { // destroy all media DestroySounds (BreakingSounds); DestroySounds (StepSounds); DestroySounds (CollideSounds); DestroyPSs (CollideParticles); DestroyMarks (CollideMarks); } void SGameMtlPair::Load(IReader& fs) { shared_str buf; R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_PAIR)); mtl0 = fs.r_u32(); mtl1 = fs.r_u32(); ID = fs.r_u32(); ID_parent = fs.r_u32(); OwnProps.assign (fs.r_u32()); R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_BREAKING)); fs.r_stringZ (buf); CreateSounds (BreakingSounds,*buf); R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_STEP)); fs.r_stringZ (buf); CreateSounds (StepSounds,*buf); R_ASSERT(fs.find_chunk(GAMEMTLPAIR_CHUNK_COLLIDE)); fs.r_stringZ (buf); CreateSounds (CollideSounds,*buf); fs.r_stringZ (buf); CreatePSs (CollideParticles,*buf); fs.r_stringZ (buf); CreateMarks (CollideMarks,*buf); }
0
0.68097
1
0.68097
game-dev
MEDIA
0.891885
game-dev
0.931154
1
0.931154
linuxmint/warpinator
1,603
src/grpcio-1.73.1/third_party/upb/upb/message/accessors.c
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "upb/message/accessors.h" #include "upb/mem/arena.h" #include "upb/message/array.h" #include "upb/message/map.h" #include "upb/message/message.h" #include "upb/mini_table/field.h" #include "upb/mini_table/message.h" // Must be last. #include "upb/port/def.inc" bool upb_Message_SetMapEntry(upb_Map* map, const upb_MiniTable* m, const upb_MiniTableField* f, upb_Message* map_entry_message, upb_Arena* arena) { UPB_ASSERT(!upb_Message_IsFrozen(map_entry_message)); const upb_MiniTable* map_entry_mini_table = upb_MiniTable_MapEntrySubMessage(m, f); UPB_ASSERT(map_entry_mini_table); const upb_MiniTableField* map_entry_key_field = upb_MiniTable_MapKey(map_entry_mini_table); const upb_MiniTableField* map_entry_value_field = upb_MiniTable_MapValue(map_entry_mini_table); // Map key/value cannot have explicit defaults, // hence assuming a zero default is valid. upb_MessageValue default_val = upb_MessageValue_Zero(); upb_MessageValue map_entry_key = upb_Message_GetField(map_entry_message, map_entry_key_field, default_val); upb_MessageValue map_entry_value = upb_Message_GetField( map_entry_message, map_entry_value_field, default_val); return upb_Map_Set(map, map_entry_key, map_entry_value, arena); }
0
0.890617
1
0.890617
game-dev
MEDIA
0.144326
game-dev
0.859124
1
0.859124
danielga/garrysmod_common
1,148
helpers_extended/include/GarrysMod/Lua/AutoCall.h
#pragma once #include "AutoStack.h" namespace GarrysMod { namespace Lua { class AutoCall : public AutoStack { public: AutoCall( GarrysMod::Lua::ILuaBase *lua_base, bool custom_error_function = false ) : AutoStack( lua_base ), use_custom_error_function( custom_error_function ) { lua->GetField( GarrysMod::Lua::INDEX_GLOBAL, "debug" ); if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) throw std::runtime_error( "Global debug is not a table!" ); lua->GetField( -1, "traceback" ); lua->Remove( -2 ); if( !lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) ) throw std::runtime_error( "Global debug.traceback is not a function!" ); ++stack_offset; } void Call( int32_t results ) { lua->Call( GetStackDifference( ) - stack_offset, results ); } bool PCall( int32_t results, int32_t errorFunc = 0 ) { if( errorFunc == 0 && use_custom_error_function ) errorFunc = stack_start + 1; return lua->PCall( GetStackDifference( ) - stack_offset, results, errorFunc ) == 0; } protected: int32_t stack_offset = 0; bool use_custom_error_function; }; } }
0
0.789719
1
0.789719
game-dev
MEDIA
0.441031
game-dev
0.651655
1
0.651655
pinky39/grove
1,200
source/Grove/UserInterface/CombatDamage/BlockerDamageAssignments.cs
namespace Grove.UserInterface.CombatDamage { using System.Collections; using System.Collections.Generic; using System.Linq; using Infrastructure; public class BlockerDamageAssignments : IEnumerable<BlockerDamageAssignment> { private readonly List<BlockerDamageAssignment> _assignments; public BlockerDamageAssignments(Attacker attacker) { _assignments = attacker.Blockers .OrderBy(x => x.DamageAssignmentOrder) .Select(x => Bindable.Create<BlockerDamageAssignment>(x)) .ToList(); } public IEnumerator<BlockerDamageAssignment> GetEnumerator() { return _assignments.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool CanAssignCombatDamageTo(BlockerDamageAssignment blocker) { foreach (var assignment in _assignments) { if (assignment == blocker) return true; if (assignment.HasAssignedLeathalDamage == false) return false; } return false; } public void Clear() { foreach (var blocker in _assignments) { blocker.AssignedDamage = 0; } } } }
0
0.758825
1
0.758825
game-dev
MEDIA
0.346263
game-dev
0.814157
1
0.814157
ProjectIgnis/CardScripts
2,796
official/c55584558.lua
--ピュアリィ・デリシャスメモリー --Purrely Delicious Memory --scripted by Naim local s,id=GetID() function s.initial_effect(c) --Selected monster cannot be destroyed by battle, discard 1 card and Special Summon 1 "Purrely" monster local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_HANDES+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetHintTiming(TIMING_MAIN_END) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) --Increase ATK/DEF of a "Purrely" Xyz monster with this card as material local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_XMATERIAL) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetRange(LOCATION_MZONE) e2:SetCondition(function(e) return e:GetHandler():IsSetCard(SET_PURRELY) end) e2:SetValue(s.atkvalue) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_UPDATE_DEFENSE) c:RegisterEffect(e3) end s.listed_series={SET_PURRELY} function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.SetPossibleOperationInfo(0,CATEGORY_HANDES,nil,0,tp,1) Duel.SetPossibleOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function s.spfilter(c,e,tp) return c:IsSetCard(SET_PURRELY) and c:IsLevel(1) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function s.activate(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_APPLYTO) local tc=Duel.SelectMatchingCard(tp,nil,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil):GetFirst() if not tc then return end Duel.HintSelection(tc,true) --Cannot be destroyed by battle local extraproperty=tc:IsPosition(POS_FACEDOWN) and EFFECT_FLAG_SET_AVAILABLE or 0 local e1=Effect.CreateEffect(e:GetHandler()) e1:SetDescription(3000) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT+extraproperty) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetReset(RESETS_STANDARD_PHASE_END,2) e1:SetValue(1) tc:RegisterEffect(e1) --Discard 1 card and Special Summon 1 "Purrely" monster from the Deck if Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) and Duel.SelectYesNo(tp,aux.Stringid(id,1)) then Duel.BreakEffect() if Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_EFFECT|REASON_DISCARD,nil)>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if #g>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end end end function s.atkvalue(e,c) return e:GetHandler():GetOverlayCount()*300 end
0
0.95651
1
0.95651
game-dev
MEDIA
0.987206
game-dev
0.956628
1
0.956628
wolfetplayer/RealRTCW
152,072
sdk/rtcw-bspc-custom/src/botlib/be_aas_reach.c
/* =========================================================================== Return to Castle Wolfenstein single player GPL Source Code Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company. This file is part of the Return to Castle Wolfenstein single player GPL Source Code (“RTCW SP Source Code”). RTCW SP Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RTCW SP Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ /***************************************************************************** * name: be_aas_reach.c * * desc: reachability calculations * * *****************************************************************************/ #include "../game/q_shared.h" #include "l_log.h" #include "l_memory.h" #include "l_script.h" #include "l_libvar.h" #include "l_precomp.h" #include "l_struct.h" #include "aasfile.h" #include "../game/botlib.h" #include "../game/be_aas.h" #include "be_aas_funcs.h" #include "be_aas_def.h" extern int Sys_MilliSeconds( void ); //#include "../../../gladiator/bspc/aas_store.h" extern botlib_import_t botimport; //#define REACHDEBUG //NOTE: all travel times are in hundreth of a second //maximum fall delta before getting damaged // Ridah, tweaked for Wolf AI #define FALLDELTA_5DAMAGE 25 //40 #define FALLDELTA_10DAMAGE 40 //60 // done. //maximum number of reachability links #define AAS_MAX_REACHABILITYSIZE 65536 //number of areas reachability is calculated for each frame #define REACHABILITYAREASPERCYCLE 15 //number of units reachability points are placed inside the areas #define INSIDEUNITS 2 // Ridah, tweaked this, routing issues around small areas #define INSIDEUNITS_WALKEND 5 // original //#define INSIDEUNITS_WALKEND 0.2 // new // Ridah, added this for better walking off ledges #define INSIDEUNITS_WALKOFFLEDGEEND 15 #define INSIDEUNITS_WALKSTART 0.1 #define INSIDEUNITS_WATERJUMP 15 //travel times in hundreth of a second // Ridah, tweaked these for Wolf AI #define REACH_MIN_TIME 4 // always at least this much time for a reachability #define WATERJUMP_TIME 700 //7 seconds #define TELEPORT_TIME 50 //0.5 seconds #define BARRIERJUMP_TIME 900 //fixed value? #define STARTCROUCH_TIME 300 //3 sec to start crouching #define STARTGRAPPLE_TIME 500 //using the grapple costs a lot of time #define STARTWALKOFFLEDGE_TIME 300 //3 seconds #define STARTJUMP_TIME 500 //3 seconds for jumping #define FALLDAMAGE_5_TIME 400 //extra travel time when falling hurts #define FALLDAMAGE_10_TIME 900 //extra travel time when falling hurts // done. //maximum height the bot may fall down when jumping #define MAX_JUMPFALLHEIGHT 450 //area flag used for weapon jumping #define AREA_WEAPONJUMP 8192 //valid area to weapon jump to //number of reachabilities of each type int reach_swim; //swim int reach_equalfloor; //walk on floors with equal height int reach_step; //step up int reach_walk; //walk of step int reach_barrier; //jump up to a barrier int reach_waterjump; //jump out of water int reach_walkoffledge; //walk of a ledge int reach_jump; //jump int reach_ladder; //climb or descent a ladder int reach_teleport; //teleport int reach_elevator; //use an elevator int reach_funcbob; //use a func bob int reach_grapple; //grapple hook int reach_doublejump; //double jump int reach_rampjump; //ramp jump int reach_strafejump; //strafe jump (just normal jump but further) int reach_rocketjump; //rocket jump int reach_bfgjump; //bfg jump int reach_jumppad; //jump pads //if true grapple reachabilities are skipped int calcgrapplereach; //linked reachability typedef struct aas_lreachability_s { int areanum; //number of the reachable area int facenum; //number of the face towards the other area int edgenum; //number of the edge towards the other area vec3_t start; //start point of inter area movement vec3_t end; //end point of inter area movement int traveltype; //type of travel required to get to the area unsigned short int traveltime; //travel time of the inter area movement // struct aas_lreachability_s *next; } aas_lreachability_t; //temporary reachabilities aas_lreachability_t *reachabilityheap; //heap with reachabilities aas_lreachability_t *nextreachability; //next free reachability from the heap aas_lreachability_t **areareachability; //reachability links for every area int numlreachabilities; //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_BestReachableLinkArea( aas_link_t *areas ) { aas_link_t *link; for ( link = areas; link; link = link->next_area ) { if ( AAS_AreaGrounded( link->areanum ) || AAS_AreaSwim( link->areanum ) ) { return link->areanum; } //end if } //end for // for ( link = areas; link; link = link->next_area ) { if ( link->areanum ) { return link->areanum; } //FIXME: cannot enable next line right now because the reachability // does not have to be calculated when the level items are loaded //if (AAS_AreaReachability(link->areanum)) return link->areanum; } //end for return 0; } //end of the function AAS_BestReachableLinkArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_BestReachableArea( vec3_t origin, vec3_t mins, vec3_t maxs, vec3_t goalorigin ) { int areanum, i, j, k, l; aas_link_t *areas; vec3_t absmins, absmaxs; //vec3_t bbmins, bbmaxs; vec3_t start, end; aas_trace_t trace; if ( !( *aasworld ).loaded ) { botimport.Print( PRT_ERROR, "AAS_BestReachableArea: aas not loaded\n" ); return 0; } //end if //find a point in an area VectorCopy( origin, start ); areanum = AAS_PointAreaNum( start ); //while no area found fudge around a little for ( i = 0; i < 5 && !areanum; i++ ) { for ( j = 0; j < 5 && !areanum; j++ ) { for ( k = -1; k <= 1 && !areanum; k++ ) { for ( l = -1; l <= 1 && !areanum; l++ ) { VectorCopy( origin, start ); start[0] += (float) j * 4 * k; start[1] += (float) j * 4 * l; start[2] += (float) i * 4; areanum = AAS_PointAreaNum( start ); } //end for } //end for } //end for } //end for //if an area was found if ( areanum ) { //drop client bbox down and try again VectorCopy( start, end ); start[2] += 0.25; end[2] -= 50; trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, -1 ); if ( !trace.startsolid ) { areanum = AAS_PointAreaNum( trace.endpos ); VectorCopy( trace.endpos, goalorigin ); //FIXME: cannot enable next line right now because the reachability // does not have to be calculated when the level items are loaded //if the origin is in an area with reachability //if (AAS_AreaReachability(areanum)) return areanum; if ( areanum ) { return areanum; } } //end if else { //it can very well happen that the AAS_PointAreaNum function tells that //a point is in an area and that starting a AAS_TraceClientBBox from that //point will return trace.startsolid qtrue /* if (AAS_PointAreaNum(start)) { Log_Write("point %f %f %f in area %d but trace startsolid", start[0], start[1], start[2], areanum); AAS_DrawPermanentCross(start, 4, LINECOLOR_RED); } //end if botimport.Print(PRT_MESSAGE, "AAS_BestReachableArea: start solid\n"); */ VectorCopy( start, goalorigin ); return areanum; } //end else } //end if // //AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, bbmins, bbmaxs); //NOTE: the goal origin does not have to be in the goal area // because the bot will have to move towards the item origin anyway VectorCopy( origin, goalorigin ); // VectorAdd( origin, mins, absmins ); VectorAdd( origin, maxs, absmaxs ); //add bounding box size //VectorSubtract(absmins, bbmaxs, absmins); //VectorSubtract(absmaxs, bbmins, absmaxs); //link an invalid (-1) entity areas = AAS_AASLinkEntity( absmins, absmaxs, -1 ); //get the reachable link arae areanum = AAS_BestReachableLinkArea( areas ); //unlink the invalid entity AAS_UnlinkFromAreas( areas ); // return areanum; } //end of the function AAS_BestReachableArea //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_SetupReachabilityHeap( void ) { int i; reachabilityheap = (aas_lreachability_t *) GetClearedMemory( AAS_MAX_REACHABILITYSIZE * sizeof( aas_lreachability_t ) ); for ( i = 0; i < AAS_MAX_REACHABILITYSIZE - 1; i++ ) { reachabilityheap[i].next = &reachabilityheap[i + 1]; } //end for reachabilityheap[AAS_MAX_REACHABILITYSIZE - 1].next = NULL; nextreachability = reachabilityheap; numlreachabilities = 0; } //end of the function AAS_InitReachabilityHeap //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_ShutDownReachabilityHeap( void ) { FreeMemory( reachabilityheap ); numlreachabilities = 0; } //end of the function AAS_ShutDownReachabilityHeap //=========================================================================== // returns a reachability link // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== aas_lreachability_t *AAS_AllocReachability( void ) { aas_lreachability_t *r; if ( !nextreachability ) { return NULL; } //make sure the error message only shows up once if ( !nextreachability->next ) { AAS_Error( "AAS_MAX_REACHABILITYSIZE" ); } // r = nextreachability; nextreachability = nextreachability->next; numlreachabilities++; return r; } //end of the function AAS_AllocReachability //=========================================================================== // frees a reachability link // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_FreeReachability( aas_lreachability_t *lreach ) { memset( lreach, 0, sizeof( aas_lreachability_t ) ); lreach->next = nextreachability; nextreachability = lreach; numlreachabilities--; } //end of the function AAS_FreeReachability //=========================================================================== // returns qtrue if the area has reachability links // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaReachability( int areanum ) { if ( areanum < 0 || areanum >= ( *aasworld ).numareas ) { AAS_Error( "AAS_AreaReachability: areanum %d out of range", areanum ); return 0; } //end if // RF, if this area is disabled, then fail if ( ( *aasworld ).areasettings[areanum].areaflags & AREA_DISABLED ) { return 0; } return ( *aasworld ).areasettings[areanum].numreachableareas; } //end of the function AAS_AreaReachability //=========================================================================== // returns the surface area of the given face // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_FaceArea( aas_face_t *face ) { int i, edgenum, side; float total; vec_t *v; vec3_t d1, d2, cross; aas_edge_t *edge; edgenum = ( *aasworld ).edgeindex[face->firstedge]; side = edgenum < 0; edge = &( *aasworld ).edges[abs( edgenum )]; v = ( *aasworld ).vertexes[edge->v[side]]; total = 0; for ( i = 1; i < face->numedges - 1; i++ ) { edgenum = ( *aasworld ).edgeindex[face->firstedge + i]; side = edgenum < 0; edge = &( *aasworld ).edges[abs( edgenum )]; VectorSubtract( ( *aasworld ).vertexes[edge->v[side]], v, d1 ); VectorSubtract( ( *aasworld ).vertexes[edge->v[!side]], v, d2 ); CrossProduct( d1, d2, cross ); total += 0.5 * VectorLength( cross ); } //end for return total; } //end of the function AAS_FaceArea //=========================================================================== // returns the volume of an area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_AreaVolume( int areanum ) { int i, edgenum, facenum; vec_t d, a, volume; vec3_t corner; aas_plane_t *plane; aas_edge_t *edge; aas_face_t *face; aas_area_t *area; area = &( *aasworld ).areas[areanum]; facenum = ( *aasworld ).faceindex[area->firstface]; face = &( *aasworld ).faces[abs( facenum )]; edgenum = ( *aasworld ).edgeindex[face->firstedge]; edge = &( *aasworld ).edges[abs( edgenum )]; // VectorCopy( ( *aasworld ).vertexes[edge->v[0]], corner ); //make tetrahedrons to all other faces volume = 0; for ( i = 0; i < area->numfaces; i++ ) { facenum = abs( ( *aasworld ).faceindex[area->firstface + i] ); face = &( *aasworld ).faces[facenum]; plane = &( *aasworld ).planes[face->planenum]; d = -( DotProduct( corner, plane->normal ) - plane->dist ); a = AAS_FaceArea( face ); volume += d * a; } //end for volume /= 3; return volume; } //end of the function AAS_AreaVolume //=========================================================================== // returns the surface area of all ground faces together of the area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_AreaGroundFaceArea( int areanum ) { int i; float total; aas_area_t *area; aas_face_t *face; total = 0; area = &( *aasworld ).areas[areanum]; for ( i = 0; i < area->numfaces; i++ ) { face = &( *aasworld ).faces[abs( ( *aasworld ).faceindex[area->firstface + i] )]; if ( !( face->faceflags & FACE_GROUND ) ) { continue; } // total += AAS_FaceArea( face ); } //end for return total; } //end of the function AAS_AreaGroundFaceArea //=========================================================================== // returns the center of a face // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_FaceCenter( int facenum, vec3_t center ) { int i; float scale; aas_face_t *face; aas_edge_t *edge; face = &( *aasworld ).faces[facenum]; VectorClear( center ); for ( i = 0; i < face->numedges; i++ ) { edge = &( *aasworld ).edges[abs( ( *aasworld ).edgeindex[face->firstedge + i] )]; VectorAdd( center, ( *aasworld ).vertexes[edge->v[0]], center ); VectorAdd( center, ( *aasworld ).vertexes[edge->v[1]], center ); } //end for scale = 0.5 / face->numedges; VectorScale( center, scale, center ); } //end of the function AAS_FaceCenter //=========================================================================== // returns the maximum distance a player can fall before being damaged // damage = deltavelocity*deltavelocity * 0.0001 // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_FallDamageDistance( void ) { float maxzvelocity, gravity, t; maxzvelocity = sqrt( 30 * 10000 ); gravity = aassettings.sv_gravity; t = maxzvelocity / gravity; return 0.5 * gravity * t * t; } //end of the function AAS_FallDamageDistance //=========================================================================== // distance = 0.5 * gravity * t * t // vel = t * gravity // damage = vel * vel * 0.0001 // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_FallDelta( float distance ) { float t, delta, gravity; gravity = aassettings.sv_gravity; t = sqrt( fabs( distance ) * 2 / gravity ); delta = t * gravity; return delta * delta * 0.0001; } //end of the function AAS_FallDelta //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_MaxJumpHeight( float sv_jumpvel ) { float sv_gravity; sv_gravity = aassettings.sv_gravity; //maximum height a player can jump with the given initial z velocity return 0.5 * sv_gravity * ( sv_jumpvel / sv_gravity ) * ( sv_jumpvel / sv_gravity ); } //end of the function MaxJumpHeight //=========================================================================== // returns true if a player can only crouch in the area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== float AAS_MaxJumpDistance( float sv_jumpvel ) { float sv_gravity, sv_maxvelocity, t; sv_gravity = aassettings.sv_gravity; sv_maxvelocity = aassettings.sv_maxvelocity; //time a player takes to fall the height t = sqrt( MAX_JUMPFALLHEIGHT / ( 0.5 * sv_gravity ) ); //maximum distance return sv_maxvelocity * ( t + sv_jumpvel / sv_gravity ); } //end of the function AAS_MaxJumpDistance //=========================================================================== // returns true if a player can only crouch in the area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaCrouch( int areanum ) { if ( !( ( *aasworld ).areasettings[areanum].presencetype & PRESENCE_NORMAL ) ) { return qtrue; } else { return qfalse;} } //end of the function AAS_AreaCrouch //=========================================================================== // returns qtrue if it is possible to swim in the area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaSwim( int areanum ) { if ( ( *aasworld ).areasettings[areanum].areaflags & AREA_LIQUID ) { return qtrue; } else { return qfalse;} } //end of the function AAS_AreaSwim //=========================================================================== // returns qtrue if the area contains a liquid // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaLiquid( int areanum ) { if ( ( *aasworld ).areasettings[areanum].areaflags & AREA_LIQUID ) { return qtrue; } else { return qfalse;} } //end of the function AAS_AreaLiquid //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaLava( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_LAVA ); } //end of the function AAS_AreaLava //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaSlime( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_SLIME ); } //end of the function AAS_AreaSlime //=========================================================================== // returns qtrue if the area contains ground faces // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaGrounded( int areanum ) { return ( ( *aasworld ).areasettings[areanum].areaflags & AREA_GROUNDED ); } //end of the function AAS_AreaGround //=========================================================================== // returns true if the area contains ladder faces // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaLadder( int areanum ) { return ( ( *aasworld ).areasettings[areanum].areaflags & AREA_LADDER ); } //end of the function AAS_AreaLadder //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaJumpPad( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_JUMPPAD ); } //end of the function AAS_AreaJumpPad //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaTeleporter( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_TELEPORTER ); } //end of the function AAS_AreaTeleporter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaDoNotEnter( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_DONOTENTER ); } //end of the function AAS_AreaDoNotEnter //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_AreaDoNotEnterLarge( int areanum ) { return ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_DONOTENTER_LARGE ); } //end of the function AAS_AreaDoNotEnter //=========================================================================== // returns the time it takes perform a barrier jump // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== unsigned short int AAS_BarrierJumpTravelTime( void ) { return aassettings.sv_jumpvel / ( aassettings.sv_gravity * 0.1 ); } //end op the function AAS_BarrierJumpTravelTime //=========================================================================== // returns true if there already exists a reachability from area1 to area2 // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== qboolean AAS_ReachabilityExists( int area1num, int area2num ) { aas_lreachability_t *r; for ( r = areareachability[area1num]; r; r = r->next ) { if ( r->areanum == area2num ) { return qtrue; } } //end for return qfalse; } //end of the function AAS_ReachabilityExists //=========================================================================== // returns true if there is a solid just after the end point when going // from start to end // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_NearbySolidOrGap( vec3_t start, vec3_t end ) { vec3_t dir, testpoint; int areanum; VectorSubtract( end, start, dir ); dir[2] = 0; VectorNormalize( dir ); VectorMA( end, 48, dir, testpoint ); areanum = AAS_PointAreaNum( testpoint ); if ( !areanum ) { testpoint[2] += 16; areanum = AAS_PointAreaNum( testpoint ); if ( !areanum ) { return qtrue; } } //end if VectorMA( end, 64, dir, testpoint ); areanum = AAS_PointAreaNum( testpoint ); if ( areanum ) { if ( !AAS_AreaSwim( areanum ) && !AAS_AreaGrounded( areanum ) ) { return qtrue; } } //end if return qfalse; } //end of the function AAS_SolidGapTime //=========================================================================== // searches for swim reachabilities between adjacent areas // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_Swim( int area1num, int area2num ) { int i, j, face1num, face2num, side1; aas_area_t *area1, *area2; aas_areasettings_t *areasettings; aas_lreachability_t *lreach; aas_face_t *face1; aas_plane_t *plane; vec3_t start; if ( !AAS_AreaSwim( area1num ) || !AAS_AreaSwim( area2num ) ) { return qfalse; } //if the second area is crouch only if ( !( ( *aasworld ).areasettings[area2num].presencetype & PRESENCE_NORMAL ) ) { return qfalse; } area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; //if the areas are not near anough for ( i = 0; i < 3; i++ ) { if ( area1->mins[i] > area2->maxs[i] + 10 ) { return qfalse; } if ( area1->maxs[i] < area2->mins[i] - 10 ) { return qfalse; } } //end for //find a shared face and create a reachability link for ( i = 0; i < area1->numfaces; i++ ) { face1num = ( *aasworld ).faceindex[area1->firstface + i]; side1 = face1num < 0; face1num = abs( face1num ); // for ( j = 0; j < area2->numfaces; j++ ) { face2num = abs( ( *aasworld ).faceindex[area2->firstface + j] ); // if ( face1num == face2num ) { AAS_FaceCenter( face1num, start ); // if ( AAS_PointContents( start ) & ( CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER ) ) { // face1 = &( *aasworld ).faces[face1num]; areasettings = &( *aasworld ).areasettings[area1num]; //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = face1num; lreach->edgenum = 0; VectorCopy( start, lreach->start ); plane = &( *aasworld ).planes[face1->planenum ^ side1]; VectorMA( lreach->start, INSIDEUNITS, plane->normal, lreach->end ); lreach->traveltype = TRAVEL_SWIM; lreach->traveltime = 1; //if the volume of the area is rather small if ( AAS_AreaVolume( area2num ) < 800 ) { lreach->traveltime += 200; } //if (!(AAS_PointContents(start) & MASK_WATER)) lreach->traveltime += 500; //link the reachability lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; reach_swim++; return qtrue; } //end if } //end if } //end for } //end for return qfalse; } //end of the function AAS_Reachability_Swim //=========================================================================== // searches for reachabilities between adjacent areas with equal floor // heights // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_EqualFloorHeight( int area1num, int area2num ) { int i, j, edgenum, edgenum1, edgenum2, foundreach, side; float height, bestheight, length, bestlength; vec3_t dir, start, end, normal, invgravity, gravitydirection = {0, 0, -1}; vec3_t edgevec; aas_area_t *area1, *area2; aas_face_t *face1, *face2; aas_edge_t *edge; aas_plane_t *plane2; aas_lreachability_t lr, *lreach; if ( !AAS_AreaGrounded( area1num ) || !AAS_AreaGrounded( area2num ) ) { return qfalse; } area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; //if the areas are not near anough in the x-y direction for ( i = 0; i < 2; i++ ) { if ( area1->mins[i] > area2->maxs[i] + 10 ) { return qfalse; } if ( area1->maxs[i] < area2->mins[i] - 10 ) { return qfalse; } } //end for //if area 2 is too high above area 1 if ( area2->mins[2] > area1->maxs[2] ) { return qfalse; } // VectorCopy( gravitydirection, invgravity ); VectorInverse( invgravity ); // bestheight = 99999; bestlength = 0; foundreach = qfalse; memset( &lr, 0, sizeof( aas_lreachability_t ) ); //make the compiler happy // //check if the areas have ground faces with a common edge //if existing use the lowest common edge for a reachability link for ( i = 0; i < area1->numfaces; i++ ) { face1 = &( *aasworld ).faces[abs( ( *aasworld ).faceindex[area1->firstface + i] )]; if ( !( face1->faceflags & FACE_GROUND ) ) { continue; } // for ( j = 0; j < area2->numfaces; j++ ) { face2 = &( *aasworld ).faces[abs( ( *aasworld ).faceindex[area2->firstface + j] )]; if ( !( face2->faceflags & FACE_GROUND ) ) { continue; } //if there is a common edge for ( edgenum1 = 0; edgenum1 < face1->numedges; edgenum1++ ) { for ( edgenum2 = 0; edgenum2 < face2->numedges; edgenum2++ ) { if ( abs( ( *aasworld ).edgeindex[face1->firstedge + edgenum1] ) != abs( ( *aasworld ).edgeindex[face2->firstedge + edgenum2] ) ) { continue; } edgenum = ( *aasworld ).edgeindex[face1->firstedge + edgenum1]; side = edgenum < 0; edge = &( *aasworld ).edges[abs( edgenum )]; //get the length of the edge VectorSubtract( ( *aasworld ).vertexes[edge->v[1]], ( *aasworld ).vertexes[edge->v[0]], dir ); length = VectorLength( dir ); //get the start point VectorAdd( ( *aasworld ).vertexes[edge->v[0]], ( *aasworld ).vertexes[edge->v[1]], start ); VectorScale( start, 0.5, start ); VectorCopy( start, end ); //get the end point several units inside area2 //and the start point several units inside area1 //NOTE: normal is pointing into area2 because the //face edges are stored counter clockwise VectorSubtract( ( *aasworld ).vertexes[edge->v[side]], ( *aasworld ).vertexes[edge->v[!side]], edgevec ); plane2 = &( *aasworld ).planes[face2->planenum]; CrossProduct( edgevec, plane2->normal, normal ); VectorNormalize( normal ); // //VectorMA(start, -1, normal, start); VectorMA( end, INSIDEUNITS_WALKEND, normal, end ); VectorMA( start, INSIDEUNITS_WALKSTART, normal, start ); end[2] += 0.125; // height = DotProduct( invgravity, start ); //NOTE: if there's nearby solid or a gap area after this area //disabled this crap //if (AAS_NearbySolidOrGap(start, end)) height += 200; //NOTE: disabled because it disables reachabilities to very small areas //if (AAS_PointAreaNum(end) != area2num) continue; //get the longest lowest edge if ( height < bestheight || ( height < bestheight + 1 && length > bestlength ) ) { bestheight = height; bestlength = length; //create a new reachability link lr.areanum = area2num; lr.facenum = 0; lr.edgenum = edgenum; VectorCopy( start, lr.start ); VectorCopy( end, lr.end ); lr.traveltype = TRAVEL_WALK; lr.traveltime = 1; foundreach = qtrue; } //end if } //end for } //end for } //end for } //end for if ( foundreach ) { //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = lr.areanum; lreach->facenum = lr.facenum; lreach->edgenum = lr.edgenum; VectorCopy( lr.start, lreach->start ); VectorCopy( lr.end, lreach->end ); lreach->traveltype = lr.traveltype; lreach->traveltime = lr.traveltime; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //if going into a crouch area if ( !AAS_AreaCrouch( area1num ) && AAS_AreaCrouch( area2num ) ) { lreach->traveltime += STARTCROUCH_TIME; } //end if /* //NOTE: if there's nearby solid or a gap area after this area if (!AAS_NearbySolidOrGap(lreach->start, lreach->end)) { lreach->traveltime += 100; } //end if */ //avoid rather small areas //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; // reach_equalfloor++; return qtrue; } //end if return qfalse; } //end of the function AAS_Reachability_EqualFloorHeight //=========================================================================== // searches step, barrier, waterjump and walk off ledge reachabilities // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge( int area1num, int area2num ) { int i, j, k, l, edge1num, edge2num; int ground_bestarea2groundedgenum, ground_foundreach; int water_bestarea2groundedgenum, water_foundreach; int side1, area1swim, faceside1, groundface1num; float dist, dist1, dist2, diff, invgravitydot, ortdot; float x1, x2, x3, x4, y1, y2, y3, y4, tmp, y; float length, ground_bestlength, water_bestlength, ground_bestdist, water_bestdist; vec3_t v1, v2, v3, v4, tmpv, p1area1, p1area2, p2area1, p2area2; vec3_t normal, ort, edgevec, start, end, dir; vec3_t ground_beststart, ground_bestend, ground_bestnormal; vec3_t water_beststart, water_bestend, water_bestnormal; vec3_t invgravity = {0, 0, 1}; vec3_t testpoint; aas_plane_t *plane; aas_area_t *area1, *area2; aas_face_t *groundface1, *groundface2, *ground_bestface1, *water_bestface1; aas_edge_t *edge1, *edge2; aas_lreachability_t *lreach; aas_trace_t trace; //must be able to walk or swim in the first area if ( !AAS_AreaGrounded( area1num ) && !AAS_AreaSwim( area1num ) ) { return qfalse; } // if ( !AAS_AreaGrounded( area2num ) && !AAS_AreaSwim( area2num ) ) { return qfalse; } // area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; //if the first area contains a liquid area1swim = AAS_AreaSwim( area1num ); //if the areas are not near anough in the x-y direction for ( i = 0; i < 2; i++ ) { if ( area1->mins[i] > area2->maxs[i] + 10 ) { return qfalse; } if ( area1->maxs[i] < area2->mins[i] - 10 ) { return qfalse; } } //end for // ground_foundreach = qfalse; ground_bestdist = 99999; ground_bestlength = 0; ground_bestarea2groundedgenum = 0; // water_foundreach = qfalse; water_bestdist = 99999; water_bestlength = 0; water_bestarea2groundedgenum = 0; // for ( i = 0; i < area1->numfaces; i++ ) { groundface1num = ( *aasworld ).faceindex[area1->firstface + i]; faceside1 = groundface1num < 0; groundface1 = &( *aasworld ).faces[abs( groundface1num )]; //if this isn't a ground face if ( !( groundface1->faceflags & FACE_GROUND ) ) { //if we can swim in the first area if ( area1swim ) { //face plane must be more or less horizontal plane = &( *aasworld ).planes[groundface1->planenum ^ ( !faceside1 )]; if ( DotProduct( plane->normal, invgravity ) < 0.7 ) { continue; } } //end if else { //if we can't swim in the area it must be a ground face continue; } //end else } //end if // for ( k = 0; k < groundface1->numedges; k++ ) { edge1num = ( *aasworld ).edgeindex[groundface1->firstedge + k]; side1 = ( edge1num < 0 ); //NOTE: for water faces we must take the side area 1 is // on into account because the face is shared and doesn't // have to be oriented correctly if ( !( groundface1->faceflags & FACE_GROUND ) ) { side1 = ( side1 == faceside1 ); } edge1num = abs( edge1num ); edge1 = &( *aasworld ).edges[edge1num]; //vertexes of the edge VectorCopy( ( *aasworld ).vertexes[edge1->v[!side1]], v1 ); VectorCopy( ( *aasworld ).vertexes[edge1->v[side1]], v2 ); //get a vertical plane through the edge //NOTE: normal is pointing into area 2 because the //face edges are stored counter clockwise VectorSubtract( v2, v1, edgevec ); CrossProduct( edgevec, invgravity, normal ); VectorNormalize( normal ); dist = DotProduct( normal, v1 ); //check the faces from the second area for ( j = 0; j < area2->numfaces; j++ ) { groundface2 = &( *aasworld ).faces[abs( ( *aasworld ).faceindex[area2->firstface + j] )]; //must be a ground face if ( !( groundface2->faceflags & FACE_GROUND ) ) { continue; } //check the edges of this ground face for ( l = 0; l < groundface2->numedges; l++ ) { edge2num = abs( ( *aasworld ).edgeindex[groundface2->firstedge + l] ); edge2 = &( *aasworld ).edges[edge2num]; //vertexes of the edge VectorCopy( ( *aasworld ).vertexes[edge2->v[0]], v3 ); VectorCopy( ( *aasworld ).vertexes[edge2->v[1]], v4 ); //check the distance between the two points and the vertical plane //through the edge of area1 diff = DotProduct( normal, v3 ) - dist; if ( diff < -0.1 || diff > 0.1 ) { continue; } diff = DotProduct( normal, v4 ) - dist; if ( diff < -0.1 || diff > 0.1 ) { continue; } // //project the two ground edges into the step side plane //and calculate the shortest distance between the two //edges if they overlap in the direction orthogonal to //the gravity direction CrossProduct( invgravity, normal, ort ); invgravitydot = DotProduct( invgravity, invgravity ); ortdot = DotProduct( ort, ort ); //projection into the step plane //NOTE: since gravity is vertical this is just the z coordinate y1 = v1[2]; //DotProduct(v1, invgravity) / invgravitydot; y2 = v2[2]; //DotProduct(v2, invgravity) / invgravitydot; y3 = v3[2]; //DotProduct(v3, invgravity) / invgravitydot; y4 = v4[2]; //DotProduct(v4, invgravity) / invgravitydot; // x1 = DotProduct( v1, ort ) / ortdot; x2 = DotProduct( v2, ort ) / ortdot; x3 = DotProduct( v3, ort ) / ortdot; x4 = DotProduct( v4, ort ) / ortdot; // if ( x1 > x2 ) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; VectorCopy( v1, tmpv ); VectorCopy( v2, v1 ); VectorCopy( tmpv, v2 ); } //end if if ( x3 > x4 ) { tmp = x3; x3 = x4; x4 = tmp; tmp = y3; y3 = y4; y4 = tmp; VectorCopy( v3, tmpv ); VectorCopy( v4, v3 ); VectorCopy( tmpv, v4 ); } //end if //if the two projected edge lines have no overlap if ( x2 <= x3 || x4 <= x1 ) { // Log_Write("lines no overlap: from area %d to %d\r\n", area1num, area2num); continue; } //end if //if the two lines fully overlap if ( ( x1 - 0.5 < x3 && x4 < x2 + 0.5 ) && ( x3 - 0.5 < x1 && x2 < x4 + 0.5 ) ) { dist1 = y3 - y1; dist2 = y4 - y2; VectorCopy( v1, p1area1 ); VectorCopy( v2, p2area1 ); VectorCopy( v3, p1area2 ); VectorCopy( v4, p2area2 ); } //end if else { //if the points are equal if ( x1 > x3 - 0.1 && x1 < x3 + 0.1 ) { dist1 = y3 - y1; VectorCopy( v1, p1area1 ); VectorCopy( v3, p1area2 ); } //end if else if ( x1 < x3 ) { y = y1 + ( x3 - x1 ) * ( y2 - y1 ) / ( x2 - x1 ); dist1 = y3 - y; VectorCopy( v3, p1area1 ); p1area1[2] = y; VectorCopy( v3, p1area2 ); } //end if else { y = y3 + ( x1 - x3 ) * ( y4 - y3 ) / ( x4 - x3 ); dist1 = y - y1; VectorCopy( v1, p1area1 ); VectorCopy( v1, p1area2 ); p1area2[2] = y; } //end if //if the points are equal if ( x2 > x4 - 0.1 && x2 < x4 + 0.1 ) { dist2 = y4 - y2; VectorCopy( v2, p2area1 ); VectorCopy( v4, p2area2 ); } //end if else if ( x2 < x4 ) { y = y3 + ( x2 - x3 ) * ( y4 - y3 ) / ( x4 - x3 ); dist2 = y - y2; VectorCopy( v2, p2area1 ); VectorCopy( v2, p2area2 ); p2area2[2] = y; } //end if else { y = y1 + ( x4 - x1 ) * ( y2 - y1 ) / ( x2 - x1 ); dist2 = y4 - y; VectorCopy( v4, p2area1 ); p2area1[2] = y; VectorCopy( v4, p2area2 ); } //end else } //end else //if both distances are pretty much equal //then we take the middle of the points if ( dist1 > dist2 - 1 && dist1 < dist2 + 1 ) { dist = dist1; VectorAdd( p1area1, p2area1, start ); VectorScale( start, 0.5, start ); VectorAdd( p1area2, p2area2, end ); VectorScale( end, 0.5, end ); } //end if else if ( dist1 < dist2 ) { dist = dist1; VectorCopy( p1area1, start ); VectorCopy( p1area2, end ); } //end else if else { dist = dist2; VectorCopy( p2area1, start ); VectorCopy( p2area2, end ); } //end else //get the length of the overlapping part of the edges of the two areas VectorSubtract( p2area2, p1area2, dir ); length = VectorLength( dir ); // if ( groundface1->faceflags & FACE_GROUND ) { //if the vertical distance is smaller if ( dist < ground_bestdist || //or the vertical distance is pretty much the same //but the overlapping part of the edges is longer ( dist < ground_bestdist + 1 && length > ground_bestlength ) ) { ground_bestdist = dist; ground_bestlength = length; ground_foundreach = qtrue; ground_bestarea2groundedgenum = edge1num; ground_bestface1 = groundface1; //best point towards area1 VectorCopy( start, ground_beststart ); //normal is pointing into area2 VectorCopy( normal, ground_bestnormal ); //best point towards area2 VectorCopy( end, ground_bestend ); } //end if } //end if else { //if the vertical distance is smaller if ( dist < water_bestdist || //or the vertical distance is pretty much the same //but the overlapping part of the edges is longer ( dist < water_bestdist + 1 && length > water_bestlength ) ) { water_bestdist = dist; water_bestlength = length; water_foundreach = qtrue; water_bestarea2groundedgenum = edge1num; water_bestface1 = groundface1; //best point towards area1 VectorCopy( start, water_beststart ); //normal is pointing into area2 VectorCopy( normal, water_bestnormal ); //best point towards area2 VectorCopy( end, water_bestend ); } //end if } //end else } //end for } //end for } //end for } //end for // // NOTE: swim reachabilities are already filtered out // // Steps // // --------- // | step height -> TRAVEL_WALK //--------| // // --------- //~~~~~~~~| step height and low water -> TRAVEL_WALK //--------| // //~~~~~~~~~~~~~~~~~~ // --------- // | step height and low water up to the step -> TRAVEL_WALK //--------| // //check for a step reachability if ( ground_foundreach ) { //if area2 is higher but lower than the maximum step height //NOTE: ground_bestdist >= 0 also catches equal floor reachabilities if ( ground_bestdist >= 0 && ground_bestdist < aassettings.sv_maxstep ) { //create walk reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorMA( ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start ); VectorMA( ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end ); lreach->traveltype = TRAVEL_WALK; lreach->traveltime = 0; //1; //if going into a crouch area if ( !AAS_AreaCrouch( area1num ) && AAS_AreaCrouch( area2num ) ) { lreach->traveltime += STARTCROUCH_TIME; } //end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //NOTE: if there's nearby solid or a gap area after this area /* if (!AAS_NearbySolidOrGap(lreach->start, lreach->end)) { lreach->traveltime += 100; } //end if */ //avoid rather small areas //if (AAS_AreaGroundFaceArea(lreach->areanum) < 500) lreach->traveltime += 100; // reach_step++; return qtrue; } //end if } //end if // // Water Jumps // // --------- // | //~~~~~~~~| // | // | higher than step height and water up to waterjump height -> TRAVEL_WATERJUMP //--------| // //~~~~~~~~~~~~~~~~~~ // --------- // | // | // | // | higher than step height and low water up to the step -> TRAVEL_WATERJUMP //--------| // //check for a waterjump reachability if ( water_foundreach ) { //get a test point a little bit towards area1 VectorMA( water_bestend, -INSIDEUNITS, water_bestnormal, testpoint ); //go down the maximum waterjump height testpoint[2] -= aassettings.sv_maxwaterjump; //if there IS water the sv_maxwaterjump height below the bestend point if ( ( *aasworld ).areasettings[AAS_PointAreaNum( testpoint )].areaflags & AREA_LIQUID ) { //don't create rediculous water jump reachabilities from areas very far below //the water surface if ( water_bestdist < aassettings.sv_maxwaterjump + 24 ) { //waterjumping from or towards a crouch only area is not possible in Quake2 if ( ( ( *aasworld ).areasettings[area1num].presencetype & PRESENCE_NORMAL ) && ( ( *aasworld ).areasettings[area2num].presencetype & PRESENCE_NORMAL ) ) { //create water jump reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = water_bestarea2groundedgenum; VectorCopy( water_beststart, lreach->start ); VectorMA( water_bestend, INSIDEUNITS_WATERJUMP, water_bestnormal, lreach->end ); lreach->traveltype = TRAVEL_WATERJUMP; lreach->traveltime = WATERJUMP_TIME; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //we've got another waterjump reachability reach_waterjump++; return qtrue; } //end if } //end if } //end if } //end if // // Barrier Jumps // // --------- // | // | // | // | higher than step height lower than barrier height -> TRAVEL_BARRIERJUMP //--------| // // --------- // | // | // | //~~~~~~~~| higher than step height lower than barrier height //--------| and a thin layer of water in the area to jump from -> TRAVEL_BARRIERJUMP // //check for a barrier jump reachability if ( ground_foundreach ) { //if area2 is higher but lower than the maximum barrier jump height if ( ground_bestdist > 0 && ground_bestdist < aassettings.sv_maxbarrier ) { //if no water in area1 or a very thin layer of water on the ground if ( !water_foundreach || ( ground_bestdist - water_bestdist < 16 ) ) { //cannot perform a barrier jump towards or from a crouch area in Quake2 if ( !AAS_AreaCrouch( area1num ) && !AAS_AreaCrouch( area2num ) ) { //create barrier jump reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorMA( ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start ); VectorMA( ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end ); lreach->traveltype = TRAVEL_BARRIERJUMP; lreach->traveltime = BARRIERJUMP_TIME; //AAS_BarrierJumpTravelTime(); lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //we've got another barrierjump reachability reach_barrier++; return qtrue; } //end if } //end if } //end if } //end if // // Walk and Walk Off Ledge // //--------| // | can walk or step back -> TRAVEL_WALK // --------- // //--------| // | // | // | // | cannot walk/step back -> TRAVEL_WALKOFFLEDGE // --------- // //--------| // | // |~~~~~~~~ // | // | cannot step back but can waterjump back -> TRAVEL_WALKOFFLEDGE // --------- FIXME: create TRAVEL_WALK reach?? // //check for a walk or walk off ledge reachability if ( ground_foundreach ) { if ( ground_bestdist < 0 ) { if ( ground_bestdist > -aassettings.sv_maxstep ) { //create walk reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorMA( ground_beststart, INSIDEUNITS_WALKSTART, ground_bestnormal, lreach->start ); // Ridah // VectorMA(ground_bestend, INSIDEUNITS_WALKEND, ground_bestnormal, lreach->end); VectorMA( ground_bestend, INSIDEUNITS_WALKOFFLEDGEEND, ground_bestnormal, lreach->end ); lreach->traveltype = TRAVEL_WALK; lreach->traveltime = 1; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //we've got another walk reachability reach_walk++; return qtrue; } //end if //trace a bounding box vertically to check for solids VectorMA( ground_bestend, INSIDEUNITS, ground_bestnormal, ground_bestend ); VectorCopy( ground_bestend, start ); start[2] = ground_beststart[2]; VectorCopy( ground_bestend, end ); end[2] += 4; trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, -1 ); //if no solids were found if ( !trace.startsolid && trace.fraction >= 1.0 ) { //the trace end point must be in the goal area trace.endpos[2] += 1; if ( AAS_PointAreaNum( trace.endpos ) == area2num ) { //create a walk off ledge reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = ground_bestarea2groundedgenum; VectorCopy( ground_beststart, lreach->start ); VectorCopy( ground_bestend, lreach->end ); lreach->traveltype = TRAVEL_WALKOFFLEDGE; lreach->traveltime = STARTWALKOFFLEDGE_TIME + fabs( ground_bestdist ) * 50 / aassettings.sv_gravity; //if falling from too high and not falling into water if ( !AAS_AreaSwim( area2num ) && !AAS_AreaJumpPad( area2num ) ) { if ( AAS_FallDelta( ground_bestdist ) > FALLDELTA_5DAMAGE ) { lreach->traveltime += FALLDAMAGE_5_TIME; } //end if if ( AAS_FallDelta( ground_bestdist ) > FALLDELTA_10DAMAGE ) { lreach->traveltime += FALLDAMAGE_10_TIME; } //end if } //end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_walkoffledge++; //NOTE: don't create a weapon (rl, bfg) jump reachability here //because it interferes with other reachabilities //like the ladder reachability return qtrue; } //end if } //end if } //end else } //end if return qfalse; } //end of the function AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge //=========================================================================== // returns the distance between the two vectors // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== /* Ridah, moved to q_math.c float VectorDistance(vec3_t v1, vec3_t v2) { vec3_t dir; VectorSubtract(v2, v1, dir); return VectorLength(dir); } //end of the function VectorDistance */ //=========================================================================== // returns true if the first vector is between the last two vectors // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int VectorBetweenVectors( vec3_t v, vec3_t v1, vec3_t v2 ) { vec3_t dir1, dir2; VectorSubtract( v, v1, dir1 ); VectorSubtract( v, v2, dir2 ); return ( DotProduct( dir1, dir2 ) <= 0 ); } //end of the function VectorBetweenVectors //=========================================================================== // returns the mid point between the two vectors // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void VectorMiddle( vec3_t v1, vec3_t v2, vec3_t middle ) { VectorAdd( v1, v2, middle ); VectorScale( middle, 0.5, middle ); } //end of the function VectorMiddle //=========================================================================== // calculate a range of points closest to each other on both edges // // Parameter: beststart1 start of the range of points on edge v1-v2 // beststart2 end of the range of points on edge v1-v2 // bestend1 start of the range of points on edge v3-v4 // bestend2 end of the range of points on edge v3-v4 // bestdist best distance so far // Returns: - // Changes Globals: - //=========================================================================== /* float AAS_ClosestEdgePoints(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, aas_plane_t *plane1, aas_plane_t *plane2, vec3_t beststart, vec3_t bestend, float bestdist) { vec3_t dir1, dir2, p1, p2, p3, p4; float a1, a2, b1, b2, dist; int founddist; //edge vectors VectorSubtract(v2, v1, dir1); VectorSubtract(v4, v3, dir2); //get the horizontal directions dir1[2] = 0; dir2[2] = 0; // // p1 = point on an edge vector of area2 closest to v1 // p2 = point on an edge vector of area2 closest to v2 // p3 = point on an edge vector of area1 closest to v3 // p4 = point on an edge vector of area1 closest to v4 // if (dir2[0]) { a2 = dir2[1] / dir2[0]; b2 = v3[1] - a2 * v3[0]; //point on the edge vector of area2 closest to v1 p1[0] = (DotProduct(v1, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0]; p1[1] = a2 * p1[0] + b2; //point on the edge vector of area2 closest to v2 p2[0] = (DotProduct(v2, dir2) - (a2 * dir2[0] + b2 * dir2[1])) / dir2[0]; p2[1] = a2 * p2[0] + b2; } //end if else { //point on the edge vector of area2 closest to v1 p1[0] = v3[0]; p1[1] = v1[1]; //point on the edge vector of area2 closest to v2 p2[0] = v3[0]; p2[1] = v2[1]; } //end else // if (dir1[0]) { // a1 = dir1[1] / dir1[0]; b1 = v1[1] - a1 * v1[0]; //point on the edge vector of area1 closest to v3 p3[0] = (DotProduct(v3, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0]; p3[1] = a1 * p3[0] + b1; //point on the edge vector of area1 closest to v4 p4[0] = (DotProduct(v4, dir1) - (a1 * dir1[0] + b1 * dir1[1])) / dir1[0]; p4[1] = a1 * p4[0] + b1; } //end if else { //point on the edge vector of area1 closest to v3 p3[0] = v1[0]; p3[1] = v3[1]; //point on the edge vector of area1 closest to v4 p4[0] = v1[0]; p4[1] = v4[1]; } //end else //start with zero z-coordinates p1[2] = 0; p2[2] = 0; p3[2] = 0; p4[2] = 0; //calculate the z-coordinates from the ground planes p1[2] = (plane2->dist - DotProduct(plane2->normal, p1)) / plane2->normal[2]; p2[2] = (plane2->dist - DotProduct(plane2->normal, p2)) / plane2->normal[2]; p3[2] = (plane1->dist - DotProduct(plane1->normal, p3)) / plane1->normal[2]; p4[2] = (plane1->dist - DotProduct(plane1->normal, p4)) / plane1->normal[2]; // founddist = qfalse; // if (VectorBetweenVectors(p1, v3, v4)) { dist = VectorDistance(v1, p1); if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { VectorMiddle(beststart, v1, beststart); VectorMiddle(bestend, p1, bestend); } //end if else if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart); VectorCopy(p1, bestend); } //end if founddist = qtrue; } //end if if (VectorBetweenVectors(p2, v3, v4)) { dist = VectorDistance(v2, p2); if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { VectorMiddle(beststart, v2, beststart); VectorMiddle(bestend, p2, bestend); } //end if else if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart); VectorCopy(p2, bestend); } //end if founddist = qtrue; } //end else if if (VectorBetweenVectors(p3, v1, v2)) { dist = VectorDistance(v3, p3); if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { VectorMiddle(beststart, p3, beststart); VectorMiddle(bestend, v3, bestend); } //end if else if (dist < bestdist) { bestdist = dist; VectorCopy(p3, beststart); VectorCopy(v3, bestend); } //end if founddist = qtrue; } //end else if if (VectorBetweenVectors(p4, v1, v2)) { dist = VectorDistance(v4, p4); if (dist > bestdist - 0.5 && dist < bestdist + 0.5) { VectorMiddle(beststart, p4, beststart); VectorMiddle(bestend, v4, bestend); } //end if else if (dist < bestdist) { bestdist = dist; VectorCopy(p4, beststart); VectorCopy(v4, bestend); } //end if founddist = qtrue; } //end else if //if no shortest distance was found the shortest distance //is between one of the vertexes of edge1 and one of edge2 if (!founddist) { dist = VectorDistance(v1, v3); if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart); VectorCopy(v3, bestend); } //end if dist = VectorDistance(v1, v4); if (dist < bestdist) { bestdist = dist; VectorCopy(v1, beststart); VectorCopy(v4, bestend); } //end if dist = VectorDistance(v2, v3); if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart); VectorCopy(v3, bestend); } //end if dist = VectorDistance(v2, v4); if (dist < bestdist) { bestdist = dist; VectorCopy(v2, beststart); VectorCopy(v4, bestend); } //end if } //end if return bestdist; } //end of the function AAS_ClosestEdgePoints*/ float AAS_ClosestEdgePoints( vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4, aas_plane_t *plane1, aas_plane_t *plane2, vec3_t beststart1, vec3_t bestend1, vec3_t beststart2, vec3_t bestend2, float bestdist ) { vec3_t dir1, dir2, p1, p2, p3, p4; float a1, a2, b1, b2, dist, dist1, dist2; int founddist; //edge vectors VectorSubtract( v2, v1, dir1 ); VectorSubtract( v4, v3, dir2 ); //get the horizontal directions dir1[2] = 0; dir2[2] = 0; // // p1 = point on an edge vector of area2 closest to v1 // p2 = point on an edge vector of area2 closest to v2 // p3 = point on an edge vector of area1 closest to v3 // p4 = point on an edge vector of area1 closest to v4 // if ( dir2[0] ) { a2 = dir2[1] / dir2[0]; b2 = v3[1] - a2 * v3[0]; //point on the edge vector of area2 closest to v1 p1[0] = ( DotProduct( v1, dir2 ) - ( a2 * dir2[0] + b2 * dir2[1] ) ) / dir2[0]; p1[1] = a2 * p1[0] + b2; //point on the edge vector of area2 closest to v2 p2[0] = ( DotProduct( v2, dir2 ) - ( a2 * dir2[0] + b2 * dir2[1] ) ) / dir2[0]; p2[1] = a2 * p2[0] + b2; } //end if else { //point on the edge vector of area2 closest to v1 p1[0] = v3[0]; p1[1] = v1[1]; //point on the edge vector of area2 closest to v2 p2[0] = v3[0]; p2[1] = v2[1]; } //end else // if ( dir1[0] ) { // a1 = dir1[1] / dir1[0]; b1 = v1[1] - a1 * v1[0]; //point on the edge vector of area1 closest to v3 p3[0] = ( DotProduct( v3, dir1 ) - ( a1 * dir1[0] + b1 * dir1[1] ) ) / dir1[0]; p3[1] = a1 * p3[0] + b1; //point on the edge vector of area1 closest to v4 p4[0] = ( DotProduct( v4, dir1 ) - ( a1 * dir1[0] + b1 * dir1[1] ) ) / dir1[0]; p4[1] = a1 * p4[0] + b1; } //end if else { //point on the edge vector of area1 closest to v3 p3[0] = v1[0]; p3[1] = v3[1]; //point on the edge vector of area1 closest to v4 p4[0] = v1[0]; p4[1] = v4[1]; } //end else //start with zero z-coordinates p1[2] = 0; p2[2] = 0; p3[2] = 0; p4[2] = 0; //calculate the z-coordinates from the ground planes p1[2] = ( plane2->dist - DotProduct( plane2->normal, p1 ) ) / plane2->normal[2]; p2[2] = ( plane2->dist - DotProduct( plane2->normal, p2 ) ) / plane2->normal[2]; p3[2] = ( plane1->dist - DotProduct( plane1->normal, p3 ) ) / plane1->normal[2]; p4[2] = ( plane1->dist - DotProduct( plane1->normal, p4 ) ) / plane1->normal[2]; // founddist = qfalse; // if ( VectorBetweenVectors( p1, v3, v4 ) ) { dist = VectorDistance( v1, p1 ); if ( dist > bestdist - 0.5 && dist < bestdist + 0.5 ) { dist1 = VectorDistance( beststart1, v1 ); dist2 = VectorDistance( beststart2, v1 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( v1, beststart2 ); } } //end if else { if ( dist2 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( v1, beststart1 ); } } //end else dist1 = VectorDistance( bestend1, p1 ); dist2 = VectorDistance( bestend2, p1 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( p1, bestend2 ); } } //end if else { if ( dist2 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( p1, bestend1 ); } } //end else } //end if else if ( dist < bestdist ) { bestdist = dist; VectorCopy( v1, beststart1 ); VectorCopy( v1, beststart2 ); VectorCopy( p1, bestend1 ); VectorCopy( p1, bestend2 ); } //end if founddist = qtrue; } //end if if ( VectorBetweenVectors( p2, v3, v4 ) ) { dist = VectorDistance( v2, p2 ); if ( dist > bestdist - 0.5 && dist < bestdist + 0.5 ) { dist1 = VectorDistance( beststart1, v2 ); dist2 = VectorDistance( beststart2, v2 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( v2, beststart2 ); } } //end if else { if ( dist2 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( v2, beststart1 ); } } //end else dist1 = VectorDistance( bestend1, p2 ); dist2 = VectorDistance( bestend2, p2 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( p2, bestend2 ); } } //end if else { if ( dist2 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( p2, bestend1 ); } } //end else } //end if else if ( dist < bestdist ) { bestdist = dist; VectorCopy( v2, beststart1 ); VectorCopy( v2, beststart2 ); VectorCopy( p2, bestend1 ); VectorCopy( p2, bestend2 ); } //end if founddist = qtrue; } //end else if if ( VectorBetweenVectors( p3, v1, v2 ) ) { dist = VectorDistance( v3, p3 ); if ( dist > bestdist - 0.5 && dist < bestdist + 0.5 ) { dist1 = VectorDistance( beststart1, p3 ); dist2 = VectorDistance( beststart2, p3 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( p3, beststart2 ); } } //end if else { if ( dist2 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( p3, beststart1 ); } } //end else dist1 = VectorDistance( bestend1, v3 ); dist2 = VectorDistance( bestend2, v3 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( v3, bestend2 ); } } //end if else { if ( dist2 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( v3, bestend1 ); } } //end else } //end if else if ( dist < bestdist ) { bestdist = dist; VectorCopy( p3, beststart1 ); VectorCopy( p3, beststart2 ); VectorCopy( v3, bestend1 ); VectorCopy( v3, bestend2 ); } //end if founddist = qtrue; } //end else if if ( VectorBetweenVectors( p4, v1, v2 ) ) { dist = VectorDistance( v4, p4 ); if ( dist > bestdist - 0.5 && dist < bestdist + 0.5 ) { dist1 = VectorDistance( beststart1, p4 ); dist2 = VectorDistance( beststart2, p4 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( p4, beststart2 ); } } //end if else { if ( dist2 > VectorDistance( beststart1, beststart2 ) ) { VectorCopy( p4, beststart1 ); } } //end else dist1 = VectorDistance( bestend1, v4 ); dist2 = VectorDistance( bestend2, v4 ); if ( dist1 > dist2 ) { if ( dist1 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( v4, bestend2 ); } } //end if else { if ( dist2 > VectorDistance( bestend1, bestend2 ) ) { VectorCopy( v4, bestend1 ); } } //end else } //end if else if ( dist < bestdist ) { bestdist = dist; VectorCopy( p4, beststart1 ); VectorCopy( p4, beststart2 ); VectorCopy( v4, bestend1 ); VectorCopy( v4, bestend2 ); } //end if founddist = qtrue; } //end else if //if no shortest distance was found the shortest distance //is between one of the vertexes of edge1 and one of edge2 if ( !founddist ) { dist = VectorDistance( v1, v3 ); if ( dist < bestdist ) { bestdist = dist; VectorCopy( v1, beststart1 ); VectorCopy( v1, beststart2 ); VectorCopy( v3, bestend1 ); VectorCopy( v3, bestend2 ); } //end if dist = VectorDistance( v1, v4 ); if ( dist < bestdist ) { bestdist = dist; VectorCopy( v1, beststart1 ); VectorCopy( v1, beststart2 ); VectorCopy( v4, bestend1 ); VectorCopy( v4, bestend2 ); } //end if dist = VectorDistance( v2, v3 ); if ( dist < bestdist ) { bestdist = dist; VectorCopy( v2, beststart1 ); VectorCopy( v2, beststart2 ); VectorCopy( v3, bestend1 ); VectorCopy( v3, bestend2 ); } //end if dist = VectorDistance( v2, v4 ); if ( dist < bestdist ) { bestdist = dist; VectorCopy( v2, beststart1 ); VectorCopy( v2, beststart2 ); VectorCopy( v4, bestend1 ); VectorCopy( v4, bestend2 ); } //end if } //end if return bestdist; } //end of the function AAS_ClosestEdgePoints //=========================================================================== // creates possible jump reachabilities between the areas // // The two closest points on the ground of the areas are calculated // One of the points will be on an edge of a ground face of area1 and // one on an edge of a ground face of area2. // If there is a range of closest points the point in the middle of this range // is selected. // Between these two points there must be one or more gaps. // If the gaps exist a potential jump is predicted. // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_Jump( int area1num, int area2num ) { int i, j, k, l, face1num, face2num, edge1num, edge2num, traveltype; float sv_jumpvel, maxjumpdistance, maxjumpheight, height, bestdist, speed; vec_t *v1, *v2, *v3, *v4; vec3_t beststart, beststart2, bestend, bestend2; vec3_t teststart, testend, dir, velocity, cmdmove, up = {0, 0, 1}; aas_area_t *area1, *area2; aas_face_t *face1, *face2; aas_edge_t *edge1, *edge2; aas_plane_t *plane1, *plane2, *plane; aas_trace_t trace; aas_clientmove_t move; aas_lreachability_t *lreach; if ( !AAS_AreaGrounded( area1num ) || !AAS_AreaGrounded( area2num ) ) { return qfalse; } //cannot jump from or to a crouch area if ( AAS_AreaCrouch( area1num ) || AAS_AreaCrouch( area2num ) ) { return qfalse; } // area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; // sv_jumpvel = aassettings.sv_jumpvel; //maximum distance a player can jump maxjumpdistance = 2 * AAS_MaxJumpDistance( sv_jumpvel ); //maximum height a player can jump with the given initial z velocity maxjumpheight = AAS_MaxJumpHeight( sv_jumpvel ); //if the areas are not near anough in the x-y direction for ( i = 0; i < 2; i++ ) { if ( area1->mins[i] > area2->maxs[i] + maxjumpdistance ) { return qfalse; } if ( area1->maxs[i] < area2->mins[i] - maxjumpdistance ) { return qfalse; } } //end for //if area2 is way to high to jump up to if ( area2->mins[2] > area1->maxs[2] + maxjumpheight ) { return qfalse; } // bestdist = 999999; // for ( i = 0; i < area1->numfaces; i++ ) { face1num = ( *aasworld ).faceindex[area1->firstface + i]; face1 = &( *aasworld ).faces[abs( face1num )]; //if not a ground face if ( !( face1->faceflags & FACE_GROUND ) ) { continue; } // for ( j = 0; j < area2->numfaces; j++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + j]; face2 = &( *aasworld ).faces[abs( face2num )]; //if not a ground face if ( !( face2->faceflags & FACE_GROUND ) ) { continue; } // for ( k = 0; k < face1->numedges; k++ ) { edge1num = abs( ( *aasworld ).edgeindex[face1->firstedge + k] ); edge1 = &( *aasworld ).edges[edge1num]; for ( l = 0; l < face2->numedges; l++ ) { edge2num = abs( ( *aasworld ).edgeindex[face2->firstedge + l] ); edge2 = &( *aasworld ).edges[edge2num]; //calculate the minimum distance between the two edges v1 = ( *aasworld ).vertexes[edge1->v[0]]; v2 = ( *aasworld ).vertexes[edge1->v[1]]; v3 = ( *aasworld ).vertexes[edge2->v[0]]; v4 = ( *aasworld ).vertexes[edge2->v[1]]; //get the ground planes plane1 = &( *aasworld ).planes[face1->planenum]; plane2 = &( *aasworld ).planes[face2->planenum]; // bestdist = AAS_ClosestEdgePoints( v1, v2, v3, v4, plane1, plane2, beststart, bestend, beststart2, bestend2, bestdist ); } //end for } //end for } //end for } //end for VectorMiddle( beststart, beststart2, beststart ); VectorMiddle( bestend, bestend2, bestend ); if ( bestdist > 4 && bestdist < maxjumpdistance ) { // Log_Write("shortest distance between %d and %d is %f\r\n", area1num, area2num, bestdist); //if the fall would damage the bot // if ( AAS_HorizontalVelocityForJump( 0, beststart, bestend, &speed ) ) { //FIXME: why multiply with 1.2??? speed *= 1.2; traveltype = TRAVEL_WALKOFFLEDGE; } //end if else if ( bestdist <= 48 && fabs( beststart[2] - bestend[2] ) < 8 ) { speed = 400; traveltype = TRAVEL_WALKOFFLEDGE; } //end else if else { //get the horizontal speed for the jump, if it isn't possible to calculate this //speed (the jump is not possible) then there's no jump reachability created if ( !AAS_HorizontalVelocityForJump( sv_jumpvel, beststart, bestend, &speed ) ) { return qfalse; } traveltype = TRAVEL_JUMP; // //NOTE: test if the horizontal distance isn't too small VectorSubtract( bestend, beststart, dir ); dir[2] = 0; if ( VectorLength( dir ) < 10 ) { return qfalse; } } //end if // VectorSubtract( bestend, beststart, dir ); VectorNormalize( dir ); VectorMA( beststart, 1, dir, teststart ); // VectorCopy( teststart, testend ); testend[2] -= 100; trace = AAS_TraceClientBBox( teststart, testend, PRESENCE_NORMAL, -1 ); // if ( trace.startsolid ) { return qfalse; } if ( trace.fraction < 1 ) { plane = &( *aasworld ).planes[trace.planenum]; if ( DotProduct( plane->normal, up ) >= 0.7 ) { if ( !( AAS_PointContents( trace.endpos ) & CONTENTS_LAVA ) ) { //----(SA) modified since slime is no longer deadly // if (!(AAS_PointContents(trace.endpos) & (CONTENTS_LAVA|CONTENTS_SLIME))) if ( teststart[2] - trace.endpos[2] <= aassettings.sv_maxbarrier ) { return qfalse; } } //end if } //end if } //end if // VectorMA( bestend, -1, dir, teststart ); // VectorCopy( teststart, testend ); testend[2] -= 100; trace = AAS_TraceClientBBox( teststart, testend, PRESENCE_NORMAL, -1 ); // if ( trace.startsolid ) { return qfalse; } if ( trace.fraction < 1 ) { plane = &( *aasworld ).planes[trace.planenum]; if ( DotProduct( plane->normal, up ) >= 0.7 ) { if ( !( AAS_PointContents( trace.endpos ) & ( CONTENTS_LAVA | CONTENTS_SLIME ) ) ) { if ( teststart[2] - trace.endpos[2] <= aassettings.sv_maxbarrier ) { return qfalse; } } //end if } //end if } //end if // VectorSubtract( bestend, beststart, dir ); dir[2] = 0; VectorNormalize( dir ); // VectorScale( dir, speed, velocity ); //get command movement VectorClear( cmdmove ); if ( traveltype == TRAVEL_JUMP ) { cmdmove[2] = aassettings.sv_jumpvel; } else { cmdmove[2] = 0;} // AAS_PredictClientMovement( &move, -1, beststart, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 3, 30, 0.1, SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE, 0, qfalse ); //if prediction time wasn't enough to fully predict the movement if ( move.frames >= 30 ) { return qfalse; } //don't enter slime or lava and don't fall from too high if ( move.stopevent & SE_ENTERLAVA ) { return qfalse; //----(SA) modified since slime is no longer deadly } // if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA)) return qfalse; //the end position should be in area2, also test a little bit back //because the predicted jump could have rushed through the area for ( i = 0; i <= 32; i += 8 ) { VectorMA( move.endpos, -i, dir, teststart ); teststart[2] += 0.125; if ( AAS_PointAreaNum( teststart ) == area2num ) { break; } } //end for if ( i > 32 ) { return qfalse; } // #ifdef REACHDEBUG //create the reachability Log_Write( "jump reachability between %d and %d\r\n", area1num, area2num ); #endif //REACHDEBUG //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; VectorCopy( beststart, lreach->start ); VectorCopy( bestend, lreach->end ); lreach->traveltype = traveltype; VectorSubtract( bestend, beststart, dir ); height = dir[2]; dir[2] = 0; if ( traveltype == TRAVEL_WALKOFFLEDGE && height > VectorLength( dir ) ) { lreach->traveltime = STARTWALKOFFLEDGE_TIME + height * 50 / aassettings.sv_gravity; } else { lreach->traveltime = STARTJUMP_TIME + VectorDistance( bestend, beststart ) * 240 / aassettings.sv_maxwalkvelocity; } //end if // if ( !AAS_AreaJumpPad( area2num ) ) { if ( AAS_FallDelta( beststart[2] - bestend[2] ) > FALLDELTA_5DAMAGE ) { lreach->traveltime += FALLDAMAGE_5_TIME; } //end if else if ( AAS_FallDelta( beststart[2] - bestend[2] ) > FALLDELTA_10DAMAGE ) { lreach->traveltime += FALLDAMAGE_10_TIME; } //end if } //end if lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // if ( traveltype == TRAVEL_JUMP ) { reach_jump++; } else { reach_walkoffledge++;} } //end if return qfalse; } //end of the function AAS_Reachability_Jump //=========================================================================== // create a possible ladder reachability from area1 to area2 // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_Ladder( int area1num, int area2num ) { int i, j, k, l, edge1num, edge2num, sharededgenum, lowestedgenum; int face1num, face2num, ladderface1num, ladderface2num; int ladderface1vertical, ladderface2vertical, firstv; float face1area, face2area, bestface1area, bestface2area; float sv_jumpvel, maxjumpheight; vec3_t area1point, area2point, v1, v2, up = {0, 0, 1}; vec3_t mid, lowestpoint, start, end, sharededgevec, dir; aas_area_t *area1, *area2; aas_face_t *face1, *face2, *ladderface1, *ladderface2; aas_plane_t *plane1, *plane2; aas_edge_t *sharededge, *edge1; aas_lreachability_t *lreach; aas_trace_t trace; if ( !AAS_AreaLadder( area1num ) || !AAS_AreaLadder( area2num ) ) { return qfalse; } // sv_jumpvel = aassettings.sv_jumpvel; //maximum height a player can jump with the given initial z velocity maxjumpheight = AAS_MaxJumpHeight( sv_jumpvel ); area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; // ladderface1 = NULL; ladderface2 = NULL; ladderface1num = 0; //make compiler happy ladderface2num = 0; //make compiler happy bestface1area = -9999; bestface2area = -9999; sharededgenum = 0; //make compiler happy lowestedgenum = 0; //make compiler happy // for ( i = 0; i < area1->numfaces; i++ ) { face1num = ( *aasworld ).faceindex[area1->firstface + i]; face1 = &( *aasworld ).faces[abs( face1num )]; //if not a ladder face if ( !( face1->faceflags & FACE_LADDER ) ) { continue; } // for ( j = 0; j < area2->numfaces; j++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + j]; face2 = &( *aasworld ).faces[abs( face2num )]; //if not a ladder face if ( !( face2->faceflags & FACE_LADDER ) ) { continue; } //check if the faces share an edge for ( k = 0; k < face1->numedges; k++ ) { edge1num = ( *aasworld ).edgeindex[face1->firstedge + k]; for ( l = 0; l < face2->numedges; l++ ) { edge2num = ( *aasworld ).edgeindex[face2->firstedge + l]; if ( abs( edge1num ) == abs( edge2num ) ) { //get the face with the largest area face1area = AAS_FaceArea( face1 ); face2area = AAS_FaceArea( face2 ); if ( face1area > bestface1area && face2area > bestface2area ) { bestface1area = face1area; bestface2area = face2area; ladderface1 = face1; ladderface2 = face2; ladderface1num = face1num; ladderface2num = face2num; sharededgenum = edge1num; } //end if break; } //end if } //end for if ( l != face2->numedges ) { break; } } //end for } //end for } //end for // if ( ladderface1 && ladderface2 ) { //get the middle of the shared edge sharededge = &( *aasworld ).edges[abs( sharededgenum )]; firstv = sharededgenum < 0; // VectorCopy( ( *aasworld ).vertexes[sharededge->v[firstv]], v1 ); VectorCopy( ( *aasworld ).vertexes[sharededge->v[!firstv]], v2 ); VectorAdd( v1, v2, area1point ); VectorScale( area1point, 0.5, area1point ); VectorCopy( area1point, area2point ); // //if the face plane in area 1 is pretty much vertical plane1 = &( *aasworld ).planes[ladderface1->planenum ^ ( ladderface1num < 0 )]; plane2 = &( *aasworld ).planes[ladderface2->planenum ^ ( ladderface2num < 0 )]; // //get the points really into the areas VectorSubtract( v2, v1, sharededgevec ); CrossProduct( plane1->normal, sharededgevec, dir ); VectorNormalize( dir ); //NOTE: 32 because that's larger than 16 (bot bbox x,y) VectorMA( area1point, -32, dir, area1point ); VectorMA( area2point, 32, dir, area2point ); // ladderface1vertical = abs( DotProduct( plane1->normal, up ) ) < 0.1; ladderface2vertical = abs( DotProduct( plane2->normal, up ) ) < 0.1; //there's only reachability between vertical ladder faces if ( !ladderface1vertical && !ladderface2vertical ) { return qfalse; } //if both vertical ladder faces if ( ladderface1vertical && ladderface2vertical //and the ladder faces do not make a sharp corner && DotProduct( plane1->normal, plane2->normal ) > 0.7 //and the shared edge is not too vertical && abs( DotProduct( sharededgevec, up ) ) < 0.7 ) { //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = abs( sharededgenum ); VectorCopy( area1point, lreach->start ); //VectorCopy(area2point, lreach->end); VectorMA( area2point, -3, plane1->normal, lreach->end ); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_ladder++; //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area1num; lreach->facenum = ladderface2num; lreach->edgenum = abs( sharededgenum ); VectorCopy( area2point, lreach->start ); //VectorCopy(area1point, lreach->end); VectorMA( area1point, -3, plane2->normal, lreach->end ); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; lreach->next = areareachability[area2num]; areareachability[area2num] = lreach; // reach_ladder++; // return qtrue; } //end if //if the second ladder face is also a ground face //create ladder end (just ladder) reachability and //walk off a ladder (ledge) reachability if ( ladderface1vertical && ( ladderface2->faceflags & FACE_GROUND ) ) { //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = abs( sharededgenum ); VectorCopy( area1point, lreach->start ); VectorCopy( area2point, lreach->end ); lreach->end[2] += 16; VectorMA( lreach->end, -15, plane1->normal, lreach->end ); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_ladder++; //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area1num; lreach->facenum = ladderface2num; lreach->edgenum = abs( sharededgenum ); VectorCopy( area2point, lreach->start ); VectorCopy( area1point, lreach->end ); lreach->traveltype = TRAVEL_WALKOFFLEDGE; lreach->traveltime = 10; lreach->next = areareachability[area2num]; areareachability[area2num] = lreach; // reach_walkoffledge++; // return qtrue; } //end if // if ( ladderface1vertical ) { //find lowest edge of the ladder face lowestpoint[2] = 99999; for ( i = 0; i < ladderface1->numedges; i++ ) { edge1num = abs( ( *aasworld ).edgeindex[ladderface1->firstedge + i] ); edge1 = &( *aasworld ).edges[edge1num]; // VectorCopy( ( *aasworld ).vertexes[edge1->v[0]], v1 ); VectorCopy( ( *aasworld ).vertexes[edge1->v[1]], v2 ); // VectorAdd( v1, v2, mid ); VectorScale( mid, 0.5, mid ); // if ( mid[2] < lowestpoint[2] ) { VectorCopy( mid, lowestpoint ); lowestedgenum = edge1num; } //end if } //end for // plane1 = &( *aasworld ).planes[ladderface1->planenum]; //trace down in the middle of this edge VectorMA( lowestpoint, 5, plane1->normal, start ); VectorCopy( start, end ); start[2] += 5; end[2] -= 100; //trace without entity collision trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, -1 ); // // #ifdef REACHDEBUG if ( trace.startsolid ) { Log_Write( "trace from area %d started in solid\r\n", area1num ); } //end if #endif //REACHDEBUG // trace.endpos[2] += 1; area2num = AAS_PointAreaNum( trace.endpos ); // area2 = &( *aasworld ).areas[area2num]; for ( i = 0; i < area2->numfaces; i++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + i]; face2 = &( *aasworld ).faces[abs( face2num )]; // if ( face2->faceflags & FACE_LADDER ) { plane2 = &( *aasworld ).planes[face2->planenum]; if ( abs( DotProduct( plane2->normal, up ) ) < 0.1 ) { break; } } //end if } //end for //if from another area without vertical ladder faces if ( i >= area2->numfaces && area2num != area1num && //the reachabilities shouldn't exist already !AAS_ReachabilityExists( area1num, area2num ) && !AAS_ReachabilityExists( area2num, area1num ) ) { //if the height is jumpable if ( start[2] - trace.endpos[2] < maxjumpheight ) { //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = ladderface1num; lreach->edgenum = lowestedgenum; VectorCopy( lowestpoint, lreach->start ); VectorCopy( trace.endpos, lreach->end ); lreach->traveltype = TRAVEL_LADDER; lreach->traveltime = 10; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_ladder++; //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area1num; lreach->facenum = ladderface1num; lreach->edgenum = lowestedgenum; VectorCopy( trace.endpos, lreach->start ); //get the end point a little bit into the ladder VectorMA( lowestpoint, -5, plane1->normal, lreach->end ); //get the end point a little higher lreach->end[2] += 10; lreach->traveltype = TRAVEL_JUMP; lreach->traveltime = 10; lreach->next = areareachability[area2num]; areareachability[area2num] = lreach; // reach_jump++; // return qtrue; #ifdef REACHDEBUG Log_Write( "jump up to ladder reach between %d and %d\r\n", area2num, area1num ); #endif //REACHDEBUG } //end if #ifdef REACHDEBUG else {Log_Write( "jump too high between area %d and %d\r\n", area2num, area1num );} #endif //REACHDEBUG } //end if /*//if slime or lava below the ladder //try jump reachability from far towards the ladder if ((*aasworld).areasettings[area2num].contents & (AREACONTENTS_SLIME | AREACONTENTS_LAVA)) { for (i = 20; i <= 120; i += 20) { //trace down in the middle of this edge VectorMA(lowestpoint, i, plane1->normal, start); VectorCopy(start, end); start[2] += 5; end[2] -= 100; //trace without entity collision trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, -1); // if (trace.startsolid) break; trace.endpos[2] += 1; area2num = AAS_PointAreaNum(trace.endpos); if (area2num == area1num) continue; // if (start[2] - trace.endpos[2] > maxjumpheight) continue; if ((*aasworld).areasettings[area2num].contents & (AREACONTENTS_SLIME | AREACONTENTS_LAVA)) continue; // //create a new reachability link lreach = AAS_AllocReachability(); if (!lreach) return qfalse; lreach->areanum = area1num; lreach->facenum = ladderface1num; lreach->edgenum = lowestedgenum; VectorCopy(trace.endpos, lreach->start); VectorCopy(lowestpoint, lreach->end); lreach->end[2] += 5; lreach->traveltype = TRAVEL_JUMP; lreach->traveltime = 10; lreach->next = areareachability[area2num]; areareachability[area2num] = lreach; // reach_jump++; // Log_Write("jump far to ladder reach between %d and %d\r\n", area2num, area1num); // break; } //end for } //end if*/ } //end if } //end if return qfalse; } //end of the function AAS_Reachability_Ladder //=========================================================================== // create possible teleporter reachabilities // this is very game dependent.... :( // // classname = trigger_multiple or trigger_teleport // target = "t1" // // classname = target_teleporter // targetname = "t1" // target = "t2" // // classname = misc_teleporter_dest // targetname = "t2" // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_Reachability_Teleport( void ) { int area1num, area2num; char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY]; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; int ent, dest; vec3_t origin, destorigin, mins, maxs, end, angles = {0, 0, 0}; vec3_t mid; aas_lreachability_t *lreach; aas_trace_t trace; aas_link_t *areas, *link; for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) ) { if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( classname, "trigger_multiple" ) ) { AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ); //#ifdef REACHDEBUG botimport.Print( PRT_MESSAGE, "trigger_multiple model = \"%s\"\n", model ); //#endif REACHDEBUG AAS_BSPModelMinsMaxsOrigin( atoi( model + 1 ), angles, mins, maxs, origin ); // if ( !AAS_ValueForBSPEpairKey( ent, "target", target, MAX_EPAIRKEY ) ) { botimport.Print( PRT_ERROR, "trigger_multiple at %1.0f %1.0f %1.0f without target\n", origin[0], origin[1], origin[2] ); continue; } //end if for ( dest = AAS_NextBSPEntity( 0 ); dest; dest = AAS_NextBSPEntity( dest ) ) { if ( !AAS_ValueForBSPEpairKey( dest, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( classname, "target_teleporter" ) ) { if ( !AAS_ValueForBSPEpairKey( dest, "targetname", targetname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( targetname, target ) ) { break; } //end if } //end if } //end for if ( !dest ) { continue; } //end if if ( !AAS_ValueForBSPEpairKey( dest, "target", target, MAX_EPAIRKEY ) ) { botimport.Print( PRT_ERROR, "target_teleporter without target\n" ); continue; } //end if } //end else else if ( !strcmp( classname, "trigger_teleport" ) ) { AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ); //#ifdef REACHDEBUG botimport.Print( PRT_MESSAGE, "trigger_teleport model = \"%s\"\n", model ); //#endif REACHDEBUG AAS_BSPModelMinsMaxsOrigin( atoi( model + 1 ), angles, mins, maxs, origin ); // if ( !AAS_ValueForBSPEpairKey( ent, "target", target, MAX_EPAIRKEY ) ) { botimport.Print( PRT_ERROR, "trigger_teleport at %1.0f %1.0f %1.0f without target\n", origin[0], origin[1], origin[2] ); continue; } //end if } //end if else { continue; } //end else // for ( dest = AAS_NextBSPEntity( 0 ); dest; dest = AAS_NextBSPEntity( dest ) ) { //classname should be misc_teleporter_dest //but I've also seen target_position and actually any //entity could be used... burp if ( AAS_ValueForBSPEpairKey( dest, "targetname", targetname, MAX_EPAIRKEY ) ) { if ( !strcmp( targetname, target ) ) { break; } //end if } //end if } //end for if ( !dest ) { botimport.Print( PRT_ERROR, "teleporter without misc_teleporter_dest (%s)\n", target ); continue; } //end if if ( !AAS_VectorForBSPEpairKey( dest, "origin", destorigin ) ) { botimport.Print( PRT_ERROR, "teleporter destination (%s) without origin\n", target ); continue; } //end if // area2num = AAS_PointAreaNum( destorigin ); //if not teleported into a teleporter or into a jumppad if ( !AAS_AreaTeleporter( area2num ) && !AAS_AreaJumpPad( area2num ) ) { destorigin[2] += 24; //just for q2e1m2, the dork has put the telepads in the ground VectorCopy( destorigin, end ); end[2] -= 100; trace = AAS_TraceClientBBox( destorigin, end, PRESENCE_CROUCH, -1 ); if ( trace.startsolid ) { botimport.Print( PRT_ERROR, "teleporter destination (%s) in solid\n", target ); continue; } //end if VectorCopy( trace.endpos, destorigin ); area2num = AAS_PointAreaNum( destorigin ); } //end if // //botimport.Print(PRT_MESSAGE, "teleporter brush origin at %f %f %f\n", origin[0], origin[1], origin[2]); //botimport.Print(PRT_MESSAGE, "teleporter brush mins = %f %f %f\n", mins[0], mins[1], mins[2]); //botimport.Print(PRT_MESSAGE, "teleporter brush maxs = %f %f %f\n", maxs[0], maxs[1], maxs[2]); VectorAdd( origin, mins, mins ); VectorAdd( origin, maxs, maxs ); // VectorAdd( mins, maxs, mid ); VectorScale( mid, 0.5, mid ); //link an invalid (-1) entity areas = AAS_LinkEntityClientBBox( mins, maxs, -1, PRESENCE_CROUCH ); if ( !areas ) { botimport.Print( PRT_MESSAGE, "trigger_multiple not in any area\n" ); } // for ( link = areas; link; link = link->next_area ) { //if (!AAS_AreaGrounded(link->areanum)) continue; if ( !AAS_AreaTeleporter( link->areanum ) ) { continue; } // area1num = link->areanum; //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { break; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; VectorCopy( mid, lreach->start ); VectorCopy( destorigin, lreach->end ); lreach->traveltype = TRAVEL_TELEPORT; lreach->traveltime = TELEPORT_TIME; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_teleport++; } //end for //unlink the invalid entity AAS_UnlinkFromAreas( areas ); } //end for } //end of the function AAS_Reachability_Teleport //=========================================================================== // create possible elevator (func_plat) reachabilities // this is very game dependent.... :( // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== #define REACHDEBUG void AAS_Reachability_Elevator( void ) { int area1num, area2num, modelnum, i, j, k, l, n, p; float lip, height, speed; char model[MAX_EPAIRKEY], classname[MAX_EPAIRKEY]; int ent; vec3_t mins, maxs, origin, angles = {0, 0, 0}; vec3_t pos1, pos2, mids, platbottom, plattop; vec3_t bottomorg, toporg, start, end, dir; vec_t xvals[8], yvals[8], xvals_top[8], yvals_top[8]; aas_lreachability_t *lreach; aas_trace_t trace; #ifdef REACHDEBUG Log_Write( "AAS_Reachability_Elevator\r\n" ); #endif //REACHDEBUG for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) ) { if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( classname, "func_plat" ) ) { #ifdef REACHDEBUG Log_Write( "found func plat\r\n" ); #endif //REACHDEBUG if ( !AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ) ) { botimport.Print( PRT_ERROR, "func_plat without model\n" ); continue; } //end if //get the model number, and skip the leading * modelnum = atoi( model + 1 ); if ( modelnum <= 0 ) { botimport.Print( PRT_ERROR, "func_plat with invalid model number\n" ); continue; } //end if //get the mins, maxs and origin of the model //NOTE: the origin is usually (0,0,0) and the mins and maxs // are the absolute mins and maxs AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, origin ); // AAS_VectorForBSPEpairKey( ent, "origin", origin ); //pos1 is the top position, pos2 is the bottom VectorCopy( origin, pos1 ); VectorCopy( origin, pos2 ); //get the lip of the plat AAS_FloatForBSPEpairKey( ent, "lip", &lip ); if ( !lip ) { lip = 8; } //get the movement height of the plat AAS_FloatForBSPEpairKey( ent, "height", &height ); if ( !height ) { height = ( maxs[2] - mins[2] ) - lip; } //get the speed of the plat AAS_FloatForBSPEpairKey( ent, "speed", &speed ); if ( !speed ) { speed = 200; } //get bottom position below pos1 pos2[2] -= height; // botimport.Print( PRT_MESSAGE, "pos2[2] = %1.1f pos1[2] = %1.1f\n", pos2[2], pos1[2] ); //get a point just above the plat in the bottom position VectorAdd( mins, maxs, mids ); VectorMA( pos2, 0.5, mids, platbottom ); platbottom[2] = maxs[2] - ( pos1[2] - pos2[2] ) + 2; //get a point just above the plat in the top position VectorAdd( mins, maxs, mids ); VectorMA( pos2, 0.5, mids, plattop ); plattop[2] = maxs[2] + 2; // /*if (!area1num) { Log_Write("no grounded area near plat bottom\r\n"); continue; } //end if*/ //get the mins and maxs a little larger for ( i = 0; i < 3; i++ ) { mins[i] -= 1; maxs[i] += 1; } //end for // botimport.Print( PRT_MESSAGE, "platbottom[2] = %1.1f plattop[2] = %1.1f\n", platbottom[2], plattop[2] ); // VectorAdd( mins, maxs, mids ); VectorScale( mids, 0.5, mids ); // xvals[0] = mins[0]; xvals[1] = mids[0]; xvals[2] = maxs[0]; xvals[3] = mids[0]; yvals[0] = mids[1]; yvals[1] = maxs[1]; yvals[2] = mids[1]; yvals[3] = mins[1]; // xvals[4] = mins[0]; xvals[5] = maxs[0]; xvals[6] = maxs[0]; xvals[7] = mins[0]; yvals[4] = maxs[1]; yvals[5] = maxs[1]; yvals[6] = mins[1]; yvals[7] = mins[1]; //find adjacent areas around the bottom of the plat for ( i = 0; i < 9; i++ ) { if ( i < 8 ) { //check at the sides of the plat bottomorg[0] = origin[0] + xvals[i]; bottomorg[1] = origin[1] + yvals[i]; bottomorg[2] = platbottom[2] + 16; //get a grounded or swim area near the plat in the bottom position area1num = AAS_PointAreaNum( bottomorg ); for ( k = 0; k < 16; k++ ) { if ( area1num ) { if ( AAS_AreaGrounded( area1num ) || AAS_AreaSwim( area1num ) ) { break; } } //end if bottomorg[2] += 4; area1num = AAS_PointAreaNum( bottomorg ); } //end if //if in solid if ( k >= 16 ) { continue; } //end if } //end if else //at the middle of the plat { VectorCopy( plattop, bottomorg ); bottomorg[2] += 24; area1num = AAS_PointAreaNum( bottomorg ); if ( !area1num ) { continue; } VectorCopy( platbottom, bottomorg ); bottomorg[2] += 24; } //end else //look at adjacent areas around the top of the plat //make larger steps to outside the plat everytime for ( n = 0; n < 3; n++ ) { for ( k = 0; k < 3; k++ ) { mins[k] -= 4; maxs[k] += 4; } //end for xvals_top[0] = mins[0]; xvals_top[1] = mids[0]; xvals_top[2] = maxs[0]; xvals_top[3] = mids[0]; yvals_top[0] = mids[1]; yvals_top[1] = maxs[1]; yvals_top[2] = mids[1]; yvals_top[3] = mins[1]; // xvals_top[4] = mins[0]; xvals_top[5] = maxs[0]; xvals_top[6] = maxs[0]; xvals_top[7] = mins[0]; yvals_top[4] = maxs[1]; yvals_top[5] = maxs[1]; yvals_top[6] = mins[1]; yvals_top[7] = mins[1]; // for ( j = 0; j < 8; j++ ) { toporg[0] = origin[0] + xvals_top[j]; toporg[1] = origin[1] + yvals_top[j]; toporg[2] = plattop[2] + 16; //get a grounded or swim area near the plat in the top position area2num = AAS_PointAreaNum( toporg ); for ( l = 0; l < 16; l++ ) { if ( area2num ) { if ( AAS_AreaGrounded( area2num ) || AAS_AreaSwim( area2num ) ) { VectorCopy( plattop, start ); start[2] += 32; VectorCopy( toporg, end ); end[2] += 1; trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, -1 ); if ( trace.fraction >= 1 ) { break; } } //end if } //end if toporg[2] += 4; area2num = AAS_PointAreaNum( toporg ); } //end if //if in solid if ( l >= 16 ) { continue; } //never create a reachability in the same area if ( area2num == area1num ) { continue; } //if the area isn't grounded if ( !AAS_AreaGrounded( area2num ) ) { continue; } //if there already exists reachability between the areas if ( AAS_ReachabilityExists( area1num, area2num ) ) { continue; } //if the reachability start is within the elevator bounding box VectorSubtract( bottomorg, platbottom, dir ); VectorNormalize( dir ); dir[0] = bottomorg[0] + 24 * dir[0]; dir[1] = bottomorg[1] + 24 * dir[1]; dir[2] = bottomorg[2]; // for ( p = 0; p < 3; p++ ) if ( dir[p] < origin[p] + mins[p] || dir[p] > origin[p] + maxs[p] ) { break; } if ( p >= 3 ) { continue; } //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { continue; } lreach->areanum = area2num; //the facenum is the model number lreach->facenum = modelnum; //the edgenum is the height lreach->edgenum = (int) height; // VectorCopy( dir, lreach->start ); VectorCopy( toporg, lreach->end ); lreach->traveltype = TRAVEL_ELEVATOR; lreach->traveltime = height * 100 / speed; if ( !lreach->traveltime ) { lreach->traveltime = 50; } lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; //don't go any further to the outside n = 9999; // #ifdef REACHDEBUG Log_Write( "elevator reach from %d to %d\r\n", area1num, area2num ); #endif //REACHDEBUG // reach_elevator++; } //end for } //end for } //end for } //end if } //end for } //end of the function AAS_Reachability_Elevator //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== aas_lreachability_t *AAS_FindFaceReachabilities( vec3_t *facepoints, int numpoints, aas_plane_t *plane, int towardsface ) { int i, j, k, l; int facenum, edgenum, bestfacenum; float *v1, *v2, *v3, *v4; float bestdist, speed, hordist, dist; vec3_t beststart, beststart2, bestend, bestend2, tmp, hordir, testpoint; aas_lreachability_t *lreach, *lreachabilities; aas_area_t *area; aas_face_t *face; aas_edge_t *edge; aas_plane_t *faceplane, *bestfaceplane; // lreachabilities = NULL; bestfacenum = 0; bestfaceplane = NULL; // for ( i = 1; i < ( *aasworld ).numareas; i++ ) { area = &( *aasworld ).areas[i]; // get the shortest distance between one of the func_bob start edges and // one of the face edges of area1 bestdist = 999999; for ( j = 0; j < area->numfaces; j++ ) { facenum = ( *aasworld ).faceindex[area->firstface + j]; face = &( *aasworld ).faces[abs( facenum )]; //if not a ground face if ( !( face->faceflags & FACE_GROUND ) ) { continue; } //get the ground planes faceplane = &( *aasworld ).planes[face->planenum]; // for ( k = 0; k < face->numedges; k++ ) { edgenum = abs( ( *aasworld ).edgeindex[face->firstedge + k] ); edge = &( *aasworld ).edges[edgenum]; //calculate the minimum distance between the two edges v1 = ( *aasworld ).vertexes[edge->v[0]]; v2 = ( *aasworld ).vertexes[edge->v[1]]; // for ( l = 0; l < numpoints; l++ ) { v3 = facepoints[l]; v4 = facepoints[( l + 1 ) % numpoints]; dist = AAS_ClosestEdgePoints( v1, v2, v3, v4, faceplane, plane, beststart, bestend, beststart2, bestend2, bestdist ); if ( dist < bestdist ) { bestfacenum = facenum; bestfaceplane = faceplane; bestdist = dist; } //end if } //end for } //end for } //end for // if ( bestdist > 192 ) { continue; } // VectorMiddle( beststart, beststart2, beststart ); VectorMiddle( bestend, bestend2, bestend ); // if ( !towardsface ) { VectorCopy( beststart, tmp ); VectorCopy( bestend, beststart ); VectorCopy( tmp, bestend ); } //end if // VectorSubtract( bestend, beststart, hordir ); hordir[2] = 0; hordist = VectorLength( hordir ); // if ( hordist > 2 * AAS_MaxJumpDistance( aassettings.sv_jumpvel ) ) { continue; } //the end point should not be significantly higher than the start point if ( bestend[2] - 32 > beststart[2] ) { continue; } //don't fall down too far if ( bestend[2] < beststart[2] - 128 ) { continue; } //the distance should not be too far if ( hordist > 32 ) { //check for walk off ledge if ( !AAS_HorizontalVelocityForJump( 0, beststart, bestend, &speed ) ) { continue; } } //end if // beststart[2] += 1; bestend[2] += 1; // if ( towardsface ) { VectorCopy( bestend, testpoint ); } else { VectorCopy( beststart, testpoint );} testpoint[2] = 0; testpoint[2] = ( bestfaceplane->dist - DotProduct( bestfaceplane->normal, testpoint ) ) / bestfaceplane->normal[2]; // if ( !AAS_PointInsideFace( bestfacenum, testpoint, 0.1 ) ) { //if the faces are not overlapping then only go down if ( bestend[2] - 16 > beststart[2] ) { continue; } } //end if lreach = AAS_AllocReachability(); if ( !lreach ) { return lreachabilities; } lreach->areanum = i; lreach->facenum = 0; lreach->edgenum = 0; VectorCopy( beststart, lreach->start ); VectorCopy( bestend, lreach->end ); lreach->traveltype = 0; lreach->traveltime = 0; lreach->next = lreachabilities; lreachabilities = lreach; #ifndef BSPC if ( towardsface ) { AAS_PermanentLine( lreach->start, lreach->end, 1 ); } else { AAS_PermanentLine( lreach->start, lreach->end, 2 );} #endif } //end for return lreachabilities; } //end of the function AAS_FindFaceReachabilities //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_Reachability_FuncBobbing( void ) { int ent, spawnflags, modelnum, axis; int i, numareas, areas[10]; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; vec3_t origin, move_end, move_start, move_start_top, move_end_top; vec3_t mins, maxs, angles = {0, 0, 0}; vec3_t start_edgeverts[4], end_edgeverts[4], mid; vec3_t org, start, end, dir, points[10]; float height; aas_plane_t start_plane, end_plane; aas_lreachability_t *startreach, *endreach, *nextstartreach, *nextendreach, *lreach; aas_lreachability_t *firststartreach, *firstendreach; for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) ) { if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( strcmp( classname, "func_bobbing" ) ) { continue; } AAS_FloatForBSPEpairKey( ent, "height", &height ); if ( !height ) { height = 32; } // if ( !AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ) ) { botimport.Print( PRT_ERROR, "func_bobbing without model\n" ); continue; } //end if //get the model number, and skip the leading * modelnum = atoi( model + 1 ); if ( modelnum <= 0 ) { botimport.Print( PRT_ERROR, "func_bobbing with invalid model number\n" ); continue; } //end if // AAS_BSPModelMinsMaxsOrigin( modelnum, angles, mins, maxs, NULL ); // VectorAdd( mins, maxs, mid ); VectorScale( mid, 0.5, mid ); //VectorAdd(mid, origin, mid); VectorCopy( mid, origin ); // VectorCopy( origin, move_end ); VectorCopy( origin, move_start ); // AAS_IntForBSPEpairKey( ent, "spawnflags", &spawnflags ); // set the axis of bobbing if ( spawnflags & 1 ) { axis = 0; } else if ( spawnflags & 2 ) { axis = 1; } else { axis = 2;} // move_start[axis] -= height; move_end[axis] += height; // Log_Write( "funcbob model %d, start = {%1.1f, %1.1f, %1.1f} end = {%1.1f, %1.1f, %1.1f}\n", modelnum, move_start[0], move_start[1], move_start[2], move_end[0], move_end[1], move_end[2] ); // #ifndef BSPC /* AAS_DrawPermanentCross(move_start, 4, 1); AAS_DrawPermanentCross(move_end, 4, 2); */ #endif // for ( i = 0; i < 4; i++ ) { VectorCopy( move_start, start_edgeverts[i] ); start_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z start_edgeverts[i][2] += 24; //+ player origin to ground dist } //end for start_edgeverts[0][0] += maxs[0] - mid[0]; start_edgeverts[0][1] += maxs[1] - mid[1]; start_edgeverts[1][0] += maxs[0] - mid[0]; start_edgeverts[1][1] += mins[1] - mid[1]; start_edgeverts[2][0] += mins[0] - mid[0]; start_edgeverts[2][1] += mins[1] - mid[1]; start_edgeverts[3][0] += mins[0] - mid[0]; start_edgeverts[3][1] += maxs[1] - mid[1]; // start_plane.dist = start_edgeverts[0][2]; VectorSet( start_plane.normal, 0, 0, 1 ); // for ( i = 0; i < 4; i++ ) { VectorCopy( move_end, end_edgeverts[i] ); end_edgeverts[i][2] += maxs[2] - mid[2]; //+ bbox maxs z end_edgeverts[i][2] += 24; //+ player origin to ground dist } //end for end_edgeverts[0][0] += maxs[0] - mid[0]; end_edgeverts[0][1] += maxs[1] - mid[1]; end_edgeverts[1][0] += maxs[0] - mid[0]; end_edgeverts[1][1] += mins[1] - mid[1]; end_edgeverts[2][0] += mins[0] - mid[0]; end_edgeverts[2][1] += mins[1] - mid[1]; end_edgeverts[3][0] += mins[0] - mid[0]; end_edgeverts[3][1] += maxs[1] - mid[1]; // end_plane.dist = end_edgeverts[0][2]; VectorSet( end_plane.normal, 0, 0, 1 ); // #ifndef BSPC /* for (i = 0; i < 4; i++) { AAS_PermanentLine(start_edgeverts[i], start_edgeverts[(i+1)%4], 1); AAS_PermanentLine(end_edgeverts[i], end_edgeverts[(i+1)%4], 1); } //end for */ #endif VectorCopy( move_start, move_start_top ); move_start_top[2] += maxs[2] - mid[2] + 24; //+ bbox maxs z VectorCopy( move_end, move_end_top ); move_end_top[2] += maxs[2] - mid[2] + 24; //+ bbox maxs z // if ( !AAS_PointAreaNum( move_start_top ) ) { continue; } if ( !AAS_PointAreaNum( move_end_top ) ) { continue; } // for ( i = 0; i < 2; i++ ) { firststartreach = firstendreach = NULL; // if ( i == 0 ) { firststartreach = AAS_FindFaceReachabilities( start_edgeverts, 4, &start_plane, qtrue ); firstendreach = AAS_FindFaceReachabilities( end_edgeverts, 4, &end_plane, qfalse ); } //end if else { firststartreach = AAS_FindFaceReachabilities( end_edgeverts, 4, &end_plane, qtrue ); firstendreach = AAS_FindFaceReachabilities( start_edgeverts, 4, &start_plane, qfalse ); } //end else // //create reachabilities from start to end for ( startreach = firststartreach; startreach; startreach = nextstartreach ) { nextstartreach = startreach->next; // //trace = AAS_TraceClientBBox(startreach->start, move_start_top, PRESENCE_NORMAL, -1); //if (trace.fraction < 1) continue; // for ( endreach = firstendreach; endreach; endreach = nextendreach ) { nextendreach = endreach->next; // //trace = AAS_TraceClientBBox(endreach->end, move_end_top, PRESENCE_NORMAL, -1); //if (trace.fraction < 1) continue; // Log_Write( "funcbob reach from area %d to %d\n", startreach->areanum, endreach->areanum ); // // if ( i == 0 ) { VectorCopy( move_start_top, org ); } else { VectorCopy( move_end_top, org );} VectorSubtract( startreach->start, org, dir ); dir[2] = 0; VectorNormalize( dir ); VectorCopy( startreach->start, start ); VectorMA( startreach->start, 1, dir, start ); start[2] += 1; VectorMA( startreach->start, 16, dir, end ); end[2] += 1; // numareas = AAS_TraceAreas( start, end, areas, points, 10 ); if ( numareas <= 0 ) { continue; } if ( numareas > 1 ) { VectorCopy( points[1], startreach->start ); } else { VectorCopy( end, startreach->start );} // if ( !AAS_PointAreaNum( startreach->start ) ) { continue; } if ( !AAS_PointAreaNum( endreach->end ) ) { continue; } // lreach = AAS_AllocReachability(); lreach->areanum = endreach->areanum; if ( i == 0 ) { lreach->edgenum = ( (int)move_start[axis] << 16 ) | ( (int) move_end[axis] & 0x0000ffff ); } else { lreach->edgenum = ( (int)move_end[axis] << 16 ) | ( (int) move_start[axis] & 0x0000ffff );} lreach->facenum = ( spawnflags << 16 ) | modelnum; VectorCopy( startreach->start, lreach->start ); VectorCopy( endreach->end, lreach->end ); #ifndef BSPC // AAS_DrawArrow(lreach->start, lreach->end, LINECOLOR_BLUE, LINECOLOR_YELLOW); // AAS_PermanentLine(lreach->start, lreach->end, 1); #endif lreach->traveltype = TRAVEL_FUNCBOB; lreach->traveltime = 300; reach_funcbob++; lreach->next = areareachability[startreach->areanum]; areareachability[startreach->areanum] = lreach; // } //end for } //end for for ( startreach = firststartreach; startreach; startreach = nextstartreach ) { nextstartreach = startreach->next; AAS_FreeReachability( startreach ); } //end for for ( endreach = firstendreach; endreach; endreach = nextendreach ) { nextendreach = endreach->next; AAS_FreeReachability( endreach ); } //end for //only go up with func_bobbing entities that go up and down if ( !( spawnflags & 1 ) && !( spawnflags & 2 ) ) { break; } } //end for } //end for } //end of the function AAS_Reachability_FuncBobbing //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_Reachability_JumpPad( void ) { int face2num, i, ret, modelnum, area2num, visualize; float speed, zvel, hordist, dist, time, height, gravity, forward; aas_face_t *face2; aas_area_t *area2; aas_lreachability_t *lreach; vec3_t areastart, facecenter, dir, cmdmove, teststart; vec3_t velocity, origin, ent2origin, angles, absmins, absmaxs; aas_clientmove_t move; aas_trace_t trace; int ent, ent2; aas_link_t *areas, *link; char target[MAX_EPAIRKEY], targetname[MAX_EPAIRKEY]; char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY]; for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) ) { if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( strcmp( classname, "trigger_push" ) ) { continue; } // AAS_FloatForBSPEpairKey( ent, "speed", &speed ); if ( !speed ) { speed = 1000; } // AAS_VectorForBSPEpairKey(ent, "angles", angles); // AAS_SetMovedir(angles, velocity); // VectorScale(velocity, speed, velocity); VectorClear( angles ); //get the mins, maxs and origin of the model AAS_ValueForBSPEpairKey( ent, "model", model, MAX_EPAIRKEY ); if ( model[0] ) { modelnum = atoi( model + 1 ); } else { modelnum = 0;} AAS_BSPModelMinsMaxsOrigin( modelnum, angles, absmins, absmaxs, origin ); VectorAdd( origin, absmins, absmins ); VectorAdd( origin, absmaxs, absmaxs ); // #ifdef REACHDEBUG botimport.Print( PRT_MESSAGE, "absmins = %f %f %f\n", absmins[0], absmins[1], absmins[2] ); botimport.Print( PRT_MESSAGE, "absmaxs = %f %f %f\n", absmaxs[0], absmaxs[1], absmaxs[2] ); #endif //REACHDEBUG VectorAdd( absmins, absmaxs, origin ); VectorScale( origin, 0.5, origin ); //get the start areas VectorCopy( origin, teststart ); teststart[2] += 64; trace = AAS_TraceClientBBox( teststart, origin, PRESENCE_CROUCH, -1 ); if ( trace.startsolid ) { botimport.Print( PRT_MESSAGE, "trigger_push start solid\n" ); VectorCopy( origin, areastart ); } //end if else { VectorCopy( trace.endpos, areastart ); } //end else areastart[2] += 0.125; // //AAS_DrawPermanentCross(origin, 4, 4); //get the target entity AAS_ValueForBSPEpairKey( ent, "target", target, MAX_EPAIRKEY ); for ( ent2 = AAS_NextBSPEntity( 0 ); ent2; ent2 = AAS_NextBSPEntity( ent2 ) ) { if ( !AAS_ValueForBSPEpairKey( ent2, "targetname", targetname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( targetname, target ) ) { break; } } //end for if ( !ent2 ) { botimport.Print( PRT_MESSAGE, "trigger_push without target entity %s\n", target ); continue; } //end if AAS_VectorForBSPEpairKey( ent2, "origin", ent2origin ); // height = ent2origin[2] - origin[2]; gravity = aassettings.sv_gravity; time = sqrt( height / ( 0.5 * gravity ) ); if ( !time ) { botimport.Print( PRT_MESSAGE, "trigger_push without time\n" ); continue; } //end if // set s.origin2 to the push velocity VectorSubtract( ent2origin, origin, velocity ); dist = VectorNormalize( velocity ); forward = dist / time; //FIXME: why multiply by 1.1 forward *= 1.1; VectorScale( velocity, forward, velocity ); velocity[2] = time * gravity; //get the areas the jump pad brush is in areas = AAS_LinkEntityClientBBox( absmins, absmaxs, -1, PRESENCE_CROUCH ); //* for ( link = areas; link; link = link->next_area ) { if ( link->areanum == 5772 ) { ret = qfalse; } } //*/ for ( link = areas; link; link = link->next_area ) { if ( AAS_AreaJumpPad( link->areanum ) ) { break; } } //end for if ( !link ) { botimport.Print( PRT_MESSAGE, "trigger_multiple not in any jump pad area\n" ); AAS_UnlinkFromAreas( areas ); continue; } //end if // botimport.Print( PRT_MESSAGE, "found a trigger_push with velocity %f %f %f\n", velocity[0], velocity[1], velocity[2] ); //if there is a horizontal velocity check for a reachability without air control if ( velocity[0] || velocity[1] ) { VectorSet( cmdmove, 0, 0, 0 ); //VectorCopy(velocity, cmdmove); //cmdmove[2] = 0; memset( &move, 0, sizeof( aas_clientmove_t ) ); area2num = 0; for ( i = 0; i < 20; i++ ) { AAS_PredictClientMovement( &move, -1, areastart, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 0, 30, 0.1, SE_HITGROUND | SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER, 0, qfalse ); //qtrue); area2num = AAS_PointAreaNum( move.endpos ); for ( link = areas; link; link = link->next_area ) { if ( !AAS_AreaJumpPad( link->areanum ) ) { continue; } if ( link->areanum == area2num ) { break; } } //end if if ( !link ) { break; } VectorCopy( move.endpos, areastart ); VectorCopy( move.velocity, velocity ); } //end for if ( area2num && i < 20 ) { for ( link = areas; link; link = link->next_area ) { if ( !AAS_AreaJumpPad( link->areanum ) ) { continue; } if ( AAS_ReachabilityExists( link->areanum, area2num ) ) { continue; } //create a rocket or bfg jump reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { AAS_UnlinkFromAreas( areas ); return; } //end if lreach->areanum = area2num; //NOTE: the facenum is the Z velocity lreach->facenum = velocity[2]; //NOTE: the edgenum is the horizontal velocity lreach->edgenum = sqrt( velocity[0] * velocity[0] + velocity[1] * velocity[1] ); VectorCopy( areastart, lreach->start ); VectorCopy( move.endpos, lreach->end ); lreach->traveltype = TRAVEL_JUMPPAD; lreach->traveltime = 200; lreach->next = areareachability[link->areanum]; areareachability[link->areanum] = lreach; // reach_jumppad++; } //end for } //end if } //end if // if ( fabs( velocity[0] ) > 100 || fabs( velocity[1] ) > 100 ) { continue; } //check for areas we can reach with air control for ( area2num = 1; area2num < ( *aasworld ).numareas; area2num++ ) { visualize = qfalse; /* if (area2num == 3568) { for (link = areas; link; link = link->next_area) { if (link->areanum == 3380) { visualize = qtrue; botimport.Print(PRT_MESSAGE, "bah\n"); } //end if } //end for } //end if*/ //never try to go back to one of the original jumppad areas //and don't create reachabilities if they already exist for ( link = areas; link; link = link->next_area ) { if ( AAS_ReachabilityExists( link->areanum, area2num ) ) { break; } if ( AAS_AreaJumpPad( link->areanum ) ) { if ( link->areanum == area2num ) { break; } } //end if } //end if if ( link ) { continue; } // area2 = &( *aasworld ).areas[area2num]; for ( i = 0; i < area2->numfaces; i++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + i]; face2 = &( *aasworld ).faces[abs( face2num )]; //if it is not a ground face if ( !( face2->faceflags & FACE_GROUND ) ) { continue; } //get the center of the face AAS_FaceCenter( face2num, facecenter ); //only go higher up if ( facecenter[2] < areastart[2] ) { continue; } //get the jumppad jump z velocity zvel = velocity[2]; //get the horizontal speed for the jump, if it isn't possible to calculate this //speed (the jump is not possible) then there's no jump reachability created ret = AAS_HorizontalVelocityForJump( zvel, areastart, facecenter, &speed ); if ( ret && speed < 150 ) { //direction towards the face center VectorSubtract( facecenter, areastart, dir ); dir[2] = 0; hordist = VectorNormalize( dir ); //if (hordist < 1.6 * facecenter[2] - areastart[2]) { //get command movement VectorScale( dir, speed, cmdmove ); // AAS_PredictClientMovement( &move, -1, areastart, PRESENCE_NORMAL, qfalse, velocity, cmdmove, 30, 30, 0.1, SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER | SE_HITGROUNDAREA, area2num, visualize ); //if prediction time wasn't enough to fully predict the movement //don't enter slime or lava and don't fall from too high if ( move.frames < 30 && !( move.stopevent & ( SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE ) ) && ( move.stopevent & ( SE_HITGROUNDAREA | SE_TOUCHJUMPPAD | SE_TOUCHTELEPORTER ) ) ) { for ( link = areas; link; link = link->next_area ) { if ( !AAS_AreaJumpPad( link->areanum ) ) { continue; } if ( AAS_ReachabilityExists( link->areanum, area2num ) ) { continue; } //create a jumppad reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { AAS_UnlinkFromAreas( areas ); return; } //end if lreach->areanum = area2num; //NOTE: the facenum is the Z velocity lreach->facenum = velocity[2]; //NOTE: the edgenum is the horizontal velocity lreach->edgenum = sqrt( cmdmove[0] * cmdmove[0] + cmdmove[1] * cmdmove[1] ); VectorCopy( areastart, lreach->start ); VectorCopy( facecenter, lreach->end ); lreach->traveltype = TRAVEL_JUMPPAD; lreach->traveltime = 250; lreach->next = areareachability[link->areanum]; areareachability[link->areanum] = lreach; // reach_jumppad++; } //end for } //end if } //end if } //end for } //end for } //end for AAS_UnlinkFromAreas( areas ); } //end for } //end of the function AAS_Reachability_JumpPad //=========================================================================== // never point at ground faces // always a higher and pretty far area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_Grapple( int area1num, int area2num ) { int face2num, i, j, areanum, numareas, areas[20]; float mingrappleangle, z, hordist; bsp_trace_t bsptrace; aas_trace_t trace; aas_face_t *face2; aas_area_t *area1, *area2; aas_lreachability_t *lreach; vec3_t areastart, facecenter, start, end, dir, down = {0, 0, -1}; vec_t *v; //only grapple when on the ground or swimming if ( !AAS_AreaGrounded( area1num ) && !AAS_AreaSwim( area1num ) ) { return qfalse; } //don't grapple from a crouch area if ( !( AAS_AreaPresenceType( area1num ) & PRESENCE_NORMAL ) ) { return qfalse; } //NOTE: disabled area swim it doesn't work right if ( AAS_AreaSwim( area1num ) ) { return qfalse; } // area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; //don't grapple towards way lower areas if ( area2->maxs[2] < area1->mins[2] ) { return qfalse; } // VectorCopy( ( *aasworld ).areas[area1num].center, start ); //if not a swim area if ( !AAS_AreaSwim( area1num ) ) { if ( !AAS_PointAreaNum( start ) ) { Log_Write( "area %d center %f %f %f in solid?\r\n", area1num, start[0], start[1], start[2] ); } VectorCopy( start, end ); end[2] -= 1000; trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, -1 ); if ( trace.startsolid ) { return qfalse; } VectorCopy( trace.endpos, areastart ); } //end if else { if ( !( AAS_PointContents( start ) & ( CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER ) ) ) { return qfalse; } } //end else // //start is now the start point // for ( i = 0; i < area2->numfaces; i++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + i]; face2 = &( *aasworld ).faces[abs( face2num )]; //if it is not a solid face if ( !( face2->faceflags & FACE_SOLID ) ) { continue; } //direction towards the first vertex of the face v = ( *aasworld ).vertexes[( *aasworld ).edges[abs( ( *aasworld ).edgeindex[face2->firstedge] )].v[0]]; VectorSubtract( v, areastart, dir ); //if the face plane is facing away if ( DotProduct( ( *aasworld ).planes[face2->planenum].normal, dir ) > 0 ) { continue; } //get the center of the face AAS_FaceCenter( face2num, facecenter ); //only go higher up with the grapple if ( facecenter[2] < areastart[2] + 64 ) { continue; } //only use vertical faces or downward facing faces if ( DotProduct( ( *aasworld ).planes[face2->planenum].normal, down ) < 0 ) { continue; } //direction towards the face center VectorSubtract( facecenter, areastart, dir ); // z = dir[2]; dir[2] = 0; hordist = VectorLength( dir ); if ( !hordist ) { continue; } //if too far if ( hordist > 2000 ) { continue; } //check the minimal angle of the movement mingrappleangle = 15; //15 degrees if ( z / hordist < tan( 2 * M_PI * mingrappleangle / 360 ) ) { continue; } // VectorCopy( facecenter, start ); VectorMA( facecenter, -500, ( *aasworld ).planes[face2->planenum].normal, end ); // bsptrace = AAS_Trace( start, NULL, NULL, end, 0, CONTENTS_SOLID ); //the grapple won't stick to the sky and the grapple point should be near the AAS wall if ( ( bsptrace.surface.flags & SURF_SKY ) || ( bsptrace.fraction * 500 > 32 ) ) { continue; } //trace a full bounding box from the area center on the ground to //the center of the face VectorSubtract( facecenter, areastart, dir ); VectorNormalize( dir ); VectorMA( areastart, 4, dir, start ); VectorCopy( bsptrace.endpos, end ); trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, -1 ); VectorSubtract( trace.endpos, facecenter, dir ); if ( VectorLength( dir ) > 24 ) { continue; } // VectorCopy( trace.endpos, start ); VectorCopy( trace.endpos, end ); end[2] -= AAS_FallDamageDistance(); trace = AAS_TraceClientBBox( start, end, PRESENCE_NORMAL, -1 ); if ( trace.fraction >= 1 ) { continue; } //area to end in areanum = AAS_PointAreaNum( trace.endpos ); //if not in lava or slime if ( ( *aasworld ).areasettings[areanum].contents & AREACONTENTS_LAVA ) { //----(SA) modified since slime is no longer deadly // if ((*aasworld).areasettings[areanum].contents & (AREACONTENTS_SLIME|AREACONTENTS_LAVA)) continue; } //end if //do not go the the source area if ( areanum == area1num ) { continue; } //don't create reachabilities if they already exist if ( AAS_ReachabilityExists( area1num, areanum ) ) { continue; } //only end in areas we can stand if ( !AAS_AreaGrounded( areanum ) ) { continue; } //never go through cluster portals!! numareas = AAS_TraceAreas( areastart, bsptrace.endpos, areas, NULL, 20 ); if ( numareas >= 20 ) { continue; } for ( j = 0; j < numareas; j++ ) { if ( ( *aasworld ).areasettings[areas[j]].contents & AREACONTENTS_CLUSTERPORTAL ) { break; } } //end for if ( j < numareas ) { continue; } //create a new reachability link lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = areanum; lreach->facenum = face2num; lreach->edgenum = 0; VectorCopy( areastart, lreach->start ); //VectorCopy(facecenter, lreach->end); VectorCopy( bsptrace.endpos, lreach->end ); lreach->traveltype = TRAVEL_GRAPPLEHOOK; VectorSubtract( lreach->end, lreach->start, dir ); lreach->traveltime = STARTGRAPPLE_TIME + VectorLength( dir ) * 0.25; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_grapple++; } //end for // return qfalse; } //end of the function AAS_Reachability_Grapple //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_SetWeaponJumpAreaFlags( void ) { int ent, i; vec3_t mins = {-15, -15, -15}, maxs = {15, 15, 15}; vec3_t origin; int areanum, weaponjumpareas, spawnflags; char classname[MAX_EPAIRKEY]; weaponjumpareas = 0; for ( ent = AAS_NextBSPEntity( 0 ); ent; ent = AAS_NextBSPEntity( ent ) ) { if ( !AAS_ValueForBSPEpairKey( ent, "classname", classname, MAX_EPAIRKEY ) ) { continue; } if ( !strcmp( classname, "item_armor_body" ) || !strcmp( classname, "item_armor_combat" ) || !strcmp( classname, "item_health_mega" ) || !strcmp( classname, "weapon_grenadelauncher" ) || !strcmp( classname, "weapon_rocketlauncher" ) || !strcmp( classname, "weapon_lightning" ) || !strcmp( classname, "weapon_sp5" ) || !strcmp( classname, "weapon_railgun" ) || !strcmp( classname, "weapon_bfg" ) || !strcmp( classname, "item_quad" ) || !strcmp( classname, "item_regen" ) || !strcmp( classname, "item_invulnerability" ) ) { if ( AAS_VectorForBSPEpairKey( ent, "origin", origin ) ) { spawnflags = 0; AAS_IntForBSPEpairKey( ent, "spawnflags", &spawnflags ); //if not a stationary item if ( !( spawnflags & 1 ) ) { if ( !AAS_DropToFloor( origin, mins, maxs ) ) { botimport.Print( PRT_MESSAGE, "%s in solid at (%1.1f %1.1f %1.1f)\n", classname, origin[0], origin[1], origin[2] ); } //end if } //end if //areanum = AAS_PointAreaNum(origin); areanum = AAS_BestReachableArea( origin, mins, maxs, origin ); //the bot may rocket jump towards this area ( *aasworld ).areasettings[areanum].areaflags |= AREA_WEAPONJUMP; // if ( !AAS_AreaGrounded( areanum ) ) { botimport.Print( PRT_MESSAGE, "area not grounded\n" ); } // weaponjumpareas++; } //end if } //end if } //end for for ( i = 1; i < ( *aasworld ).numareas; i++ ) { if ( ( *aasworld ).areasettings[i].contents & AREACONTENTS_JUMPPAD ) { ( *aasworld ).areasettings[i].areaflags |= AREA_WEAPONJUMP; weaponjumpareas++; } //end if } //end for botimport.Print( PRT_MESSAGE, "%d weapon jump areas\n", weaponjumpareas ); } //end of the function AAS_SetWeaponJumpAreaFlags //=========================================================================== // create a possible weapon jump reachability from area1 to area2 // // check if there's a cool item in the second area // check if area1 is lower than area2 // check if the bot can rocketjump from area1 to area2 // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== int AAS_Reachability_WeaponJump( int area1num, int area2num ) { int face2num, i, n, ret; float speed, zvel, hordist; aas_face_t *face2; aas_area_t *area1, *area2; aas_lreachability_t *lreach; vec3_t areastart, facecenter, start, end, dir, cmdmove; // teststart; vec3_t velocity; aas_clientmove_t move; aas_trace_t trace; if ( !AAS_AreaGrounded( area1num ) || AAS_AreaSwim( area1num ) ) { return qfalse; } if ( !AAS_AreaGrounded( area2num ) ) { return qfalse; } //NOTE: only weapon jump towards areas with an interesting item in it?? if ( !( ( *aasworld ).areasettings[area2num].areaflags & AREA_WEAPONJUMP ) ) { return qfalse; } // area1 = &( *aasworld ).areas[area1num]; area2 = &( *aasworld ).areas[area2num]; //don't weapon jump towards way lower areas if ( area2->maxs[2] < area1->mins[2] ) { return qfalse; } // VectorCopy( ( *aasworld ).areas[area1num].center, start ); //if not a swim area if ( !AAS_PointAreaNum( start ) ) { Log_Write( "area %d center %f %f %f in solid?\r\n", area1num, start[0], start[1], start[2] ); } VectorCopy( start, end ); end[2] -= 1000; trace = AAS_TraceClientBBox( start, end, PRESENCE_CROUCH, -1 ); if ( trace.startsolid ) { return qfalse; } VectorCopy( trace.endpos, areastart ); // //areastart is now the start point // for ( i = 0; i < area2->numfaces; i++ ) { face2num = ( *aasworld ).faceindex[area2->firstface + i]; face2 = &( *aasworld ).faces[abs( face2num )]; //if it is not a solid face if ( !( face2->faceflags & FACE_GROUND ) ) { continue; } //get the center of the face AAS_FaceCenter( face2num, facecenter ); //only go higher up with weapon jumps if ( facecenter[2] < areastart[2] + 64 ) { continue; } //NOTE: set to 2 to allow bfg jump reachabilities for ( n = 0; n < 1 /*2*/; n++ ) { //get the rocket jump z velocity if ( n ) { zvel = AAS_BFGJumpZVelocity( areastart ); } else { zvel = AAS_RocketJumpZVelocity( areastart );} //get the horizontal speed for the jump, if it isn't possible to calculate this //speed (the jump is not possible) then there's no jump reachability created ret = AAS_HorizontalVelocityForJump( zvel, areastart, facecenter, &speed ); if ( ret && speed < 270 ) { //direction towards the face center VectorSubtract( facecenter, areastart, dir ); dir[2] = 0; hordist = VectorNormalize( dir ); //if (hordist < 1.6 * (facecenter[2] - areastart[2])) { //get command movement VectorScale( dir, speed, cmdmove ); VectorSet( velocity, 0, 0, zvel ); /* //get command movement VectorScale(dir, speed, velocity); velocity[2] = zvel; VectorSet(cmdmove, 0, 0, 0); */ // AAS_PredictClientMovement( &move, -1, areastart, PRESENCE_NORMAL, qtrue, velocity, cmdmove, 30, 30, 0.1, SE_ENTERWATER | SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE | SE_TOUCHJUMPPAD | SE_HITGROUNDAREA, area2num, qfalse ); //if prediction time wasn't enough to fully predict the movement //don't enter slime or lava and don't fall from too high if ( move.frames < 30 && !( move.stopevent & ( SE_ENTERSLIME | SE_ENTERLAVA | SE_HITGROUNDDAMAGE ) ) && ( move.stopevent & ( SE_HITGROUNDAREA | SE_TOUCHJUMPPAD ) ) ) { //create a rocket or bfg jump reachability from area1 to area2 lreach = AAS_AllocReachability(); if ( !lreach ) { return qfalse; } lreach->areanum = area2num; lreach->facenum = 0; lreach->edgenum = 0; VectorCopy( areastart, lreach->start ); VectorCopy( facecenter, lreach->end ); if ( n ) { lreach->traveltype = TRAVEL_BFGJUMP; } else { lreach->traveltype = TRAVEL_ROCKETJUMP;} lreach->traveltime = 300; lreach->next = areareachability[area1num]; areareachability[area1num] = lreach; // reach_rocketjump++; return qtrue; } //end if } //end if } //end if } //end for } //end for // return qfalse; } //end of the function AAS_Reachability_WeaponJump //=========================================================================== // calculates additional walk off ledge reachabilities for the given area // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_Reachability_WalkOffLedge( int areanum ) { int i, j, k, l, m, n; int face1num, face2num, face3num, edge1num, edge2num, edge3num; int otherareanum, gap, reachareanum, side; aas_area_t *area, *area2; aas_face_t *face1, *face2, *face3; aas_edge_t *edge; aas_plane_t *plane; vec_t *v1, *v2; vec3_t sharededgevec, mid, dir, testend; aas_lreachability_t *lreach; aas_trace_t trace; if ( !AAS_AreaGrounded( areanum ) || AAS_AreaSwim( areanum ) ) { return; } // area = &( *aasworld ).areas[areanum]; // for ( i = 0; i < area->numfaces; i++ ) { face1num = ( *aasworld ).faceindex[area->firstface + i]; face1 = &( *aasworld ).faces[abs( face1num )]; //face 1 must be a ground face if ( !( face1->faceflags & FACE_GROUND ) ) { continue; } //go through all the edges of this ground face for ( k = 0; k < face1->numedges; k++ ) { edge1num = ( *aasworld ).edgeindex[face1->firstedge + k]; //find another not ground face using this same edge for ( j = 0; j < area->numfaces; j++ ) { face2num = ( *aasworld ).faceindex[area->firstface + j]; face2 = &( *aasworld ).faces[abs( face2num )]; //face 2 may not be a ground face if ( face2->faceflags & FACE_GROUND ) { continue; } //compare all the edges for ( l = 0; l < face2->numedges; l++ ) { edge2num = ( *aasworld ).edgeindex[face2->firstedge + l]; if ( abs( edge1num ) == abs( edge2num ) ) { //get the area at the other side of the face if ( face2->frontarea == areanum ) { otherareanum = face2->backarea; } else { otherareanum = face2->frontarea;} // area2 = &( *aasworld ).areas[otherareanum]; //if the other area is grounded! if ( ( *aasworld ).areasettings[otherareanum].areaflags & AREA_GROUNDED ) { //check for a possible gap gap = qfalse; for ( n = 0; n < area2->numfaces; n++ ) { face3num = ( *aasworld ).faceindex[area2->firstface + n]; //may not be the shared face of the two areas if ( abs( face3num ) == abs( face2num ) ) { continue; } // face3 = &( *aasworld ).faces[abs( face3num )]; //find an edge shared by all three faces for ( m = 0; m < face3->numedges; m++ ) { edge3num = ( *aasworld ).edgeindex[face3->firstedge + m]; //but the edge should be shared by all three faces if ( abs( edge3num ) == abs( edge1num ) ) { if ( !( face3->faceflags & FACE_SOLID ) ) { gap = qtrue; break; } //end if // if ( face3->faceflags & FACE_GROUND ) { gap = qfalse; break; } //end if //FIXME: there are more situations to be handled gap = qtrue; break; } //end if } //end for if ( m < face3->numedges ) { break; } } //end for if ( !gap ) { break; } } //end if //check for a walk off ledge reachability edge = &( *aasworld ).edges[abs( edge1num )]; side = edge1num < 0; // v1 = ( *aasworld ).vertexes[edge->v[side]]; v2 = ( *aasworld ).vertexes[edge->v[!side]]; // plane = &( *aasworld ).planes[face1->planenum]; //get the points really into the areas VectorSubtract( v2, v1, sharededgevec ); CrossProduct( plane->normal, sharededgevec, dir ); VectorNormalize( dir ); // VectorAdd( v1, v2, mid ); VectorScale( mid, 0.5, mid ); VectorMA( mid, 8, dir, mid ); // VectorCopy( mid, testend ); testend[2] -= 1000; trace = AAS_TraceClientBBox( mid, testend, PRESENCE_CROUCH, -1 ); // if ( trace.startsolid ) { //Log_Write("area %d: trace.startsolid\r\n", areanum); break; } //end if reachareanum = AAS_PointAreaNum( trace.endpos ); if ( reachareanum == areanum ) { //Log_Write("area %d: same area\r\n", areanum); break; } //end if if ( AAS_ReachabilityExists( areanum, reachareanum ) ) { //Log_Write("area %d: reachability already exists\r\n", areanum); break; } //end if if ( !AAS_AreaGrounded( reachareanum ) && !AAS_AreaSwim( reachareanum ) ) { //Log_Write("area %d, reach area %d: not grounded and not swim\r\n", areanum, reachareanum); break; } //end if // if ( ( *aasworld ).areasettings[reachareanum].contents & AREACONTENTS_LAVA ) { //----(SA) modified since slime is no longer deadly // if ((*aasworld).areasettings[reachareanum].contents & (AREACONTENTS_SLIME | AREACONTENTS_LAVA)) //Log_Write("area %d, reach area %d: lava or slime\r\n", areanum, reachareanum); break; } //end if lreach = AAS_AllocReachability(); if ( !lreach ) { break; } lreach->areanum = reachareanum; lreach->facenum = 0; lreach->edgenum = edge1num; VectorCopy( mid, lreach->start ); VectorCopy( trace.endpos, lreach->end ); lreach->traveltype = TRAVEL_WALKOFFLEDGE; lreach->traveltime = STARTWALKOFFLEDGE_TIME + fabs( mid[2] - trace.endpos[2] ) * 50 / aassettings.sv_gravity; if ( !AAS_AreaSwim( reachareanum ) && !AAS_AreaJumpPad( reachareanum ) ) { if ( AAS_FallDelta( mid[2] - trace.endpos[2] ) > FALLDELTA_5DAMAGE ) { lreach->traveltime += FALLDAMAGE_5_TIME; } //end if else if ( AAS_FallDelta( mid[2] - trace.endpos[2] ) > FALLDELTA_10DAMAGE ) { lreach->traveltime += FALLDAMAGE_10_TIME; } //end if } //end if lreach->next = areareachability[areanum]; areareachability[areanum] = lreach; //we've got another walk off ledge reachability reach_walkoffledge++; } //end if } //end for } //end for } //end for } //end for } //end of the function AAS_Reachability_WalkOffLedge //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_StoreReachability( void ) { int i; aas_areasettings_t *areasettings; aas_lreachability_t *lreach; aas_reachability_t *reach; if ( ( *aasworld ).reachability ) { FreeMemory( ( *aasworld ).reachability ); } ( *aasworld ).reachability = (aas_reachability_t *) GetClearedMemory( ( numlreachabilities + 10 ) * sizeof( aas_reachability_t ) ); ( *aasworld ).reachabilitysize = 1; for ( i = 0; i < ( *aasworld ).numareas; i++ ) { areasettings = &( *aasworld ).areasettings[i]; areasettings->firstreachablearea = ( *aasworld ).reachabilitysize; areasettings->numreachableareas = 0; for ( lreach = areareachability[i]; lreach; lreach = lreach->next ) { reach = &( *aasworld ).reachability[areasettings->firstreachablearea + areasettings->numreachableareas]; reach->areanum = lreach->areanum; reach->facenum = lreach->facenum; reach->edgenum = lreach->edgenum; VectorCopy( lreach->start, reach->start ); VectorCopy( lreach->end, reach->end ); reach->traveltype = lreach->traveltype; reach->traveltime = lreach->traveltime; // RF, enforce the min reach time if ( reach->traveltime < REACH_MIN_TIME ) { reach->traveltime = REACH_MIN_TIME; } // areasettings->numreachableareas++; } //end for ( *aasworld ).reachabilitysize += areasettings->numreachableareas; } //end for } //end of the function AAS_StoreReachability //=========================================================================== // // TRAVEL_WALK 100% equal floor height + steps // TRAVEL_CROUCH 100% // TRAVEL_BARRIERJUMP 100% // TRAVEL_JUMP 80% // TRAVEL_LADDER 100% + fall down from ladder + jump up to ladder // TRAVEL_WALKOFFLEDGE 90% walk off very steep walls? // TRAVEL_SWIM 100% // TRAVEL_WATERJUMP 100% // TRAVEL_TELEPORT 100% // TRAVEL_ELEVATOR 100% // TRAVEL_GRAPPLEHOOK 100% // TRAVEL_DOUBLEJUMP 0% // TRAVEL_RAMPJUMP 0% // TRAVEL_STRAFEJUMP 0% // TRAVEL_ROCKETJUMP 100% (currently limited towards areas with items) // TRAVEL_BFGJUMP 0% (currently disabled) // TRAVEL_JUMPPAD 100% // TRAVEL_FUNCBOB 100% // // Parameter: - // Returns: true if NOT finished // Changes Globals: - //=========================================================================== int AAS_ContinueInitReachability( float time ) { int i, j, todo, start_time; static float framereachability, reachability_delay; static int lastpercentage; if ( !( *aasworld ).loaded ) { return qfalse; } //if reachability is calculated for all areas if ( ( *aasworld ).reachabilityareas >= ( *aasworld ).numareas + 2 ) { return qfalse; } //if starting with area 1 (area 0 is a dummy) if ( ( *aasworld ).reachabilityareas == 1 ) { botimport.Print( PRT_MESSAGE, "calculating reachability...\n" ); lastpercentage = 0; framereachability = 2000; reachability_delay = 1000; } //end if //number of areas to calculate reachability for this cycle todo = ( *aasworld ).reachabilityareas + (int) framereachability; start_time = Sys_MilliSeconds(); //loop over the areas for ( i = ( *aasworld ).reachabilityareas; i < ( *aasworld ).numareas && i < todo; i++ ) { ( *aasworld ).reachabilityareas++; //only create jumppad reachabilities from jumppad areas if ( ( *aasworld ).areasettings[i].contents & AREACONTENTS_JUMPPAD ) { continue; } //end if //loop over the areas for ( j = 1; j < ( *aasworld ).numareas; j++ ) { if ( i == j ) { continue; } //never create reachabilities from teleporter or jumppad areas to regular areas if ( ( *aasworld ).areasettings[i].contents & ( AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD ) ) { if ( !( ( *aasworld ).areasettings[j].contents & ( AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD ) ) ) { continue; } //end if } //end if //if there already is a reachability link from area i to j if ( AAS_ReachabilityExists( i, j ) ) { continue; } //check for a swim reachability if ( AAS_Reachability_Swim( i, j ) ) { continue; } //check for a simple walk on equal floor height reachability if ( AAS_Reachability_EqualFloorHeight( i, j ) ) { continue; } //check for step, barrier, waterjump and walk off ledge reachabilities if ( AAS_Reachability_Step_Barrier_WaterJump_WalkOffLedge( i, j ) ) { continue; } //check for ladder reachabilities if ( AAS_Reachability_Ladder( i, j ) ) { continue; } //check for a jump reachability if ( AAS_Reachability_Jump( i, j ) ) { continue; } } //end for //never create these reachabilities from teleporter or jumppad areas if ( ( *aasworld ).areasettings[i].contents & ( AREACONTENTS_TELEPORTER | AREACONTENTS_JUMPPAD ) ) { continue; } //end if //loop over the areas for ( j = 1; j < ( *aasworld ).numareas; j++ ) { if ( i == j ) { continue; } // if ( AAS_ReachabilityExists( i, j ) ) { continue; } //check for a grapple hook reachability // Ridah, no grapple // AAS_Reachability_Grapple(i, j); //check for a weapon jump reachability // Ridah, no weapon jumping // AAS_Reachability_WeaponJump(i, j); } //end for //if the calculation took more time than the max reachability delay if ( Sys_MilliSeconds() - start_time > (int) reachability_delay ) { break; } // if ( ( *aasworld ).reachabilityareas * 1000 / ( *aasworld ).numareas > lastpercentage ) { break; } } //end for // if ( ( *aasworld ).reachabilityareas == ( *aasworld ).numareas ) { botimport.Print( PRT_MESSAGE, "\r%6.1f%%", (float) 100.0 ); botimport.Print( PRT_MESSAGE, "\nplease wait while storing reachability...\n" ); ( *aasworld ).reachabilityareas++; } //end if //if this is the last step in the reachability calculations else if ( ( *aasworld ).reachabilityareas == ( *aasworld ).numareas + 1 ) { //create additional walk off ledge reachabilities for every area for ( i = 1; i < ( *aasworld ).numareas; i++ ) { //only create jumppad reachabilities from jumppad areas if ( ( *aasworld ).areasettings[i].contents & AREACONTENTS_JUMPPAD ) { continue; } //end if AAS_Reachability_WalkOffLedge( i ); } //end for //create jump pad reachabilities AAS_Reachability_JumpPad(); //create teleporter reachabilities AAS_Reachability_Teleport(); //create elevator (func_plat) reachabilities AAS_Reachability_Elevator(); //create func_bobbing reachabilities AAS_Reachability_FuncBobbing(); // //#ifdef DEBUG botimport.Print( PRT_MESSAGE, "%6d reach swim\n", reach_swim ); botimport.Print( PRT_MESSAGE, "%6d reach equal floor\n", reach_equalfloor ); botimport.Print( PRT_MESSAGE, "%6d reach step\n", reach_step ); botimport.Print( PRT_MESSAGE, "%6d reach barrier\n", reach_barrier ); botimport.Print( PRT_MESSAGE, "%6d reach waterjump\n", reach_waterjump ); botimport.Print( PRT_MESSAGE, "%6d reach walkoffledge\n", reach_walkoffledge ); botimport.Print( PRT_MESSAGE, "%6d reach jump\n", reach_jump ); botimport.Print( PRT_MESSAGE, "%6d reach ladder\n", reach_ladder ); botimport.Print( PRT_MESSAGE, "%6d reach walk\n", reach_walk ); botimport.Print( PRT_MESSAGE, "%6d reach teleport\n", reach_teleport ); botimport.Print( PRT_MESSAGE, "%6d reach funcbob\n", reach_funcbob ); botimport.Print( PRT_MESSAGE, "%6d reach elevator\n", reach_elevator ); botimport.Print( PRT_MESSAGE, "%6d reach grapple\n", reach_grapple ); botimport.Print( PRT_MESSAGE, "%6d reach rocketjump\n", reach_rocketjump ); botimport.Print( PRT_MESSAGE, "%6d reach jumppad\n", reach_jumppad ); //#endif //*/ //store all the reachabilities AAS_StoreReachability(); //free the reachability link heap AAS_ShutDownReachabilityHeap(); // FreeMemory( areareachability ); // ( *aasworld ).reachabilityareas++; // botimport.Print( PRT_MESSAGE, "calculating clusters...\n" ); } //end if else { lastpercentage = ( *aasworld ).reachabilityareas * 1000 / ( *aasworld ).numareas; botimport.Print( PRT_MESSAGE, "\r%6.1f%%", (float) lastpercentage / 10 ); } //end else //not yet finished return qtrue; } //end of the function AAS_ContinueInitReachability //=========================================================================== // // Parameter: - // Returns: - // Changes Globals: - //=========================================================================== void AAS_InitReachability( void ) { if ( !( *aasworld ).loaded ) { return; } if ( ( *aasworld ).reachabilitysize ) { #ifndef BSPC if ( !( (int)LibVarGetValue( "forcereachability" ) ) ) { ( *aasworld ).reachabilityareas = ( *aasworld ).numareas + 2; return; } //end if #else ( *aasworld ).reachabilityareas = ( *aasworld ).numareas + 2; return; #endif //BSPC } //end if ( *aasworld ).savefile = qtrue; //start with area 1 because area zero is a dummy ( *aasworld ).reachabilityareas = 1; //setup the heap with reachability links AAS_SetupReachabilityHeap(); //allocate area reachability link array areareachability = (aas_lreachability_t **) GetClearedMemory( ( *aasworld ).numareas * sizeof( aas_lreachability_t * ) ); // AAS_SetWeaponJumpAreaFlags(); } //end of the function AAS_InitReachable
0
0.973185
1
0.973185
game-dev
MEDIA
0.987987
game-dev
0.96113
1
0.96113
keijiro/Teatro
4,996
Assets/Reaktion/Editor/Utility/ConstantMotionEditor.cs
// // Reaktion - An audio reactive animation toolkit for Unity. // // Copyright (C) 2013, 2014 Keijiro Takahashi // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using UnityEngine; using UnityEditor; using System.Collections; namespace Reaktion { // Custom property drawer for TransformElement. [CustomPropertyDrawer(typeof(ConstantMotion.TransformElement))] class ConstantMotionElementDrawer : PropertyDrawer { // Labels and values for TransformMode. static GUIContent[] modeLabels = { new GUIContent("Off"), new GUIContent("X Axis"), new GUIContent("Y Axis"), new GUIContent("Z Axis"), new GUIContent("Arbitrary Vector"), new GUIContent("Random Vector") }; static int[] modeValues = { 0, 1, 2, 3, 4, 5 }; static int GetExpansionLevel(SerializedProperty property) { var mode = property.FindPropertyRelative("mode"); // Fully expand if it has different values. if (mode.hasMultipleDifferentValues) return 2; // "Off" if (mode.enumValueIndex == 0) return 0; // Fully expand if it's in Arbitrary mode. if (mode.enumValueIndex == (int)ConstantMotion.TransformMode.Arbitrary) return 2; // Expand one level. return 1; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { int rows = new int[]{1, 3, 4}[GetExpansionLevel(property)]; return EditorGUIUtility.singleLineHeight * rows + EditorGUIUtility.standardVerticalSpacing * (rows - 1); } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); position.height = EditorGUIUtility.singleLineHeight; var rowHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; // Transform mode selector drop-down. EditorGUI.IntPopup(position, property.FindPropertyRelative("mode"), modeLabels, modeValues, label); position.y += rowHeight; var expansion = GetExpansionLevel(property); if (expansion > 0) { // Insert an indent. position.x += 16; position.width -= 16; EditorGUIUtility.labelWidth -= 16; if (expansion == 2) { // Vector box. EditorGUI.PropertyField(position, property.FindPropertyRelative("arbitraryVector"), GUIContent.none); position.y += rowHeight; } // Velocity box. EditorGUI.PropertyField(position, property.FindPropertyRelative("velocity"), new GUIContent("Velocity")); position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; // Randomness slider. EditorGUI.Slider(position, property.FindPropertyRelative("randomness"), 0, 1, new GUIContent("Randomness")); } EditorGUI.EndProperty(); } } [CustomEditor(typeof(ConstantMotion)), CanEditMultipleObjects] public class ConstantMotionEditor : Editor { SerializedProperty propPosition; SerializedProperty propRotation; SerializedProperty propUseLocalCoordinate; GUIContent labelLocalCoordinate; void OnEnable() { propPosition = serializedObject.FindProperty("position"); propRotation = serializedObject.FindProperty("rotation"); propUseLocalCoordinate = serializedObject.FindProperty("useLocalCoordinate"); labelLocalCoordinate = new GUIContent("Local Coordinate"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(propPosition); EditorGUILayout.PropertyField(propRotation); EditorGUILayout.PropertyField(propUseLocalCoordinate, labelLocalCoordinate); serializedObject.ApplyModifiedProperties(); } } } // namespace Reaktion
0
0.88215
1
0.88215
game-dev
MEDIA
0.848201
game-dev
0.915933
1
0.915933
xGinko/AnarchyExploitFixes
2,578
shared/src/main/java/me/xginko/aef/utils/permissions/LuckPermsPermissionHandler.java
package me.xginko.aef.utils.permissions; import me.xginko.aef.utils.EntityUtil; import me.xginko.aef.utils.enums.TriState; import net.luckperms.api.LuckPerms; import net.luckperms.api.model.user.User; import net.luckperms.api.node.Node; import net.luckperms.api.util.Tristate; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; import org.bukkit.plugin.java.JavaPlugin; import java.time.Duration; public final class LuckPermsPermissionHandler implements PermissionHandler { private final LuckPerms luckPerms; private final BukkitPermissionHandler bukkitPermissionHandler; private final boolean isCitizensInstalled; LuckPermsPermissionHandler(JavaPlugin plugin, Duration cacheDuration) { luckPerms = plugin.getServer().getServicesManager().getRegistration(LuckPerms.class).getProvider(); isCitizensInstalled = plugin.getServer().getPluginManager().getPlugin("Citizens") != null; bukkitPermissionHandler = new BukkitPermissionHandler(plugin, cacheDuration); // Fallback for non-players } @Override public void disable() { bukkitPermissionHandler.disable(); } @Override public TriState permissionValue(Permissible permissible, String permission) { if (!(permissible instanceof Player) || (isCitizensInstalled && EntityUtil.isNPC((Player) permissible))) return bukkitPermissionHandler.permissionValue(permissible, permission); final Tristate permState = luckPerms.getPlayerAdapter(Player.class).getUser((Player) permissible) .getCachedData().getPermissionData().checkPermission(permission); if (permState == Tristate.TRUE) return TriState.TRUE; if (permState == Tristate.FALSE) return TriState.FALSE; return TriState.UNDEFINED; } @Override public void setPermission(Permissible permissible, String permission, TriState state) { if (!(permissible instanceof Player) || (isCitizensInstalled && EntityUtil.isNPC((Player) permissible))) { bukkitPermissionHandler.setPermission(permissible, permission, state); return; } final User luckPermsUser = luckPerms.getPlayerAdapter(Player.class).getUser((Player) permissible); if (state == TriState.UNDEFINED) { luckPermsUser.data().remove(Node.builder(permission).build()); } else { luckPermsUser.data().add(Node.builder(permission).value(state.toBoolean()).build()); } luckPerms.getUserManager().saveUser(luckPermsUser); } }
0
0.870861
1
0.870861
game-dev
MEDIA
0.641725
game-dev
0.886822
1
0.886822
Dark-Basic-Software-Limited/Dark-Basic-Pro
1,902
SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/NarrowPhaseCollision/btPointCollector.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_POINT_COLLECTOR_H #define BT_POINT_COLLECTOR_H #include "btDiscreteCollisionDetectorInterface.h" struct btPointCollector : public btDiscreteCollisionDetectorInterface::Result { btVector3 m_normalOnBInWorld; btVector3 m_pointInWorld; btScalar m_distance;//negative means penetration bool m_hasResult; btPointCollector () : m_distance(btScalar(BT_LARGE_FLOAT)),m_hasResult(false) { } virtual void setShapeIdentifiersA(int partId0,int index0) { (void)partId0; (void)index0; } virtual void setShapeIdentifiersB(int partId1,int index1) { (void)partId1; (void)index1; } virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { if (depth< m_distance) { m_hasResult = true; m_normalOnBInWorld = normalOnBInWorld; m_pointInWorld = pointInWorld; //negative means penetration m_distance = depth; } } }; #endif //BT_POINT_COLLECTOR_H
0
0.856943
1
0.856943
game-dev
MEDIA
0.987122
game-dev
0.821747
1
0.821747
Arcnor/pixel-dungeon-gdx
7,273
core/src/com/watabou/pixeldungeon/ui/Toolbar.java
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.pixeldungeon.ui; import com.watabou.noosa.Game; import com.watabou.noosa.Gizmo; import com.watabou.noosa.Image; import com.watabou.noosa.ui.Button; import com.watabou.noosa.ui.Component; import com.watabou.pixeldungeon.Assets; import com.watabou.pixeldungeon.Dungeon; import com.watabou.pixeldungeon.DungeonTilemap; import com.watabou.pixeldungeon.input.GameAction; import com.watabou.pixeldungeon.items.Item; import com.watabou.pixeldungeon.scenes.CellSelector; import com.watabou.pixeldungeon.scenes.GameScene; import com.watabou.pixeldungeon.sprites.ItemSprite; import com.watabou.pixeldungeon.windows.WndBag; import com.watabou.pixeldungeon.windows.WndCatalogus; public class Toolbar extends Component { private Tool btnWait; private Tool btnSearch; private Tool btnInfo; private Tool btnResume; private Tool btnInventory; private Tool btnQuick; private PickedUpItem pickedUp; private boolean lastEnabled = true; public Toolbar() { super(); height = btnInventory.height(); } @Override protected void createChildren() { add( btnWait = new Tool( 0, 7, 20, 24, GameAction.REST ) { @Override protected void onClick() { restOneTurn(); } protected boolean onLongClick() { restFull(); return true; } private void restOneTurn() { Dungeon.hero.rest( false ); } private void restFull() { Dungeon.hero.rest( true ); } } ); add( btnSearch = new Tool( 20, 7, 20, 24, GameAction.SEARCH ) { @Override protected void onClick() { doSearch(); } private void doSearch() { Dungeon.hero.search( true ); } } ); add( btnInfo = new Tool( 40, 7, 21, 24, GameAction.CELL_INFO) { @Override protected void onClick() { getCellInfo(); } private void getCellInfo() { GameScene.selectCell(informer); } } ); add( btnResume = new Tool( 61, 7, 21, 24, GameAction.RESUME ) { @Override protected void onClick() { resume(); } private void resume() { Dungeon.hero.resume(); } } ); add( btnInventory = new Tool( 82, 7, 23, 24, GameAction.BACKPACK ) { private GoldIndicator gold; @Override protected void onClick() { showBackpack(); } @Override protected boolean onLongClick() { showCatalogus(); return true; } private void showBackpack() { GameScene.show(new WndBag(Dungeon.hero.belongings.backpack, null, WndBag.Mode.ALL, null)); } private void showCatalogus() { GameScene.show(new WndCatalogus()); } @Override protected void createChildren() { super.createChildren(); gold = new GoldIndicator(); add( gold ); } @Override protected void layout() { super.layout(); gold.fill( this ); } } ); add( btnQuick = new QuickslotTool( 105, 7, 22, 24 ) ); add( pickedUp = new PickedUpItem() ); } @Override protected void layout() { btnWait.setPos( x, y ); btnSearch.setPos( btnWait.right(), y ); btnInfo.setPos( btnSearch.right(), y ); btnResume.setPos( btnInfo.right(), y ); btnQuick.setPos( width - btnQuick.width(), y ); btnInventory.setPos( btnQuick.left() - btnInventory.width(), y ); } @Override public void update() { super.update(); if (lastEnabled != Dungeon.hero.ready) { lastEnabled = Dungeon.hero.ready; for (Gizmo tool : members) { if (tool instanceof Tool) { ((Tool)tool).enable( lastEnabled ); } } } btnResume.visible = Dungeon.hero.lastAction != null; if (!Dungeon.hero.isAlive()) { btnInventory.enable( true ); } } public void pickup( Item item ) { pickedUp.reset( item, btnInventory.centerX(), btnInventory.centerY() ); } private static CellSelector.Listener informer = new CellSelector.Listener() { @Override public void onSelect( Integer cell ) { GameScene.examineCell( cell ); } @Override public String prompt() { return "Select a cell to examine"; } }; private static class Tool extends Button<GameAction> { private static final int BGCOLOR = 0x7B8073; private Image base; public Tool(int x, int y, int width, int height, GameAction hotKey ) { super(); base.frame( x, y, width, height ); this.width = width; this.height = height; this.hotKey = hotKey; } @Override protected void createChildren() { super.createChildren(); base = new Image( Assets.TOOLBAR ); add( base ); } @Override protected void layout() { super.layout(); base.x = x; base.y = y; } @Override protected void onTouchDown() { base.brightness( 1.4f ); } @Override protected void onTouchUp() { if (active) { base.resetColor(); } else { base.tint( BGCOLOR, 0.7f ); } } public void enable( boolean value ) { if (value != active) { if (value) { base.resetColor(); } else { base.tint( BGCOLOR, 0.7f ); } active = value; } } } private static class QuickslotTool extends Tool { private QuickSlot slot; public QuickslotTool( int x, int y, int width, int height ) { super( x, y, width, height, null ); } @Override protected void createChildren() { super.createChildren(); slot = new QuickSlot(); add( slot ); } @Override protected void layout() { super.layout(); slot.setRect( x + 1, y + 2, width - 2, height - 2 ); } @Override public void enable( boolean value ) { slot.enable( value ); active = value; } } private static class PickedUpItem extends ItemSprite { private static final float DISTANCE = DungeonTilemap.SIZE; private static final float DURATION = 0.2f; private float dstX; private float dstY; private float left; public PickedUpItem() { super(); originToCenter(); active = visible = false; } public void reset( Item item, float dstX, float dstY ) { view( item.image(), item.glowing() ); active = visible = true; this.dstX = dstX - ItemSprite.SIZE / 2; this.dstY = dstY - ItemSprite.SIZE / 2; left = DURATION; x = this.dstX - DISTANCE; y = this.dstY - DISTANCE; alpha( 1 ); } @Override public void update() { super.update(); if ((left -= Game.elapsed) <= 0) { visible = active = false; } else { float p = left / DURATION; scale.set( (float)Math.sqrt( p ) ); float offset = DISTANCE * p; x = dstX - offset; y = dstY - offset; } } } }
0
0.954321
1
0.954321
game-dev
MEDIA
0.984923
game-dev
0.98968
1
0.98968
phillipchain/LoLServer
1,534
GameServerLib/Chatbox/Commands/SpeedCommand.cs
using LeagueSandbox.GameServer.Players; using LeagueSandbox.GameServer.GameObjects.StatsNS; namespace LeagueSandbox.GameServer.Chatbox.Commands { public class SpeedCommand : ChatCommandBase { private readonly PlayerManager _playerManager; public override string Command => "speed"; public override string Syntax => $"{Command} [flat speed] [percent speed]"; public SpeedCommand(ChatCommandManager chatCommandManager, Game game) : base(chatCommandManager, game) { _playerManager = game.PlayerManager; } public override void Execute(int userId, bool hasReceivedArguments, string arguments = "") { var split = arguments.ToLower().Split(' '); if (split.Length < 2 || split.Length > 3) { ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.SYNTAXERROR); ShowSyntax(); } try { StatsModifier stat = new StatsModifier(); if (split.Length == 3) { stat.MoveSpeed.PercentBonus = float.Parse(split[2]) / 100; } stat.MoveSpeed.FlatBonus = float.Parse(split[1]); _playerManager.GetPeerInfo(userId).Champion.AddStatModifier(stat); } catch { ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.SYNTAXERROR); ShowSyntax(); } } } }
0
0.785442
1
0.785442
game-dev
MEDIA
0.763709
game-dev
0.943369
1
0.943369
Dimbreath/AzurLaneData
7,181
en-US/mod/battle/data/wave/battlespawnwave.lua
ys = ys or {} slot0 = ys slot0.Battle.BattleSpawnWave = class("BattleSpawnWave", slot0.Battle.BattleWaveInfo) slot0.Battle.BattleSpawnWave.__name = "BattleSpawnWave" slot1 = slot0.Battle.BattleSpawnWave function slot1.Ctor(slot0) uv0.super.Ctor(slot0) slot0._spawnUnitList = {} slot0._monsterList = {} slot0._reinforceKillCount = 0 slot0._reinforceTotalKillCount = 0 slot0._airStrikeTimerList = {} slot0._spawnTimerList = {} slot0._reinforceSpawnTimerList = {} end function slot1.SetWaveData(slot0, slot1) uv0.super.SetWaveData(slot0, slot1) slot0._sapwnData = slot1.spawn or {} slot0._airStrike = slot1.airFighter or {} slot0._reinforce = slot1.reinforcement or {} slot0._reinforceCount = #slot0._reinforce slot0._spawnCount = #slot0._sapwnData slot0._reinforceDuration = slot0._reinforce.reinforceDuration or 0 slot0._reinforeceExpire = false slot0._round = slot0._param.round end function slot1.IsBossWave(slot0) slot1 = false for slot6, slot7 in ipairs(slot0._sapwnData) do if slot7.bossData then slot1 = true end end return slot1 end function slot1.DoWave(slot0) uv0.super.DoWave(slot0) if slot0._round then slot1 = false if uv1.Battle.BattleDataProxy.GetInstance():GetInitData().ChallengeInfo then slot3 = slot2:GetInitData().ChallengeInfo:getRound() if slot0._round.less and slot3 < slot0._round.less then slot1 = true end if slot0._round.more and slot0._round.more < slot3 then slot1 = true end if slot0._round.equal and table.contains(slot0._round.equal, slot3) then slot1 = true end end if not slot1 then slot0:doPass() return end end slot1 = 0 if PLATFORM_CODE == PLATFORM_CH then slot1 = 0.03 end for slot5, slot6 in ipairs(slot0._airStrike) do if slot6.delay + slot5 * slot1 <= 0 then slot0:doAirStrike(slot6) else slot0:airStrikeTimer(slot6, slot7) end end for slot6, slot7 in ipairs(slot0._sapwnData) do if slot7.bossData then slot2 = 0 + 1 end end for slot7, slot8 in ipairs(slot0._sapwnData) do if math.random() <= (slot8.chance or 1) then if slot8.bossData and slot2 > 1 then slot8.bossData.bossCount = 0 + 1 end if slot8.delay + slot7 * slot1 <= 0 then slot0:doSpawn(slot8) else slot0:spawnTimer(slot8, slot10, slot0._spawnTimerList) end else slot0._spawnCount = slot0._spawnCount - 1 end end if slot0._reinforce then slot0:doReinforce() end if slot0._spawnCount == 0 and slot0._reinforceDuration == 0 then slot0:doPass() end if slot0._reinforceDuration ~= 0 then slot0:reinforceDurationTimer(slot0._reinforceDuration) end uv1.Battle.BattleState.GenerateVertifyData(1) slot4, slot5 = uv1.Battle.BattleState.Vertify() if not slot4 then uv1.Battle.BattleState.GetInstance():GetCommandByName(uv1.Battle.BattleSingleDungeonCommand.__name):SetVertifyFail(100 + slot5) end end function slot1.AddMonster(slot0, slot1) if slot1:GetWaveIndex() ~= slot0._index then return end slot0._monsterList[slot1:GetUniqueID()] = slot1 end function slot1.RemoveMonster(slot0, slot1) slot0:onWaveUnitDie(slot1) end function slot1.doSpawn(slot0, slot1) slot2 = uv0.Battle.BattleConst.UnitType.ENEMY_UNIT if slot1.bossData then slot2 = uv0.Battle.BattleConst.UnitType.BOSS_UNIT end slot0._spawnFunc(slot1, slot0._index, slot2) end function slot1.spawnTimer(slot0, slot1, slot2, slot3) slot4 = nil slot3[pg.TimeMgr.GetInstance():AddBattleTimer("", 1, slot2, function () uv0[uv1] = nil uv2:doSpawn(uv3) pg.TimeMgr.GetInstance():RemoveBattleTimer(uv1) end, true)] = true end function slot1.doAirStrike(slot0, slot1) slot0._airFunc(slot1) end function slot1.airStrikeTimer(slot0, slot1, slot2) slot3 = nil slot0._airStrikeTimerList[pg.TimeMgr.GetInstance():AddBattleTimer("", 1, slot2, function () uv0._airStrikeTimerList[uv1] = nil uv0:doAirStrike(uv2) pg.TimeMgr.GetInstance():RemoveBattleTimer(uv1) end, true)] = true end function slot1.doReinforce(slot0) slot0._reinforceKillCount = 0 if slot0._reinforeceExpire then return end for slot4, slot5 in ipairs(slot0._reinforce) do slot5.reinforce = true if slot5.delay <= 0 then slot0:doSpawn(slot5) else slot0:spawnTimer(slot5, slot5.delay, slot0._reinforceSpawnTimerList) end end end function slot1.reinforceTimer(slot0, slot1) slot0:clearReinforceTimer() slot0._reinforceTimer = pg.TimeMgr.GetInstance():AddBattleTimer("", 1, slot1, function () uv0:doReinforce() uv0:clearReinforceTimer() end, true) end function slot1.clearReinforceTimer(slot0) pg.TimeMgr.GetInstance():RemoveBattleTimer(slot0._reinforceTimer) slot0._reinforceTimer = nil end function slot1.reinforceDurationTimer(slot0, slot1) slot0._reinforceDurationTimer = pg.TimeMgr.GetInstance():AddBattleTimer("", 1, slot1, function () pg.TimeMgr.GetInstance():RemoveBattleTimer(uv0._reinforceDurationTimer) uv0._reinforeceExpire = true uv0._reinforceDuration = nil uv0:clearReinforceTimer() uv0.clearTimerList(uv0._reinforceSpawnTimerList) if uv0._spawnCount == 0 then uv0:doPass() end end, true) end function slot1.clearReinforceDurationTimer(slot0) pg.TimeMgr.GetInstance():RemoveBattleTimer(slot0._reinforceDurationTimer) slot0._reinforceDurationTimer = nil end function slot1.onWaveUnitDie(slot0, slot1) if slot0._monsterList[slot1] == nil then return end slot3 = nil if slot2:IsReinforcement() then slot0._reinforceKillCount = slot0._reinforceKillCount + 1 slot0._reinforceTotalKillCount = slot0._reinforceTotalKillCount + 1 if slot0._reinforceCount ~= 0 and slot0._reinforceCount == slot0._reinforceKillCount then slot3 = true end end function slot4(slot0) if uv0 and slot0 then if slot0 == 0 then uv1:doReinforce() else uv1:reinforceTimer(slot0) end uv0 = false end end slot6 = 0 for slot10, slot11 in pairs(slot0._monsterList) do if slot11:IsAlive() == false then if not slot11:IsReinforcement() then slot5 = 0 + 1 end else slot6 = slot6 + 1 slot4(slot11:GetReinforceCastTime()) end end if slot0._reinforceDuration ~= 0 and not slot0._reinforeceExpire then slot4(0) end if slot6 == 0 and slot0._spawnCount <= slot5 and slot0._reinforceCount <= slot0._reinforceTotalKillCount and (slot0._reinforceDuration == 0 or slot0._reinforeceExpire) then slot0:doPass() end end function slot1.doPass(slot0) slot0.clearTimerList(slot0._spawnTimerList) slot0.clearTimerList(slot0._reinforceSpawnTimerList) slot0:clearReinforceTimer() slot0:clearReinforceDurationTimer() uv0.Battle.BattleDataProxy.GetInstance():KillWaveSummonMonster(slot0._index) uv1.super.doPass(slot0) end function slot1.clearTimerList(slot0) for slot4, slot5 in pairs(slot0) do pg.TimeMgr.GetInstance():RemoveBattleTimer(slot4) end end function slot1.Dispose(slot0) slot0.clearTimerList(slot0._airStrikeTimerList) slot0._airStrikeTimerList = nil slot0.clearTimerList(slot0._spawnTimerList) slot0._spawnTimerList = nil slot0.clearTimerList(slot0._reinforceSpawnTimerList) slot0._reinforceSpawnTimerList = nil slot0:clearReinforceTimer() slot0:clearReinforceDurationTimer() uv0.super.Dispose(slot0) end
0
0.662853
1
0.662853
game-dev
MEDIA
0.977403
game-dev
0.934333
1
0.934333
rochus-keller/OberonSystem3
52,433
Asteroids.Mod
(* OBERON System 3, Release 2.3. Copyright 1999 ETH Zürich Institute for Computer Systems, ETH Center, CH-8092 Zürich. e-mail: oberon@inf.ethz.ch. This module may be used under the conditions of the general Oberon System 3 license contract. The full text can be downloaded from "ftp://ftp.inf.ethz.ch/pub/software/Oberon/System3/license.txt;A" Under the license terms stated it is in particular (a) prohibited to modify the interface of this module in any way that disagrees with the style or content of the system and (b) requested to provide all conversions of the source code to another platform with the name OBERON. *) MODULE Asteroids; (** portable *) (* by W. Ibl *) (* Aug '96 V 1.0 first release Sep '96 V1.1 added ship placement Feb '97 V1.2 fixed the marker trap Feb '97 V1.3 ported to release 2.2 July '97 V1.4 FileMessage Bug removed Aug '97 V1.4 drawing of selected panel updated Okt '97 V1.5 added pause button *) IMPORT Attributes,Desktops,Display,Display3,Documents,Effects,Files,Fonts, Gadgets,Strings,Modules,Math,Oberon,Objects,Out,Panels, RandomNumbers; CONST (* Program version *) Version = "V 1.5"; Date = "August '97"; (* last compatible Program version *) CompVers = "V 1.5"; (* Standard Document strings *) DefName = "Asteroids.Doc"; DocMenu1 = "Desktops.StoreDoc[Store] Asteroids.NewGame[New] Asteroids.PauseGame[Pause]"; DocMenu2 = "Desktops.StoreDoc[Store] Asteroids.NewGame[New] Asteroids.ResumeGame[Cont]"; DocIcon = "Icons3.Asteroids"; (* who wants to live forever? *) Indestructable = FALSE; (* standard timer delay *) BaseDelay = 16; (* Control: Turn Left, Turn Right, Accelerate and Brake *) ChThrust = 0C1X; ChTurnRight = 0C3X; ChTurnLeft = 0C4X; ChFire = " "; ChShield = "z"; ChWarp = "x"; (* amount of ships in credit *) StartShips = 3; (* spaceship parameters and starting values *) ShipRotvel = 0.05; (* rotation velocity inc/decrement per keypress *) ShipThrust = 0.3; (* thrust inc/decrement per keypress *) ShipShield = 100; (* shield energy on stock *) ShipWarp = 10; (* warps on stock *) (* ship's bullet parameters and starting values *) SBulletMax = 5; (* Max. of ships' bullets in space at a time *) SBulletSpd = 5.0; (* Speed of ships' bullets *) SBulletGrant = 100; (* amount of ticks a bullet is active *) SBulletCost = 10; (* score decrement per fired bullet *) (* timer rounds where shield is stable *) SShieldGrant = 5; (* factor for ufo appearance - less is more seldom *) EAppear = 8000; (* RAND < (frame/EAppear) *) (* ufo's bullet parameters and starting values *) EBulletMax = 1; (* Max. of ufos' bullets in space at a time *) EBulletSpd = 2.0; (* Speed of ufos' bullets *) EBulletGrant = 200; (* amount of ticks a bullet is active *) (* detonation parameters *) DetonationMax = 50; (* Max. radius of a detonation circle *) DetonationStep = 1; (* radius increment per tick *) (* score adds *) HitScoreE1 = 100; (* hit ufo *) HitScoreA1 = 50; (* hit big asteroid *) HitScoreA2 = 70; (* hit medium asteroid *) HitScoreA3 = 80; (* hit small asteroid *) StartAsts = 4; (* amount of asteroids at first level *) SplitAsts = 2; (* amount of asteroids appearing after detonation *) TYPE Object = Objects.Object; Document = Documents.Document; (* Message Shortcuts *) AttrMsg = Objects.AttrMsg; CopyMsg = Objects.CopyMsg; DisplayMsg = Display.DisplayMsg; FileMsg = Objects.FileMsg; InputMsg = Oberon.InputMsg; LinkMsg = Objects.LinkMsg; ModifyMsg = Display.ModifyMsg; UpdateMsg = Gadgets.UpdateMsg; (* used for updating the Document's Menu Buttons *) MenuMsg = RECORD(Display.FrameMsg) frame: Display.Frame; paused: BOOLEAN; END; Vertices = POINTER TO ARRAY OF INTEGER; (* the asteroid field *) Starfield = POINTER TO StarfieldDesc; StarfieldDesc = RECORD(Panels.PanelDesc) scaleX,scaleY: REAL; fdx: INTEGER; END; (* vertices of game figures *) Shape = POINTER TO ShapeDesc; ShapeDesc = RECORD n: INTEGER; px,py: Vertices; END; (* object in the starfield space *) SpaceObj = POINTER TO SpaceObjDesc; SpaceObjDesc = RECORD x,y,x0,y0: REAL; alive: BOOLEAN; next: SpaceObj; END; (* Detonation - a continuous expanding circle *) Detonation = POINTER TO DetonationDesc; DetonationDesc = RECORD(SpaceObjDesc) r0,r: INTEGER; END; (* hitable object in the starfield space *) Mass = POINTER TO MassDesc; MassDesc = RECORD(SpaceObjDesc) mass: LONGREAL; rot,xvel,yvel,rotvel: REAL; shape: Shape; n0,u,v,w,h: INTEGER; px0,py0,px1,py1: Vertices; END; (* controlled moving object *) FlyingObj = POINTER TO FlyingObjDesc; FlyingObjDesc = RECORD(MassDesc) bullets: INTEGER; END; (* fired bullet *) Bullet = POINTER TO BulletDesc; BulletDesc = RECORD(MassDesc) time,rpos: INTEGER; ship: FlyingObj; END; (* player's ship *) Ship = POINTER TO ShipDesc; ShipDesc = RECORD(FlyingObjDesc) thrust0,thrust: BOOLEAN; shield0,shield: SHORTINT; shieldval,warpval: INTEGER; shape0: Shape; px2,py2: Vertices; END; (* an ufo - god knows where it comes from and why *) Enemy = POINTER TO EnemyDesc; EnemyDesc = RECORD(FlyingObjDesc) END; (* ship's bullet *) SBullet = POINTER TO SBulletDesc; SBulletDesc = RECORD(BulletDesc) END; (* ufo's bullet *) EBullet = POINTER TO EBulletDesc; EBulletDesc = RECORD(BulletDesc) END; (* the "real" enemies *) Asteroid = POINTER TO AsteroidDesc; AsteroidDesc = RECORD(MassDesc) END; (* the game's model *) Field = POINTER TO FieldDesc; FieldDesc = RECORD(Gadgets.ObjDesc) ship: Ship; started,changed,paused: BOOLEAN; ships,ufos,frames: INTEGER; score,high0,high: LONGINT; line0,line: ARRAY 80 OF CHAR; objects: SpaceObj; END; (* sometimes, we need a kick... *) Timer = POINTER TO TimerDesc; TimerDesc = RECORD(Oberon.TaskDesc) model: Field; trigger: LONGINT; tnext: Timer; END; VAR shAsteroid1,shAsteroid2,shAsteroid3, (* standard shapes *) shEnemy,shEBullet, shShip,shThrShip,shSBullet: Shape; hitscore: ARRAY 4 OF INTEGER; (* score increments per figure *) fnt: ARRAY 7 OF Fonts.Font; (* score line resize *) fw,fh: ARRAY 7 OF INTEGER; b,w: INTEGER; (* drawing colors *) timer: Timer; (* active kickers *) PROCEDURE FontGeometry(IN dim: ARRAY OF CHAR; fdx: INTEGER); (* query font's parameters for zooming *) VAR fn: Objects.Name; fd: INTEGER; BEGIN fn := "Oberon"; Strings.Append(fn,dim); Strings.Append(fn,".Scn.Fnt"); fnt[fdx]:= Fonts.This(fn); Display3.StringSize("X",fnt[fdx],fw[fdx],fh[fdx],fd); END FontGeometry; PROCEDURE Intersect(x11,y11,x12,y12,x21,y21,x22,y22: INTEGER; VAR x3,y3: INTEGER): BOOLEAN; (* calculate intersection between two lines, point is in (x3,y3) *) VAR k1,k2,d1,d2: REAL; h1,h2: BOOLEAN; PROCEDURE Within(c,a,b: INTEGER): BOOLEAN; (* interval calculation *) BEGIN IF (a < b) THEN RETURN((c>a)&(c<b)); ELSE RETURN((c>=b)&(c<=a)); END; END Within; BEGIN h1:= (x11 = x12); h2:= (x21 = x22); IF ~h1 THEN k1:= (y12 - y11) / (x12 - x11); d1:= y11 - (k1 * x11); END; IF ~h2 THEN k2:= (y22 - y21) / (x22 - x21); d2:= y21 - (k2 * x21); END; IF ~h1 & ~h2 THEN IF (k1 = k2) THEN x3:= -1; y3:= -1; RETURN(FALSE); END; x3:= SHORT(ENTIER((d2 - d1) / (k1 - k2))); y3:= SHORT(ENTIER((k1 * x3) + d1)); ELSIF ~h1 & h2 THEN x3:= x21; y3:= SHORT(ENTIER((k1 * x3) + d1)); ELSIF h1 & ~h2 THEN x3:= x11; y3:= SHORT(ENTIER((k2 * x3) + d2)); ELSE x3:= x11; y3:= y11; RETURN(x11 = x21); END; RETURN(Within(x3,x11,x12) & Within(x3,x21,x22) & Within(y3,y11,y12) & Within(y3,y21,y22)); END Intersect; PROCEDURE Sign(v: REAL): INTEGER; (* get the sign of a real (+1|-1) *) BEGIN IF (v < 0.0) THEN RETURN(-1); ELSE RETURN(1); END; END Sign; PROCEDURE TransX(x,y: INTEGER; p,v: REAL): REAL; (* Transform x-coord - shift and rotate *) BEGIN RETURN((x*Math.cos(p)+y*Math.sin(p))+v); END TransX; PROCEDURE TransY(x,y: INTEGER; p,v: REAL): REAL; (* Transform y-coord - shift and rotate *) BEGIN RETURN((-x*Math.sin(p)+y*Math.cos(p))+v); END TransY; PROCEDURE Model(D: Object): Field; (* return the game's model *) VAR model: Object; BEGIN WITH D: Starfield DO model:= D.obj; END; WITH model: Field DO RETURN(model); END; END Model; PROCEDURE Score(F: Field; score: INTEGER); (* calculate player's current score *) BEGIN F.score:= F.score + score; F.changed:= TRUE; IF (F.score > F.high0) THEN F.high:= F.score; ELSE F.high:= F.high0; END; END Score; PROCEDURE Pair(sh: Shape; n,x,y: INTEGER); (* shape initialization *) BEGIN sh.px[n]:= x; sh.py[n]:= y; END Pair; PROCEDURE Tag(obj: SpaceObj; VAR tag: Objects.Name); (* string tag for loading/storing *) BEGIN WITH obj: Asteroid DO tag := "Asteroid"; | obj: EBullet DO tag := "EBullet"; | obj: SBullet DO tag := "SBullet"; | obj: Enemy DO tag := "Enemy"; | obj: Ship DO tag := "Ship"; | obj: Detonation DO tag := "Detonation"; END; END Tag; PROCEDURE ShowStatus(obj: Field; VAR status: ARRAY OF CHAR); (* create a up-to-date status line *) VAR nr: ARRAY 16 OF CHAR; BEGIN IF obj.started THEN status := "Ships: "; Strings.IntToStr(obj.ships,nr); Strings.Append(status,nr); Strings.Append(status," Warps: "); Strings.IntToStr(obj.ship.warpval,nr); Strings.Append(status,nr); Strings.Append(status," Shield: "); Strings.IntToStr(obj.ship.shieldval,nr); Strings.Append(status,nr); Strings.Append(status," Field: "); Strings.IntToStr(obj.frames,nr); Strings.Append(status,nr); Strings.Append(status," Score: "); Strings.IntToStr(obj.score,nr); Strings.Append(status,nr); Strings.Append(status," High: "); Strings.IntToStr(obj.high,nr); Strings.Append(status,nr); ELSE status := "Asteroids for Oberon "; Strings.Append(status,Version); Strings.Append(status," by W. Ibl, "); Strings.Append(status,Date); END; END ShowStatus; (*** Game object shapes ***) PROCEDURE Asteroid1Shape(VAR sh: Shape); (* Shape of a big asteroid *) BEGIN NEW(sh); sh.n:= 11; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,0,-40); Pair(sh,2,20,-40); Pair(sh,3,40,-20); Pair(sh,4,40,20); Pair(sh,5,20,40); Pair(sh,6,-20,40); Pair(sh,7,-40,20); Pair(sh,8,-40,-20); Pair(sh,9,-20,-40); Pair(sh,10,0,-40); END Asteroid1Shape; PROCEDURE Asteroid2Shape(VAR sh: Shape); (* Shape of a medium asteroid *) BEGIN NEW(sh); sh.n:= 11; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,0,-20); Pair(sh,2,10,-20); Pair(sh,3,20,-10); Pair(sh,4,20,10); Pair(sh,5,10,20); Pair(sh,6,-10,20); Pair(sh,7,-20,10); Pair(sh,8,-20,-10); Pair(sh,9,-10,-20); Pair(sh,10,0,-20); END Asteroid2Shape; PROCEDURE Asteroid3Shape(VAR sh: Shape); (* Shape of a small asteroid *) BEGIN NEW(sh); sh.n:= 11; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,0,-10); Pair(sh,2,5,-10); Pair(sh,3,10,-5); Pair(sh,4,10,5); Pair(sh,5,5,10); Pair(sh,6,-5,10); Pair(sh,7,-10,5); Pair(sh,8,-10,-5); Pair(sh,9,-5,-10); Pair(sh,10,0,-10); END Asteroid3Shape; PROCEDURE EnemyShape(VAR sh: Shape); (* Shape of an ufo *) BEGIN NEW(sh); sh.n:= 5; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,-10,0); Pair(sh,1,0,-15); Pair(sh,2,10,0); Pair(sh,3,0,15); Pair(sh,4,-10,0); END EnemyShape; PROCEDURE EBulletShape(VAR sh: Shape); (* Shape of an ufo's bullet *) BEGIN NEW(sh); sh.n:= 5; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,3,-3); Pair(sh,2,6,0); Pair(sh,3,3,3); Pair(sh,4,0,0); END EBulletShape; PROCEDURE ShipShape(VAR sh: Shape); (* Shape of the player's ship *) BEGIN NEW(sh); sh.n:= 7; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,-20,-20); Pair(sh,2,0,-20); Pair(sh,3,20,0); Pair(sh,4,0,20); Pair(sh,5,-20,20); Pair(sh,6,0,0); END ShipShape; PROCEDURE ThrShipShape(VAR sh: Shape); (* Shape of the player's ship thrusting *) BEGIN NEW(sh); sh.n:= 10; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,-20,-20); Pair(sh,2,0,-20); Pair(sh,3,20,0); Pair(sh,4,0,20); Pair(sh,5,-20,20); Pair(sh,6,0,0); Pair(sh,7,-5,5); Pair(sh,8,-20,0); Pair(sh,9,-7,-5); END ThrShipShape; PROCEDURE SBulletShape(VAR sh: Shape); (* Shape of the player's ship's bullet *) BEGIN NEW(sh); sh.n:= 2; NEW(sh.px,sh.n); NEW(sh.py,sh.n); Pair(sh,0,0,0); Pair(sh,1,10,0); END SBulletShape; (*** Object initialization ***) PROCEDURE InitSpaceObj(obj: SpaceObj); BEGIN obj.x:= 0.0; obj.y:= 0.0; obj.alive:= TRUE; obj.next:= NIL; END InitSpaceObj; PROCEDURE InitMass(obj: Mass; shape: Shape); BEGIN InitSpaceObj(obj); obj.shape:= shape; obj.n0:= shape.n; NEW(obj.px0,obj.n0); NEW(obj.py0,obj.n0); NEW(obj.px1,obj.n0); NEW(obj.py1,obj.n0); obj.rot:= 0.0; obj.xvel:= 0.0; obj.yvel:= 0.0; obj.rotvel:= 0.0; END InitMass; PROCEDURE InitFlyingObj(obj: FlyingObj; shape: Shape); BEGIN InitMass(obj,shape); obj.bullets:= 0; END InitFlyingObj; PROCEDURE InitBullet(obj: Bullet; shape: Shape; ship: FlyingObj; grant: INTEGER); BEGIN InitMass(obj,shape); obj.ship:= ship; obj.time:= grant; obj.rpos:= -1; END InitBullet; PROCEDURE InitShip(obj: Ship; x,y: REAL); BEGIN InitFlyingObj(obj,shThrShip); obj.shape:= shShip; obj.shape0:= shThrShip; IF (obj.px2 = NIL) THEN NEW(obj.px2,shThrShip.n); END; IF (obj.py2 = NIL) THEN NEW(obj.py2,shThrShip.n); END; obj.thrust:= FALSE; obj.thrust0:= FALSE; obj.shield:= 0; obj.shield0:= 0; obj.shieldval:= ShipShield; obj.warpval:= ShipWarp; obj.x:= x; obj.y:= y; END InitShip; PROCEDURE InitSBullet(obj: SBullet; ship: Ship); BEGIN InitBullet(obj,shSBullet,ship,SBulletGrant); obj.x:= ship.px1[3]; obj.y:= ship.py1[3]; obj.rot:= ship.rot; obj.xvel:= SBulletSpd * ((ship.px1[3] - ship.px1[0]) / 20); obj.yvel:= SBulletSpd * ((ship.py1[3] - ship.py1[0]) / 20); obj.rotvel:= 0.0; END InitSBullet; PROCEDURE InitEnemy(obj: Enemy); BEGIN InitFlyingObj(obj,shEnemy); obj.x:= RandomNumbers.Uniform() * Display.Width; obj.y:= RandomNumbers.Uniform() * Display.Height; obj.xvel:= RandomNumbers.Uniform() - 0.5; obj.yvel:= RandomNumbers.Uniform() - 0.5; obj.rotvel:= 0.3; END InitEnemy; PROCEDURE InitEBullet(obj: EBullet; ufo: Enemy; ship: Ship); VAR dw,dx,dy,dz: REAL; BEGIN InitBullet(obj,shEBullet,ufo,EBulletGrant); obj.x:= ufo.px1[0]; obj.y:= ufo.py1[0]; dx:= (ship.px1[0]-ufo.px1[0]); dy:= (ship.py1[0]-ufo.py1[0]); dz:= dy/dx; IF (ABS(dz) > 1.0) THEN dw:= ABS(dz); ELSE dw:= 1.0; END; obj.xvel:= Sign(dx) * (EBulletSpd / dw); obj.yvel:= Sign(dy) * (EBulletSpd / dw) * dz; obj.rotvel:= 0.0; END InitEBullet; PROCEDURE InitAsteroid(obj,father: Asteroid; shape: Shape; hx,hy: INTEGER); BEGIN InitMass(obj,shape); IF (father # NIL) THEN obj.x:= father.px1[0]; obj.y:= father.py1[0]; obj.xvel:= RandomNumbers.Uniform()-(-(0.5)*Sign(father.px1[0]-hx)); obj.yvel:= RandomNumbers.Uniform()-(-(0.5)*Sign(father.py1[0]-hy)); ELSE obj.x:= RandomNumbers.Uniform() * Display.Width; obj.y:= RandomNumbers.Uniform() * Display.Height; obj.xvel:= RandomNumbers.Uniform() - (0.5 * hx); obj.yvel:= RandomNumbers.Uniform() - (0.5 * hy); END; obj.rot:= (RandomNumbers.Uniform() - 0.5) / 10; obj.rotvel:= (RandomNumbers.Uniform() - 0.5) / 10; END InitAsteroid; PROCEDURE InitField(obj: Field); BEGIN obj.ships:= StartShips; obj.ufos:= 0; obj.frames:= 0; obj.score:= 0; obj.high0:= obj.high; obj.objects:= NIL; obj.started:= FALSE; obj.changed:= FALSE; obj.paused:= FALSE; ShowStatus(obj,obj.line); END InitField; PROCEDURE StoreShapeRef(VAR R: Files.Rider; shape: Shape); (* store a given tag string *) BEGIN IF (shape = shAsteroid1) THEN Files.WriteString(R,"shAsteroid1"); ELSIF (shape = shAsteroid2) THEN Files.WriteString(R,"shAsteroid2"); ELSIF (shape = shAsteroid3) THEN Files.WriteString(R,"shAsteroid3"); ELSIF (shape = shEnemy) THEN Files.WriteString(R,"shEnemy"); ELSIF (shape = shEBullet) THEN Files.WriteString(R,"shEBullet"); ELSIF (shape = shShip) THEN Files.WriteString(R,"shShip"); ELSIF (shape = shThrShip) THEN Files.WriteString(R,"shThrShip"); ELSIF (shape = shSBullet) THEN Files.WriteString(R,"shSBullet"); END; END StoreShapeRef; PROCEDURE LoadShapeRef(VAR R: Files.Rider; VAR shape: Shape); (* return shape depending on the tag string *) VAR str: Objects.Name; BEGIN Files.ReadString(R,str); IF (str = "shAsteroid1") THEN shape:= shAsteroid1; ELSIF (str = "shAsteroid2") THEN shape:= shAsteroid2; ELSIF (str = "shAsteroid3") THEN shape:= shAsteroid3; ELSIF (str = "shEnemy") THEN shape:= shEnemy; ELSIF (str = "shEBullet") THEN shape:= shEBullet; ELSIF (str = "shShip") THEN shape:= shShip; ELSIF (str = "shThrShip") THEN shape:= shThrShip; ELSIF (str = "shSBullet") THEN shape:= shSBullet; ELSE shape:= NIL; END; END LoadShapeRef; (*** Game Object loading/storing ***) PROCEDURE FileSpaceObj(VAR R: Files.Rider; id: INTEGER; obj,root: SpaceObj); BEGIN IF (id = Objects.store) THEN Files.WriteReal(R,obj.x); Files.WriteReal(R,obj.y); Files.WriteReal(R,obj.x0); Files.WriteReal(R,obj.y0); Files.WriteBool(R,obj.alive); ELSIF (id = Objects.load) THEN Files.ReadReal(R,obj.x); Files.ReadReal(R,obj.y); Files.ReadReal(R,obj.x0); Files.ReadReal(R,obj.y0); Files.ReadBool(R,obj.alive); END; END FileSpaceObj; PROCEDURE FileDetonation(VAR R: Files.Rider; id: INTEGER; obj: Detonation; root: SpaceObj); BEGIN FileSpaceObj(R,id,obj,root); IF (id = Objects.store) THEN Files.WriteInt(R,obj.r0); Files.WriteInt(R,obj.r); ELSIF (id = Objects.load) THEN Files.ReadInt(R,obj.r0); Files.ReadInt(R,obj.r); END; END FileDetonation; PROCEDURE FileMass(VAR R: Files.Rider; id: INTEGER; obj: Mass; root: SpaceObj); VAR i,j: LONGINT; BEGIN FileSpaceObj(R,id,obj,root); IF (id = Objects.store) THEN Files.WriteLReal(R,obj.mass); Files.WriteReal(R,obj.rot); Files.WriteReal(R,obj.xvel); Files.WriteReal(R,obj.yvel); StoreShapeRef(R,obj.shape); Files.WriteReal(R,obj.rotvel); Files.WriteInt(R,obj.n0); Files.WriteInt(R,obj.u); Files.WriteInt(R,obj.v); Files.WriteInt(R,obj.w); Files.WriteInt(R,obj.h); j:= LEN(obj.px0^); Files.WriteLInt(R,j); FOR i:= 0 TO j-1 DO Files.WriteInt(R,obj.px0[i]); Files.WriteInt(R,obj.py0[i]); Files.WriteInt(R,obj.px1[i]); Files.WriteInt(R,obj.py1[i]); END; ELSIF (id = Objects.load) THEN Files.ReadLReal(R,obj.mass); Files.ReadReal(R,obj.rot); Files.ReadReal(R,obj.xvel); Files.ReadReal(R,obj.yvel); LoadShapeRef(R,obj.shape); Files.ReadReal(R,obj.rotvel); Files.ReadInt(R,obj.n0); Files.ReadInt(R,obj.u); Files.ReadInt(R,obj.v); Files.ReadInt(R,obj.w); Files.ReadInt(R,obj.h); Files.ReadLInt(R,j); NEW(obj.px0,j); NEW(obj.py0,j); NEW(obj.px1,j); NEW(obj.py1,j); FOR i:= 0 TO j-1 DO Files.ReadInt(R,obj.px0[i]); Files.ReadInt(R,obj.py0[i]); Files.ReadInt(R,obj.px1[i]); Files.ReadInt(R,obj.py1[i]); END; END; END FileMass; PROCEDURE FileFlyingObj(VAR R: Files.Rider; id: INTEGER; obj: FlyingObj; root: SpaceObj); BEGIN FileMass(R,id,obj,root); IF (id = Objects.store) THEN Files.WriteInt(R,obj.bullets); ELSIF (id = Objects.load) THEN Files.ReadInt(R,obj.bullets); END; END FileFlyingObj; PROCEDURE FileBullet(VAR R: Files.Rider; id: INTEGER; obj: Bullet; root: SpaceObj); VAR rpos: INTEGER; BEGIN FileMass(R,id,obj,root); IF (id = Objects.store) THEN rpos:= 0; WHILE (root # obj.ship) DO INC(rpos); root:= root.next; END; Files.WriteInt(R,obj.time); Files.WriteInt(R,rpos); ELSIF (id = Objects.load) THEN Files.ReadInt(R,obj.time); Files.ReadInt(R,obj.rpos); END; END FileBullet; PROCEDURE FileShip(VAR R: Files.Rider; id: INTEGER; obj: Ship; root: SpaceObj); VAR i: INTEGER; BEGIN FileFlyingObj(R,id,obj,root); IF (id = Objects.store) THEN Files.WriteBool(R,obj.thrust0); Files.WriteBool(R,obj.thrust); Files.Write(R,obj.shield0); Files.Write(R,obj.shield); Files.WriteInt(R,obj.shieldval); Files.WriteInt(R,obj.warpval); StoreShapeRef(R,obj.shape0); FOR i:= 0 TO obj.shape0.n-1 DO Files.WriteInt(R,obj.px2[i]); Files.WriteInt(R,obj.py2[i]); END; ELSIF (id = Objects.load) THEN Files.ReadBool(R,obj.thrust0); Files.ReadBool(R,obj.thrust); Files.ReadSInt(R,obj.shield0); Files.ReadSInt(R,obj.shield); Files.ReadInt(R,obj.shieldval); Files.ReadInt(R,obj.warpval); LoadShapeRef(R,obj.shape0); NEW(obj.px2,shThrShip.n); NEW(obj.py2,shThrShip.n); FOR i:= 0 TO shThrShip.n-1 DO Files.ReadInt(R,obj.px2[i]); Files.ReadInt(R,obj.py2[i]); END; END; END FileShip; PROCEDURE FileEnemy(VAR R: Files.Rider; id: INTEGER; obj: Enemy; root: SpaceObj); BEGIN FileFlyingObj(R,id,obj,root); END FileEnemy; PROCEDURE FileSBullet(VAR R: Files.Rider; id: INTEGER; obj: SBullet; root: SpaceObj); BEGIN FileBullet(R,id,obj,root); END FileSBullet; PROCEDURE FileEBullet(VAR R: Files.Rider; id: INTEGER; obj: EBullet; root: SpaceObj); BEGIN FileBullet(R,id,obj,root); END FileEBullet; PROCEDURE FileAsteroid(VAR R: Files.Rider; id: INTEGER; obj: Asteroid; root: SpaceObj); BEGIN FileMass(R,id,obj,root); END FileAsteroid; (*** end of loading/storing ***) PROCEDURE ModifyStatus(F: Starfield; obj: Field; mx,my: INTEGER); (* create a new status line and display it *) BEGIN ShowStatus(obj,obj.line); Oberon.RemoveMarks(F.mask.X,F.mask.Y+5,F.mask.W,fh[F.fdx]); Display3.String(F.mask,F.col,mx+F.X+5,my+F.Y+5,fnt[F.fdx],obj.line0,Display3.paint); Display3.String(F.mask,w,mx+F.X+5,my+F.Y+5,fnt[F.fdx],obj.line,Display3.paint); END ModifyStatus; PROCEDURE RestoreStatus(F: Starfield; obj: Field; mx,my: INTEGER); (* display the current status line *) BEGIN Oberon.RemoveMarks(F.mask.X,F.mask.Y+5,F.mask.W,fh[F.fdx]); IF (obj.line0 # obj.line) THEN Display3.String(F.mask,F.col,mx+F.X+5,my+F.Y+5,fnt[F.fdx],obj.line0,Display3.paint); obj.line0 := obj.line; END; Display3.String(F.mask,w,mx+F.X+5,my+F.Y+5,fnt[F.fdx],obj.line,Display3.paint); END RestoreStatus; (* Game Object drawing *) PROCEDURE DrawDetonation(F: Starfield; obj: Detonation; mx,my: INTEGER): INTEGER; VAR sx,sy,sr: INTEGER; BEGIN sx:= SHORT(ENTIER(obj.x*F.scaleX)); sy:= SHORT(ENTIER(obj.y*F.scaleY)); sr:= SHORT(ENTIER(obj.r0*((F.scaleX+F.scaleY)/2))); Oberon.RemoveMarks(F.mask.X+sx-sr,F.mask.Y+sy-sr,sr*2,sr*2); Display3.Circle(F.mask,F.col,Display.solid,mx+F.X+sx,my+F.Y+sy,sr,1,{},Display3.replace); IF obj.alive THEN sr:= SHORT(ENTIER(obj.r*((F.scaleX+F.scaleY)/2))); Oberon.RemoveMarks(F.mask.X+sx-sr,F.mask.Y+sy-sr,sr*2,sr*2); Display3.Circle(F.mask,w,Display.grey2,mx+F.X+sx,my+F.Y+sy,sr,1,{},Display3.replace); END; RETURN(sy-sr); END DrawDetonation; PROCEDURE DrawMass(F: Starfield; obj: Mass; mx,my: INTEGER): INTEGER; VAR su,sv,sw,sh: INTEGER; PROCEDURE Poly(x,y: ARRAY OF INTEGER; n,dx,dy,c: INTEGER); (* add offset to every point in array and draw *) VAR i: INTEGER; BEGIN FOR i:= 0 TO n-1 DO x[i]:= SHORT(ENTIER(x[i]*F.scaleX))+dx; y[i]:= SHORT(ENTIER(y[i]*F.scaleY))+dy; END; Display3.Poly(F.mask,c,Display.solid,x,y,n,1,{},Display3.replace); END Poly; BEGIN su:= SHORT(ENTIER(obj.u*F.scaleX)); sv:= SHORT(ENTIER(obj.v*F.scaleY)); sw:= SHORT(ENTIER(obj.w*F.scaleX)); sh:= SHORT(ENTIER(obj.h*F.scaleY)); Oberon.RemoveMarks(F.mask.X+su,F.mask.Y+sv,sw,sh); Poly(obj.px0^,obj.py0^,obj.n0,mx+F.X,my+F.Y,F.col); IF obj.alive THEN Poly(obj.px1^,obj.py1^,obj.shape.n,mx+F.X,my+F.Y,w); END; RETURN(sv); END DrawMass; PROCEDURE DrawShip(F: Starfield; obj: Ship; mx,my: INTEGER): INTEGER; VAR sx,sy,sr,sv: INTEGER; BEGIN sr:= SHORT(ENTIER(34*((F.scaleX+F.scaleY)/2))); IF (obj.shield0 > 0) THEN sx:= SHORT(ENTIER(obj.x0*F.scaleX)); sy:= SHORT(ENTIER(obj.y0*F.scaleY)); Oberon.RemoveMarks(F.mask.X+sx-sr,F.mask.Y+sy-sr,sr*2,sr*2); Display3.Circle(F.mask,F.col,Display.solid,mx+F.X+sx,my+F.Y+sy,sr,1,{},Display3.replace); END; sv:= DrawMass(F,obj,mx,my); IF obj.alive & (obj.shield > 0) THEN Oberon.RemoveMarks(F.mask.X+sx-sr,F.mask.Y+sy-sr,sr*2,sr*2); sx:= SHORT(ENTIER(obj.x*F.scaleX)); sy:= SHORT(ENTIER(obj.y*F.scaleY)); sv:= sy - sr; Display3.Circle(F.mask,w,Display.solid,mx+F.X+sx,my+F.Y+sy,sr,1,{},Display3.replace); END; RETURN(sv); END DrawShip; PROCEDURE MoveMass(obj: Mass); (* calculate new position of shape vertices using velocities for x, y and rot *) VAR i,w1,h1,w2,h2: INTEGER; shp: Shape; BEGIN w1:= 0; h1:= 0; w2:= 0; h2:= 0; shp:= obj.shape; obj.x0:= obj.x; obj.y0:= obj.y; obj.x:= obj.x + obj.xvel; obj.y:= obj.y + obj.yvel; obj.rot:= obj.rot + obj.rotvel; FOR i:= 0 TO shp.n-1 DO obj.px1[i]:= SHORT(ENTIER(TransX(shp.px[i],shp.py[i],obj.rot,obj.x))); obj.py1[i]:= SHORT(ENTIER(TransY(shp.px[i],shp.py[i],obj.rot,obj.y))); IF (obj.px1[i] > Display.Width) THEN INC(w1); END; IF (obj.px1[i] < 0) THEN INC(w2); END; IF (obj.py1[i] > Display.Height) THEN INC(h1); END; IF (obj.py1[i] < 0) THEN INC(h2); END; END; (* if an object disappeared completly, let it fully appear on the opposite *) IF (w1 = shp.n) THEN obj.x:= obj.x - Display.Width; FOR i:= 0 TO shp.n-1 DO DEC(obj.px1[i],Display.Width); END; ELSIF (w2 = shp.n) THEN obj.x:= obj.x + Display.Width; FOR i:= 0 TO shp.n-1 DO INC(obj.px1[i],Display.Width); END; END; IF (h1 = shp.n) THEN obj.y:= obj.y - Display.Height; FOR i:= 0 TO shp.n-1 DO DEC(obj.py1[i],Display.Height); END; ELSIF (h2 = shp.n) THEN obj.y:= obj.y + Display.Height; FOR i:= 0 TO obj.shape.n-1 DO DEC(obj.py1[i],Display.Height); END; END; (* calculate the objects hull (x,y,u,v) for easier intersection and redraw *) w1:= MAX(INTEGER); h1:= MAX(INTEGER); w2:= MIN(INTEGER); h2:= MIN(INTEGER); FOR i:= 0 TO shp.n-1 DO IF (obj.px1[i] < w1) THEN w1:= obj.px1[i]; END; IF (obj.py1[i] < h1) THEN h1:= obj.py1[i]; END; IF (obj.px1[i] > w2) THEN w2:= obj.px1[i]; END; IF (obj.py1[i] > h2) THEN h2:= obj.py1[i]; END; END; obj.u:= w1; obj.v:= h1; obj.w:= w2 - w1; obj.h:= h2 - h1; END MoveMass; PROCEDURE IntersectMass(obj1,obj2: Mass; VAR x,y: INTEGER): BOOLEAN; (* calculate intersection of two objects *) VAR i,j: INTEGER; PROCEDURE In(v,min,max: INTEGER): BOOLEAN; BEGIN RETURN((v >= min) & (v <= max)); END In; PROCEDURE InBound(i,j: Mass): BOOLEAN; (* intersect the hulls *) BEGIN RETURN((In(i.u,j.u,j.u+j.w) OR In(i.u+i.w,j.u,j.u+j.w)) & (In(i.v,j.v,j.v+j.h) OR In(i.v+i.h,j.v,j.v+j.h))); END InBound; BEGIN (* if hulls don't intersect, skip line checking *) IF InBound(obj1,obj2) OR InBound(obj2,obj1) THEN (* just a speedup for small asteroids *) IF (obj1.shape = shAsteroid3) OR (obj2.shape = shAsteroid3) THEN RETURN(TRUE); END; FOR i:= 0 TO obj1.shape.n-2 DO FOR j:= 0 TO obj2.shape.n-2 DO IF Intersect(obj1.px1[i],obj1.py1[i],obj1.px1[i+1],obj1.py1[i+1], obj2.px1[j],obj2.py1[j],obj2.px1[j+1],obj2.py1[j+1],x,y) THEN RETURN(TRUE); END; END; END; END; RETURN(FALSE); END IntersectMass; PROCEDURE SFire(F: Field; ship: Ship); (* fire a ship's bullet - if possible *) VAR bullet: SBullet; BEGIN IF (ship.bullets < SBulletMax) THEN NEW(bullet); InitSBullet(bullet,ship); INC(ship.bullets); bullet.next:= F.objects; F.objects:= bullet; Score(F,-SBulletCost); END; END SFire; PROCEDURE SShield(F: Field; ship: Ship); (* activate ship's shield - if possible *) BEGIN IF (ship.shieldval > 0) THEN ship.shield:= SShieldGrant; DEC(ship.shieldval); F.changed:= TRUE; END; END SShield; PROCEDURE SWarp(F: Field; ship: Ship); (* warp to another position - if possible *) BEGIN IF (ship.warpval > 0) THEN DEC(ship.warpval); ship.x:= RandomNumbers.Uniform() * Display.Width; ship.y:= RandomNumbers.Uniform() * Display.Height; ship.xvel:= 0.0; ship.yvel:= 0.0; ship.rot:= 0.0; ship.rotvel:= 0.0; F.changed:= TRUE; END; END SWarp; PROCEDURE EFire(F: Field; ufo: Enemy); (* fire an ufo's bullet - if possible *) VAR bullet: EBullet; BEGIN IF (ufo.bullets < EBulletMax) THEN NEW(bullet); InitEBullet(bullet,ufo,F.ship); INC(ufo.bullets); bullet.next:= F.objects; F.objects:= bullet; END; END EFire; PROCEDURE Hit(F: Field; x,y: REAL); (* produce a nice detonation *) VAR det: Detonation; BEGIN NEW(det); InitSpaceObj(det); det.x:= x; det.y:= y; det.r0:= 0; det.r:= 0; det.next:= F.objects; F.objects:= det; END Hit; PROCEDURE HitShip(F: Field; obj: Ship); (* maybe, you're gone. draw detonation and update status *) BEGIN IF (obj.shield = 0) & ~Indestructable THEN Hit(F,obj.px1[0],obj.py1[0]); obj.alive:= FALSE; DEC(F.ships); F.changed:= TRUE; END; END HitShip; PROCEDURE SplitAsteroid(F: Field; obj: Asteroid; x,y: INTEGER): INTEGER; (* split asteroid into pieces (ast1->ast2*SplitAsts->ast3*SplitAsts->none *) VAR ast: Asteroid; shp: Shape; size,i: INTEGER; BEGIN IF (obj.shape = shAsteroid1) THEN (* Big Asteroid *) size:= 1; shp:= shAsteroid2; ELSIF (obj.shape = shAsteroid2) THEN (* Medium Asteroid *) size:= 2; shp:= shAsteroid3; ELSE (* Small Asteroid *) size:= 3; obj.alive:= FALSE; END; IF obj.alive THEN FOR i:= 1 TO SplitAsts DO NEW(ast); InitAsteroid(ast,obj,shp,x,y); ast.next:= F.objects; F.objects:= ast; END; END; RETURN(size); END SplitAsteroid; PROCEDURE NewShip(F: Field; x,y: REAL); (* initialize a new ship and place it somewhere into the field *) BEGIN IF (F.ships > 0) THEN IF (F.ships = StartShips) THEN NEW(F.ship); F.ship.px2:= NIL; F.ship.py2:= NIL; END; InitShip(F.ship,x,y); (* new ships are always static *) F.ship.next:= F.objects; F.objects:= F.ship; F.changed:= TRUE; END; END NewShip; PROCEDURE NewEnemy(F: Field); (* initialize a new ufo and place it somewhere into the field *) VAR obj: Enemy; BEGIN NEW(obj); InitEnemy(obj); INC(F.ufos); (* ufo's are moving *) obj.next:= F.objects; F.objects:= obj; END NewEnemy; PROCEDURE NewRound(F: Field; amt: INTEGER); (* produce new, big asteroids and place them, amount depends on level *) VAR ast: Asteroid; i: INTEGER; BEGIN FOR i:= 1 TO amt DO NEW(ast); InitAsteroid(ast,NIL,shAsteroid1,1,1); ast.next:= F.objects; F.objects:= ast; END; END NewRound; PROCEDURE MoveShip(F: Field; obj: Ship); (* calculate new position of ships' vertices using velocities and thrust *) VAR tgt: SpaceObj; hit: BOOLEAN; x,y: INTEGER; swpV: Vertices; swpS: Shape; BEGIN IF (obj.thrust0 # obj.thrust) THEN (* change shapes if or not thrusting *) swpV:= obj.px1; obj.px1:= obj.px2; obj.px2:= swpV; swpV:= obj.py1; obj.py1:= obj.py2; obj.py2:= swpV; swpS:= obj.shape; obj.shape:= obj.shape0; obj.shape0:= swpS; END; IF obj.thrust THEN obj.xvel:= obj.xvel + ShipThrust * ((obj.px1[3] - obj.px1[0]) / 20); obj.yvel:= obj.yvel + ShipThrust * ((obj.py1[3] - obj.py1[0]) / 20); END; MoveMass(obj); obj.rotvel:= 0.0; tgt:= F.objects; hit:= FALSE; WHILE ~hit & (tgt # NIL) DO (* check, if ship is hitten *) IF (tgt IS Asteroid) OR (tgt IS Enemy) THEN WITH tgt: Mass DO hit:= IntersectMass(obj,tgt,x,y); END; END; IF ~hit THEN tgt:= tgt.next; END; END; IF hit THEN HitShip(F,obj); WITH (* produce a post mortal animation *) tgt: Asteroid DO Hit(F,tgt.px1[0],tgt.py1[0]); x:= SplitAsteroid(F,tgt,x,y); | tgt: Enemy DO Hit(F,tgt.px1[0],tgt.py1[0]); x:= 0; END; Score(F,hitscore[x]); tgt.alive:= FALSE; (* kamikaze salairy *) END; END MoveShip; PROCEDURE MoveEnemy(F: Field; obj: Enemy); (* calculate new position of ships' vertices using velocities *) VAR tgt: SpaceObj; hit: BOOLEAN; x,y: INTEGER; BEGIN MoveMass(obj); tgt:= F.objects; hit:= FALSE; WHILE ~hit & (tgt # NIL) DO (* check, if ufo is hitten *) IF (tgt IS Asteroid) OR (tgt IS Ship) THEN WITH tgt: Mass DO hit:= IntersectMass(obj,tgt,x,y); END; END; IF ~hit THEN tgt:= tgt.next; END; END; IF hit THEN IF (tgt IS Asteroid) THEN WITH tgt: Asteroid DO Hit(F,tgt.px1[0],tgt.py1[0]); x:= SplitAsteroid(F,tgt,x,y); tgt.alive:= FALSE; END; ELSE WITH tgt: Ship DO HitShip(F,tgt); END; END; Hit(F,obj.px1[0],obj.py1[0]); obj.alive:= FALSE; END; END MoveEnemy; PROCEDURE MoveSBullet(F: Field; obj: SBullet); (* calculate new position of ships' bullet using velocities *) VAR tgt: SpaceObj; hit: BOOLEAN; x,y: INTEGER; BEGIN MoveMass(obj); tgt:= F.objects; hit:= FALSE; WHILE ~hit & (tgt # NIL) DO (* check, if shot wasn't in vain *) IF ~(tgt IS SBullet) & (tgt IS Mass) THEN WITH tgt: Mass DO hit:= IntersectMass(obj,tgt,x,y); END; END; IF ~hit THEN tgt:= tgt.next; END; END; IF hit THEN obj.time:= 0; IF (tgt IS Ship) THEN (* self destruction is not fair! *) ELSIF (tgt IS Enemy) THEN Hit(F,x,y); tgt.alive:= FALSE; DEC(F.ufos); Score(F,hitscore[0]); ELSIF (tgt IS Asteroid) THEN WITH tgt: Asteroid DO Hit(F,tgt.px1[0],tgt.py1[0]); x:= SplitAsteroid(F,tgt,x,y); Score(F,hitscore[x]); END; tgt.alive:= FALSE; END; END; DEC(obj.time); IF (obj.time < 0) THEN DEC(obj.ship.bullets); obj.alive:= FALSE; END; END MoveSBullet; PROCEDURE MoveEBullet(F: Field; obj: EBullet); (* calculate new position of ufos' bullet using velocities *) VAR tgt: SpaceObj; hit: BOOLEAN; x,y: INTEGER; BEGIN MoveMass(obj); tgt:= F.objects; hit:= FALSE; WHILE ~hit & (tgt # NIL) DO (* check ufo's shot *) IF ~(tgt IS EBullet) & (tgt IS Mass) THEN WITH tgt: Mass DO hit:= IntersectMass(obj,tgt,x,y); END; END; IF ~hit THEN tgt:= tgt.next; END; END; IF hit & ~(tgt IS Enemy) THEN obj.time:= 0; IF (tgt IS Ship) THEN (* gotcha! *) WITH tgt: Ship DO HitShip(F,tgt); END; ELSIF (tgt IS Asteroid) THEN WITH tgt: Asteroid DO Hit(F,tgt.px1[0],tgt.py1[0]); x:= SplitAsteroid(F,tgt,x,y); END; tgt.alive:= FALSE; END; END; DEC(obj.time); IF (obj.time < 0) THEN DEC(obj.ship.bullets); obj.alive:= FALSE; END; END MoveEBullet; PROCEDURE UpdateShip(obj: Ship); (* update ship values after redraw *) BEGIN obj.shield0:= obj.shield; IF (obj.shield > 0) THEN DEC(obj.shield); END; obj.thrust0:= obj.thrust; obj.thrust:= FALSE; END UpdateShip; PROCEDURE UpdateStatus(obj: Field); (* update score line values after redraw *) BEGIN IF obj.changed THEN obj.line0 := obj.line; END; obj.changed:= FALSE; END UpdateStatus; PROCEDURE Step1(F: Field; obj: SpaceObj); (* first step of animation - keep old vertices and calculate new ones *) VAR swp: Vertices; BEGIN IF (obj IS Detonation) THEN (* special behavior of detonations *) WITH obj: Detonation DO obj.r0:= obj.r; IF obj.alive THEN INC(obj.r,DetonationStep); obj.alive:= (obj.r <= DetonationMax); END; END; ELSIF (obj IS Mass) THEN (* keep old shape for object removal *) WITH obj: Mass DO swp:= obj.px0; obj.px0:= obj.px1; obj.px1:= swp; swp:= obj.py0; obj.py0:= obj.py1; obj.py1:= swp; obj.n0:= obj.shape.n; IF obj.alive THEN WITH (* various move algorithms *) obj: Ship DO MoveShip(F,obj); | obj: SBullet DO MoveSBullet(F,obj); | obj: Enemy DO MoveEnemy(F,obj); | obj: EBullet DO MoveEBullet(F,obj); | obj: Mass DO MoveMass(obj); END; END; END; END; END Step1; PROCEDURE Step2(F: Field; obj: SpaceObj; VAR obj0: SpaceObj): BOOLEAN; (* second step of animation *) VAR b: BOOLEAN; BEGIN b:= FALSE; IF ~obj.alive THEN (* remove "dead" objects *) IF (obj0 = NIL) THEN F.objects:= obj.next; ELSE obj0.next:= obj.next; END; ELSE IF (obj IS Ship) THEN (* update ship's values after draw *) WITH obj: Ship DO UpdateShip(obj); END; ELSE b:= TRUE; END; obj0:= obj; END; RETURN(b); END Step2; PROCEDURE TimerHandler(me: Oberon.Task); (* tick task handler *) VAR time: LONGINT; model: Field; amt: INTEGER; r1: REAL; obj0,obj: SpaceObj; BEGIN WITH me: Timer DO model:= me.model; IF (model # NIL) & ~model.paused THEN time:= Oberon.Time(); (* slow down animation *) IF (me.trigger <= time) THEN obj:= model.objects; WHILE (obj # NIL) DO Step1(model,obj); obj:= obj.next; END; Gadgets.Update(model); obj0:= NIL; obj:= model.objects; WHILE (obj # NIL) DO IF Step2(model,obj,obj0) THEN INC(amt); END; obj:= obj.next; END; IF (amt = 0) THEN INC(model.frames); NewRound(model,model.frames+StartAsts); ELSIF (model.ship # NIL) & model.ship.alive & (model.ufos <= model.frames) THEN r1:= RandomNumbers.Uniform(); (* create a new ufo *) IF (r1 < (model.frames+1)/EAppear) THEN NewEnemy(model); END; END; UpdateStatus(model); amt:= BaseDelay - amt; IF (amt < 0) THEN amt:= 0; END; me.trigger:= Oberon.Time() + amt; END; END; END; END TimerHandler; PROCEDURE StopTimers(); (* remove all tick tasks - a term handler *) BEGIN WHILE (timer # NIL) DO Oberon.Remove(timer); timer:= timer.tnext; END; END StopTimers; (*** Field Handler ***) PROCEDURE FieldAttr(F: Field; VAR M: AttrMsg); BEGIN M.res:= -1; IF (M.id = Objects.get) THEN IF (M.name = "Gen") THEN M.class:= Objects.String; M.res:= 0; M.s:= "Asteroids.NewField"; END; ELSIF (M.id = Objects.enum) THEN END; IF (M.res = -1) THEN Gadgets.objecthandle(F,M); END; END FieldAttr; PROCEDURE FieldFile(F: Field; VAR M: FileMsg); VAR obj0,obj: SpaceObj; rpos: INTEGER; id: Objects.Name; as: Asteroid; eb: EBullet; sb: SBullet; sh: Ship; en: Enemy; de: Detonation; PROCEDURE Connect(VAR root,obj: SpaceObj; new: SpaceObj); (* get the pointer by stepping thru' *) BEGIN IF (obj = NIL) THEN root:= new; ELSE obj.next:= new; END; new.next:= NIL; obj:= new; END Connect; BEGIN IF (M.id = Objects.store) THEN obj:= F.objects; rpos:= 0; WHILE (obj # NIL) & (obj # F.ship) DO INC(rpos); obj:= obj.next; END; Files.WriteInt(M.R,rpos); Files.WriteBool(M.R,F.started); Files.WriteBool(M.R,F.paused); Files.WriteInt(M.R,F.ships); Files.WriteInt(M.R,F.ufos); Files.WriteInt(M.R,F.frames); Files.WriteLInt(M.R,F.score); Files.WriteLInt(M.R,F.high0); Files.WriteLInt(M.R,F.high); Files.WriteString(M.R,F.line0); Files.WriteString(M.R,F.line); obj:= F.objects; WHILE (obj # NIL) DO Tag(obj,id); Files.WriteString(M.R,id); IF (id = "Asteroid") THEN WITH obj: Asteroid DO FileAsteroid(M.R,M.id,obj,F.objects); END; ELSIF (id = "EBullet") THEN WITH obj: EBullet DO FileEBullet(M.R,M.id,obj,F.objects); END; ELSIF (id = "SBullet") THEN WITH obj: SBullet DO FileSBullet(M.R,M.id,obj,F.objects); END; ELSIF (id = "Enemy") THEN WITH obj: Enemy DO FileEnemy(M.R,M.id,obj,F.objects); END; ELSIF (id = "Ship") THEN WITH obj: Ship DO FileShip(M.R,M.id,obj,F.objects); END; ELSIF (id = "Detonation") THEN WITH obj: Detonation DO FileDetonation(M.R,M.id,obj,F.objects); END; END; obj:= obj.next; END; Files.WriteString(M.R,"$"); ELSIF (M.id = Objects.load) THEN Files.ReadInt(M.R,rpos); Files.ReadBool(M.R,F.started); Files.ReadBool(M.R,F.paused); Files.ReadInt(M.R,F.ships); Files.ReadInt(M.R,F.ufos); Files.ReadInt(M.R,F.frames); Files.ReadLInt(M.R,F.score); Files.ReadLInt(M.R,F.high0); Files.ReadLInt(M.R,F.high); Files.ReadString(M.R,F.line0); Files.ReadString(M.R,F.line); F.objects:= NIL; obj:= NIL; REPEAT Files.ReadString(M.R,id); IF (id = "Asteroid") THEN NEW(as); FileAsteroid(M.R,M.id,as,NIL); Connect(F.objects,obj,as); ELSIF (id = "EBullet") THEN NEW(eb); FileEBullet(M.R,M.id,eb,NIL); Connect(F.objects,obj,eb); ELSIF (id = "SBullet") THEN NEW(sb); FileSBullet(M.R,M.id,sb,NIL); Connect(F.objects,obj,sb); ELSIF (id = "Enemy") THEN NEW(en); FileEnemy(M.R,M.id,en,NIL); Connect(F.objects,obj,en); ELSIF (id = "Ship") THEN NEW(sh); FileShip(M.R,M.id,sh,NIL); Connect(F.objects,obj,sh); ELSIF (id = "Detonation") THEN NEW(de); FileDetonation(M.R,M.id,de,NIL); Connect(F.objects,obj,de); END; UNTIL (id = "$"); obj:= F.objects; WHILE (obj # NIL) DO IF (obj IS Bullet) THEN WITH obj: Bullet DO obj0:= F.objects; WHILE (obj.rpos > 0) DO obj0:= obj0.next; DEC(obj.rpos); END; WITH obj0: FlyingObj DO obj.ship:= obj0; END; END; ELSIF (obj IS Ship) & (rpos = 0) THEN WITH obj: Ship DO F.ship:= obj; END; END; obj:= obj.next; DEC(rpos); END; END; Gadgets.objecthandle(F,M); END FieldFile; PROCEDURE FieldHandler*(F: Object; VAR M: Objects.ObjMsg); BEGIN WITH F: Field DO WITH M: AttrMsg DO FieldAttr(F,M); | M: CopyMsg DO M.obj:= F; | M: FileMsg DO FieldFile(F,M); ELSE Gadgets.objecthandle(F,M); END; END; END FieldHandler; (*** Starfield Handler ***) PROCEDURE StarfieldAttr(F: Starfield; VAR M: AttrMsg); BEGIN M.res:= -1; IF (M.id = Objects.get) THEN IF (M.name = "Gen") THEN M.class:= Objects.String; M.res:= 0; M.s:= "Asteroids.NewStarfield"; END; END; IF (M.res = -1) THEN Panels.PanelHandler(F,M); END; END StarfieldAttr; PROCEDURE StarfieldCopy(F: Starfield; VAR M: CopyMsg); VAR obj: Object; BEGIN IF (M.stamp = F.stamp) THEN M.obj:= F.dlink; ELSE obj:= Gadgets.CreateObject("Asteroids.NewStarfield"); F.stamp:= M.stamp; F.dlink:= obj; M.obj:= obj; WITH obj: Starfield DO Panels.CopyPanel(M,F,obj); END; END; END StarfieldCopy; PROCEDURE StarfieldDisplay(F: Starfield; VAR M: DisplayMsg); VAR model: Field; obj: SpaceObj; mx,my,v: INTEGER; mask: Display3.Mask; (* needed for MakeMask *) BEGIN Panels.PanelHandler(F,M); mx:= M.x + F.X; my:= M.y + F.Y; Gadgets.MakeMask(F,mx,my,M.dlink,mask); IF (M.id = Display.area) THEN Display3.AdjustMask(F.mask,mx+M.u,my+F.H-1+M.v,M.w,M.h); END; model:= Model(F); obj:= model.objects; WHILE (obj # NIL) DO IF (obj IS Detonation) THEN WITH obj: Detonation DO v:= DrawDetonation(F,obj,M.x,M.y); END; ELSIF (obj IS Ship) THEN WITH obj: Ship DO v:= DrawShip(F,obj,M.x,M.y); END; ELSIF (obj IS Mass) THEN WITH obj: Mass DO v:= DrawMass(F,obj,M.x,M.y); END; END; obj:= obj.next; END; RestoreStatus(F,model,M.x,M.y); END StarfieldDisplay; PROCEDURE StarfieldFile(F: Starfield; VAR M: FileMsg); BEGIN IF (M.id = Objects.store) THEN Files.WriteReal(M.R,F.scaleX); Files.WriteReal(M.R,F.scaleY); ELSIF (M.id = Objects.load) THEN Files.ReadReal(M.R,F.scaleX); Files.ReadReal(M.R,F.scaleY); END; Panels.PanelHandler(F,M); END StarfieldFile; PROCEDURE StarfieldInput(F: Starfield; VAR M: InputMsg); VAR model: Field; keysum: SET; BEGIN model:= Model(F); M.res:= -1; IF (M.id = Oberon.consume) & (model.ship # NIL) & model.ship.alive THEN CASE M.ch OF | ChTurnLeft: model.ship.rotvel:= -ShipRotvel; M.res:= 0; | ChTurnRight: model.ship.rotvel:= ShipRotvel; M.res:= 0; | ChThrust: model.ship.thrust:= TRUE; M.res:= 0; | ChFire: SFire(model,model.ship); M.res:= 0; | ChShield: SShield(model,model.ship); M.res:= 0; | ChWarp: SWarp(model,model.ship); M.res:= 0; ELSE Panels.PanelHandler(F,M); END; ELSIF ~model.paused & ((model.ship = NIL) OR ~model.ship.alive & (model.ships > 0)) THEN IF (M.id = Oberon.track) & Gadgets.InActiveArea(F,M) & (M.keys = {2}) THEN REPEAT Effects.TrackMouse(M.keys,M.X,M.Y,Oberon.Star); keysum:= keysum + M.keys; UNTIL M.keys = {}; NewShip(model,(M.X-M.x-F.X) / F.scaleX,(M.Y-M.y-F.Y) / F.scaleY); model.started:= TRUE; M.res:= 0; ELSE Oberon.DrawCursor(Oberon.Mouse,Oberon.Star,M.X,M.Y); M.res:= 0; END; ELSE Panels.PanelHandler(F,M); END; END StarfieldInput; PROCEDURE StarfieldModify(F: Starfield; VAR M: ModifyMsg); VAR model: Field; len: LONGINT; BEGIN IF (M.F = F) THEN F.scaleX:= M.W / Display.Width; F.scaleY:= M.H / Display.Height; model:= Model(F); len:= Strings.Length(model.line) + 4; F.fdx:= 6; WHILE (F.fdx > 0) & (M.W < (len * fw[F.fdx])) DO DEC(F.fdx); END; END; Panels.PanelHandler(F,M); END StarfieldModify; PROCEDURE StarfieldUpdate(F: Starfield; VAR M: UpdateMsg); VAR model: Field; obj: SpaceObj; sv: INTEGER; ovlap: BOOLEAN; mask: Display3.Mask; (* needed for MakeMask *) BEGIN Panels.PanelHandler(F,M); IF (F.obj # NIL) & (M.obj = F.obj) THEN Gadgets.MakeMask(F,F.X+M.x,F.Y+M.y,M.dlink,mask); model:= Model(F); ovlap:= FALSE; obj:= model.objects; WHILE (obj # NIL) DO IF (obj IS Detonation) THEN WITH obj: Detonation DO sv:= DrawDetonation(F,obj,M.x,M.y); END; ELSIF (obj IS Ship) THEN WITH obj: Ship DO sv:= DrawShip(F,obj,M.x,M.y); END; ELSIF (obj IS Mass) THEN WITH obj: Mass DO sv:= DrawMass(F,obj,M.x,M.y); END; END; IF obj IS Enemy THEN WITH obj: Enemy DO EFire(model,obj); END; END; ovlap:= ovlap OR (sv <= 5+fh[F.fdx]); obj:= obj.next; END; IF (Gadgets.selected IN F.state) THEN Display3.FillPattern(F.mask,Display3.white,Display3.selectpat,M.x+F.X,M.y+F.Y,M.x+F.X,M.y+F.Y,F.W,F.H,Display3.paint); END; IF model.changed THEN ModifyStatus(F,model,M.x,M.y); ELSIF ovlap THEN RestoreStatus(F,model,M.x,M.y); END; END; END StarfieldUpdate; PROCEDURE StarfieldHandler*(F: Object; VAR M: Objects.ObjMsg); BEGIN WITH F: Starfield DO WITH M: CopyMsg DO StarfieldCopy(F,M); | M: AttrMsg DO StarfieldAttr(F,M); | M: DisplayMsg DO StarfieldDisplay(F,M); | M: FileMsg DO StarfieldFile(F,M); | M: InputMsg DO StarfieldInput(F,M); | M: ModifyMsg DO StarfieldModify(F,M); | M: UpdateMsg DO StarfieldUpdate(F,M); ELSE Panels.PanelHandler(F,M); END; END; END StarfieldHandler; (*** Document Handler ***) PROCEDURE DocAttr(D: Document; VAR M: AttrMsg); BEGIN M.res:= -1; IF (M.id = Objects.get) THEN IF (M.name = "Gen") THEN M.class:= Objects.String; M.res:= 0; M.s:= "Asteroids.NewDoc"; ELSIF (M.name = "Adaptive") THEN M.class:= Objects.Bool; M.res:= 0; M.b:= TRUE; ELSIF (M.name = "Icon") THEN M.class:= Objects.String; M.res:= 0; M.s:= DocIcon; END; END; IF (M.res = -1) THEN Documents.Handler(D,M); END; END DocAttr; PROCEDURE DocLink(D: Document; VAR M: LinkMsg); VAR model: Field; BEGIN IF (M.id = Objects.get) & ((M.name = "DeskMenu") OR (M.name = "SystemMenu") OR (M.name = "UserMenu")) THEN model:= Model(D.dsc); IF ~model.paused THEN M.obj:= Desktops.NewMenu(DocMenu1); ELSE M.obj:= Desktops.NewMenu(DocMenu2); END; M.res:= 0; ELSE Documents.Handler(D,M); END; END DocLink; PROCEDURE DocMenu(D: Document; VAR M: MenuMsg); VAR f,menu: Display.Frame; capt: ARRAY 64 OF CHAR; BEGIN IF (M.frame = D.dsc) THEN menu := Desktops.CurMenu(M.dlink); IF (menu # NIL) THEN f:= menu.dsc; WHILE (f # NIL) DO Attributes.GetString(f,"Caption",capt); IF (capt = "Pause") OR (capt = "Cont") THEN IF M.paused THEN Attributes.SetString(f,"Caption","Cont"); Attributes.SetString(f,"Cmd","Asteroids.ResumeGame"); Gadgets.Update(f); ELSE Attributes.SetString(f,"Caption","Pause"); Attributes.SetString(f,"Cmd","Asteroids.PauseGame"); Gadgets.Update(f); END; END; f:= f.next END; END; END; END DocMenu; PROCEDURE DocHandler*(D: Object; VAR M: Objects.ObjMsg); BEGIN WITH D: Document DO IF M IS AttrMsg THEN WITH M: AttrMsg DO DocAttr(D,M); END; ELSIF M IS LinkMsg THEN WITH M: LinkMsg DO DocLink(D,M); END; ELSIF M IS MenuMsg THEN WITH M: MenuMsg DO DocMenu(D,M); END; ELSE Documents.Handler(D,M); END; END; END DocHandler; (*** Document Creation ***) PROCEDURE OldDocument(F: Files.File; D: Document; VAR f: Gadgets.Frame); (* Restore an old Asteroids document from file *) VAR obj: Objects.Object; tag: INTEGER; len: LONGINT; id: CHAR; str: Objects.Name; lib: Objects.Library; R: Files.Rider; BEGIN Files.Set(R,F,0); Files.ReadInt(R,tag); IF (tag = Documents.Id) THEN Files.ReadString(R,str); (* Skip over Generator *) Files.ReadString(R,str); (* Document Version *) Files.ReadInt(R,D.X); Files.ReadInt(R,D.Y); Files.ReadInt(R,D.W); Files.ReadInt(R,D.H); Files.ReadChar(R,id); IF (str # Version) & (str # CompVers) THEN (* Check Program Version *) Out.String("Unmatching "); Out.String(str); Out.Ln(); ELSIF (id = Objects.LibBlockId) THEN (* Check for correct id *) NEW(lib); Objects.OpenLibrary(lib); Objects.LoadLibrary(lib,F,Files.Pos(R),len); lib.GetObj(lib,0,obj); IF (obj # NIL) THEN IF obj IS Objects.Dummy THEN WITH obj: Objects.Dummy DO Out.String("Discarding "); Out.String(obj.GName); Out.Ln(); END; ELSIF obj IS Panels.Panel THEN WITH obj: Gadgets.Frame DO obj.handle:= StarfieldHandler; f:= obj; END; END; END; END; END; END OldDocument; PROCEDURE NewDocument(D: Document; VAR f: Gadgets.Frame); (* Create a new Asteroids Document *) VAR frame: Display.Frame; BEGIN frame:= Gadgets.CreateViewModel("Asteroids.NewStarfield","Asteroids.NewField"); WITH frame: Gadgets.Frame DO f:= frame; END; END NewDocument; PROCEDURE LoadDocument(D: Document); (* Loading Method for Asteroids Documents *) VAR F: Files.File; T: Timer; frame: Gadgets.Frame; model: Field; BEGIN F:= NIL; frame:= NIL; IF (D.name = "") THEN D.name:= DefName; ELSE F:= Files.Old(D.name); END; IF (F # NIL) THEN OldDocument(F,D,frame); Files.Close(F); ELSE NewDocument(D,frame); model:= Model(frame); Oberon.Defocus(); END; NEW(T); T.model:= Model(frame); T.trigger:= 0; T.tnext:= timer; T.handle:= TimerHandler; timer:= T; Oberon.Install(T); Documents.Init(D,frame); END LoadDocument; PROCEDURE StoreDocument(D: Document); (* Storing Method for Asteroids Documents *) VAR F: Files.File; R: Files.Rider; B: Objects.BindMsg; str: Objects.Name; len: LONGINT; BEGIN IF (D.name # "") & (D.dsc # NIL) THEN Out.String("Store "); NEW(B.lib); Objects.OpenLibrary(B.lib); D.dsc.handle(D.dsc,B); Attributes.GetString(D,"Gen",str); F:= Files.New(D.name); Files.Set(R,F,0); Files.WriteInt(R,Documents.Id); Files.WriteString(R,str); Files.WriteString(R,Version); Files.WriteInt(R,D.X); Files.WriteInt(R,D.Y); Files.WriteInt(R,D.W); Files.WriteInt(R,D.H); Objects.StoreLibrary(B.lib,F,Files.Pos(R),len); Files.Register(F); Files.Close(F); Out.Char(22X); Out.String(D.name); Out.Char(22X); Out.Ln(); END; END StoreDocument; (*** Generators ***) PROCEDURE NewField*; VAR F: Field; BEGIN NEW(F); InitField(F); F.line0 := F.line; F.handle:= FieldHandler; Objects.NewObj:= F; END NewField; PROCEDURE NewStarfield*; VAR F: Starfield; BEGIN NEW(F); Panels.InitPanel(F); F.handle:= StarfieldHandler; F.col:= b; INCL(F.state0,Panels.flatlook); F.fdx:= 0; F.scaleX:= 1.0; F.scaleY:= 1.0; Objects.NewObj:= F; END NewStarfield; PROCEDURE NewDoc*; VAR D: Document; BEGIN NEW(D); D.Load:= LoadDocument; D.Store:= StoreDocument; D.W:= 292; D.H:= 292; D.handle:= DocHandler; Objects.NewObj:= D; END NewDoc; (*** Commands ***) PROCEDURE NewGame*; VAR D: Document; model: Field; obj: SpaceObj; BEGIN D:= Desktops.CurDoc(Gadgets.context); IF (D # NIL) & (D.dsc IS Panels.Panel) THEN model:= Model(D.dsc); IF (model # NIL) THEN obj:= model.objects; WHILE (obj # NIL) DO obj.alive:= FALSE; Step1(model,obj); obj:= obj.next; END; Gadgets.Update(model); InitField(model); INC(model.frames); NewRound(model,StartAsts); Gadgets.Update(model); END; END; END NewGame; PROCEDURE PauseGame*; VAR D: Document; M: MenuMsg; model: Field; i,j: LONGINT; BEGIN D:= Desktops.CurDoc(Gadgets.context); IF (D # NIL) & (D.dsc IS Panels.Panel) THEN model:= Model(D.dsc); IF (model # NIL) THEN i:= Strings.Length(model.line); model.line:= "Game paused . . ."; FOR j:= Strings.Length(model.line) TO i DO model.line[j]:= " "; END; model.line[j]:= 0X; model.paused:= TRUE; Gadgets.Update(model); M.frame:= D.dsc; M.paused:= TRUE; Display.Broadcast(M); END; END; END PauseGame; PROCEDURE ResumeGame*; VAR D: Document; M: MenuMsg; model: Field; BEGIN D:= Desktops.CurDoc(Gadgets.context); IF (D # NIL) & (D.dsc IS Panels.Panel) THEN model:= Model(D.dsc); IF (model # NIL) THEN ShowStatus(model,model.line); model.paused:= FALSE; Gadgets.Update(model); M.frame:= D.dsc; M.paused:= FALSE; Display.Broadcast(M); END; END; END ResumeGame; BEGIN (* What I wanted to say... *) Out.String("Asteroids "); Out.String(Version); Out.String(" by W. Ibl, "); Out.String(Date); Out.Ln(); (* create object shapes *) Asteroid1Shape(shAsteroid1); Asteroid2Shape(shAsteroid2); Asteroid3Shape(shAsteroid3); EnemyShape(shEnemy); EBulletShape(shEBullet); ShipShape(shShip); ThrShipShape(shThrShip); SBulletShape(shSBullet); (* query font information *) FontGeometry("8",0); FontGeometry("10",1); FontGeometry("12",2); FontGeometry("14",3); FontGeometry("16",4); FontGeometry("20",5); FontGeometry("24",6); (* initialize score increments *) hitscore[0]:= HitScoreE1; hitscore[1]:= HitScoreA1; hitscore[2]:= HitScoreA2; hitscore[3]:= HitScoreA3; b:= Display3.black; w:= Display3.white; timer:= NIL; Modules.InstallTermHandler(StopTimers); END Asteroids. Desktops.OpenDoc Asteroids.Doc (Asteroids.NewDoc)~ System.Free Asteroids~ System.DeleteFiles Asteroids.Doc~ Compiler.Compile *\2s
0
0.657132
1
0.657132
game-dev
MEDIA
0.892802
game-dev
0.860294
1
0.860294
pWn3d1337/Techguns2
2,623
src/main/java/techguns/world/structures/NetherAltarMedium.java
package techguns.world.structures; import java.util.ArrayList; import java.util.Random; import net.minecraft.init.Blocks; import net.minecraft.world.World; import techguns.TGBlocks; import techguns.blocks.EnumMonsterSpawnerType; import techguns.entities.npcs.CyberDemon; import techguns.util.BlockUtils; import techguns.util.MBlock; import techguns.world.dungeon.presets.specialblocks.MBlockTGSpawner; import techguns.world.structures.WorldgenStructure.BiomeColorType; public class NetherAltarMedium extends WorldgenStructure { static ArrayList<MBlock> blockList = new ArrayList<MBlock>(); static short[][] blocks; static { blockList.add(new MBlock(TGBlocks.NETHER_METAL, 0)); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 6)); blockList.add(new MBlock(Blocks.NETHER_BRICK_FENCE, 0)); blockList.add(MBlockRegister.AIR); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 2)); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 8)); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 1)); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 7)); blockList.add(new MBlock(TGBlocks.NETHER_METAL, 9)); blockList.add(new MBlock(Blocks.NETHER_BRICK_STAIRS, 0)); blockList.add(new MBlockTGSpawner(EnumMonsterSpawnerType.HOLE,3,1,200,1).addMobType(CyberDemon.class, 1)); blockList.add(new MBlock(Blocks.NETHER_BRICK_STAIRS, 2)); blockList.add(new MBlock(Blocks.NETHER_BRICK_STAIRS, 3)); blockList.add(new MBlock(Blocks.NETHER_BRICK, 0)); blockList.add(new MBlock(Blocks.NETHER_BRICK_STAIRS, 1)); blocks = BlockUtils.loadStructureFromFile("nether_altar_medium"); } public NetherAltarMedium() { super(16,9,16, 16,9,16); } @Override public void setBlocks(World world, int posX, int posY, int posZ, int sizeX, int sizeY, int sizeZ, int direction, BiomeColorType colorType, Random rnd) { int centerX, centerZ; int hoffset = -1; if (((sizeX < this.minX) && (sizeZ > this.minX) && (sizeX >= this.minZ)) ||((sizeZ < this.minZ) && (sizeX > this.minZ) && (sizeZ >= this.minX))) { direction = (direction+1) % 4; centerZ = (int) (sizeX/2.0f); centerX = (int) (sizeZ/2.0f); }else { centerX = (int) (sizeX/2.0f); centerZ = (int) (sizeZ/2.0f); } BlockUtils.placeFoundationNether(world, blocks, blockList, posX, posY+hoffset, posZ, centerX, centerZ, direction, 0,16); BlockUtils.placeScannedStructure(world, blocks, blockList, posX, posY+hoffset, posZ, centerX, centerZ, direction, 0,this.lootTier,colorType); BlockUtils.placeScannedStructure(world, blocks, blockList, posX, posY+hoffset, posZ, centerX, centerZ, direction, 1,this.lootTier,colorType); } }
0
0.834225
1
0.834225
game-dev
MEDIA
0.982662
game-dev
0.877636
1
0.877636
rfresh2/XaeroPlus
2,752
forge/src/main/java/xaeroplus/forge/XaeroPlusForgeClient.java
package xaeroplus.forge; import com.github.benmanes.caffeine.cache.RemovalCause; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.client.Minecraft; import net.minecraftforge.client.ConfigScreenHandler; import net.minecraftforge.client.event.RegisterClientCommandsEvent; import net.minecraftforge.client.event.RegisterClientReloadListenersEvent; import net.minecraftforge.client.event.RegisterKeyMappingsEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.loading.FMLLoader; import xaero.map.gui.GuiWorldMapSettings; import xaeroplus.XaeroPlus; import xaeroplus.commands.XPClientCommandSource; import xaeroplus.feature.extensions.GuiXaeroPlusWorldMapSettings; import xaeroplus.settings.Settings; import xaeroplus.util.XaeroPlusGameTest; public class XaeroPlusForgeClient { public void init(final IEventBus modEventBus, final IEventBus forgeEventBus) { modEventBus.addListener(this::onRegisterKeyMappingsEvent); modEventBus.addListener(this::onRegisterClientResourceReloadListeners); forgeEventBus.addListener(this::onRegisterClientCommandsEvent); forgeEventBus.register(modEventBus); if (EmbeddiumHelper.isEmbeddiumPresent()) forgeEventBus.addListener(XaeroPlusEmbeddiumOptionsInit::onEmbeddiumOptionGUIConstructionEvent); RemovalCause explicit = RemovalCause.EXPLICIT; // force class load to stop forge shitting itself at runtime?? ModLoadingContext.get().registerExtensionPoint( ConfigScreenHandler.ConfigScreenFactory.class, () -> new ConfigScreenHandler.ConfigScreenFactory((mc, screen) -> new GuiXaeroPlusWorldMapSettings(new GuiWorldMapSettings(screen), screen)) ); } public void onRegisterKeyMappingsEvent(final RegisterKeyMappingsEvent event) { if (XaeroPlus.initialized.compareAndSet(false, true)) { XaeroPlus.XP_VERSION = FMLLoader.getLoadingModList().getModFileById("xaeroplus").versionString(); XaeroPlus.initializeSettings(); Settings.REGISTRY.getKeybindings().forEach(event::register); if (System.getenv("XP_CI_TEST") != null) Minecraft.getInstance().execute(XaeroPlusGameTest::applyMixinsTest); } } public void onRegisterClientCommandsEvent(final RegisterClientCommandsEvent event) { XaeroPlus.registerCommands((CommandDispatcher<XPClientCommandSource>) (CommandDispatcher<?>) event.getDispatcher(), event.getBuildContext()); } public void onRegisterClientResourceReloadListeners(RegisterClientReloadListenersEvent event) { event.registerReloadListener(new XaeroPlusForgeResourceReloadListener()); } }
0
0.9098
1
0.9098
game-dev
MEDIA
0.81584
game-dev
0.894195
1
0.894195
Gibberlings3/Tweaks-Anthology
1,574
cdtweaks/lib/comp_1180.tpa
/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ ///// \\\\\ ///// Edwina \\\\\ ///// \\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ ACTION_IF enhanced_edition THEN BEGIN COPY ~cdtweaks/bmp/royo4_330.bmp~ ~override/royo4l.bmp~ ~cdtweaks/bmp/royo4_266.bmp~ ~override/royo4m.bmp~ END ELSE BEGIN COPY ~cdtweaks/bmp/royo4_170.bmp~ ~override/royo4l.bmp~ ~cdtweaks/bmp/royo4_60.bmp~ ~override/royo4m.bmp~ END // add portrait change opcodes to edwin transform spells COPY_EXISTING ~spin662.spl~ ~override~ // return to edwin LPF DELETE_EFFECT INT_VAR match_opcode = 107 END LPF ADD_SPELL_EFFECT INT_VAR opcode = 107 target = 2 parameter2 = 1 timing = 1 STR_VAR resource = nedwinm END // large portrait LPF ADD_SPELL_EFFECT INT_VAR opcode = 107 target = 2 parameter2 = 0 timing = 1 STR_VAR resource = nedwins END // small portrait // add portrait change opcodes to edwin transform spells COPY_EXISTING ~spin916.spl~ ~override~ // change to edwina LPF DELETE_EFFECT INT_VAR match_opcode = 107 END LPF ADD_SPELL_EFFECT INT_VAR opcode = 107 target = 2 parameter2 = 1 timing = 1 STR_VAR resource = royo4l END // large portrait LPF ADD_SPELL_EFFECT INT_VAR opcode = 107 target = 2 parameter2 = 0 timing = 1 STR_VAR resource = royo4m END // small portrait
0
0.777158
1
0.777158
game-dev
MEDIA
0.465868
game-dev
0.653866
1
0.653866
Kaedrin/nwn2cc
1,314
NWN2 WIP/Override/override_latest/Scripts/cmi_s2_brkconca.NSS
//:://///////////////////////////////////////////// //:: Dissonant Chord - Break Concentration //:: cmi_s2_brkconca //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: October 18, 2009 //::////////////////////////////////////////////// #include "x0_i0_spells" #include "x2_inc_spellhook" #include "cmi_ginc_spells" void main() { //SpeakString("nw_s2_auradespairA.nss: On Enter: function entry"); object oTarget = GetEnteringObject(); object oCaster = GetAreaOfEffectCreator(); //SendMessageToPC(oCaster,GetName(oTarget)); int nPenalty = GetLevelByClass(CLASS_DISSONANT_CHORD, oCaster); nPenalty += GetAbilityModifier(ABILITY_CHARISMA, oCaster); effect eConcPenalty = EffectSkillDecrease(SKILL_CONCENTRATION, nPenalty); eConcPenalty = SupernaturalEffect(eConcPenalty); // Doesn't work on self if (oTarget != oCaster) { //SpeakString("nw_s2_auradespairA.nss: On Enter: target is not the same as the creator"); SignalEvent (oTarget, EventSpellCastAt(oCaster, SPELLABILITY_DISCHORD_BREAK_CONC, FALSE)); //Faction Check if (spellsIsTarget(oTarget, SPELL_TARGET_SELECTIVEHOSTILE, oCaster)) { //SpeakString("nw_s2_auradespairA.ns: On Enter: target is enemy"); ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eConcPenalty, oTarget, HoursToSeconds(24)); } } }
0
0.561076
1
0.561076
game-dev
MEDIA
0.960868
game-dev
0.846908
1
0.846908
NetCodersX/Unity-Script
2,907
斗地主/Assets/Scripts/UI/02.Game/ButtomPanel.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtomPanel : UIBase { //豆子 private Text txtBeen; //当前倍数 private Text txtMutiple; private Button butChat; private Button[] btns; private Image chooseListPanel; SocketMsg socketMsg; void Start() { Bind(UIEvent.Change_Mutiple, UIEvent.Change_Been); socketMsg = new SocketMsg(); btns = new Button[7]; txtBeen = transform.Find("txt_Been").GetComponent<Text>(); txtMutiple = transform.Find("txt_Mutiple").GetComponent<Text>(); butChat = transform.Find("but_Chat").GetComponent<Button>(); chooseListPanel = transform.Find("ChooseListPanel").GetComponent<Image>(); //btns = transform.Find("ChooseListPanel").GetComponentsInChildren<Button>(); for (int i = 0; i < chooseListPanel.transform.GetChild(0).transform.childCount; i++) { int index = i + 1; btns[i] = chooseListPanel.transform.GetChild(0).transform.GetChild(i).GetComponent<Button>(); btns[i].onClick.AddListener(() => { OnCharClick(index); }); } var userInfo = Data.GameData.UserCharacterDto; if (userInfo != null) { RefreshView(userInfo.Been); } //添加监听 butChat.onClick.AddListener(SetChooseListPanel); //默认设置 chooseListPanel.gameObject.SetActive(false); } public override void Execute(int eventCode, object message) { switch (eventCode) { case UIEvent.Change_Mutiple: ChangeMutiple((int)message); break; case UIEvent.Change_Been: RefreshView((int)message); break; } } public override void OnDestroy() { base.OnDestroy(); butChat.onClick.RemoveListener(SetChooseListPanel); } void Update() { } /// <summary> /// 刷新豆子 /// </summary> /// <param name="beenCount"></param> private void RefreshView(int beenCount) { txtBeen.text = "x " + beenCount; } /// <summary> /// 更改当前局倍数 /// </summary> /// <param name="beenCount"></param> private void ChangeMutiple(int mutiple) { txtMutiple.text = "倍数 x " + mutiple; } /// <summary> /// 设置快捷喊话面板 /// </summary> private void SetChooseListPanel() { chooseListPanel.gameObject.SetActive(!chooseListPanel.gameObject.activeInHierarchy); } /// <summary> /// 发送消息 /// </summary> /// <param name="index"></param> private void OnCharClick(int index) { socketMsg.OpCode = MsgType.Chat; socketMsg.SubCode = ChatCode.Default; socketMsg.value = index; Dispatch(AreaCode.NET, 0, socketMsg); } }
0
0.904892
1
0.904892
game-dev
MEDIA
0.609283
game-dev
0.967992
1
0.967992
geotools/geotools
8,500
modules/library/main/src/main/java/org/geotools/temporal/object/DefaultTemporalPrimitive.java
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.temporal.object; import java.util.Date; import org.geotools.api.temporal.Instant; import org.geotools.api.temporal.Period; import org.geotools.api.temporal.RelativePosition; import org.geotools.api.temporal.TemporalOrder; import org.geotools.api.temporal.TemporalPrimitive; /** * An abstract class that represents a non-decomposed element of geometry or topology of time. * * @author Mehdi Sidhoum (Geomatys) * @author Simone Giannecchini, GeoSolutions SAS */ @SuppressWarnings("ComparableType") public abstract class DefaultTemporalPrimitive extends DefaultTemporalObject implements TemporalPrimitive, TemporalOrder, Comparable<TemporalPrimitive> { @Override public int compareTo(TemporalPrimitive that) { if (that == null) throw new IllegalArgumentException("Provided temporal object is null"); final RelativePosition pos = this.relativePosition(that); if (pos == null) throw new ClassCastException("The provided object cannot be compared to this one"); if (pos == RelativePosition.BEFORE) return -1; if (pos == RelativePosition.AFTER) return +1; if (pos == RelativePosition.EQUALS) return 0; // TODO rethink this since it looks like it is a pretty dirty hack if (this instanceof Period && that instanceof Instant || this instanceof Instant && that instanceof Period) { if (pos == RelativePosition.ENDED_BY || pos == RelativePosition.BEGUN_BY || pos == RelativePosition.CONTAINS) return 0; } // TODO rethink this since it looks like it is a pretty dirty hack if (this instanceof Period && that instanceof Period) { if (pos == RelativePosition.MEETS) return -1; if (pos == RelativePosition.BEGINS) return -1; if (pos == RelativePosition.BEGUN_BY) return +1; if (pos == RelativePosition.ENDS) return +1; if (pos == RelativePosition.ENDED_BY) return -1; if (pos == RelativePosition.OVERLAPS) return -1; if (pos == RelativePosition.OVERLAPPED_BY) return +1; if (pos == RelativePosition.DURING || pos == RelativePosition.CONTAINS || pos == RelativePosition.EQUALS) return 0; } throw new IllegalStateException("Unable to compare the provided object with this one"); } /** * Returns a value for relative position which are provided by the enumerated data type TM_RelativePosition and are * based on the 13 temporal relationships identified by Allen (1983). * * @param other TemporalPrimitive */ @Override public RelativePosition relativePosition(TemporalPrimitive other) { if (this instanceof Instant thisInstant && other instanceof Instant otherIstant) { return relativePosition(thisInstant, otherIstant); } else { if (this instanceof Period thisPeriod && other instanceof Instant otherInstant) { return relativePosition(thisPeriod, otherInstant); } else { if (this instanceof Instant thisIstant && other instanceof Period otherPeriod) { return relativePosition(thisIstant, otherPeriod); } else { if (this instanceof Period thisPeriod && other instanceof Period otherPeriod) { return relativePosition(thisPeriod, otherPeriod); } else { return null; } } } } } private RelativePosition relativePosition(Period thisPeriod, Period otherPeriod) { Date thisBeginning = thisPeriod.getBeginning().getPosition().getDate(); Date thisEnding = thisPeriod.getEnding().getPosition().getDate(); Date otherBeginning = otherPeriod.getBeginning().getPosition().getDate(); Date otherEnding = otherPeriod.getEnding().getPosition().getDate(); if (thisEnding.before(otherBeginning)) { return RelativePosition.BEFORE; } else if (thisEnding.compareTo(otherBeginning) == 0) { return RelativePosition.MEETS; } else if (thisBeginning.before(otherBeginning) && thisEnding.after(otherBeginning) && thisEnding.before(otherEnding)) { return RelativePosition.OVERLAPS; } else if (thisBeginning.compareTo(otherBeginning) == 0 && thisEnding.before(otherEnding)) { return RelativePosition.BEGINS; } else if (thisBeginning.compareTo(otherBeginning) == 0 && thisEnding.after(otherEnding)) { return RelativePosition.BEGUN_BY; } else if (thisBeginning.after(otherBeginning) && thisEnding.before(otherEnding)) { return RelativePosition.DURING; } else if (thisBeginning.before(otherBeginning) && thisEnding.after(otherEnding)) { return RelativePosition.CONTAINS; } else if (thisBeginning.compareTo(otherBeginning) == 0 && thisEnding.compareTo(otherEnding) == 0) { return RelativePosition.EQUALS; } else if (thisBeginning.after(otherBeginning) && thisBeginning.before(otherEnding) && thisEnding.after(otherEnding)) { return RelativePosition.OVERLAPPED_BY; } else if (thisBeginning.after(otherBeginning) && thisEnding.compareTo(otherEnding) == 0) { return RelativePosition.ENDS; } else if (thisBeginning.before(otherBeginning) && thisEnding.compareTo(otherEnding) == 0) { return RelativePosition.ENDED_BY; } else { return thisBeginning.compareTo(otherEnding) == 0 ? RelativePosition.MET_BY : RelativePosition.AFTER; } } private RelativePosition relativePosition(Instant thisInstant, Period otherPeriod) { Date otherEnd = otherPeriod.getEnding().getPosition().getDate(); Date thisDate = thisInstant.getPosition().getDate(); if (otherEnd.before(thisDate)) { return RelativePosition.AFTER; } else { if (otherEnd.compareTo(thisDate) == 0) { return RelativePosition.ENDS; } else { Date otherBeginning = otherPeriod.getBeginning().getPosition().getDate(); if (otherBeginning.before(thisDate) && otherEnd.after(thisDate)) { return RelativePosition.DURING; } else { return otherBeginning.compareTo(thisDate) == 0 ? RelativePosition.BEGINS : RelativePosition.BEFORE; } } } } private RelativePosition relativePosition(Period thisPeriod, Instant otherInstant) { Date thisEnd = thisPeriod.getEnding().getPosition().getDate(); Date otherDate = otherInstant.getPosition().getDate(); if (thisEnd.before(otherDate)) { return RelativePosition.BEFORE; } else if (thisEnd.compareTo(otherDate) == 0) { return RelativePosition.ENDED_BY; } else { Date thisStart = thisPeriod.getBeginning().getPosition().getDate(); if (thisStart.before(otherDate) && thisEnd.after(otherDate)) { return RelativePosition.CONTAINS; } else { return thisStart.compareTo(otherDate) == 0 ? RelativePosition.BEGUN_BY : RelativePosition.AFTER; } } } private RelativePosition relativePosition(Instant thisInstant, Instant otherIstant) { Date thisDate = thisInstant.getPosition().getDate(); Date otherDate = otherIstant.getPosition().getDate(); if (thisDate.before(otherDate)) { return RelativePosition.BEFORE; } else { return thisDate.compareTo(otherDate) == 0 ? RelativePosition.EQUALS : RelativePosition.AFTER; } } }
0
0.818212
1
0.818212
game-dev
MEDIA
0.224774
game-dev
0.85685
1
0.85685
ferrumc-rs/ferrumc
8,938
src/lib/net/src/packets/outgoing/entity_metadata.rs
// https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Entity_metadata#Entity_Metadata_Format use crate::packets::outgoing::entity_metadata::entity_state::{EntityState, EntityStateMask}; use crate::packets::outgoing::entity_metadata::index_type::EntityMetadataIndexType; use crate::packets::outgoing::entity_metadata::value::EntityMetadataValue; use ferrumc_macros::{packet, NetEncode}; use ferrumc_net_codec::encode::{NetEncode, NetEncodeOpts}; use ferrumc_net_codec::net_types::var_int::VarInt; use std::io::Write; /// Packet for sending entity metadata updates to clients #[derive(NetEncode, Clone)] #[packet(packet_id = "set_entity_data", state = "play")] pub struct EntityMetadataPacket { entity_id: VarInt, metadata: Vec<EntityMetadata>, terminator: u8, // Always 0xFF to indicate end of metadata (Simple is Best) } impl EntityMetadataPacket { /// Creates a new metadata packet for the specified entity /// /// # Arguments /// * `entity_id` - The entity ID to update metadata for /// * `metadata` - Iterator of metadata entries to send /// /// # Example /// ```ignored /// let entity_id = ...; /// let metadata = vec![ /// EntityMetadata::entity_sneaking_pressed(), /// EntityMetadata::entity_sneaking_visual(), /// EntityMetadata::entity_standing() /// ]; /// let packet = EntityMetadataPacket::new(entity_id, metadata); /// ``` pub fn new<T>(entity_id: VarInt, metadata: T) -> Self where T: IntoIterator<Item = EntityMetadata>, { Self { entity_id, metadata: metadata.into_iter().collect(), terminator: 0xFF, } } } /// Single metadata entry containing an index, type and value #[derive(NetEncode, Clone)] pub struct EntityMetadata { index: u8, index_type: EntityMetadataIndexType, value: EntityMetadataValue, } pub mod constructors { use super::*; use crate::packets::outgoing::entity_metadata::extra_data_types::EntityPose; impl EntityMetadata { fn new(index_type: EntityMetadataIndexType, value: EntityMetadataValue) -> Self { EntityMetadata { index: value.index(), index_type, value, } } /// To hide the name tag and stuff pub fn entity_sneaking_pressed() -> Self { Self::new( EntityMetadataIndexType::Byte, EntityMetadataValue::Entity0(EntityStateMask::from_state( EntityState::SneakingVisual, )), ) } /// Actual sneaking visual, so you can see the player sneaking pub fn entity_sneaking_visual() -> Self { Self::new( EntityMetadataIndexType::Pose, EntityMetadataValue::Entity6(EntityPose::Sneaking), ) } /// Entity in standing pose pub fn entity_standing() -> Self { Self::new( EntityMetadataIndexType::Pose, EntityMetadataValue::Entity6(EntityPose::Standing), ) } } } mod index_type { use super::*; use ferrumc_net_codec::encode::errors::NetEncodeError; /// Available metadata field types /// See: https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Entity_metadata#Entity_Metadata_Format #[derive(Debug, Clone, Copy)] pub enum EntityMetadataIndexType { Byte, // (0) Used for bit masks and small numbers Pose, // (21) Used for entity pose } impl EntityMetadataIndexType { pub fn index(&self) -> VarInt { use EntityMetadataIndexType::*; let val = match self { Byte => 0, Pose => 21, }; VarInt::new(val) } } impl NetEncode for EntityMetadataIndexType { fn encode<W: Write>( &self, writer: &mut W, opts: &NetEncodeOpts, ) -> Result<(), NetEncodeError> { self.index().encode(writer, opts) } async fn encode_async<W: tokio::io::AsyncWrite + Unpin>( &self, writer: &mut W, opts: &NetEncodeOpts, ) -> Result<(), NetEncodeError> { self.index().encode_async(writer, opts).await } } } mod value { use super::*; use crate::packets::outgoing::entity_metadata::extra_data_types::EntityPose; /// Possible metadata values that can be sent /// /// Couldn't be arsed coming up with the names. /// Read here: /// https://minecraft.wiki/w/Minecraft_Wiki:Projects/wiki.vg_merge/Entity_metadata#Entity /// /// Formatted like: /// {Class Name}{Index} #[derive(NetEncode, Clone)] pub enum EntityMetadataValue { Entity0(EntityStateMask), Entity6(EntityPose), } impl EntityMetadataValue { pub fn index(&self) -> u8 { use EntityMetadataValue::*; match self { Entity0(_) => 0, Entity6(_) => 6, } } } } mod entity_state { use ferrumc_macros::NetEncode; /// Bit mask for various entity states #[derive(Debug, NetEncode, Clone)] pub struct EntityStateMask { mask: u8, } impl Default for EntityStateMask { fn default() -> Self { Self::new() } } impl EntityStateMask { pub fn new() -> Self { Self { mask: 0 } } pub fn from_state(state: EntityState) -> Self { let mut mask = Self::new(); mask.set(state); mask } pub fn set(&mut self, state: EntityState) { self.mask |= state.mask(); } } /// Individual states that can be applied to an entity /// Multiple states can be combined using a bit mask #[expect(dead_code)] pub enum EntityState { OnFire, // 0x01 SneakingVisual, // 0x02 Sprinting, // 0x08 Swimming, // 0x10 Invisible, // 0x20 Glowing, // 0x40 FlyingWithElytra, // 0x80 } impl EntityState { pub fn mask(&self) -> u8 { use EntityState::*; match self { OnFire => 0x01, SneakingVisual => 0x02, Sprinting => 0x08, Swimming => 0x10, Invisible => 0x20, Glowing => 0x40, FlyingWithElytra => 0x80, } } } } mod extra_data_types { use ferrumc_net_codec::encode::errors::NetEncodeError; use ferrumc_net_codec::encode::{NetEncode, NetEncodeOpts}; use ferrumc_net_codec::net_types::var_int::VarInt; use std::io::Write; // STANDING = 0, FALL_FLYING = 1, SLEEPING = 2, SWIMMING = 3, SPIN_ATTACK = 4, SNEAKING = 5, LONG_JUMPING = 6, DYING = 7, CROAKING = 8, // USING_TONGUE = 9, SITTING = 10, ROARING = 11, SNIFFING = 12, EMERGING = 13, DIGGING = 14, (1.21.3: SLIDING = 15, SHOOTING = 16, // INHALING = 17 /// Possible poses/animations an entity can have #[derive(Debug, Clone)] #[expect(dead_code)] pub enum EntityPose { Standing, FallFlying, Sleeping, Swimming, SpinAttack, Sneaking, LongJumping, Dying, Croaking, UsingTongue, Sitting, Roaring, Sniffing, Emerging, Digging, Sliding, Shooting, Inhaling, } impl EntityPose { pub fn index(&self) -> VarInt { use EntityPose::*; let val = match self { Standing => 0, FallFlying => 1, Sleeping => 2, Swimming => 3, SpinAttack => 4, Sneaking => 5, LongJumping => 6, Dying => 7, Croaking => 8, UsingTongue => 9, Sitting => 10, Roaring => 11, Sniffing => 12, Emerging => 13, Digging => 14, Sliding => 15, Shooting => 16, Inhaling => 17, }; VarInt::new(val) } } impl NetEncode for EntityPose { fn encode<W: Write>( &self, writer: &mut W, opts: &NetEncodeOpts, ) -> Result<(), NetEncodeError> { self.index().encode(writer, opts) } async fn encode_async<W: tokio::io::AsyncWrite + Unpin>( &self, writer: &mut W, opts: &NetEncodeOpts, ) -> Result<(), NetEncodeError> { self.index().encode_async(writer, opts).await } } }
0
0.641621
1
0.641621
game-dev
MEDIA
0.867154
game-dev
0.760763
1
0.760763
johnttaylor/pim
2,848
src/Cpl/Text/btoa.cpp
/*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2022 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- * FULL DISCLOSURE: This code is based the LTOSTR.C implementation by Jerry * Coffin which is in the public domain. The original code snippet can be * found at: * * https://github.com/vonj/snippets/blob/master/ltostr.c * *----------------------------------------------------------------------------*/ #include "btoa.h" #include <string.h> #include "Cpl/System/Trace.h" #define SECT_ "_0test" //////////////////////////////////////////// static const char* convert_( size_t num, char* dstString, size_t maxChars, unsigned base, char padChar, bool isNegative ) { // Error check the base argument if ( base < 2 || base > 36 ) { return 0; } // When convert a negative value, I need to leave room for the minus sign size_t sign = isNegative ? 1 : 0; // Null terminate the string dstString[--maxChars] = '\0'; // Handle special case: original number is zero if ( num == 0 ) { dstString[--maxChars] = '0'; } // Convert the number else { // Conversion is done LSB first while ( num != 0 && maxChars > sign ) { char remainder = (char) ( num % base ); if ( remainder <= 9 ) { dstString[--maxChars] = remainder + '0'; } else { dstString[--maxChars] = remainder - 10 + 'A'; } num /= base; } } // Add the minus when needed if ( isNegative ) { dstString[--maxChars] = '-'; } // Add pad character(s) if ( maxChars > 0 ) { memset( dstString, padChar, maxChars ); } // Return the 'left justified' string return dstString + maxChars; } ////////////////////////////////////////////////// const char* Cpl::Text::longToStr( long num, char* dstString, size_t maxChars, unsigned base, char padChar ) { bool negFlag = false; if ( num < 0 ) { negFlag = true; num = -num; } return convert_( num, dstString, maxChars, base, padChar, negFlag ); } const char* Cpl::Text::ulongToStr( unsigned long num, char* dstString, size_t maxChars, unsigned base, char padChar ) { return convert_( num, dstString, maxChars, base, padChar, false ); } const char* Cpl::Text::sizetToStr( size_t num, char* dstString, size_t maxChars, unsigned base, char padChar ) { return convert_( num, dstString, maxChars, base, padChar, false ); }
0
0.924535
1
0.924535
game-dev
MEDIA
0.320277
game-dev
0.963314
1
0.963314
HarommelRabbid/LifeLua
1,265
docs/ImGui.lua
imgui.init() imgui.darktheme() theme = 1 -- for checking only --imgui.cursor(false) imgui.touch(true) imgui.gamepad(true) while true do imgui.renderinit() --imgui.setcursor(ImGuiMouseCursor_None) if imgui.menubarbegin() then if imgui.menubegin("test") then if imgui.menubegin("Theme") then if imgui.menuitem("Dark theme", theme == 1) then imgui.darktheme() theme = 1 end if imgui.menuitem("Light theme", theme == 2) then imgui.lighttheme() theme = 2 end if imgui.menuitem("Classic theme", theme == 3) then imgui.classictheme() theme = 3 end imgui.menuend() end if imgui.menuitem("Error") then imgui.shutdown() error() end if imgui.menuitem("Exit") then imgui.shutdown() os.exit() end imgui.menuend() end imgui.menubarend() end draw.text(10, 30, "This is an ImGui test in LifeLua", color.new(255, 255, 255)) -- you can draw anything non-ImGui related imgui.text("Test") imgui.button("Button", 100) imgui.smallbutton("Small button") if imgui.menubegin("test1") then imgui.menuitem("test") imgui.menuend() end imgui.renderterm() draw.swapbuffers() end
0
0.525092
1
0.525092
game-dev
MEDIA
0.691484
game-dev
0.694607
1
0.694607
smefpw/Indigo
24,130
INDIGO/steam_sdk/isteamuserstats.h
//====== Copyright � 1996-2009, Valve Corporation, All rights reserved. ======= // // Purpose: interface to stats, achievements, and leaderboards // //============================================================================= #ifndef ISTEAMUSERSTATS_H #define ISTEAMUSERSTATS_H #ifdef _WIN32 #pragma once #endif #include "isteamclient.h" #include "isteamremotestorage.h" // size limit on stat or achievement name (UTF-8 encoded) enum { k_cchStatNameMax = 128 }; // maximum number of bytes for a leaderboard name (UTF-8 encoded) enum { k_cchLeaderboardNameMax = 128 }; // maximum number of details int32's storable for a single leaderboard entry enum { k_cLeaderboardDetailsMax = 64 }; // handle to a single leaderboard typedef uint64 SteamLeaderboard_t; // handle to a set of downloaded entries in a leaderboard typedef uint64 SteamLeaderboardEntries_t; // type of data request, when downloading leaderboard entries enum ELeaderboardDataRequest { k_ELeaderboardDataRequestGlobal = 0, k_ELeaderboardDataRequestGlobalAroundUser = 1, k_ELeaderboardDataRequestFriends = 2, k_ELeaderboardDataRequestUsers = 3 }; // the sort order of a leaderboard enum ELeaderboardSortMethod { k_ELeaderboardSortMethodNone = 0, k_ELeaderboardSortMethodAscending = 1, // top-score is lowest number k_ELeaderboardSortMethodDescending = 2, // top-score is highest number }; // the display type (used by the Steam Community web site) for a leaderboard enum ELeaderboardDisplayType { k_ELeaderboardDisplayTypeNone = 0, k_ELeaderboardDisplayTypeNumeric = 1, // simple numerical score k_ELeaderboardDisplayTypeTimeSeconds = 2, // the score represents a time, in seconds k_ELeaderboardDisplayTypeTimeMilliSeconds = 3, // the score represents a time, in milliseconds }; enum ELeaderboardUploadScoreMethod { k_ELeaderboardUploadScoreMethodNone = 0, k_ELeaderboardUploadScoreMethodKeepBest = 1, // Leaderboard will keep user's best score k_ELeaderboardUploadScoreMethodForceUpdate = 2, // Leaderboard will always replace score with specified }; // a single entry in a leaderboard, as returned by GetDownloadedLeaderboardEntry() #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error isteamclient.h must be included #endif struct LeaderboardEntry_t { CSteamID m_steamIDUser; // user with the entry - use SteamFriends()->GetFriendPersonaName() & SteamFriends()->GetFriendAvatar() to get more info int32 m_nGlobalRank; // [1..N], where N is the number of users with an entry in the leaderboard int32 m_nScore; // score as set in the leaderboard int32 m_cDetails; // number of int32 details available for this entry UGCHandle_t m_hUGC; // handle for UGC attached to the entry }; #pragma pack( pop ) //----------------------------------------------------------------------------- // Purpose: Functions for accessing stats, achievements, and leaderboard information //----------------------------------------------------------------------------- class ISteamUserStats { public: // Ask the server to send down this user's data and achievements for this game CALL_BACK( UserStatsReceived_t ) virtual bool RequestCurrentStats() = 0; // Data accessors virtual bool GetStat( const char *pchName, int32 *pData ) = 0; virtual bool GetStat( const char *pchName, float *pData ) = 0; // Set / update data virtual bool SetStat( const char *pchName, int32 nData ) = 0; virtual bool SetStat( const char *pchName, float fData ) = 0; virtual bool UpdateAvgRateStat( const char *pchName, float flCountThisSession, double dSessionLength ) = 0; // Achievement flag accessors virtual bool GetAchievement( const char *pchName, bool *pbAchieved ) = 0; virtual bool SetAchievement( const char *pchName ) = 0; virtual bool ClearAchievement( const char *pchName ) = 0; // Get the achievement status, and the time it was unlocked if unlocked. // If the return value is true, but the unlock time is zero, that means it was unlocked before Steam // began tracking achievement unlock times (December 2009). Time is seconds since January 1, 1970. virtual bool GetAchievementAndUnlockTime( const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; // Store the current data on the server, will get a callback when set // And one callback for every new achievement // // If the callback has a result of k_EResultInvalidParam, one or more stats // uploaded has been rejected, either because they broke constraints // or were out of date. In this case the server sends back updated values. // The stats should be re-iterated to keep in sync. virtual bool StoreStats() = 0; // Achievement / GroupAchievement metadata // Gets the icon of the achievement, which is a handle to be used in ISteamUtils::GetImageRGBA(), or 0 if none set. // A return value of 0 may indicate we are still fetching data, and you can wait for the UserAchievementIconFetched_t callback // which will notify you when the bits are ready. If the callback still returns zero, then there is no image set for the // specified achievement. virtual int GetAchievementIcon( const char *pchName ) = 0; // Get general attributes for an achievement. Accepts the following keys: // - "name" and "desc" for retrieving the localized achievement name and description (returned in UTF8) // - "hidden" for retrieving if an achievement is hidden (returns "0" when not hidden, "1" when hidden) virtual const char *GetAchievementDisplayAttribute( const char *pchName, const char *pchKey ) = 0; // Achievement progress - triggers an AchievementProgress callback, that is all. // Calling this w/ N out of N progress will NOT set the achievement, the game must still do that. virtual bool IndicateAchievementProgress( const char *pchName, uint32 nCurProgress, uint32 nMaxProgress ) = 0; // Used for iterating achievements. In general games should not need these functions because they should have a // list of existing achievements compiled into them virtual uint32 GetNumAchievements() = 0; // Get achievement name iAchievement in [0,GetNumAchievements) virtual const char *GetAchievementName( uint32 iAchievement ) = 0; // Friends stats & achievements // downloads stats for the user // returns a UserStatsReceived_t received when completed // if the other user has no stats, UserStatsReceived_t.m_eResult will be set to k_EResultFail // these stats won't be auto-updated; you'll need to call RequestUserStats() again to refresh any data CALL_RESULT( UserStatsReceived_t ) virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; // requests stat information for a user, usable after a successful call to RequestUserStats() virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; // See notes for GetAchievementAndUnlockTime above virtual bool GetUserAchievementAndUnlockTime( CSteamID steamIDUser, const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; // Reset stats virtual bool ResetAllStats( bool bAchievementsToo ) = 0; // Leaderboard functions // asks the Steam back-end for a leaderboard by name, and will create it if it's not yet // This call is asynchronous, with the result returned in LeaderboardFindResult_t CALL_RESULT(LeaderboardFindResult_t) virtual SteamAPICall_t FindOrCreateLeaderboard( const char *pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType ) = 0; // as above, but won't create the leaderboard if it's not found // This call is asynchronous, with the result returned in LeaderboardFindResult_t CALL_RESULT( LeaderboardFindResult_t ) virtual SteamAPICall_t FindLeaderboard( const char *pchLeaderboardName ) = 0; // returns the name of a leaderboard virtual const char *GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the total number of entries in a leaderboard, as of the last request virtual int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the sort method of the leaderboard virtual ELeaderboardSortMethod GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) = 0; // returns the display type of the leaderboard virtual ELeaderboardDisplayType GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) = 0; // Asks the Steam back-end for a set of rows in the leaderboard. // This call is asynchronous, with the result returned in LeaderboardScoresDownloaded_t // LeaderboardScoresDownloaded_t will contain a handle to pull the results from GetDownloadedLeaderboardEntries() (below) // You can ask for more entries than exist, and it will return as many as do exist. // k_ELeaderboardDataRequestGlobal requests rows in the leaderboard from the full table, with nRangeStart & nRangeEnd in the range [1, TotalEntries] // k_ELeaderboardDataRequestGlobalAroundUser requests rows around the current user, nRangeStart being negate // e.g. DownloadLeaderboardEntries( hLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -3, 3 ) will return 7 rows, 3 before the user, 3 after // k_ELeaderboardDataRequestFriends requests all the rows for friends of the current user CALL_RESULT( LeaderboardScoresDownloaded_t ) virtual SteamAPICall_t DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) = 0; // as above, but downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers // if a user doesn't have a leaderboard entry, they won't be included in the result // a max of 100 users can be downloaded at a time, with only one outstanding call at a time METHOD_DESC(Downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers) CALL_RESULT( LeaderboardScoresDownloaded_t ) virtual SteamAPICall_t DownloadLeaderboardEntriesForUsers( SteamLeaderboard_t hSteamLeaderboard, ARRAY_COUNT_D(cUsers, Array of users to retrieve) CSteamID *prgUsers, int cUsers ) = 0; // Returns data about a single leaderboard entry // use a for loop from 0 to LeaderboardScoresDownloaded_t::m_cEntryCount to get all the downloaded entries // e.g. // void OnLeaderboardScoresDownloaded( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded ) // { // for ( int index = 0; index < pLeaderboardScoresDownloaded->m_cEntryCount; index++ ) // { // LeaderboardEntry_t leaderboardEntry; // int32 details[3]; // we know this is how many we've stored previously // GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries, index, &leaderboardEntry, details, 3 ); // assert( leaderboardEntry.m_cDetails == 3 ); // ... // } // once you've accessed all the entries, the data will be free'd, and the SteamLeaderboardEntries_t handle will become invalid virtual bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry_t *pLeaderboardEntry, int32 *pDetails, int cDetailsMax ) = 0; // Uploads a user score to the Steam back-end. // This call is asynchronous, with the result returned in LeaderboardScoreUploaded_t // Details are extra game-defined information regarding how the user got that score // pScoreDetails points to an array of int32's, cScoreDetailsCount is the number of int32's in the list CALL_RESULT( LeaderboardScoreUploaded_t ) virtual SteamAPICall_t UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int32 nScore, const int32 *pScoreDetails, int cScoreDetailsCount ) = 0; // Attaches a piece of user generated content the user's entry on a leaderboard. // hContent is a handle to a piece of user generated content that was shared using ISteamUserRemoteStorage::FileShare(). // This call is asynchronous, with the result returned in LeaderboardUGCSet_t. CALL_RESULT( LeaderboardUGCSet_t ) virtual SteamAPICall_t AttachLeaderboardUGC( SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ) = 0; // Retrieves the number of players currently playing your game (online + offline) // This call is asynchronous, with the result returned in NumberOfCurrentPlayers_t CALL_RESULT( NumberOfCurrentPlayers_t ) virtual SteamAPICall_t GetNumberOfCurrentPlayers() = 0; // Requests that Steam fetch data on the percentage of players who have received each achievement // for the game globally. // This call is asynchronous, with the result returned in GlobalAchievementPercentagesReady_t. CALL_RESULT( GlobalAchievementPercentagesReady_t ) virtual SteamAPICall_t RequestGlobalAchievementPercentages() = 0; // Get the info on the most achieved achievement for the game, returns an iterator index you can use to fetch // the next most achieved afterwards. Will return -1 if there is no data on achievement // percentages (ie, you haven't called RequestGlobalAchievementPercentages and waited on the callback). virtual int GetMostAchievedAchievementInfo( char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; // Get the info on the next most achieved achievement for the game. Call this after GetMostAchievedAchievementInfo or another // GetNextMostAchievedAchievementInfo call passing the iterator from the previous call. Returns -1 after the last // achievement has been iterated. virtual int GetNextMostAchievedAchievementInfo( int iIteratorPrevious, char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; // Returns the percentage of users who have achieved the specified achievement. virtual bool GetAchievementAchievedPercent( const char *pchName, float *pflPercent ) = 0; // Requests global stats data, which is available for stats marked as "aggregated". // This call is asynchronous, with the results returned in GlobalStatsReceived_t. // nHistoryDays specifies how many days of day-by-day history to retrieve in addition // to the overall totals. The limit is 60. CALL_RESULT( GlobalStatsReceived_t ) virtual SteamAPICall_t RequestGlobalStats( int nHistoryDays ) = 0; // Gets the lifetime totals for an aggregated stat virtual bool GetGlobalStat( const char *pchStatName, int64 *pData ) = 0; virtual bool GetGlobalStat( const char *pchStatName, double *pData ) = 0; // Gets history for an aggregated stat. pData will be filled with daily values, starting with today. // So when called, pData[0] will be today, pData[1] will be yesterday, and pData[2] will be two days ago, // etc. cubData is the size in bytes of the pubData buffer. Returns the number of // elements actually set. virtual int32 GetGlobalStatHistory( const char *pchStatName, ARRAY_COUNT(cubData) int64 *pData, uint32 cubData ) = 0; virtual int32 GetGlobalStatHistory( const char *pchStatName, ARRAY_COUNT(cubData) double *pData, uint32 cubData ) = 0; #ifdef _PS3 // Call to kick off installation of the PS3 trophies. This call is asynchronous, and the results will be returned in a PS3TrophiesInstalled_t // callback. virtual bool InstallPS3Trophies() = 0; // Returns the amount of space required at boot to install trophies. This value can be used when comparing the amount of space needed // by the game to the available space value passed to the game at boot. The value is set during InstallPS3Trophies(). virtual uint64 GetTrophySpaceRequiredBeforeInstall() = 0; // On PS3, user stats & achievement progress through Steam must be stored with the user's saved game data. // At startup, before calling RequestCurrentStats(), you must pass the user's stats data to Steam via this method. // If you do not have any user data, call this function with pvData = NULL and cubData = 0 virtual bool SetUserStatsData( const void *pvData, uint32 cubData ) = 0; // Call to get the user's current stats data. You should retrieve this data after receiving successful UserStatsReceived_t & UserStatsStored_t // callbacks, and store the data with the user's save game data. You can call this method with pvData = NULL and cubData = 0 to get the required // buffer size. virtual bool GetUserStatsData( void *pvData, uint32 cubData, uint32 *pcubWritten ) = 0; #endif }; #define STEAMUSERSTATS_INTERFACE_VERSION "STEAMUSERSTATS_INTERFACE_VERSION011" // callbacks #if defined( VALVE_CALLBACK_PACK_SMALL ) #pragma pack( push, 4 ) #elif defined( VALVE_CALLBACK_PACK_LARGE ) #pragma pack( push, 8 ) #else #error isteamclient.h must be included #endif //----------------------------------------------------------------------------- // Purpose: called when the latests stats and achievements have been received // from the server //----------------------------------------------------------------------------- struct UserStatsReceived_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 1 }; uint64 m_nGameID; // Game these stats are for EResult m_eResult; // Success / error fetching the stats CSteamID m_steamIDUser; // The user for whom the stats are retrieved for }; //----------------------------------------------------------------------------- // Purpose: result of a request to store the user stats for a game //----------------------------------------------------------------------------- struct UserStatsStored_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 2 }; uint64 m_nGameID; // Game these stats are for EResult m_eResult; // success / error }; //----------------------------------------------------------------------------- // Purpose: result of a request to store the achievements for a game, or an // "indicate progress" call. If both m_nCurProgress and m_nMaxProgress // are zero, that means the achievement has been fully unlocked. //----------------------------------------------------------------------------- struct UserAchievementStored_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 3 }; uint64 m_nGameID; // Game this is for bool m_bGroupAchievement; // if this is a "group" achievement char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement uint32 m_nCurProgress; // current progress towards the achievement uint32 m_nMaxProgress; // "out of" this many }; //----------------------------------------------------------------------------- // Purpose: call result for finding a leaderboard, returned as a result of FindOrCreateLeaderboard() or FindLeaderboard() // use CCallResult<> to map this async result to a member function //----------------------------------------------------------------------------- struct LeaderboardFindResult_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 4 }; SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard serarched for, 0 if no leaderboard found uint8 m_bLeaderboardFound; // 0 if no leaderboard found }; //----------------------------------------------------------------------------- // Purpose: call result indicating scores for a leaderboard have been downloaded and are ready to be retrieved, returned as a result of DownloadLeaderboardEntries() // use CCallResult<> to map this async result to a member function //----------------------------------------------------------------------------- struct LeaderboardScoresDownloaded_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 5 }; SteamLeaderboard_t m_hSteamLeaderboard; SteamLeaderboardEntries_t m_hSteamLeaderboardEntries; // the handle to pass into GetDownloadedLeaderboardEntries() int m_cEntryCount; // the number of entries downloaded }; //----------------------------------------------------------------------------- // Purpose: call result indicating scores has been uploaded, returned as a result of UploadLeaderboardScore() // use CCallResult<> to map this async result to a member function //----------------------------------------------------------------------------- struct LeaderboardScoreUploaded_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 6 }; uint8 m_bSuccess; // 1 if the call was successful SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was int32 m_nScore; // the score that was attempted to set uint8 m_bScoreChanged; // true if the score in the leaderboard change, false if the existing score was better int m_nGlobalRankNew; // the new global rank of the user in this leaderboard int m_nGlobalRankPrevious; // the previous global rank of the user in this leaderboard; 0 if the user had no existing entry in the leaderboard }; struct NumberOfCurrentPlayers_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 7 }; uint8 m_bSuccess; // 1 if the call was successful int32 m_cPlayers; // Number of players currently playing }; //----------------------------------------------------------------------------- // Purpose: Callback indicating that a user's stats have been unloaded. // Call RequestUserStats again to access stats for this user //----------------------------------------------------------------------------- struct UserStatsUnloaded_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 }; CSteamID m_steamIDUser; // User whose stats have been unloaded }; //----------------------------------------------------------------------------- // Purpose: Callback indicating that an achievement icon has been fetched //----------------------------------------------------------------------------- struct UserAchievementIconFetched_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 9 }; CGameID m_nGameID; // Game this is for char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement bool m_bAchieved; // Is the icon for the achieved or not achieved version? int m_nIconHandle; // Handle to the image, which can be used in SteamUtils()->GetImageRGBA(), 0 means no image is set for the achievement }; //----------------------------------------------------------------------------- // Purpose: Callback indicating that global achievement percentages are fetched //----------------------------------------------------------------------------- struct GlobalAchievementPercentagesReady_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 10 }; uint64 m_nGameID; // Game this is for EResult m_eResult; // Result of the operation }; //----------------------------------------------------------------------------- // Purpose: call result indicating UGC has been uploaded, returned as a result of SetLeaderboardUGC() //----------------------------------------------------------------------------- struct LeaderboardUGCSet_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 11 }; EResult m_eResult; // The result of the operation SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was }; //----------------------------------------------------------------------------- // Purpose: callback indicating that PS3 trophies have been installed //----------------------------------------------------------------------------- struct PS3TrophiesInstalled_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; uint64 m_nGameID; // Game these stats are for EResult m_eResult; // The result of the operation uint64 m_ulRequiredDiskSpace; // If m_eResult is k_EResultDiskFull, will contain the amount of space needed to install trophies }; //----------------------------------------------------------------------------- // Purpose: callback indicating global stats have been received. // Returned as a result of RequestGlobalStats() //----------------------------------------------------------------------------- struct GlobalStatsReceived_t { enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; uint64 m_nGameID; // Game global stats were requested for EResult m_eResult; // The result of the request }; #pragma pack( pop ) #endif // ISTEAMUSER_H
0
0.882487
1
0.882487
game-dev
MEDIA
0.316954
game-dev
0.840024
1
0.840024
awgil/ffxiv_bossmod
3,635
BossMod/Modules/Endwalker/Savage/P3SPhoinix/TrailOfCondemnation.cs
namespace BossMod.Endwalker.Savage.P3SPhoinix; // state related to trail of condemnation mechanic class TrailOfCondemnation(BossModule module) : BossComponent(module) { public bool Done { get; private set; } private readonly bool _isCenter = module.PrimaryActor.CastInfo?.IsSpell(AID.TrailOfCondemnationCenter) ?? false; private const float _halfWidth = 7.5f; private const float _sidesOffset = 12.5f; private const float _aoeRadius = 6; public override void AddHints(int slot, Actor actor, TextHints hints) { if (Module.PrimaryActor.Position == Module.Center) return; var dir = (Module.Center - Module.PrimaryActor.Position).Normalized(); if (_isCenter) { if (actor.Position.InRect(Module.PrimaryActor.Position, dir, 2 * Module.Bounds.Radius, 0, _halfWidth)) { hints.Add("GTFO from aoe!"); } if (Raid.WithoutSlot().InRadiusExcluding(actor, _aoeRadius).Any()) { hints.Add("Spread!"); } } else { var offset = _sidesOffset * dir.OrthoR(); if (actor.Position.InRect(Module.PrimaryActor.Position + offset, dir, 2 * Module.Bounds.Radius, 0, _halfWidth) || actor.Position.InRect(Module.PrimaryActor.Position - offset, dir, 2 * Module.Bounds.Radius, 0, _halfWidth)) { hints.Add("GTFO from aoe!"); } // note: sparks either target all tanks & healers or all dds - so correct pairings are always dd+tank/healer int numStacked = 0; bool goodPair = false; foreach (var pair in Raid.WithoutSlot().InRadiusExcluding(actor, _aoeRadius)) { ++numStacked; goodPair = (actor.Role == Role.Tank || actor.Role == Role.Healer) != (pair.Role == Role.Tank || pair.Role == Role.Healer); } if (numStacked != 1) { hints.Add("Stack in pairs!"); } else if (!goodPair) { hints.Add("Incorrect pairing!"); } } } public override void DrawArenaBackground(int pcSlot, Actor pc) { if (Module.PrimaryActor.Position == Module.Center) return; var dir = (Module.Center - Module.PrimaryActor.Position).Normalized(); if (_isCenter) { Arena.ZoneRect(Module.PrimaryActor.Position, dir, 2 * Module.Bounds.Radius, 0, _halfWidth, ArenaColor.AOE); } else { var offset = _sidesOffset * dir.OrthoR(); Arena.ZoneRect(Module.PrimaryActor.Position + offset, dir, 2 * Module.Bounds.Radius, 0, _halfWidth, ArenaColor.AOE); Arena.ZoneRect(Module.PrimaryActor.Position - offset, dir, 2 * Module.Bounds.Radius, 0, _halfWidth, ArenaColor.AOE); } } public override void DrawArenaForeground(int pcSlot, Actor pc) { // draw all raid members, to simplify positioning foreach (var player in Raid.WithoutSlot().Exclude(pc)) { bool inRange = player.Position.InCircle(pc.Position, _aoeRadius); Arena.Actor(player, inRange ? ArenaColor.PlayerInteresting : ArenaColor.PlayerGeneric); } // draw circle around pc Arena.AddCircle(pc.Position, _aoeRadius, ArenaColor.Danger); } public override void OnEventCast(Actor caster, ActorCastEvent spell) { if ((AID)spell.Action.ID is AID.FlareOfCondemnation or AID.SparksOfCondemnation) Done = true; } }
0
0.938022
1
0.938022
game-dev
MEDIA
0.956812
game-dev
0.936002
1
0.936002
mosra/magnum-examples
7,997
doc/fluidsimulation2d.dox
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025 Vladimír Vondruš <mosra@centrum.cz> Copyright © 2018 Michal Mikula <miso.mikula@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Magnum { /** @page examples-fluidsimulation2d 2D Fluid Simulation @brief 2D fluid simulation using the APIC method. @m_since_{examples,2020,06} @m_footernavigation @image html fluidsimulation2d.png width=400px A 2D fluid simulation using the APIC ([Affine Particle-in-Cell](https://dl.acm.org/citation.cfm?id=2766996)) method. Compared to @ref examples-fluidsimulation3d, the simulation is running in a single thread. @m_div{m-button m-primary} <a href="https://magnum.graphics/showcase/fluidsimulation2d/">@m_div{m-big} Live web demo @m_enddiv @m_div{m-small} uses WebAssembly & WebGL 2 @m_enddiv </a> @m_enddiv @section examples-fluidsimulation2d-controls Controls - @m_class{m-label m-default} **mouse drag** interacts with the simulation - @m_class{m-label m-default} **E** emits more particles - @m_class{m-label m-default} **H** shows / hides the overlay - @m_class{m-label m-default} **R** resets the simulation - @m_class{m-label m-default} **Space** pauses the simulation @section examples-fluidsimulation2d-credits Credits This example was originally contributed by [Nghia Truong](https://github.com/ttnghia). @m_class{m-block m-success} @thirdparty This example makes use of the [Adobe Source Sans Pro](https://github.com/adobe-fonts/source-sans-pro) font, licensed under @m_class{m-label m-success} **OFL 1.1** ([license text](https://github.com/adobe-fonts/source-sans-pro/blob/release/LICENSE.md), [choosealicense.com](https://choosealicense.com/licenses/ofl-1.1/)). Attribution is required for public use. @section examples-fluidsimulation2d-source Source Full source code is linked below and also available in the [magnum-examples GitHub repository](https://github.com/mosra/magnum-examples/tree/master/src/fluidsimulation2d). This example depends on the @ref ImGuiIntegration library which is not a part of the core Magnum repository, see its documentation for usage instructions. - @ref fluidsimulation2d/CMakeLists.txt "CMakeLists.txt" - @ref fluidsimulation2d/DataStructures/Array2X.h "DataStructures/Array2X.h" - @ref fluidsimulation2d/DataStructures/MathHelpers.h "DataStructures/MathHelpers.h" - @ref fluidsimulation2d/DataStructures/PCGSolver.h "DataStructures/PCGSolver.h" - @ref fluidsimulation2d/DataStructures/SDFObject.h "DataStructures/SDFObject.h" - @ref fluidsimulation2d/DataStructures/SparseMatrix.h "DataStructures/SparseMatrix.h" - @ref fluidsimulation2d/DrawableObjects/FlatShadeObject2D.h "DrawableObjects/FlatShadeObject2D.h" - @ref fluidsimulation2d/DrawableObjects/ParticleGroup2D.cpp "DrawableObjects/ParticleGroup2D.cpp" - @ref fluidsimulation2d/DrawableObjects/ParticleGroup2D.h "DrawableObjects/ParticleGroup2D.h" - @ref fluidsimulation2d/DrawableObjects/WireframeObject2D.h "DrawableObjects/WireframeObject2D.h" - @ref fluidsimulation2d/FluidSimulation2DExample.cpp "FluidSimulation2DExample.cpp" - @ref fluidsimulation2d/FluidSolver/ApicSolver2D.cpp "FluidSolver/ApicSolver2D.cpp" - @ref fluidsimulation2d/FluidSolver/ApicSolver2D.h "FluidSolver/ApicSolver2D.h" - @ref fluidsimulation2d/FluidSolver/SolverData.h "FluidSolver/SolverData.h" - @ref fluidsimulation2d/resources.conf "resources.conf" - @ref fluidsimulation2d/Shaders/ParticleSphereShader2D.cpp "Shaders/ParticleSphereShader2D.cpp" - @ref fluidsimulation2d/Shaders/ParticleSphereShader2D.frag "Shaders/ParticleSphereShader2D.frag" - @ref fluidsimulation2d/Shaders/ParticleSphereShader2D.h "Shaders/ParticleSphereShader.h" - @ref fluidsimulation2d/Shaders/ParticleSphereShader2D.vert "Shaders/ParticleSphereShader2D.vert" The [ports branch](https://github.com/mosra/magnum-examples/tree/ports/src/fluidsimulation2d) contains additional patches for @ref CORRADE_TARGET_EMSCRIPTEN "Emscripten" support that aren't present in `master` in order to keep the example code as simple as possible. @example fluidsimulation2d/CMakeLists.txt @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DataStructures/Array2X.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DataStructures/MathHelpers.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DataStructures/PCGSolver.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DataStructures/SDFObject.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DataStructures/SparseMatrix.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DrawableObjects/FlatShadeObject2D.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DrawableObjects/ParticleGroup2D.cpp @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DrawableObjects/ParticleGroup2D.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/DrawableObjects/WireframeObject2D.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/FluidSolver/ApicSolver2D.cpp @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/FluidSolver/ApicSolver2D.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/FluidSolver/SolverData.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/FluidSimulation2DExample.cpp @m_examplenavigation{examples-fluidsimulation3d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/resources.conf @m_examplenavigation{examples-fluidsimulation3d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/Shaders/ParticleSphereShader2D.cpp @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/Shaders/ParticleSphereShader2D.h @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/Shaders/ParticleSphereShader2D.frag @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation @example fluidsimulation2d/Shaders/ParticleSphereShader2D.vert @m_examplenavigation{examples-fluidsimulation2d,fluidsimulation2d/} @m_footernavigation */ }
0
0.675393
1
0.675393
game-dev
MEDIA
0.501136
game-dev
0.598666
1
0.598666
Farama-Foundation/stable-retro
7,256
cores/32x/platform/libpicofe/gp2x/in_gp2x.c
/* * (C) Gražvydas "notaz" Ignotas, 2006-2012 * * This work is licensed under the terms of any of these licenses * (at your option): * - GNU GPL, version 2 or later. * - GNU LGPL, version 2.1 or later. * - MAME license. * See the COPYING file in the top-level directory. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "../input.h" #include "soc.h" #include "plat_gp2x.h" #include "in_gp2x.h" #define IN_GP2X_PREFIX "gp2x:" #define IN_GP2X_NBUTTONS 32 /* note: in_gp2x handles combos (if 2 btns have the same bind, * both must be pressed for action to happen) */ static int in_gp2x_combo_keys = 0; static int in_gp2x_combo_acts = 0; static int gpiodev = -1; /* Wiz only */ static int (*in_gp2x_get_bits)(void); static const char *in_gp2x_keys[IN_GP2X_NBUTTONS] = { [0 ... IN_GP2X_NBUTTONS-1] = NULL, [GP2X_BTN_UP] = "Up", [GP2X_BTN_LEFT] = "Left", [GP2X_BTN_DOWN] = "Down", [GP2X_BTN_RIGHT] = "Right", [GP2X_BTN_START] = "Start", [GP2X_BTN_SELECT] = "Select", [GP2X_BTN_L] = "L", [GP2X_BTN_R] = "R", [GP2X_BTN_A] = "A", [GP2X_BTN_B] = "B", [GP2X_BTN_X] = "X", [GP2X_BTN_Y] = "Y", [GP2X_BTN_VOL_DOWN] = "VOL DOWN", [GP2X_BTN_VOL_UP] = "VOL UP", [GP2X_BTN_PUSH] = "PUSH" }; static int in_gp2x_get_mmsp2_bits(void) { int value; value = memregs[0x1198>>1] & 0xff; // GPIO M if (value == 0xFD) value = 0xFA; if (value == 0xF7) value = 0xEB; if (value == 0xDF) value = 0xAF; if (value == 0x7F) value = 0xBE; value |= memregs[0x1184>>1] & 0xFF00; // GPIO C value |= memregs[0x1186>>1] << 16; // GPIO D value = ~value & 0x08c0ff55; return value; } static int in_gp2x_get_wiz_bits(void) { int r, value = 0; r = read(gpiodev, &value, 4); if (value & 0x02) value |= 0x05; if (value & 0x08) value |= 0x14; if (value & 0x20) value |= 0x50; if (value & 0x80) value |= 0x41; /* convert to GP2X style */ value &= 0x7ff55; if (value & (1 << 16)) value |= 1 << GP2X_BTN_VOL_UP; if (value & (1 << 17)) value |= 1 << GP2X_BTN_VOL_DOWN; if (value & (1 << 18)) value |= 1 << GP2X_BTN_PUSH; value &= ~0x70000; return value; } static void in_gp2x_probe(const in_drv_t *drv) { switch (gp2x_dev_id) { case GP2X_DEV_GP2X: in_gp2x_get_bits = in_gp2x_get_mmsp2_bits; break; case GP2X_DEV_WIZ: gpiodev = open("/dev/GPIO", O_RDONLY); if (gpiodev < 0) { perror("in_gp2x: couldn't open /dev/GPIO"); return; } in_gp2x_get_bits = in_gp2x_get_wiz_bits; break; // we'll use evdev for Caanoo default: return; } in_register(IN_GP2X_PREFIX "GP2X pad", -1, NULL, IN_GP2X_NBUTTONS, in_gp2x_keys, 1); } static void in_gp2x_free(void *drv_data) { if (gpiodev >= 0) { close(gpiodev); gpiodev = -1; } } static const char * const * in_gp2x_get_key_names(const in_drv_t *drv, int *count) { *count = IN_GP2X_NBUTTONS; return in_gp2x_keys; } /* ORs result with pressed buttons */ static int in_gp2x_update(void *drv_data, const int *binds, int *result) { int type_start = 0; int i, t, keys; keys = in_gp2x_get_bits(); if (keys & in_gp2x_combo_keys) { result[IN_BINDTYPE_EMU] = in_combos_do(keys, binds, GP2X_BTN_PUSH, in_gp2x_combo_keys, in_gp2x_combo_acts); type_start = IN_BINDTYPE_PLAYER12; } for (i = 0; keys; i++, keys >>= 1) { if (!(keys & 1)) continue; for (t = type_start; t < IN_BINDTYPE_COUNT; t++) result[t] |= binds[IN_BIND_OFFS(i, t)]; } return 0; } int in_gp2x_update_keycode(void *data, int *is_down) { static int old_val = 0; int val, diff, i; val = in_gp2x_get_bits(); diff = val ^ old_val; if (diff == 0) return -1; /* take one bit only */ for (i = 0; i < sizeof(diff)*8; i++) if (diff & (1<<i)) break; old_val ^= 1 << i; if (is_down) *is_down = !!(val & (1<<i)); return i; } static const struct { short key; short pbtn; } key_pbtn_map[] = { { GP2X_BTN_UP, PBTN_UP }, { GP2X_BTN_DOWN, PBTN_DOWN }, { GP2X_BTN_LEFT, PBTN_LEFT }, { GP2X_BTN_RIGHT, PBTN_RIGHT }, { GP2X_BTN_B, PBTN_MOK }, { GP2X_BTN_X, PBTN_MBACK }, { GP2X_BTN_A, PBTN_MA2 }, { GP2X_BTN_Y, PBTN_MA3 }, { GP2X_BTN_L, PBTN_L }, { GP2X_BTN_R, PBTN_R }, { GP2X_BTN_SELECT, PBTN_MENU }, }; #define KEY_PBTN_MAP_SIZE (sizeof(key_pbtn_map) / sizeof(key_pbtn_map[0])) static int in_gp2x_menu_translate(void *drv_data, int keycode, char *charcode) { int i; if (keycode < 0) { /* menu -> kc */ keycode = -keycode; for (i = 0; i < KEY_PBTN_MAP_SIZE; i++) if (key_pbtn_map[i].pbtn == keycode) return key_pbtn_map[i].key; } else { for (i = 0; i < KEY_PBTN_MAP_SIZE; i++) if (key_pbtn_map[i].key == keycode) return key_pbtn_map[i].pbtn; } return 0; } #if 0 // TODO: move to pico static const struct { short code; char btype; char bit; } in_gp2x_defbinds[] = { /* MXYZ SACB RLDU */ { BTN_UP, IN_BINDTYPE_PLAYER12, 0 }, { BTN_DOWN, IN_BINDTYPE_PLAYER12, 1 }, { BTN_LEFT, IN_BINDTYPE_PLAYER12, 2 }, { BTN_RIGHT, IN_BINDTYPE_PLAYER12, 3 }, { BTN_X, IN_BINDTYPE_PLAYER12, 4 }, /* B */ { BTN_B, IN_BINDTYPE_PLAYER12, 5 }, /* C */ { BTN_A, IN_BINDTYPE_PLAYER12, 6 }, /* A */ { BTN_START, IN_BINDTYPE_PLAYER12, 7 }, { BTN_SELECT, IN_BINDTYPE_EMU, PEVB_MENU }, // { BTN_Y, IN_BINDTYPE_EMU, PEVB_SWITCH_RND }, { BTN_L, IN_BINDTYPE_EMU, PEVB_STATE_SAVE }, { BTN_R, IN_BINDTYPE_EMU, PEVB_STATE_LOAD }, { BTN_VOL_UP, IN_BINDTYPE_EMU, PEVB_VOL_UP }, { BTN_VOL_DOWN, IN_BINDTYPE_EMU, PEVB_VOL_DOWN }, { 0, 0, 0 }, }; #endif /* remove binds of missing keys, count remaining ones */ static int in_gp2x_clean_binds(void *drv_data, int *binds, int *def_binds) { int i, count = 0; // int eb, have_vol = 0, have_menu = 0; for (i = 0; i < IN_GP2X_NBUTTONS; i++) { int t, offs; for (t = 0; t < IN_BINDTYPE_COUNT; t++) { offs = IN_BIND_OFFS(i, t); if (in_gp2x_keys[i] == NULL) binds[offs] = def_binds[offs] = 0; if (binds[offs]) count++; } #if 0 eb = binds[IN_BIND_OFFS(i, IN_BINDTYPE_EMU)]; if (eb & (PEV_VOL_DOWN|PEV_VOL_UP)) have_vol = 1; if (eb & PEV_MENU) have_menu = 1; #endif } // TODO: move to pico #if 0 /* autobind some important keys, if they are unbound */ if (!have_vol && binds[GP2X_BTN_VOL_UP] == 0 && binds[GP2X_BTN_VOL_DOWN] == 0) { binds[IN_BIND_OFFS(GP2X_BTN_VOL_UP, IN_BINDTYPE_EMU)] = PEV_VOL_UP; binds[IN_BIND_OFFS(GP2X_BTN_VOL_DOWN, IN_BINDTYPE_EMU)] = PEV_VOL_DOWN; count += 2; } if (!have_menu) { binds[IN_BIND_OFFS(GP2X_BTN_SELECT, IN_BINDTYPE_EMU)] = PEV_MENU; count++; } #endif in_combos_find(binds, GP2X_BTN_PUSH, &in_gp2x_combo_keys, &in_gp2x_combo_acts); return count; } static const in_drv_t in_gp2x_drv = { .prefix = IN_GP2X_PREFIX, .probe = in_gp2x_probe, .free = in_gp2x_free, .get_key_names = in_gp2x_get_key_names, .clean_binds = in_gp2x_clean_binds, .update = in_gp2x_update, .update_keycode = in_gp2x_update_keycode, .menu_translate = in_gp2x_menu_translate, }; void in_gp2x_init(const struct in_default_bind *defbinds) { if (gp2x_dev_id == GP2X_DEV_WIZ) in_gp2x_keys[GP2X_BTN_START] = "MENU"; in_gp2x_combo_keys = in_gp2x_combo_acts = 0; in_register_driver(&in_gp2x_drv, defbinds, NULL); }
0
0.933614
1
0.933614
game-dev
MEDIA
0.548344
game-dev
0.964998
1
0.964998
crawl/crawl
17,354
crawl-ref/source/dat/dlua/vault.lua
-------------------------------------------------------------------------- -- vault.lua: Vault helper functions from more than one file. -------------------------------------------------------------------------- -- Counting Pan runes for exits. function count_pan_runes() local runes = 0 for _, r in ipairs({"demonic","glowing","magical","fiery","dark"}) do if you.have_rune(r) then runes = runes + 1 end end return runes end -- Functionality for some of HangedMan's decor vaults. function init_hm_decor_walldepth(e, variables) local a = you.absdepth() * 5 if a - 75 > 0 then e.subst(variables .. " : x:50 c:" .. a .. " b:" .. a - 75) else e.subst(variables .. " : x:50 c:" .. a) end end -- Functionality for Kennysheep vaults. -- c: outer vault walls -- x: inner vault walls (could be see-through blocks, or not there at all) -- t: doodads. fountains, statues or the more decorative walls. Sometimes get replaced by normal walls -- w: water or lava or trees. or nothing -- D/F opposite/adjacent vault entrances, that may or may not be there -- E/H placed in front of the alternate doors. become w tiles if there's no door there function ks_random_setup(e, norandomexits) e.tags("no_pool_fixup") -- 1/2 chance the adjacent door is there, followed by a 1/2 chance every -- side has a door. if norandomexits == nil then e.tags("transparent") if crawl.one_chance_in(2) then e.subst("D : +") e.subst("E : .") if crawl.one_chance_in(2) then e.subst("F : +") e.subst("H : .") else e.subst("F : c") e.subst("H : w") end else e.subst("DF : c") e.subst("EH : w") end end --rooms have a 1/2 chance of being bordered by water or trees --q is used as a placeholder for trees to keep them from being -- re-selected in the next step. e.subst("w : w.") e.subst("w : wwwWWqq") --room setups: --0 : doodads replaced with walls --1 : walls replaced with water/lava or removed. doodads may or may not be walls --2 : doodads picked from more obvious vault decorations selected = crawl.random2(3) if selected == 0 then e.subst("t : x") e.subst("x : cvbttm") elseif selected == 1 then e.subst("x : ..wW") e.subst("t : .TmbttwG") elseif selected == 2 then e.subst("t : .TttG") e.subst("x : cvbtt") end -- Turn q into t for tree borders. e.subst("q : t") -- The outer walls are probably stone or rock, but can be metal or crystal. e.subst("c : ccccxxxxvb") -- One chance in three of turning all water on the floor into lava. -- Tree and fountain tiles are changed so the vault looks normal. if crawl.one_chance_in(3) then e.subst("Wwt : l") e.subst("T : V") end end function zot_entry_setup(e, use_default_mons) e.tags("zot_entry") e.place("Depths:$") e.orient("float") e.kitem("R = midnight gem") e.kfeat("O = enter_zot") e.kfeat("Z = zot_statue") e.kmask("R = no_item_gen") if use_default_mons then e.mons("patrolling base draconian") e.mons("fire dragon w:12 / ice dragon w:12 / storm dragon / \ shadow dragon / golden dragon w:12 / wyrmhole w:4") e.mons("patrolling nonbase draconian") e.kmons("0 = ettin / rakshasa / glowing shapeshifter w:5 / \ stone giant w:12 / spriggan berserker w:8 / hell knight w:5") e.kmons("9 = fire giant w:12 / titan w:8 / vampire knight / \ spriggan air mage w:8 / deep troll earth mage w:8 / \ tengu reaver w:12 / tentacled monstrosity / lich w:2") end end function soh_hangout() if dgn.persist.soh_hangout == nil then local hell_branches = { "Geh", "Coc", "Dis", "Tar" } dgn.persist.soh_hangout = util.random_from(hell_branches) end return dgn.persist.soh_hangout end -- the Serpent should appear in exactly one hell end. Vaults that call this -- should guarantee that `D` is present. function serpent_of_hell_setup(e) local b = soh_hangout() if not you.uniques("the Serpent of Hell") and you.in_branch(b) and you.depth() == dgn.br_depth(b) then e.kmons('D = the Serpent of Hell') end end -- Guarantee two or three rare base types with a brand function hall_of_blades_weapon(e) local long_blade_type = crawl.one_chance_in(2) and "double sword" or "triple sword" local polearm_type = crawl.one_chance_in(2) and "partisan" or "bardiche" local types = {"eveningstar", "executioner's axe", polearm_type, "lajatang", "quick blade", long_blade_type} local egos = {"flaming", "freezing", "electrocution", "heavy", "holy_wrath", "pain", "vampirism", "antimagic", "distortion", "spectral"} local weapon_t = util.random_subset(types, 3) local weapon_e = util.random_subset(egos, 3) e.mons("dancing weapon; good_item " .. weapon_t[1] .. " ego:" .. weapon_e[1]) e.mons("dancing weapon; good_item " .. weapon_t[2] .. " ego:" .. weapon_e[2]) e.mons("dancing weapon; good_item " .. weapon_t[3] .. " ego:" .. weapon_e[3] .. " / nothing") end -- Setup for door vaults to define a common loot set and create the door -- markers. function door_vault_setup(e) -- Don't generate loot in Hells, generate down hatches instead. if you.in_branch("Geh") or you.in_branch("Tar") or you.in_branch("Coc") or you.in_branch("Dis") then e.kfeat("23 = >") else e.kitem("1 = * / nothing") e.kitem("23 = | / nothing") end -- The marker affects find_connected_range() so that each door opens and -- closes separately rather than all of them joining together into a huge -- gate that opens all at once. e.lua_marker('+', props_marker { connected_exclude="true" }) e.lua_marker('a', props_marker { stop_explore="strange structure made of doors" }) e.kfeat("a = runed_clear_door") end --[[ Set up a string for a master elementalist vault-defined monster. This monster will have either the elemental staff or a staff of air and a robe of resistance, so it has all of the elemental resistances. @tab e The map environment. @string glyph The glyph on which to define the KMONS. ]] function master_elementalist_setup(e, sprintscale) local equip_def = " ; elemental staff . robe ego:willpower good_item" -- Don't want to use the fallback here, so we can know to give resistance -- ego robe if the elemental staff isn't available. if you.unrands("elemental staff") then equip_def = " ; staff of air . robe randart artprops:rF&&rC&&Will" end pow = "hd:18" name = "" -- For use in arenasprint. if sprintscale then pow = pow .. " hp:200 exp:3950" name = "name:grandmaster_elementalist n_rpl n_des n_noc" else pow = pow .. " hp:100 exp:1425" name = "name:master_elementalist n_rpl n_des n_noc" end return "occultist " .. pow .. " " .. name .. " " .. "tile:mons_master_elementalist " .. "spells:lehudib's_crystal_spear.11.wizard;" .. "chain_lightning.11.wizard;" .. "fire_storm.11.wizard;" .. "ozocubu's_refrigeration.11.wizard;" .. "haste.11.wizard;" .. "repel_missiles.11.wizard" .. equip_def .. " . ring of willpower" end -- A function to crunch down decorative skeletons. -- Vaults that only want to place regular branch skeletons or given vault -- theme skeletons don't need to call this whole function. function vault_species_skeletons(e, category) -- (Djinni, gargoyles, mummies, octopodes, poltergeists, revenants don't leave -- corpses. I don't want to think about how one recognizes vine stalkers -- post-rotting. Orcs are included to cover Beogh's popularity in the Dungeon. -- Coglins have their exoskeletons stolen. Species that only show up -- in extended are counted as the rarest type. local s1 = {"goblin", "gnoll", "elf", "kobold", "troll", "orc"} local s2 = {"draconian", "naga", "merfolk", "minotaur", "spriggan", "tengu"} local s3 = {"armataur", "barachi", "demigod", "dwarf", "demonspawn", "felid", "oni"} local output = "human skeleton" if category == "early" or category == "dungeon" or category == "all" then output = output .. " / " .. table.concat(s1, " skeleton / ") end if category == "late" or category == "dungeon" or category == "all" then output = output .. " / " .. table.concat(s2, " skeleton / ") end if category == "all" then output = output .. " / " .. table.concat(s3, " skeleton / ") end return output .. " skeleton" end -- Three sets of reusable vault feature redefines scattered across the game, -- kept in this one function for both consistency and ease of use. function vault_granite_statue_setup(e, glyph, type) e.kfeat(glyph .. " = granite_statue") -- Feature name, console colour, tile name. local statues = { ["broken pillar"] = {"lightgrey", "dngn_crumbled_column"}, ["gravestone"] = {"lightgrey", "dngn_gravestone"}, ["sarcophagus"] = {"yellow", "dngn_sarcophagus_pedestal_right"}, ["scintillating statue"] = {"mountain", "dngn_scintillating_statue"}, } for name, contents in pairs(statues) do if type == name then e.colour(glyph .. " = " .. contents[1]) e.tile(glyph .. " = " .. contents[2]) end end e.set_feature_name("granite_statue", type) end function vault_metal_statue_setup(e, glyph, type) e.kfeat(glyph .. " = metal_statue") local statues = { ["golden statue"] = {"yellow", "dngn_golden_statue"}, ["silver statue"] = {"silver", "dngn_silver_statue"}, ["iron statue"] = {"cyan", "dngn_statue_iron"}, ["mystic cage"] = {"mist", "dngn_mystic_cage"}, ["arcane conduit"] = {"vehumet", "arcane_conduit"}, ["misfortune conduit"] = {"shimmer_blue", "misfortune_conduit"}, ["dimensional conduit"] = {"warp", "dimensional_conduit"}, ["soul conduit"] = {"smoke", "soul_conduit"}, ["alchemical conduit"] = {"poison", "alchemical_conduit"}, ["fiery conduit"] = {"fire", "fiery_conduit"}, ["icy conduit"] = {"ice", "icy_conduit"}, ["earthen conduit"] = {"earth", "earthen_conduit"}, ["storm conduit"] = {"electricity", "storm_conduit"}, ["enigmatic dynamo"] = {"magic", "dngn_enigmatic_dynamo"}, ["nascence circuit"] = {"magic", "dngn_nascence_circuit"} } for name, contents in pairs(statues) do if type == name then e.colour(glyph .. " = " .. contents[1]) e.tile(glyph .. " = " .. contents[2]) end end e.set_feature_name("metal_statue", type) end function decorative_floor (e, glyph, type) e.kfeat(glyph .. ' = decorative_floor') local dec = { ["flower patch"] = {"green", "dngn_flower_patch"}, ["garden patch"] = {"yellow", "dngn_garden_patch"}, ["floral vase"] = {"yellow", "dngn_flower_pot"}, ["mourning vase"] = {"magenta", "dngn_dark_flower_pot"}, ["broken floral vase"] = {"magenta", "dngn_flower_pot_broken / " .. "dngn_dark_flower_pot_broken"}, ["orcish standard"] = {"lightcyan", "dngn_ensign_beogh"}, ["infernal standard"] = {"red", "dngn_ensign_gehenna"}, ["fur brush"] = {"brown", "dngn_yak_fur"}, ["set of bottled spirits"] = {"lightgreen", "dngn_bottled_spirits"}, ["mop and bucket"] = {"lightblue", "dngn_mop"}, ["bloodied mop and bucket"] = {"lightred", "dngn_mop_bloody"}, ["weapon-inlaid floor"] = {"lightgrey", "floor_blade"} } for name, contents in pairs(dec) do if type == name then e.colour(glyph .. " = " .. contents[1]) e.tile(glyph .. " = " .. contents[2]) end end e.set_feature_name('decorative_floor', type) end -- A reusable poison / fire / snake theming for statues that show up in Snake. function snake_statue_setup (e, glyph) if crawl.x_chance_in_y(2, 3) then vault_metal_statue_setup(e, glyph, "alchemical conduit") else vault_metal_statue_setup(e, glyph, "fiery conduit") end e.tile("G : dngn_statue_naga / dngn_statue_archer w:7") end -- A function for standardizing some tags and some floor tiles for vaults_hard -- subvaults. function vaults_hard_standard(e, ngen, ft) e.tags('vaults_hard') if ngen == nil then ngen = false end if ngen then e.tags('no_monster_gen') e.tags('no_item_gen') end if you.in_branch("Vaults") then if not ft then e.ftile('0123456789._^~$%*|defghijkmnFGITUVY+mn{([<})]}> = floor_metal_gold') else e.ftile(ft .. ' = floor_metal_gold') end end end -- A function that uses what's in the mon-pick-data (and bands) for V in 0.32 -- for several distinct, tiered, depths-scaling themes + decorations. function index_vaults_room_themes (e, set, hard) e.tags('luniq_vaults_room_' .. set) local d = you.depth() + 1 if hard then e.tags("vaults_hard") d = d + 1 else e.tags("vaults_room") end if set == 'magic' then local sl = 1 if crawl.x_chance_in_y(d, 10) then sl = sl + 1 end e.mons('lindwurm w:' .. 7 - d .. ' / crawling flesh cage w:5 / ' .. 'crystal guardian w:' .. d) e.mons('great orb of eyes w:' .. 7 - d .. ' / ' .. 'boggart band w:5 / glowing orange brain w:' .. d + 1) e.mons('arcanist w:' .. 14 - d * 2 .. ' / sphinx marauder w:8 / ' .. 'ironbound convoker w:4 / ironbound mechanist w:4') e.mons('deep elf annihilator / deep elf sorcerer / lich / ' .. 'guardian sphinx w:5 / tengu reaver') e.item('robe / mundane hat') e.item('parchment slevel:' .. sl .. ' / ' .. 'mundane ring of magical power w:2') e.tile('c = wall_studio') elseif set == 'icebox' then e.tags('no_wall_fixup') local f = 'ego:freezing pre_id' local c = 'ego:cold_resistance pre_id' e.mons('white ugly thing w:' .. 8 - d * 2 .. ' / ' .. 'harpy simulacrum w:' .. 8 - d * 2 .. ' / ' .. 'freezing wraith w:2 / guardian sphinx simulacrum w:' .. d - 1) e.mons('arcanist / crawling flesh cage') e.mons('ironbound frostheart / frost giant w:1') e.mons('golden dragon / tengu reaver w:25 ; halberd ' .. f .. ' | war axe ' .. f .. ' . ring mail ' .. c) e.kitem('d : dagger ' .. f .. ' no_pickup / ' .. 'long sword ' .. f .. ' no_pickup/ ' .. 'mace ' .. f .. ' no_pickup') e.kitem('e = robe ' .. c .. ' / leather armour ' .. c) e.kfeat('m = cache of meat') e.kfeat('I = rock_wall') e.tile('I = wall_ice_block') e.tile('v = dngn_metal_wall_lightblue') e.set_feature_name("rock_wall", "ice covered rock wall") elseif set == 'garden' then e.tags('no_pool_fixup') e.mons('harpy w:' .. 80 - d * 20 .. ' / ' .. 'wolf spider w:' .. 20 - d * 3 .. ' / ' .. 'lindwurm w:' .. 140 - d * 20 .. ' / ' .. 'dire elephant w:' .. d * 3 ) e.mons('dire elephant w:' .. 18 - d * 3 .. ' / ' .. 'formless jellyfish w:' .. 2 + d * 4 .. ' / ' .. 'guardian sphinx w:' .. 2 + d * 2) e.mons('ironbound preserver w:' .. 10 - d * 2 .. ' / ' .. 'entropy weaver w:' .. 2 + d * 3 .. ' / ' .. 'ironbound beastmaster w:' .. -2 + d * 4) e.kmons('S = bush') e.kfeat('F = cache of fruit') e.ftile('`SF = floor_moss') e.tile('T = dngn_fountain_novelty_fancy') e.kitem('d = animal skin / club / whip w:5 / quarterstaff w:5') decorative_floor(e, 'p', "garden patch") elseif set == 'rangers' then local eq = "arbalest w:29 | hand cannon w:1 . " .. " scimitar . ring mail | scale mail" e.mons('centaur warrior w:' .. 6 - d * 2 .. ' / ' .. 'yaktaur w:' .. 6 - d * 2 .. ' / ' .. 'polterguardian w:' .. 6 - d * 2 ) e.mons('vault sentinel w:' .. 8 - d * 2 .. ' ; ' .. eq .. ' / ' .. 'orc knight w:' .. 2 + d * 2 .. ' ; ' .. eq .. ' / ' .. 'yaktaur captain w:' .. 2 + d * 2) e.mons('orc warlord w:' .. 2 + d * 2 .. ' ; ' .. eq .. ' / ' .. 'deep elf high priest w:' .. 2 + d * 3 .. ' / ' .. 'vault warden w:' .. 2 + d * 4 .. ' ; ' .. eq) e.mons('stone giant') e.kmons('U = training dummy ; nothing') e.item('sling no_pickup w:5 / shortbow no_pickup / arbalest no_pickup') elseif set == 'warriorcrypt' then e.tags('no_wall_fixup') e.mons('vault guard w:' .. 14 - d .. ' / ' .. 'vault sentinel w:' .. 10 - d .. ' / ' .. 'orc knight') e.mons('phantasmal warrior w:' .. 10 - d .. ' / ' .. 'flayed ghost w:' .. 10 - d .. ' / ' .. 'death knight w:' .. d + 2) e.mons('war gargoyle w:' .. 16 - d * 2 .. ' / ' .. 'deep elf death mage w:4 / ' .. 'undying armoury w:' .. -2 + d) e.mons('deep elf death mage w:5 / lich / ancient lich') e.item('human skeleton / ogre skeleton w:1 / orc skeleton w:1') e.kfeat('u = rock_wall') e.tile('u = wall_undead') e.tile('c = wall_crypt') e.tile('G = dngn_statue_angel / dngn_statue_wraith / dngn_statue_twins / ' .. 'dngn_statue_dwarf / dngn_statue_sword / dngn_statue_centaur') end end
0
0.922713
1
0.922713
game-dev
MEDIA
0.958599
game-dev
0.661312
1
0.661312
gamekit-developers/gamekit
9,819
bullet/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "LinearMath/btPoolAllocator.h" #include "BulletCollision/CollisionDispatch/btCollisionConfiguration.h" #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h" int gNumManifold = 0; #ifdef BT_DEBUG #include <stdio.h> #endif btCollisionDispatcher::btCollisionDispatcher (btCollisionConfiguration* collisionConfiguration): m_dispatcherFlags(btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD), m_collisionConfiguration(collisionConfiguration) { int i; setNearCallback(defaultNearCallback); m_collisionAlgorithmPoolAllocator = collisionConfiguration->getCollisionAlgorithmPool(); m_persistentManifoldPoolAllocator = collisionConfiguration->getPersistentManifoldPool(); for (i=0;i<MAX_BROADPHASE_COLLISION_TYPES;i++) { for (int j=0;j<MAX_BROADPHASE_COLLISION_TYPES;j++) { m_doubleDispatch[i][j] = m_collisionConfiguration->getCollisionAlgorithmCreateFunc(i,j); btAssert(m_doubleDispatch[i][j]); } } } void btCollisionDispatcher::registerCollisionCreateFunc(int proxyType0, int proxyType1, btCollisionAlgorithmCreateFunc *createFunc) { m_doubleDispatch[proxyType0][proxyType1] = createFunc; } btCollisionDispatcher::~btCollisionDispatcher() { } btPersistentManifold* btCollisionDispatcher::getNewManifold(const btCollisionObject* body0,const btCollisionObject* body1) { gNumManifold++; //btAssert(gNumManifold < 65535); //optional relative contact breaking threshold, turned on by default (use setDispatcherFlags to switch off feature for improved performance) btScalar contactBreakingThreshold = (m_dispatcherFlags & btCollisionDispatcher::CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD) ? btMin(body0->getCollisionShape()->getContactBreakingThreshold(gContactBreakingThreshold) , body1->getCollisionShape()->getContactBreakingThreshold(gContactBreakingThreshold)) : gContactBreakingThreshold ; btScalar contactProcessingThreshold = btMin(body0->getContactProcessingThreshold(),body1->getContactProcessingThreshold()); void* mem = 0; if (m_persistentManifoldPoolAllocator->getFreeCount()) { mem = m_persistentManifoldPoolAllocator->allocate(sizeof(btPersistentManifold)); } else { //we got a pool memory overflow, by default we fallback to dynamically allocate memory. If we require a contiguous contact pool then assert. if ((m_dispatcherFlags&CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION)==0) { mem = btAlignedAlloc(sizeof(btPersistentManifold),16); } else { btAssert(0); //make sure to increase the m_defaultMaxPersistentManifoldPoolSize in the btDefaultCollisionConstructionInfo/btDefaultCollisionConfiguration return 0; } } btPersistentManifold* manifold = new(mem) btPersistentManifold (body0,body1,0,contactBreakingThreshold,contactProcessingThreshold); manifold->m_index1a = m_manifoldsPtr.size(); m_manifoldsPtr.push_back(manifold); return manifold; } void btCollisionDispatcher::clearManifold(btPersistentManifold* manifold) { manifold->clearManifold(); } void btCollisionDispatcher::releaseManifold(btPersistentManifold* manifold) { gNumManifold--; //printf("releaseManifold: gNumManifold %d\n",gNumManifold); clearManifold(manifold); int findIndex = manifold->m_index1a; btAssert(findIndex < m_manifoldsPtr.size()); m_manifoldsPtr.swap(findIndex,m_manifoldsPtr.size()-1); m_manifoldsPtr[findIndex]->m_index1a = findIndex; m_manifoldsPtr.pop_back(); manifold->~btPersistentManifold(); if (m_persistentManifoldPoolAllocator->validPtr(manifold)) { m_persistentManifoldPoolAllocator->freeMemory(manifold); } else { btAlignedFree(manifold); } } btCollisionAlgorithm* btCollisionDispatcher::findAlgorithm(const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btPersistentManifold* sharedManifold) { btCollisionAlgorithmConstructionInfo ci; ci.m_dispatcher1 = this; ci.m_manifold = sharedManifold; btCollisionAlgorithm* algo = m_doubleDispatch[body0Wrap->getCollisionShape()->getShapeType()][body1Wrap->getCollisionShape()->getShapeType()]->CreateCollisionAlgorithm(ci,body0Wrap,body1Wrap); return algo; } bool btCollisionDispatcher::needsResponse(const btCollisionObject* body0,const btCollisionObject* body1) { //here you can do filtering bool hasResponse = (body0->hasContactResponse() && body1->hasContactResponse()); //no response between two static/kinematic bodies: hasResponse = hasResponse && ((!body0->isStaticOrKinematicObject()) ||(! body1->isStaticOrKinematicObject())); return hasResponse; } bool btCollisionDispatcher::needsCollision(const btCollisionObject* body0,const btCollisionObject* body1) { btAssert(body0); btAssert(body1); bool needsCollision = true; #ifdef BT_DEBUG if (!(m_dispatcherFlags & btCollisionDispatcher::CD_STATIC_STATIC_REPORTED)) { //broadphase filtering already deals with this if (body0->isStaticOrKinematicObject() && body1->isStaticOrKinematicObject()) { m_dispatcherFlags |= btCollisionDispatcher::CD_STATIC_STATIC_REPORTED; printf("warning btCollisionDispatcher::needsCollision: static-static collision!\n"); } } #endif //BT_DEBUG if ((!body0->isActive()) && (!body1->isActive())) needsCollision = false; else if ((!body0->checkCollideWith(body1)) || (!body1->checkCollideWith(body0))) needsCollision = false; return needsCollision ; } ///interface for iterating all overlapping collision pairs, no matter how those pairs are stored (array, set, map etc) ///this is useful for the collision dispatcher. class btCollisionPairCallback : public btOverlapCallback { const btDispatcherInfo& m_dispatchInfo; btCollisionDispatcher* m_dispatcher; public: btCollisionPairCallback(const btDispatcherInfo& dispatchInfo,btCollisionDispatcher* dispatcher) :m_dispatchInfo(dispatchInfo), m_dispatcher(dispatcher) { } /*btCollisionPairCallback& operator=(btCollisionPairCallback& other) { m_dispatchInfo = other.m_dispatchInfo; m_dispatcher = other.m_dispatcher; return *this; } */ virtual ~btCollisionPairCallback() {} virtual bool processOverlap(btBroadphasePair& pair) { (*m_dispatcher->getNearCallback())(pair,*m_dispatcher,m_dispatchInfo); return false; } }; void btCollisionDispatcher::dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) { //m_blockedForChanges = true; btCollisionPairCallback collisionCallback(dispatchInfo,this); pairCache->processAllOverlappingPairs(&collisionCallback,dispatcher); //m_blockedForChanges = false; } //by default, Bullet will use this near callback void btCollisionDispatcher::defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo) { btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject; btCollisionObject* colObj1 = (btCollisionObject*)collisionPair.m_pProxy1->m_clientObject; if (dispatcher.needsCollision(colObj0,colObj1)) { btCollisionObjectWrapper obj0Wrap(0,colObj0->getCollisionShape(),colObj0,colObj0->getWorldTransform(),-1,-1); btCollisionObjectWrapper obj1Wrap(0,colObj1->getCollisionShape(),colObj1,colObj1->getWorldTransform(),-1,-1); //dispatcher will keep algorithms persistent in the collision pair if (!collisionPair.m_algorithm) { collisionPair.m_algorithm = dispatcher.findAlgorithm(&obj0Wrap,&obj1Wrap); } if (collisionPair.m_algorithm) { btManifoldResult contactPointResult(&obj0Wrap,&obj1Wrap); if (dispatchInfo.m_dispatchFunc == btDispatcherInfo::DISPATCH_DISCRETE) { //discrete collision detection query collisionPair.m_algorithm->processCollision(&obj0Wrap,&obj1Wrap,dispatchInfo,&contactPointResult); } else { //continuous collision detection query, time of impact (toi) btScalar toi = collisionPair.m_algorithm->calculateTimeOfImpact(colObj0,colObj1,dispatchInfo,&contactPointResult); if (dispatchInfo.m_timeOfImpact > toi) dispatchInfo.m_timeOfImpact = toi; } } } } void* btCollisionDispatcher::allocateCollisionAlgorithm(int size) { if (m_collisionAlgorithmPoolAllocator->getFreeCount()) { return m_collisionAlgorithmPoolAllocator->allocate(size); } //warn user for overflow? return btAlignedAlloc(static_cast<size_t>(size), 16); } void btCollisionDispatcher::freeCollisionAlgorithm(void* ptr) { if (m_collisionAlgorithmPoolAllocator->validPtr(ptr)) { m_collisionAlgorithmPoolAllocator->freeMemory(ptr); } else { btAlignedFree(ptr); } }
0
0.942516
1
0.942516
game-dev
MEDIA
0.981671
game-dev
0.96942
1
0.96942
codygibb/animus-visualizer
7,811
application.linux64/source/Camera.pde
public class Camera { PVector pos; //current position of camera PVector center; //center view for camera PVector dir; //"up" of camera; PVector moveStart; //saves the initial panning coordinates PVector moveEnd; //ending panning coordinates boolean movingCamera; //boolean storing whether camera is panning int moveTime; //total time to move from moveStart to moveEnd int currentTime; //current time while panning PVector dirStart; PVector dirEnd; boolean movingDir; int mDirTime; int mDirCurrTime; PVector mCenterStart; PVector mCenterEnd; boolean movingCenter; int mCenterTime; int mCenterCurrTime; boolean viewingMode; //true: free panning on boolean autoPanningMode; //true: auto panning on boolean autoDirChangeMode; PVector leftOuterBounds; //leftmost x, y, z auto panning bounds (generally negative) PVector rightOuterBounds; //rightmost x, y, z auto panning bounds (generally positive) PVector leftInnerBounds; PVector rightInnerBounds; Camera(float initX, float initY, float initZ) { pos = new PVector(initX, initY, initZ); dir = new PVector(0, 1, 0); center = new PVector(0, 0, 0); moveStart = new PVector(width/2, height/2, height/2); moveEnd = new PVector(width/2, height/2, height/2); movingCamera = false; autoPanningMode = false; leftOuterBounds = new PVector(-2000, -2000, -2000); rightOuterBounds = new PVector(2000, 2000, 2000); leftInnerBounds = new PVector(0, 0, 0); rightInnerBounds = new PVector(0, 0, 0); viewingMode = true; mCenterStart = new PVector(0, 0, 0); mCenterEnd = new PVector(0, 0, 0); dirStart = new PVector(0, 0, 0); dirEnd = new PVector(0, 0, 0); movingCenter = false; autoDirChangeMode = false; } Camera() { this(width/2, height/2, height/2); } void setCenter(float cx, float cy, float cz) { center = new PVector(cx, cy, cz); } void setOuterBounds(float lx, float ly, float lz, float rx, float ry, float rz) { leftOuterBounds = new PVector(lx, ly, lz); rightOuterBounds = new PVector(rx, ry, rz); } void setInnerBounds(float lx, float ly, float lz, float rx, float ry, float rz) { leftInnerBounds = new PVector(lx, ly, lz); rightInnerBounds = new PVector(rx, ry, rz); } //switches autoPanningMode on/off, also turns viewingMode off void autoPanSwitch() { autoPanningMode = !autoPanningMode; viewingMode = false; } //switches dir on/off, also turns viewingMode off void dirSwitch() { autoDirChangeMode = !autoDirChangeMode; viewingMode = false; } //switches viewingMode on/off, also turns autoPanningMode off void viewSwitch() { viewingMode = !viewingMode; if (viewingMode) { disableAllModes(); viewingMode = true; } else { disableAllModes(); } } // disables and mode that is affecting camera movement / orientation void disableAllModes() { viewingMode = false; autoPanningMode = false; autoDirChangeMode = false; movingCamera = false; movingDir = false; movingCenter = false; } //pans camera to set destination at set time (100 apprx. equals 2 seconds) void initMoveCamera(PVector destination, int time) { moveStart.x = pos.x; moveStart.y = pos.y; moveStart.z = pos.z; moveEnd = destination; moveTime = time; currentTime = 0; movingCamera = true; } void initMoveDir(PVector destination, int time) { dirStart.x = dir.x; dirStart.y = dir.y; dirStart.z = dir.z; dirEnd = destination; mDirTime = time; mDirCurrTime = 0; movingDir = true; } void initMoveCenter(float dx, float dy, float dz, int time) { mCenterStart.x = center.x; mCenterStart.y = center.y; mCenterStart.z = center.z; mCenterEnd = new PVector(dx, dy, dz); mCenterTime = time; mCenterCurrTime = 0; movingCenter = true; } void rotateCamera(float angleInc) { dir.rotate(angleInc); } PVector pickRandomPoint() { float xf, yf, zf; float x1 = random(leftOuterBounds.x, leftInnerBounds.x); float x2 = random(rightInnerBounds.x, rightOuterBounds.x); if (random(1) > 0.5) xf = x1; else xf = x2; // // float y1 = random(leftOuterBounds.y, leftInnerBounds.y); // float y2 = random(rightInnerBounds.y, rightOuterBounds.y); // if (random(1) > 0.5) // yf = y1; // else // yf = y2; yf = random(leftOuterBounds.y, rightOuterBounds.y); float z1 = random(leftOuterBounds.z, leftInnerBounds.z); float z2 = random(rightInnerBounds.z, rightOuterBounds.z); if (random(1) > 0.5) zf = z1; else zf = z2; // xf = random(leftOuterBounds.x, rightOuterBounds.x); // yf = random(leftOuterBounds.y, rightOuterBounds.y); // zf = random(leftOuterBounds.z, rightOuterBounds.z); return new PVector(xf, yf, zf); } void integrate(int currentTime, int maxTime, PVector v, PVector start, PVector end) { float angle = (currentTime*1.0 / maxTime) * PI; float xAmp = ((end.x - start.x) * PI) / (2 * maxTime); float dx = xAmp*sin(angle); v.x += dx; float yAmp = ((end.y - start.y) * PI) / (2 * maxTime); float dy = yAmp*sin(angle); v.y += dy; float zAmp = ((end.z - start.z) * PI) / (2 * maxTime); float dz = zAmp*sin(angle); v.z += dz; } //must be called every frame void update() { if (viewingMode) { pos.x = map(mouseX, 0, width, leftOuterBounds.x, rightOuterBounds.x); pos.y = map(mouseY, 0, height, leftOuterBounds.y, rightOuterBounds.y); } if (autoPanningMode && !movingCamera) { int time = (int)random(frameRate*8, frameRate*12); PVector nextPos = pickRandomPoint(); initMoveCamera(nextPos, time); } if (autoDirChangeMode && !movingDir) { int time; if (!autoPanningMode) { time = (int)random(frameRate*8, frameRate*12); } else { time = moveTime; } float x = random(-1, 1); float y = random(-1, 1); float z = random(-1, 1); initMoveDir(new PVector(x, y, z), time); } if (movingCamera) { integrate(currentTime, moveTime, pos, moveStart, moveEnd); currentTime++; if (currentTime == moveTime) { movingCamera = false; } } if (movingDir) { integrate(mDirCurrTime, mDirTime, dir, dirStart, dirEnd); mDirCurrTime++; if (mDirCurrTime == mDirTime) { movingDir = false; } } if (movingCenter) { integrate(mCenterCurrTime, mCenterTime, center, mCenterStart, mCenterEnd); mCenterCurrTime++; if (mCenterCurrTime == mCenterTime) { movingCenter = false; } } camera(pos.x, pos.y, pos.z, center.x, center.y, center.z, dir.x, dir.y, dir.z); } }
0
0.867024
1
0.867024
game-dev
MEDIA
0.645524
game-dev,graphics-rendering
0.983785
1
0.983785
andersonfreitas/opengl-tutorial-org
5,591
external/bullet-2.81-rev2613/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #define BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/BroadphaseCollision/btDispatcher.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" class btSoftBody; class btCollisionShape; #include "LinearMath/btHashMap.h" #include "BulletCollision/BroadphaseCollision/btQuantizedBvh.h" //for definition of MAX_NUM_PARTS_IN_BITS struct btTriIndex { int m_PartIdTriangleIndex; class btCollisionShape* m_childShape; btTriIndex(int partId,int triangleIndex,btCollisionShape* shape) { m_PartIdTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex; m_childShape = shape; } int getTriangleIndex() const { // Get only the lower bits where the triangle index is stored unsigned int x = 0; unsigned int y = (~(x&0))<<(31-MAX_NUM_PARTS_IN_BITS); return (m_PartIdTriangleIndex&~(y)); } int getPartId() const { // Get only the highest bits where the part index is stored return (m_PartIdTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS)); } int getUid() const { return m_PartIdTriangleIndex; } }; ///For each triangle in the concave mesh that overlaps with the AABB of a soft body (m_softBody), processTriangle is called. class btSoftBodyTriangleCallback : public btTriangleCallback { btSoftBody* m_softBody; const btCollisionObject* m_triBody; btVector3 m_aabbMin; btVector3 m_aabbMax ; btManifoldResult* m_resultOut; btDispatcher* m_dispatcher; const btDispatcherInfo* m_dispatchInfoPtr; btScalar m_collisionMarginTriangle; btHashMap<btHashKey<btTriIndex>,btTriIndex> m_shapeCache; public: int m_triangleCount; // btPersistentManifold* m_manifoldPtr; btSoftBodyTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); void setTimeStepAndCounters(btScalar collisionMarginTriangle,const btCollisionObjectWrapper* triObjWrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual ~btSoftBodyTriangleCallback(); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); void clearCache(); SIMD_FORCE_INLINE const btVector3& getAabbMin() const { return m_aabbMin; } SIMD_FORCE_INLINE const btVector3& getAabbMax() const { return m_aabbMax; } }; /// btSoftBodyConcaveCollisionAlgorithm supports collision between soft body shapes and (concave) trianges meshes. class btSoftBodyConcaveCollisionAlgorithm : public btCollisionAlgorithm { bool m_isSwapped; btSoftBodyTriangleCallback m_btSoftBodyTriangleCallback; public: btSoftBodyConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped); virtual ~btSoftBodyConcaveCollisionAlgorithm(); virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); virtual void getAllContactManifolds(btManifoldArray& manifoldArray) { //we don't add any manifolds } void clearCache(); struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,false); } }; struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap) { void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,true); } }; }; #endif //BT_SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H
0
0.913386
1
0.913386
game-dev
MEDIA
0.993985
game-dev
0.769071
1
0.769071
Balatro-Multiplayer/BalatroMultiplayer
1,868
objects/jokers/skip_off.lua
SMODS.Atlas({ key = "skip_off", path = "j_skip_off.png", px = 71, py = 95, }) SMODS.Joker({ key = "skip_off", atlas = "skip_off", rarity = 2, cost = 5, unlocked = true, discovered = true, blueprint_compat = false, eternal_compat = true, perishable_compat = true, config = { extra = { hands = 0, discards = 0, extra_hands = 1, extra_discards = 1 } }, loc_vars = function(self, info_queue, card) MP.UTILS.add_nemesis_info(info_queue) return { vars = { card.ability.extra.extra_hands, card.ability.extra.extra_discards, card.ability.extra.hands, card.ability.extra.discards, G.GAME.skips ~= nil and MP.GAME.enemy.skips ~= nil and localize({ type = "variable", key = MP.GAME.enemy.skips > G.GAME.skips and "a_mp_skips_behind" or MP.GAME.enemy.skips == G.GAME.skips and "a_mp_skips_tied" or "a_mp_skips_ahead", vars = { math.abs(MP.GAME.enemy.skips - G.GAME.skips) }, })[1] or "", }, } end, in_pool = function(self) return MP.LOBBY.code and MP.LOBBY.config.multiplayer_jokers end, update = function(self, card, dt) if G.STAGE == G.STAGES.RUN and G.GAME.skips ~= nil and MP.GAME.enemy.skips ~= nil then local skip_diff = (math.max(G.GAME.skips - MP.GAME.enemy.skips, 0)) card.ability.extra.hands = skip_diff * card.ability.extra.extra_hands card.ability.extra.discards = skip_diff * card.ability.extra.extra_discards end end, calculate = function(self, card, context) if context.cardarea == G.jokers and context.setting_blind and not context.blueprint then G.E_MANAGER:add_event(Event({ func = function() ease_hands_played(card.ability.extra.hands) ease_discard(card.ability.extra.discards, nil, true) return true end, })) end end, mp_credits = { idea = { "Dr. Monty", "Carter" }, art = { "Aura!" }, code = { "Virtualized" }, }, })
0
0.900426
1
0.900426
game-dev
MEDIA
0.994488
game-dev
0.820383
1
0.820383
soartech/jsoar
2,647
jsoar-performance-testing/src/main/resources/APT/all-test/Johnbot/Johnbot/predict-enemy/create-enemy-state.soar
#echo "\nLoading create-enemy-state" sp {predict-enemy*propose*create-enemy-state (state <s> ^name predict-enemy -^map.current-room) --> # #tcl |tsiDisplayAndSendCommand stop-soar|) (<s> ^operator <o> + >, =) (<o> ^name create-enemy-state)} sp {predict-enemy*apply*create-enemy-state*game (state <s> ^operator.name create-enemy-state ^io.input-link.game <game> ^superstate.io.input-link.game.mapname <mname>) --> (<game> ^mapname <mname>)} sp {predict-enemy*apply*create-enemy-state*create-prediction-structure (state <s> ^operator.name create-enemy-state ^superstate.operator.enemy <enemy>) --> # (<enemy> ^prediction-structure none) (<s> ^predicted-distance 0 ^last-door none)} sp {predict-enemy*apply*create-enemy-state*agent (state <s> ^operator.name create-enemy-state ^io.input-link.agent <agent> ^superstate.operator.enemy <enemy>) (<enemy> ^health <health> ^name <name> ^skin <skin> ^team <team> ^weapon <wname>) --> (<agent> ^armor-amount 0 ^deadflag alive ^health <health> ^origin <nor> ^name <name> ^skin <skin> ^team <team> ^weapon <nwid> ^weapon-selected <wname>) (<nwid> ^classname <wname>) } sp {predict-enemy*apply*create-enemy-state*agent*origin (state <s> ^operator.name create-enemy-state ^io.input-link.agent.origin <nor> ^superstate.operator.enemy <enemy>) (<enemy> ^x <x> ^y <y> ^z <z>) --> (<nor> ^x <x> ^y <y> ^z <z>) } sp {predict-enemy*apply*create-enemy-state*agent*yaw (state <s> ^operator.name create-enemy-state ^io.input-link.agent <agent> ^superstate.operator.enemy.old-aspect-h <ah>) --> (<agent> ^angle.yaw <ah>) } sp {predict-enemy*apply*create-enemy-state*current-room (state <s> ^operator.name create-enemy-state ^top-state.map <map> ^superstate.operator.enemy.old-room.room-number <rn>) (<map> ^room <room> -^current-room) (<room> ^room-number <rn>) --> (<map> ^current-room <room>)} ### Create following based on enemy-data parameters that have ### been adjusted based on observations of the enemy sp {predict-enemy*apply*create-enemy-state*self-parameters (state <s> ^operator.name create-enemy-state ^self <self> ^real-top-state.enemy-data.parameters <param>) --> (<self> ^parameters <param>)}
0
0.805396
1
0.805396
game-dev
MEDIA
0.953063
game-dev
0.842193
1
0.842193
scallyw4g/bonsai
5,307
generated/serdes_struct_lighting_settings.h
// src/engine/serdes.cpp:372:0 link_internal bonsai_type_info TypeInfo(lighting_settings *Ignored) { bonsai_type_info Result = {}; Result.Name = CSz("lighting_settings"); Result.Version = 0 ; /* type.map(member) */ /* { */ /* { */ /* member_info Member = {CSz("member.name"), CSz("member.name"), 0x(member.hash)}; */ /* Push(&Result.Members, &Member); */ /* } */ /* } */ return Result; } link_internal b32 Serialize(u8_cursor_block_array *Bytes, lighting_settings *BaseElement, umm Count = 1) { Assert(Count > 0); u64 PointerTrue = True; u64 PointerFalse = False; b32 Result = True; RangeIterator_t(umm, ElementIndex, Count) { lighting_settings *Element = BaseElement + ElementIndex; Result &= Serialize(Bytes, &Element->AutoDayNightCycle); // default Result &= Serialize(Bytes, &Element->tDay); // default Result &= Serialize(Bytes, &Element->SunP); // default Result &= Serialize(Bytes, &Element->DawnIntensity); // default Result &= Serialize(Bytes, &Element->DawnColor); // default Result &= Serialize(Bytes, &Element->SunIntensity); // default Result &= Serialize(Bytes, &Element->SunColor); // default Result &= Serialize(Bytes, &Element->DuskIntensity); // default Result &= Serialize(Bytes, &Element->DuskColor); // default Result &= Serialize(Bytes, &Element->MoonIntensity); // default Result &= Serialize(Bytes, &Element->MoonColor); // default Result &= Serialize(Bytes, &Element->CurrentSunColor); // default MAYBE_WRITE_DEBUG_OBJECT_DELIM(); } return Result; } link_internal b32 Deserialize(u8_cursor *Bytes, lighting_settings *Element, memory_arena *Memory, umm Count = 1); link_internal b32 DeserializeCurrentVersion(u8_cursor *Bytes, lighting_settings *Element, memory_arena *Memory); link_internal b32 DeserializeCurrentVersion(u8_cursor *Bytes, lighting_settings *Element, memory_arena *Memory) { b32 Result = True; // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->AutoDayNightCycle, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->tDay, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->SunP, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->DawnIntensity, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->DawnColor, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->SunIntensity, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->SunColor, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->DuskIntensity, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->DuskColor, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->MoonIntensity, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->MoonColor, Memory); // NOTE(Jesse): Unfortunately we can't check for primitives because // strings are considered primitive, but need memory to deserialize Result &= Deserialize(Bytes, &Element->CurrentSunColor, Memory); MAYBE_READ_DEBUG_OBJECT_DELIM(); return Result; } link_internal b32 Deserialize(u8_cursor *Bytes, lighting_settings *Element, memory_arena *Memory, umm Count) { Assert(Count > 0); b32 Result = True; RangeIterator_t(umm, ElementIndex, Count) { Result &= DeserializeCurrentVersion(Bytes, Element+ElementIndex, Memory); } return Result; }
0
0.502705
1
0.502705
game-dev
MEDIA
0.380561
game-dev
0.73804
1
0.73804
thelumiereguy/AstroAdventures-Android
6,745
app/src/main/java/com/thelumierguy/astroadventures/ui/game/views/enemyShip/EnemyClusterView.kt
package com.thelumierguy.astroadventures.ui.game.views.enemyShip import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import com.thelumierguy.astroadventures.data.* import com.thelumierguy.astroadventures.data.GlobalCounter.enemyTimerFlow import com.thelumierguy.astroadventures.ui.base.BaseCustomView import com.thelumierguy.astroadventures.utils.HapticService import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.ticker import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.receiveAsFlow import java.util.* class EnemyClusterView(context: Context, attributeSet: AttributeSet? = null) : BaseCustomView(context, attributeSet), RigidBodyObject { companion object { var speed = 2F } private val maxRowsSize = 5 private var columnSize = 6 private var rowSize = 1 lateinit var bulletStore: BulletStore private val hapticService by lazy { HapticService(context) } var onCollisionCallBack: OnCollisionCallBack? = null set(value) { field = value collisionDetector.onCollisionCallBack = value } override val collisionDetector: CollisionDetector = CollisionDetector(lifeCycleOwner) var enemyDetailsCallback: EnemyDetailsCallback? = null private val enemyList = mutableListOf( EnemyColumn() ) private var translateJob: Job = Job() private var firingJob: Job = SupervisorJob() var disableInit: Boolean = false override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (!disableInit) initEnemies() } init { setLayerType(LAYER_TYPE_HARDWARE, null) if (rowSize < maxRowsSize) { rowSize = LevelInfo.level + 1 } } private fun initEnemies() { enemyList.clear() repeat(columnSize) { x -> val enemiesList = MutableList(rowSize) { y -> Enemy.builder(columnSize, measuredWidth, x, y) } val range = enemiesList.getRangeX() enemyList.add( EnemyColumn( EnemyLocationRange(range.first, range.second), enemiesList ) ) } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() translateJob.cancel() firingJob.cancel() } /** * Counter for translating the enemies */ private fun startTranslating() { translateJob.cancel() translateJob = lifeCycleOwner.customViewLifeCycleScope.launchWhenCreated { enemyTimerFlow.collect { executeIfActive { enemyList.checkIfYReached(measuredHeight) { hasReachedMax -> if (hasReachedMax) { resetEnemies() } if (enemyList.isNotEmpty()) { translateEnemy(System.currentTimeMillis()) invalidate() } } } } } } private fun fireCanon() { if (shouldEmitObjects()) { firingJob.cancel() firingJob = lifeCycleOwner.customViewLifeCycleScope.launchWhenCreated { ticker(1000, 200).receiveAsFlow().collect { executeIfActive { if (enemyList.isNotEmpty()) { val enemyList = enemyList.random() val enemy = enemyList.enemyList.findLast { it.isVisible } enemy?.let { enemyDetailsCallback?.onCanonReady(enemy.enemyX, enemy.enemyY) } } } } } } } private fun shouldEmitObjects(): Boolean = LevelInfo.level != 0 private fun translateEnemy(millisUntilFinished: Long) { enemyList.flattenedForEach { enemy -> enemy.translate(millisUntilFinished) } } private fun resetEnemies() { enemyList.clear() enemyDetailsCallback?.onGameOver() hapticService.performHapticFeedback(320) postInvalidate() } override fun onDraw(canvas: Canvas?) { enemyList.flattenedForEach { it.onDraw(canvas) } } override fun checkCollision( softBodyObjectData: SoftBodyObjectData, ) { collisionDetector.checkCollision(softBodyObjectData) { softBodyPosition, softBodyObject -> enemyList.checkXForEach(softBodyPosition.x) { val enemyInLine = it.enemyList.reversed().find { it.checkEnemyYPosition(softBodyPosition.y) } enemyInLine?.let { enemy -> collisionDetector.onHitRigidBody(softBodyObject) destroyEnemy(enemy) scanForEnemies() } } } } override fun removeSoftBodyEntry(bullet: UUID) { collisionDetector.removeSoftBodyEntry(bullet) } private fun scanForEnemies() { val anyVisible = enemyList.any { it.areAnyVisible() } if (!anyVisible) { hapticService.performHapticFeedback(320) if (::bulletStore.isInitialized) enemyDetailsCallback?.onAllEliminated(bulletStore.getAmmoCount()) } } private fun destroyEnemy(enemyInLine: Enemy) { enemyList.flattenedForEach { if (it == enemyInLine) { it.onHit() } } dropGift(enemyInLine) hapticService.performHapticFeedback(64, 48) postInvalidate() } private fun dropGift(enemyInLine: Enemy) { if (enemyInLine.hasDrops && enemyInLine.enemyLife == 0 && shouldEmitObjects()) { enemyDetailsCallback?.hasDrop(enemyInLine.enemyX, enemyInLine.enemyY) } } fun startGame() { startTranslating() fireCanon() } } fun List<Enemy>.getRangeX(): Pair<Float, Float> { return if (size > 0) { val enemy = get(0) Pair(enemy.enemyX - enemy.hitBoxRadius, enemy.enemyX + enemy.hitBoxRadius) } else { Pair(0F, 0F) } } interface EnemyDetailsCallback { fun onAllEliminated(ammoCount: Int) fun onCanonReady(enemyX: Float, enemyY: Float) fun hasDrop(enemyX: Float, enemyY: Float) fun onGameOver() } interface OnCollisionCallBack { fun onCollision(softBodyObject: SoftBodyObjectData) }
0
0.877368
1
0.877368
game-dev
MEDIA
0.849844
game-dev
0.918554
1
0.918554
ww-rm/SpineViewer
3,586
SpineRuntimes/SpineRuntime37/TransformConstraintData.cs
/****************************************************************************** * Spine Runtimes License Agreement * Last updated May 1, 2019. Replaces all prior versions. * * Copyright (c) 2013-2019, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS * INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace SpineRuntime37 { public class TransformConstraintData { internal string name; internal int order; internal ExposedList<BoneData> bones = new ExposedList<BoneData>(); internal BoneData target; internal float rotateMix, translateMix, scaleMix, shearMix; internal float offsetRotation, offsetX, offsetY, offsetScaleX, offsetScaleY, offsetShearY; internal bool relative, local; public string Name { get { return name; } } public int Order { get { return order; } set { order = value; } } public ExposedList<BoneData> Bones { get { return bones; } } public BoneData Target { get { return target; } set { target = value; } } public float RotateMix { get { return rotateMix; } set { rotateMix = value; } } public float TranslateMix { get { return translateMix; } set { translateMix = value; } } public float ScaleMix { get { return scaleMix; } set { scaleMix = value; } } public float ShearMix { get { return shearMix; } set { shearMix = value; } } public float OffsetRotation { get { return offsetRotation; } set { offsetRotation = value; } } public float OffsetX { get { return offsetX; } set { offsetX = value; } } public float OffsetY { get { return offsetY; } set { offsetY = value; } } public float OffsetScaleX { get { return offsetScaleX; } set { offsetScaleX = value; } } public float OffsetScaleY { get { return offsetScaleY; } set { offsetScaleY = value; } } public float OffsetShearY { get { return offsetShearY; } set { offsetShearY = value; } } public bool Relative { get { return relative; } set { relative = value; } } public bool Local { get { return local; } set { local = value; } } public TransformConstraintData (string name) { if (name == null) throw new ArgumentNullException("name", "name cannot be null."); this.name = name; } override public string ToString () { return name; } } }
0
0.62046
1
0.62046
game-dev
MEDIA
0.700448
game-dev
0.917588
1
0.917588
KoffeinFlummi/AGM
2,452
AGM_Core/functions/fn_doAnimation.sqf
/* * Author: commy2 * * Execute an animation. This is used to not break things like the unconsciousness animation. * * Argument: * 0: Unit (Object) * 1: Animation (String) * 2: Priority of the animation. (Number, optional default: 0) * 0: PlayMove * 1: PlayMoveNow * 2: SwitchMove (no transitional animation, doesn't overwrite priority 1) * * Return value: * Nothing */ private ["_unit", "_animation", "_priority", "_force"]; _unit = _this select 0; _animation = _this select 1; _priority = _this select 2; _force = False; // no animation given if (isNil "_animation") exitWith { diag_log format ["[AGM] ERROR: No animation specified in %1", _fnc_scriptNameParent]; }; if (isNil "_priority") then { _priority = 0; }; if (count _this > 3) then { _force = _this select 3; }; // don't overwrite more important animations if (_unit getVariable ["AGM_isUnconscious", false] && {!_force}) exitWith { if (_animation != "Unconscious") then { [_unit, "Unconscious", 2] call AGM_Core_fnc_doAnimation; }; }; // don't go unconscious if the unit isn't unconscious if (_animation == "Unconscious" && {!(_unit getVariable ["AGM_isUnconscious", false])}) exitWith {}; // switchMove "" no longer works in dev 1.37 if (_animation == "") then { _animation = [_unit] call AGM_Core_fnc_getDefaultAnim; }; switch (_priority) do { case 0 : { if (_unit == vehicle _unit) then { [_unit, format ["{_this playMove '%1'}", _animation], _unit] call AGM_Core_fnc_execRemoteFnc; } else { // Execute on all machines. PlayMove and PlayMoveNow are bugged: They have no global effects when executed on remote machines inside vehicles. [_unit, format ["{_this playMove '%1'}", _animation]] call AGM_Core_fnc_execRemoteFnc; }; }; case 1 : { if (_unit == vehicle _unit) then { [_unit, format ["{_this playMoveNow '%1'}", _animation], _unit] call AGM_Core_fnc_execRemoteFnc; } else { // Execute on all machines. PlayMove and PlayMoveNow are bugged: They have no global effects when executed on remote machines inside vehicles. [_unit, format ["{_this playMoveNow '%1'}", _animation]] call AGM_Core_fnc_execRemoteFnc; }; }; case 2 : { // Execute on all machines. SwitchMove has local effects. [_unit, format ["{_this switchMove '%1'}", _animation]] call AGM_Core_fnc_execRemoteFnc; }; default {}; }; ["Anim", [_priority, _animation]] call AGM_Debug_fnc_log;
0
0.588614
1
0.588614
game-dev
MEDIA
0.982555
game-dev
0.859932
1
0.859932
Nextpeer/Nextpeer-UFORUN
16,698
cocos2d-x-2.2/external/emscripten/tests/bullet/src/BulletCollision/Gimpact/gim_box_set.h
#ifndef GIM_BOX_SET_H_INCLUDED #define GIM_BOX_SET_H_INCLUDED /*! \file gim_box_set.h \author Francisco Leon Najera */ /* ----------------------------------------------------------------------------- This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file GIMPACT-LICENSE-LGPL.TXT. (2) The BSD-style license that is included with this library in the file GIMPACT-LICENSE-BSD.TXT. (3) The zlib/libpng license that is included with this library in the file GIMPACT-LICENSE-ZLIB.TXT. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details. ----------------------------------------------------------------------------- */ #include "gim_array.h" #include "gim_radixsort.h" #include "gim_box_collision.h" #include "gim_tri_collision.h" //! Overlapping pair struct GIM_PAIR { GUINT m_index1; GUINT m_index2; GIM_PAIR() {} GIM_PAIR(const GIM_PAIR & p) { m_index1 = p.m_index1; m_index2 = p.m_index2; } GIM_PAIR(GUINT index1, GUINT index2) { m_index1 = index1; m_index2 = index2; } }; //! A pairset array class gim_pair_set: public gim_array<GIM_PAIR> { public: gim_pair_set():gim_array<GIM_PAIR>(32) { } inline void push_pair(GUINT index1,GUINT index2) { push_back(GIM_PAIR(index1,index2)); } inline void push_pair_inv(GUINT index1,GUINT index2) { push_back(GIM_PAIR(index2,index1)); } }; //! Prototype Base class for primitive classification /*! This class is a wrapper for primitive collections. This tells relevant info for the Bounding Box set classes, which take care of space classification. This class can manage Compound shapes and trimeshes, and if it is managing trimesh then the Hierarchy Bounding Box classes will take advantage of primitive Vs Box overlapping tests for getting optimal results and less Per Box compairisons. */ class GIM_PRIMITIVE_MANAGER_PROTOTYPE { public: virtual ~GIM_PRIMITIVE_MANAGER_PROTOTYPE() {} //! determines if this manager consist on only triangles, which special case will be optimized virtual bool is_trimesh() = 0; virtual GUINT get_primitive_count() = 0; virtual void get_primitive_box(GUINT prim_index ,GIM_AABB & primbox) = 0; virtual void get_primitive_triangle(GUINT prim_index,GIM_TRIANGLE & triangle) = 0; }; struct GIM_AABB_DATA { GIM_AABB m_bound; GUINT m_data; }; //! Node Structure for trees struct GIM_BOX_TREE_NODE { GIM_AABB m_bound; GUINT m_left;//!< Left subtree GUINT m_right;//!< Right subtree GUINT m_escapeIndex;//!< Scape index for traversing GUINT m_data;//!< primitive index if apply GIM_BOX_TREE_NODE() { m_left = 0; m_right = 0; m_escapeIndex = 0; m_data = 0; } SIMD_FORCE_INLINE bool is_leaf_node() const { return (!m_left && !m_right); } }; //! Basic Box tree structure class GIM_BOX_TREE { protected: GUINT m_num_nodes; gim_array<GIM_BOX_TREE_NODE> m_node_array; protected: GUINT _sort_and_calc_splitting_index( gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex, GUINT splitAxis); GUINT _calc_splitting_axis(gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex); void _build_sub_tree(gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex); public: GIM_BOX_TREE() { m_num_nodes = 0; } //! prototype functions for box tree management //!@{ void build_tree(gim_array<GIM_AABB_DATA> & primitive_boxes); SIMD_FORCE_INLINE void clearNodes() { m_node_array.clear(); m_num_nodes = 0; } //! node count SIMD_FORCE_INLINE GUINT getNodeCount() const { return m_num_nodes; } //! tells if the node is a leaf SIMD_FORCE_INLINE bool isLeafNode(GUINT nodeindex) const { return m_node_array[nodeindex].is_leaf_node(); } SIMD_FORCE_INLINE GUINT getNodeData(GUINT nodeindex) const { return m_node_array[nodeindex].m_data; } SIMD_FORCE_INLINE void getNodeBound(GUINT nodeindex, GIM_AABB & bound) const { bound = m_node_array[nodeindex].m_bound; } SIMD_FORCE_INLINE void setNodeBound(GUINT nodeindex, const GIM_AABB & bound) { m_node_array[nodeindex].m_bound = bound; } SIMD_FORCE_INLINE GUINT getLeftNodeIndex(GUINT nodeindex) const { return m_node_array[nodeindex].m_left; } SIMD_FORCE_INLINE GUINT getRightNodeIndex(GUINT nodeindex) const { return m_node_array[nodeindex].m_right; } SIMD_FORCE_INLINE GUINT getScapeNodeIndex(GUINT nodeindex) const { return m_node_array[nodeindex].m_escapeIndex; } //!@} }; //! Generic Box Tree Template /*! This class offers an structure for managing a box tree of primitives. Requires a Primitive prototype (like GIM_PRIMITIVE_MANAGER_PROTOTYPE ) and a Box tree structure ( like GIM_BOX_TREE). */ template<typename _GIM_PRIMITIVE_MANAGER_PROTOTYPE, typename _GIM_BOX_TREE_PROTOTYPE> class GIM_BOX_TREE_TEMPLATE_SET { protected: _GIM_PRIMITIVE_MANAGER_PROTOTYPE m_primitive_manager; _GIM_BOX_TREE_PROTOTYPE m_box_tree; protected: //stackless refit SIMD_FORCE_INLINE void refit() { GUINT nodecount = getNodeCount(); while(nodecount--) { if(isLeafNode(nodecount)) { GIM_AABB leafbox; m_primitive_manager.get_primitive_box(getNodeData(nodecount),leafbox); setNodeBound(nodecount,leafbox); } else { //get left bound GUINT childindex = getLeftNodeIndex(nodecount); GIM_AABB bound; getNodeBound(childindex,bound); //get right bound childindex = getRightNodeIndex(nodecount); GIM_AABB bound2; getNodeBound(childindex,bound2); bound.merge(bound2); setNodeBound(nodecount,bound); } } } public: GIM_BOX_TREE_TEMPLATE_SET() { } SIMD_FORCE_INLINE GIM_AABB getGlobalBox() const { GIM_AABB totalbox; getNodeBound(0, totalbox); return totalbox; } SIMD_FORCE_INLINE void setPrimitiveManager(const _GIM_PRIMITIVE_MANAGER_PROTOTYPE & primitive_manager) { m_primitive_manager = primitive_manager; } const _GIM_PRIMITIVE_MANAGER_PROTOTYPE & getPrimitiveManager() const { return m_primitive_manager; } _GIM_PRIMITIVE_MANAGER_PROTOTYPE & getPrimitiveManager() { return m_primitive_manager; } //! node manager prototype functions ///@{ //! this attemps to refit the box set. SIMD_FORCE_INLINE void update() { refit(); } //! this rebuild the entire set SIMD_FORCE_INLINE void buildSet() { //obtain primitive boxes gim_array<GIM_AABB_DATA> primitive_boxes; primitive_boxes.resize(m_primitive_manager.get_primitive_count(),false); for (GUINT i = 0;i<primitive_boxes.size() ;i++ ) { m_primitive_manager.get_primitive_box(i,primitive_boxes[i].m_bound); primitive_boxes[i].m_data = i; } m_box_tree.build_tree(primitive_boxes); } //! returns the indices of the primitives in the m_primitive_manager SIMD_FORCE_INLINE bool boxQuery(const GIM_AABB & box, gim_array<GUINT> & collided_results) const { GUINT curIndex = 0; GUINT numNodes = getNodeCount(); while (curIndex < numNodes) { GIM_AABB bound; getNodeBound(curIndex,bound); //catch bugs in tree data bool aabbOverlap = bound.has_collision(box); bool isleafnode = isLeafNode(curIndex); if (isleafnode && aabbOverlap) { collided_results.push_back(getNodeData(curIndex)); } if (aabbOverlap || isleafnode) { //next subnode curIndex++; } else { //skip node curIndex+= getScapeNodeIndex(curIndex); } } if(collided_results.size()>0) return true; return false; } //! returns the indices of the primitives in the m_primitive_manager SIMD_FORCE_INLINE bool boxQueryTrans(const GIM_AABB & box, const btTransform & transform, gim_array<GUINT> & collided_results) const { GIM_AABB transbox=box; transbox.appy_transform(transform); return boxQuery(transbox,collided_results); } //! returns the indices of the primitives in the m_primitive_manager SIMD_FORCE_INLINE bool rayQuery( const btVector3 & ray_dir,const btVector3 & ray_origin , gim_array<GUINT> & collided_results) const { GUINT curIndex = 0; GUINT numNodes = getNodeCount(); while (curIndex < numNodes) { GIM_AABB bound; getNodeBound(curIndex,bound); //catch bugs in tree data bool aabbOverlap = bound.collide_ray(ray_origin,ray_dir); bool isleafnode = isLeafNode(curIndex); if (isleafnode && aabbOverlap) { collided_results.push_back(getNodeData( curIndex)); } if (aabbOverlap || isleafnode) { //next subnode curIndex++; } else { //skip node curIndex+= getScapeNodeIndex(curIndex); } } if(collided_results.size()>0) return true; return false; } //! tells if this set has hierarcht SIMD_FORCE_INLINE bool hasHierarchy() const { return true; } //! tells if this set is a trimesh SIMD_FORCE_INLINE bool isTrimesh() const { return m_primitive_manager.is_trimesh(); } //! node count SIMD_FORCE_INLINE GUINT getNodeCount() const { return m_box_tree.getNodeCount(); } //! tells if the node is a leaf SIMD_FORCE_INLINE bool isLeafNode(GUINT nodeindex) const { return m_box_tree.isLeafNode(nodeindex); } SIMD_FORCE_INLINE GUINT getNodeData(GUINT nodeindex) const { return m_box_tree.getNodeData(nodeindex); } SIMD_FORCE_INLINE void getNodeBound(GUINT nodeindex, GIM_AABB & bound) const { m_box_tree.getNodeBound(nodeindex, bound); } SIMD_FORCE_INLINE void setNodeBound(GUINT nodeindex, const GIM_AABB & bound) { m_box_tree.setNodeBound(nodeindex, bound); } SIMD_FORCE_INLINE GUINT getLeftNodeIndex(GUINT nodeindex) const { return m_box_tree.getLeftNodeIndex(nodeindex); } SIMD_FORCE_INLINE GUINT getRightNodeIndex(GUINT nodeindex) const { return m_box_tree.getRightNodeIndex(nodeindex); } SIMD_FORCE_INLINE GUINT getScapeNodeIndex(GUINT nodeindex) const { return m_box_tree.getScapeNodeIndex(nodeindex); } SIMD_FORCE_INLINE void getNodeTriangle(GUINT nodeindex,GIM_TRIANGLE & triangle) const { m_primitive_manager.get_primitive_triangle(getNodeData(nodeindex),triangle); } }; //! Class for Box Tree Sets /*! this has the GIM_BOX_TREE implementation for bounding boxes. */ template<typename _GIM_PRIMITIVE_MANAGER_PROTOTYPE> class GIM_BOX_TREE_SET: public GIM_BOX_TREE_TEMPLATE_SET< _GIM_PRIMITIVE_MANAGER_PROTOTYPE, GIM_BOX_TREE> { public: }; /// GIM_BOX_SET collision methods template<typename BOX_SET_CLASS0,typename BOX_SET_CLASS1> class GIM_TREE_TREE_COLLIDER { public: gim_pair_set * m_collision_pairs; BOX_SET_CLASS0 * m_boxset0; BOX_SET_CLASS1 * m_boxset1; GUINT current_node0; GUINT current_node1; bool node0_is_leaf; bool node1_is_leaf; bool t0_is_trimesh; bool t1_is_trimesh; bool node0_has_triangle; bool node1_has_triangle; GIM_AABB m_box0; GIM_AABB m_box1; GIM_BOX_BOX_TRANSFORM_CACHE trans_cache_1to0; btTransform trans_cache_0to1; GIM_TRIANGLE m_tri0; btVector4 m_tri0_plane; GIM_TRIANGLE m_tri1; btVector4 m_tri1_plane; public: GIM_TREE_TREE_COLLIDER() { current_node0 = G_UINT_INFINITY; current_node1 = G_UINT_INFINITY; } protected: SIMD_FORCE_INLINE void retrieve_node0_triangle(GUINT node0) { if(node0_has_triangle) return; m_boxset0->getNodeTriangle(node0,m_tri0); //transform triangle m_tri0.m_vertices[0] = trans_cache_0to1(m_tri0.m_vertices[0]); m_tri0.m_vertices[1] = trans_cache_0to1(m_tri0.m_vertices[1]); m_tri0.m_vertices[2] = trans_cache_0to1(m_tri0.m_vertices[2]); m_tri0.get_plane(m_tri0_plane); node0_has_triangle = true; } SIMD_FORCE_INLINE void retrieve_node1_triangle(GUINT node1) { if(node1_has_triangle) return; m_boxset1->getNodeTriangle(node1,m_tri1); //transform triangle m_tri1.m_vertices[0] = trans_cache_1to0.transform(m_tri1.m_vertices[0]); m_tri1.m_vertices[1] = trans_cache_1to0.transform(m_tri1.m_vertices[1]); m_tri1.m_vertices[2] = trans_cache_1to0.transform(m_tri1.m_vertices[2]); m_tri1.get_plane(m_tri1_plane); node1_has_triangle = true; } SIMD_FORCE_INLINE void retrieve_node0_info(GUINT node0) { if(node0 == current_node0) return; m_boxset0->getNodeBound(node0,m_box0); node0_is_leaf = m_boxset0->isLeafNode(node0); node0_has_triangle = false; current_node0 = node0; } SIMD_FORCE_INLINE void retrieve_node1_info(GUINT node1) { if(node1 == current_node1) return; m_boxset1->getNodeBound(node1,m_box1); node1_is_leaf = m_boxset1->isLeafNode(node1); node1_has_triangle = false; current_node1 = node1; } SIMD_FORCE_INLINE bool node_collision(GUINT node0 ,GUINT node1) { retrieve_node0_info(node0); retrieve_node1_info(node1); bool result = m_box0.overlapping_trans_cache(m_box1,trans_cache_1to0,true); if(!result) return false; if(t0_is_trimesh && node0_is_leaf) { //perform primitive vs box collision retrieve_node0_triangle(node0); //do triangle vs box collision m_box1.increment_margin(m_tri0.m_margin); result = m_box1.collide_triangle_exact( m_tri0.m_vertices[0],m_tri0.m_vertices[1],m_tri0.m_vertices[2],m_tri0_plane); m_box1.increment_margin(-m_tri0.m_margin); if(!result) return false; return true; } else if(t1_is_trimesh && node1_is_leaf) { //perform primitive vs box collision retrieve_node1_triangle(node1); //do triangle vs box collision m_box0.increment_margin(m_tri1.m_margin); result = m_box0.collide_triangle_exact( m_tri1.m_vertices[0],m_tri1.m_vertices[1],m_tri1.m_vertices[2],m_tri1_plane); m_box0.increment_margin(-m_tri1.m_margin); if(!result) return false; return true; } return true; } //stackless collision routine void find_collision_pairs() { gim_pair_set stack_collisions; stack_collisions.reserve(32); //add the first pair stack_collisions.push_pair(0,0); while(stack_collisions.size()) { //retrieve the last pair and pop GUINT node0 = stack_collisions.back().m_index1; GUINT node1 = stack_collisions.back().m_index2; stack_collisions.pop_back(); if(node_collision(node0,node1)) // a collision is found { if(node0_is_leaf) { if(node1_is_leaf) { m_collision_pairs->push_pair(m_boxset0->getNodeData(node0),m_boxset1->getNodeData(node1)); } else { //collide left stack_collisions.push_pair(node0,m_boxset1->getLeftNodeIndex(node1)); //collide right stack_collisions.push_pair(node0,m_boxset1->getRightNodeIndex(node1)); } } else { if(node1_is_leaf) { //collide left stack_collisions.push_pair(m_boxset0->getLeftNodeIndex(node0),node1); //collide right stack_collisions.push_pair(m_boxset0->getRightNodeIndex(node0),node1); } else { GUINT left0 = m_boxset0->getLeftNodeIndex(node0); GUINT right0 = m_boxset0->getRightNodeIndex(node0); GUINT left1 = m_boxset1->getLeftNodeIndex(node1); GUINT right1 = m_boxset1->getRightNodeIndex(node1); //collide left stack_collisions.push_pair(left0,left1); //collide right stack_collisions.push_pair(left0,right1); //collide left stack_collisions.push_pair(right0,left1); //collide right stack_collisions.push_pair(right0,right1); }// else if node1 is not a leaf }// else if node0 is not a leaf }// if(node_collision(node0,node1)) }//while(stack_collisions.size()) } public: void find_collision(BOX_SET_CLASS0 * boxset1, const btTransform & trans1, BOX_SET_CLASS1 * boxset2, const btTransform & trans2, gim_pair_set & collision_pairs, bool complete_primitive_tests = true) { m_collision_pairs = &collision_pairs; m_boxset0 = boxset1; m_boxset1 = boxset2; trans_cache_1to0.calc_from_homogenic(trans1,trans2); trans_cache_0to1 = trans2.inverse(); trans_cache_0to1 *= trans1; if(complete_primitive_tests) { t0_is_trimesh = boxset1->getPrimitiveManager().is_trimesh(); t1_is_trimesh = boxset2->getPrimitiveManager().is_trimesh(); } else { t0_is_trimesh = false; t1_is_trimesh = false; } find_collision_pairs(); } }; #endif // GIM_BOXPRUNING_H_INCLUDED
0
0.961887
1
0.961887
game-dev
MEDIA
0.621163
game-dev
0.714309
1
0.714309
PiratesOnlineRewritten/Pirates-Online-Rewritten
10,119
pirates/invasion/DistributedInvasionDelFuego.py
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.gui.DirectGui import * from pirates.ai import HolidayGlobals from pirates.audio import SoundGlobals from pirates.audio.SoundGlobals import loadSfx from pirates.piratesbase import PiratesGlobals from pirates.piratesgui import PiratesGuiGlobals from pirates.piratesbase import PLocalizer from pirates.invasion import DistributedInvasionObject from pirates.ship import ShipGlobals import copy import random class DistributedInvasionDelFuego(DistributedInvasionObject.DistributedInvasionObject): notify = directNotify.newCategory('DistributedInvasionDelFuego') def __init__(self, cr): DistributedInvasionObject.DistributedInvasionObject.__init__(self, cr) self.setHolidayId(HolidayGlobals.INVASIONDELFUEGO) def announceGenerate(self): DistributedInvasionObject.DistributedInvasionObject.announceGenerate(self) if self.canPlaySfx: self.startMessages = [ loadSfx(SoundGlobals.SFX_MONSTER_JR_FORWARD_ATTACK)] self.secondWaveMessages = [ loadSfx(SoundGlobals.SFX_MONSTER_JR_NEXT_BRIGADE)] self.waveMessages = [ loadSfx(SoundGlobals.SFX_MONSTER_JR_BREAK), loadSfx(SoundGlobals.SFX_MONSTER_JR_TONIGHT), loadSfx(SoundGlobals.SFX_MONSTER_JR_NOT_BAD), loadSfx(SoundGlobals.SFX_MONSTER_JR_ACCEPT), loadSfx(SoundGlobals.SFX_MONSTER_JR_HOWS_THIS), loadSfx(SoundGlobals.SFX_MONSTER_JR_RIP), loadSfx(SoundGlobals.SFX_MONSTER_JR_FIGHT), loadSfx(SoundGlobals.SFX_MONSTER_JR_BRING), loadSfx(SoundGlobals.SFX_MONSTER_JR_ITCHING_TO_FIGHT), loadSfx(SoundGlobals.SFX_MONSTER_JR_FORWARD), loadSfx(SoundGlobals.SFX_MONSTER_JR_SPINELESS_FOOLS), loadSfx(SoundGlobals.SFX_MONSTER_JR_STORM_THE_BEACHES), loadSfx(SoundGlobals.SFX_MONSTER_JR_FIGHT_ON), loadSfx(SoundGlobals.SFX_MONSTER_JR_FEAST_SOULS), loadSfx(SoundGlobals.SFX_MONSTER_JR_FASTER_YOU_SCABS), loadSfx(SoundGlobals.SFX_MONSTER_JR_DISPATCH), loadSfx(SoundGlobals.SFX_MONSTER_JR_DESTROY_EVERYTHING), loadSfx(SoundGlobals.SFX_MONSTER_JR_BEG_MERCY), loadSfx(SoundGlobals.SFX_MONSTER_JR_BARRICADES_A), loadSfx(SoundGlobals.SFX_MONSTER_JR_ATTACK_THE_TOWN), loadSfx(SoundGlobals.SFX_MONSTER_JR_ATTACK), loadSfx(SoundGlobals.SFX_MONSTER_JR_RUBBLE), loadSfx(SoundGlobals.SFX_MONSTER_JR_CRABS)] self.lastWaveMessages = [ loadSfx(SoundGlobals.SFX_MONSTER_JR_STAND)] self.goodBossMessages = [ ( PLocalizer.InvasionJollyRogerBoss1, loadSfx(SoundGlobals.SFX_MONSTER_JR_NO_TIME)), (PLocalizer.InvasionJollyRogerBoss3, loadSfx(SoundGlobals.SFX_MONSTER_JR_USELESS_SCABS)), (PLocalizer.InvasionJollyRogerBoss4, loadSfx(SoundGlobals.SFX_MONSTER_JR_FOOLS)), (PLocalizer.InvasionJollyRogerBoss5, loadSfx(SoundGlobals.SFX_MONSTER_JR_FOLLOW_ME_NOW))] self.badBossMessages = [ ( PLocalizer.InvasionJollyRogerBoss2, loadSfx(SoundGlobals.SFX_MONSTER_JR_NO_MERCY))] self.mainZoneMessages = [ ( PLocalizer.InvasionJollyRogerMainZone1, loadSfx(SoundGlobals.SFX_MONSTER_JR_FUNERAL_FIRE)), (PLocalizer.InvasionJollyRogerMainZone2, loadSfx(SoundGlobals.SFX_MONSTER_JR_YOUR_DESTINY))] self.winMessages = [ ( PLocalizer.InvasionJollyRogerEndPlayerWin4, loadSfx(SoundGlobals.SFX_MONSTER_JR_RETREAT))] self.loseMessages = [ ( PLocalizer.InvasionJollyRogerEndPlayerLose1, loadSfx(SoundGlobals.SFX_MONSTER_JR_VICTORY_MINE)), (PLocalizer.InvasionJollyRogerEndPlayerLose2, loadSfx(SoundGlobals.SFX_MONSTER_JR_NEXT_CONQUEST)), (PLocalizer.InvasionJollyRogerEndPlayerLose3, loadSfx(SoundGlobals.SFX_MONSTER_JR_NEXT_TARGET))] else: self.goodBossMessages = [ ( PLocalizer.InvasionJollyRogerBoss1, None), (PLocalizer.InvasionJollyRogerBoss3, None), (PLocalizer.InvasionJollyRogerBoss4, None), (PLocalizer.InvasionJollyRogerBoss5, None)] self.badBossMessages = [ ( PLocalizer.InvasionJollyRogerBoss2, None)] self.mainZoneMessages = [ ( PLocalizer.InvasionJollyRogerMainZone1, None), (PLocalizer.InvasionJollyRogerMainZone2, None)] self.winMessages = [ ( PLocalizer.InvasionJollyRogerEndPlayerWin4, None)] self.loseMessages = [ ( PLocalizer.InvasionJollyRogerEndPlayerLose1, None), (PLocalizer.InvasionJollyRogerEndPlayerLose2, None), (PLocalizer.InvasionJollyRogerEndPlayerLose3, None)] return None def disable(self): DistributedInvasionObject.DistributedInvasionObject.disable(self) def delete(self): DistributedInvasionObject.DistributedInvasionObject.delete(self) def spawnShip(self, shipClass, startPosHpr, midPosHpr, endPosHpr): self.shipNode = self.parentObj.attachNewNode('invasionShipNode') self.invasionShip = base.shipFactory.getShip(shipClass, ShipGlobals.Styles.Undead, 0) self.invasionShip.setOwner(self.shipNode) startPos = (startPosHpr[0], startPosHpr[1], startPosHpr[2]) startHpr = (startPosHpr[3], startPosHpr[4], startPosHpr[5]) midPos = (midPosHpr[0], midPosHpr[1], midPosHpr[2]) midHpr = (midPosHpr[3], midPosHpr[4], midPosHpr[5]) self.endPos = (endPosHpr[0], endPosHpr[1], endPosHpr[2]) self.shipNode.setPos(startPos) self.shipNode.setHpr(startHpr) self.invasionShip.modelRoot.setColorScale(0, 0, 0, 0) self.invasionShip.modelRoot.setTransparency(1) self.invasionShip.modelRoot.hide() self.shipShowingIval = Parallel(self.startLightingEffects(startPos), Sequence(Wait(8.5), Func(self.invasionShip.modelRoot.show)), Sequence(Wait(8.5), Func(self.startDarkFog, startPos)), Sequence(Wait(10.0), Func(self.invasionShip.playStormEffect), Func(self.invasionShip.fadeIn)), Sequence(Wait(10.0), LerpPosInterval(self.shipNode, 18.0, midPos, blendType='easeOut')), Sequence(Wait(15.0), Func(self.stopDarkFog)), Sequence(Wait(28.0), Func(self.startMainFog)), Sequence(Wait(28.0), Func(base.musicMgr.requestFadeOut, SoundGlobals.MUSIC_TORMENTA)), Sequence(Wait(28.0), LerpHprInterval(self.shipNode, 10.0, midHpr, blendType='easeInOut')), Sequence(Wait(36.0), Func(base.musicMgr.request, SoundGlobals.MUSIC_TORMENTA_COMBAT, looping=True))) self.shipShowingIval.start() def placeShip(self, shipClass, midPosHpr, endPosHpr): if not self.invasionShip: self.shipNode = self.parentObj.attachNewNode('invasionShipNode') self.invasionShip = base.shipFactory.getShip(shipClass, ShipGlobals.Styles.Undead, 0) self.invasionShip.setOwner(self.shipNode) midPos = (midPosHpr[0], midPosHpr[1], midPosHpr[2]) midHpr = (midPosHpr[3], midPosHpr[4], midPosHpr[5]) self.endPos = (endPosHpr[0], endPosHpr[1], endPosHpr[2]) self.invasionShip.playStormEffect() self.shipNode.setPos(midPos) self.shipNode.setHpr(midHpr) base.musicMgr.requestFadeOut(SoundGlobals.MUSIC_TORMENTA) base.musicMgr.request(SoundGlobals.MUSIC_TORMENTA_COMBAT, looping=True) self.startMainFog(False) def hideShip(self): self.shipHidingIval = Parallel(Sequence(Wait(0.5), LerpPosInterval(self.shipNode, 18.0, self.endPos, blendType='easeIn')), Sequence(Wait(0.5), Func(self.stopMainFog)), Sequence(Wait(13.5), Func(self.startDarkFog, self.endPos)), Sequence(Wait(16.5), Func(self.invasionShip.fadeOut), Func(self.invasionShip.stopStormEffect)), Sequence(Wait(18.5), Func(self.invasionShip.modelRoot.hide)), Sequence(Wait(19.0), Func(self.stopDarkFog))) self.shipHidingIval.start() def updateBrigadeText(self): if self.brigadeText and self.parentObj.minimapArea: self.brigadeText.destroy() self.brigadeText = None elif not self.brigadeText and not self.parentObj.minimapArea and self.parentObj.minimap: self.brigadeText = DirectLabel(parent=self.parentObj.minimap.getOverlayNode(), relief=None, text=PLocalizer.InvasionJollyRogerBrigadeUpdate % (self.currentPhase, self.totalPhases - self.currentPhase), text_align=TextNode.ALeft, text_fg=PiratesGuiGlobals.TextFG2, text_font=PiratesGlobals.getPirateOutlineFont(), text_shadow=PiratesGuiGlobals.TextShadow, textMayChange=1, scale=60, pos=(-800, -200, 0), hpr=(0, -90, 0)) return
0
0.654591
1
0.654591
game-dev
MEDIA
0.820464
game-dev
0.714707
1
0.714707
thomasmarsh/ODE
37,788
ode/src/collision_trimesh_ccylinder.cpp
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ /* * Triangle-Capsule(Capsule) collider by Alen Ladavac * Ported to ODE by Nguyen Binh */ // NOTES from Nguyen Binh // 14 Apr : Seem to be robust // There is a problem when you use original Step and set contact friction // surface.mu = dInfinity; // More description : // When I dropped Capsule over the bunny ears, it seems to stuck // there for a while. I think the cause is when you set surface.mu = dInfinity; // the friction force is too high so it just hang the capsule there. // So the good cure for this is to set mu = around 1.5 (in my case) // For StepFast1, this become as solid as rock : StepFast1 just approximate // friction force. // NOTES from Croteam's Alen //As a side note... there are some extra contacts that can be generated //on the edge between two triangles, and if the capsule penetrates deeply into //the triangle (usually happens with large mass or low FPS), some such //contacts can in some cases push the capsule away from the edge instead of //away from the two triangles. This shows up as capsule slowing down a bit //when hitting an edge while sliding along a flat tesselated grid of //triangles. This is only if capsule is standing upwards. //Same thing can appear whenever a smooth object (e.g sphere) hits such an //edge, and it needs to be solved as a special case probably. This is a //problem we are looking forward to address soon. #include <ode/collision.h> #include <ode/rotation.h> #include "config.h" #include "matrix.h" #include "odemath.h" #include "collision_util.h" #include "collision_trimesh_internal.h" #include "util.h" #if dTRIMESH_ENABLED // OPCODE version #if dTRIMESH_OPCODE // largest number, double or float #if defined(dSINGLE) #define MAX_REAL FLT_MAX #define MIN_REAL (-FLT_MAX) #else #define MAX_REAL DBL_MAX #define MIN_REAL (-DBL_MAX) #endif // To optimize before send contacts to dynamic part #define OPTIMIZE_CONTACTS 1 // dVector3 // r=a-b #define SUBTRACT(a,b,r) dSubtractVectors3(r, a, b) // dVector3 // a=b #define SET(a,b) dCopyVector3(a, b) // dMatrix3 // a=b #define SETM(a,b) dCopyMatrix4x4(a, b) // dVector3 // r=a+b #define ADD(a,b,r) dAddVectors3(r, a, b) // dMatrix3, int, dVector3 // v=column a from m #define GETCOL(m,a,v) dGetMatrixColumn3(v, m, a) // dVector4, dVector3 // distance between plane p and point v #define POINTDISTANCE(p,v) dPointPlaneDistance(v, p) // dVector4, dVector3, dReal // construct plane from normal and d #define CONSTRUCTPLANE(plane,normal,d) dConstructPlane(normal, d, plane) // dVector3 // length of vector a #define LENGTHOF(a) dCalcVectorLength3(a) static inline dReal _length2OfVector3(dVector3 v) { return dCalcVectorLengthSquare3(v); } // Local contacts data typedef struct _sLocalContactData { dVector3 vPos; dVector3 vNormal; dReal fDepth; int triIndex; int nFlags; // 0 = filtered out, 1 = OK }sLocalContactData; struct sTrimeshCapsuleColliderData { sTrimeshCapsuleColliderData(): m_gLocalContacts(NULL), m_ctContacts(0) { memset(m_vN, 0, sizeof(dVector3)); } void SetupInitialContext(dxTriMesh *TriMesh, dxGeom *Capsule, int flags, int skip); int TestCollisionForSingleTriangle(int ctContacts0, int Triint, dVector3 dv[3], uint8 flags, bool &bOutFinishSearching); #if OPTIMIZE_CONTACTS void _OptimizeLocalContacts(); #endif int _ProcessLocalContacts(dContactGeom *contact, dxTriMesh *TriMesh, dxGeom *Capsule); static BOOL _cldClipEdgeToPlane(dVector3 &vEpnt0, dVector3 &vEpnt1, const dVector4& plPlane); BOOL _cldTestAxis(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2, dVector3 vAxis, int iAxis, BOOL bNoFlip = FALSE); BOOL _cldTestSeparatingAxesOfCapsule(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2, uint8 flags); void _cldTestOneTriangleVSCapsule(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2, uint8 flags); sLocalContactData *m_gLocalContacts; unsigned int m_ctContacts; // capsule data // real time data dMatrix3 m_mCapsuleRotation; dVector3 m_vCapsulePosition; dVector3 m_vCapsuleAxis; // static data dReal m_vCapsuleRadius; dReal m_fCapsuleSize; // mesh data // dMatrix4 mHullDstPl; dMatrix3 m_mTriMeshRot; dVector3 m_vTriMeshPos; dVector3 m_vE0, m_vE1, m_vE2; // global collider data dVector3 m_vNormal; dReal m_fBestDepth; dReal m_fBestCenter; dReal m_fBestrt; int m_iBestAxis; dVector3 m_vN; dVector3 m_vV0; dVector3 m_vV1; dVector3 m_vV2; // ODE contact's specific unsigned int m_iFlags; int m_iStride; }; // Capsule lie on axis number 3 = (Z axis) static const int nCAPSULE_AXIS = 2; #if OPTIMIZE_CONTACTS // Use to classify contacts to be "near" in position static const dReal fSameContactPositionEpsilon = REAL(0.0001); // 1e-4 // Use to classify contacts to be "near" in normal direction static const dReal fSameContactNormalEpsilon = REAL(0.0001); // 1e-4 // If this two contact can be classified as "near" inline int _IsNearContacts(sLocalContactData& c1,sLocalContactData& c2) { int bPosNear = 0; int bSameDir = 0; dVector3 vDiff; // First check if they are "near" in position SUBTRACT(c1.vPos,c2.vPos,vDiff); if ( (dFabs(vDiff[0]) < fSameContactPositionEpsilon) &&(dFabs(vDiff[1]) < fSameContactPositionEpsilon) &&(dFabs(vDiff[2]) < fSameContactPositionEpsilon)) { bPosNear = 1; } // Second check if they are "near" in normal direction SUBTRACT(c1.vNormal,c2.vNormal,vDiff); if ( (dFabs(vDiff[0]) < fSameContactNormalEpsilon) &&(dFabs(vDiff[1]) < fSameContactNormalEpsilon) &&(dFabs(vDiff[2]) < fSameContactNormalEpsilon) ) { bSameDir = 1; } // Will be "near" if position and normal direction are "near" return (bPosNear && bSameDir); } inline int _IsBetter(sLocalContactData& c1,sLocalContactData& c2) { // The not better will be throw away // You can change the selection criteria here return (c1.fDepth > c2.fDepth); } // iterate through gLocalContacts and filtered out "near contact" void sTrimeshCapsuleColliderData::_OptimizeLocalContacts() { int nContacts = m_ctContacts; for (int i = 0; i < nContacts-1; i++) { for (int j = i+1; j < nContacts; j++) { if (_IsNearContacts(m_gLocalContacts[i],m_gLocalContacts[j])) { // If they are seem to be the samed then filtered // out the least penetrate one if (_IsBetter(m_gLocalContacts[j],m_gLocalContacts[i])) { m_gLocalContacts[i].nFlags = 0; // filtered 1st contact } else { m_gLocalContacts[j].nFlags = 0; // filtered 2nd contact } // NOTE // There is other way is to add two depth together but // it not work so well. Why??? } } } } #endif // OPTIMIZE_CONTACTS int sTrimeshCapsuleColliderData::_ProcessLocalContacts(dContactGeom *contact, dxTriMesh *TriMesh, dxGeom *Capsule) { #if OPTIMIZE_CONTACTS if (m_ctContacts > 1 && !(m_iFlags & CONTACTS_UNIMPORTANT)) { // Can be optimized... _OptimizeLocalContacts(); } #endif unsigned int iContact = 0; dContactGeom* Contact = 0; unsigned int nFinalContact = 0; for (iContact = 0; iContact < m_ctContacts; iContact ++) { // Ensure that we haven't created too many contacts if( nFinalContact >= (m_iFlags & NUMC_MASK)) { break; } if (1 == m_gLocalContacts[iContact].nFlags) { Contact = SAFECONTACT(m_iFlags, contact, nFinalContact, m_iStride); Contact->depth = m_gLocalContacts[iContact].fDepth; SET(Contact->normal,m_gLocalContacts[iContact].vNormal); SET(Contact->pos,m_gLocalContacts[iContact].vPos); Contact->g1 = TriMesh; Contact->g2 = Capsule; Contact->side1 = m_gLocalContacts[iContact].triIndex; Contact->side2 = -1; nFinalContact++; } } // debug //if (nFinalContact != m_ctContacts) //{ // printf("[Info] %d contacts generated,%d filtered.\n",m_ctContacts,m_ctContacts-nFinalContact); //} return nFinalContact; } BOOL sTrimeshCapsuleColliderData::_cldClipEdgeToPlane( dVector3 &vEpnt0, dVector3 &vEpnt1, const dVector4& plPlane) { // calculate distance of edge points to plane dReal fDistance0 = POINTDISTANCE( plPlane, vEpnt0 ); dReal fDistance1 = POINTDISTANCE( plPlane, vEpnt1 ); // if both points are behind the plane if ( fDistance0 < 0 && fDistance1 < 0 ) { // do nothing return FALSE; // if both points in front of the plane } else if ( fDistance0 > 0 && fDistance1 > 0 ) { // accept them return TRUE; // if we have edge/plane intersection } else if ((fDistance0 > 0 && fDistance1 < 0) || ( fDistance0 < 0 && fDistance1 > 0)) { // find intersection point of edge and plane dVector3 vIntersectionPoint; vIntersectionPoint[0]= vEpnt0[0]-(vEpnt0[0]-vEpnt1[0])*fDistance0/(fDistance0-fDistance1); vIntersectionPoint[1]= vEpnt0[1]-(vEpnt0[1]-vEpnt1[1])*fDistance0/(fDistance0-fDistance1); vIntersectionPoint[2]= vEpnt0[2]-(vEpnt0[2]-vEpnt1[2])*fDistance0/(fDistance0-fDistance1); // clamp correct edge to intersection point if ( fDistance0 < 0 ) { SET(vEpnt0,vIntersectionPoint); } else { SET(vEpnt1,vIntersectionPoint); } return TRUE; } return TRUE; } BOOL sTrimeshCapsuleColliderData::_cldTestAxis( const dVector3 &/*v0*/, const dVector3 &/*v1*/, const dVector3 &/*v2*/, dVector3 vAxis, int iAxis, BOOL bNoFlip/* = FALSE*/) { // calculate length of separating axis vector dReal fL = LENGTHOF(vAxis); // if not long enough // TODO : dReal epsilon please if ( fL < REAL(1e-5) ) { // do nothing //iLastOutAxis = 0; return TRUE; } // otherwise normalize it dNormalize3(vAxis); // project capsule on vAxis dReal frc = dFabs(dCalcVectorDot3(m_vCapsuleAxis,vAxis))*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius) + m_vCapsuleRadius; // project triangle on vAxis dReal afv[3]; afv[0] = dCalcVectorDot3(m_vV0, vAxis); afv[1] = dCalcVectorDot3(m_vV1, vAxis); afv[2] = dCalcVectorDot3(m_vV2, vAxis); dReal fMin = MAX_REAL; dReal fMax = MIN_REAL; // for each vertex for(int i=0; i<3; i++) { // find minimum if (afv[i]<fMin) { fMin = afv[i]; } // find maximum if (afv[i]>fMax) { fMax = afv[i]; } } // find triangle's center of interval on axis dReal fCenter = (fMin+fMax)*REAL(0.5); // calculate triangles half interval dReal fTriangleRadius = (fMax-fMin)*REAL(0.5); // if they do not overlap, if (dFabs(fCenter) > ( frc + fTriangleRadius )) { // exit, we have no intersection return FALSE; } // calculate depth dReal fDepth = dFabs(fCenter) - (frc+fTriangleRadius); // if greater then best found so far if ( fDepth > m_fBestDepth ) { // remember depth m_fBestDepth = fDepth; m_fBestCenter = fCenter; m_fBestrt = fTriangleRadius; m_vNormal[0] = vAxis[0]; m_vNormal[1] = vAxis[1]; m_vNormal[2] = vAxis[2]; m_iBestAxis = iAxis; // flip normal if interval is wrong faced if (fCenter<0 && !bNoFlip) { m_vNormal[0] = -m_vNormal[0]; m_vNormal[1] = -m_vNormal[1]; m_vNormal[2] = -m_vNormal[2]; m_fBestCenter = -fCenter; } } return TRUE; } // helper for less key strokes inline void _CalculateAxis(const dVector3& v1, const dVector3& v2, const dVector3& v3, const dVector3& v4, dVector3& r) { dVector3 t1; dVector3 t2; SUBTRACT(v1,v2,t1); dCalcVectorCross3(t2,t1,v3); dCalcVectorCross3(r,t2,v4); } BOOL sTrimeshCapsuleColliderData::_cldTestSeparatingAxesOfCapsule( const dVector3 &v0, const dVector3 &v1, const dVector3 &v2, uint8 flags) { // calculate caps centers in absolute space dVector3 vCp0; vCp0[0] = m_vCapsulePosition[0] + m_vCapsuleAxis[0]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCp0[1] = m_vCapsulePosition[1] + m_vCapsuleAxis[1]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCp0[2] = m_vCapsulePosition[2] + m_vCapsuleAxis[2]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); dVector3 vCp1; vCp1[0] = m_vCapsulePosition[0] - m_vCapsuleAxis[0]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCp1[1] = m_vCapsulePosition[1] - m_vCapsuleAxis[1]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCp1[2] = m_vCapsulePosition[2] - m_vCapsuleAxis[2]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); // reset best axis m_iBestAxis = 0; // reset best depth m_fBestDepth = -MAX_REAL; // reset separating axis vector dVector3 vAxis = {REAL(0.0),REAL(0.0),REAL(0.0),REAL(0.0)}; // Epsilon value for checking axis vector length const dReal fEpsilon = 1e-6f; // Translate triangle to Cc cord. SUBTRACT(v0, m_vCapsulePosition, m_vV0); SUBTRACT(v1, m_vCapsulePosition, m_vV1); SUBTRACT(v2, m_vCapsulePosition, m_vV2); // We begin to test for 19 separating axis now // I wonder does it help if we employ the method like ISA-GJK??? // Or at least we should do experiment and find what axis will // be most likely to be separating axis to check it first. // Original // axis m_vN //vAxis = -m_vN; vAxis[0] = - m_vN[0]; vAxis[1] = - m_vN[1]; vAxis[2] = - m_vN[2]; if (!_cldTestAxis(v0, v1, v2, vAxis, 1, TRUE)) { return FALSE; } if (flags & dxTriMeshData::CUF_USE_FIRST_EDGE) { // axis CxE0 - Edge 0 dCalcVectorCross3(vAxis,m_vCapsuleAxis,m_vE0); //vAxis = dCalcVectorCross3( m_vCapsuleAxis cross vE0 ); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 2)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_EDGE) { // axis CxE1 - Edge 1 dCalcVectorCross3(vAxis,m_vCapsuleAxis,m_vE1); //vAxis = ( m_vCapsuleAxis cross m_vE1 ); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 3)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_EDGE) { // axis CxE2 - Edge 2 //vAxis = ( m_vCapsuleAxis cross m_vE2 ); dCalcVectorCross3(vAxis,m_vCapsuleAxis,m_vE2); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 4)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_FIRST_EDGE) { // first capsule point // axis ((Cp0-V0) x E0) x E0 _CalculateAxis(vCp0,v0,m_vE0,m_vE0,vAxis); // vAxis = ( ( vCp0-v0) cross vE0 ) cross vE0; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 5)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_EDGE) { // axis ((Cp0-V1) x E1) x E1 _CalculateAxis(vCp0,v1,m_vE1,m_vE1,vAxis); //vAxis = ( ( vCp0-v1) cross vE1 ) cross vE1; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 6)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_EDGE) { // axis ((Cp0-V2) x E2) x E2 _CalculateAxis(vCp0,v2,m_vE2,m_vE2,vAxis); //vAxis = ( ( vCp0-v2) cross vE2 ) cross vE2; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 7)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_FIRST_EDGE) { // second capsule point // axis ((Cp1-V0) x E0) x E0 _CalculateAxis(vCp1,v0,m_vE0,m_vE0,vAxis); //vAxis = ( ( vCp1-v0 ) cross vE0 ) cross vE0; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 8)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_EDGE) { // axis ((Cp1-V1) x E1) x E1 _CalculateAxis(vCp1,v1,m_vE1,m_vE1,vAxis); //vAxis = ( ( vCp1-v1 ) cross vE1 ) cross vE1; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 9)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_EDGE) { // axis ((Cp1-V2) x E2) x E2 _CalculateAxis(vCp1,v2,m_vE2,m_vE2,vAxis); //vAxis = ( ( vCp1-v2 ) cross vE2 ) cross vE2; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 10)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_FIRST_VERTEX) { // first vertex on triangle // axis ((V0-Cp0) x C) x C _CalculateAxis(v0,vCp0,m_vCapsuleAxis,m_vCapsuleAxis,vAxis); //vAxis = ( ( v0-vCp0 ) cross m_vCapsuleAxis ) cross m_vCapsuleAxis; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 11)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_VERTEX) { // second vertex on triangle // axis ((V1-Cp0) x C) x C _CalculateAxis(v1,vCp0,m_vCapsuleAxis,m_vCapsuleAxis,vAxis); //vAxis = ( ( v1-vCp0 ) cross vCapsuleAxis ) cross vCapsuleAxis; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 12)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_VERTEX) { // third vertex on triangle // axis ((V2-Cp0) x C) x C _CalculateAxis(v2,vCp0,m_vCapsuleAxis,m_vCapsuleAxis,vAxis); //vAxis = ( ( v2-vCp0 ) cross vCapsuleAxis ) cross vCapsuleAxis; if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 13)) { return FALSE; } } } // Test as separating axes direction vectors between each triangle // edge and each capsule's cap center if (flags & dxTriMeshData::CUF_USE_FIRST_VERTEX) { // first triangle vertex and first capsule point //vAxis = v0 - vCp0; SUBTRACT(v0,vCp0,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 14)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_VERTEX) { // second triangle vertex and first capsule point //vAxis = v1 - vCp0; SUBTRACT(v1,vCp0,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 15)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_VERTEX) { // third triangle vertex and first capsule point //vAxis = v2 - vCp0; SUBTRACT(v2,vCp0,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 16)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_FIRST_VERTEX) { // first triangle vertex and second capsule point //vAxis = v0 - vCp1; SUBTRACT(v0,vCp1,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 17)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_SECOND_VERTEX) { // second triangle vertex and second capsule point //vAxis = v1 - vCp1; SUBTRACT(v1,vCp1,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 18)) { return FALSE; } } } if (flags & dxTriMeshData::CUF_USE_THIRD_VERTEX) { // third triangle vertex and second capsule point //vAxis = v2 - vCp1; SUBTRACT(v2,vCp1,vAxis); if (_length2OfVector3( vAxis ) > fEpsilon) { if (!_cldTestAxis(v0, v1, v2, vAxis, 19)) { return FALSE; } } } return TRUE; } // test one mesh triangle on intersection with capsule void sTrimeshCapsuleColliderData::_cldTestOneTriangleVSCapsule( const dVector3 &v0, const dVector3 &v1, const dVector3 &v2, uint8 flags) { // calculate edges SUBTRACT(v1,v0,m_vE0); SUBTRACT(v2,v1,m_vE1); SUBTRACT(v0,v2,m_vE2); dVector3 _minus_vE0; SUBTRACT(v0,v1,_minus_vE0); // calculate poly normal dCalcVectorCross3(m_vN,m_vE1,_minus_vE0); // Even though all triangles might be initially valid, // a triangle may degenerate into a segment after applying // space transformation. if (!dSafeNormalize3(m_vN)) { return; } // create plane from triangle dReal plDistance = -dCalcVectorDot3(v0,m_vN); dVector4 plTrianglePlane; CONSTRUCTPLANE(plTrianglePlane,m_vN,plDistance); // calculate capsule distance to plane dReal fDistanceCapsuleCenterToPlane = POINTDISTANCE(plTrianglePlane,m_vCapsulePosition); // Capsule must be over positive side of triangle if (fDistanceCapsuleCenterToPlane < 0 /* && !bDoubleSided*/) { // if not don't generate contacts return; } dVector3 vPnt0, vPnt1, vPnt2; SET (vPnt0,v0); if (fDistanceCapsuleCenterToPlane < 0) { SET (vPnt1,v2); SET (vPnt2,v1); } else { SET (vPnt1,v1); SET (vPnt2,v2); } // do intersection test and find best separating axis if (!_cldTestSeparatingAxesOfCapsule(vPnt0, vPnt1, vPnt2, flags)) { // if not found do nothing return; } // if best separation axis is not found if (m_iBestAxis == 0 ) { // this should not happen (we should already exit in that case) dIASSERT(FALSE); // do nothing return; } // calculate caps centers in absolute space dVector3 vCposTrans; vCposTrans[0] = m_vCapsulePosition[0] + m_vNormal[0]*m_vCapsuleRadius; vCposTrans[1] = m_vCapsulePosition[1] + m_vNormal[1]*m_vCapsuleRadius; vCposTrans[2] = m_vCapsulePosition[2] + m_vNormal[2]*m_vCapsuleRadius; dVector3 vCEdgePoint0; vCEdgePoint0[0] = vCposTrans[0] + m_vCapsuleAxis[0]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCEdgePoint0[1] = vCposTrans[1] + m_vCapsuleAxis[1]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCEdgePoint0[2] = vCposTrans[2] + m_vCapsuleAxis[2]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); dVector3 vCEdgePoint1; vCEdgePoint1[0] = vCposTrans[0] - m_vCapsuleAxis[0]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCEdgePoint1[1] = vCposTrans[1] - m_vCapsuleAxis[1]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); vCEdgePoint1[2] = vCposTrans[2] - m_vCapsuleAxis[2]*(m_fCapsuleSize*REAL(0.5)-m_vCapsuleRadius); // transform capsule edge points into triangle space vCEdgePoint0[0] -= vPnt0[0]; vCEdgePoint0[1] -= vPnt0[1]; vCEdgePoint0[2] -= vPnt0[2]; vCEdgePoint1[0] -= vPnt0[0]; vCEdgePoint1[1] -= vPnt0[1]; vCEdgePoint1[2] -= vPnt0[2]; dVector4 plPlane; dVector3 _minus_vN; _minus_vN[0] = -m_vN[0]; _minus_vN[1] = -m_vN[1]; _minus_vN[2] = -m_vN[2]; // triangle plane CONSTRUCTPLANE(plPlane,_minus_vN,0); //plPlane = Plane4f( -m_vN, 0); if (!_cldClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane )) { return; } // plane with edge 0 dVector3 vTemp; dCalcVectorCross3(vTemp,m_vN,m_vE0); CONSTRUCTPLANE(plPlane, vTemp, REAL(1e-5)); if (!_cldClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane )) { return; } dCalcVectorCross3(vTemp,m_vN,m_vE1); CONSTRUCTPLANE(plPlane, vTemp, -(dCalcVectorDot3(m_vE0,vTemp)-REAL(1e-5))); if (!_cldClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane )) { return; } dCalcVectorCross3(vTemp,m_vN,m_vE2); CONSTRUCTPLANE(plPlane, vTemp, REAL(1e-5)); if (!_cldClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane )) { return; } // return capsule edge points into absolute space vCEdgePoint0[0] += vPnt0[0]; vCEdgePoint0[1] += vPnt0[1]; vCEdgePoint0[2] += vPnt0[2]; vCEdgePoint1[0] += vPnt0[0]; vCEdgePoint1[1] += vPnt0[1]; vCEdgePoint1[2] += vPnt0[2]; // calculate depths for both contact points SUBTRACT(vCEdgePoint0,m_vCapsulePosition,vTemp); dReal fDepth0 = dCalcVectorDot3(vTemp,m_vNormal) - (m_fBestCenter-m_fBestrt); SUBTRACT(vCEdgePoint1,m_vCapsulePosition,vTemp); dReal fDepth1 = dCalcVectorDot3(vTemp,m_vNormal) - (m_fBestCenter-m_fBestrt); // clamp depths to zero if (fDepth0 < 0) { fDepth0 = 0.0f; } if (fDepth1 < 0 ) { fDepth1 = 0.0f; } // Cached contacts's data // contact 0 dIASSERT(m_ctContacts < (m_iFlags & NUMC_MASK)); // Do not call function if there is no room to store result m_gLocalContacts[m_ctContacts].fDepth = fDepth0; SET(m_gLocalContacts[m_ctContacts].vNormal,m_vNormal); SET(m_gLocalContacts[m_ctContacts].vPos,vCEdgePoint0); m_gLocalContacts[m_ctContacts].nFlags = 1; m_ctContacts++; if (m_ctContacts < (m_iFlags & NUMC_MASK)) { // contact 1 m_gLocalContacts[m_ctContacts].fDepth = fDepth1; SET(m_gLocalContacts[m_ctContacts].vNormal,m_vNormal); SET(m_gLocalContacts[m_ctContacts].vPos,vCEdgePoint1); m_gLocalContacts[m_ctContacts].nFlags = 1; m_ctContacts++; } } void sTrimeshCapsuleColliderData::SetupInitialContext(dxTriMesh *TriMesh, dxGeom *Capsule, int flags, int skip) { const dMatrix3* pRot = (const dMatrix3*)dGeomGetRotation(Capsule); memcpy(m_mCapsuleRotation, pRot, sizeof(dMatrix3)); const dVector3* pDst = (const dVector3*)dGeomGetPosition(Capsule); memcpy(m_vCapsulePosition, pDst, sizeof(dVector3)); m_vCapsuleAxis[0] = m_mCapsuleRotation[0*4 + nCAPSULE_AXIS]; m_vCapsuleAxis[1] = m_mCapsuleRotation[1*4 + nCAPSULE_AXIS]; m_vCapsuleAxis[2] = m_mCapsuleRotation[2*4 + nCAPSULE_AXIS]; // Get size of Capsule dGeomCapsuleGetParams(Capsule, &m_vCapsuleRadius, &m_fCapsuleSize); m_fCapsuleSize += 2*m_vCapsuleRadius; const dMatrix3* pTriRot = (const dMatrix3*)dGeomGetRotation(TriMesh); memcpy(m_mTriMeshRot, pTriRot, sizeof(dMatrix3)); const dVector3* pTriPos = (const dVector3*)dGeomGetPosition(TriMesh); memcpy(m_vTriMeshPos, pTriPos, sizeof(dVector3)); // global info for contact creation m_iStride =skip; m_iFlags =flags; // reset contact counter m_ctContacts = 0; // reset best depth m_fBestDepth = - MAX_REAL; m_fBestCenter = 0; m_fBestrt = 0; // reset collision normal m_vNormal[0] = REAL(0.0); m_vNormal[1] = REAL(0.0); m_vNormal[2] = REAL(0.0); } int sTrimeshCapsuleColliderData::TestCollisionForSingleTriangle(int ctContacts0, int Triint, dVector3 dv[3], uint8 flags, bool &bOutFinishSearching) { // test this triangle _cldTestOneTriangleVSCapsule(dv[0],dv[1],dv[2], flags); // fill-in tri index for generated contacts for (; ctContacts0 < (int)m_ctContacts; ctContacts0++) m_gLocalContacts[ctContacts0].triIndex = Triint; // Putting "break" at the end of loop prevents unnecessary checks on first pass and "continue" bOutFinishSearching = (m_ctContacts >= (m_iFlags & NUMC_MASK)); return ctContacts0; } static void dQueryCCTLPotentialCollisionTriangles(OBBCollider &Collider, const sTrimeshCapsuleColliderData &cData, dxTriMesh *TriMesh, dxGeom *Capsule, OBBCache &BoxCache) { Matrix4x4 MeshMatrix; const dVector3 vZeroVector3 = { REAL(0.0), }; MakeMatrix(vZeroVector3, cData.m_mTriMeshRot, MeshMatrix); const dVector3 &vCapsulePos = cData.m_vCapsulePosition; const dMatrix3 &mCapsuleRot = cData.m_mCapsuleRotation; dVector3 vCapsuleOffsetPos; dSubtractVectors3(vCapsuleOffsetPos, vCapsulePos, cData.m_vTriMeshPos); const dReal fCapsuleRadius = cData.m_vCapsuleRadius, fCapsuleHalfAxis = cData.m_fCapsuleSize * REAL(0.5); OBB obbCapsule; obbCapsule.mCenter.Set(vCapsuleOffsetPos[0], vCapsuleOffsetPos[1], vCapsuleOffsetPos[2]); obbCapsule.mExtents.Set( 0 == nCAPSULE_AXIS ? fCapsuleHalfAxis : fCapsuleRadius, 1 == nCAPSULE_AXIS ? fCapsuleHalfAxis : fCapsuleRadius, 2 == nCAPSULE_AXIS ? fCapsuleHalfAxis : fCapsuleRadius); obbCapsule.mRot.Set( mCapsuleRot[0], mCapsuleRot[4], mCapsuleRot[8], mCapsuleRot[1], mCapsuleRot[5], mCapsuleRot[9], mCapsuleRot[2], mCapsuleRot[6], mCapsuleRot[10]); // TC results if (TriMesh->getDoTC(dxTriMesh::TTC_BOX)) { dxTriMesh::BoxTC* BoxTC = 0; const int iBoxCacheSize = TriMesh->m_BoxTCCache.size(); for (int i = 0; i != iBoxCacheSize; i++){ if (TriMesh->m_BoxTCCache[i].Geom == Capsule){ BoxTC = &TriMesh->m_BoxTCCache[i]; break; } } if (!BoxTC){ TriMesh->m_BoxTCCache.push(dxTriMesh::BoxTC()); BoxTC = &TriMesh->m_BoxTCCache[TriMesh->m_BoxTCCache.size() - 1]; BoxTC->Geom = Capsule; BoxTC->FatCoeff = 1.0f; } // Intersect Collider.SetTemporalCoherence(true); Collider.Collide(*BoxTC, obbCapsule, TriMesh->retrieveMeshBVTreeRef(), null, &MeshMatrix); } else { Collider.SetTemporalCoherence(false); Collider.Collide(BoxCache, obbCapsule, TriMesh->retrieveMeshBVTreeRef(), null, &MeshMatrix); } } // capsule - trimesh by CroTeam // Ported by Nguyem Binh int dCollideCCTL(dxGeom *o1, dxGeom *o2, int flags, dContactGeom *contact, int skip) { dIASSERT (skip >= (int)sizeof(dContactGeom)); dIASSERT (o1->type == dTriMeshClass); dIASSERT (o2->type == dCapsuleClass); dIASSERT ((flags & NUMC_MASK) >= 1); int nContactCount = 0; dxTriMesh *TriMesh = (dxTriMesh*)o1; dxGeom *Capsule = o2; sTrimeshCapsuleColliderData cData; cData.SetupInitialContext(TriMesh, Capsule, flags, skip); const unsigned uiTLSKind = TriMesh->getParentSpaceTLSKind(); dIASSERT(uiTLSKind == Capsule->getParentSpaceTLSKind()); // The colliding spaces must use matching cleanup method TrimeshCollidersCache *pccColliderCache = GetTrimeshCollidersCache(uiTLSKind); OBBCollider& Collider = pccColliderCache->m_OBBCollider; // Will it be better to use LSS here? -> confirm Pierre. dQueryCCTLPotentialCollisionTriangles(Collider, cData, TriMesh, Capsule, pccColliderCache->m_DefaultBoxCache); if (Collider.GetContactStatus()) { // Retrieve data int TriCount = Collider.GetNbTouchedPrimitives(); if (TriCount != 0) { const int* Triangles = (const int*)Collider.GetTouchedPrimitives(); if (TriMesh->m_ArrayCallback != null) { TriMesh->m_ArrayCallback(TriMesh, Capsule, Triangles, TriCount); } // allocate buffer for local contacts on stack cData.m_gLocalContacts = (sLocalContactData*)dALLOCA16(sizeof(sLocalContactData)*(cData.m_iFlags & NUMC_MASK)); unsigned int ctContacts0 = cData.m_ctContacts; const uint8 *useFlags = TriMesh->retrieveMeshSmartUseFlags(); // loop through all intersecting triangles for (int i = 0; i < TriCount; i++) { const int Triint = Triangles[i]; if (!TriMesh->invokeCallback(Capsule, Triint)) continue; dVector3 dv[3]; TriMesh->fetchMeshTriangle(dv, Triint, cData.m_vTriMeshPos, cData.m_mTriMeshRot); uint8 flags = useFlags != NULL ? useFlags[Triint] : (uint8)dxTriMeshData::CUF__USE_ALL_COMPONENTS; bool bFinishSearching; ctContacts0 = cData.TestCollisionForSingleTriangle(ctContacts0, Triint, dv, flags, bFinishSearching); if (bFinishSearching) { break; } } if (cData.m_ctContacts != 0) { nContactCount = cData._ProcessLocalContacts(contact, TriMesh, Capsule); } } } return nContactCount; } #endif // GIMPACT version #if dTRIMESH_GIMPACT #include "gimpact_contact_export_helper.h" #include "gimpact_gim_contact_accessor.h" #define nCAPSULE_AXIS 2 // capsule - trimesh By francisco leon int dCollideCCTL(dxGeom *o1, dxGeom *o2, int flags, dContactGeom *contact, int skip) { dIASSERT (skip >= (int)sizeof(dContactGeom)); dIASSERT (o1->type == dTriMeshClass); dIASSERT (o2->type == dCapsuleClass); dIASSERT ((flags & NUMC_MASK) >= 1); dxTriMesh* TriMesh = (dxTriMesh*)o1; dxGeom* gCylinder = o2; //Get capsule params dMatrix3 mCapsuleRotation; dVector3 vCapsulePosition; dVector3 vCapsuleAxis; dReal vCapsuleRadius; dReal fCapsuleSize; dMatrix3* pRot = (dMatrix3*) dGeomGetRotation(gCylinder); memcpy(mCapsuleRotation,pRot,sizeof(dMatrix3)); dVector3* pDst = (dVector3*)dGeomGetPosition(gCylinder); memcpy(vCapsulePosition,pDst,sizeof(dVector3)); //Axis vCapsuleAxis[0] = mCapsuleRotation[0*4 + nCAPSULE_AXIS]; vCapsuleAxis[1] = mCapsuleRotation[1*4 + nCAPSULE_AXIS]; vCapsuleAxis[2] = mCapsuleRotation[2*4 + nCAPSULE_AXIS]; // Get size of CCylinder dGeomCCylinderGetParams(gCylinder,&vCapsuleRadius,&fCapsuleSize); fCapsuleSize*=0.5f; //Set Capsule params GIM_CAPSULE_DATA capsule; capsule.m_radius = vCapsuleRadius; VEC_SCALE(capsule.m_point1,fCapsuleSize,vCapsuleAxis); VEC_SUM(capsule.m_point1,vCapsulePosition,capsule.m_point1); VEC_SCALE(capsule.m_point2,-fCapsuleSize,vCapsuleAxis); VEC_SUM(capsule.m_point2,vCapsulePosition,capsule.m_point2); //Create contact list GDYNAMIC_ARRAY trimeshcontacts; GIM_CREATE_CONTACT_LIST(trimeshcontacts); //Collide trimeshe vs capsule gim_trimesh_capsule_collision(&TriMesh->m_collision_trimesh,&capsule,&trimeshcontacts); if(trimeshcontacts.m_size == 0) { GIM_DYNARRAY_DESTROY(trimeshcontacts); return 0; } GIM_CONTACT * ptrimeshcontacts = GIM_DYNARRAY_POINTER(GIM_CONTACT,trimeshcontacts); unsigned contactcount = trimeshcontacts.m_size; dxGIMCContactAccessor contactaccessor(ptrimeshcontacts, TriMesh, gCylinder, -1); contactcount = dxGImpactContactsExportHelper::ExportMaxDepthGImpactContacts(contactaccessor, contactcount, flags, contact, skip); GIM_DYNARRAY_DESTROY(trimeshcontacts); return (int)contactcount; } #endif // dTRIMESH_GIMPACT #endif // dTRIMESH_ENABLED
0
0.97629
1
0.97629
game-dev
MEDIA
0.451198
game-dev,scientific-computing
0.995919
1
0.995919
dotnet-state-machine/stateless
3,289
test/Stateless.Tests/IgnoredTriggerBehaviourFixture.cs
using System; using Xunit; namespace Stateless.Tests { public class IgnoredTriggerBehaviourFixture { [Fact] public void StateRemainsUnchanged() { var sm = new StateMachine<State, Trigger>(State.A); sm.Configure(State.A).Ignore(Trigger.X); sm.Fire(Trigger.X); Assert.Equal(State.A, sm.State); } [Fact] public void ExposesCorrectUnderlyingTrigger() { var ignored = new StateMachine<State, Trigger>.IgnoredTriggerBehaviour( Trigger.X, null); Assert.Equal(Trigger.X, ignored.Trigger); } private bool False(params object[] args) { return false; } [Fact] public void WhenGuardConditionFalse_IsGuardConditionMetIsFalse() { var ignored = new StateMachine<State, Trigger>.IgnoredTriggerBehaviour( Trigger.X, new StateMachine<State, Trigger>.TransitionGuard(False)); Assert.False(ignored.GuardConditionsMet()); } private bool True(params object[] args) { return true; } [Fact] public void WhenGuardConditionTrue_IsGuardConditionMetIsTrue() { var ignored = new StateMachine<State, Trigger>.IgnoredTriggerBehaviour( Trigger.X, new StateMachine<State, Trigger>.TransitionGuard(True)); Assert.True(ignored.GuardConditionsMet()); } [Fact] public void IgnoredTriggerMustBeIgnoredSync() { bool internalActionExecuted = false; var stateMachine = new StateMachine<State, Trigger>(State.B); stateMachine.Configure(State.A) .Permit(Trigger.X, State.C); stateMachine.Configure(State.B) .SubstateOf(State.A) .Ignore(Trigger.X); try { // >>> The following statement should not execute the internal action stateMachine.Fire(Trigger.X); } catch (NullReferenceException) { internalActionExecuted = true; } Assert.False(internalActionExecuted); } [Fact] public void IgnoreIfTrueTriggerMustBeIgnored() { var stateMachine = new StateMachine<State, Trigger>(State.B); stateMachine.Configure(State.A) .Permit(Trigger.X, State.C); stateMachine.Configure(State.B) .SubstateOf(State.A) .IgnoreIf(Trigger.X, () => true); stateMachine.Fire(Trigger.X); Assert.Equal(State.B, stateMachine.State); } [Fact] public void IgnoreIfFalseTriggerMustNotBeIgnored() { var stateMachine = new StateMachine<State, Trigger>(State.B); stateMachine.Configure(State.A) .Permit(Trigger.X, State.C); stateMachine.Configure(State.B) .SubstateOf(State.A) .IgnoreIf(Trigger.X, () => false); stateMachine.Fire(Trigger.X); Assert.Equal(State.C, stateMachine.State); } } }
0
0.808152
1
0.808152
game-dev
MEDIA
0.474455
game-dev,testing-qa
0.52501
1
0.52501
shagu/pfQuest
78,497
toolbox/extractor.lua
#!/usr/bin/lua -- depends on luasql -- map pngs with alpha channel generated with: -- `convert $file -transparent white -resize '100x100!' $file` local debugsql = { ["areatrigger"] = { "Using only client-data to find areatrigger locations" }, -- ["units"] = { "Iterate over all creatures using mangos data" }, ["units_faction"] = { "Using mangos and client-data to find unit faction" }, ["units_coords"] = { "Using mangos and client-data to find unit locations" }, ["units_coords_pool"] = { "Only applies to CMaNGOS(TBC) to find pooled unit locations" }, ["units_event"] = { "Using mangos data to find spawns from events" }, ["units_event_map_object"] = { "Using mangos data to determine map based on object requirements associated with event" }, ["units_event_spell"] = { "Using mangos data to find spells associated with spawn" }, ["units_event_spell_map_object"] = { "Using mangos data to determine map based on objects associated with spawn spells" }, ["units_event_spell_map_item"] = { "Using mangos data to determine map based on items associated with spawn spells" }, ["units_summon_fixed"] = { "Using mangos data to find units that summon others and use their map with fixed spawn positions" }, ["units_summon_unknown"] = { "Using mangos data to find units that summon others and use their coordinates as target spawn positions" }, -- ["objects"] = { "Iterate over all gameobjects using mangos data" }, ["objects_faction"] = { "Using mangos and client-data to find object faction" }, ["objects_coords"] = { "Using mangos and client-data to find unit locations" }, -- ["items"] = { "Iterate over all items using mangos data" }, ["items_container"] = { "Using mangos data to find items that are looted from other items" }, ["items_unit"] = { "Using mangos data to find units that drop an item" }, ["items_object"] = { "Using mangos data to find objects that drop an item" }, ["items_reference"] = { "Using mangos data to query for shared loot lists" }, ["items_vendor"] = { "Using mangos data to find vendors for items" }, ["items_vendortemplate"] = { "Using mangos data to find vendor templates of the item" }, -- ["refloot"] = { "Using mangos data to find shared loot lists" }, ["refloot_unit"] = { "Using mangos data to find units for shared loot" }, ["refloot_object"] = { "Using mangos data to find objects for shared loot" }, -- ["quests"] = { "Using mangos data to iterate over all quests" }, ["quests_events"] = { "Using mangos data to detect event quests" }, ["quests_eventscreature"] = { "Using mangos data to detect event quests based on creature" }, ["quests_eventsobjects"] = { "Using mangos data to detect event quests based on objects" }, ["quests_prequests"] = { "Using mangos data to detect pre-quests based on other quests next entries" }, ["quests_prequestchain"] = { "Using mangos data to detect quest-chains based on other quests next entries" }, ["quests_questspellobject"] = { "Using mangos data find objects associated with quest_template spell requirements" }, ["quests_credit"] = { "Only applies to CMaNGOS(TBC) to find units that give shared credit to the quest" }, ["quests_item"] = { "Using mangos data to scan through all items with spell requirements" }, ["quests_itemspell"] = { "Using mangos data to scan through spells that apply to the given item" }, ["quests_itemspellcreature"] = { "Using mangos data to find all creatures that are a spell target of the given item" }, ["quests_itemspellobject"] = { "Using mangos data to find all objects that are a spell target of the given item" }, ["quests_itemspellscript"] = { "Using mangos data to find all scripts that are a spell target of the given item" }, ["quests_itemobject"] = { "Using mangos database and client data to search for object that can be used via item" }, ["quests_itemcreature"] = { "Using mangos database and client data to search for creature that can be target of item" }, ["quests_areatrigger"] = { "Using mangos data to find associated areatriggers" }, ["quests_starterunit"] = { "Using mangos data to search for quest starter units" }, ["quests_starterobject"] = { "Using mangos data to search for quest starter objects" }, ["quests_starteritem"] = { "Using mangos data to search for quest starter items" }, ["quests_enderunit"] = { "Using mangos data to search for quest ender units" }, ["quests_enderobject"] = { "Using mangos data to search for quest ender objects" }, -- ["zones"] = { "Using client data to read zone data" }, -- ["minimap"] = { "Using client data to read minimap zoom levels" }, -- ["meta_rares"] = { "Using client and mangos data to find rare mobs" }, ["meta_npcs"] = { "Using client and mangos data to find npcs" }, ["meta_objects"] = { "Using client and mangos data to find objects" }, ["meta_openable"] = { "Using client and mangos data to find chests, herbs and mines" }, -- ["locales_unit"] = { "Using mangos data to find unit translations" }, ["locales_object"] = { "Using mangos data to find object translations" }, ["locales_item"] = { "Using mangos data to find item translations" }, ["locales_quest"] = { "Using mangos data to find quest translations" }, ["locales_profession"] = { "Using client and mangos data to find profession translations" }, ["locales_zone"] = { "Using client and mangos data to find zone translations" }, } -- limit all sql loops local limit = nil function debug(name) -- count sql debugs debugsql[name][2] = debugsql[name][2] or 0 debugsql[name][2] = debugsql[name][2] + 1 -- abort here when no debug limit is set if not limit then return nil end return debugsql[name][2] > limit or nil end function debug_statistics() for name, data in pairs(debugsql) do local count = data[2] or 0 if count == 0 then print("WARNING: \27[1m\27[31m" .. count .. "\27[0m \27[1m" .. name .. "\27[0m \27[2m-- " .. data[1] .. "\27[0m") end debugsql[name][2] = nil end end -- local associations local all_locales = { ["enUS"] = 0, ["koKR"] = 1, ["frFR"] = 2, ["deDE"] = 3, ["zhCN"] = 4, ["zhTW"] = 5, ["esES"] = 6, ["ruRU"] = 8, ["ptBR"] = 10, } local config = { -- known expansions and their config expansions = { { name = "vanilla", core = "vmangos", database = "vmangos", locales = all_locales, custom = false, }, { name = "tbc", core = "cmangos", database = "cmangos-tbc", locales = all_locales, custom = false, }, }, -- core-type database column glue tables -- every table column name that differs -- from cmangos should be listed here cores = { ["cmangos"] = setmetatable({}, { __index = function(tab,key) local value = tostring(key) rawset(tab,key,value) return value end }), ["vmangos"] = { ["Id"] = "entry", ["Entry"] = "entry", ["Faction"] = "faction", ["Name"] = "name", ["MinLevel"] = "level_min", ["MaxLevel"] = "level_max", ["Rank"] = "rank", ["RequiresSpellFocus"] = "requiresSpellFocus", ["dbscripts_on_event"] = "event_scripts", ["VendorTemplateId"] = "vendor_id", ["NpcFlags"] = "npc_flags", ["EffectTriggerSpell"] = "effectTriggerSpell", ["Map"] = "map_bound", ["startquest"] = "start_quest", ["targetEntry"] = "target_entry", }, } } if false then -- add turtle settings to expansions table.insert(config.expansions, { name = "turtle", core = "vmangos", database = "turtle", locales = { ["enUS"] = 0 }, custom = true, }) end do -- map lookup functions maps = {} package.path = './pngLua/?.lua;' .. package.path require("png") function isFile(name) if type(name)~="string" then return false end if not ( os.rename(name,name) and true or false ) then return false end local f = io.open(name) if not f then return false end f:close() return true end function isValidMap(map,x,y,expansion) local id = map..expansion -- load map if required if not maps[id] then local preferred = string.format("maps/%s/%s.png", expansion, map) local fallback = string.format("maps/%s.png", map) if isFile(preferred) then maps[id] = pngImage(preferred) elseif isFile(fallback) then maps[id] = pngImage(fallback) end end -- no mapfile means valid map if not maps[id] then return true end -- error handling if not maps[id].getPixel then return false end if x == 0 or y == 0 then return false end -- check pixel alpha local pixel = maps[id]:getPixel(x,y) if pixel and pixel.A and pixel.A > 0 then return true else return false end end end do -- helper functions function round(input, places) if not places then places = 0 end if type(input) == "number" and type(places) == "number" then local pow = 1 for i = 1, places do pow = pow * 10 end local result = math.floor(input * pow + 0.5) / pow return result == math.floor(result) and math.floor(result) or result end end function sanitize(str) str = string.gsub(str, "\\", "\\\\") str = string.gsub(str, "\"", "\\\"") str = string.gsub(str, "\'", "\\\'") str = string.gsub(str, "\r", "") str = string.gsub(str, "\n", "") return str end -- http://lua-users.org/wiki/SortedIteration function __genOrderedIndex( t ) local orderedIndex = {} for key in pairs(t) do table.insert( orderedIndex, key ) end table.sort( orderedIndex ) return orderedIndex end function orderedNext(t, state) local key = nil if state == nil then t.__orderedIndex = __genOrderedIndex( t ) key = t.__orderedIndex[1] else for i = 1,#t.__orderedIndex do if t.__orderedIndex[i] == state then key = t.__orderedIndex[i+1] end end end if key then return key, t[key] end t.__orderedIndex = nil return end function opairs(t) return orderedNext, t, nil end -- function tblsize(tbl) local count = 0 for _ in pairs(tbl) do count = count + 1 end return count end function smalltable(tbl) local size = tblsize(tbl) if size > 10 then return end if size < 1 then return end for i=1, size do if not tbl[i] then return end if type(tbl[i]) == "table" then return end end return true end function trealsize(tbl) local count = 0 for _ in pairs(tbl) do count = count + 1 end return count end local dupehashes = {} function removedupes(tbl) dupehashes = {} local output = {} -- [count] = { x, y, zone, respawn } for k, coords in pairs(tbl) do local hash = "" for k, v in pairs(coords) do hash = hash .. v end if not dupehashes[hash] then dupehashes[hash] = true table.insert(output, coords) end end return output end -- return true if the base table or any of its subtables -- has different values than the new table function isdiff(new, base) -- different types if type(new) ~= type(base) then return true end -- different values if type(new) ~= "table" then if new ~= base then return true end end -- recursive on tables if type(new) == "table" then for k, v in pairs(new) do local result = isdiff(new[k], base[k]) if result then return true end end end return nil end -- create a new table with only those indexes that are -- either different or non-existing in the base table function tablesubstract(new, base) local result = {} -- changed value for k, v in pairs(new) do if new[k] and ( not base or not base[k] ) then -- write new entries result[k] = new[k] elseif new[k] and base[k] and isdiff(new[k], base[k]) then -- write different entries result[k] = new[k] end end -- remove obsolete entries if base then for k, v in pairs(base) do if base[k] and not new[k] then result[k] = "_" end end end return result end function serialize(file, name, tbl, spacing, flat) local closehandle = type(file) == "string" local file = type(file) == "string" and io.open(file, "w") or file local spacing = spacing or "" if tblsize(tbl) == 0 then file:write(string.format("%s%s = {}%s\n", spacing, name, (spacing == "" and "" or ","))) else file:write(spacing .. name .. " = {\n") for k, v in opairs(tbl) do local prefix = "["..k.."]" if type(k) == "string" then prefix = "[\""..k.."\"]" end if type(v) == "table" and flat then file:write(" "..spacing..prefix .. " = {},\n") elseif type(v) == "table" and smalltable(v) then local init local line = spacing.." "..prefix.." = { " for _, v in pairs(v) do line = line .. (init and ", " or "") .. (type(v) == "string" and "\""..v.."\"" or v) if not init then init = true end end line = line .. " },\n" file:write(line) elseif type(v) == "table" then serialize(file, prefix, v, spacing .. " ") elseif type(v) == "string" then file:write(" "..spacing..prefix .. " = " .. "\"" .. v .. "\",\n") elseif type(v) == "number" then file:write(" "..spacing..prefix .. " = " .. v .. ",\n") end end file:write(spacing.."}" .. (not closehandle and "," or "") .. "\n") end if closehandle then file:close() end end end local pfDB = {} for id, settings in pairs(config.expansions) do print("Extracting: " .. settings.name) local expansion = settings.name local db = settings.database local core = settings.core local locales = settings.locales local C = config.cores[core] local idcolumns = core == "vmangos" and { "id", "id2", "id3", "id4" } or { "id" } local exp = expansion == "vanilla" and "" or "-"..expansion local data = "data".. exp do -- database connection luasql = require("luasql.mysql").mysql() mysql = luasql:connect(settings.database, "mangos", "mangos", "127.0.0.1") end do -- database query functions function GetAreaTriggerCoords(id) local areatrigger = {} local ret = {} local sql = [[ SELECT * FROM pfquest.AreaTrigger_]]..expansion..[[ LEFT JOIN pfquest.WorldMapArea_]]..expansion..[[ ON ( pfquest.WorldMapArea_]]..expansion..[[.mapID = pfquest.AreaTrigger_]]..expansion..[[.MapID AND pfquest.WorldMapArea_]]..expansion..[[.x_min < pfquest.AreaTrigger_]]..expansion..[[.X AND pfquest.WorldMapArea_]]..expansion..[[.x_max > pfquest.AreaTrigger_]]..expansion..[[.X AND pfquest.WorldMapArea_]]..expansion..[[.y_min < pfquest.AreaTrigger_]]..expansion..[[.Y AND pfquest.WorldMapArea_]]..expansion..[[.y_max > pfquest.AreaTrigger_]]..expansion..[[.Y AND pfquest.WorldMapArea_]]..expansion..[[.areatableID > 0) WHERE pfquest.AreaTrigger_]]..expansion..[[.ID = ]] .. id .. [[ ORDER BY areatableID ]] local query = mysql:execute(sql) while query:fetch(areatrigger, "a") do local zone = areatrigger.areatableID local x = areatrigger.X local y = areatrigger.Y local x_max = areatrigger.x_max local x_min = areatrigger.x_min local y_max = areatrigger.y_max local y_min = areatrigger.y_min local px, py = 0, 0 if x and y and x_min and y_min then px = round(100 - (y - y_min) / ((y_max - y_min)/100),1) py = round(100 - (x - x_min) / ((x_max - x_min)/100),1) if isValidMap(zone, round(px), round(py), expansion) then local coord = { px, py, tonumber(zone) } table.insert(ret, coord) end end end return ret end function GetCustomCoords(m,x,y) local worldmap = {} local ret = {} local sql = [[ SELECT * FROM pfquest.WorldMapArea_]]..expansion..[[ WHERE pfquest.WorldMapArea_]]..expansion..[[.mapID = ]] .. m .. [[ AND pfquest.WorldMapArea_]]..expansion..[[.x_min < ]] .. x .. [[ AND pfquest.WorldMapArea_]]..expansion..[[.x_max > ]] .. x .. [[ AND pfquest.WorldMapArea_]]..expansion..[[.y_min < ]] .. y .. [[ AND pfquest.WorldMapArea_]]..expansion..[[.y_max > ]] .. y .. [[ AND pfquest.WorldMapArea_]]..expansion..[[.areatableID > 0 ]] local query = mysql:execute(sql) while query:fetch(worldmap, "a") do local zone = worldmap.areatableID local x_max = worldmap.x_max local x_min = worldmap.x_min local y_max = worldmap.y_max local y_min = worldmap.y_min local px, py = 0, 0 if x and y and x_min and y_min then px = round(100 - (y - y_min) / ((y_max - y_min)/100),1) py = round(100 - (x - x_min) / ((x_max - x_min)/100),1) if isValidMap(zone, round(px), round(py), expansion) then local coord = { px, py, tonumber(zone), 0 } table.insert(ret, coord) end end end return ret end function GetCreatureCoordsPool(id) local creature = {} local ret = {} local sql = [[ SELECT * FROM creature, creature_spawn_entry, pfquest.WorldMapArea_]]..expansion..[[ WHERE creature_spawn_entry.entry = ]] .. id .. [[ AND creature.guid = creature_spawn_entry.guid AND ( pfquest.WorldMapArea_]]..expansion..[[.mapID = creature.map AND pfquest.WorldMapArea_]]..expansion..[[.x_min < creature.position_x AND pfquest.WorldMapArea_]]..expansion..[[.x_max > creature.position_x AND pfquest.WorldMapArea_]]..expansion..[[.y_min < creature.position_y AND pfquest.WorldMapArea_]]..expansion..[[.y_max > creature.position_y AND pfquest.WorldMapArea_]]..expansion..[[.areatableID > 0) ORDER BY areatableID, position_x, position_y, spawntimesecsmin ]] local query = mysql:execute(sql) while query:fetch(creature, "a") do local zone = creature.areatableID local x = creature.position_x local y = creature.position_y local x_max = creature.x_max local x_min = creature.x_min local y_max = creature.y_max local y_min = creature.y_min local px, py = 0, 0 if x and y and x_min and y_min then px = round(100 - (y - y_min) / ((y_max - y_min)/100),1) py = round(100 - (x - x_min) / ((x_max - x_min)/100),1) if isValidMap(zone, round(px), round(py), expansion) then local coord = { px, py, tonumber(zone), ( tonumber(creature.spawntimesecsmin) > 0 and tonumber(creature.spawntimesecsmin) or 0) } table.insert(ret, coord) end end end return ret end function GetCreatureCoords(id) local creature = {} local ret = {} for _, column in pairs(idcolumns) do local sql = [[ SELECT * FROM creature LEFT JOIN pfquest.WorldMapArea_]]..expansion..[[ ON ( pfquest.WorldMapArea_]]..expansion..[[.mapID = creature.map AND pfquest.WorldMapArea_]]..expansion..[[.x_min < creature.position_x AND pfquest.WorldMapArea_]]..expansion..[[.x_max > creature.position_x AND pfquest.WorldMapArea_]]..expansion..[[.y_min < creature.position_y AND pfquest.WorldMapArea_]]..expansion..[[.y_max > creature.position_y AND pfquest.WorldMapArea_]]..expansion..[[.areatableID > 0) WHERE creature.]] .. column .. [[ = ]] .. id .. [[ ORDER BY areatableID, position_x, position_y, spawntimesecsmin ]] local query = mysql:execute(sql) while query:fetch(creature, "a") do local zone = creature.areatableID local x = creature.position_x local y = creature.position_y local x_max = creature.x_max local x_min = creature.x_min local y_max = creature.y_max local y_min = creature.y_min local px, py = 0, 0 if x and y and x_min and y_min then px = round(100 - (y - y_min) / ((y_max - y_min)/100),1) py = round(100 - (x - x_min) / ((x_max - x_min)/100),1) if isValidMap(zone, round(px), round(py), expansion) then local coord = { px, py, tonumber(zone), ( tonumber(creature.spawntimesecsmin) > 0 and tonumber(creature.spawntimesecsmin) or 0) } table.insert(ret, coord) end end end end return ret end function GetGameObjectCoords(id) local gameobject = {} local ret = {} local sql = [[ SELECT * FROM gameobject LEFT JOIN pfquest.WorldMapArea_]]..expansion..[[ ON ( pfquest.WorldMapArea_]]..expansion..[[.mapID = gameobject.map AND pfquest.WorldMapArea_]]..expansion..[[.x_min < gameobject.position_x AND pfquest.WorldMapArea_]]..expansion..[[.x_max > gameobject.position_x AND pfquest.WorldMapArea_]]..expansion..[[.y_min < gameobject.position_y AND pfquest.WorldMapArea_]]..expansion..[[.y_max > gameobject.position_y AND pfquest.WorldMapArea_]]..expansion..[[.areatableID > 0) WHERE gameobject.id = ]] .. id .. [[ ORDER BY areatableID, position_x, position_y, spawntimesecsmin ]] local query = mysql:execute(sql) while query:fetch(gameobject, "a") do local zone = gameobject.areatableID local x = gameobject.position_x local y = gameobject.position_y local x_max = gameobject.x_max local x_min = gameobject.x_min local y_max = gameobject.y_max local y_min = gameobject.y_min local px, py = 0, 0 if x and y and x_min and y_min then px = round(100 - (y - y_min) / ((y_max - y_min)/100),1) py = round(100 - (x - x_min) / ((x_max - x_min)/100),1) if isValidMap(zone, round(px), round(py), expansion) then local coord = { px, py, tonumber(zone), ( tonumber(gameobject.spawntimesecsmin) > 0 and tonumber(gameobject.spawntimesecsmin) or 0) } table.insert(ret, coord) end end end return ret end end do -- areatrigger print("- loading areatrigger...") pfDB["areatrigger"] = pfDB["areatrigger"] or {} pfDB["areatrigger"][data] = {} -- iterate over all areatriggers local areatrigger = {} local query = mysql:execute('SELECT * FROM pfquest.AreaTrigger_'..expansion..' ORDER BY ID') while query:fetch(areatrigger, "a") do if debug("areatrigger") then break end local entry = tonumber(areatrigger.ID) pfDB["areatrigger"][data][entry] = {} do -- coordinates pfDB["areatrigger"][data][entry]["coords"] = {} for id, coords in pairs(GetAreaTriggerCoords(entry)) do local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["areatrigger"][data][entry]["coords"], { x, y, zone, respawn }) end end end end do -- units print("- loading units...") pfDB["units"] = pfDB["units"] or {} pfDB["units"][data] = {} -- iterate over all creatures local creature_template = {} local query = mysql:execute('SELECT * FROM creature_template GROUP BY creature_template.entry ORDER BY creature_template.entry') while query:fetch(creature_template, "a") do if debug("units") then break end local entry = tonumber(creature_template[C.Entry]) local name = creature_template[C.Name] local minlvl = creature_template[C.MinLevel] local maxlvl = creature_template[C.MaxLevel] local rnk = creature_template[C.Rank] local lvl = (minlvl == maxlvl) and minlvl or minlvl .. "-" .. maxlvl pfDB["units"][data][entry] = {} pfDB["units"][data][entry]["lvl"] = lvl if tonumber(rnk) > 0 then pfDB["units"][data][entry]["rnk"] = rnk end do -- detect faction local fac = "" local faction = {} local sql = [[ SELECT A, H FROM creature_template, pfquest.FactionTemplate_]]..expansion..[[ WHERE pfquest.FactionTemplate_]]..expansion..[[.factiontemplateID = creature_template.]] .. C.Faction .. [[ AND creature_template.]] .. C.Entry .. [[ = ]] .. creature_template[C.Entry] local query = mysql:execute(sql) while query:fetch(faction, "a") do if debug("units_faction") then break end local A, H = faction.A, faction.H if A == "1" and not string.find(fac, "A") then fac = fac .. "A" end if H == "1" and not string.find(fac, "H") then fac = fac .. "H" end end if fac ~= "" then pfDB["units"][data][entry]["fac"] = fac end end do -- coordinates pfDB["units"][data][entry]["coords"] = {} for id, coords in pairs(GetCreatureCoords(entry)) do local x, y, zone, respawn = table.unpack(coords) if debug("units_coords") then break end table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end if core ~= "vmangos" then for id, coords in pairs(GetCreatureCoordsPool(entry)) do local x, y, zone, respawn = table.unpack(coords) if debug("units_coords_pool") then break end table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end end -- search for Event summons (fixed position) -- [Gazban:2624, Maraudine Khan Guard:6069, Echeyakee:3475] local dbscripts_on_event = {} local query = mysql:execute('SELECT id as event, x as x, y as y FROM '..C.dbscripts_on_event..' WHERE command = 10 AND datalong = ' .. entry) while query:fetch(dbscripts_on_event, "a") do if debug("units_event") then break end local event = tonumber(dbscripts_on_event.event) local x = tonumber(dbscripts_on_event.x) local y = tonumber(dbscripts_on_event.y) local map = nil -- guess map based on gameobject relation -- [Gazban:2624] local map_object = {} local query = mysql:execute([[ SELECT map AS map FROM gameobject_template, gameobject WHERE gameobject_template.type = 10 AND gameobject_template.data2 = ]]..event..[[ AND gameobject.id = gameobject_template.entry GROUP BY gameobject.map ]]) while query:fetch(map_object, "a") do if debug("units_event_map_object") then break end map = map or tonumber(map_object.map) end -- guess map based on spell relation local spell_template = {} local query = mysql:execute([[ SELECT ]]..C.Id..[[ AS spell, ]]..C.RequiresSpellFocus..[[ AS focus FROM spell_template WHERE ( EffectMiscValue1 = ]]..event..[[ AND effect1 = 61 ) OR ( EffectMiscValue2 = ]]..event..[[ AND effect2 = 61 ) OR ( EffectMiscValue3 = ]]..event..[[ AND effect3 = 61 ) ]]) while query:fetch(spell_template, "a") do if debug("units_event_spell") then break end local spell = tonumber(spell_template.spell) local focus = tonumber(spell_template.focus) -- guess map based on gameobject target -- [Echeyakee:3475] local gameobject_template = {} local query = mysql:execute([[ SELECT map as map FROM gameobject_template, gameobject WHERE gameobject.id = gameobject_template.entry AND gameobject_template.data0 > 0 AND gameobject_template.type = 8 AND gameobject_template.data0 = ]]..focus..[[ GROUP BY map ]]) while query:fetch(gameobject_template, "a") do if debug("units_event_spell_map_object") then break end map = map or tonumber(gameobject_template.map) end -- guess map based on item map/area bond -- [Maraudine Khan Guard:6069] local item_template = {} local query = mysql:execute([[ SELECT ]]..C.Map..[[ as map FROM item_template WHERE spelltrigger_1 = 0 AND spellid_1 = ]]..spell..[[ GROUP BY map ]]) while query:fetch(item_template, "a") do if debug("units_event_spell_map_item") then break end -- Zul'Farrak Executioner Key is not bound to map. -- Ignoring its unlocking spell that spawns sandfuries. if spell == 10738 then break end map = map or tonumber(item_template.map) end end if map then -- in case we found a map, add the coordinates for id, coords in pairs(GetCustomCoords(map, x, y)) do local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end end end -- search for AI summons (fixed position) -- [Verog Derwisch:3395] local creature_ai_scripts = {} local query = mysql:execute(core == "vmangos" and [[ SELECT creature.map AS map, x AS x, y AS y FROM creature_ai_scripts, creature_ai_events, creature WHERE creature.id = creature_ai_events.creature_id AND creature_ai_scripts.command = 10 AND creature_ai_scripts.id = creature_ai_events.id AND creature_ai_scripts.datalong = ]]..entry..[[ AND x != 0 AND y != 0 GROUP BY map ]] or [[ SELECT creature.map as map, creature_ai_summons.position_x AS x, creature_ai_summons.position_y AS y FROM creature_ai_scripts LEFT JOIN creature_ai_summons ON creature_ai_scripts.action2_type = 32 AND creature_ai_scripts.action2_param3 = creature_ai_summons.id LEFT JOIN creature ON creature_ai_scripts.creature_id = creature.id WHERE action2_type = 32 AND action2_param1 = ]]..entry..[[ GROUP BY map ]]) while query:fetch(creature_ai_scripts, "a") do if debug("units_summon_fixed") then break end for id, coords in pairs(GetCustomCoords(tonumber(creature_ai_scripts.map), tonumber(creature_ai_scripts.x), tonumber(creature_ai_scripts.y))) do local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end end -- search for AI summons (summoner position) -- [Darrowshire Spirit:11064] local creature_ai_scripts = {} local query = mysql:execute(core == "vmangos" and [[ SELECT creature_ai_events.creature_id AS summoner FROM creature_ai_scripts, creature_ai_events WHERE creature_ai_scripts.command = 10 AND creature_ai_scripts.id = creature_ai_events.id AND creature_ai_scripts.datalong = ]]..entry..[[ AND x = 0 AND y = 0 ]] or [[ SELECT creature_id AS summoner FROM spell_template LEFT JOIN creature_ai_scripts ON action1_type = 11 AND action1_param1 = spell_template.Id WHERE spell_template.Effect1 = 28 AND creature_id > 0 AND spell_template.EffectMiscValue1 = ]]..entry..[[ ]]) while query:fetch(creature_ai_scripts, "a") do if debug("units_summon_unknown") then break end for id, coords in pairs(GetCreatureCoords(tonumber(creature_ai_scripts.summoner))) do local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end if core ~= "vmangos" then for id, coords in pairs(GetCreatureCoordsPool(tonumber(creature_ai_scripts.summoner))) do local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["units"][data][entry]["coords"], { x, y, zone, respawn }) end end end -- clear duplicates pfDB["units"][data][entry]["coords"] = removedupes(pfDB["units"][data][entry]["coords"]) end end do -- Patch creature table with manual entries -- Only use this method of adding creatures if there is REALLY no way -- to extract data out of the databases of the mangos cores. If the list -- becomes too big, this should be separated to another file. pfDB["units"][data][420] = { ["coords"] = { [1] = { 69, 21, 148, 300 } }, ["fac"] = "H", ["lvl"] = "60", } do -- Sentinel Selarin:3694 -- taken from https://classic.wowhead.com/npc=3694/sentinel-selarin pfDB["units"][data][3694]["coords"] = { [1] = { 39.2, 43.4, 42, 0 } } end do -- Mokk the Savage:1514 -- taken from https://classic.wowhead.com/npc=1514/mokk-the-savage pfDB["units"][data][1514]["coords"] = { [1] = { 35.2, 60.4, 33, 0 } } end end end do -- objects print("- loading objects...") pfDB["objects"] = pfDB["objects"] or {} pfDB["objects"][data] = {} -- iterate over all objects local gameobject_template = {} local query = mysql:execute('SELECT * FROM gameobject_template GROUP BY gameobject_template.entry ORDER BY gameobject_template.entry ASC') while query:fetch(gameobject_template, "a") do if debug("objects") then break end local entry = tonumber(gameobject_template.entry) local name = gameobject_template.name pfDB["objects"][data][entry] = {} do -- detect faction local fac = "" local faction = {} local sql = [[ SELECT A, H FROM gameobject_template, pfquest.FactionTemplate_]]..expansion..[[ WHERE pfquest.FactionTemplate_]]..expansion..[[.factiontemplateID = gameobject_template.faction AND gameobject_template.entry = ]] .. gameobject_template.entry local query = mysql:execute(sql) while query:fetch(faction, "a") do if debug("objects_faction") then break end local A, H = faction.A, faction.H if A == "1" and not string.find(fac, "A") then fac = fac .. "A" end if H == "1" and not string.find(fac, "H") then fac = fac .. "H" end end if fac ~= "" then pfDB["objects"][data][entry]["fac"] = fac end end do -- coordinates pfDB["objects"][data][entry]["coords"] = {} for id,coords in pairs(GetGameObjectCoords(entry)) do if debug("objects_coords") then break end local x, y, zone, respawn = table.unpack(coords) table.insert(pfDB["objects"][data][entry]["coords"], { x, y, zone, respawn }) end end -- clear duplicates pfDB["objects"][data][entry]["coords"] = removedupes(pfDB["objects"][data][entry]["coords"]) end end do -- items print("- loading items...") pfDB["items"] = pfDB["items"] or {} pfDB["items"][data] = {} -- iterate over all items local item_template = {} local query = mysql:execute('SELECT entry, name FROM item_template GROUP BY item_template.entry ASC') while query:fetch(item_template, "a") do if debug("items") then break end local entry = tonumber(item_template.entry) local scans = { [0] = { entry, nil } } -- add items that contain the actual item to the itemlist local item_loot_item = {} local count = 0 local query = mysql:execute('SELECT entry, ChanceOrQuestChance FROM item_loot_template WHERE item = ' .. item_template.entry .. ' ORDER BY entry') while query:fetch(item_loot_item, "a") do if debug("items_container") then break end if math.abs(item_loot_item.ChanceOrQuestChance) > 0 then local chance = math.abs(item_loot_item.ChanceOrQuestChance) chance = chance < 0.01 and round(chance, 5) or round(chance, 2) table.insert(scans, { tonumber(item_loot_item.entry), chance }) end end -- recursively read U, O, V, R blocks of the item for id, item in pairs(scans) do local entry = tonumber(item[1]) local chance = item[2] and item[2] / 100 or 1 pfDB["items"][data][entry] = pfDB["items"][data][entry] or {} -- fill unit table local creature_loot_template = {} local query = mysql:execute('SELECT entry, ChanceOrQuestChance FROM creature_loot_template WHERE item = ' .. entry .. ' ORDER BY entry') while query:fetch(creature_loot_template, "a") do if debug("items_unit") then break end local chance = math.abs(creature_loot_template.ChanceOrQuestChance) * chance chance = chance < 0.01 and round(chance, 5) or round(chance, 2) if chance > 0 then pfDB["items"][data][entry]["U"] = pfDB["items"][data][entry]["U"] or {} pfDB["items"][data][entry]["U"][tonumber(creature_loot_template.entry)] = chance end end -- fill object table local gameobject_loot_template = {} local query = mysql:execute([[ SELECT gameobject_template.entry, gameobject_loot_template.ChanceOrQuestChance FROM gameobject_loot_template INNER JOIN gameobject_template ON gameobject_template.data1 = gameobject_loot_template.entry WHERE ( gameobject_template.type = 3 OR gameobject_template.type = 25 ) AND gameobject_loot_template.item = ]] .. entry .. [[ ORDER BY gameobject_template.entry ]]) while query:fetch(gameobject_loot_template, "a") do if debug("items_object") then break end local chance = math.abs(gameobject_loot_template.ChanceOrQuestChance) * chance chance = chance < 0.01 and round(chance, 5) or round(chance, 2) if chance > 0 then pfDB["items"][data][entry]["O"] = pfDB["items"][data][entry]["O"] or {} pfDB["items"][data][entry]["O"][tonumber(gameobject_loot_template.entry)] = chance end end -- fill reference table local reference_loot_template = {} local query = mysql:execute([[ SELECT entry, ChanceOrQuestChance FROM reference_loot_template where reference_loot_template.item = ]] .. entry .. [[ GROUP BY entry ]]) while query:fetch(reference_loot_template, "a") do if debug("items_reference") then break end local chance = math.abs(reference_loot_template.ChanceOrQuestChance) chance = chance < 0.01 and round(chance, 5) or round(chance, 2) pfDB["items"][data][entry]["R"] = pfDB["items"][data][entry]["R"] or {} pfDB["items"][data][entry]["R"][tonumber(reference_loot_template.entry)] = chance end -- fill vendor table local npc_vendor = {} local query = mysql:execute('SELECT entry, maxcount FROM npc_vendor WHERE item = ' .. entry .. ' ORDER BY entry') while query:fetch(npc_vendor, "a") do if debug("items_vendor") then break end pfDB["items"][data][entry]["V"] = pfDB["items"][data][entry]["V"] or {} pfDB["items"][data][entry]["V"][tonumber(npc_vendor.entry)] = tonumber(npc_vendor.maxcount) end -- handle vendor template tables local npc_vendor = {} local query = mysql:execute('SELECT creature_template.Entry, maxcount FROM npc_vendor_template, creature_template WHERE item = ' .. entry .. ' and creature_template.' .. C["VendorTemplateId"] .. ' = npc_vendor_template.entry ORDER BY creature_template.Entry') while query:fetch(npc_vendor, "a") do if debug("items_vendortemplate") then break end pfDB["items"][data][entry]["V"] = pfDB["items"][data][entry]["V"] or {} pfDB["items"][data][entry]["V"][tonumber(npc_vendor.Entry)] = tonumber(npc_vendor.maxcount) end end end end do -- refloot print("- loading refloot...") pfDB["refloot"] = pfDB["refloot"] or {} pfDB["refloot"][data] = {} -- iterate over all reference loots local reference_loot_template = {} local query = mysql:execute('SELECT entry, ChanceOrQuestChance FROM reference_loot_template GROUP BY entry') while query:fetch(reference_loot_template, "a") do if debug("refloot") then break end local entry = tonumber(reference_loot_template.entry) -- fill unit table local creature_loot_template = {} local count = 0 local query = mysql:execute([[ SELECT entry FROM creature_loot_template WHERE creature_loot_template.mincountOrRef < 0 AND item = ]] .. entry .. [[ ORDER BY entry ]]) while query:fetch(creature_loot_template, "a") do if debug("refloot_unit") then break end pfDB["refloot"][data][entry] = pfDB["refloot"][data][entry] or {} pfDB["refloot"][data][entry]["U"] = pfDB["refloot"][data][entry]["U"] or {} pfDB["refloot"][data][entry]["U"][tonumber(creature_loot_template.entry)] = 1 end -- fill object table local gameobject_template = {} local count = 0 local query = mysql:execute([[ SELECT gameobject_template.entry FROM gameobject_template, gameobject_loot_template WHERE gameobject_template.data1 = gameobject_loot_template.entry AND gameobject_loot_template.mincountOrRef < 0 AND gameobject_loot_template.item = ]] .. entry .. [[ ORDER BY gameobject_template.entry ; ]]) while query:fetch(gameobject_template, "a") do if debug("refloot_object") then break end pfDB["refloot"][data][entry] = pfDB["refloot"][data][entry] or {} pfDB["refloot"][data][entry]["O"] = pfDB["refloot"][data][entry]["O"] or {} pfDB["refloot"][data][entry]["O"][tonumber(gameobject_template.entry)] = 1 end end end do -- quests print("- loading quests...") pfDB["quests"] = pfDB["quests"] or {} pfDB["quests"][data] = {} pfDB["quests-itemreq"] = pfDB["quests-itemreq"] or {} pfDB["quests-itemreq"][data] = {} -- iterate over all quests local quest_template = {} local query = mysql:execute('SELECT * FROM quest_template GROUP BY quest_template.entry') while query:fetch(quest_template, "a") do if debug("quests") then break end local entry = tonumber(quest_template.entry) local minlevel = tonumber(quest_template.MinLevel) local questlevel = tonumber(quest_template.QuestLevel) local class = tonumber(quest_template.RequiredClasses) local race = tonumber(quest_template.RequiredRaces) local skill = tonumber(quest_template.RequiredSkill) local chain = tonumber(quest_template.NextQuestInChain) local srcitem = tonumber(quest_template.SrcItemId) local repeatable = tonumber(quest_template.SpecialFlags) & 1 local exclusive = tonumber(quest_template.ExclusiveGroup) local close = nil local event = nil -- seach for quests closed by this one if exclusive and exclusive > 0 then close = close or {} local exclusive_template = {} local query = mysql:execute('SELECT entry, ExclusiveGroup FROM quest_template WHERE ExclusiveGroup = ' .. exclusive .. ' GROUP BY quest_template.entry') while query:fetch(exclusive_template, "a") do table.insert(close, tonumber(exclusive_template.entry)) end end -- try to detect event by quest event entry local game_event_quest = {} local query = mysql:execute('SELECT event FROM game_event_quest WHERE quest = ' .. entry) while query:fetch(game_event_quest, "a") do if debug("quests_events") then break end event = tonumber(game_event_quest.event) break end -- try to detect event by creature event if not event then local game_event_creature = {} local sql = [[ SELECT game_event_creature.event as event FROM creature, game_event_creature, creature_questrelation WHERE creature.guid = game_event_creature.guid AND creature.id = creature_questrelation.id AND creature_questrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(game_event_creature, "a") do if debug("quests_eventscreature") then break end event = tonumber(game_event_creature.event) break end end -- try to detect event by gameobject event if not event then local game_event_gameobject = {} local sql = [[ SELECT game_event_gameobject.event as event FROM gameobject, game_event_gameobject, gameobject_questrelation WHERE gameobject.guid = game_event_gameobject.guid AND gameobject.id = gameobject_questrelation.id AND gameobject_questrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(game_event_gameobject, "a") do if debug("quests_eventsobjects") then break end event = tonumber(game_event_gameobject.event) break end end pfDB["quests"][data][entry] = {} pfDB["quests"][data][entry]["min"] = minlevel ~= 0 and minlevel pfDB["quests"][data][entry]["skill"] = skill ~= 0 and skill pfDB["quests"][data][entry]["lvl"] = questlevel ~= 0 and questlevel pfDB["quests"][data][entry]["class"] = class ~= 0 and class pfDB["quests"][data][entry]["race"] = race ~= 0 and race pfDB["quests"][data][entry]["skill"] = skill ~= 0 and skill pfDB["quests"][data][entry]["event"] = event ~= 0 and event pfDB["quests"][data][entry]["close"] = close and close -- quest objectives local units, objects, items, itemreq, areatrigger, zones, pre = {}, {}, {}, {}, {}, {}, {} -- add single pre-quests if tonumber(quest_template.PrevQuestId) ~= 0 then pre[math.abs(tonumber(quest_template.PrevQuestId))] = true end -- add required pre-quests local prequests = {} local query = mysql:execute('SELECT quest_template.entry FROM quest_template WHERE NextQuestId = ' .. entry .. ' AND ExclusiveGroup < 0') while query:fetch(prequests, "a") do if debug("quests_prequests") then break end pre[tonumber(prequests["entry"])] = true end -- add pre quests from quest chains local query = mysql:execute('SELECT quest_template.entry FROM quest_template WHERE NextQuestInChain = ' .. entry) while query:fetch(prequests, "a") do if debug("quests_prequestchain") then break end pre[tonumber(prequests["entry"])] = true end -- temporary add provided quest item items[srcitem] = true for i=1,4 do if quest_template["ReqCreatureOrGOId" .. i] and tonumber(quest_template["ReqCreatureOrGOId" .. i]) > 0 then units[tonumber(quest_template["ReqCreatureOrGOId" .. i])] = true elseif quest_template["ReqCreatureOrGOId" .. i] and tonumber(quest_template["ReqCreatureOrGOId" .. i]) < 0 then objects[math.abs(tonumber(quest_template["ReqCreatureOrGOId" .. i]))] = true end if quest_template["ReqItemId" .. i] and tonumber(quest_template["ReqItemId" .. i]) > 0 then items[tonumber(quest_template["ReqItemId" .. i])] = true end if quest_template["ReqSourceId" .. i] and tonumber(quest_template["ReqSourceId" .. i]) > 0 then items[tonumber(quest_template["ReqSourceId" .. i])] = true end if quest_template["ReqSpellCast" .. i] and tonumber(quest_template["ReqSpellCast" .. i]) > 0 then local spell_template = {} local query = mysql:execute('SELECT * FROM spell_template WHERE spell_template.' .. C.Id .. ' = ' .. quest_template["ReqSpellCast" .. i]) while query:fetch(spell_template, "a") do if debug("quests_questspellobject") then break end if spell_template[C.RequiresSpellFocus] ~= "0" then local gameobject_template = {} local query = mysql:execute('SELECT * FROM gameobject_template WHERE gameobject_template.type = 8 and gameobject_template.data0 = ' .. spell_template[C.RequiresSpellFocus]) while query:fetch(gameobject_template, "a") do objects[tonumber(gameobject_template["entry"])] = true end end end end end -- add all units that give kill credit for one of the known units if core ~= "vmangos" then for id in pairs(units) do local creature_template = {} local query = mysql:execute('SELECT * FROM creature_template WHERE KillCredit1 = ' .. id .. ' or KillCredit2 = ' .. id) while query:fetch(creature_template, "a") do if debug("quests_credit") then break end units[tonumber(creature_template["Entry"])] = true end end end -- scan all involved questitems for spells that require or are required by gameobjects, units or zones for id in pairs(items) do if id > 0 then local item_template = {} for _, spellcolumn in pairs({ "spellid_1", "spellid_2", "spellid_3", "spellid_4", "spellid_5" }) do local query = mysql:execute('SELECT * FROM item_template WHERE ' .. spellcolumn .. ' > 0 and entry = ' .. id) while query:fetch(item_template, "a") do if debug("quests_item") then break end local spellid = item_template[spellcolumn] -- scan through all spells that are associated with the item local spell_template = {} local query = mysql:execute('SELECT * FROM spell_template WHERE ' .. C.Id .. ' = ' .. spellid) while query:fetch(spell_template, "a") do if debug("quests_itemspell") then break end local area = spell_template["AreaId"] local focus = spell_template[C.RequiresSpellFocus] local match = nil -- spell requires focusing a creature local spell_script_target = {} for itemid in pairs(items) do local query = mysql:execute([[ SELECT spell_script_target.targetEntry AS creature FROM spell_script_target, item_template WHERE ]] .. spellid .. [[ > 0 AND ]] .. spellid .. [[ = spell_script_target.entry ]]) while query:fetch(spell_script_target, "a") do if debug("quests_itemspellcreature") then break end pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][tonumber(spell_script_target.creature)] = spellid itemreq[id] = true match = true end end -- spell requries focusing an object if focus and tonumber(focus) > 0 then local gameobject_template = {} local query = mysql:execute('SELECT * FROM gameobject_template WHERE gameobject_template.type = 8 and gameobject_template.data0 = ' .. focus) while query:fetch(gameobject_template, "a") do if debug("quests_itemspellobject") then break end pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][-tonumber(gameobject_template["entry"])] = spellid itemreq[id] = true match = true end end -- spell triggers something that requires a special target for _, trigger in pairs({ spell_template[C["EffectTriggerSpell"]..1], spell_template[C["EffectTriggerSpell"]..2], spell_template[C["EffectTriggerSpell"]..3] }) do if trigger and tonumber(trigger) > 0 then local spell_script_target = {} local query = mysql:execute('SELECT * FROM spell_script_target WHERE entry = ' .. trigger) while query:fetch(spell_script_target, "a") do if debug("quests_itemspellscript") then break end local targetobj = spell_script_target["type"] local targetentry = spell_script_target["targetEntry"] if tonumber(targetobj) == 0 then -- object pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][-tonumber(targetentry)] = spellid itemreq[id] = true match = true elseif tonumber(targetobj) == 1 then -- unit pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][tonumber(targetentry)] = spellid itemreq[id] = true match = true end end end end -- only spell limitation is a zone if not match and area and tonumber(area) > 0 then zones[tonumber(area)] = true end end end end -- item is used to open a creature local creature_items = {} local query = mysql:execute([[ SELECT ]] .. C.targetEntry .. [[ AS creature FROM item_required_target WHERE entry = ]] .. id .. [[ ]]) while query:fetch(creature_items, "a") do if debug("quests_itemcreature") then break end pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][tonumber(creature_items.creature)] = 0 itemreq[id] = true end -- item is used to open an object local object_items = {} local query = mysql:execute([[ SELECT gameobject_template.entry AS object FROM gameobject_template, pfquest.Lock_]]..expansion..[[ WHERE type = 10 and data0 = pfquest.Lock_]]..expansion..[[.id AND pfquest.Lock_]]..expansion..[[.data = ]] .. id .. [[ ]]) while query:fetch(object_items, "a") do if debug("quests_itemobject") then break end pfDB["quests-itemreq"][data][id] = pfDB["quests-itemreq"][data][id] or {} pfDB["quests-itemreq"][data][id][-tonumber(object_items.object)] = 0 itemreq[id] = true end end end -- scan for related areatriggers local areatrigger_involvedrelation = {} local query = mysql:execute('SELECT * FROM areatrigger_involvedrelation WHERE quest = ' .. entry) while query:fetch(areatrigger_involvedrelation, "a") do if debug("quests_areatrigger") then break end areatrigger[tonumber(areatrigger_involvedrelation["id"])] = true end -- remove provided quest item from objectives items[srcitem] = nil -- write pre-quests for id in opairs(pre) do pfDB["quests"][data][entry]["pre"] = pfDB["quests"][data][entry]["pre"] or {} table.insert(pfDB["quests"][data][entry]["pre"], tonumber(id)) end do -- write objectives if tblsize(units) > 0 or tblsize(objects) > 0 or tblsize(items) > 0 or tblsize(itemreq) > 0 or tblsize(areatrigger) > 0 or tblsize(zones) > 0 then pfDB["quests"][data][entry]["obj"] = pfDB["quests"][data][entry]["obj"] or {} for id in opairs(units) do pfDB["quests"][data][entry]["obj"]["U"] = pfDB["quests"][data][entry]["obj"]["U"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["U"], tonumber(id)) end for id in opairs(objects) do pfDB["quests"][data][entry]["obj"]["O"] = pfDB["quests"][data][entry]["obj"]["O"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["O"], tonumber(id)) end for id in opairs(items) do pfDB["quests"][data][entry]["obj"]["I"] = pfDB["quests"][data][entry]["obj"]["I"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["I"], tonumber(id)) end for id in opairs(itemreq) do pfDB["quests"][data][entry]["obj"]["IR"] = pfDB["quests"][data][entry]["obj"]["IR"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["IR"], tonumber(id)) end for id in opairs(areatrigger) do pfDB["quests"][data][entry]["obj"]["A"] = pfDB["quests"][data][entry]["obj"]["A"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["A"], tonumber(id)) end for id in opairs(zones) do pfDB["quests"][data][entry]["obj"]["Z"] = pfDB["quests"][data][entry]["obj"]["Z"] or {} table.insert(pfDB["quests"][data][entry]["obj"]["Z"], tonumber(id)) end end end do -- quest starter local creature_questrelation = {} local sql = [[ SELECT * FROM creature_questrelation WHERE creature_questrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(creature_questrelation, "a") do if debug("quests_starterunit") then break end pfDB["quests"][data][entry]["start"] = pfDB["quests"][data][entry]["start"] or {} pfDB["quests"][data][entry]["start"]["U"] = pfDB["quests"][data][entry]["start"]["U"] or {} table.insert(pfDB["quests"][data][entry]["start"]["U"], tonumber(creature_questrelation.id)) end local gameobject_questrelation = {} local sql = [[ SELECT * FROM gameobject_questrelation WHERE gameobject_questrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(gameobject_questrelation, "a") do if debug("quests_starterobject") then break end pfDB["quests"][data][entry]["start"] = pfDB["quests"][data][entry]["start"] or {} pfDB["quests"][data][entry]["start"]["O"] = pfDB["quests"][data][entry]["start"]["O"] or {} table.insert(pfDB["quests"][data][entry]["start"]["O"], tonumber(gameobject_questrelation.id)) end local item_template = {} local sql = [[ SELECT entry as id FROM item_template WHERE ]] .. C.startquest .. [[ = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(item_template, "a") do if debug("quests_starteritem") then break end -- remove quest start items from objectives if pfDB["quests"][data][entry]["obj"] and pfDB["quests"][data][entry]["obj"]["I"] then for id, objective in pairs(pfDB["quests"][data][entry]["obj"]["I"]) do if objective == tonumber(item_template.id) then pfDB["quests"][data][entry]["obj"]["I"][id] = nil end end end -- add item to quest starters pfDB["quests"][data][entry]["start"] = pfDB["quests"][data][entry]["start"] or {} pfDB["quests"][data][entry]["start"]["I"] = pfDB["quests"][data][entry]["start"]["I"] or {} table.insert(pfDB["quests"][data][entry]["start"]["I"], tonumber(item_template.id)) end end do -- quest ender local creature_involvedrelation = {} local sql = [[ SELECT * FROM creature_involvedrelation WHERE creature_involvedrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(creature_involvedrelation, "a") do if debug("quests_enderunit") then break end pfDB["quests"][data][entry]["end"] = pfDB["quests"][data][entry]["end"] or {} pfDB["quests"][data][entry]["end"]["U"] = pfDB["quests"][data][entry]["end"]["U"] or {} table.insert(pfDB["quests"][data][entry]["end"]["U"], tonumber(creature_involvedrelation.id)) end local gameobject_involvedrelation = {} local first = true local sql = [[ SELECT * FROM gameobject_involvedrelation WHERE gameobject_involvedrelation.quest = ]] .. quest_template.entry local query = mysql:execute(sql) while query:fetch(gameobject_involvedrelation, "a") do if debug("quests_enderobject") then break end pfDB["quests"][data][entry]["end"] = pfDB["quests"][data][entry]["end"] or {} pfDB["quests"][data][entry]["end"]["O"] = pfDB["quests"][data][entry]["end"]["O"] or {} table.insert(pfDB["quests"][data][entry]["end"]["O"], tonumber(gameobject_involvedrelation.id)) end end end end do -- zones print("- loading zones...") pfDB["zones"] = pfDB["zones"] or {} pfDB["zones"][data] = {} local zones = {} local query = mysql:execute('SELECT * FROM pfquest.WorldMapOverlay_'..expansion..' LEFT JOIN pfquest.AreaTable_'..expansion..' ON pfquest.WorldMapOverlay_'..expansion..'.areaID = pfquest.AreaTable_'..expansion..'.id') while query:fetch(zones, "a") do if debug("zones") then break end local entry = tonumber(zones.id) local zone = tonumber(zones.zoneID) local textureWidth = tonumber(zones.textureWidth) local textureHeight = tonumber(zones.textureHeight) local offsetX = tonumber(zones.offsetX) local offsetY = tonumber(zones.offsetY) -- convert square to map scale local hitRectTop = tonumber(zones.hitRectTop)/668*100 local hitRectLeft = tonumber(zones.hitRectLeft)/1002*100 local hitRectBottom = tonumber(zones.hitRectBottom)/668*100 local hitRectRight = tonumber(zones.hitRectRight)/1002*100 -- area size local width = hitRectRight - hitRectLeft local height = hitRectBottom - hitRectTop -- area center local cx = (hitRectLeft+hitRectRight)/2 local cy = (hitRectTop+hitRectBottom)/2 if entry then pfDB["zones"][data][entry] = { zone, round(width,2), round(height,2), round(cx,2), round(cy,2)} end end end do -- minimap print("- loading minimap...") pfDB["minimap"..exp] = pfDB["minimap"..exp] or {} local minimap_size = {} local query = mysql:execute('SELECT * FROM pfquest.WorldMapArea_'..expansion..' ORDER BY areatableID ASC') while query:fetch(minimap_size, "a") do if debug("minimap") then break end local mapID = minimap_size.mapID local areaID = minimap_size.areatableID local name = minimap_size.name local x_min = minimap_size.x_min local y_min = minimap_size.y_min local x_max = minimap_size.x_max local y_max = minimap_size.y_max local x = -1 * x_min + x_max local y = -1 * y_min + y_max pfDB["minimap"..exp][tonumber(areaID)] = { tonumber(y+.0), tonumber(x+.0) } end end do -- meta print("- loading meta...") pfDB["meta"..exp] = pfDB["meta"..exp] or { ["mines"] = {}, ["herbs"] = {}, ["chests"] = {}, ["rares"] = {}, ["flight"] = {}, } do -- raremobs local creature_template = {} local query = mysql:execute([[ SELECT * FROM `creature_template` WHERE ]] .. C.Rank .. [[ = 4 OR ]] .. C.Rank .. [[ = 2 ]]) while query:fetch(creature_template, "a") do if debug("meta_rares") then break end local entry = tonumber(creature_template[C.Entry]) local level = tonumber(creature_template[C.MinLevel]) pfDB["meta"..exp].rares[entry] = level end end do -- npcs local creature_flags = { [4] = "vendor", [8] = "flight", [32] = "spirithealer", [64] = "spirithealer", [128] = "innkeeper", [256] = "banker", [2048] = "battlemaster", [4096] = "auctioneer", [8192] = "stablemaster", [16384] = "repair", } local tbc_flag_map = { [4] = 128, [8] = 8192, [32] = 16384, [64] = 32768, [128] = 65536, [256] = 20000, [2048] = 1048576, [4096] = 2097152, [8192] = 4194304, [16384] = 4096, } for mask, name in pairs(creature_flags) do -- create meta relation table if not existing pfDB["meta"..exp][name] = pfDB["meta"..exp][name] or {} local mask = core == "vmangos" and mask or tbc_flag_map[mask] local creature_template = {} local query = mysql:execute([[ SELECT Entry, A, H FROM `creature_template`, `pfquest`.FactionTemplate_]]..expansion..[[ WHERE pfquest.FactionTemplate_]]..expansion..[[.factiontemplateID = creature_template.]] .. C.Faction .. [[ AND ( ]] .. C.NpcFlags .. [[ & ]]..mask..[[) > 0 ]]) while query:fetch(creature_template, "a") do if debug("meta_npcs") then break end local fac = "" local entry = tonumber(creature_template.Entry) local A = tonumber(creature_template.A) local H = tonumber(creature_template.H) if A >= 0 then fac = fac .. "A" end if H >= 0 then fac = fac .. "H" end pfDB["meta"..exp][name][entry] = fac end end end do -- objects local gameobject_flags = { [19] = "mailbox", [23] = "meetingstone", [25] = "fish", } for flag, name in pairs(gameobject_flags) do -- create meta relation table if not existing pfDB["meta"..exp][name] = pfDB["meta"..exp][name] or {} -- gameobject_template.type local gameobject_template = {} local query = mysql:execute([[ SELECT * FROM `gameobject_template` LEFT JOIN pfquest.FactionTemplate_]]..expansion..[[ ON pfquest.FactionTemplate_]]..expansion..[[.factiontemplateID = gameobject_template.faction WHERE `type` = ]]..flag..[[ ]]) while query:fetch(gameobject_template, "a") do if debug("meta_objects") then break end local entry = tonumber(gameobject_template.entry) * -1 local A = tonumber(gameobject_template.A) local H = tonumber(gameobject_template.H) local fac = "" if not A or A >= 0 then fac = fac .. "A" end if not H or H >= 0 then fac = fac .. "H" end pfDB["meta"..exp][name][entry] = fac end end end do -- openables local gameobject_template = {} local query = mysql:execute([[ SELECT * FROM `gameobject_template`, pfquest.Lock_]]..expansion..[[ WHERE `type` = 3 AND `locktype` = 2 AND `flags` = 0 AND `data1` > 0 and id = data0 GROUP BY `gameobject_template`.entry ORDER BY `gameobject_template`.entry ASC ]]) while query:fetch(gameobject_template, "a") do if debug("meta_openable") then break end local entry = tonumber(gameobject_template.entry) * -1 local data = tonumber(gameobject_template.data) local skill = tonumber(gameobject_template.skill) if data == 1 then pfDB["meta"..exp]["chests"][entry] = skill elseif data == 2 then pfDB["meta"..exp]["herbs"][entry] = skill elseif data == 3 then pfDB["meta"..exp]["mines"][entry] = skill end end end end print("- loading locales...") do -- unit locales -- load unit locales local units_loc = {} local locales_creature = {} local query = mysql:execute('SELECT *, creature_template.'..C.Entry..' AS _entry FROM creature_template LEFT JOIN locales_creature ON locales_creature.entry = creature_template.entry GROUP BY creature_template.entry ORDER BY creature_template.entry ASC') while query:fetch(locales_creature, "a") do if debug("locales_unit") then break end local entry = tonumber(locales_creature["_entry"]) local name = locales_creature[C.Name] if entry then for loc in pairs(locales) do local name_loc = locales_creature["name_loc" .. locales[loc]] if not name_loc or name_loc == "" then name_loc = name or "" end if name_loc and name_loc ~= "" then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["units"][locale] = pfDB["units"][locale] or { [420] = "Shagu" } pfDB["units"][locale][entry] = sanitize(name_loc) end end end end end do -- objects locales local locales_gameobject = {} local query = mysql:execute('SELECT *, gameobject_template.entry AS _entry FROM gameobject_template LEFT JOIN locales_gameobject ON locales_gameobject.entry = gameobject_template.entry GROUP BY gameobject_template.entry ORDER BY gameobject_template.entry ASC') while query:fetch(locales_gameobject, "a") do if debug("locales_object") then break end local entry = tonumber(locales_gameobject["_entry"]) local name = locales_gameobject.name if entry then for loc in pairs(locales) do local name_loc = locales_gameobject["name_loc" .. locales[loc]] if not name_loc or name_loc == "" then name_loc = name or "" end if name_loc and name_loc ~= "" then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["objects"][locale] = pfDB["objects"][locale] or {} pfDB["objects"][locale][entry] = sanitize(name_loc) end end end end end do -- items locales local items_loc = {} local locales_item = {} local query = mysql:execute('SELECT *, item_template.entry AS _entry FROM item_template LEFT JOIN locales_item ON locales_item.entry = item_template.entry GROUP BY item_template.entry ORDER BY item_template.entry ASC') while query:fetch(locales_item, "a") do if debug("locales_item") then break end local entry = tonumber(locales_item["_entry"]) local name = locales_item.name if entry then for loc in pairs(locales) do local name_loc = locales_item["name_loc" .. locales[loc]] if not name_loc or name_loc == "" then name_loc = name or "" end if name_loc and name_loc ~= "" then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["items"][locale] = pfDB["items"][locale] or {} pfDB["items"][locale][entry] = sanitize(name_loc) end end end end end do -- quests locales local locales_quest = {} local query = mysql:execute('SELECT *, quest_template.entry AS _entry FROM quest_template LEFT JOIN locales_quest ON locales_quest.entry = quest_template.entry GROUP BY quest_template.entry ORDER BY quest_template.entry ASC') while query:fetch(locales_quest, "a") do if debug("locales_quest") then break end for loc in pairs(locales) do local entry = tonumber(locales_quest["_entry"]) if entry then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["quests"][locale] = pfDB["quests"][locale] or {} local title_loc = locales_quest["Title_loc" .. locales[loc]] local details_loc = locales_quest["Details_loc" .. locales[loc]] local objectives_loc = locales_quest["Objectives_loc" .. locales[loc]] -- fallback to enUS titles if not title_loc or title_loc == "" then title_loc = locales_quest.Title or "" end if not details_loc or details_loc == "" then details_loc = locales_quest.Details or "" end if not objectives_loc or objectives_loc == "" then objectives_loc = locales_quest.Objectives or "" end pfDB["quests"][locale][entry] = { ["T"] = sanitize(title_loc), ["O"] = sanitize(objectives_loc), ["D"] = sanitize(details_loc) } end end end end do -- professions locales pfDB["professions"] = {} local locales_professions = {} local query = mysql:execute('SELECT * FROM pfquest.SkillLine_'..expansion..' ORDER BY id ASC') while query:fetch(locales_professions, "a") do if debug("locales_profession") then break end local entry = tonumber(locales_professions.id) if entry then for loc in pairs(locales) do local name = locales_professions["name_loc" .. locales[loc]] if name and name ~= "" then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["professions"][locale] = pfDB["professions"][locale] or {} pfDB["professions"][locale][entry] = sanitize(name) end end end end end do -- zones locales local locales_zones = {} local query = mysql:execute('SELECT * FROM pfquest.AreaTable_'..expansion..' ORDER BY id ASC') while query:fetch(locales_zones, "a") do if debug("locales_zone") then break end local entry = tonumber(locales_zones.id) if entry then for loc in pairs(locales) do local name = locales_zones["name_loc" .. locales[loc]] if name and name ~= "" then local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) pfDB["zones"][locale] = pfDB["zones"][locale] or {} pfDB["zones"][locale][entry] = sanitize(name) end end end end end if expansion ~= "vanilla" then print("- compress DB") pfDB["areatrigger"][data] = tablesubstract(pfDB["areatrigger"][data], pfDB["areatrigger"]["data"]) pfDB["units"][data] = tablesubstract(pfDB["units"][data], pfDB["units"]["data"]) pfDB["objects"][data] = tablesubstract(pfDB["objects"][data], pfDB["objects"]["data"]) pfDB["items"][data] = tablesubstract(pfDB["items"][data], pfDB["items"]["data"]) pfDB["refloot"][data] = tablesubstract(pfDB["refloot"][data], pfDB["refloot"]["data"]) pfDB["quests"][data] = tablesubstract(pfDB["quests"][data], pfDB["quests"]["data"]) pfDB["quests-itemreq"][data] = tablesubstract(pfDB["quests-itemreq"][data], pfDB["quests-itemreq"]["data"]) pfDB["zones"][data] = tablesubstract(pfDB["zones"][data], pfDB["zones"]["data"]) pfDB["minimap"..exp] = tablesubstract(pfDB["minimap"..exp], pfDB["minimap"]) pfDB["meta"..exp] = tablesubstract(pfDB["meta"..exp], pfDB["meta"]) for loc in pairs(locales) do local locale = loc .. exp local prev_locale = loc pfDB["units"][locale] = pfDB["units"][locale] and tablesubstract(pfDB["units"][locale], pfDB["units"][prev_locale]) or {} pfDB["objects"][locale] = pfDB["objects"][locale] and tablesubstract(pfDB["objects"][locale], pfDB["objects"][prev_locale]) or {} pfDB["items"][locale] = pfDB["items"][locale] and tablesubstract(pfDB["items"][locale], pfDB["items"][prev_locale]) or {} pfDB["quests"][locale] = pfDB["quests"][locale] and tablesubstract(pfDB["quests"][locale], pfDB["quests"][prev_locale]) or {} pfDB["zones"][locale] = pfDB["zones"][locale] and tablesubstract(pfDB["zones"][locale], pfDB["zones"][prev_locale]) or {} pfDB["professions"][locale] = pfDB["professions"][locale] and tablesubstract(pfDB["professions"][locale], pfDB["professions"][prev_locale]) or {} end end -- write down tables print("- writing database...") local output = settings.custom and "output/custom/" or "output/" os.execute("mkdir -p " .. output) serialize(output .. string.format("areatrigger%s.lua", exp), "pfDB[\"areatrigger\"][\""..data.."\"]", pfDB["areatrigger"][data]) serialize(output .. string.format("units%s.lua", exp), "pfDB[\"units\"][\""..data.."\"]", pfDB["units"][data]) serialize(output .. string.format("objects%s.lua", exp), "pfDB[\"objects\"][\""..data.."\"]", pfDB["objects"][data]) serialize(output .. string.format("items%s.lua", exp), "pfDB[\"items\"][\""..data.."\"]", pfDB["items"][data]) serialize(output .. string.format("refloot%s.lua", exp), "pfDB[\"refloot\"][\""..data.."\"]", pfDB["refloot"][data]) serialize(output .. string.format("quests%s.lua", exp), "pfDB[\"quests\"][\""..data.."\"]", pfDB["quests"][data]) serialize(output .. string.format("quests-itemreq%s.lua", exp), "pfDB[\"quests-itemreq\"][\""..data.."\"]", pfDB["quests-itemreq"][data]) serialize(output .. string.format("zones%s.lua", exp), "pfDB[\"zones\"][\""..data.."\"]", pfDB["zones"][data]) serialize(output .. string.format("minimap%s.lua", exp), "pfDB[\"minimap"..exp.."\"]", pfDB["minimap"..exp]) serialize(output .. string.format("meta%s.lua", exp), "pfDB[\"meta"..exp.."\"]", pfDB["meta"..exp]) for loc in pairs(locales) do local locale = loc .. ( expansion ~= "vanilla" and "-" .. expansion or "" ) os.execute("mkdir -p " .. output .. loc) serialize(output .. string.format("%s/units%s.lua", loc, exp), "pfDB[\"units\"][\""..locale.."\"]", pfDB["units"][locale]) serialize(output .. string.format("%s/objects%s.lua", loc, exp), "pfDB[\"objects\"][\""..locale.."\"]", pfDB["objects"][locale]) serialize(output .. string.format("%s/items%s.lua", loc, exp), "pfDB[\"items\"][\""..locale.."\"]", pfDB["items"][locale]) serialize(output .. string.format("%s/quests%s.lua", loc, exp), "pfDB[\"quests\"][\""..locale.."\"]", pfDB["quests"][locale]) serialize(output .. string.format("%s/professions%s.lua", loc, exp), "pfDB[\"professions\"][\""..locale.."\"]", pfDB["professions"][locale]) serialize(output .. string.format("%s/zones%s.lua", loc, exp), "pfDB[\"zones\"][\""..locale.."\"]", pfDB["zones"][locale]) end if not settings.custom then serialize(output .. "init.lua", "pfDB", pfDB, nil, true) end debug_statistics() end
0
0.827951
1
0.827951
game-dev
MEDIA
0.901149
game-dev
0.900212
1
0.900212
Greymerk/minecraft-roguelike
6,005
src/main/java/com/greymerk/roguelike/editor/boundingbox/BoundingBox.java
package com.greymerk.roguelike.editor.boundingbox; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.jetbrains.annotations.NotNull; import com.greymerk.roguelike.editor.BlockContext; import com.greymerk.roguelike.editor.Cardinal; import com.greymerk.roguelike.editor.Coord; import com.greymerk.roguelike.editor.IBlockFactory; import com.greymerk.roguelike.editor.IWorldEditor; import com.greymerk.roguelike.editor.shapes.IShape; import com.greymerk.roguelike.editor.shapes.Shape; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.nbt.NbtCompound; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.random.Random; import net.minecraft.world.chunk.WorldChunk; public class BoundingBox implements IBounded, IShape, Iterable<Coord>{ public static Codec<BoundingBox> CODEC = RecordCodecBuilder.create( instance -> instance.group( Coord.CODEC.fieldOf("start").forGetter(bb -> bb.start), Coord.CODEC.fieldOf("end").forGetter(bb -> bb.end) ).apply(instance, BoundingBox::new) ); private Coord start; private Coord end; public static BoundingBox of(Coord origin) { return new BoundingBox(origin); } public static BoundingBox of(WorldChunk chunk) { ChunkPos cpos = chunk.getPos(); return BoundingBox.of( Coord.of(cpos.getStartX(), chunk.getBottomY(), cpos.getStartZ()), Coord.of(cpos.getEndX(), chunk.getTopYInclusive(), cpos.getEndZ()) ); } public static BoundingBox of(Coord start, Coord end) { return new BoundingBox(start, end); } public static BoundingBox of(IBounded box) { return new BoundingBox(box.getStart(), box.getEnd()); } public BoundingBox copy() { return new BoundingBox(start, end); } private BoundingBox(Coord origin) { this.start = origin.copy(); this.end = origin.copy(); } private BoundingBox(Coord start, Coord end){ this.start = start.copy(); this.end = end.copy(); this.correct(); } public BoundingBox(NbtCompound tag) { this.start = Coord.of(tag.getCompound("start").get()); this.end = Coord.of(tag.getCompound("end").get()); this.correct(); } public BoundingBox getBoundingBox(){ return this; } public BoundingBox combine(IBounded other) { BoundingBox starts = new BoundingBox(start, other.getStart()); BoundingBox ends = new BoundingBox(end, other.getEnd()); this.start = starts.start; this.end = ends.end; this.correct(); return this; } public boolean collide(IBounded other){ BoundingBox otherBox = BoundingBox.of(other); if(end.getX() < otherBox.start.getX() || otherBox.end.getX() < start.getX()) return false; if(end.getY() < otherBox.start.getY() || otherBox.end.getY() < start.getY()) return false; if(end.getZ() < otherBox.start.getZ() || otherBox.end.getZ() < start.getZ()) return false; return true; } @Override public IShape getShape(Shape type) { return Shape.get(type, this); } public BoundingBox grow(Cardinal dir) { return this.grow(dir, 1); } public BoundingBox grow(Cardinal dir, int amount) { switch(dir) { case DOWN: case NORTH: case WEST: start.add(dir, amount); break; case UP: case EAST: case SOUTH: end.add(dir, amount); break; default: } this.correct(); return this; } public BoundingBox grow(Iterable<Cardinal> dirs) { return this.grow(dirs, 1); } public BoundingBox grow(Iterable<Cardinal> dirs, int amount) { for(Cardinal dir : dirs) { this.grow(dir, amount); } return this; } public BoundingBox add(Cardinal dir) { return this.add(dir, 1); } public BoundingBox add(Cardinal dir, int amount) { this.start.add(dir, amount); this.end.add(dir, amount); return this; } public BoundingBox add(Coord pos) { this.start.add(pos); this.end.add(pos); return this; } @Override public Coord getStart() { return start.copy(); } @Override public Coord getEnd() { return end.copy(); } @Override public boolean contains(Coord pos) { if(pos.getX() < this.start.getX() || pos.getX() > this.end.getX()) return false; if(pos.getY() < this.start.getY() || pos.getY() > this.end.getY()) return false; if(pos.getZ() < this.start.getZ() || pos.getZ() > this.end.getZ()) return false; return true; } @Override public int hashCode() { return Objects.hash(end, start); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoundingBox other = (BoundingBox) obj; return Objects.equals(end, other.end) && Objects.equals(start, other.start); } private void correct() { Coord s = Coord.of( end.getX() < start.getX() ? end.getX() : start.getX(), end.getY() < start.getY() ? end.getY() : start.getY(), end.getZ() < start.getZ() ? end.getZ() : start.getZ() ); Coord e = Coord.of( end.getX() < start.getX() ? start.getX() : end.getX(), end.getY() < start.getY() ? start.getY() : end.getY(), end.getZ() < start.getZ() ? start.getZ() : end.getZ() ); this.start = s; this.end = e; } @Override public Iterator<Coord> iterator() { return this.getShape(Shape.RECTSOLID).iterator(); } @Override public void fill(IWorldEditor editor, Random rand, @NotNull IBlockFactory block) { this.getShape(Shape.RECTSOLID).fill(editor, rand, block); } @Override public void fill(IWorldEditor editor, Random rand, @NotNull IBlockFactory block, Predicate<BlockContext> p) { this.getShape(Shape.RECTSOLID).fill(editor, rand, block, p); } @Override public List<Coord> get() { return this.getShape(Shape.RECTSOLID).get(); } @Override public String toString() { return List.of(start, end).toString(); } public Stream<Coord> stream() { return StreamSupport.stream(this.spliterator(), false); } }
0
0.832411
1
0.832411
game-dev
MEDIA
0.511571
game-dev
0.948876
1
0.948876
The-Aether-Team/The-Aether-II
1,539
src/main/java/com/aetherteam/aetherii/world/feature/configuration/ArcticIceSpikeConfiguration.java
package com.aetherteam.aetherii.world.feature.configuration; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import net.minecraft.core.registries.Registries; import net.minecraft.tags.TagKey; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; public record ArcticIceSpikeConfiguration(BlockStateProvider block, float baseRadius, int additionalRadius, float baseSlopeIntensity, int additionalSlopeIntensity, TagKey<Block> validBlocks) implements FeatureConfiguration { public static final Codec<ArcticIceSpikeConfiguration> CODEC = RecordCodecBuilder.create((instance) -> instance.group( BlockStateProvider.CODEC.fieldOf("block").forGetter(ArcticIceSpikeConfiguration::block), Codec.FLOAT.fieldOf("base_radius").forGetter(ArcticIceSpikeConfiguration::baseRadius), Codec.INT.fieldOf("additional_radius").forGetter(ArcticIceSpikeConfiguration::additionalRadius), Codec.FLOAT.fieldOf("base_slope_intensity").forGetter(ArcticIceSpikeConfiguration::baseSlopeIntensity), Codec.INT.fieldOf("additional_slope_intensity").forGetter(ArcticIceSpikeConfiguration::additionalSlopeIntensity), TagKey.codec(Registries.BLOCK).fieldOf("valid_blocks").forGetter(ArcticIceSpikeConfiguration::validBlocks) ).apply(instance, ArcticIceSpikeConfiguration::new)); }
0
0.58428
1
0.58428
game-dev
MEDIA
0.988579
game-dev
0.708072
1
0.708072
juce-framework/JUCE
4,652
extras/AudioPluginHost/Builds/Android/app/src/main/assets/Box2DTests/Tiles.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef TILES_H #define TILES_H /// This stress tests the dynamic tree broad-phase. This also shows that tile /// based collision is _not_ smooth due to Box2D not knowing about adjacency. class Tiles : public Test { public: enum { e_count = 20 }; Tiles() { m_fixtureCount = 0; b2Timer timer; { float32 a = 0.5f; b2BodyDef bd; bd.position.y = -a; b2Body* ground = m_world->CreateBody(&bd); #if 1 int32 N = 200; int32 M = 10; b2Vec2 position; position.y = 0.0f; for (int32 j = 0; j < M; ++j) { position.x = -N * a; for (int32 i = 0; i < N; ++i) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); ++m_fixtureCount; position.x += 2.0f * a; } position.y -= 2.0f * a; } #else int32 N = 200; int32 M = 10; b2Vec2 position; position.x = -N * a; for (int32 i = 0; i < N; ++i) { position.y = 0.0f; for (int32 j = 0; j < M; ++j) { b2PolygonShape shape; shape.SetAsBox(a, a, position, 0.0f); ground->CreateFixture(&shape, 0.0f); position.y -= 2.0f * a; } position.x += 2.0f * a; } #endif } { float32 a = 0.5f; b2PolygonShape shape; shape.SetAsBox(a, a); b2Vec2 x(-7.0f, 0.75f); b2Vec2 y; b2Vec2 deltaX(0.5625f, 1.25f); b2Vec2 deltaY(1.125f, 0.0f); for (int32 i = 0; i < e_count; ++i) { y = x; for (int32 j = i; j < e_count; ++j) { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position = y; //if (i == 0 && j == 0) //{ // bd.allowSleep = false; //} //else //{ // bd.allowSleep = true; //} b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 5.0f); ++m_fixtureCount; y += deltaY; } x += deltaX; } } m_createTime = timer.GetMilliseconds(); } void Step(Settings* settings) { const b2ContactManager& cm = m_world->GetContactManager(); int32 height = cm.m_broadPhase.GetTreeHeight(); int32 leafCount = cm.m_broadPhase.GetProxyCount(); int32 minimumNodeCount = 2 * leafCount - 1; float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / logf(2.0f)); m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, min = %d", height, int32(minimumHeight)); m_textLine += 15; Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixture count = %d", m_createTime, m_fixtureCount); m_textLine += 15; //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree; //if (m_stepCount == 400) //{ // tree->RebuildBottomUp(); //} } static Test* Create() { return new Tiles; } int32 m_fixtureCount; float32 m_createTime; }; #endif
0
0.883553
1
0.883553
game-dev
MEDIA
0.603343
game-dev
0.924381
1
0.924381
AgriCraft/AgriCraft
2,740
src/main/java/com/infinityraider/agricraft/handler/ResourceHandler.java
package com.infinityraider.agricraft.handler; import net.minecraft.server.ReloadableServerResources; import net.minecraft.server.packs.resources.PreparableReloadListener; import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.util.profiling.ProfilerFiller; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; public class ResourceHandler { private static final ResourceHandler INSTANCE = new ResourceHandler(); public static ResourceHandler getInstance() { return INSTANCE; } private ResourceHandler() {} @SubscribeEvent @SuppressWarnings("unused") public void onReloadListenerRegistration(AddReloadListenerEvent event) { event.addListener(new AgriJsonReloadListener(event.getServerResources())); } public static class AgriJsonReloadListener implements PreparableReloadListener { private final ReloadableServerResources dataPacks; private AgriJsonReloadListener(ReloadableServerResources dataPacks) { this.dataPacks = dataPacks; } public ReloadableServerResources getDataPacks() { return this.dataPacks; } // TODO: multi-thread magic which: // 1) reads jsons in time (on the server) // 2) uploads the required textures on the correct SpriteUploader in due time (on the client) // 3) registers the required models on the ModelManager in due time (on the client) // 4) Waits for the NetworkTagManager to finish processing the tags to then finish loading the jsons (on the server) @Override @Nonnull @ParametersAreNonnullByDefault public CompletableFuture<Void> reload(PreparationBarrier barrier, ResourceManager resourceManager, ProfilerFiller prepProfiler, ProfilerFiller reloadProfiler, Executor backgroundExecutor, Executor gameExecutor) { return CompletableFuture.runAsync(() -> this.readJsons(resourceManager), backgroundExecutor) .thenAccept((v) -> this.uploadTextures(resourceManager)) .thenAccept((v) -> this.uploadModels(resourceManager)) .thenAccept((v) -> this.finalize(resourceManager)); } protected void readJsons(ResourceManager manager) { } protected void uploadTextures(ResourceManager manager) { } protected void uploadModels(ResourceManager manager) { } public void finalize(ResourceManager manager) { } } }
0
0.914883
1
0.914883
game-dev
MEDIA
0.890046
game-dev
0.921796
1
0.921796
jnmartin84/doom64-dc
29,475
src/st_main.c
/* st_main.c -- status bar */ #include "doomdef.h" #include "st_main.h" #include "r_local.h" #include "st_faces.h" sbflash_t flashCards[6]; // 800A8180 boolean tryopen[6]; // 800A81E0 uint8_t *sfontlump; // 800A81F8 uint8_t *statuslump; // 800A81FC int sumbolslump; // 800A8204 int err_text_x = 20; // 800A8208 int err_text_y = 20; // 800A820C symboldata_t symboldata[] = // 8005B260 { { 120, 14, 13, 13 }, // 0 { 134, 14, 9, 13 }, // 1 { 144, 14, 14, 13 }, // 2 { 159, 14, 14, 13 }, // 3 { 174, 14, 16, 13 }, // 4 { 191, 14, 13, 13 }, // 5 { 205, 14, 13, 13 }, // 6 { 219, 14, 14, 13 }, // 7 { 234, 14, 14, 13 }, // 8 { 0, 29, 13, 13 }, // 9 { 67, 28, 14, 13 }, // - { 36, 28, 15, 14 }, // % { 28, 28, 7, 14 }, // ! { 14, 29, 6, 13 }, // . { 52, 28, 13, 13 }, // ? { 21, 29, 6, 13 }, // : { 0, 0, 13, 13 }, // A { 14, 0, 13, 13 }, // B { 28, 0, 13, 13 }, // C { 42, 0, 14, 13 }, // D { 57, 0, 14, 13 }, // E { 72, 0, 14, 13 }, // F { 87, 0, 15, 13 }, // G { 103, 0, 15, 13 }, // H { 119, 0, 6, 13 }, // I { 126, 0, 13, 13 }, // J { 140, 0, 14, 13 }, // K { 155, 0, 11, 13 }, // L { 167, 0, 15, 13 }, // M { 183, 0, 16, 13 }, // N { 200, 0, 15, 13 }, // O { 216, 0, 13, 13 }, // P { 230, 0, 15, 13 }, // Q { 246, 0, 13, 13 }, // R { 0, 14, 14, 13 }, // S { 15, 14, 14, 13 }, // T { 30, 14, 13, 13 }, // U { 44, 14, 15, 13 }, // V { 60, 14, 15, 13 }, // W { 76, 14, 15, 13 }, // X { 92, 14, 13, 13 }, // Y { 106, 14, 13, 13 }, // Z { 83, 31, 10, 11 }, // a { 93, 31, 10, 11 }, // b { 103, 31, 11, 11 }, // c { 114, 31, 11, 11 }, // d { 125, 31, 11, 11 }, // e { 136, 31, 11, 11 }, // f { 147, 31, 12, 11 }, // g { 159, 31, 12, 11 }, // h { 171, 31, 4, 11 }, // i { 175, 31, 10, 11 }, // j { 185, 31, 11, 11 }, // k { 196, 31, 9, 11 }, // l { 205, 31, 12, 11 }, // m { 217, 31, 13, 11 }, // n { 230, 31, 12, 11 }, // o { 242, 31, 11, 11 }, // p { 0, 43, 12, 11 }, // q { 12, 43, 11, 11 }, // r { 23, 43, 11, 11 }, // s { 34, 43, 10, 11 }, // t { 44, 43, 11, 11 }, // u { 55, 43, 12, 11 }, // v { 67, 43, 13, 11 }, // w { 80, 43, 13, 11 }, // x { 93, 43, 10, 11 }, // y { 103, 43, 11, 11 }, // z { 0, 95, 108, 11 }, // Slider bar 0x74 { 108, 95, 6, 11 }, // Slider gem 0x75 { 0, 54, 32, 26 }, // Skull 1 0x76 { 32, 54, 32, 26 }, // Skull 2 0x77 { 64, 54, 32, 26 }, // Skull 3 0x78 { 96, 54, 32, 26 }, // Skull 4 0x79 { 128, 54, 32, 26 }, // Skull 5 0x7a { 160, 54, 32, 26 }, // Skull 6 0x7b { 192, 54, 32, 26 }, // Skull 7 0x7c { 224, 54, 32, 26 }, // Skull 8 0x7d { 134, 97, 7, 11 }, // Right arrow 0x7e { 114, 95, 20, 18 }, // Select box 0x7f { 105, 80, 15, 15 }, // Dpad left 0x80 { 120, 80, 15, 15 }, // Dpad right 0x81 { 135, 80, 15, 15 }, // Dpad up 0x82 { 150, 80, 15, 15 }, // Dpad down 0x83 { 45, 80, 15, 15 }, // C left button 0x84 { 60, 80, 15, 15 }, // C right button 0x85 { 75, 80, 15, 15 }, // C up button 0x86 { 90, 80, 15, 15 }, // C down button 0x87 { 165, 80, 15, 15 }, // L button 0x88 { 180, 80, 15, 15 }, // R button 0x89 { 0, 80, 15, 15 }, // A button 0x8a { 15, 80, 15, 15 }, // B btton 0x8b { 195, 80, 15, 15 }, // Z button 0x8c { 30, 80, 15, 15 }, // Start button 0x8d { 156, 96, 13, 13 }, // Down arrow 0x8e { 143, 96, 13, 13 }, // Up arrow 0x8f { 169, 96, 7, 13 }, // Left arrow 0x90 //{134, 96, 7, 13}, // Right arrow Missing On Doom 64 }; int card_x[6] = { (78 << 2), (89 << 2), (100 << 2), (78 << 2), (89 << 2), (100 << 2) }; // 8005b870 // N/256*100% probability // that the normal face state will change #define ST_FACEPROBABILITY 96 // Number of status faces. #define ST_NUMPAINFACES 5 #define ST_NUMSTRAIGHTFACES 3 #define ST_NUMTURNFACES 2 #define ST_NUMSPECIALFACES 3 #define ST_FACESTRIDE \ (ST_NUMSTRAIGHTFACES + ST_NUMTURNFACES + ST_NUMSPECIALFACES) #define ST_NUMEXTRAFACES 2 #define ST_NUMFACES (ST_FACESTRIDE * ST_NUMPAINFACES + ST_NUMEXTRAFACES) #define ST_TURNOFFSET (ST_NUMSTRAIGHTFACES) #define ST_OUCHOFFSET (ST_TURNOFFSET + ST_NUMTURNFACES) #define ST_EVILGRINOFFSET (ST_OUCHOFFSET + 1) #define ST_RAMPAGEOFFSET (ST_EVILGRINOFFSET + 1) #define ST_GODFACE (ST_NUMPAINFACES * ST_FACESTRIDE) #define ST_DEADFACE (ST_GODFACE + 1) #define ST_EVILGRINCOUNT (2 * TICRATE) #define ST_STRAIGHTFACECOUNT (TICRATE / 2) #define ST_TURNCOUNT (1 * TICRATE) #define ST_OUCHCOUNT (1 * TICRATE) #define ST_RAMPAGEDELAY (2 * TICRATE) #define ST_MUCHPAIN 20 // used to use appopriately pained face static int st_oldhealth = -1; // count until face changes static int st_facecount = 0; // current face index, used by w_faces static int st_faceindex = 0; unsigned char *faces[ST_NUMFACES]; void ST_updateFaceWidget(void); void ST_Init(void) // 80029BA0 { // these get pre-converted in r_data.c now // sfontlump = (uint8_t *)W_CacheLumpName("SFONT",PU_STATIC,dec_jag); // statuslump = (uint8_t *)W_CacheLumpName("STATUS",PU_STATIC,dec_jag); // sumbolslump = W_GetNumForName("SYMBOLS"); int facenum; // face states facenum = 0; faces[facenum++] = STFST00_bits; faces[facenum++] = STFST01_bits; faces[facenum++] = STFST02_bits; faces[facenum++] = STFTR00_bits; faces[facenum++] = STFTL00_bits; faces[facenum++] = STFOUCH0_bits; faces[facenum++] = STFEVL0_bits; faces[facenum++] = STFKILL0_bits; faces[facenum++] = STFST10_bits; faces[facenum++] = STFST11_bits; faces[facenum++] = STFST12_bits; faces[facenum++] = STFTR10_bits; faces[facenum++] = STFTL10_bits; faces[facenum++] = STFOUCH1_bits; faces[facenum++] = STFEVL1_bits; faces[facenum++] = STFKILL1_bits; faces[facenum++] = STFST20_bits; faces[facenum++] = STFST21_bits; faces[facenum++] = STFST22_bits; faces[facenum++] = STFTR20_bits; faces[facenum++] = STFTL20_bits; faces[facenum++] = STFOUCH2_bits; faces[facenum++] = STFEVL2_bits; faces[facenum++] = STFKILL2_bits; faces[facenum++] = STFST30_bits; faces[facenum++] = STFST31_bits; faces[facenum++] = STFST32_bits; faces[facenum++] = STFTR30_bits; faces[facenum++] = STFTL30_bits; faces[facenum++] = STFOUCH3_bits; faces[facenum++] = STFEVL3_bits; faces[facenum++] = STFKILL3_bits; faces[facenum++] = STFST40_bits; faces[facenum++] = STFST41_bits; faces[facenum++] = STFST42_bits; faces[facenum++] = STFTR40_bits; faces[facenum++] = STFTL40_bits; faces[facenum++] = STFOUCH4_bits; faces[facenum++] = STFEVL4_bits; faces[facenum++] = STFKILL4_bits; faces[facenum++] = STFGOD0_bits; faces[facenum++] = STFDEAD0_bits; } // used for evil grin static boolean oldweaponsowned[NUMWEAPONS]; // a random number per tick static int st_randomnumber; void ST_InitEveryLevel(void) // 80029C00 { player_t *plyr = &players[0]; infraredFactor = 0; quakeviewy = 0; quakeviewx = 0; camviewpitch = 0; flashCards[0].active = false; flashCards[1].active = false; flashCards[2].active = false; flashCards[3].active = false; flashCards[4].active = false; flashCards[5].active = false; tryopen[0] = false; tryopen[1] = false; tryopen[2] = false; tryopen[3] = false; tryopen[4] = false; tryopen[5] = false; for (int i = 0; i < NUMWEAPONS; i++) oldweaponsowned[i] = plyr->weaponowned[i]; } /* ==================== = = ST_Ticker = ==================== */ extern int force_vmu_refresh; void ST_Ticker(void) // 80029C88 { player_t *player; int ind; player = &players[0]; /* */ /* Countdown time for the message */ /* */ player->messagetic--; player->messagetic1--; // [Immorpher] decriment message buffer player->messagetic2--; // [Immorpher] decriment message buffer player->messagetic3--; // [Immorpher] decriment message buffer /* */ /* Tried to open a CARD or SKULL door? */ /* */ for (ind = 0; ind < NUMCARDS; ind++) { if (tryopen[ind]) { /* CHECK FOR INITIALIZATION */ tryopen[ind] = false; flashCards[ind].active = true; flashCards[ind].delay = FLASHDELAY - 1; flashCards[ind].times = FLASHTIMES + 1; flashCards[ind].doDraw = false; } else if (flashCards[ind].active && !--flashCards[ind].delay) { /* MIGHT AS WELL DO TICKING IN THE SAME LOOP! */ flashCards[ind].delay = FLASHDELAY - 1; flashCards[ind].doDraw ^= 1; if (!--flashCards[ind].times) flashCards[ind].active = false; if (flashCards[ind].doDraw && flashCards[ind].active) S_StartSound(NULL, sfx_itemup); } } /* */ /* Do flashes from damage/items */ /* */ if (cameratarget == player->mo) { ST_UpdateFlash(); } if (demoplayback == false && (force_vmu_refresh || menu_settings.VmuDisplay)) { st_randomnumber = I_Random(); ST_updateFaceWidget(); // Update VMU I_VMUFB(force_vmu_refresh); if (force_vmu_refresh) force_vmu_refresh = 0; } } /* ==================== = = ST_Drawer = ==================== */ pvr_sprite_hdr_t status_shdr; pvr_sprite_cxt_t status_scxt; pvr_sprite_txr_t status_stxr; void ST_Drawer(void) // 80029DC0 { player_t *player; weapontype_t weapon; int ammo, ind, ms_alpha; float x1, x2, y1, y2, u1, u2, v1, v2; status_stxr.flags = PVR_CMD_VERTEX_EOL; status_stxr.az = 8.9999999f; status_stxr.bz = 8.9999999f; status_stxr.cz = 8.9999999f; status_stxr.dummy = 0; player = &players[0]; /* */ /* Draw Text Message */ /* */ // [Immorpher] only display messages and calculate if global tic is active if ((menu_settings.enable_messages) && players[0].messagetic > 0) { // [Immorpher] new global tic indicates new message to add if (players[0].messagetic != players[0].messagetic1) { // Sequentially shift messages to lower states players[0].message3 = players[0].message2; players[0].messagetic3 = players[0].messagetic2; players[0].messagecolor3 = players[0].messagecolor2; players[0].message2 = players[0].message1; players[0].messagetic2 = players[0].messagetic1; players[0].messagecolor2 = players[0].messagecolor1; players[0].message1 = players[0].message; players[0].messagetic1 = players[0].messagetic; players[0].messagecolor1 = players[0].messagecolor; } // display message 1 if (players[0].messagetic1 > 0) { // set message alpha ms_alpha = players[0].messagetic1 * 8; if (ms_alpha >= 196) ms_alpha = 196; ST_Message(2 + menu_settings.HUDmargin, menu_settings.HUDmargin, players[0].message1, ms_alpha | players[0].messagecolor1, ST_BELOW_OVL); // display message } // display message 2 if (players[0].messagetic2 > 0) { // set message alpha ms_alpha = players[0].messagetic2 * 8; if (ms_alpha >= 196) ms_alpha = 196; ST_Message(2 + menu_settings.HUDmargin, 10 + menu_settings.HUDmargin, players[0].message2, ms_alpha | players[0].messagecolor2, ST_BELOW_OVL); // display message } // display message 3 if (players[0].messagetic3 > 0) { // set message alpha ms_alpha = players[0].messagetic3 * 8; if (ms_alpha >= 196) ms_alpha = 196; ST_Message(2 + menu_settings.HUDmargin, 20 + menu_settings.HUDmargin, players[0].message3, ms_alpha | players[0].messagecolor3, ST_BELOW_OVL); // display message } } if (menu_settings.HUDopacity) { uint32_t HUDcolor = PACKRGBA(224, 0, 0, menu_settings.HUDopacity); /* */ /* Gray color */ /* */ { int xpos = 2 + menu_settings.HUDmargin; int ypos = 218 - menu_settings.HUDmargin; int hw = (42 - 2); int hh = (224 - 218); x1 = xpos * (float)RES_RATIO; x2 = (xpos + hw) * (float)RES_RATIO; y1 = ypos * (float)RES_RATIO; y2 = (ypos + hh) * (float)RES_RATIO; u1 = (float)0.0f; u2 = (float)hw / 128.0f; v1 = (float)0.0f; v2 = (float)hh / 16.0f; status_shdr.argb = D64_PVR_PACK_COLOR( 0x80, 0x80, 0x80, menu_settings.HUDopacity); status_stxr.ax = x1; status_stxr.ay = y2; status_stxr.bx = x1; status_stxr.by = y1; status_stxr.cx = x2; status_stxr.cy = y1; status_stxr.dx = x2; status_stxr.dy = y2; status_stxr.auv = PVR_PACK_16BIT_UV(u1, v2); status_stxr.buv = PVR_PACK_16BIT_UV(u1, v1); status_stxr.cuv = PVR_PACK_16BIT_UV(u2, v1); pvr_list_prim(PVR_LIST_TR_POLY, &status_shdr, sizeof(pvr_sprite_hdr_t)); pvr_list_prim(PVR_LIST_TR_POLY, &status_stxr, sizeof(pvr_sprite_txr_t)); } /* */ /* Armor */ /* */ { int xpos = 280 - menu_settings.HUDmargin; int ypos = 218 - menu_settings.HUDmargin; int hw = (316 - 280); int hh = (224 - 218); x1 = xpos * (float)RES_RATIO; x2 = (xpos + hw) * (float)RES_RATIO; y1 = ypos * (float)RES_RATIO; y2 = (ypos + hh) * (float)RES_RATIO; u1 = 40.0f / 128.0f; u2 = (float)(40.0f + hw) / 128.0f; v1 = 0.0f; v2 = (float)hh / 16.0f; status_stxr.ax = x1; status_stxr.ay = y2; status_stxr.bx = x1; status_stxr.by = y1; status_stxr.cx = x2; status_stxr.cy = y1; status_stxr.dx = x2; status_stxr.dy = y2; status_stxr.auv = PVR_PACK_16BIT_UV(u1, v2); status_stxr.buv = PVR_PACK_16BIT_UV(u1, v1); status_stxr.cuv = PVR_PACK_16BIT_UV(u2, v1); pvr_list_prim(PVR_LIST_TR_POLY, &status_stxr, sizeof(pvr_sprite_txr_t)); } /* */ /* White color */ /* */ /* */ /* Cards & skulls */ /* */ for (ind = 0; ind < NUMCARDS; ind++) { if (player->cards[ind] || (flashCards[ind].active && flashCards[ind].doDraw)) { /* */ /* Draw Keys Graphics */ /* */ int xpos = card_x[ind] >> 2; int ypos = 230 - menu_settings.HUDmargin; int hw = 9; int hh = 10; x1 = (float)xpos * (float)RES_RATIO; x2 = (float)(xpos + hw) * (float)RES_RATIO; y1 = (float)ypos * (float)RES_RATIO; y2 = (float)(ypos + hh) * (float)RES_RATIO; u1 = (float)(ind * 9) / 128.0f; u2 = (float)((float)(ind * 9) + hw) / 128.0f; v1 = 6.0f / 16.0f; v2 = (6.0f + (float)hh) / 16.0f; status_shdr.argb = D64_PVR_PACK_COLOR( 0xff, 0xff, 0xff, menu_settings.HUDopacity); status_stxr.ax = x1; status_stxr.ay = y2; status_stxr.bx = x1; status_stxr.by = y1; status_stxr.cx = x2; status_stxr.cy = y1; status_stxr.dx = x2; status_stxr.dy = y2; status_stxr.auv = PVR_PACK_16BIT_UV(u1, v2); status_stxr.buv = PVR_PACK_16BIT_UV(u1, v1); status_stxr.cuv = PVR_PACK_16BIT_UV(u2, v1); pvr_list_prim(PVR_LIST_TR_POLY, &status_shdr, sizeof(pvr_sprite_hdr_t)); pvr_list_prim(PVR_LIST_TR_POLY, &status_stxr, sizeof(pvr_sprite_txr_t)); } } /* */ /* Ammo */ /* */ weapon = player->pendingweapon; if (weapon == wp_nochange) weapon = player->readyweapon; #ifdef OSDSHOWFPS ammo = (int)last_fps; ST_Message(148, 227 - menu_settings.HUDmargin - 10, "FPS", 0x80808000 | menu_settings.HUDopacity, ST_BELOW_OVL); ST_DrawNumber(160, 227 - menu_settings.HUDmargin, ammo, 0, PACKRGBA(224, 0, 0, menu_settings.HUDopacity), ST_BELOW_OVL); #else if (weaponinfo[weapon].ammo != am_noammo) { if (menu_settings.ColoredHUD) { switch (weaponinfo[weapon].ammo) { case am_clip: HUDcolor = PACKRGBA(96, 96, 128, menu_settings.HUDopacity); break; case am_shell: HUDcolor = PACKRGBA(196, 32, 0, menu_settings.HUDopacity); break; case am_cell: HUDcolor = PACKRGBA(0, 96, 128, menu_settings.HUDopacity); break; default: HUDcolor = PACKRGBA(164, 96, 0, menu_settings.HUDopacity); break; } } ammo = player->ammo[weaponinfo[weapon].ammo]; if (ammo < 0) ammo = 0; ST_DrawNumber(160, 227 - menu_settings.HUDmargin, ammo, 0, HUDcolor, ST_BELOW_OVL); } #endif /* */ /* Health */ /* */ if (menu_settings.ColoredHUD) { if (player->health <= 67) HUDcolor = PACKRGBA(224 - 96 * player->health / 67, 128 * player->health / 67, 0, menu_settings.HUDopacity); else if (player->health <= 133) HUDcolor = PACKRGBA(256 - 256 * player->health / 133, 128, 64 * player->health / 133 - 32, menu_settings.HUDopacity); else HUDcolor = PACKRGBA(0, 256 - 192 * player->health / 200, 288 * player->health / 200 - 160, menu_settings.HUDopacity); } ST_DrawNumber(22 + menu_settings.HUDmargin, 227 - menu_settings.HUDmargin, player->health, 0, HUDcolor, ST_BELOW_OVL); /* */ /* Armor */ /* */ if (menu_settings.ColoredHUD) { if (player->armorpoints == 0) HUDcolor = PACKRGBA(224, 0, 0, menu_settings.HUDopacity); else if (player->armortype == 1) HUDcolor = PACKRGBA(0, 128, 64, menu_settings.HUDopacity); else HUDcolor = PACKRGBA(0, 64, 128, menu_settings.HUDopacity); } ST_DrawNumber(298 - menu_settings.HUDmargin, 227 - menu_settings.HUDmargin, player->armorpoints, 0, HUDcolor, ST_BELOW_OVL); } } #define ST_FONTWHSIZE 8 pvr_ptr_t pvrfont; pvr_sprite_hdr_t font_shdr; pvr_sprite_cxt_t font_scxt; pvr_sprite_txr_t font_stxr; void ST_Message(int x, int y, char *text, uint32_t color, int prio) { uint8_t c; int s, t; int xpos, ypos; float x1, x2, y1, y2, u1, u2, v1, v2; if (!text || text[0] == '\0') { return; } font_stxr.flags = PVR_CMD_VERTEX_EOL; if (prio == ST_ABOVE_OVL) { font_stxr.az = 10.0000001f; font_stxr.bz = 10.0000001f; font_stxr.cz = 10.0000001f; } else { font_stxr.az = 8.9999999f; font_stxr.bz = 8.9999999f; font_stxr.cz = 8.9999999f; } font_stxr.dummy = 0; font_shdr.argb = D64_PVR_REPACK_COLOR(color); ypos = y; xpos = x; pvr_list_prim(PVR_LIST_TR_POLY, &font_shdr, sizeof(pvr_sprite_hdr_t)); while (*text) { c = *text; if (c == '\n') { ypos += (ST_FONTWHSIZE + 1); xpos = x; } else { if (c >= 'a' && c <= 'z') c -= (26 + 6); if (c >= '!' && c <= '_') { if ((c - '!') < 32) t = 0; else t = ST_FONTWHSIZE; s = ((c - '!') & ~32) * ST_FONTWHSIZE; x1 = (float)xpos * (float)RES_RATIO; x2 = (float)(xpos + ST_FONTWHSIZE) * (float)RES_RATIO; y1 = (float)ypos * (float)RES_RATIO; y2 = (float)(ypos + ST_FONTWHSIZE) * (float)RES_RATIO; u1 = (float)s / 256.0f; u2 = (float)(s + ST_FONTWHSIZE) / 256.0f; v1 = (float)t / 16.0f; v2 = (float)(t + ST_FONTWHSIZE) / 16.0f; font_stxr.ax = x1; font_stxr.ay = y2; font_stxr.bx = x1; font_stxr.by = y1; font_stxr.cx = x2; font_stxr.cy = y1; font_stxr.dx = x2; font_stxr.dy = y2; font_stxr.auv = PVR_PACK_16BIT_UV(u1, v2); font_stxr.buv = PVR_PACK_16BIT_UV(u1, v1); font_stxr.cuv = PVR_PACK_16BIT_UV(u2, v1); pvr_list_prim(PVR_LIST_TR_POLY, &font_stxr, sizeof(pvr_sprite_txr_t)); } xpos += ST_FONTWHSIZE; } text++; } } void ST_DrawNumber(int x, int y, int value, int mode, uint32_t color, int prio) { int index, width, i; int number[16]; width = 0; for (index = 0; index < 16; index++) { number[index] = value % 10; width += symboldata[number[index]].w; value /= 10; if (!value) break; } switch (mode) { case 0: /* Center */ x -= (width / 2); case 1: /* Right */ while (index >= 0) { ST_DrawSymbol(x, y, number[index], color, prio); x += symboldata[number[index]].w; index--; } break; case 2: /* Left */ i = 0; while (index >= 0) { x -= symboldata[number[i]].w; ST_DrawSymbol(x, y, number[i], color, prio); i++; index--; } break; default: break; } } void ST_DrawString(int x, int y, char *text, uint32_t color, int prio) { unsigned char c; int xpos, ypos, index; xpos = x; if (xpos <= -1) xpos = ST_GetCenterTextX(text); ypos = y; while (*text) { int cur_y; c = *text; // [jnmartin84] newline support :-) if (c == '\n') { ypos += 16; xpos = x + 8; text++; continue; } cur_y = ypos; if (c >= 'A' && c <= 'Z') { index = (c - 'A') + 16; } else if (c >= 'a' && c <= 'z') { index = (c - 'a') + 42; cur_y = ypos + 2; } else if (c >= '0' && c <= '9') { index = (c - '0') + 0; } else if (c == '!') { index = 12; cur_y = ypos - 1; } else if (c == '-') { index = 10; } else if (c == '.') { index = 13; } else if (c == ':') { index = 15; } else if (c == '?') { index = 14; } else if (c == '%') { index = 11; } else if (c >= FIRST_SYMBOL && c <= LAST_SYMBOL) { index = (c - '0'); } else { xpos += 6; /* space */ text++; continue; } ST_DrawSymbol(xpos, cur_y, index, color, prio); xpos += symboldata[index].w; text++; } } int ST_GetCenterTextX(char *text) { unsigned char c; int xpos, index; xpos = 0; while (*text) { c = *text; if (c >= 'A' && c <= 'Z') { index = (c - 'A') + 16; } else if (c >= 'a' && c <= 'z') { index = (c - 'a') + 42; } else if (c >= '0' && c <= '9') { index = (c - '0') + 0; } else if (c == '!') { index = 12; } else if (c == '-') { index = 10; } else if (c == '.') { index = 13; } else if (c == ':') { index = 15; } else if (c == '?') { index = 14; } else if (c == '%') { index = 11; } else if (c >= FIRST_SYMBOL && c <= LAST_SYMBOL) { index = (c - '0'); } else { xpos += 6; /* space */ text++; continue; } xpos += symboldata[index].w; text++; } return (320 - xpos) / 2; } #define ST_MAXDMGCOUNT 144 #define ST_MAXSTRCOUNT 32 #define ST_MAXBONCOUNT 100 void ST_UpdateFlash(void) { player_t *plyr; int cnt; int bzc; int bnc; plyr = &players[0]; if ((plyr->f_powers[pw_infrared] < 120) && infraredFactor) { infraredFactor -= 4; if (infraredFactor < 0) { infraredFactor = 0; } P_RefreshBrightness(); } if (plyr->f_powers[pw_invulnerability] >= 61 || ((int)plyr->f_powers[pw_invulnerability]) & 8) { /* invulnerability flash (white) */ FlashEnvColor = PACKRGBA(128, 128, 128, 255); } else if ((int)plyr->f_bfgcount > 0) { /* bfg flash (green)*/ FlashEnvColor = PACKRGBA(0, (int)plyr->f_bfgcount, 0, 255); } else { /* damage and strength flash (red) */ cnt = (int)plyr->f_damagecount; if (cnt) { if ((cnt + 16) > ST_MAXDMGCOUNT) cnt = ST_MAXDMGCOUNT; } if (plyr->f_powers[pw_strength] <= ST_MAXSTRCOUNT) { /* slowly fade the berzerk out */ bzc = (int)plyr->f_powers[pw_strength]; if (bzc == 1) bzc = 0; } else { bzc = ST_MAXSTRCOUNT; } if ((cnt != 0) || (bzc != 0)) { FlashEnvColor = PACKRGBA(0, 0, 0, 0); if (bzc < cnt) { if (cnt != 0) FlashEnvColor = PACKRGBA(cnt, 0, 0, 255); } else { if (bzc != 0) FlashEnvColor = PACKRGBA(bzc, 0, 0, 255); } } else if (plyr->f_powers[pw_ironfeet] >= 61 || ((int)plyr->f_powers[pw_ironfeet]) & 8) { /* suit flash (green/yellow) */ FlashEnvColor = PACKRGBA(0, 32, 4, 255); } else if ((int)plyr->f_bonuscount > 0) { /* bonus flash (yellow) */ //cnt = FlashBrightness*((plyr->bonuscount+7)/8)/32; cnt = FLASH_BRIGHTNESS * (((int)plyr->f_bonuscount + 7) / 8) / 32; if (cnt > ST_MAXBONCOUNT) cnt = ST_MAXBONCOUNT; //bnc = (cnt << 2) + cnt << 1; bnc = cnt * 10; FlashEnvColor = PACKRGBA(bnc, bnc, cnt, 255); } else { /* Default Flash */ FlashEnvColor = PACKRGBA(0, 0, 0, 0); } } } extern uint16_t *symbols16; extern float recip_symw; extern float recip_symh; extern int symbols16_size; extern int rawsymbol_w; extern int rawsymbol_h; pvr_ptr_t pvr_symbols; pvr_sprite_hdr_t symbols_shdr; pvr_sprite_cxt_t symbols_scxt; pvr_sprite_txr_t symbols_stxr; void ST_DrawSymbol(int xpos, int ypos, int index, uint32_t color, int prio) { symboldata_t *symbol; symbol = &symboldata[index]; uint32_t symw = symbol->w; uint32_t symh = symbol->h; float x1 = xpos; float x2 = x1 + symw; float yd = 0.0f; float y1 = ypos; if (ypos < 0) { y1 = 0.0f; yd = -ypos; } float y2 = y1 + (symh - yd); float u1, u2, v1, v2; u1 = (float)symbol->x * recip_symw; if (ypos < 0) v1 = (float)((float)symbol->y + yd) * recip_symh; else v1 = (float)symbol->y * recip_symh; u2 = (float)((float)symbol->x + (float)symbol->w) * recip_symw; v2 = (float)((float)symbol->y + (float)symbol->h) * recip_symh; symbols_stxr.flags = PVR_CMD_VERTEX_EOL; if (prio == ST_ABOVE_OVL) { symbols_stxr.az = 10.0000001f; symbols_stxr.bz = 10.0000001f; symbols_stxr.cz = 10.0000001f; } else { symbols_stxr.az = 8.9999999f; symbols_stxr.bz = 8.9999999f; symbols_stxr.cz = 8.9999999f; } symbols_stxr.dummy = 0; symbols_shdr.argb = D64_PVR_REPACK_COLOR(color); x1 *= (float)RES_RATIO; x2 *= (float)RES_RATIO; y1 *= (float)RES_RATIO; y2 *= (float)RES_RATIO; symbols_stxr.ax = x1; symbols_stxr.ay = y2; symbols_stxr.bx = x1; symbols_stxr.by = y1; symbols_stxr.cx = x2; symbols_stxr.cy = y1; symbols_stxr.dx = x2; symbols_stxr.dy = y2; symbols_stxr.auv = PVR_PACK_16BIT_UV(u1, v2); symbols_stxr.buv = PVR_PACK_16BIT_UV(u1, v1); symbols_stxr.cuv = PVR_PACK_16BIT_UV(u2, v1); pvr_list_prim(PVR_LIST_TR_POLY, &symbols_shdr, sizeof(pvr_sprite_hdr_t)); pvr_list_prim(PVR_LIST_TR_POLY, &symbols_stxr, sizeof(pvr_sprite_txr_t)); } int ST_calcPainOffset(void) { static int lastcalc; static int oldhealth = -1; player_t *plyr = &players[0]; int health; health = plyr->health > 100 ? 100 : plyr->health; if (health != oldhealth) { lastcalc = ST_FACESTRIDE * (((100 - health) * ST_NUMPAINFACES) / 101); oldhealth = health; } return lastcalc; } void ST_drawVMUFace(void) { I_VMUUpdateFace(faces[st_faceindex], force_vmu_refresh); } // // This is a not-very-pretty routine which handles // the face states and their timing. // the precedence of expressions is: // dead > evil grin > turned head > straight ahead // void ST_updateFaceWidget(void) { player_t *plyr = &players[0]; int i; angle_t badguyangle; angle_t diffang; static int lastattackdown = -1; static int priority = 0; static int last_priority = -1; boolean doevilgrin; int new_faceindex = 0; if (force_vmu_refresh) { ST_drawVMUFace(); return; } if (priority < 10) { // dead if (!plyr->health) { last_priority = priority; priority = 9; new_faceindex = ST_DEADFACE; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } st_facecount = 1; } } if (priority < 9) { if (plyr->f_bonuscount > 0) { // picking up bonus doevilgrin = false; for (i = 0; i < NUMWEAPONS; i++) { if (oldweaponsowned[i] != plyr->weaponowned[i]) { doevilgrin = true; oldweaponsowned[i] = plyr->weaponowned[i]; } } if (doevilgrin) { // evil grin if just picked up weapon last_priority = priority; priority = 8; st_facecount = ST_EVILGRINCOUNT; new_faceindex = ST_calcPainOffset() + ST_EVILGRINOFFSET; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } } } } if (priority < 8) { if ((int)plyr->f_damagecount && plyr->attacker && plyr->attacker != plyr->mo) { last_priority = priority; // being attacked priority = 7; if (st_oldhealth - plyr->health > ST_MUCHPAIN) { st_facecount = ST_TURNCOUNT; new_faceindex = ST_calcPainOffset() + ST_OUCHOFFSET; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } } else { badguyangle = R_PointToAngle2(plyr->mo->x, plyr->mo->y, plyr->attacker->x, plyr->attacker->y); if (badguyangle > plyr->mo->angle) { // whether right or left diffang = badguyangle - plyr->mo->angle; i = diffang > ANG180; } else { // whether left or right diffang = plyr->mo->angle - badguyangle; i = diffang <= ANG180; } // confusing, aint it? st_facecount = ST_TURNCOUNT; new_faceindex = ST_calcPainOffset(); if (diffang < ANG45) // head-on new_faceindex += ST_RAMPAGEOFFSET; else if (i) // turn face right new_faceindex += ST_TURNOFFSET; else // turn face left new_faceindex += ST_TURNOFFSET + 1; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } } } } if (priority < 7) { // getting hurt because of your own damn stupidity if ((int)plyr->f_damagecount) { if (st_oldhealth - plyr->health > ST_MUCHPAIN) { last_priority = priority; priority = 7; st_facecount = ST_TURNCOUNT; new_faceindex = ST_calcPainOffset() + ST_OUCHOFFSET; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } } else { last_priority = priority; priority = 6; st_facecount = ST_TURNCOUNT; new_faceindex = ST_calcPainOffset() + ST_RAMPAGEOFFSET; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } } } } if (priority < 6) { // rapid firing if (plyr->attackdown) { if (lastattackdown == -1) { lastattackdown = ST_RAMPAGEDELAY; } else if (!--lastattackdown) { last_priority = priority; priority = 5; new_faceindex = ST_calcPainOffset() + ST_RAMPAGEOFFSET; if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } st_facecount = 1; lastattackdown = 1; } } else { lastattackdown = -1; } } if (priority < 5) { // invulnerability if ((plyr->cheats & CF_GODMODE) || (plyr->f_powers[pw_invulnerability] > 0)) { last_priority = priority; priority = 4; st_faceindex = ST_GODFACE; if (last_priority != priority) { ST_drawVMUFace(); } st_facecount = 1; } } // look left or look right if the facecount has timed out if (!st_facecount) { new_faceindex = ST_calcPainOffset() + (st_randomnumber % 3); if (new_faceindex != st_faceindex) { st_faceindex = new_faceindex; ST_drawVMUFace(); } st_facecount = ST_STRAIGHTFACECOUNT; last_priority = priority; priority = 0; } st_facecount--; }
0
0.896958
1
0.896958
game-dev
MEDIA
0.882946
game-dev
0.741956
1
0.741956
FMXExpress/Firemonkey
2,289
Embarcadero/Berlin/CPP/ThingPoint ThingConnect IoT Demo/Thingpointcpp/CacheDataModuleU.h
// --------------------------------------------------------------------------- #ifndef CacheDataModuleUH #define CacheDataModuleUH // --------------------------------------------------------------------------- #include <System.Classes.hpp> #include <System.JSON.hpp> #include <vector> // --------------------------------------------------------------------------- struct TItem { private: TDateTime FTime; String FDevice; String FValue; String FPerson; public: __fastcall TItem(TDateTime ATime, String ADevice, String APerson, TJSONObject * AValue) { FTime = ATime; FDevice = ADevice; FPerson = APerson; FValue = AValue->ToJSON(); } __fastcall TItem(void) { } __property String Person = {read = FPerson}; __property String Device = {read = FDevice}; __property TDateTime Time = {read = FTime}; __property String Value = {read = FValue}; }; class TCache { private: std::vector<TItem> *FList; public: __fastcall TCache() { FList = new std::vector<TItem>(); } __fastcall ~TCache() { delete FList; } typedef void __fastcall(__closure * TItemsEvent)(const TItem & AItem, bool &ADone); bool __fastcall TryGetRecent(String ADevice, TItem &AItem); bool __fastcall EnumItems(String ADevice, TItemsEvent AOnItem); void __fastcall ClearDevice(String ADevice); void __fastcall Save(TItem * AItem); }; class TCacheDataModule : public TDataModule { __published: // IDE-managed Components private : // User declarations TCache * FCache; private: void __fastcall OnItem(const TItem &AItem, bool &ADone); public: // User declarations __fastcall TCacheDataModule(TComponent* Owner); __fastcall ~TCacheDataModule(void); void __fastcall SaveDeviceData(String ADevice, TDateTime ATime, TJSONObject * AData); void __fastcall ClearDeviceData(String ADevice); bool __fastcall TryGetRecentDeviceData(String ADevice, TDateTime &ATime, TJSONObject * AData); bool __fastcall TryGetDeviceDataStats(String ADevice, TDateTime &ATime, TJSONObject *AData); }; // --------------------------------------------------------------------------- extern PACKAGE TCacheDataModule *CacheDataModule; // --------------------------------------------------------------------------- #endif
0
0.854864
1
0.854864
game-dev
MEDIA
0.346203
game-dev
0.868071
1
0.868071
holycake/mhsj
1,368
daemon/class/yaomo/wudidong/kugu-blade/diyu.c
#include <ansi.h> #include <combat.h> inherit SSERVER; int perform(object me, object target) { string msg; int extra,lvl,lv; int i; object weapon; if( !target ) target = offensive_target(me); if( !target || !target->is_character() || !me->is_fighting(target) ) return notify_fail("无边地狱只能对战斗中的对手使用。\n"); if(me->query("family/family_name")!="陷空山无底洞") return notify_fail("“无边地狱”只有无底洞门人才可以用!\n"); weapon = me->query_temp("weapon"); if( (string)weapon->query("skill_type") != "blade" ) return notify_fail("你手上无刀,不能使用无边地狱!\n"); if( (int)me->query("force") <= 1000 ) return notify_fail("你内力不够,不能使用无边地狱!\n"); //if(me->query("force_factor")>100) // me->set("force_factor",100); extra = me->query_skill("kugu-blade",1) / 5; me->add_temp("apply/attack", extra); //me->add_temp("apply/damage", extra);^M msg = HIR "$N使出[枯骨刀法]的无边地狱,手中的"+ weapon->name() +"斜斜劈出,$n顿觉呼吸一窒!" NOR; COMBAT_D->do_attack(me,target, weapon, TYPE_REGULAR); msg = HIW "$N刀光连闪,$n周围鬼哭神号,恰似无边地狱!\n" NOR; message_vision(msg, me, target); lvl=extra/10; if(lvl>4) lvl =2; for(i=0;i<=lvl;i++) { msg = HIY "$N劈出一刀!\n" NOR; COMBAT_D->do_attack(me,target, weapon, TYPE_REGULAR); message_vision(msg,me,target); } me->add_temp("apply/att ack", -extra); // me->add_temp("apply/damage", -extra); me->start_busy(1+lvl/2); return 1; }
0
0.840231
1
0.840231
game-dev
MEDIA
0.982238
game-dev
0.931739
1
0.931739
Flemmli97/ImprovedMobs
2,642
common/src/main/java/io/github/flemmli97/improvedmobs/mixin/TNTEntityMixin.java
package io.github.flemmli97.improvedmobs.mixin; import io.github.flemmli97.improvedmobs.common.utils.EntityFlags; import io.github.flemmli97.improvedmobs.mixinhelper.TNTExtension; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.item.PrimedTnt; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(PrimedTnt.class) public abstract class TNTEntityMixin extends Entity implements TNTExtension { private TNTEntityMixin(EntityType<?> type, Level world) { super(type, world); } @Shadow protected abstract void explode(); @Inject(method = "tick", at = @At(value = "RETURN"), cancellable = true) private void modifyExplosion(CallbackInfo info) { PrimedTnt tnt = (PrimedTnt) (Object) this; if (EntityFlags.get(tnt).isThrownEntity && tnt.getFuse() == 2) { info.cancel(); tnt.remove(RemovalReason.KILLED); if (!tnt.level().isClientSide) this.explode(); } } @Override public void improvedMobs$shootFromEntity(Entity shooter, float pitch, float yaw, float delta, float velocity, float accuracy) { PrimedTnt tnt = (PrimedTnt) (Object) this; float x = -Mth.sin(yaw * (float) Math.PI / 180F) * Mth.cos(pitch * (float) Math.PI / 180F); float y = -Mth.sin((pitch + delta) * (float) Math.PI / 180F); float z = Mth.cos(yaw * (float) Math.PI / 180F) * Mth.cos(pitch * (float) Math.PI / 180F); Vec3 newMotion = new Vec3(x, y, z).normalize() .add(this.random.nextGaussian() * 0.0075F * accuracy, this.random.nextGaussian() * 0.0075F * accuracy, this.random.nextGaussian() * 0.0075F * accuracy).scale(velocity); tnt.setDeltaMovement(newMotion); double f3 = Math.sqrt(newMotion.x * newMotion.x + newMotion.z * newMotion.z); tnt.setYRot((float) (Mth.atan2(newMotion.x, newMotion.z) * (180F / (float) Math.PI))); tnt.setXRot((float) (Mth.atan2(newMotion.y, f3) * (180F / (float) Math.PI))); tnt.yRotO = tnt.getYRot(); tnt.xRotO = tnt.getXRot(); Vec3 shooterMotion = shooter.getDeltaMovement(); tnt.setDeltaMovement(tnt.getDeltaMovement().add(shooterMotion.x, shooter.onGround() ? 0.0D : shooterMotion.y, shooterMotion.z)); } }
0
0.8747
1
0.8747
game-dev
MEDIA
0.992533
game-dev
0.935332
1
0.935332